diff --git "a/swe-bench-verified/pytest-dev#pytest#8aba863a634f40560e25055d179220f0eefabe9a.graph.json" "b/swe-bench-verified/pytest-dev#pytest#8aba863a634f40560e25055d179220f0eefabe9a.graph.json" new file mode 100644--- /dev/null +++ "b/swe-bench-verified/pytest-dev#pytest#8aba863a634f40560e25055d179220f0eefabe9a.graph.json" @@ -0,0 +1 @@ +{"edges":[{"edgeType":"contains","source":3228,"target":3325},{"edgeType":"contains","source":5312,"target":5315},{"edgeType":"calls","source":3105,"target":364},{"edgeType":"contains","source":5410,"target":5448},{"edgeType":"extends","source":168,"target":189},{"edgeType":"contains","source":3726,"target":3743},{"edgeType":"imports","source":3949,"target":78},{"edgeType":"contains","source":3808,"target":4372},{"edgeType":"calls","source":1797,"target":1801},{"edgeType":"contains","source":190,"target":255},{"edgeType":"contains","source":132,"target":995},{"edgeType":"calls","source":4066,"target":170},{"edgeType":"contains","source":2237,"target":2335},{"edgeType":"calls","source":3348,"target":3401},{"edgeType":"calls","source":6146,"target":170},{"edgeType":"calls","source":4912,"target":371},{"edgeType":"contains","source":1814,"target":2764},{"edgeType":"contains","source":2581,"target":128},{"edgeType":"contains","source":3726,"target":3742},{"edgeType":"imports","source":3949,"target":79},{"edgeType":"contains","source":3819,"target":4030},{"edgeType":"contains","source":3808,"target":4371},{"edgeType":"calls","source":1701,"target":548},{"edgeType":"contains","source":190,"target":254},{"edgeType":"contains","source":30,"target":5214},{"edgeType":"calls","source":1738,"target":458},{"edgeType":"contains","source":190,"target":253},{"edgeType":"contains","source":30,"target":5213},{"edgeType":"calls","source":4066,"target":171},{"edgeType":"calls","source":6863,"target":2257},{"edgeType":"contains","source":3624,"target":3733},{"edgeType":"calls","source":4912,"target":370},{"edgeType":"contains","source":3297,"target":3298},{"edgeType":"contains","source":5312,"target":5313},{"edgeType":"contains","source":4691,"target":5537},{"edgeType":"contains","source":4502,"target":5054},{"edgeType":"contains","source":190,"target":257},{"edgeType":"contains","source":2237,"target":2332},{"edgeType":"calls","source":5533,"target":144},{"edgeType":"calls","source":6206,"target":422},{"edgeType":"contains","source":132,"target":998},{"edgeType":"calls","source":6728,"target":6443},{"edgeType":"calls","source":6863,"target":2258},{"edgeType":"imports","source":2961,"target":49},{"edgeType":"calls","source":2087,"target":212},{"edgeType":"calls","source":4912,"target":369},{"edgeType":"contains","source":928,"target":4861},{"edgeType":"calls","source":1534,"target":1499},{"edgeType":"calls","source":3034,"target":450},{"edgeType":"calls","source":2986,"target":2995},{"edgeType":"calls","source":7027,"target":6688},{"edgeType":"contains","source":4474,"target":4864},{"edgeType":"calls","source":3510,"target":1550},{"edgeType":"contains","source":3808,"target":4369},{"edgeType":"calls","source":3512,"target":431},{"edgeType":"contains","source":190,"target":256},{"edgeType":"extends","source":5780,"target":1691},{"edgeType":"contains","source":132,"target":997},{"edgeType":"calls","source":6590,"target":6494},{"edgeType":"calls","source":6206,"target":421},{"edgeType":"calls","source":6296,"target":1859},{"edgeType":"calls","source":3487,"target":148},{"edgeType":"contains","source":6280,"target":7022},{"edgeType":"contains","source":2768,"target":2785},{"edgeType":"calls","source":4912,"target":368},{"edgeType":"calls","source":6559,"target":56},{"edgeType":"calls","source":7135,"target":170},{"edgeType":"calls","source":1830,"target":1831},{"edgeType":"contains","source":190,"target":259},{"edgeType":"contains","source":2075,"target":2076},{"edgeType":"calls","source":2623,"target":2618},{"edgeType":"calls","source":2689,"target":572},{"edgeType":"calls","source":6713,"target":568},{"edgeType":"contains","source":2237,"target":2339},{"edgeType":"calls","source":6863,"target":146},{"edgeType":"contains","source":4668,"target":5199},{"edgeType":"imports","source":3166,"target":3205},{"edgeType":"contains","source":2768,"target":2790},{"edgeType":"contains","source":4691,"target":5543},{"edgeType":"calls","source":7135,"target":171},{"edgeType":"contains","source":3624,"target":3737},{"edgeType":"contains","source":190,"target":258},{"edgeType":"calls","source":2689,"target":573},{"edgeType":"calls","source":4010,"target":4017},{"edgeType":"contains","source":2237,"target":2340},{"edgeType":"calls","source":4968,"target":4972},{"edgeType":"calls","source":4674,"target":4573},{"edgeType":"calls","source":4912,"target":366},{"edgeType":"contains","source":2768,"target":2791},{"edgeType":"calls","source":4944,"target":431},{"edgeType":"contains","source":190,"target":261},{"edgeType":"extends","source":6106,"target":36},{"edgeType":"calls","source":1738,"target":457},{"edgeType":"calls","source":3921,"target":431},{"edgeType":"contains","source":3808,"target":4374},{"edgeType":"calls","source":1764,"target":1765},{"edgeType":"calls","source":4232,"target":303},{"edgeType":"calls","source":5077,"target":535},{"edgeType":"contains","source":2768,"target":2788},{"edgeType":"contains","source":3241,"target":3982},{"edgeType":"contains","source":5312,"target":5316},{"edgeType":"calls","source":2523,"target":431},{"edgeType":"contains","source":190,"target":260},{"edgeType":"calls","source":4291,"target":588},{"edgeType":"calls","source":1748,"target":146},{"edgeType":"contains","source":3808,"target":4373},{"edgeType":"calls","source":4912,"target":364},{"edgeType":"calls","source":4042,"target":4080},{"edgeType":"calls","source":4232,"target":304},{"edgeType":"calls","source":4262,"target":431},{"edgeType":"calls","source":6541,"target":2732},{"edgeType":"calls","source":3565,"target":897},{"edgeType":"contains","source":2237,"target":2338},{"edgeType":"calls","source":6752,"target":2533},{"edgeType":"calls","source":4595,"target":3849},{"edgeType":"calls","source":6481,"target":364},{"edgeType":"calls","source":711,"target":582},{"edgeType":"contains","source":5081,"target":5085},{"edgeType":"contains","source":3819,"target":4039},{"edgeType":"contains","source":190,"target":263},{"edgeType":"calls","source":2326,"target":2307},{"edgeType":"imports","source":1415,"target":1476},{"edgeType":"calls","source":4850,"target":171},{"edgeType":"calls","source":6541,"target":2733},{"edgeType":"contains","source":2902,"target":2868},{"edgeType":"calls","source":4968,"target":4969},{"edgeType":"contains","source":6280,"target":7027},{"edgeType":"calls","source":3227,"target":1859},{"edgeType":"calls","source":5077,"target":533},{"edgeType":"imports","source":3726,"target":1698},{"edgeType":"calls","source":5201,"target":5144},{"edgeType":"contains","source":3819,"target":4038},{"edgeType":"contains","source":5081,"target":5084},{"edgeType":"contains","source":190,"target":262},{"edgeType":"contains","source":3954,"target":4081},{"edgeType":"calls","source":3719,"target":350},{"edgeType":"calls","source":2689,"target":2683},{"edgeType":"calls","source":1534,"target":431},{"edgeType":"calls","source":4850,"target":170},{"edgeType":"calls","source":3481,"target":3499},{"edgeType":"calls","source":6481,"target":366},{"edgeType":"contains","source":6280,"target":7028},{"edgeType":"imports","source":3166,"target":3216},{"edgeType":"calls","source":3925,"target":303},{"edgeType":"contains","source":3819,"target":4037},{"edgeType":"contains","source":190,"target":265},{"edgeType":"contains","source":5081,"target":5083},{"edgeType":"contains","source":952,"target":955},{"edgeType":"calls","source":1830,"target":1829},{"edgeType":"contains","source":1942,"target":1972},{"edgeType":"calls","source":4175,"target":4181},{"edgeType":"contains","source":2768,"target":2792},{"edgeType":"calls","source":6486,"target":212},{"edgeType":"calls","source":3021,"target":2958},{"edgeType":"calls","source":3925,"target":304},{"edgeType":"contains","source":3808,"target":4377},{"edgeType":"contains","source":5081,"target":5082},{"edgeType":"contains","source":2210,"target":5293},{"edgeType":"contains","source":190,"target":264},{"edgeType":"calls","source":7136,"target":146},{"edgeType":"calls","source":1830,"target":1828},{"edgeType":"contains","source":3954,"target":4079},{"edgeType":"calls","source":4274,"target":4282},{"edgeType":"calls","source":2826,"target":548},{"edgeType":"calls","source":6550,"target":1400},{"edgeType":"contains","source":1942,"target":1974},{"edgeType":"calls","source":6481,"target":368},{"edgeType":"contains","source":2174,"target":2181},{"edgeType":"calls","source":905,"target":906},{"edgeType":"calls","source":5133,"target":5136},{"edgeType":"calls","source":1100,"target":146},{"edgeType":"calls","source":1136,"target":1139},{"edgeType":"contains","source":952,"target":957},{"edgeType":"contains","source":190,"target":267},{"edgeType":"calls","source":3861,"target":171},{"edgeType":"calls","source":1002,"target":1065},{"edgeType":"contains","source":885,"target":920},{"edgeType":"contains","source":6038,"target":6068},{"edgeType":"calls","source":711,"target":572},{"edgeType":"calls","source":547,"target":371},{"edgeType":"imports","source":2176,"target":78},{"edgeType":"contains","source":5081,"target":5089},{"edgeType":"extends","source":6038,"target":36},{"edgeType":"calls","source":4274,"target":4281},{"edgeType":"calls","source":6400,"target":1797},{"edgeType":"imports","source":2176,"target":79},{"edgeType":"extends","source":4913,"target":36},{"edgeType":"calls","source":711,"target":573},{"edgeType":"calls","source":6481,"target":369},{"edgeType":"calls","source":6989,"target":6819},{"edgeType":"calls","source":3861,"target":170},{"edgeType":"calls","source":5133,"target":5135},{"edgeType":"calls","source":3510,"target":481},{"edgeType":"calls","source":1136,"target":1138},{"edgeType":"contains","source":5081,"target":5088},{"edgeType":"contains","source":3030,"target":2077},{"edgeType":"contains","source":190,"target":266},{"edgeType":"calls","source":4026,"target":342},{"edgeType":"contains","source":885,"target":919},{"edgeType":"calls","source":2079,"target":445},{"edgeType":"calls","source":4274,"target":4280},{"edgeType":"calls","source":547,"target":370},{"edgeType":"calls","source":145,"target":148},{"edgeType":"calls","source":5077,"target":528},{"edgeType":"calls","source":112,"target":114},{"edgeType":"calls","source":3629,"target":2078},{"edgeType":"contains","source":1942,"target":1980},{"edgeType":"calls","source":6481,"target":370},{"edgeType":"calls","source":5055,"target":3324},{"edgeType":"calls","source":208,"target":309},{"edgeType":"calls","source":4880,"target":3464},{"edgeType":"calls","source":1701,"target":535},{"edgeType":"calls","source":5133,"target":5134},{"edgeType":"contains","source":132,"target":1007},{"edgeType":"contains","source":41,"target":3828},{"edgeType":"contains","source":6280,"target":7024},{"edgeType":"contains","source":4432,"target":5123},{"edgeType":"calls","source":5656,"target":548},{"edgeType":"contains","source":190,"target":269},{"edgeType":"contains","source":4378,"target":4682},{"edgeType":"calls","source":6887,"target":469},{"edgeType":"contains","source":3030,"target":2074},{"edgeType":"contains","source":5081,"target":5087},{"edgeType":"calls","source":1002,"target":1067},{"edgeType":"calls","source":6281,"target":2313},{"edgeType":"calls","source":5077,"target":527},{"edgeType":"calls","source":5031,"target":1953},{"edgeType":"imports","source":3726,"target":1704},{"edgeType":"calls","source":4274,"target":4279},{"edgeType":"calls","source":6481,"target":371},{"edgeType":"calls","source":5018,"target":1299},{"edgeType":"calls","source":3510,"target":479},{"edgeType":"imports","source":3030,"target":2142},{"edgeType":"calls","source":3481,"target":3492},{"edgeType":"contains","source":5081,"target":5086},{"edgeType":"imports","source":4691,"target":4558},{"edgeType":"contains","source":190,"target":268},{"edgeType":"contains","source":3867,"target":438},{"edgeType":"calls","source":1070,"target":1072},{"edgeType":"calls","source":6795,"target":2265},{"edgeType":"calls","source":1002,"target":1066},{"edgeType":"calls","source":6541,"target":2740},{"edgeType":"contains","source":3297,"target":3311},{"edgeType":"calls","source":4274,"target":4278},{"edgeType":"calls","source":4180,"target":4021},{"edgeType":"calls","source":5075,"target":588},{"edgeType":"contains","source":6280,"target":7026},{"edgeType":"contains","source":4618,"target":4640},{"edgeType":"calls","source":3481,"target":3493},{"edgeType":"contains","source":132,"target":1009},{"edgeType":"calls","source":3510,"target":480},{"edgeType":"contains","source":2901,"target":2875},{"edgeType":"calls","source":487,"target":146},{"edgeType":"calls","source":1878,"target":364},{"edgeType":"contains","source":3624,"target":3717},{"edgeType":"contains","source":2768,"target":2770},{"edgeType":"calls","source":4538,"target":354},{"edgeType":"contains","source":3032,"target":3042},{"edgeType":"calls","source":2626,"target":431},{"edgeType":"calls","source":2246,"target":584},{"edgeType":"imports","source":5380,"target":5381},{"edgeType":"calls","source":2987,"target":2982},{"edgeType":"calls","source":2998,"target":1584},{"edgeType":"contains","source":4432,"target":5095},{"edgeType":"calls","source":3922,"target":422},{"edgeType":"calls","source":3815,"target":568},{"edgeType":"contains","source":6038,"target":6048},{"edgeType":"contains","source":5,"target":3859},{"edgeType":"contains","source":41,"target":3800},{"edgeType":"calls","source":5670,"target":144},{"edgeType":"contains","source":2173,"target":2189},{"edgeType":"calls","source":6104,"target":431},{"edgeType":"contains","source":2702,"target":2703},{"edgeType":"calls","source":6727,"target":114},{"edgeType":"contains","source":2768,"target":2771},{"edgeType":"contains","source":1229,"target":1856},{"edgeType":"contains","source":3013,"target":3632},{"edgeType":"imports","source":5380,"target":5382},{"edgeType":"extends","source":4196,"target":36},{"edgeType":"calls","source":5075,"target":2733},{"edgeType":"calls","source":3133,"target":571},{"edgeType":"contains","source":4432,"target":5094},{"edgeType":"calls","source":5329,"target":144},{"edgeType":"contains","source":1942,"target":1951},{"edgeType":"calls","source":3348,"target":3419},{"edgeType":"contains","source":3,"target":2863},{"edgeType":"calls","source":5733,"target":304},{"edgeType":"calls","source":5741,"target":56},{"edgeType":"calls","source":3577,"target":548},{"edgeType":"calls","source":1170,"target":1173},{"edgeType":"calls","source":1878,"target":366},{"edgeType":"calls","source":6998,"target":170},{"edgeType":"calls","source":3123,"target":2992},{"edgeType":"calls","source":4440,"target":4447},{"edgeType":"calls","source":6728,"target":84},{"edgeType":"contains","source":6699,"target":6700},{"edgeType":"contains","source":3032,"target":3040},{"edgeType":"calls","source":6456,"target":1117},{"edgeType":"contains","source":4579,"target":4764},{"edgeType":"imports","source":5380,"target":5383},{"edgeType":"contains","source":4691,"target":5520},{"edgeType":"calls","source":1401,"target":354},{"edgeType":"calls","source":5670,"target":142},{"edgeType":"calls","source":1269,"target":1275},{"edgeType":"contains","source":6038,"target":6050},{"edgeType":"contains","source":2008,"target":2016},{"edgeType":"calls","source":5733,"target":303},{"edgeType":"contains","source":26,"target":39},{"edgeType":"contains","source":153,"target":329},{"edgeType":"calls","source":2626,"target":1487},{"edgeType":"contains","source":2237,"target":2317},{"edgeType":"calls","source":4046,"target":3977},{"edgeType":"calls","source":6998,"target":171},{"edgeType":"calls","source":3119,"target":3117},{"edgeType":"contains","source":1302,"target":3819},{"edgeType":"contains","source":2768,"target":2769},{"edgeType":"contains","source":4882,"target":4884},{"edgeType":"contains","source":3032,"target":3041},{"edgeType":"calls","source":6473,"target":591},{"edgeType":"imports","source":5380,"target":5384},{"edgeType":"contains","source":4579,"target":4763},{"edgeType":"calls","source":3922,"target":421},{"edgeType":"calls","source":6947,"target":1753},{"edgeType":"contains","source":3807,"target":4384},{"edgeType":"calls","source":1827,"target":888},{"edgeType":"calls","source":1702,"target":535},{"edgeType":"contains","source":2173,"target":2187},{"edgeType":"contains","source":5,"target":3863},{"edgeType":"contains","source":2173,"target":2192},{"edgeType":"contains","source":2237,"target":2322},{"edgeType":"contains","source":4618,"target":4619},{"edgeType":"contains","source":2768,"target":2774},{"edgeType":"calls","source":4743,"target":4565},{"edgeType":"contains","source":3819,"target":4019},{"edgeType":"contains","source":6038,"target":6044},{"edgeType":"extends","source":2764,"target":36},{"edgeType":"calls","source":2227,"target":2226},{"edgeType":"imports","source":2315,"target":1030},{"edgeType":"calls","source":1805,"target":508},{"edgeType":"calls","source":1981,"target":337},{"edgeType":"contains","source":5,"target":3862},{"edgeType":"calls","source":2626,"target":1485},{"edgeType":"contains","source":153,"target":331},{"edgeType":"calls","source":5015,"target":4588},{"edgeType":"calls","source":5013,"target":422},{"edgeType":"contains","source":2768,"target":2775},{"edgeType":"calls","source":1602,"target":458},{"edgeType":"contains","source":4474,"target":4853},{"edgeType":"calls","source":1805,"target":507},{"edgeType":"extends","source":6651,"target":36},{"edgeType":"contains","source":153,"target":334},{"edgeType":"calls","source":2963,"target":548},{"edgeType":"calls","source":1107,"target":1008},{"edgeType":"contains","source":4717,"target":4719},{"edgeType":"contains","source":1229,"target":1857},{"edgeType":"contains","source":2768,"target":2772},{"edgeType":"calls","source":4674,"target":4588},{"edgeType":"calls","source":5013,"target":421},{"edgeType":"calls","source":4092,"target":431},{"edgeType":"calls","source":1981,"target":339},{"edgeType":"contains","source":5,"target":3864},{"edgeType":"calls","source":3541,"target":601},{"edgeType":"contains","source":3624,"target":3718},{"edgeType":"calls","source":1239,"target":1143},{"edgeType":"calls","source":2601,"target":144},{"edgeType":"contains","source":1229,"target":1858},{"edgeType":"contains","source":2768,"target":2773},{"edgeType":"calls","source":2227,"target":2225},{"edgeType":"imports","source":2070,"target":166},{"edgeType":"calls","source":4448,"target":4194},{"edgeType":"imports","source":5285,"target":1991},{"edgeType":"calls","source":5787,"target":1795},{"edgeType":"calls","source":1805,"target":509},{"edgeType":"calls","source":1981,"target":338},{"edgeType":"contains","source":3954,"target":4059},{"edgeType":"calls","source":2730,"target":370},{"edgeType":"calls","source":5738,"target":142},{"edgeType":"calls","source":6688,"target":3444},{"edgeType":"calls","source":6757,"target":248},{"edgeType":"calls","source":4879,"target":4573},{"edgeType":"contains","source":6459,"target":6746},{"edgeType":"calls","source":1742,"target":1400},{"edgeType":"contains","source":6459,"target":6747},{"edgeType":"calls","source":4448,"target":4193},{"edgeType":"calls","source":1805,"target":504},{"edgeType":"contains","source":3820,"target":3992},{"edgeType":"contains","source":3819,"target":4023},{"edgeType":"calls","source":1827,"target":879},{"edgeType":"calls","source":6419,"target":171},{"edgeType":"calls","source":6784,"target":469},{"edgeType":"calls","source":2730,"target":371},{"edgeType":"calls","source":4708,"target":4588},{"edgeType":"contains","source":2008,"target":2027},{"edgeType":"contains","source":2237,"target":2327},{"edgeType":"calls","source":4933,"target":5012},{"edgeType":"calls","source":1239,"target":80},{"edgeType":"calls","source":1805,"target":503},{"edgeType":"contains","source":4432,"target":5102},{"edgeType":"contains","source":1814,"target":2756},{"edgeType":"calls","source":6723,"target":4475},{"edgeType":"calls","source":6206,"target":431},{"edgeType":"calls","source":2024,"target":56},{"edgeType":"calls","source":6879,"target":1753},{"edgeType":"contains","source":2768,"target":2776},{"edgeType":"calls","source":2883,"target":910},{"edgeType":"calls","source":6419,"target":170},{"edgeType":"imports","source":2176,"target":2178},{"edgeType":"calls","source":2730,"target":368},{"edgeType":"extends","source":957,"target":36},{"edgeType":"calls","source":3105,"target":370},{"edgeType":"contains","source":4691,"target":5529},{"edgeType":"calls","source":1805,"target":506},{"edgeType":"contains","source":190,"target":248},{"edgeType":"calls","source":1602,"target":457},{"edgeType":"calls","source":6885,"target":6853},{"edgeType":"contains","source":1854,"target":456},{"edgeType":"imports","source":2176,"target":2177},{"edgeType":"calls","source":4931,"target":1901},{"edgeType":"calls","source":2883,"target":911},{"edgeType":"contains","source":6038,"target":6059},{"edgeType":"calls","source":2730,"target":369},{"edgeType":"calls","source":3105,"target":371},{"edgeType":"calls","source":3123,"target":2985},{"edgeType":"calls","source":1805,"target":505},{"edgeType":"contains","source":3726,"target":3732},{"edgeType":"contains","source":3561,"target":3562},{"edgeType":"calls","source":6723,"target":4477},{"edgeType":"calls","source":6719,"target":6715},{"edgeType":"calls","source":4175,"target":4195},{"edgeType":"calls","source":6409,"target":5755},{"edgeType":"calls","source":4951,"target":4451},{"edgeType":"calls","source":3034,"target":455},{"edgeType":"calls","source":7065,"target":6560},{"edgeType":"calls","source":3105,"target":368},{"edgeType":"contains","source":3818,"target":4058},{"edgeType":"calls","source":5117,"target":4590},{"edgeType":"calls","source":1236,"target":170},{"edgeType":"extends","source":2662,"target":36},{"edgeType":"contains","source":190,"target":250},{"edgeType":"extends","source":6924,"target":36},{"edgeType":"calls","source":2730,"target":366},{"edgeType":"imports","source":4528,"target":78},{"edgeType":"imports","source":4528,"target":79},{"edgeType":"calls","source":3741,"target":737},{"edgeType":"contains","source":6699,"target":6703},{"edgeType":"calls","source":3105,"target":369},{"edgeType":"contains","source":6459,"target":6743},{"edgeType":"contains","source":190,"target":249},{"edgeType":"contains","source":6038,"target":6053},{"edgeType":"calls","source":6818,"target":6819},{"edgeType":"contains","source":2008,"target":2028},{"edgeType":"calls","source":3105,"target":366},{"edgeType":"contains","source":190,"target":252},{"edgeType":"calls","source":2601,"target":1192},{"edgeType":"calls","source":1747,"target":1243},{"edgeType":"calls","source":1805,"target":502},{"edgeType":"calls","source":4076,"target":4090},{"edgeType":"calls","source":2730,"target":364},{"edgeType":"contains","source":5636,"target":1604},{"edgeType":"contains","source":2008,"target":2029},{"edgeType":"contains","source":3954,"target":4067},{"edgeType":"contains","source":4474,"target":4860},{"edgeType":"calls","source":1236,"target":171},{"edgeType":"contains","source":190,"target":251},{"edgeType":"calls","source":4817,"target":146},{"edgeType":"calls","source":3986,"target":3710},{"edgeType":"contains","source":3775,"target":4331},{"edgeType":"calls","source":6146,"target":171},{"edgeType":"calls","source":4876,"target":431},{"edgeType":"calls","source":4442,"target":144},{"edgeType":"contains","source":521,"target":531},{"edgeType":"contains","source":453,"target":525},{"edgeType":"calls","source":2998,"target":477},{"edgeType":"calls","source":144,"target":159},{"edgeType":"contains","source":4668,"target":5162},{"edgeType":"calls","source":5220,"target":303},{"edgeType":"imports","source":6437,"target":147},{"edgeType":"calls","source":2019,"target":171},{"edgeType":"calls","source":4195,"target":366},{"edgeType":"calls","source":1191,"target":470},{"edgeType":"calls","source":1135,"target":1149},{"edgeType":"calls","source":4043,"target":4021},{"edgeType":"contains","source":6824,"target":7034},{"edgeType":"calls","source":7020,"target":527},{"edgeType":"contains","source":4782,"target":4799},{"edgeType":"contains","source":1243,"target":1405},{"edgeType":"contains","source":3014,"target":3583},{"edgeType":"calls","source":2555,"target":469},{"edgeType":"calls","source":2998,"target":478},{"edgeType":"contains","source":6599,"target":6611},{"edgeType":"calls","source":4951,"target":4413},{"edgeType":"imports","source":1814,"target":1815},{"edgeType":"contains","source":453,"target":524},{"edgeType":"calls","source":3822,"target":303},{"edgeType":"calls","source":5662,"target":5627},{"edgeType":"contains","source":30,"target":6238},{"edgeType":"calls","source":2019,"target":170},{"edgeType":"calls","source":3302,"target":567},{"edgeType":"calls","source":1242,"target":1002},{"edgeType":"contains","source":3624,"target":3700},{"edgeType":"contains","source":6824,"target":7035},{"edgeType":"calls","source":7020,"target":528},{"edgeType":"calls","source":1132,"target":1241},{"edgeType":"calls","source":4912,"target":1394},{"edgeType":"contains","source":3014,"target":3584},{"edgeType":"contains","source":4691,"target":5504},{"edgeType":"calls","source":144,"target":161},{"edgeType":"calls","source":5655,"target":558},{"edgeType":"calls","source":3447,"target":3469},{"edgeType":"contains","source":4318,"target":4383},{"edgeType":"contains","source":153,"target":314},{"edgeType":"calls","source":4195,"target":364},{"edgeType":"calls","source":2078,"target":458},{"edgeType":"calls","source":3417,"target":170},{"edgeType":"calls","source":4912,"target":1393},{"edgeType":"contains","source":6824,"target":7036},{"edgeType":"calls","source":2998,"target":476},{"edgeType":"calls","source":2952,"target":2959},{"edgeType":"calls","source":144,"target":160},{"edgeType":"contains","source":24,"target":83},{"edgeType":"calls","source":3417,"target":171},{"edgeType":"contains","source":3624,"target":3698},{"edgeType":"calls","source":5662,"target":339},{"edgeType":"calls","source":2078,"target":457},{"edgeType":"calls","source":6685,"target":6687},{"edgeType":"imports","source":4528,"target":1192},{"edgeType":"calls","source":6711,"target":596},{"edgeType":"calls","source":4912,"target":1392},{"edgeType":"contains","source":3014,"target":3582},{"edgeType":"calls","source":4673,"target":4573},{"edgeType":"calls","source":4815,"target":171},{"edgeType":"contains","source":3820,"target":3971},{"edgeType":"contains","source":92,"target":93},{"edgeType":"calls","source":4231,"target":303},{"edgeType":"contains","source":132,"target":967},{"edgeType":"calls","source":6685,"target":6688},{"edgeType":"calls","source":5662,"target":338},{"edgeType":"calls","source":6440,"target":532},{"edgeType":"calls","source":1499,"target":431},{"edgeType":"calls","source":6728,"target":6412},{"edgeType":"contains","source":4691,"target":5510},{"edgeType":"contains","source":3014,"target":3587},{"edgeType":"calls","source":4815,"target":170},{"edgeType":"contains","source":2961,"target":3116},{"edgeType":"calls","source":4912,"target":1391},{"edgeType":"contains","source":4782,"target":4803},{"edgeType":"contains","source":4579,"target":4753},{"edgeType":"calls","source":4468,"target":4583},{"edgeType":"imports","source":2961,"target":79},{"edgeType":"calls","source":7026,"target":6688},{"edgeType":"calls","source":7068,"target":6443},{"edgeType":"extends","source":6448,"target":36},{"edgeType":"contains","source":24,"target":85},{"edgeType":"calls","source":3844,"target":3845},{"edgeType":"calls","source":1382,"target":886},{"edgeType":"contains","source":153,"target":315},{"edgeType":"calls","source":4231,"target":304},{"edgeType":"calls","source":5662,"target":337},{"edgeType":"calls","source":6891,"target":303},{"edgeType":"contains","source":4691,"target":5509},{"edgeType":"calls","source":4912,"target":1390},{"edgeType":"contains","source":1083,"target":1085},{"edgeType":"calls","source":4508,"target":171},{"edgeType":"calls","source":4606,"target":304},{"edgeType":"imports","source":2961,"target":78},{"edgeType":"calls","source":4005,"target":965},{"edgeType":"calls","source":2122,"target":144},{"edgeType":"contains","source":3954,"target":4043},{"edgeType":"contains","source":2173,"target":2174},{"edgeType":"calls","source":4918,"target":146},{"edgeType":"calls","source":4912,"target":1389},{"edgeType":"contains","source":3624,"target":3703},{"edgeType":"contains","source":4318,"target":4387},{"edgeType":"calls","source":6891,"target":304},{"edgeType":"calls","source":4570,"target":4592},{"edgeType":"calls","source":2897,"target":431},{"edgeType":"calls","source":4877,"target":4588},{"edgeType":"contains","source":3014,"target":3585},{"edgeType":"calls","source":3018,"target":3022},{"edgeType":"calls","source":4606,"target":303},{"edgeType":"contains","source":4579,"target":4751},{"edgeType":"imports","source":5285,"target":2041},{"edgeType":"calls","source":5200,"target":5144},{"edgeType":"calls","source":7018,"target":596},{"edgeType":"calls","source":7020,"target":534},{"edgeType":"contains","source":4502,"target":5024},{"edgeType":"calls","source":4508,"target":170},{"edgeType":"contains","source":6599,"target":6609},{"edgeType":"contains","source":5410,"target":5416},{"edgeType":"calls","source":4912,"target":1388},{"edgeType":"calls","source":6303,"target":3719},{"edgeType":"contains","source":1302,"target":3807},{"edgeType":"calls","source":5600,"target":1200},{"edgeType":"calls","source":3447,"target":3465},{"edgeType":"contains","source":3461,"target":3470},{"edgeType":"calls","source":5518,"target":571},{"edgeType":"contains","source":2879,"target":3543},{"edgeType":"imports","source":4668,"target":2141},{"edgeType":"contains","source":3014,"target":3592},{"edgeType":"contains","source":3954,"target":4049},{"edgeType":"contains","source":3624,"target":3709},{"edgeType":"contains","source":3461,"target":3477},{"edgeType":"imports","source":1415,"target":1509},{"edgeType":"contains","source":6038,"target":6040},{"edgeType":"contains","source":2008,"target":2010},{"edgeType":"contains","source":153,"target":320},{"edgeType":"calls","source":6546,"target":431},{"edgeType":"imports","source":3166,"target":79},{"edgeType":"contains","source":3014,"target":3593},{"edgeType":"calls","source":4911,"target":4588},{"edgeType":"contains","source":1942,"target":1943},{"edgeType":"contains","source":6038,"target":6041},{"edgeType":"calls","source":2886,"target":2885},{"edgeType":"extends","source":6653,"target":36},{"edgeType":"calls","source":3155,"target":888},{"edgeType":"calls","source":2560,"target":303},{"edgeType":"contains","source":4502,"target":5029},{"edgeType":"contains","source":3014,"target":3590},{"edgeType":"calls","source":4035,"target":1088},{"edgeType":"imports","source":3166,"target":78},{"edgeType":"calls","source":2661,"target":1400},{"edgeType":"calls","source":2260,"target":1147},{"edgeType":"imports","source":3867,"target":533},{"edgeType":"contains","source":6038,"target":6042},{"edgeType":"calls","source":6541,"target":588},{"edgeType":"contains","source":2237,"target":2308},{"edgeType":"contains","source":132,"target":973},{"edgeType":"contains","source":3014,"target":3589},{"edgeType":"calls","source":5625,"target":422},{"edgeType":"contains","source":4691,"target":5512},{"edgeType":"calls","source":1132,"target":1236},{"edgeType":"calls","source":2533,"target":84},{"edgeType":"contains","source":6476,"target":4092},{"edgeType":"calls","source":2560,"target":304},{"edgeType":"calls","source":2614,"target":744},{"edgeType":"contains","source":3014,"target":3591},{"edgeType":"contains","source":951,"target":952},{"edgeType":"imports","source":6286,"target":5878},{"edgeType":"calls","source":2260,"target":1148},{"edgeType":"calls","source":2156,"target":144},{"edgeType":"contains","source":2008,"target":2009},{"edgeType":"calls","source":2931,"target":431},{"edgeType":"calls","source":5625,"target":421},{"edgeType":"calls","source":485,"target":146},{"edgeType":"calls","source":1168,"target":1171},{"edgeType":"calls","source":2614,"target":741},{"edgeType":"calls","source":1225,"target":461},{"edgeType":"calls","source":3342,"target":371},{"edgeType":"contains","source":3032,"target":3038},{"edgeType":"contains","source":2901,"target":2871},{"edgeType":"contains","source":4882,"target":4883},{"edgeType":"calls","source":2837,"target":170},{"edgeType":"calls","source":6689,"target":6572},{"edgeType":"calls","source":144,"target":147},{"edgeType":"calls","source":2837,"target":171},{"edgeType":"calls","source":5729,"target":5652},{"edgeType":"contains","source":3819,"target":4011},{"edgeType":"contains","source":2173,"target":2184},{"edgeType":"contains","source":153,"target":324},{"edgeType":"calls","source":1604,"target":339},{"edgeType":"calls","source":4576,"target":4398},{"edgeType":"contains","source":3624,"target":3712},{"edgeType":"contains","source":3032,"target":3039},{"edgeType":"contains","source":3807,"target":4381},{"edgeType":"calls","source":7135,"target":146},{"edgeType":"calls","source":2260,"target":1146},{"edgeType":"extends","source":5596,"target":36},{"edgeType":"calls","source":580,"target":371},{"edgeType":"calls","source":4363,"target":431},{"edgeType":"calls","source":144,"target":146},{"edgeType":"contains","source":2008,"target":2015},{"edgeType":"calls","source":3710,"target":591},{"edgeType":"contains","source":6459,"target":6727},{"edgeType":"calls","source":1604,"target":338},{"edgeType":"contains","source":521,"target":542},{"edgeType":"calls","source":3343,"target":338},{"edgeType":"calls","source":3342,"target":369},{"edgeType":"calls","source":1780,"target":171},{"edgeType":"calls","source":2821,"target":2778},{"edgeType":"calls","source":7019,"target":572},{"edgeType":"contains","source":1302,"target":3814},{"edgeType":"contains","source":3013,"target":3626},{"edgeType":"contains","source":3032,"target":3037},{"edgeType":"calls","source":3343,"target":339},{"edgeType":"calls","source":3342,"target":370},{"edgeType":"calls","source":1780,"target":170},{"edgeType":"calls","source":4938,"target":573},{"edgeType":"calls","source":7019,"target":573},{"edgeType":"contains","source":6038,"target":6039},{"edgeType":"calls","source":5131,"target":5161},{"edgeType":"contains","source":6459,"target":6729},{"edgeType":"extends","source":4532,"target":4478},{"edgeType":"contains","source":752,"target":753},{"edgeType":"calls","source":1239,"target":56},{"edgeType":"contains","source":4782,"target":4783},{"edgeType":"calls","source":6690,"target":170},{"edgeType":"calls","source":4274,"target":4277},{"edgeType":"contains","source":2502,"target":2526},{"edgeType":"calls","source":5077,"target":525},{"edgeType":"calls","source":2098,"target":911},{"edgeType":"contains","source":4474,"target":4817},{"edgeType":"contains","source":4432,"target":5062},{"edgeType":"calls","source":3481,"target":3490},{"edgeType":"calls","source":3414,"target":3453},{"edgeType":"calls","source":3510,"target":477},{"edgeType":"calls","source":547,"target":366},{"edgeType":"calls","source":1189,"target":548},{"edgeType":"calls","source":4045,"target":3977},{"edgeType":"calls","source":4848,"target":4451},{"edgeType":"contains","source":5241,"target":5351},{"edgeType":"calls","source":6690,"target":171},{"edgeType":"calls","source":4274,"target":4276},{"edgeType":"extends","source":37,"target":38},{"edgeType":"calls","source":3510,"target":478},{"edgeType":"calls","source":5868,"target":5599},{"edgeType":"calls","source":3481,"target":3491},{"edgeType":"contains","source":153,"target":297},{"edgeType":"contains","source":132,"target":948},{"edgeType":"contains","source":3624,"target":3682},{"edgeType":"calls","source":2626,"target":1453},{"edgeType":"contains","source":752,"target":755},{"edgeType":"calls","source":2531,"target":170},{"edgeType":"calls","source":6568,"target":2897},{"edgeType":"calls","source":547,"target":369},{"edgeType":"imports","source":3460,"target":452},{"edgeType":"contains","source":1908,"target":1912},{"edgeType":"calls","source":2978,"target":1112},{"edgeType":"calls","source":4368,"target":304},{"edgeType":"calls","source":4274,"target":4275},{"edgeType":"contains","source":4748,"target":4777},{"edgeType":"calls","source":1784,"target":1132},{"edgeType":"extends","source":3856,"target":36},{"edgeType":"calls","source":547,"target":368},{"edgeType":"imports","source":4307,"target":2741},{"edgeType":"contains","source":3624,"target":3681},{"edgeType":"contains","source":752,"target":754},{"edgeType":"imports","source":6286,"target":5870},{"edgeType":"calls","source":2079,"target":443},{"edgeType":"calls","source":5433,"target":56},{"edgeType":"contains","source":6459,"target":6708},{"edgeType":"calls","source":4901,"target":4920},{"edgeType":"contains","source":6604,"target":3270},{"edgeType":"calls","source":2531,"target":171},{"edgeType":"contains","source":3014,"target":3566},{"edgeType":"contains","source":1908,"target":1913},{"edgeType":"contains","source":3954,"target":4022},{"edgeType":"calls","source":2978,"target":1113},{"edgeType":"calls","source":2157,"target":1195},{"edgeType":"calls","source":145,"target":146},{"edgeType":"calls","source":4368,"target":303},{"edgeType":"calls","source":2098,"target":910},{"edgeType":"calls","source":3510,"target":476},{"edgeType":"contains","source":5674,"target":5675},{"edgeType":"contains","source":5,"target":3827},{"edgeType":"contains","source":153,"target":296},{"edgeType":"calls","source":3244,"target":3434},{"edgeType":"calls","source":485,"target":171},{"edgeType":"calls","source":1204,"target":80},{"edgeType":"calls","source":2861,"target":508},{"edgeType":"calls","source":4673,"target":4588},{"edgeType":"imports","source":4691,"target":3523},{"edgeType":"contains","source":4748,"target":4784},{"edgeType":"contains","source":4782,"target":4787},{"edgeType":"calls","source":1673,"target":339},{"edgeType":"calls","source":1507,"target":1257},{"edgeType":"calls","source":2198,"target":2035},{"edgeType":"calls","source":5737,"target":144},{"edgeType":"calls","source":1954,"target":84},{"edgeType":"calls","source":5534,"target":5379},{"edgeType":"calls","source":6883,"target":534},{"edgeType":"calls","source":1507,"target":1256},{"edgeType":"calls","source":2861,"target":509},{"edgeType":"calls","source":6472,"target":591},{"edgeType":"calls","source":1673,"target":338},{"edgeType":"calls","source":7032,"target":144},{"edgeType":"calls","source":485,"target":170},{"edgeType":"calls","source":144,"target":171},{"edgeType":"contains","source":3954,"target":4028},{"edgeType":"imports","source":3166,"target":49},{"edgeType":"calls","source":2861,"target":506},{"edgeType":"calls","source":6678,"target":548},{"edgeType":"calls","source":1236,"target":147},{"edgeType":"calls","source":5737,"target":142},{"edgeType":"calls","source":5020,"target":171},{"edgeType":"contains","source":5241,"target":5354},{"edgeType":"contains","source":2502,"target":2528},{"edgeType":"contains","source":5871,"target":5905},{"edgeType":"calls","source":6418,"target":171},{"edgeType":"contains","source":153,"target":300},{"edgeType":"calls","source":1236,"target":146},{"edgeType":"calls","source":547,"target":364},{"edgeType":"calls","source":6728,"target":56},{"edgeType":"calls","source":4750,"target":84},{"edgeType":"contains","source":4691,"target":5491},{"edgeType":"calls","source":2861,"target":507},{"edgeType":"calls","source":5020,"target":170},{"edgeType":"imports","source":4668,"target":2125},{"edgeType":"calls","source":6927,"target":6572},{"edgeType":"contains","source":6834,"target":4592},{"edgeType":"calls","source":3917,"target":3710},{"edgeType":"contains","source":2073,"target":2087},{"edgeType":"calls","source":2861,"target":504},{"edgeType":"calls","source":3481,"target":3482},{"edgeType":"calls","source":6418,"target":170},{"edgeType":"calls","source":1270,"target":144},{"edgeType":"contains","source":521,"target":523},{"edgeType":"calls","source":3244,"target":3430},{"edgeType":"calls","source":6863,"target":6443},{"edgeType":"contains","source":5871,"target":5915},{"edgeType":"calls","source":541,"target":545},{"edgeType":"calls","source":3951,"target":3710},{"edgeType":"calls","source":4436,"target":304},{"edgeType":"calls","source":6998,"target":144},{"edgeType":"calls","source":2861,"target":505},{"edgeType":"contains","source":4782,"target":4790},{"edgeType":"calls","source":2899,"target":384},{"edgeType":"calls","source":6671,"target":2882},{"edgeType":"contains","source":2502,"target":2536},{"edgeType":"contains","source":2599,"target":2700},{"edgeType":"calls","source":1039,"target":961},{"edgeType":"contains","source":5241,"target":5359},{"edgeType":"contains","source":3954,"target":4032},{"edgeType":"calls","source":4436,"target":303},{"edgeType":"calls","source":4103,"target":56},{"edgeType":"calls","source":4495,"target":588},{"edgeType":"calls","source":6955,"target":421},{"edgeType":"contains","source":2872,"target":576},{"edgeType":"calls","source":2899,"target":381},{"edgeType":"contains","source":2073,"target":2090},{"edgeType":"calls","source":3518,"target":2333},{"edgeType":"calls","source":4950,"target":4451},{"edgeType":"contains","source":1302,"target":2736},{"edgeType":"calls","source":5786,"target":733},{"edgeType":"calls","source":2974,"target":170},{"edgeType":"calls","source":2861,"target":502},{"edgeType":"contains","source":153,"target":305},{"edgeType":"contains","source":3014,"target":3573},{"edgeType":"calls","source":5441,"target":5086},{"edgeType":"contains","source":4748,"target":4786},{"edgeType":"calls","source":1085,"target":596},{"edgeType":"contains","source":3820,"target":3957},{"edgeType":"contains","source":2502,"target":2532},{"edgeType":"calls","source":1673,"target":337},{"edgeType":"calls","source":144,"target":170},{"edgeType":"calls","source":2626,"target":1445},{"edgeType":"extends","source":4095,"target":36},{"edgeType":"calls","source":6955,"target":422},{"edgeType":"calls","source":6893,"target":6572},{"edgeType":"calls","source":2861,"target":503},{"edgeType":"calls","source":2893,"target":568},{"edgeType":"calls","source":4976,"target":2587},{"edgeType":"calls","source":2899,"target":382},{"edgeType":"calls","source":2974,"target":171},{"edgeType":"calls","source":5786,"target":732},{"edgeType":"contains","source":1305,"target":530},{"edgeType":"calls","source":5854,"target":1795},{"edgeType":"contains","source":2502,"target":2534},{"edgeType":"contains","source":4788,"target":4602},{"edgeType":"contains","source":4748,"target":4785},{"edgeType":"contains","source":4579,"target":4738},{"edgeType":"calls","source":1818,"target":1126},{"edgeType":"contains","source":3626,"target":3628},{"edgeType":"calls","source":6722,"target":4475},{"edgeType":"contains","source":4691,"target":5502},{"edgeType":"imports","source":6610,"target":49},{"edgeType":"calls","source":2998,"target":481},{"edgeType":"contains","source":4432,"target":5075},{"edgeType":"calls","source":1964,"target":1880},{"edgeType":"contains","source":3820,"target":3963},{"edgeType":"calls","source":4195,"target":370},{"edgeType":"calls","source":2626,"target":1443},{"edgeType":"contains","source":5674,"target":5676},{"edgeType":"contains","source":2599,"target":2704},{"edgeType":"calls","source":2899,"target":380},{"edgeType":"contains","source":153,"target":306},{"edgeType":"calls","source":1325,"target":548},{"edgeType":"contains","source":4318,"target":4379},{"edgeType":"contains","source":521,"target":526},{"edgeType":"calls","source":6145,"target":171},{"edgeType":"calls","source":1234,"target":1254},{"edgeType":"contains","source":3820,"target":3962},{"edgeType":"contains","source":3819,"target":3993},{"edgeType":"calls","source":4195,"target":371},{"edgeType":"calls","source":6722,"target":4477},{"edgeType":"contains","source":5674,"target":5677},{"edgeType":"calls","source":2998,"target":479},{"edgeType":"contains","source":4782,"target":4793},{"edgeType":"calls","source":144,"target":165},{"edgeType":"calls","source":6589,"target":144},{"edgeType":"calls","source":3822,"target":304},{"edgeType":"contains","source":2502,"target":2537},{"edgeType":"contains","source":6599,"target":6600},{"edgeType":"calls","source":4195,"target":368},{"edgeType":"calls","source":6145,"target":170},{"edgeType":"contains","source":3461,"target":3463},{"edgeType":"calls","source":6711,"target":591},{"edgeType":"calls","source":2485,"target":527},{"edgeType":"calls","source":6657,"target":2265},{"edgeType":"calls","source":144,"target":164},{"edgeType":"calls","source":5220,"target":304},{"edgeType":"calls","source":2998,"target":480},{"edgeType":"calls","source":968,"target":1046},{"edgeType":"contains","source":153,"target":308},{"edgeType":"calls","source":1579,"target":1132},{"edgeType":"contains","source":453,"target":522},{"edgeType":"contains","source":3014,"target":3578},{"edgeType":"calls","source":6717,"target":6748},{"edgeType":"calls","source":2620,"target":571},{"edgeType":"calls","source":6374,"target":469},{"edgeType":"calls","source":4195,"target":369},{"edgeType":"calls","source":569,"target":731},{"edgeType":"calls","source":2795,"target":431},{"edgeType":"calls","source":2626,"target":1442},{"edgeType":"calls","source":2485,"target":528},{"edgeType":"calls","source":6419,"target":2344},{"edgeType":"contains","source":2502,"target":2510},{"edgeType":"calls","source":1667,"target":1669},{"edgeType":"calls","source":3872,"target":965},{"edgeType":"calls","source":1602,"target":1570},{"edgeType":"calls","source":5504,"target":1112},{"edgeType":"contains","source":885,"target":1898},{"edgeType":"contains","source":30,"target":5148},{"edgeType":"imports","source":4459,"target":190},{"edgeType":"contains","source":3624,"target":3668},{"edgeType":"calls","source":4739,"target":4743},{"edgeType":"calls","source":4415,"target":1046},{"edgeType":"calls","source":6419,"target":2345},{"edgeType":"calls","source":5453,"target":5863},{"edgeType":"calls","source":3387,"target":146},{"edgeType":"imports","source":130,"target":144},{"edgeType":"contains","source":885,"target":1897},{"edgeType":"imports","source":130,"target":145},{"edgeType":"contains","source":30,"target":5147},{"edgeType":"calls","source":2801,"target":342},{"edgeType":"imports","source":1379,"target":535},{"edgeType":"calls","source":4471,"target":366},{"edgeType":"calls","source":6419,"target":2346},{"edgeType":"contains","source":4668,"target":5127},{"edgeType":"calls","source":1539,"target":354},{"edgeType":"calls","source":4471,"target":364},{"edgeType":"contains","source":4579,"target":4715},{"edgeType":"calls","source":2984,"target":3122},{"edgeType":"contains","source":2502,"target":2508},{"edgeType":"contains","source":3,"target":3873},{"edgeType":"calls","source":1135,"target":1250},{"edgeType":"calls","source":1799,"target":1807},{"edgeType":"contains","source":4352,"target":4353},{"edgeType":"contains","source":885,"target":1900},{"edgeType":"calls","source":1749,"target":1243},{"edgeType":"calls","source":6860,"target":303},{"edgeType":"calls","source":607,"target":706},{"edgeType":"calls","source":6419,"target":2347},{"edgeType":"contains","source":4668,"target":5126},{"edgeType":"contains","source":3954,"target":4005},{"edgeType":"calls","source":968,"target":84},{"edgeType":"imports","source":6286,"target":1691},{"edgeType":"calls","source":3821,"target":431},{"edgeType":"imports","source":130,"target":142},{"edgeType":"calls","source":5453,"target":5861},{"edgeType":"contains","source":30,"target":5149},{"edgeType":"calls","source":1135,"target":1249},{"edgeType":"contains","source":885,"target":1899},{"edgeType":"calls","source":6860,"target":304},{"edgeType":"calls","source":4568,"target":528},{"edgeType":"calls","source":4145,"target":4128},{"edgeType":"contains","source":5196,"target":5670},{"edgeType":"calls","source":6483,"target":364},{"edgeType":"imports","source":1379,"target":533},{"edgeType":"calls","source":4750,"target":171},{"edgeType":"contains","source":5241,"target":5340},{"edgeType":"calls","source":5905,"target":304},{"edgeType":"calls","source":2984,"target":3120},{"edgeType":"calls","source":2329,"target":170},{"edgeType":"contains","source":3624,"target":3672},{"edgeType":"contains","source":30,"target":924},{"edgeType":"calls","source":2086,"target":303},{"edgeType":"calls","source":6424,"target":6422},{"edgeType":"calls","source":6797,"target":144},{"edgeType":"calls","source":1350,"target":921},{"edgeType":"contains","source":1305,"target":511},{"edgeType":"calls","source":4568,"target":527},{"edgeType":"calls","source":4750,"target":170},{"edgeType":"imports","source":5285,"target":2072},{"edgeType":"calls","source":5905,"target":303},{"edgeType":"calls","source":2329,"target":171},{"edgeType":"contains","source":2502,"target":2515},{"edgeType":"calls","source":2963,"target":601},{"edgeType":"contains","source":5871,"target":5887},{"edgeType":"calls","source":3840,"target":897},{"edgeType":"contains","source":1814,"target":2702},{"edgeType":"contains","source":3856,"target":3878},{"edgeType":"contains","source":3624,"target":3671},{"edgeType":"calls","source":6786,"target":1543},{"edgeType":"contains","source":5686,"target":6337},{"edgeType":"calls","source":6483,"target":366},{"edgeType":"extends","source":5324,"target":36},{"edgeType":"calls","source":1192,"target":533},{"edgeType":"calls","source":2559,"target":2555},{"edgeType":"calls","source":3824,"target":333},{"edgeType":"contains","source":4668,"target":5131},{"edgeType":"contains","source":2502,"target":2512},{"edgeType":"contains","source":2599,"target":2676},{"edgeType":"calls","source":4443,"target":171},{"edgeType":"calls","source":1799,"target":1803},{"edgeType":"calls","source":1029,"target":304},{"edgeType":"contains","source":4748,"target":4765},{"edgeType":"contains","source":3030,"target":3056},{"edgeType":"calls","source":4536,"target":458},{"edgeType":"contains","source":5241,"target":5337},{"edgeType":"calls","source":4443,"target":170},{"edgeType":"contains","source":4115,"target":4303},{"edgeType":"calls","source":5867,"target":422},{"edgeType":"calls","source":1799,"target":1802},{"edgeType":"contains","source":12,"target":3598},{"edgeType":"calls","source":2086,"target":304},{"edgeType":"calls","source":5386,"target":4762},{"edgeType":"contains","source":5592,"target":6082},{"edgeType":"imports","source":6476,"target":3205},{"edgeType":"calls","source":6483,"target":368},{"edgeType":"contains","source":1305,"target":510},{"edgeType":"calls","source":1029,"target":303},{"edgeType":"contains","source":3030,"target":3057},{"edgeType":"calls","source":4536,"target":457},{"edgeType":"contains","source":1907,"target":1936},{"edgeType":"contains","source":3954,"target":4016},{"edgeType":"calls","source":6716,"target":1602},{"edgeType":"calls","source":5867,"target":421},{"edgeType":"contains","source":3624,"target":3676},{"edgeType":"calls","source":4881,"target":333},{"edgeType":"calls","source":6483,"target":369},{"edgeType":"contains","source":2502,"target":2518},{"edgeType":"calls","source":3824,"target":332},{"edgeType":"calls","source":4301,"target":342},{"edgeType":"calls","source":6863,"target":6559},{"edgeType":"calls","source":6658,"target":6572},{"edgeType":"extends","source":2119,"target":36},{"edgeType":"calls","source":4881,"target":332},{"edgeType":"calls","source":5488,"target":2655},{"edgeType":"calls","source":6483,"target":370},{"edgeType":"calls","source":4740,"target":475},{"edgeType":"contains","source":4579,"target":4724},{"edgeType":"contains","source":2502,"target":2519},{"edgeType":"calls","source":2826,"target":2730},{"edgeType":"calls","source":1163,"target":371},{"edgeType":"calls","source":5868,"target":5673},{"edgeType":"contains","source":5871,"target":5900},{"edgeType":"calls","source":4740,"target":473},{"edgeType":"contains","source":3954,"target":4014},{"edgeType":"calls","source":5901,"target":422},{"edgeType":"calls","source":6863,"target":6560},{"edgeType":"calls","source":4078,"target":4082},{"edgeType":"calls","source":2184,"target":431},{"edgeType":"calls","source":6839,"target":962},{"edgeType":"calls","source":6483,"target":371},{"edgeType":"calls","source":5488,"target":2654},{"edgeType":"contains","source":4115,"target":4309},{"edgeType":"calls","source":3373,"target":568},{"edgeType":"contains","source":4318,"target":4358},{"edgeType":"calls","source":4740,"target":474},{"edgeType":"extends","source":6620,"target":36},{"edgeType":"contains","source":2311,"target":5267},{"edgeType":"contains","source":2502,"target":2517},{"edgeType":"calls","source":5901,"target":421},{"edgeType":"calls","source":7070,"target":144},{"edgeType":"calls","source":6839,"target":963},{"edgeType":"contains","source":3954,"target":4013},{"edgeType":"calls","source":4293,"target":588},{"edgeType":"calls","source":2691,"target":571},{"edgeType":"calls","source":1234,"target":1343},{"edgeType":"calls","source":1163,"target":368},{"edgeType":"calls","source":1039,"target":1041},{"edgeType":"contains","source":3624,"target":3680},{"edgeType":"calls","source":1784,"target":144},{"edgeType":"imports","source":4668,"target":49},{"edgeType":"calls","source":4511,"target":171},{"edgeType":"calls","source":6572,"target":2899},{"edgeType":"extends","source":4165,"target":36},{"edgeType":"calls","source":2870,"target":304},{"edgeType":"contains","source":1977,"target":1885},{"edgeType":"calls","source":6464,"target":962},{"edgeType":"contains","source":3954,"target":4021},{"edgeType":"contains","source":30,"target":933},{"edgeType":"contains","source":1908,"target":1910},{"edgeType":"contains","source":2502,"target":2522},{"edgeType":"calls","source":5004,"target":4972},{"edgeType":"calls","source":6777,"target":2887},{"edgeType":"calls","source":1136,"target":147},{"edgeType":"calls","source":4511,"target":170},{"edgeType":"calls","source":7072,"target":84},{"edgeType":"contains","source":5196,"target":5685},{"edgeType":"contains","source":3624,"target":3679},{"edgeType":"contains","source":4748,"target":4774},{"edgeType":"calls","source":6464,"target":963},{"edgeType":"calls","source":2859,"target":1703},{"edgeType":"calls","source":147,"target":152},{"edgeType":"contains","source":1908,"target":1911},{"edgeType":"contains","source":30,"target":932},{"edgeType":"contains","source":2502,"target":2523},{"edgeType":"contains","source":4318,"target":4363},{"edgeType":"contains","source":4502,"target":5001},{"edgeType":"contains","source":5908,"target":6863},{"edgeType":"calls","source":4750,"target":1216},{"edgeType":"calls","source":4770,"target":596},{"edgeType":"contains","source":3856,"target":3885},{"edgeType":"calls","source":6682,"target":548},{"edgeType":"contains","source":1907,"target":1938},{"edgeType":"contains","source":5196,"target":5684},{"edgeType":"contains","source":3624,"target":3678},{"edgeType":"calls","source":6512,"target":533},{"edgeType":"contains","source":1302,"target":3781},{"edgeType":"contains","source":4748,"target":4773},{"edgeType":"contains","source":6280,"target":6959},{"edgeType":"contains","source":2073,"target":2078},{"edgeType":"calls","source":5102,"target":5103},{"edgeType":"calls","source":5127,"target":1157},{"edgeType":"contains","source":4668,"target":5139},{"edgeType":"calls","source":1163,"target":370},{"edgeType":"calls","source":5355,"target":431},{"edgeType":"calls","source":1006,"target":1008},{"edgeType":"calls","source":6206,"target":475},{"edgeType":"calls","source":4914,"target":4588},{"edgeType":"calls","source":1531,"target":588},{"edgeType":"imports","source":130,"target":147},{"edgeType":"contains","source":1229,"target":1817},{"edgeType":"contains","source":1908,"target":1909},{"edgeType":"contains","source":3954,"target":4018},{"edgeType":"calls","source":2870,"target":303},{"edgeType":"calls","source":1385,"target":886},{"edgeType":"calls","source":1163,"target":369},{"edgeType":"imports","source":5195,"target":2741},{"edgeType":"calls","source":1196,"target":431},{"edgeType":"contains","source":4318,"target":4335},{"edgeType":"calls","source":1800,"target":1791},{"edgeType":"calls","source":6804,"target":963},{"edgeType":"calls","source":4641,"target":4626},{"edgeType":"contains","source":6432,"target":6452},{"edgeType":"imports","source":6432,"target":5604},{"edgeType":"calls","source":6249,"target":2345},{"edgeType":"calls","source":4240,"target":144},{"edgeType":"calls","source":6215,"target":2342},{"edgeType":"contains","source":5196,"target":5657},{"edgeType":"contains","source":3955,"target":3961},{"edgeType":"calls","source":7065,"target":3443},{"edgeType":"contains","source":2599,"target":3714},{"edgeType":"contains","source":4579,"target":4700},{"edgeType":"contains","source":5871,"target":5874},{"edgeType":"contains","source":4391,"target":5243},{"edgeType":"calls","source":1602,"target":1586},{"edgeType":"calls","source":5220,"target":4647},{"edgeType":"extends","source":2316,"target":2359},{"edgeType":"contains","source":2237,"target":2252},{"edgeType":"contains","source":4115,"target":4286},{"edgeType":"contains","source":4318,"target":4334},{"edgeType":"calls","source":4641,"target":4625},{"edgeType":"contains","source":6432,"target":6453},{"edgeType":"calls","source":1139,"target":1140},{"edgeType":"calls","source":6992,"target":421},{"edgeType":"calls","source":4171,"target":170},{"edgeType":"calls","source":6215,"target":2341},{"edgeType":"calls","source":6249,"target":2344},{"edgeType":"calls","source":4652,"target":1113},{"edgeType":"contains","source":5241,"target":5318},{"edgeType":"calls","source":6930,"target":6572},{"edgeType":"contains","source":3955,"target":3960},{"edgeType":"calls","source":5876,"target":165},{"edgeType":"calls","source":6992,"target":422},{"edgeType":"imports","source":130,"target":128},{"edgeType":"calls","source":1045,"target":886},{"edgeType":"calls","source":3992,"target":431},{"edgeType":"calls","source":1812,"target":364},{"edgeType":"contains","source":6432,"target":6454},{"edgeType":"calls","source":6423,"target":6434},{"edgeType":"contains","source":5195,"target":5686},{"edgeType":"calls","source":6249,"target":2343},{"edgeType":"calls","source":4652,"target":1112},{"edgeType":"extends","source":5360,"target":5241},{"edgeType":"calls","source":2256,"target":338},{"edgeType":"contains","source":3955,"target":3959},{"edgeType":"calls","source":4338,"target":3447},{"edgeType":"calls","source":5876,"target":164},{"edgeType":"calls","source":7117,"target":7118},{"edgeType":"contains","source":2468,"target":2488},{"edgeType":"contains","source":3856,"target":3857},{"edgeType":"calls","source":3513,"target":481},{"edgeType":"calls","source":3518,"target":3497},{"edgeType":"contains","source":4115,"target":4284},{"edgeType":"contains","source":4318,"target":4333},{"edgeType":"calls","source":6689,"target":303},{"edgeType":"contains","source":2898,"target":2901},{"edgeType":"calls","source":6249,"target":2342},{"edgeType":"contains","source":3814,"target":4100},{"edgeType":"contains","source":4913,"target":4914},{"edgeType":"calls","source":6544,"target":570},{"edgeType":"calls","source":2256,"target":339},{"edgeType":"contains","source":2599,"target":3713},{"edgeType":"calls","source":749,"target":548},{"edgeType":"calls","source":2878,"target":84},{"edgeType":"calls","source":5659,"target":548},{"edgeType":"calls","source":6753,"target":6776},{"edgeType":"contains","source":5671,"target":5735},{"edgeType":"calls","source":7117,"target":7119},{"edgeType":"contains","source":4318,"target":4332},{"edgeType":"calls","source":2593,"target":2573},{"edgeType":"calls","source":4103,"target":1216},{"edgeType":"calls","source":4013,"target":4006},{"edgeType":"calls","source":1948,"target":370},{"edgeType":"calls","source":6249,"target":2341},{"edgeType":"calls","source":6689,"target":304},{"edgeType":"calls","source":4649,"target":146},{"edgeType":"contains","source":4682,"target":4683},{"edgeType":"imports","source":1415,"target":1513},{"edgeType":"calls","source":6896,"target":6572},{"edgeType":"calls","source":4949,"target":4588},{"edgeType":"contains","source":4391,"target":5247},{"edgeType":"contains","source":5908,"target":6837},{"edgeType":"calls","source":5672,"target":144},{"edgeType":"calls","source":3513,"target":479},{"edgeType":"calls","source":1948,"target":369},{"edgeType":"calls","source":1818,"target":171},{"edgeType":"contains","source":4318,"target":4338},{"edgeType":"contains","source":4748,"target":4750},{"edgeType":"calls","source":2256,"target":337},{"edgeType":"contains","source":4391,"target":5246},{"edgeType":"calls","source":6725,"target":4475},{"edgeType":"calls","source":3513,"target":480},{"edgeType":"calls","source":1948,"target":368},{"edgeType":"contains","source":3820,"target":3921},{"edgeType":"calls","source":1818,"target":170},{"edgeType":"contains","source":6432,"target":6450},{"edgeType":"contains","source":5592,"target":6064},{"edgeType":"calls","source":3513,"target":477},{"edgeType":"calls","source":6207,"target":5755},{"edgeType":"calls","source":5235,"target":5233},{"edgeType":"contains","source":586,"target":587},{"edgeType":"calls","source":3224,"target":980},{"edgeType":"contains","source":4748,"target":4749},{"edgeType":"calls","source":5120,"target":342},{"edgeType":"imports","source":3949,"target":2248},{"edgeType":"calls","source":143,"target":304},{"edgeType":"calls","source":1733,"target":1751},{"edgeType":"contains","source":4391,"target":5245},{"edgeType":"contains","source":3856,"target":3861},{"edgeType":"calls","source":6047,"target":144},{"edgeType":"calls","source":1948,"target":371},{"edgeType":"calls","source":3513,"target":478},{"edgeType":"contains","source":5895,"target":3014},{"edgeType":"contains","source":4788,"target":4565},{"edgeType":"contains","source":5196,"target":5658},{"edgeType":"calls","source":4511,"target":1250},{"edgeType":"contains","source":2468,"target":2493},{"edgeType":"calls","source":143,"target":303},{"edgeType":"calls","source":6725,"target":4477},{"edgeType":"calls","source":6110,"target":304},{"edgeType":"calls","source":6118,"target":56},{"edgeType":"contains","source":4391,"target":5244},{"edgeType":"contains","source":3988,"target":3996},{"edgeType":"calls","source":7136,"target":1249},{"edgeType":"imports","source":5895,"target":3216},{"edgeType":"contains","source":6824,"target":6993},{"edgeType":"calls","source":1507,"target":1352},{"edgeType":"imports","source":163,"target":169},{"edgeType":"contains","source":885,"target":1890},{"edgeType":"contains","source":520,"target":521},{"edgeType":"calls","source":4511,"target":1249},{"edgeType":"contains","source":5871,"target":5882},{"edgeType":"contains","source":2330,"target":2548},{"edgeType":"calls","source":2560,"target":421},{"edgeType":"calls","source":1582,"target":84},{"edgeType":"calls","source":7136,"target":1250},{"edgeType":"calls","source":2228,"target":2257},{"edgeType":"calls","source":6110,"target":303},{"edgeType":"contains","source":5607,"target":5610},{"edgeType":"imports","source":6610,"target":78},{"edgeType":"contains","source":24,"target":40},{"edgeType":"calls","source":6486,"target":6602},{"edgeType":"contains","source":5,"target":2743},{"edgeType":"calls","source":4714,"target":4468},{"edgeType":"contains","source":6834,"target":4570},{"edgeType":"contains","source":1988,"target":2581},{"edgeType":"calls","source":3513,"target":476},{"edgeType":"calls","source":2533,"target":1259},{"edgeType":"calls","source":2560,"target":422},{"edgeType":"contains","source":4579,"target":4708},{"edgeType":"contains","source":2502,"target":2503},{"edgeType":"contains","source":3820,"target":3925},{"edgeType":"contains","source":2468,"target":2499},{"edgeType":"contains","source":3856,"target":3866},{"edgeType":"contains","source":2330,"target":2549},{"edgeType":"extends","source":5460,"target":36},{"edgeType":"calls","source":2228,"target":2258},{"edgeType":"calls","source":1948,"target":364},{"edgeType":"contains","source":5607,"target":5611},{"edgeType":"contains","source":6824,"target":6995},{"edgeType":"calls","source":5740,"target":144},{"edgeType":"imports","source":2315,"target":49},{"edgeType":"calls","source":5478,"target":5095},{"edgeType":"imports","source":2176,"target":2244},{"edgeType":"contains","source":4378,"target":4595},{"edgeType":"calls","source":4676,"target":4588},{"edgeType":"contains","source":885,"target":1892},{"edgeType":"calls","source":4938,"target":4922},{"edgeType":"contains","source":6459,"target":6683},{"edgeType":"contains","source":5196,"target":5663},{"edgeType":"contains","source":6499,"target":6500},{"edgeType":"calls","source":1676,"target":1400},{"edgeType":"contains","source":2330,"target":2546},{"edgeType":"contains","source":3624,"target":3658},{"edgeType":"calls","source":1962,"target":2047},{"edgeType":"calls","source":4818,"target":4413},{"edgeType":"contains","source":4115,"target":4291},{"edgeType":"calls","source":6410,"target":2618},{"edgeType":"calls","source":525,"target":84},{"edgeType":"contains","source":4682,"target":4684},{"edgeType":"contains","source":885,"target":1891},{"edgeType":"contains","source":3014,"target":3541},{"edgeType":"calls","source":5235,"target":5228},{"edgeType":"imports","source":3166,"target":2207},{"edgeType":"contains","source":2330,"target":2547},{"edgeType":"calls","source":4376,"target":146},{"edgeType":"calls","source":4251,"target":4021},{"edgeType":"imports","source":6610,"target":79},{"edgeType":"calls","source":6820,"target":6821},{"edgeType":"calls","source":1948,"target":366},{"edgeType":"calls","source":1962,"target":2046},{"edgeType":"imports","source":130,"target":131},{"edgeType":"contains","source":4115,"target":4298},{"edgeType":"imports","source":5895,"target":49},{"edgeType":"contains","source":5,"target":4862},{"edgeType":"contains","source":6459,"target":6676},{"edgeType":"calls","source":2984,"target":3128},{"edgeType":"contains","source":3624,"target":3664},{"edgeType":"contains","source":885,"target":1894},{"edgeType":"contains","source":5196,"target":5669},{"edgeType":"calls","source":7037,"target":1152},{"edgeType":"calls","source":4471,"target":371},{"edgeType":"calls","source":6690,"target":282},{"edgeType":"calls","source":6381,"target":354},{"edgeType":"calls","source":6419,"target":2341},{"edgeType":"contains","source":2502,"target":2507},{"edgeType":"contains","source":6664,"target":6665},{"edgeType":"contains","source":6824,"target":6990},{"edgeType":"contains","source":6699,"target":6637},{"edgeType":"calls","source":1799,"target":1808},{"edgeType":"imports","source":435,"target":190},{"edgeType":"contains","source":885,"target":1893},{"edgeType":"calls","source":1991,"target":84},{"edgeType":"contains","source":2898,"target":2915},{"edgeType":"calls","source":4471,"target":370},{"edgeType":"calls","source":6820,"target":6823},{"edgeType":"calls","source":607,"target":707},{"edgeType":"contains","source":5196,"target":5668},{"edgeType":"calls","source":511,"target":512},{"edgeType":"imports","source":130,"target":1186},{"edgeType":"calls","source":6419,"target":2342},{"edgeType":"calls","source":3535,"target":1901},{"edgeType":"calls","source":5867,"target":431},{"edgeType":"calls","source":4852,"target":4413},{"edgeType":"calls","source":5433,"target":144},{"edgeType":"calls","source":1818,"target":165},{"edgeType":"contains","source":2330,"target":2550},{"edgeType":"calls","source":2559,"target":2560},{"edgeType":"contains","source":885,"target":1896},{"edgeType":"calls","source":4471,"target":369},{"edgeType":"calls","source":2014,"target":431},{"edgeType":"contains","source":5607,"target":5608},{"edgeType":"contains","source":3460,"target":3461},{"edgeType":"calls","source":6419,"target":2343},{"edgeType":"calls","source":2999,"target":548},{"edgeType":"imports","source":3781,"target":49},{"edgeType":"calls","source":2984,"target":3127},{"edgeType":"contains","source":6699,"target":6639},{"edgeType":"calls","source":5504,"target":1113},{"edgeType":"contains","source":2502,"target":2505},{"edgeType":"calls","source":1818,"target":164},{"edgeType":"contains","source":2330,"target":2551},{"edgeType":"contains","source":5196,"target":5666},{"edgeType":"contains","source":885,"target":1895},{"edgeType":"calls","source":4471,"target":368},{"edgeType":"contains","source":5607,"target":5609},{"edgeType":"calls","source":7028,"target":6687},{"edgeType":"calls","source":930,"target":171},{"edgeType":"calls","source":2983,"target":3122},{"edgeType":"contains","source":4432,"target":5013},{"edgeType":"contains","source":2203,"target":2232},{"edgeType":"contains","source":4119,"target":4145},{"edgeType":"contains","source":321,"target":323},{"edgeType":"contains","source":4318,"target":4319},{"edgeType":"contains","source":30,"target":5115},{"edgeType":"contains","source":6824,"target":6968},{"edgeType":"calls","source":6552,"target":303},{"edgeType":"calls","source":930,"target":170},{"edgeType":"contains","source":23,"target":46},{"edgeType":"contains","source":22,"target":77},{"edgeType":"calls","source":4272,"target":1216},{"edgeType":"contains","source":2468,"target":2475},{"edgeType":"contains","source":4432,"target":5012},{"edgeType":"contains","source":321,"target":322},{"edgeType":"contains","source":2330,"target":2525},{"edgeType":"calls","source":1708,"target":364},{"edgeType":"imports","source":6604,"target":321},{"edgeType":"calls","source":6893,"target":303},{"edgeType":"calls","source":6147,"target":171},{"edgeType":"calls","source":6552,"target":304},{"edgeType":"contains","source":1305,"target":471},{"edgeType":"contains","source":2071,"target":2094},{"edgeType":"contains","source":2764,"target":2809},{"edgeType":"contains","source":1814,"target":2662},{"edgeType":"contains","source":2203,"target":2230},{"edgeType":"contains","source":3624,"target":3633},{"edgeType":"calls","source":6893,"target":304},{"edgeType":"calls","source":6147,"target":170},{"edgeType":"calls","source":2024,"target":84},{"edgeType":"contains","source":5241,"target":5300},{"edgeType":"contains","source":6824,"target":6970},{"edgeType":"calls","source":2826,"target":588},{"edgeType":"imports","source":4631,"target":179},{"edgeType":"contains","source":4119,"target":4142},{"edgeType":"contains","source":3981,"target":4192},{"edgeType":"calls","source":7020,"target":596},{"edgeType":"imports","source":5380,"target":2329},{"edgeType":"calls","source":5222,"target":304},{"edgeType":"calls","source":1708,"target":366},{"edgeType":"calls","source":6104,"target":445},{"edgeType":"calls","source":1581,"target":1132},{"edgeType":"imports","source":130,"target":175},{"edgeType":"calls","source":6724,"target":6601},{"edgeType":"calls","source":2833,"target":372},{"edgeType":"calls","source":2793,"target":555},{"edgeType":"calls","source":2533,"target":1216},{"edgeType":"calls","source":4740,"target":448},{"edgeType":"calls","source":5222,"target":303},{"edgeType":"contains","source":2468,"target":2478},{"edgeType":"calls","source":1798,"target":1799},{"edgeType":"imports","source":130,"target":172},{"edgeType":"contains","source":4115,"target":4273},{"edgeType":"calls","source":1804,"target":556},{"edgeType":"calls","source":7065,"target":6601},{"edgeType":"contains","source":132,"target":901},{"edgeType":"contains","source":6604,"target":3214},{"edgeType":"calls","source":4199,"target":304},{"edgeType":"contains","source":4318,"target":4323},{"edgeType":"calls","source":6712,"target":4860},{"edgeType":"contains","source":5686,"target":6303},{"edgeType":"calls","source":2801,"target":304},{"edgeType":"calls","source":4740,"target":447},{"edgeType":"calls","source":4881,"target":304},{"edgeType":"calls","source":2809,"target":1113},{"edgeType":"extends","source":2495,"target":36},{"edgeType":"calls","source":6104,"target":443},{"edgeType":"calls","source":1534,"target":469},{"edgeType":"contains","source":4115,"target":4272},{"edgeType":"calls","source":6937,"target":1057},{"edgeType":"calls","source":3513,"target":431},{"edgeType":"contains","source":3624,"target":3638},{"edgeType":"contains","source":5705,"target":5715},{"edgeType":"calls","source":2823,"target":2794},{"edgeType":"contains","source":4691,"target":5443},{"edgeType":"calls","source":4881,"target":303},{"edgeType":"contains","source":2468,"target":2476},{"edgeType":"contains","source":6824,"target":6966},{"edgeType":"calls","source":6138,"target":445},{"edgeType":"contains","source":2203,"target":2234},{"edgeType":"calls","source":5896,"target":548},{"edgeType":"calls","source":4801,"target":1725},{"edgeType":"contains","source":2237,"target":2238},{"edgeType":"contains","source":2860,"target":3008},{"edgeType":"calls","source":6374,"target":528},{"edgeType":"calls","source":3348,"target":3428},{"edgeType":"calls","source":708,"target":709},{"edgeType":"contains","source":2599,"target":3701},{"edgeType":"contains","source":4691,"target":5441},{"edgeType":"contains","source":2330,"target":2527},{"edgeType":"calls","source":6215,"target":171},{"edgeType":"calls","source":1804,"target":557},{"edgeType":"contains","source":4115,"target":4270},{"edgeType":"contains","source":2203,"target":2236},{"edgeType":"calls","source":6374,"target":527},{"edgeType":"contains","source":4318,"target":4320},{"edgeType":"calls","source":4199,"target":303},{"edgeType":"imports","source":3030,"target":1175},{"edgeType":"calls","source":3348,"target":3429},{"edgeType":"contains","source":5671,"target":5714},{"edgeType":"imports","source":1907,"target":49},{"edgeType":"calls","source":6514,"target":431},{"edgeType":"calls","source":2809,"target":1112},{"edgeType":"calls","source":2801,"target":303},{"edgeType":"contains","source":4391,"target":5235},{"edgeType":"calls","source":2525,"target":2513},{"edgeType":"contains","source":162,"target":6317},{"edgeType":"calls","source":6688,"target":3494},{"edgeType":"imports","source":4668,"target":78},{"edgeType":"calls","source":6215,"target":170},{"edgeType":"calls","source":7068,"target":170},{"edgeType":"calls","source":6138,"target":443},{"edgeType":"calls","source":6442,"target":532},{"edgeType":"contains","source":132,"target":905},{"edgeType":"contains","source":2201,"target":2303},{"edgeType":"calls","source":580,"target":443},{"edgeType":"contains","source":2203,"target":2241},{"edgeType":"contains","source":2599,"target":3706},{"edgeType":"extends","source":4541,"target":36},{"edgeType":"calls","source":5227,"target":144},{"edgeType":"contains","source":6557,"target":6797},{"edgeType":"calls","source":1878,"target":371},{"edgeType":"calls","source":2524,"target":431},{"edgeType":"calls","source":4407,"target":4422},{"edgeType":"contains","source":5241,"target":5310},{"edgeType":"imports","source":4668,"target":79},{"edgeType":"extends","source":5647,"target":1691},{"edgeType":"calls","source":6115,"target":1155},{"edgeType":"calls","source":7068,"target":171},{"edgeType":"contains","source":2764,"target":2820},{"edgeType":"calls","source":4079,"target":4021},{"edgeType":"calls","source":1384,"target":886},{"edgeType":"calls","source":6541,"target":4881},{"edgeType":"calls","source":1137,"target":1144},{"edgeType":"contains","source":2599,"target":3707},{"edgeType":"contains","source":936,"target":3466},{"edgeType":"contains","source":4579,"target":4690},{"edgeType":"contains","source":5592,"target":6060},{"edgeType":"imports","source":4668,"target":80},{"edgeType":"contains","source":2070,"target":2133},{"edgeType":"calls","source":6249,"target":171},{"edgeType":"calls","source":4879,"target":4588},{"edgeType":"calls","source":2899,"target":431},{"edgeType":"imports","source":1379,"target":575},{"edgeType":"calls","source":580,"target":445},{"edgeType":"contains","source":2237,"target":2242},{"edgeType":"imports","source":130,"target":183},{"edgeType":"calls","source":968,"target":1101},{"edgeType":"contains","source":2468,"target":2481},{"edgeType":"calls","source":4667,"target":588},{"edgeType":"calls","source":1804,"target":553},{"edgeType":"contains","source":2330,"target":2531},{"edgeType":"calls","source":6249,"target":170},{"edgeType":"imports","source":6074,"target":889},{"edgeType":"calls","source":6115,"target":1153},{"edgeType":"calls","source":4952,"target":210},{"edgeType":"contains","source":5,"target":3786},{"edgeType":"contains","source":132,"target":906},{"edgeType":"contains","source":2599,"target":3705},{"edgeType":"calls","source":1226,"target":501},{"edgeType":"contains","source":4691,"target":5445},{"edgeType":"contains","source":885,"target":1878},{"edgeType":"calls","source":1748,"target":170},{"edgeType":"calls","source":1878,"target":368},{"edgeType":"calls","source":4433,"target":442},{"edgeType":"calls","source":6384,"target":212},{"edgeType":"calls","source":6601,"target":910},{"edgeType":"contains","source":3988,"target":3991},{"edgeType":"calls","source":4952,"target":209},{"edgeType":"contains","source":5,"target":3789},{"edgeType":"contains","source":6604,"target":3222},{"edgeType":"contains","source":4391,"target":5238},{"edgeType":"calls","source":6381,"target":304},{"edgeType":"calls","source":6601,"target":911},{"edgeType":"calls","source":4466,"target":475},{"edgeType":"calls","source":2976,"target":157},{"edgeType":"contains","source":3988,"target":3990},{"edgeType":"contains","source":6604,"target":3223},{"edgeType":"contains","source":885,"target":1876},{"edgeType":"contains","source":2468,"target":2487},{"edgeType":"extends","source":4507,"target":36},{"edgeType":"calls","source":1878,"target":370},{"edgeType":"calls","source":3912,"target":3906},{"edgeType":"calls","source":6728,"target":146},{"edgeType":"calls","source":2293,"target":2300},{"edgeType":"calls","source":6381,"target":303},{"edgeType":"calls","source":6401,"target":1797},{"edgeType":"calls","source":4466,"target":474},{"edgeType":"imports","source":130,"target":179},{"edgeType":"contains","source":4091,"target":1853},{"edgeType":"contains","source":2201,"target":2305},{"edgeType":"contains","source":6607,"target":3131},{"edgeType":"contains","source":6604,"target":3224},{"edgeType":"calls","source":5672,"target":84},{"edgeType":"contains","source":6630,"target":6646},{"edgeType":"calls","source":6804,"target":962},{"edgeType":"calls","source":1748,"target":171},{"edgeType":"imports","source":5285,"target":3156},{"edgeType":"calls","source":1878,"target":369},{"edgeType":"calls","source":6690,"target":268},{"edgeType":"calls","source":7069,"target":146},{"edgeType":"calls","source":4466,"target":473},{"edgeType":"calls","source":2533,"target":146},{"edgeType":"extends","source":4882,"target":36},{"edgeType":"extends","source":6280,"target":36},{"edgeType":"calls","source":2874,"target":146},{"edgeType":"calls","source":4954,"target":144},{"edgeType":"calls","source":1701,"target":570},{"edgeType":"calls","source":4740,"target":467},{"edgeType":"extends","source":4472,"target":36},{"edgeType":"calls","source":3311,"target":370},{"edgeType":"contains","source":3056,"target":1142},{"edgeType":"calls","source":3932,"target":146},{"edgeType":"calls","source":6206,"target":474},{"edgeType":"calls","source":1163,"target":364},{"edgeType":"calls","source":6727,"target":146},{"edgeType":"calls","source":4715,"target":4413},{"edgeType":"calls","source":6402,"target":1797},{"edgeType":"contains","source":4671,"target":4986},{"edgeType":"contains","source":6032,"target":6135},{"edgeType":"calls","source":4302,"target":304},{"edgeType":"contains","source":1814,"target":2648},{"edgeType":"calls","source":7105,"target":56},{"edgeType":"calls","source":7068,"target":146},{"edgeType":"contains","source":4691,"target":5423},{"edgeType":"contains","source":6557,"target":6772},{"edgeType":"contains","source":5870,"target":5872},{"edgeType":"calls","source":3311,"target":371},{"edgeType":"calls","source":4740,"target":466},{"edgeType":"calls","source":3120,"target":3121},{"edgeType":"calls","source":6206,"target":473},{"edgeType":"calls","source":1170,"target":146},{"edgeType":"imports","source":6432,"target":5636},{"edgeType":"contains","source":2764,"target":2796},{"edgeType":"calls","source":6559,"target":6412},{"edgeType":"contains","source":4671,"target":4985},{"edgeType":"calls","source":4302,"target":303},{"edgeType":"contains","source":5870,"target":5873},{"edgeType":"calls","source":1886,"target":147},{"edgeType":"contains","source":4119,"target":4128},{"edgeType":"calls","source":1163,"target":366},{"edgeType":"contains","source":3056,"target":1140},{"edgeType":"calls","source":1195,"target":431},{"edgeType":"calls","source":5418,"target":588},{"edgeType":"calls","source":3271,"target":551},{"edgeType":"calls","source":1093,"target":422},{"edgeType":"calls","source":3311,"target":368},{"edgeType":"contains","source":750,"target":751},{"edgeType":"contains","source":5241,"target":5284},{"edgeType":"calls","source":2827,"target":573},{"edgeType":"calls","source":5018,"target":303},{"edgeType":"calls","source":2795,"target":508},{"edgeType":"calls","source":4740,"target":465},{"edgeType":"contains","source":4691,"target":5421},{"edgeType":"contains","source":4671,"target":4984},{"edgeType":"contains","source":4668,"target":5077},{"edgeType":"calls","source":5018,"target":304},{"edgeType":"calls","source":7063,"target":303},{"edgeType":"contains","source":6557,"target":6774},{"edgeType":"contains","source":6530,"target":6554},{"edgeType":"calls","source":972,"target":1002},{"edgeType":"calls","source":1419,"target":886},{"edgeType":"calls","source":3311,"target":369},{"edgeType":"calls","source":1234,"target":1335},{"edgeType":"calls","source":1093,"target":421},{"edgeType":"calls","source":2795,"target":509},{"edgeType":"contains","source":5241,"target":5283},{"edgeType":"calls","source":4682,"target":148},{"edgeType":"calls","source":4740,"target":464},{"edgeType":"extends","source":2051,"target":36},{"edgeType":"contains","source":4671,"target":4983},{"edgeType":"contains","source":4668,"target":5076},{"edgeType":"calls","source":6929,"target":6572},{"edgeType":"calls","source":7063,"target":304},{"edgeType":"contains","source":2764,"target":2793},{"edgeType":"contains","source":6557,"target":6775},{"edgeType":"calls","source":5330,"target":144},{"edgeType":"contains","source":6032,"target":6138},{"edgeType":"calls","source":3683,"target":3635},{"edgeType":"contains","source":2330,"target":2506},{"edgeType":"imports","source":6476,"target":49},{"edgeType":"contains","source":1476,"target":1502},{"edgeType":"calls","source":3311,"target":366},{"edgeType":"calls","source":749,"target":509},{"edgeType":"contains","source":5166,"target":2330},{"edgeType":"contains","source":4691,"target":5428},{"edgeType":"contains","source":2764,"target":2799},{"edgeType":"calls","source":2795,"target":506},{"edgeType":"calls","source":4740,"target":463},{"edgeType":"calls","source":5119,"target":342},{"edgeType":"contains","source":6166,"target":6205},{"edgeType":"contains","source":3326,"target":3346},{"edgeType":"contains","source":2599,"target":3685},{"edgeType":"contains","source":2641,"target":1326},{"edgeType":"calls","source":3720,"target":371},{"edgeType":"calls","source":3295,"target":2977},{"edgeType":"calls","source":6688,"target":303},{"edgeType":"contains","source":1302,"target":3726},{"edgeType":"contains","source":1476,"target":1503},{"edgeType":"calls","source":2789,"target":2807},{"edgeType":"calls","source":749,"target":508},{"edgeType":"contains","source":2599,"target":3687},{"edgeType":"contains","source":4691,"target":5427},{"edgeType":"calls","source":4740,"target":462},{"edgeType":"calls","source":2827,"target":572},{"edgeType":"calls","source":912,"target":740},{"edgeType":"imports","source":1379,"target":547},{"edgeType":"calls","source":2795,"target":507},{"edgeType":"calls","source":6889,"target":6757},{"edgeType":"calls","source":4982,"target":4588},{"edgeType":"contains","source":6032,"target":6132},{"edgeType":"contains","source":4691,"target":5426},{"edgeType":"contains","source":2599,"target":3686},{"edgeType":"calls","source":6833,"target":2151},{"edgeType":"calls","source":3625,"target":146},{"edgeType":"imports","source":130,"target":157},{"edgeType":"calls","source":2795,"target":504},{"edgeType":"calls","source":6688,"target":304},{"edgeType":"calls","source":3311,"target":364},{"edgeType":"calls","source":2626,"target":458},{"edgeType":"calls","source":4777,"target":371},{"edgeType":"contains","source":3241,"target":3865},{"edgeType":"calls","source":6895,"target":6572},{"edgeType":"calls","source":2533,"target":170},{"edgeType":"contains","source":2599,"target":3683},{"edgeType":"calls","source":6129,"target":1797},{"edgeType":"calls","source":3720,"target":369},{"edgeType":"contains","source":2330,"target":2509},{"edgeType":"contains","source":1476,"target":1501},{"edgeType":"calls","source":1207,"target":1111},{"edgeType":"calls","source":2533,"target":171},{"edgeType":"calls","source":4777,"target":370},{"edgeType":"calls","source":2795,"target":505},{"edgeType":"calls","source":2823,"target":2808},{"edgeType":"contains","source":4691,"target":5424},{"edgeType":"contains","source":4671,"target":4987},{"edgeType":"contains","source":2599,"target":3684},{"edgeType":"calls","source":3884,"target":571},{"edgeType":"calls","source":5865,"target":467},{"edgeType":"calls","source":3720,"target":370},{"edgeType":"calls","source":7109,"target":6281},{"edgeType":"calls","source":7136,"target":1216},{"edgeType":"calls","source":6690,"target":244},{"edgeType":"calls","source":2795,"target":502},{"edgeType":"contains","source":1476,"target":1506},{"edgeType":"contains","source":2070,"target":2119},{"edgeType":"imports","source":5895,"target":78},{"edgeType":"calls","source":749,"target":505},{"edgeType":"calls","source":3348,"target":3443},{"edgeType":"contains","source":2599,"target":3690},{"edgeType":"calls","source":4777,"target":369},{"edgeType":"contains","source":4579,"target":4676},{"edgeType":"contains","source":4691,"target":5432},{"edgeType":"extends","source":5754,"target":5756},{"edgeType":"contains","source":3057,"target":3233},{"edgeType":"contains","source":3241,"target":3871},{"edgeType":"contains","source":3624,"target":3627},{"edgeType":"contains","source":5671,"target":5707},{"edgeType":"contains","source":5686,"target":6299},{"edgeType":"calls","source":2261,"target":2258},{"edgeType":"calls","source":5865,"target":466},{"edgeType":"calls","source":6816,"target":567},{"edgeType":"contains","source":3558,"target":3559},{"edgeType":"calls","source":6995,"target":303},{"edgeType":"calls","source":2795,"target":503},{"edgeType":"contains","source":4119,"target":4136},{"edgeType":"calls","source":749,"target":504},{"edgeType":"calls","source":1226,"target":516},{"edgeType":"contains","source":585,"target":586},{"edgeType":"calls","source":2626,"target":457},{"edgeType":"calls","source":4777,"target":368},{"edgeType":"extends","source":6450,"target":36},{"edgeType":"contains","source":2599,"target":3691},{"edgeType":"calls","source":5127,"target":1145},{"edgeType":"contains","source":4691,"target":5431},{"edgeType":"calls","source":1136,"target":1192},{"edgeType":"contains","source":4579,"target":4674},{"edgeType":"contains","source":3057,"target":3234},{"edgeType":"calls","source":4404,"target":304},{"edgeType":"calls","source":5788,"target":1795},{"edgeType":"calls","source":7135,"target":1249},{"edgeType":"calls","source":2183,"target":449},{"edgeType":"calls","source":5865,"target":465},{"edgeType":"contains","source":5686,"target":6300},{"edgeType":"calls","source":3720,"target":368},{"edgeType":"calls","source":2066,"target":1962},{"edgeType":"calls","source":6995,"target":304},{"edgeType":"calls","source":7025,"target":431},{"edgeType":"contains","source":1476,"target":1504},{"edgeType":"imports","source":130,"target":166},{"edgeType":"calls","source":6591,"target":144},{"edgeType":"contains","source":4691,"target":5430},{"edgeType":"calls","source":5386,"target":4743},{"edgeType":"calls","source":749,"target":507},{"edgeType":"contains","source":2599,"target":3688},{"edgeType":"calls","source":968,"target":1117},{"edgeType":"contains","source":4579,"target":4673},{"edgeType":"calls","source":1534,"target":1541},{"edgeType":"contains","source":2330,"target":2513},{"edgeType":"calls","source":7135,"target":1250},{"edgeType":"calls","source":5865,"target":464},{"edgeType":"contains","source":3624,"target":3625},{"edgeType":"calls","source":2293,"target":2321},{"edgeType":"calls","source":6757,"target":284},{"edgeType":"calls","source":4404,"target":303},{"edgeType":"contains","source":5686,"target":6301},{"edgeType":"calls","source":6888,"target":6793},{"edgeType":"contains","source":1476,"target":1505},{"edgeType":"imports","source":3781,"target":78},{"edgeType":"calls","source":6346,"target":3522},{"edgeType":"calls","source":749,"target":506},{"edgeType":"calls","source":576,"target":584},{"edgeType":"imports","source":5895,"target":79},{"edgeType":"imports","source":130,"target":167},{"edgeType":"contains","source":2599,"target":3689},{"edgeType":"contains","source":4691,"target":5429},{"edgeType":"calls","source":1074,"target":1002},{"edgeType":"contains","source":2898,"target":2876},{"edgeType":"contains","source":2764,"target":2802},{"edgeType":"contains","source":6604,"target":3213},{"edgeType":"contains","source":5705,"target":5713},{"edgeType":"extends","source":6075,"target":36},{"edgeType":"contains","source":2330,"target":2514},{"edgeType":"calls","source":4777,"target":366},{"edgeType":"calls","source":4750,"target":146},{"edgeType":"calls","source":5865,"target":463},{"edgeType":"calls","source":3720,"target":366},{"edgeType":"calls","source":2261,"target":2257},{"edgeType":"calls","source":6690,"target":248},{"edgeType":"imports","source":3781,"target":79},{"edgeType":"calls","source":6482,"target":354},{"edgeType":"contains","source":23,"target":43},{"edgeType":"calls","source":5865,"target":462},{"edgeType":"extends","source":2597,"target":36},{"edgeType":"calls","source":1708,"target":369},{"edgeType":"imports","source":3030,"target":1170},{"edgeType":"calls","source":1226,"target":513},{"edgeType":"calls","source":5432,"target":144},{"edgeType":"contains","source":2599,"target":3694},{"edgeType":"calls","source":6937,"target":1048},{"edgeType":"calls","source":2601,"target":170},{"edgeType":"calls","source":510,"target":511},{"edgeType":"calls","source":6806,"target":1938},{"edgeType":"contains","source":5705,"target":5706},{"edgeType":"calls","source":2329,"target":146},{"edgeType":"calls","source":4914,"target":4573},{"edgeType":"imports","source":2315,"target":79},{"edgeType":"calls","source":3720,"target":364},{"edgeType":"contains","source":3,"target":3833},{"edgeType":"calls","source":5470,"target":2136},{"edgeType":"contains","source":453,"target":454},{"edgeType":"calls","source":1666,"target":1670},{"edgeType":"calls","source":1708,"target":368},{"edgeType":"contains","source":2203,"target":2229},{"edgeType":"calls","source":1234,"target":1321},{"edgeType":"contains","source":2468,"target":2471},{"edgeType":"calls","source":1414,"target":1026},{"edgeType":"calls","source":2601,"target":171},{"edgeType":"calls","source":4777,"target":364},{"edgeType":"extends","source":5393,"target":36},{"edgeType":"contains","source":1302,"target":3735},{"edgeType":"calls","source":6541,"target":2755},{"edgeType":"calls","source":6712,"target":4853},{"edgeType":"calls","source":4433,"target":458},{"edgeType":"calls","source":6544,"target":548},{"edgeType":"calls","source":4241,"target":4294},{"edgeType":"imports","source":4528,"target":179},{"edgeType":"imports","source":2315,"target":78},{"edgeType":"calls","source":2988,"target":2969},{"edgeType":"calls","source":749,"target":503},{"edgeType":"calls","source":1274,"target":84},{"edgeType":"imports","source":1303,"target":1853},{"edgeType":"contains","source":3,"target":3836},{"edgeType":"calls","source":1226,"target":515},{"edgeType":"imports","source":952,"target":49},{"edgeType":"contains","source":2599,"target":3692},{"edgeType":"calls","source":6753,"target":6754},{"edgeType":"calls","source":6927,"target":303},{"edgeType":"calls","source":6932,"target":148},{"edgeType":"calls","source":1708,"target":371},{"edgeType":"calls","source":5868,"target":5652},{"edgeType":"contains","source":3057,"target":3235},{"edgeType":"calls","source":6819,"target":6822},{"edgeType":"contains","source":3624,"target":3629},{"edgeType":"calls","source":4433,"target":457},{"edgeType":"calls","source":213,"target":207},{"edgeType":"calls","source":749,"target":502},{"edgeType":"calls","source":2096,"target":2082},{"edgeType":"calls","source":4885,"target":4413},{"edgeType":"calls","source":2988,"target":2970},{"edgeType":"contains","source":2599,"target":3693},{"edgeType":"contains","source":4691,"target":5433},{"edgeType":"calls","source":1226,"target":514},{"edgeType":"contains","source":6630,"target":6631},{"edgeType":"calls","source":6927,"target":304},{"edgeType":"calls","source":2558,"target":2559},{"edgeType":"calls","source":1708,"target":370},{"edgeType":"imports","source":6824,"target":1938},{"edgeType":"contains","source":3954,"target":3968},{"edgeType":"calls","source":4872,"target":588},{"edgeType":"calls","source":6281,"target":4475},{"edgeType":"imports","source":6213,"target":1853},{"edgeType":"contains","source":4671,"target":4970},{"edgeType":"calls","source":6277,"target":5755},{"edgeType":"contains","source":3975,"target":4348},{"edgeType":"calls","source":971,"target":56},{"edgeType":"contains","source":3808,"target":4240},{"edgeType":"contains","source":2068,"target":2156},{"edgeType":"calls","source":3554,"target":319},{"edgeType":"calls","source":1242,"target":1169},{"edgeType":"calls","source":7068,"target":6603},{"edgeType":"imports","source":6286,"target":5720},{"edgeType":"contains","source":6166,"target":6192},{"edgeType":"contains","source":4350,"target":4351},{"edgeType":"contains","source":885,"target":1832},{"edgeType":"calls","source":1991,"target":147},{"edgeType":"calls","source":2735,"target":339},{"edgeType":"calls","source":546,"target":547},{"edgeType":"calls","source":6423,"target":171},{"edgeType":"contains","source":3326,"target":3327},{"edgeType":"calls","source":1262,"target":548},{"edgeType":"contains","source":6166,"target":6193},{"edgeType":"calls","source":3348,"target":364},{"edgeType":"calls","source":6591,"target":6593},{"edgeType":"calls","source":4076,"target":4221},{"edgeType":"calls","source":4098,"target":368},{"edgeType":"calls","source":213,"target":299},{"edgeType":"calls","source":6423,"target":170},{"edgeType":"contains","source":4668,"target":5061},{"edgeType":"contains","source":3975,"target":4346},{"edgeType":"contains","source":6557,"target":6758},{"edgeType":"extends","source":4806,"target":36},{"edgeType":"contains","source":4378,"target":4537},{"edgeType":"calls","source":2604,"target":170},{"edgeType":"extends","source":5878,"target":1691},{"edgeType":"contains","source":184,"target":310},{"edgeType":"imports","source":6604,"target":2207},{"edgeType":"calls","source":1818,"target":1284},{"edgeType":"calls","source":5893,"target":6029},{"edgeType":"calls","source":6584,"target":469},{"edgeType":"calls","source":2735,"target":337},{"edgeType":"contains","source":4668,"target":5060},{"edgeType":"contains","source":2599,"target":2607},{"edgeType":"calls","source":7068,"target":6606},{"edgeType":"contains","source":6166,"target":6195},{"edgeType":"calls","source":3554,"target":318},{"edgeType":"calls","source":2604,"target":171},{"edgeType":"calls","source":4098,"target":366},{"edgeType":"calls","source":4107,"target":1144},{"edgeType":"calls","source":6492,"target":6493},{"edgeType":"calls","source":213,"target":301},{"edgeType":"contains","source":1031,"target":1535},{"edgeType":"contains","source":5232,"target":5545},{"edgeType":"calls","source":580,"target":551},{"edgeType":"calls","source":2735,"target":338},{"edgeType":"calls","source":144,"target":326},{"edgeType":"calls","source":4546,"target":4447},{"edgeType":"contains","source":4579,"target":4655},{"edgeType":"contains","source":5166,"target":6542},{"edgeType":"calls","source":4448,"target":84},{"edgeType":"contains","source":6166,"target":6188},{"edgeType":"calls","source":1360,"target":678},{"edgeType":"calls","source":6959,"target":473},{"edgeType":"calls","source":1702,"target":1703},{"edgeType":"extends","source":4397,"target":36},{"edgeType":"calls","source":2084,"target":431},{"edgeType":"extends","source":1076,"target":453},{"edgeType":"contains","source":4378,"target":4544},{"edgeType":"calls","source":347,"target":370},{"edgeType":"imports","source":6824,"target":2787},{"edgeType":"contains","source":6166,"target":6189},{"edgeType":"calls","source":2984,"target":3187},{"edgeType":"contains","source":2599,"target":3670},{"edgeType":"calls","source":143,"target":350},{"edgeType":"calls","source":347,"target":368},{"edgeType":"calls","source":2099,"target":2082},{"edgeType":"calls","source":7000,"target":6602},{"edgeType":"calls","source":6959,"target":474},{"edgeType":"contains","source":3981,"target":4165},{"edgeType":"calls","source":1801,"target":1804},{"edgeType":"calls","source":7063,"target":421},{"edgeType":"calls","source":2012,"target":548},{"edgeType":"contains","source":2203,"target":2205},{"edgeType":"calls","source":4098,"target":364},{"edgeType":"calls","source":347,"target":369},{"edgeType":"calls","source":6210,"target":5712},{"edgeType":"calls","source":744,"target":746},{"edgeType":"imports","source":130,"target":996},{"edgeType":"contains","source":4668,"target":5065},{"edgeType":"calls","source":6597,"target":6412},{"edgeType":"calls","source":3554,"target":313},{"edgeType":"calls","source":3518,"target":372},{"edgeType":"contains","source":6166,"target":6190},{"edgeType":"calls","source":6959,"target":475},{"edgeType":"calls","source":7063,"target":422},{"edgeType":"calls","source":1311,"target":84},{"edgeType":"calls","source":6587,"target":380},{"edgeType":"calls","source":2968,"target":509},{"edgeType":"imports","source":1907,"target":1933},{"edgeType":"contains","source":1245,"target":1246},{"edgeType":"calls","source":2735,"target":333},{"edgeType":"contains","source":6032,"target":6117},{"edgeType":"contains","source":4668,"target":5064},{"edgeType":"contains","source":6557,"target":6755},{"edgeType":"contains","source":6166,"target":6191},{"edgeType":"calls","source":6587,"target":381},{"edgeType":"contains","source":4378,"target":4541},{"edgeType":"calls","source":347,"target":371},{"edgeType":"contains","source":1245,"target":1247},{"edgeType":"contains","source":1031,"target":1539},{"edgeType":"contains","source":6032,"target":6126},{"edgeType":"contains","source":184,"target":317},{"edgeType":"contains","source":3975,"target":4356},{"edgeType":"calls","source":5893,"target":1795},{"edgeType":"imports","source":2206,"target":78},{"edgeType":"calls","source":6587,"target":382},{"edgeType":"calls","source":1263,"target":509},{"edgeType":"calls","source":484,"target":347},{"edgeType":"contains","source":6166,"target":6201},{"edgeType":"contains","source":4671,"target":4978},{"edgeType":"contains","source":1031,"target":1542},{"edgeType":"calls","source":2968,"target":507},{"edgeType":"calls","source":347,"target":364},{"edgeType":"imports","source":2581,"target":79},{"edgeType":"calls","source":3554,"target":312},{"edgeType":"contains","source":184,"target":316},{"edgeType":"contains","source":1814,"target":2640},{"edgeType":"calls","source":1813,"target":371},{"edgeType":"calls","source":6807,"target":962},{"edgeType":"imports","source":5380,"target":1030},{"edgeType":"calls","source":2735,"target":332},{"edgeType":"calls","source":1319,"target":886},{"edgeType":"calls","source":4198,"target":431},{"edgeType":"calls","source":3244,"target":3579},{"edgeType":"calls","source":6994,"target":6793},{"edgeType":"calls","source":3554,"target":311},{"edgeType":"contains","source":4119,"target":4120},{"edgeType":"calls","source":1486,"target":994},{"edgeType":"calls","source":484,"target":346},{"edgeType":"contains","source":1245,"target":1253},{"edgeType":"contains","source":4671,"target":4977},{"edgeType":"imports","source":6286,"target":2540},{"edgeType":"calls","source":1263,"target":508},{"edgeType":"calls","source":4581,"target":4413},{"edgeType":"calls","source":2796,"target":555},{"edgeType":"calls","source":2968,"target":508},{"edgeType":"extends","source":1942,"target":36},{"edgeType":"contains","source":3326,"target":3332},{"edgeType":"imports","source":2581,"target":78},{"edgeType":"contains","source":5723,"target":4080},{"edgeType":"calls","source":6807,"target":963},{"edgeType":"contains","source":3975,"target":4354},{"edgeType":"calls","source":4104,"target":171},{"edgeType":"contains","source":6166,"target":6203},{"edgeType":"calls","source":6587,"target":384},{"edgeType":"calls","source":4202,"target":304},{"edgeType":"calls","source":7068,"target":3443},{"edgeType":"imports","source":4528,"target":2074},{"edgeType":"contains","source":6032,"target":6129},{"edgeType":"calls","source":2968,"target":505},{"edgeType":"calls","source":1008,"target":1017},{"edgeType":"calls","source":3204,"target":588},{"edgeType":"extends","source":5420,"target":36},{"edgeType":"calls","source":3120,"target":2136},{"edgeType":"contains","source":5209,"target":5210},{"edgeType":"contains","source":1031,"target":1544},{"edgeType":"calls","source":347,"target":366},{"edgeType":"contains","source":2068,"target":2163},{"edgeType":"contains","source":23,"target":24},{"edgeType":"calls","source":6194,"target":6202},{"edgeType":"contains","source":6166,"target":6204},{"edgeType":"calls","source":6933,"target":6572},{"edgeType":"contains","source":4668,"target":5068},{"edgeType":"contains","source":6557,"target":6767},{"edgeType":"calls","source":2968,"target":506},{"edgeType":"extends","source":3954,"target":36},{"edgeType":"calls","source":1813,"target":368},{"edgeType":"calls","source":1800,"target":1828},{"edgeType":"contains","source":3056,"target":1138},{"edgeType":"contains","source":5241,"target":5282},{"edgeType":"contains","source":6166,"target":6196},{"edgeType":"contains","source":4115,"target":4249},{"edgeType":"contains","source":20,"target":120},{"edgeType":"contains","source":2068,"target":2169},{"edgeType":"calls","source":1263,"target":505},{"edgeType":"calls","source":4615,"target":4413},{"edgeType":"calls","source":2891,"target":2890},{"edgeType":"calls","source":2968,"target":503},{"edgeType":"calls","source":942,"target":943},{"edgeType":"calls","source":1353,"target":886},{"edgeType":"calls","source":1129,"target":431},{"edgeType":"contains","source":3056,"target":1139},{"edgeType":"contains","source":6166,"target":6197},{"edgeType":"contains","source":5241,"target":5281},{"edgeType":"calls","source":2148,"target":555},{"edgeType":"calls","source":4104,"target":170},{"edgeType":"calls","source":4202,"target":303},{"edgeType":"calls","source":6287,"target":146},{"edgeType":"calls","source":3554,"target":307},{"edgeType":"imports","source":4528,"target":2077},{"edgeType":"imports","source":3013,"target":3595},{"edgeType":"calls","source":4848,"target":4588},{"edgeType":"contains","source":6166,"target":6198},{"edgeType":"calls","source":1657,"target":974},{"edgeType":"calls","source":2968,"target":504},{"edgeType":"calls","source":1132,"target":1394},{"edgeType":"contains","source":4671,"target":4981},{"edgeType":"calls","source":1263,"target":504},{"edgeType":"calls","source":3925,"target":431},{"edgeType":"calls","source":1813,"target":370},{"edgeType":"contains","source":5241,"target":5280},{"edgeType":"contains","source":3029,"target":3030},{"edgeType":"contains","source":3056,"target":1136},{"edgeType":"contains","source":5209,"target":5215},{"edgeType":"contains","source":4119,"target":4123},{"edgeType":"imports","source":3013,"target":3594},{"edgeType":"calls","source":5642,"target":56},{"edgeType":"contains","source":6166,"target":6199},{"edgeType":"calls","source":2838,"target":303},{"edgeType":"calls","source":1263,"target":507},{"edgeType":"calls","source":3023,"target":3024},{"edgeType":"calls","source":4672,"target":528},{"edgeType":"calls","source":1813,"target":369},{"edgeType":"calls","source":1800,"target":1829},{"edgeType":"calls","source":4642,"target":4629},{"edgeType":"calls","source":4576,"target":333},{"edgeType":"calls","source":2838,"target":304},{"edgeType":"contains","source":20,"target":121},{"edgeType":"contains","source":6166,"target":6200},{"edgeType":"calls","source":1263,"target":506},{"edgeType":"calls","source":1243,"target":1126},{"edgeType":"calls","source":2891,"target":2889},{"edgeType":"calls","source":2968,"target":502},{"edgeType":"calls","source":942,"target":944},{"edgeType":"contains","source":4671,"target":4979},{"edgeType":"calls","source":4595,"target":4004},{"edgeType":"calls","source":3123,"target":3126},{"edgeType":"contains","source":182,"target":354},{"edgeType":"calls","source":4610,"target":368},{"edgeType":"calls","source":1108,"target":1111},{"edgeType":"contains","source":2863,"target":2864},{"edgeType":"calls","source":3896,"target":304},{"edgeType":"calls","source":4536,"target":548},{"edgeType":"extends","source":1498,"target":36},{"edgeType":"calls","source":2899,"target":557},{"edgeType":"calls","source":2130,"target":84},{"edgeType":"calls","source":7032,"target":304},{"edgeType":"calls","source":5801,"target":443},{"edgeType":"calls","source":1602,"target":1652},{"edgeType":"contains","source":6166,"target":6176},{"edgeType":"calls","source":1882,"target":371},{"edgeType":"calls","source":3850,"target":3845},{"edgeType":"extends","source":4635,"target":36},{"edgeType":"calls","source":4855,"target":171},{"edgeType":"imports","source":5285,"target":1853},{"edgeType":"calls","source":2329,"target":2372},{"edgeType":"calls","source":5020,"target":342},{"edgeType":"calls","source":2899,"target":558},{"edgeType":"calls","source":6863,"target":6601},{"edgeType":"calls","source":2787,"target":1916},{"edgeType":"calls","source":5138,"target":5140},{"edgeType":"contains","source":6166,"target":6177},{"edgeType":"calls","source":1009,"target":1011},{"edgeType":"calls","source":3232,"target":1859},{"edgeType":"calls","source":3123,"target":3124},{"edgeType":"calls","source":6657,"target":303},{"edgeType":"imports","source":1907,"target":1920},{"edgeType":"calls","source":4751,"target":4451},{"edgeType":"calls","source":4855,"target":170},{"edgeType":"calls","source":2595,"target":2579},{"edgeType":"calls","source":4610,"target":366},{"edgeType":"imports","source":5616,"target":49},{"edgeType":"contains","source":4668,"target":5044},{"edgeType":"contains","source":4115,"target":4218},{"edgeType":"contains","source":6651,"target":6998},{"edgeType":"calls","source":4953,"target":304},{"edgeType":"calls","source":6728,"target":6559},{"edgeType":"calls","source":3103,"target":573},{"edgeType":"contains","source":6166,"target":6178},{"edgeType":"calls","source":3518,"target":2506},{"edgeType":"contains","source":153,"target":198},{"edgeType":"contains","source":6032,"target":6104},{"edgeType":"calls","source":1009,"target":1010},{"edgeType":"calls","source":6657,"target":304},{"edgeType":"calls","source":3896,"target":303},{"edgeType":"contains","source":5604,"target":5631},{"edgeType":"calls","source":4956,"target":209},{"edgeType":"imports","source":1907,"target":1919},{"edgeType":"calls","source":6863,"target":6603},{"edgeType":"contains","source":2872,"target":469},{"edgeType":"extends","source":2212,"target":2213},{"edgeType":"calls","source":4958,"target":148},{"edgeType":"calls","source":4953,"target":303},{"edgeType":"calls","source":4956,"target":210},{"edgeType":"calls","source":2899,"target":556},{"edgeType":"calls","source":5642,"target":84},{"edgeType":"contains","source":6166,"target":6179},{"edgeType":"calls","source":6756,"target":6749},{"edgeType":"calls","source":1572,"target":469},{"edgeType":"calls","source":3550,"target":1515},{"edgeType":"calls","source":7020,"target":7021},{"edgeType":"imports","source":6604,"target":78},{"edgeType":"calls","source":1882,"target":368},{"edgeType":"calls","source":3219,"target":146},{"edgeType":"calls","source":1168,"target":304},{"edgeType":"contains","source":1031,"target":1522},{"edgeType":"contains","source":5604,"target":5624},{"edgeType":"calls","source":2878,"target":146},{"edgeType":"calls","source":4915,"target":422},{"edgeType":"calls","source":4610,"target":364},{"edgeType":"contains","source":1186,"target":945},{"edgeType":"calls","source":895,"target":311},{"edgeType":"contains","source":6166,"target":6172},{"edgeType":"calls","source":2899,"target":553},{"edgeType":"imports","source":2206,"target":49},{"edgeType":"calls","source":1750,"target":1288},{"edgeType":"calls","source":5222,"target":4647},{"edgeType":"calls","source":6872,"target":1040},{"edgeType":"contains","source":3,"target":3793},{"edgeType":"calls","source":6716,"target":591},{"edgeType":"calls","source":1168,"target":303},{"edgeType":"calls","source":6551,"target":421},{"edgeType":"calls","source":4915,"target":421},{"edgeType":"calls","source":4646,"target":304},{"edgeType":"contains","source":6166,"target":6173},{"edgeType":"contains","source":4691,"target":5393},{"edgeType":"calls","source":3103,"target":572},{"edgeType":"calls","source":7020,"target":7023},{"edgeType":"calls","source":6030,"target":1795},{"edgeType":"calls","source":6682,"target":4817},{"edgeType":"imports","source":3030,"target":3043},{"edgeType":"calls","source":1718,"target":165},{"edgeType":"calls","source":1882,"target":366},{"edgeType":"calls","source":1750,"target":1287},{"edgeType":"calls","source":1758,"target":1039},{"edgeType":"calls","source":3619,"target":431},{"edgeType":"calls","source":2667,"target":1400},{"edgeType":"imports","source":2581,"target":49},{"edgeType":"calls","source":1882,"target":370},{"edgeType":"contains","source":153,"target":202},{"edgeType":"calls","source":4263,"target":548},{"edgeType":"calls","source":6551,"target":422},{"edgeType":"calls","source":3219,"target":2258},{"edgeType":"calls","source":2832,"target":1570},{"edgeType":"calls","source":4646,"target":303},{"edgeType":"contains","source":2797,"target":2798},{"edgeType":"imports","source":1907,"target":1916},{"edgeType":"contains","source":885,"target":1822},{"edgeType":"contains","source":5232,"target":5534},{"edgeType":"calls","source":895,"target":313},{"edgeType":"contains","source":6651,"target":6994},{"edgeType":"contains","source":6557,"target":6737},{"edgeType":"calls","source":3866,"target":170},{"edgeType":"contains","source":6166,"target":6174},{"edgeType":"calls","source":6863,"target":6606},{"edgeType":"calls","source":6940,"target":1048},{"edgeType":"calls","source":6994,"target":431},{"edgeType":"calls","source":1882,"target":369},{"edgeType":"calls","source":3916,"target":3907},{"edgeType":"imports","source":6604,"target":79},{"edgeType":"calls","source":5400,"target":183},{"edgeType":"calls","source":1041,"target":1071},{"edgeType":"contains","source":2764,"target":2765},{"edgeType":"calls","source":4951,"target":4588},{"edgeType":"imports","source":1907,"target":1915},{"edgeType":"calls","source":2264,"target":2267},{"edgeType":"calls","source":895,"target":312},{"edgeType":"calls","source":2198,"target":2199},{"edgeType":"calls","source":3560,"target":144},{"edgeType":"calls","source":1750,"target":1289},{"edgeType":"imports","source":3819,"target":1853},{"edgeType":"calls","source":1808,"target":548},{"edgeType":"contains","source":6557,"target":6738},{"edgeType":"contains","source":6166,"target":6175},{"edgeType":"contains","source":6165,"target":6206},{"edgeType":"calls","source":3866,"target":171},{"edgeType":"contains","source":2206,"target":1036},{"edgeType":"calls","source":6243,"target":475},{"edgeType":"calls","source":6609,"target":1797},{"edgeType":"calls","source":3348,"target":371},{"edgeType":"calls","source":3512,"target":572},{"edgeType":"contains","source":6166,"target":6184},{"edgeType":"contains","source":2688,"target":898},{"edgeType":"contains","source":2599,"target":2600},{"edgeType":"contains","source":4691,"target":5399},{"edgeType":"imports","source":6530,"target":4474},{"edgeType":"imports","source":2070,"target":49},{"edgeType":"calls","source":1817,"target":1321},{"edgeType":"contains","source":6032,"target":6110},{"edgeType":"contains","source":1641,"target":1644},{"edgeType":"calls","source":144,"target":333},{"edgeType":"calls","source":1750,"target":1284},{"edgeType":"calls","source":1738,"target":1656},{"edgeType":"calls","source":6930,"target":303},{"edgeType":"calls","source":3926,"target":422},{"edgeType":"calls","source":6856,"target":483},{"edgeType":"contains","source":153,"target":203},{"edgeType":"calls","source":6243,"target":474},{"edgeType":"calls","source":6597,"target":56},{"edgeType":"calls","source":1439,"target":354},{"edgeType":"calls","source":3512,"target":573},{"edgeType":"calls","source":3219,"target":2257},{"edgeType":"contains","source":6166,"target":6185},{"edgeType":"contains","source":1031,"target":1525},{"edgeType":"calls","source":2795,"target":1659},{"edgeType":"calls","source":6930,"target":304},{"edgeType":"calls","source":1876,"target":548},{"edgeType":"calls","source":144,"target":332},{"edgeType":"calls","source":1818,"target":1289},{"edgeType":"calls","source":152,"target":84},{"edgeType":"contains","source":1641,"target":1645},{"edgeType":"calls","source":6716,"target":596},{"edgeType":"extends","source":4192,"target":36},{"edgeType":"contains","source":6166,"target":6186},{"edgeType":"calls","source":6243,"target":473},{"edgeType":"calls","source":3566,"target":1010},{"edgeType":"calls","source":3348,"target":369},{"edgeType":"contains","source":3166,"target":1933},{"edgeType":"calls","source":4953,"target":1352},{"edgeType":"contains","source":6459,"target":6616},{"edgeType":"calls","source":5220,"target":475},{"edgeType":"contains","source":1641,"target":1642},{"edgeType":"calls","source":1718,"target":164},{"edgeType":"calls","source":1750,"target":1286},{"edgeType":"calls","source":6115,"target":212},{"edgeType":"contains","source":3808,"target":4230},{"edgeType":"calls","source":4050,"target":3977},{"edgeType":"contains","source":6166,"target":6187},{"edgeType":"calls","source":4194,"target":570},{"edgeType":"calls","source":3348,"target":370},{"edgeType":"contains","source":3014,"target":3475},{"edgeType":"imports","source":1379,"target":1383},{"edgeType":"calls","source":5220,"target":473},{"edgeType":"contains","source":6557,"target":6751},{"edgeType":"calls","source":895,"target":307},{"edgeType":"calls","source":6896,"target":303},{"edgeType":"calls","source":2999,"target":2733},{"edgeType":"calls","source":5220,"target":474},{"edgeType":"calls","source":6955,"target":588},{"edgeType":"calls","source":6756,"target":6757},{"edgeType":"contains","source":2581,"target":3156},{"edgeType":"calls","source":3628,"target":146},{"edgeType":"contains","source":1641,"target":1643},{"edgeType":"calls","source":3926,"target":421},{"edgeType":"calls","source":1750,"target":1285},{"edgeType":"calls","source":1882,"target":364},{"edgeType":"contains","source":3,"target":2744},{"edgeType":"extends","source":1420,"target":1409},{"edgeType":"calls","source":1241,"target":147},{"edgeType":"calls","source":1582,"target":146},{"edgeType":"contains","source":4668,"target":5059},{"edgeType":"contains","source":2581,"target":3162},{"edgeType":"calls","source":4444,"target":4445},{"edgeType":"calls","source":6896,"target":304},{"edgeType":"calls","source":1818,"target":1286},{"edgeType":"contains","source":1509,"target":1512},{"edgeType":"calls","source":4098,"target":371},{"edgeType":"contains","source":6166,"target":6180},{"edgeType":"calls","source":6602,"target":962},{"edgeType":"calls","source":6132,"target":1797},{"edgeType":"contains","source":2068,"target":2153},{"edgeType":"extends","source":5054,"target":5029},{"edgeType":"calls","source":3348,"target":368},{"edgeType":"contains","source":4668,"target":5058},{"edgeType":"contains","source":2686,"target":965},{"edgeType":"contains","source":6824,"target":6924},{"edgeType":"calls","source":1241,"target":146},{"edgeType":"imports","source":1907,"target":1926},{"edgeType":"calls","source":6690,"target":6691},{"edgeType":"calls","source":1818,"target":1285},{"edgeType":"contains","source":6166,"target":6181},{"edgeType":"contains","source":3241,"target":3843},{"edgeType":"calls","source":6602,"target":963},{"edgeType":"calls","source":7068,"target":6601},{"edgeType":"contains","source":6166,"target":6182},{"edgeType":"contains","source":2201,"target":2255},{"edgeType":"contains","source":4668,"target":5057},{"edgeType":"calls","source":4510,"target":4511},{"edgeType":"contains","source":6651,"target":7002},{"edgeType":"extends","source":6988,"target":36},{"edgeType":"calls","source":6690,"target":6692},{"edgeType":"calls","source":6863,"target":3443},{"edgeType":"calls","source":2265,"target":2227},{"edgeType":"calls","source":4098,"target":369},{"edgeType":"calls","source":1818,"target":1288},{"edgeType":"contains","source":1641,"target":1646},{"edgeType":"contains","source":5671,"target":5672},{"edgeType":"calls","source":6486,"target":332},{"edgeType":"contains","source":6166,"target":6183},{"edgeType":"calls","source":5600,"target":5602},{"edgeType":"calls","source":5791,"target":1795},{"edgeType":"calls","source":3348,"target":366},{"edgeType":"contains","source":4378,"target":4532},{"edgeType":"contains","source":2860,"target":2968},{"edgeType":"contains","source":4691,"target":5400},{"edgeType":"contains","source":2581,"target":3161},{"edgeType":"calls","source":6835,"target":84},{"edgeType":"calls","source":1818,"target":1287},{"edgeType":"calls","source":6940,"target":1057},{"edgeType":"calls","source":4098,"target":370},{"edgeType":"calls","source":525,"target":146},{"edgeType":"contains","source":1509,"target":1511},{"edgeType":"extends","source":2142,"target":167},{"edgeType":"calls","source":4415,"target":56},{"edgeType":"contains","source":3557,"target":3558},{"edgeType":"calls","source":6486,"target":333},{"edgeType":"contains","source":1641,"target":1647},{"edgeType":"calls","source":4939,"target":4918},{"edgeType":"calls","source":2962,"target":2782},{"edgeType":"contains","source":2761,"target":2838},{"edgeType":"calls","source":961,"target":333},{"edgeType":"contains","source":4839,"target":5014},{"edgeType":"contains","source":3847,"target":4055},{"edgeType":"calls","source":1311,"target":1111},{"edgeType":"contains","source":6557,"target":6723},{"edgeType":"contains","source":748,"target":761},{"edgeType":"calls","source":1750,"target":1243},{"edgeType":"calls","source":1274,"target":144},{"edgeType":"calls","source":6023,"target":911},{"edgeType":"calls","source":4781,"target":303},{"edgeType":"contains","source":1732,"target":1969},{"edgeType":"contains","source":5686,"target":6241},{"edgeType":"contains","source":1409,"target":1412},{"edgeType":"contains","source":4665,"target":5122},{"edgeType":"calls","source":961,"target":332},{"edgeType":"contains","source":3886,"target":3902},{"edgeType":"calls","source":1337,"target":304},{"edgeType":"contains","source":748,"target":760},{"edgeType":"extends","source":4432,"target":36},{"edgeType":"contains","source":4579,"target":4617},{"edgeType":"calls","source":4545,"target":4447},{"edgeType":"calls","source":5337,"target":2092},{"edgeType":"calls","source":5386,"target":573},{"edgeType":"calls","source":6095,"target":5020},{"edgeType":"calls","source":4070,"target":146},{"edgeType":"contains","source":1732,"target":1970},{"edgeType":"contains","source":3847,"target":4054},{"edgeType":"calls","source":6023,"target":910},{"edgeType":"contains","source":4665,"target":5121},{"edgeType":"calls","source":3034,"target":548},{"edgeType":"contains","source":6557,"target":6725},{"edgeType":"contains","source":748,"target":763},{"edgeType":"calls","source":5222,"target":4599},{"edgeType":"calls","source":1172,"target":1194},{"edgeType":"contains","source":4380,"target":4442},{"edgeType":"contains","source":41,"target":6824},{"edgeType":"calls","source":1172,"target":1193},{"edgeType":"calls","source":4642,"target":4610},{"edgeType":"contains","source":1732,"target":1967},{"edgeType":"calls","source":5337,"target":2091},{"edgeType":"calls","source":5386,"target":572},{"edgeType":"contains","source":3808,"target":4205},{"edgeType":"contains","source":3847,"target":4053},{"edgeType":"calls","source":592,"target":147},{"edgeType":"contains","source":1409,"target":1410},{"edgeType":"calls","source":6486,"target":303},{"edgeType":"calls","source":2626,"target":2626},{"edgeType":"calls","source":2592,"target":509},{"edgeType":"contains","source":4839,"target":5011},{"edgeType":"calls","source":5220,"target":1489},{"edgeType":"contains","source":6557,"target":6726},{"edgeType":"contains","source":748,"target":762},{"edgeType":"contains","source":4579,"target":4615},{"edgeType":"contains","source":5,"target":3711},{"edgeType":"calls","source":1602,"target":1604},{"edgeType":"calls","source":5797,"target":5800},{"edgeType":"calls","source":2527,"target":2525},{"edgeType":"calls","source":4642,"target":4609},{"edgeType":"contains","source":1732,"target":1968},{"edgeType":"contains","source":3808,"target":4204},{"edgeType":"calls","source":6486,"target":304},{"edgeType":"calls","source":2968,"target":2592},{"edgeType":"calls","source":1003,"target":84},{"edgeType":"calls","source":5220,"target":1488},{"edgeType":"calls","source":5220,"target":431},{"edgeType":"contains","source":1732,"target":1973},{"edgeType":"contains","source":4414,"target":4452},{"edgeType":"calls","source":1404,"target":338},{"edgeType":"contains","source":4000,"target":4601},{"edgeType":"calls","source":1778,"target":371},{"edgeType":"contains","source":2922,"target":3136},{"edgeType":"calls","source":2024,"target":144},{"edgeType":"calls","source":1404,"target":337},{"edgeType":"contains","source":748,"target":765},{"edgeType":"contains","source":1409,"target":1416},{"edgeType":"calls","source":2592,"target":507},{"edgeType":"calls","source":5093,"target":3310},{"edgeType":"calls","source":4508,"target":304},{"edgeType":"calls","source":4963,"target":5226},{"edgeType":"calls","source":3452,"target":3445},{"edgeType":"contains","source":6651,"target":6977},{"edgeType":"contains","source":3,"target":3775},{"edgeType":"imports","source":3981,"target":49},{"edgeType":"contains","source":4000,"target":4600},{"edgeType":"calls","source":1778,"target":370},{"edgeType":"calls","source":7139,"target":146},{"edgeType":"calls","source":3224,"target":2056},{"edgeType":"contains","source":4380,"target":4448},{"edgeType":"extends","source":920,"target":36},{"edgeType":"contains","source":748,"target":764},{"edgeType":"contains","source":4839,"target":5017},{"edgeType":"calls","source":1035,"target":148},{"edgeType":"calls","source":4672,"target":1563},{"edgeType":"calls","source":4477,"target":2323},{"edgeType":"calls","source":2592,"target":508},{"edgeType":"calls","source":4508,"target":303},{"edgeType":"contains","source":3952,"target":3973},{"edgeType":"contains","source":3808,"target":4209},{"edgeType":"contains","source":3847,"target":4057},{"edgeType":"calls","source":3452,"target":3442},{"edgeType":"calls","source":1337,"target":303},{"edgeType":"contains","source":19,"target":111},{"edgeType":"calls","source":3763,"target":2257},{"edgeType":"calls","source":3826,"target":304},{"edgeType":"calls","source":5573,"target":56},{"edgeType":"contains","source":132,"target":837},{"edgeType":"contains","source":154,"target":155},{"edgeType":"contains","source":2922,"target":3134},{"edgeType":"contains","source":748,"target":767},{"edgeType":"calls","source":6717,"target":1602},{"edgeType":"extends","source":3853,"target":1076},{"edgeType":"calls","source":3479,"target":1547},{"edgeType":"contains","source":1409,"target":1414},{"edgeType":"contains","source":4839,"target":5016},{"edgeType":"calls","source":2823,"target":2857},{"edgeType":"calls","source":2592,"target":505},{"edgeType":"calls","source":2626,"target":508},{"edgeType":"contains","source":3975,"target":4316},{"edgeType":"contains","source":2599,"target":3635},{"edgeType":"contains","source":4502,"target":4892},{"edgeType":"contains","source":3808,"target":4208},{"edgeType":"contains","source":3847,"target":4056},{"edgeType":"contains","source":19,"target":110},{"edgeType":"contains","source":6557,"target":6722},{"edgeType":"calls","source":1404,"target":339},{"edgeType":"contains","source":4414,"target":4449},{"edgeType":"calls","source":5863,"target":5864},{"edgeType":"calls","source":3763,"target":2258},{"edgeType":"contains","source":4349,"target":4350},{"edgeType":"contains","source":2922,"target":3135},{"edgeType":"calls","source":3479,"target":1548},{"edgeType":"contains","source":748,"target":766},{"edgeType":"calls","source":710,"target":712},{"edgeType":"calls","source":2592,"target":506},{"edgeType":"calls","source":2626,"target":509},{"edgeType":"extends","source":4671,"target":36},{"edgeType":"extends","source":2591,"target":36},{"edgeType":"contains","source":4000,"target":4605},{"edgeType":"calls","source":6115,"target":165},{"edgeType":"calls","source":1767,"target":1765},{"edgeType":"calls","source":6890,"target":469},{"edgeType":"calls","source":1812,"target":370},{"edgeType":"calls","source":5877,"target":144},{"edgeType":"contains","source":3808,"target":4215},{"edgeType":"calls","source":4209,"target":56},{"edgeType":"contains","source":748,"target":769},{"edgeType":"calls","source":6281,"target":304},{"edgeType":"calls","source":6573,"target":2897},{"edgeType":"contains","source":2068,"target":2132},{"edgeType":"contains","source":6166,"target":6168},{"edgeType":"calls","source":3479,"target":1545},{"edgeType":"calls","source":2592,"target":503},{"edgeType":"calls","source":2626,"target":506},{"edgeType":"calls","source":2833,"target":431},{"edgeType":"calls","source":5220,"target":1483},{"edgeType":"calls","source":5103,"target":5110},{"edgeType":"contains","source":6557,"target":6732},{"edgeType":"calls","source":3826,"target":303},{"edgeType":"calls","source":1778,"target":366},{"edgeType":"calls","source":1780,"target":304},{"edgeType":"calls","source":1812,"target":369},{"edgeType":"contains","source":4414,"target":4455},{"edgeType":"calls","source":4444,"target":4398},{"edgeType":"contains","source":4000,"target":4604},{"edgeType":"calls","source":6115,"target":164},{"edgeType":"contains","source":3808,"target":4214},{"edgeType":"contains","source":19,"target":112},{"edgeType":"calls","source":1412,"target":84},{"edgeType":"calls","source":6281,"target":303},{"edgeType":"contains","source":748,"target":768},{"edgeType":"contains","source":6166,"target":6169},{"edgeType":"calls","source":3479,"target":1546},{"edgeType":"calls","source":2592,"target":504},{"edgeType":"calls","source":2626,"target":507},{"edgeType":"calls","source":2999,"target":571},{"edgeType":"calls","source":1073,"target":1080},{"edgeType":"calls","source":5103,"target":5109},{"edgeType":"calls","source":2626,"target":503},{"edgeType":"contains","source":4414,"target":4454},{"edgeType":"contains","source":182,"target":348},{"edgeType":"contains","source":1732,"target":1975},{"edgeType":"calls","source":7028,"target":421},{"edgeType":"calls","source":1778,"target":369},{"edgeType":"contains","source":748,"target":771},{"edgeType":"contains","source":6166,"target":6170},{"edgeType":"contains","source":1409,"target":1418},{"edgeType":"calls","source":2626,"target":504},{"edgeType":"calls","source":2861,"target":2732},{"edgeType":"calls","source":2824,"target":2822},{"edgeType":"calls","source":3193,"target":1953},{"edgeType":"contains","source":2922,"target":3138},{"edgeType":"calls","source":3033,"target":571},{"edgeType":"contains","source":6557,"target":6733},{"edgeType":"calls","source":4606,"target":431},{"edgeType":"contains","source":5241,"target":5242},{"edgeType":"calls","source":4591,"target":1953},{"edgeType":"calls","source":1800,"target":1800},{"edgeType":"calls","source":7028,"target":422},{"edgeType":"calls","source":1778,"target":368},{"edgeType":"contains","source":1732,"target":1976},{"edgeType":"calls","source":6215,"target":2347},{"edgeType":"calls","source":2097,"target":2105},{"edgeType":"calls","source":1812,"target":371},{"edgeType":"contains","source":5604,"target":5623},{"edgeType":"contains","source":6166,"target":6171},{"edgeType":"contains","source":748,"target":770},{"edgeType":"contains","source":19,"target":115},{"edgeType":"calls","source":4917,"target":304},{"edgeType":"calls","source":2592,"target":502},{"edgeType":"calls","source":2626,"target":505},{"edgeType":"contains","source":5166,"target":5452},{"edgeType":"contains","source":4839,"target":5019},{"edgeType":"calls","source":5103,"target":5108},{"edgeType":"contains","source":2922,"target":3139},{"edgeType":"calls","source":1812,"target":366},{"edgeType":"calls","source":449,"target":337},{"edgeType":"calls","source":1006,"target":1040},{"edgeType":"calls","source":6215,"target":2346},{"edgeType":"contains","source":19,"target":118},{"edgeType":"contains","source":4115,"target":4216},{"edgeType":"calls","source":83,"target":56},{"edgeType":"calls","source":4917,"target":303},{"edgeType":"calls","source":974,"target":975},{"edgeType":"contains","source":748,"target":773},{"edgeType":"calls","source":3848,"target":3845},{"edgeType":"contains","source":5241,"target":5248},{"edgeType":"calls","source":2626,"target":502},{"edgeType":"calls","source":4810,"target":447},{"edgeType":"calls","source":6863,"target":6596},{"edgeType":"calls","source":5747,"target":5226},{"edgeType":"imports","source":4668,"target":4113},{"edgeType":"calls","source":6215,"target":2345},{"edgeType":"calls","source":2097,"target":2103},{"edgeType":"calls","source":4206,"target":146},{"edgeType":"calls","source":4081,"target":4021},{"edgeType":"contains","source":19,"target":117},{"edgeType":"contains","source":5723,"target":4042},{"edgeType":"calls","source":5724,"target":3824},{"edgeType":"calls","source":4810,"target":448},{"edgeType":"imports","source":3726,"target":547},{"edgeType":"calls","source":1386,"target":886},{"edgeType":"calls","source":5220,"target":422},{"edgeType":"contains","source":748,"target":772},{"edgeType":"calls","source":1780,"target":303},{"edgeType":"calls","source":1812,"target":368},{"edgeType":"calls","source":449,"target":339},{"edgeType":"calls","source":6215,"target":2344},{"edgeType":"calls","source":4171,"target":171},{"edgeType":"calls","source":6249,"target":2347},{"edgeType":"calls","source":4953,"target":1299},{"edgeType":"imports","source":885,"target":887},{"edgeType":"calls","source":4739,"target":4762},{"edgeType":"extends","source":166,"target":167},{"edgeType":"contains","source":5,"target":3725},{"edgeType":"calls","source":5220,"target":421},{"edgeType":"calls","source":2998,"target":1652},{"edgeType":"calls","source":5005,"target":4972},{"edgeType":"contains","source":4668,"target":5040},{"edgeType":"calls","source":1778,"target":364},{"edgeType":"extends","source":430,"target":438},{"edgeType":"contains","source":6557,"target":6730},{"edgeType":"calls","source":449,"target":338},{"edgeType":"contains","source":885,"target":1813},{"edgeType":"calls","source":4641,"target":4627},{"edgeType":"contains","source":182,"target":351},{"edgeType":"calls","source":6215,"target":2343},{"edgeType":"calls","source":6249,"target":2346},{"edgeType":"calls","source":511,"target":530},{"edgeType":"calls","source":4568,"target":548},{"edgeType":"contains","source":2068,"target":2135},{"edgeType":"calls","source":4299,"target":431},{"edgeType":"contains","source":6166,"target":6167},{"edgeType":"calls","source":7032,"target":303},{"edgeType":"contains","source":4115,"target":4213},{"edgeType":"contains","source":748,"target":774},{"edgeType":"calls","source":1132,"target":1391},{"edgeType":"calls","source":6752,"target":2608},{"edgeType":"calls","source":4672,"target":527},{"edgeType":"contains","source":182,"target":321},{"edgeType":"calls","source":1813,"target":364},{"edgeType":"calls","source":1035,"target":170},{"edgeType":"calls","source":4448,"target":4300},{"edgeType":"calls","source":4576,"target":332},{"edgeType":"calls","source":512,"target":527},{"edgeType":"contains","source":17,"target":151},{"edgeType":"contains","source":3,"target":585},{"edgeType":"contains","source":2761,"target":2821},{"edgeType":"contains","source":3886,"target":3887},{"edgeType":"contains","source":4558,"target":4195},{"edgeType":"calls","source":7002,"target":144},{"edgeType":"imports","source":6322,"target":4621},{"edgeType":"contains","source":5895,"target":7145},{"edgeType":"contains","source":6557,"target":6706},{"edgeType":"calls","source":1132,"target":1390},{"edgeType":"calls","source":1140,"target":1142},{"edgeType":"calls","source":1039,"target":1102},{"edgeType":"contains","source":4943,"target":4944},{"edgeType":"calls","source":4912,"target":485},{"edgeType":"contains","source":6924,"target":6958},{"edgeType":"contains","source":1379,"target":2326},{"edgeType":"calls","source":6891,"target":6757},{"edgeType":"contains","source":17,"target":150},{"edgeType":"calls","source":6959,"target":421},{"edgeType":"contains","source":5895,"target":7146},{"edgeType":"calls","source":1274,"target":1216},{"edgeType":"calls","source":3219,"target":3289},{"edgeType":"calls","source":1538,"target":431},{"edgeType":"contains","source":5686,"target":6226},{"edgeType":"calls","source":1132,"target":1393},{"edgeType":"calls","source":1041,"target":1043},{"edgeType":"calls","source":3155,"target":3156},{"edgeType":"imports","source":3726,"target":535},{"edgeType":"calls","source":1813,"target":366},{"edgeType":"calls","source":1981,"target":1500},{"edgeType":"contains","source":5405,"target":5419},{"edgeType":"imports","source":5410,"target":5411},{"edgeType":"contains","source":3975,"target":4297},{"edgeType":"calls","source":2148,"target":548},{"edgeType":"contains","source":3952,"target":3953},{"edgeType":"calls","source":1295,"target":568},{"edgeType":"calls","source":6959,"target":422},{"edgeType":"calls","source":7002,"target":146},{"edgeType":"imports","source":6322,"target":4623},{"edgeType":"calls","source":5221,"target":4647},{"edgeType":"contains","source":5895,"target":7147},{"edgeType":"calls","source":1263,"target":503},{"edgeType":"calls","source":6757,"target":342},{"edgeType":"calls","source":1132,"target":1392},{"edgeType":"contains","source":3847,"target":4035},{"edgeType":"contains","source":5196,"target":5555},{"edgeType":"calls","source":3122,"target":3123},{"edgeType":"calls","source":1035,"target":171},{"edgeType":"contains","source":1031,"target":1486},{"edgeType":"calls","source":6787,"target":469},{"edgeType":"calls","source":6357,"target":84},{"edgeType":"calls","source":512,"target":528},{"edgeType":"contains","source":2068,"target":2106},{"edgeType":"calls","source":2990,"target":2987},{"edgeType":"calls","source":1263,"target":502},{"edgeType":"contains","source":5895,"target":7148},{"edgeType":"contains","source":182,"target":325},{"edgeType":"calls","source":4004,"target":1147},{"edgeType":"imports","source":6322,"target":4625},{"edgeType":"contains","source":5895,"target":7140},{"edgeType":"extends","source":3839,"target":438},{"edgeType":"calls","source":347,"target":353},{"edgeType":"calls","source":1603,"target":527},{"edgeType":"calls","source":3023,"target":3018},{"edgeType":"extends","source":6375,"target":36},{"edgeType":"contains","source":18,"target":124},{"edgeType":"contains","source":4414,"target":4435},{"edgeType":"calls","source":3477,"target":571},{"edgeType":"contains","source":6557,"target":6702},{"edgeType":"calls","source":4004,"target":1148},{"edgeType":"calls","source":3219,"target":3285},{"edgeType":"contains","source":5895,"target":7141},{"edgeType":"contains","source":1302,"target":4717},{"edgeType":"extends","source":1926,"target":1605},{"edgeType":"contains","source":3886,"target":3890},{"edgeType":"calls","source":4370,"target":371},{"edgeType":"contains","source":4691,"target":5360},{"edgeType":"calls","source":7068,"target":6559},{"edgeType":"calls","source":5660,"target":548},{"edgeType":"contains","source":1739,"target":1741},{"edgeType":"contains","source":4432,"target":4933},{"edgeType":"calls","source":1533,"target":582},{"edgeType":"imports","source":6322,"target":4624},{"edgeType":"calls","source":1882,"target":333},{"edgeType":"calls","source":1737,"target":1657},{"edgeType":"calls","source":4014,"target":4006},{"edgeType":"calls","source":4058,"target":528},{"edgeType":"calls","source":1138,"target":146},{"edgeType":"extends","source":3886,"target":36},{"edgeType":"calls","source":3481,"target":445},{"edgeType":"calls","source":1132,"target":1389},{"edgeType":"imports","source":6322,"target":4627},{"edgeType":"contains","source":5895,"target":7142},{"edgeType":"extends","source":2147,"target":36},{"edgeType":"calls","source":4370,"target":370},{"edgeType":"calls","source":4950,"target":4588},{"edgeType":"calls","source":2456,"target":509},{"edgeType":"contains","source":1805,"target":1806},{"edgeType":"contains","source":5895,"target":7143},{"edgeType":"contains","source":3820,"target":3821},{"edgeType":"contains","source":4432,"target":4932},{"edgeType":"calls","source":6107,"target":431},{"edgeType":"calls","source":4058,"target":527},{"edgeType":"calls","source":1486,"target":985},{"edgeType":"calls","source":6934,"target":144},{"edgeType":"contains","source":6459,"target":6572},{"edgeType":"calls","source":4004,"target":1146},{"edgeType":"imports","source":6322,"target":4626},{"edgeType":"calls","source":1132,"target":1388},{"edgeType":"contains","source":1732,"target":1955},{"edgeType":"calls","source":1125,"target":548},{"edgeType":"calls","source":3194,"target":3001},{"edgeType":"contains","source":5196,"target":5559},{"edgeType":"contains","source":6924,"target":6956},{"edgeType":"calls","source":4751,"target":4413},{"edgeType":"imports","source":2206,"target":79},{"edgeType":"calls","source":1603,"target":528},{"edgeType":"extends","source":4943,"target":36},{"edgeType":"calls","source":5018,"target":4593},{"edgeType":"contains","source":6033,"target":6037},{"edgeType":"calls","source":5332,"target":144},{"edgeType":"calls","source":4370,"target":369},{"edgeType":"contains","source":1732,"target":1956},{"edgeType":"contains","source":5895,"target":7144},{"edgeType":"contains","source":6924,"target":6965},{"edgeType":"calls","source":3481,"target":443},{"edgeType":"calls","source":1208,"target":84},{"edgeType":"imports","source":3975,"target":2319},{"edgeType":"contains","source":4839,"target":5006},{"edgeType":"contains","source":5895,"target":7153},{"edgeType":"calls","source":4370,"target":368},{"edgeType":"calls","source":2456,"target":507},{"edgeType":"calls","source":7024,"target":527},{"edgeType":"imports","source":2206,"target":2207},{"edgeType":"calls","source":2593,"target":2603},{"edgeType":"calls","source":6425,"target":84},{"edgeType":"calls","source":6463,"target":1006},{"edgeType":"contains","source":2581,"target":3126},{"edgeType":"extends","source":2761,"target":36},{"edgeType":"calls","source":4852,"target":4451},{"edgeType":"calls","source":914,"target":740},{"edgeType":"calls","source":5077,"target":1704},{"edgeType":"contains","source":4943,"target":4952},{"edgeType":"contains","source":4839,"target":5005},{"edgeType":"contains","source":5895,"target":7154},{"edgeType":"calls","source":2456,"target":508},{"edgeType":"extends","source":4875,"target":36},{"edgeType":"calls","source":6986,"target":6991},{"edgeType":"calls","source":1825,"target":1039},{"edgeType":"contains","source":5604,"target":5605},{"edgeType":"contains","source":182,"target":328},{"edgeType":"calls","source":7024,"target":528},{"edgeType":"contains","source":3975,"target":4306},{"edgeType":"contains","source":3820,"target":3826},{"edgeType":"contains","source":3808,"target":4198},{"edgeType":"calls","source":3955,"target":548},{"edgeType":"contains","source":4839,"target":5004},{"edgeType":"calls","source":2456,"target":505},{"edgeType":"calls","source":6929,"target":303},{"edgeType":"contains","source":5895,"target":7155},{"edgeType":"calls","source":143,"target":333},{"edgeType":"calls","source":4370,"target":366},{"edgeType":"calls","source":2265,"target":84},{"edgeType":"calls","source":1882,"target":332},{"edgeType":"calls","source":4818,"target":4446},{"edgeType":"calls","source":6242,"target":5755},{"edgeType":"contains","source":6562,"target":6563},{"edgeType":"calls","source":6929,"target":304},{"edgeType":"imports","source":6286,"target":5730},{"edgeType":"contains","source":5908,"target":6753},{"edgeType":"contains","source":5895,"target":7156},{"edgeType":"calls","source":2456,"target":506},{"edgeType":"calls","source":5632,"target":5638},{"edgeType":"extends","source":1754,"target":1654},{"edgeType":"calls","source":143,"target":332},{"edgeType":"imports","source":2070,"target":79},{"edgeType":"calls","source":5529,"target":4602},{"edgeType":"contains","source":4839,"target":5010},{"edgeType":"calls","source":1508,"target":1350},{"edgeType":"contains","source":3975,"target":4311},{"edgeType":"calls","source":1581,"target":144},{"edgeType":"calls","source":3008,"target":303},{"edgeType":"contains","source":579,"target":711},{"edgeType":"contains","source":748,"target":757},{"edgeType":"calls","source":4476,"target":4477},{"edgeType":"calls","source":2456,"target":503},{"edgeType":"contains","source":3808,"target":4203},{"edgeType":"calls","source":6976,"target":962},{"edgeType":"calls","source":4370,"target":364},{"edgeType":"imports","source":2070,"target":78},{"edgeType":"contains","source":5895,"target":7149},{"edgeType":"contains","source":4839,"target":5009},{"edgeType":"calls","source":3008,"target":304},{"edgeType":"contains","source":517,"target":518},{"edgeType":"extends","source":2586,"target":180},{"edgeType":"calls","source":2983,"target":3193},{"edgeType":"contains","source":748,"target":756},{"edgeType":"contains","source":6924,"target":6962},{"edgeType":"calls","source":2456,"target":504},{"edgeType":"contains","source":1732,"target":1966},{"edgeType":"calls","source":6895,"target":303},{"edgeType":"calls","source":6976,"target":963},{"edgeType":"contains","source":5895,"target":7150},{"edgeType":"calls","source":6527,"target":84},{"edgeType":"contains","source":4839,"target":5008},{"edgeType":"calls","source":5741,"target":142},{"edgeType":"contains","source":2068,"target":2117},{"edgeType":"calls","source":5093,"target":146},{"edgeType":"calls","source":1538,"target":422},{"edgeType":"contains","source":5,"target":3708},{"edgeType":"contains","source":32,"target":1814},{"edgeType":"calls","source":5863,"target":588},{"edgeType":"contains","source":6604,"target":3141},{"edgeType":"calls","source":3753,"target":461},{"edgeType":"contains","source":4943,"target":4955},{"edgeType":"contains","source":748,"target":759},{"edgeType":"contains","source":6924,"target":6963},{"edgeType":"calls","source":3219,"target":3274},{"edgeType":"imports","source":5616,"target":78},{"edgeType":"contains","source":5895,"target":7151},{"edgeType":"contains","source":3808,"target":4201},{"edgeType":"calls","source":4476,"target":4475},{"edgeType":"calls","source":6895,"target":304},{"edgeType":"contains","source":6557,"target":6712},{"edgeType":"contains","source":1732,"target":1963},{"edgeType":"contains","source":4839,"target":5007},{"edgeType":"calls","source":1538,"target":421},{"edgeType":"calls","source":5632,"target":5634},{"edgeType":"extends","source":4500,"target":36},{"edgeType":"contains","source":748,"target":758},{"edgeType":"contains","source":1732,"target":1964},{"edgeType":"contains","source":3808,"target":4200},{"edgeType":"imports","source":5616,"target":79},{"edgeType":"contains","source":5895,"target":7152},{"edgeType":"calls","source":2456,"target":502},{"edgeType":"calls","source":4754,"target":84},{"edgeType":"calls","source":4752,"target":146},{"edgeType":"calls","source":4781,"target":304},{"edgeType":"calls","source":2658,"target":582},{"edgeType":"calls","source":2794,"target":2804},{"edgeType":"calls","source":5639,"target":2344},{"edgeType":"calls","source":6966,"target":318},{"edgeType":"imports","source":130,"target":2125},{"edgeType":"contains","source":349,"target":413},{"edgeType":"contains","source":4414,"target":4415},{"edgeType":"contains","source":6429,"target":6430},{"edgeType":"contains","source":349,"target":412},{"edgeType":"contains","source":5636,"target":5644},{"edgeType":"calls","source":2336,"target":1147},{"edgeType":"extends","source":5617,"target":5618},{"edgeType":"contains","source":5196,"target":5541},{"edgeType":"calls","source":2794,"target":2805},{"edgeType":"calls","source":5639,"target":2343},{"edgeType":"calls","source":1520,"target":1072},{"edgeType":"calls","source":939,"target":56},{"edgeType":"contains","source":30,"target":3958},{"edgeType":"imports","source":3981,"target":78},{"edgeType":"calls","source":6926,"target":502},{"edgeType":"calls","source":6966,"target":319},{"edgeType":"imports","source":130,"target":2126},{"edgeType":"calls","source":6085,"target":144},{"edgeType":"contains","source":349,"target":411},{"edgeType":"contains","source":5636,"target":5645},{"edgeType":"calls","source":6826,"target":431},{"edgeType":"calls","source":6552,"target":469},{"edgeType":"calls","source":554,"target":364},{"edgeType":"calls","source":2336,"target":1148},{"edgeType":"calls","source":5639,"target":2342},{"edgeType":"contains","source":1305,"target":372},{"edgeType":"calls","source":6926,"target":503},{"edgeType":"imports","source":130,"target":2123},{"edgeType":"imports","source":3981,"target":79},{"edgeType":"contains","source":429,"target":1106},{"edgeType":"contains","source":349,"target":415},{"edgeType":"calls","source":6606,"target":910},{"edgeType":"contains","source":1379,"target":2307},{"edgeType":"contains","source":6032,"target":6055},{"edgeType":"calls","source":3455,"target":3453},{"edgeType":"contains","source":3351,"target":3539},{"edgeType":"calls","source":5639,"target":2341},{"edgeType":"calls","source":2984,"target":84},{"edgeType":"contains","source":6656,"target":6795},{"edgeType":"imports","source":130,"target":2124},{"edgeType":"contains","source":349,"target":414},{"edgeType":"contains","source":162,"target":6211},{"edgeType":"contains","source":5908,"target":6728},{"edgeType":"calls","source":6926,"target":504},{"edgeType":"calls","source":1131,"target":449},{"edgeType":"calls","source":6559,"target":6596},{"edgeType":"calls","source":1825,"target":1132},{"edgeType":"calls","source":6606,"target":911},{"edgeType":"calls","source":554,"target":366},{"edgeType":"calls","source":2336,"target":1146},{"edgeType":"imports","source":5380,"target":49},{"edgeType":"imports","source":4664,"target":49},{"edgeType":"calls","source":4885,"target":4573},{"edgeType":"calls","source":1704,"target":1707},{"edgeType":"contains","source":349,"target":417},{"edgeType":"calls","source":6926,"target":505},{"edgeType":"calls","source":7068,"target":1388},{"edgeType":"calls","source":6863,"target":6686},{"edgeType":"contains","source":4378,"target":4478},{"edgeType":"calls","source":4752,"target":4468},{"edgeType":"calls","source":6425,"target":171},{"edgeType":"calls","source":4443,"target":304},{"edgeType":"contains","source":5405,"target":5408},{"edgeType":"calls","source":2931,"target":2782},{"edgeType":"contains","source":4664,"target":5124},{"edgeType":"imports","source":6286,"target":2618},{"edgeType":"calls","source":1704,"target":1706},{"edgeType":"contains","source":429,"target":1107},{"edgeType":"calls","source":7068,"target":1389},{"edgeType":"contains","source":349,"target":416},{"edgeType":"calls","source":6926,"target":506},{"edgeType":"calls","source":4757,"target":84},{"edgeType":"calls","source":3357,"target":146},{"edgeType":"calls","source":6425,"target":170},{"edgeType":"calls","source":3734,"target":84},{"edgeType":"calls","source":4443,"target":303},{"edgeType":"calls","source":2265,"target":170},{"edgeType":"calls","source":5077,"target":733},{"edgeType":"contains","source":162,"target":5159},{"edgeType":"contains","source":4558,"target":4181},{"edgeType":"calls","source":7068,"target":1390},{"edgeType":"contains","source":6651,"target":6945},{"edgeType":"contains","source":349,"target":419},{"edgeType":"calls","source":3414,"target":1548},{"edgeType":"calls","source":3791,"target":431},{"edgeType":"calls","source":6728,"target":303},{"edgeType":"calls","source":6926,"target":507},{"edgeType":"extends","source":166,"target":191},{"edgeType":"calls","source":4787,"target":210},{"edgeType":"calls","source":3414,"target":1547},{"edgeType":"calls","source":3450,"target":431},{"edgeType":"contains","source":1130,"target":1576},{"edgeType":"calls","source":4646,"target":353},{"edgeType":"calls","source":2265,"target":171},{"edgeType":"calls","source":6926,"target":508},{"edgeType":"contains","source":5405,"target":5406},{"edgeType":"calls","source":5061,"target":171},{"edgeType":"calls","source":5077,"target":732},{"edgeType":"contains","source":3951,"target":3970},{"edgeType":"imports","source":885,"target":913},{"edgeType":"contains","source":349,"target":418},{"edgeType":"contains","source":5908,"target":6724},{"edgeType":"contains","source":6651,"target":6946},{"edgeType":"calls","source":1719,"target":1243},{"edgeType":"calls","source":1704,"target":1708},{"edgeType":"calls","source":7068,"target":1391},{"edgeType":"contains","source":30,"target":3964},{"edgeType":"calls","source":6728,"target":304},{"edgeType":"calls","source":4787,"target":209},{"edgeType":"contains","source":5166,"target":2244},{"edgeType":"calls","source":5340,"target":2092},{"edgeType":"calls","source":4755,"target":144},{"edgeType":"contains","source":1130,"target":1579},{"edgeType":"calls","source":6926,"target":509},{"edgeType":"contains","source":5895,"target":7136},{"edgeType":"imports","source":6539,"target":49},{"edgeType":"imports","source":4459,"target":49},{"edgeType":"calls","source":7068,"target":1392},{"edgeType":"calls","source":6935,"target":6572},{"edgeType":"calls","source":3414,"target":1545},{"edgeType":"contains","source":1415,"target":144},{"edgeType":"extends","source":6377,"target":36},{"edgeType":"calls","source":5340,"target":2091},{"edgeType":"contains","source":4671,"target":4912},{"edgeType":"calls","source":4817,"target":4563},{"edgeType":"contains","source":4664,"target":5129},{"edgeType":"contains","source":2599,"target":3607},{"edgeType":"calls","source":5061,"target":170},{"edgeType":"contains","source":1130,"target":1578},{"edgeType":"calls","source":6659,"target":6673},{"edgeType":"contains","source":5196,"target":5549},{"edgeType":"contains","source":5207,"target":5208},{"edgeType":"calls","source":7068,"target":1393},{"edgeType":"contains","source":349,"target":420},{"edgeType":"contains","source":2068,"target":2099},{"edgeType":"calls","source":1347,"target":84},{"edgeType":"calls","source":3414,"target":1546},{"edgeType":"calls","source":7068,"target":1394},{"edgeType":"calls","source":6212,"target":5712},{"edgeType":"contains","source":1130,"target":1577},{"edgeType":"imports","source":3807,"target":179},{"edgeType":"calls","source":3113,"target":304},{"edgeType":"contains","source":5273,"target":5275},{"edgeType":"calls","source":5093,"target":2347},{"edgeType":"imports","source":6286,"target":5780},{"edgeType":"contains","source":5895,"target":7138},{"edgeType":"calls","source":4448,"target":144},{"edgeType":"calls","source":1401,"target":528},{"edgeType":"contains","source":3,"target":578},{"edgeType":"calls","source":4107,"target":144},{"edgeType":"calls","source":1704,"target":1705},{"edgeType":"contains","source":5870,"target":1571},{"edgeType":"contains","source":2068,"target":2096},{"edgeType":"contains","source":3618,"target":3728},{"edgeType":"calls","source":347,"target":434},{"edgeType":"contains","source":5196,"target":5547},{"edgeType":"calls","source":1007,"target":56},{"edgeType":"contains","source":5273,"target":5274},{"edgeType":"contains","source":5895,"target":7139},{"edgeType":"calls","source":1401,"target":527},{"edgeType":"calls","source":3729,"target":236},{"edgeType":"contains","source":2860,"target":2914},{"edgeType":"imports","source":130,"target":1076},{"edgeType":"contains","source":1031,"target":1477},{"edgeType":"calls","source":5093,"target":2346},{"edgeType":"extends","source":5388,"target":36},{"edgeType":"calls","source":1722,"target":84},{"edgeType":"calls","source":2326,"target":1444},{"edgeType":"contains","source":6557,"target":6694},{"edgeType":"calls","source":5909,"target":304},{"edgeType":"calls","source":6464,"target":2151},{"edgeType":"contains","source":5,"target":519},{"edgeType":"calls","source":6859,"target":6819},{"edgeType":"calls","source":1517,"target":1153},{"edgeType":"calls","source":5093,"target":2345},{"edgeType":"calls","source":3113,"target":303},{"edgeType":"calls","source":6633,"target":84},{"edgeType":"contains","source":4113,"target":1072},{"edgeType":"calls","source":5867,"target":548},{"edgeType":"calls","source":2252,"target":568},{"edgeType":"calls","source":5909,"target":303},{"edgeType":"calls","source":6255,"target":147},{"edgeType":"calls","source":4200,"target":431},{"edgeType":"contains","source":21,"target":22},{"edgeType":"calls","source":6977,"target":1048},{"edgeType":"calls","source":1097,"target":431},{"edgeType":"calls","source":5093,"target":2344},{"edgeType":"calls","source":5129,"target":171},{"edgeType":"calls","source":1604,"target":1630},{"edgeType":"contains","source":6656,"target":6798},{"edgeType":"imports","source":2581,"target":2254},{"edgeType":"contains","source":5196,"target":5552},{"edgeType":"imports","source":4391,"target":49},{"edgeType":"contains","source":1302,"target":4706},{"edgeType":"contains","source":17,"target":149},{"edgeType":"calls","source":5129,"target":170},{"edgeType":"calls","source":5093,"target":2343},{"edgeType":"contains","source":5895,"target":7135},{"edgeType":"calls","source":4617,"target":4413},{"edgeType":"calls","source":1517,"target":1155},{"edgeType":"calls","source":1962,"target":1101},{"edgeType":"imports","source":130,"target":2128},{"edgeType":"extends","source":167,"target":168},{"edgeType":"calls","source":5093,"target":2342},{"edgeType":"calls","source":6972,"target":148},{"edgeType":"imports","source":3166,"target":1030},{"edgeType":"calls","source":1771,"target":1765},{"edgeType":"calls","source":1134,"target":371},{"edgeType":"contains","source":349,"target":396},{"edgeType":"contains","source":185,"target":195},{"edgeType":"calls","source":6838,"target":2155},{"edgeType":"contains","source":1044,"target":1049},{"edgeType":"calls","source":4203,"target":366},{"edgeType":"contains","source":1605,"target":1628},{"edgeType":"contains","source":1440,"target":1458},{"edgeType":"contains","source":1473,"target":1492},{"edgeType":"calls","source":6285,"target":304},{"edgeType":"contains","source":3351,"target":3526},{"edgeType":"calls","source":4917,"target":431},{"edgeType":"calls","source":4860,"target":84},{"edgeType":"calls","source":6937,"target":144},{"edgeType":"calls","source":2993,"target":2994},{"edgeType":"calls","source":6803,"target":6412},{"edgeType":"calls","source":1134,"target":370},{"edgeType":"contains","source":1605,"target":1629},{"edgeType":"calls","source":6110,"target":443},{"edgeType":"contains","source":349,"target":395},{"edgeType":"contains","source":1044,"target":1048},{"edgeType":"contains","source":1473,"target":1493},{"edgeType":"contains","source":6924,"target":6925},{"edgeType":"calls","source":6285,"target":303},{"edgeType":"contains","source":1440,"target":1459},{"edgeType":"calls","source":4264,"target":590},{"edgeType":"contains","source":3351,"target":3525},{"edgeType":"contains","source":2662,"target":2687},{"edgeType":"contains","source":4706,"target":4858},{"edgeType":"calls","source":5633,"target":431},{"edgeType":"calls","source":1673,"target":1630},{"edgeType":"calls","source":6998,"target":368},{"edgeType":"calls","source":4959,"target":4413},{"edgeType":"contains","source":4380,"target":4394},{"edgeType":"contains","source":2331,"target":2375},{"edgeType":"contains","source":6604,"target":3104},{"edgeType":"calls","source":1723,"target":84},{"edgeType":"calls","source":4203,"target":364},{"edgeType":"contains","source":6924,"target":6926},{"edgeType":"contains","source":1440,"target":1456},{"edgeType":"contains","source":1473,"target":1490},{"edgeType":"contains","source":1605,"target":1626},{"edgeType":"contains","source":3351,"target":3524},{"edgeType":"calls","source":3729,"target":259},{"edgeType":"contains","source":349,"target":398},{"edgeType":"contains","source":2662,"target":2684},{"edgeType":"contains","source":4706,"target":4857},{"edgeType":"calls","source":6998,"target":369},{"edgeType":"calls","source":3224,"target":3230},{"edgeType":"contains","source":4502,"target":4839},{"edgeType":"contains","source":4544,"target":4594},{"edgeType":"contains","source":2599,"target":3580},{"edgeType":"calls","source":1708,"target":548},{"edgeType":"calls","source":483,"target":469},{"edgeType":"contains","source":1605,"target":1627},{"edgeType":"contains","source":1440,"target":1457},{"edgeType":"contains","source":1473,"target":1491},{"edgeType":"calls","source":5739,"target":5599},{"edgeType":"calls","source":889,"target":568},{"edgeType":"calls","source":5220,"target":548},{"edgeType":"contains","source":349,"target":397},{"edgeType":"contains","source":4706,"target":4856},{"edgeType":"calls","source":6998,"target":370},{"edgeType":"calls","source":2531,"target":2513},{"edgeType":"calls","source":1143,"target":1145},{"edgeType":"calls","source":6611,"target":1797},{"edgeType":"calls","source":6591,"target":303},{"edgeType":"contains","source":1440,"target":1462},{"edgeType":"contains","source":1473,"target":1496},{"edgeType":"contains","source":3351,"target":3530},{"edgeType":"calls","source":4646,"target":371},{"edgeType":"imports","source":1379,"target":1440},{"edgeType":"contains","source":2599,"target":3586},{"edgeType":"contains","source":1907,"target":2841},{"edgeType":"calls","source":4993,"target":4413},{"edgeType":"calls","source":2907,"target":371},{"edgeType":"calls","source":4941,"target":740},{"edgeType":"contains","source":713,"target":743},{"edgeType":"calls","source":6858,"target":483},{"edgeType":"calls","source":6932,"target":303},{"edgeType":"contains","source":349,"target":400},{"edgeType":"calls","source":6998,"target":371},{"edgeType":"contains","source":6557,"target":6669},{"edgeType":"contains","source":4347,"target":4364},{"edgeType":"contains","source":1473,"target":1497},{"edgeType":"calls","source":1134,"target":366},{"edgeType":"calls","source":6591,"target":304},{"edgeType":"calls","source":1142,"target":1175},{"edgeType":"calls","source":6423,"target":2341},{"edgeType":"calls","source":4926,"target":146},{"edgeType":"contains","source":4839,"target":4968},{"edgeType":"contains","source":3508,"target":3947},{"edgeType":"contains","source":1440,"target":1463},{"edgeType":"calls","source":4715,"target":4573},{"edgeType":"calls","source":4646,"target":370},{"edgeType":"contains","source":1228,"target":2750},{"edgeType":"calls","source":2530,"target":431},{"edgeType":"contains","source":3013,"target":4495},{"edgeType":"contains","source":6032,"target":6033},{"edgeType":"contains","source":2662,"target":2691},{"edgeType":"contains","source":3819,"target":3820},{"edgeType":"calls","source":3753,"target":571},{"edgeType":"contains","source":4478,"target":4531},{"edgeType":"contains","source":6557,"target":6670},{"edgeType":"contains","source":349,"target":399},{"edgeType":"calls","source":6966,"target":307},{"edgeType":"calls","source":6932,"target":304},{"edgeType":"calls","source":1134,"target":369},{"edgeType":"calls","source":6528,"target":144},{"edgeType":"calls","source":6423,"target":2342},{"edgeType":"contains","source":1440,"target":1460},{"edgeType":"contains","source":1473,"target":1494},{"edgeType":"contains","source":4839,"target":4967},{"edgeType":"contains","source":1044,"target":1055},{"edgeType":"calls","source":2907,"target":368},{"edgeType":"calls","source":4753,"target":4451},{"edgeType":"calls","source":351,"target":330},{"edgeType":"contains","source":3351,"target":3528},{"edgeType":"calls","source":4646,"target":369},{"edgeType":"calls","source":2595,"target":1584},{"edgeType":"contains","source":1907,"target":2839},{"edgeType":"calls","source":2907,"target":369},{"edgeType":"calls","source":4885,"target":4588},{"edgeType":"contains","source":349,"target":402},{"edgeType":"calls","source":3932,"target":304},{"edgeType":"contains","source":185,"target":201},{"edgeType":"extends","source":6683,"target":36},{"edgeType":"contains","source":1605,"target":1631},{"edgeType":"calls","source":1134,"target":368},{"edgeType":"calls","source":6606,"target":898},{"edgeType":"calls","source":6423,"target":2343},{"edgeType":"calls","source":4098,"target":445},{"edgeType":"calls","source":3989,"target":3824},{"edgeType":"contains","source":1044,"target":1054},{"edgeType":"contains","source":1440,"target":1461},{"edgeType":"contains","source":1473,"target":1495},{"edgeType":"calls","source":4264,"target":584},{"edgeType":"contains","source":5754,"target":3025},{"edgeType":"calls","source":4646,"target":368},{"edgeType":"contains","source":3351,"target":3527},{"edgeType":"calls","source":4721,"target":157},{"edgeType":"contains","source":1907,"target":2840},{"edgeType":"contains","source":6824,"target":6851},{"edgeType":"calls","source":2907,"target":370},{"edgeType":"contains","source":349,"target":401},{"edgeType":"contains","source":52,"target":95},{"edgeType":"calls","source":6688,"target":1528},{"edgeType":"calls","source":6423,"target":2344},{"edgeType":"calls","source":3311,"target":527},{"edgeType":"contains","source":1440,"target":1466},{"edgeType":"calls","source":4841,"target":4892},{"edgeType":"calls","source":2907,"target":366},{"edgeType":"contains","source":3013,"target":4498},{"edgeType":"contains","source":2662,"target":2695},{"edgeType":"calls","source":883,"target":744},{"edgeType":"contains","source":4839,"target":4973},{"edgeType":"contains","source":1044,"target":1057},{"edgeType":"contains","source":1186,"target":883},{"edgeType":"contains","source":4558,"target":4170},{"edgeType":"calls","source":2252,"target":588},{"edgeType":"contains","source":1639,"target":1640},{"edgeType":"contains","source":349,"target":404},{"edgeType":"calls","source":6807,"target":1011},{"edgeType":"calls","source":4098,"target":443},{"edgeType":"calls","source":6423,"target":2345},{"edgeType":"calls","source":3311,"target":528},{"edgeType":"contains","source":1440,"target":1467},{"edgeType":"contains","source":6432,"target":1044},{"edgeType":"contains","source":2662,"target":2696},{"edgeType":"calls","source":4646,"target":366},{"edgeType":"calls","source":1109,"target":1137},{"edgeType":"calls","source":4841,"target":4891},{"edgeType":"contains","source":3351,"target":3533},{"edgeType":"calls","source":4687,"target":152},{"edgeType":"contains","source":3013,"target":4499},{"edgeType":"contains","source":4668,"target":4988},{"edgeType":"contains","source":6651,"target":6940},{"edgeType":"contains","source":1044,"target":1056},{"edgeType":"contains","source":6557,"target":6682},{"edgeType":"calls","source":6966,"target":311},{"edgeType":"calls","source":6791,"target":6793},{"edgeType":"calls","source":3932,"target":303},{"edgeType":"contains","source":6032,"target":6045},{"edgeType":"contains","source":349,"target":403},{"edgeType":"extends","source":4003,"target":3847},{"edgeType":"contains","source":5636,"target":5637},{"edgeType":"calls","source":5642,"target":144},{"edgeType":"contains","source":3,"target":2673},{"edgeType":"calls","source":6423,"target":2346},{"edgeType":"contains","source":1440,"target":1464},{"edgeType":"contains","source":4380,"target":4401},{"edgeType":"calls","source":5018,"target":1517},{"edgeType":"contains","source":2761,"target":2795},{"edgeType":"contains","source":3351,"target":3532},{"edgeType":"calls","source":4620,"target":114},{"edgeType":"contains","source":5196,"target":5531},{"edgeType":"contains","source":1044,"target":1059},{"edgeType":"calls","source":4841,"target":4890},{"edgeType":"calls","source":2907,"target":364},{"edgeType":"calls","source":1572,"target":1585},{"edgeType":"contains","source":349,"target":406},{"edgeType":"calls","source":6966,"target":312},{"edgeType":"contains","source":162,"target":5146},{"edgeType":"calls","source":4337,"target":431},{"edgeType":"calls","source":1823,"target":146},{"edgeType":"calls","source":6423,"target":2347},{"edgeType":"calls","source":7063,"target":6819},{"edgeType":"contains","source":1440,"target":1465},{"edgeType":"calls","source":1134,"target":364},{"edgeType":"calls","source":4646,"target":364},{"edgeType":"contains","source":2688,"target":1888},{"edgeType":"contains","source":1044,"target":1058},{"edgeType":"calls","source":5023,"target":304},{"edgeType":"calls","source":4841,"target":4889},{"edgeType":"calls","source":1572,"target":1584},{"edgeType":"calls","source":6692,"target":6693},{"edgeType":"calls","source":5042,"target":5001},{"edgeType":"contains","source":349,"target":405},{"edgeType":"calls","source":6966,"target":313},{"edgeType":"calls","source":4250,"target":4184},{"edgeType":"contains","source":6032,"target":6047},{"edgeType":"contains","source":185,"target":204},{"edgeType":"contains","source":41,"target":4668},{"edgeType":"contains","source":3975,"target":4271},{"edgeType":"contains","source":1302,"target":4691},{"edgeType":"contains","source":1440,"target":1470},{"edgeType":"contains","source":20,"target":37},{"edgeType":"contains","source":3351,"target":3538},{"edgeType":"calls","source":6421,"target":304},{"edgeType":"calls","source":554,"target":369},{"edgeType":"contains","source":4313,"target":4370},{"edgeType":"calls","source":4595,"target":4058},{"edgeType":"calls","source":2871,"target":421},{"edgeType":"contains","source":4558,"target":4175},{"edgeType":"calls","source":922,"target":588},{"edgeType":"calls","source":1143,"target":80},{"edgeType":"contains","source":2662,"target":2699},{"edgeType":"calls","source":5023,"target":303},{"edgeType":"contains","source":4579,"target":4581},{"edgeType":"calls","source":6659,"target":6660},{"edgeType":"calls","source":5220,"target":2653},{"edgeType":"calls","source":6590,"target":6685},{"edgeType":"contains","source":1044,"target":1061},{"edgeType":"calls","source":3824,"target":475},{"edgeType":"contains","source":5272,"target":5295},{"edgeType":"contains","source":349,"target":408},{"edgeType":"calls","source":4584,"target":171},{"edgeType":"contains","source":6651,"target":6934},{"edgeType":"calls","source":2198,"target":144},{"edgeType":"calls","source":6110,"target":431},{"edgeType":"contains","source":4839,"target":4976},{"edgeType":"contains","source":1440,"target":1471},{"edgeType":"calls","source":4714,"target":4596},{"edgeType":"contains","source":3,"target":2677},{"edgeType":"calls","source":6421,"target":303},{"edgeType":"calls","source":5639,"target":2347},{"edgeType":"calls","source":554,"target":368},{"edgeType":"calls","source":4761,"target":2082},{"edgeType":"calls","source":2871,"target":422},{"edgeType":"calls","source":5222,"target":475},{"edgeType":"calls","source":2795,"target":2778},{"edgeType":"calls","source":5018,"target":1514},{"edgeType":"contains","source":4612,"target":4614},{"edgeType":"contains","source":1044,"target":1060},{"edgeType":"calls","source":5220,"target":2652},{"edgeType":"calls","source":4386,"target":4194},{"edgeType":"contains","source":6557,"target":6678},{"edgeType":"calls","source":4584,"target":170},{"edgeType":"contains","source":349,"target":407},{"edgeType":"contains","source":185,"target":206},{"edgeType":"contains","source":1440,"target":1472},{"edgeType":"contains","source":1440,"target":1468},{"edgeType":"contains","source":3,"target":2680},{"edgeType":"calls","source":554,"target":371},{"edgeType":"contains","source":3351,"target":3536},{"edgeType":"calls","source":5639,"target":2346},{"edgeType":"contains","source":2597,"target":2598},{"edgeType":"extends","source":955,"target":36},{"edgeType":"calls","source":1142,"target":1170},{"edgeType":"calls","source":5222,"target":474},{"edgeType":"contains","source":4612,"target":4613},{"edgeType":"calls","source":5077,"target":741},{"edgeType":"contains","source":349,"target":410},{"edgeType":"contains","source":162,"target":5150},{"edgeType":"calls","source":4386,"target":4193},{"edgeType":"calls","source":3824,"target":473},{"edgeType":"calls","source":2329,"target":309},{"edgeType":"contains","source":1440,"target":1469},{"edgeType":"calls","source":6357,"target":171},{"edgeType":"calls","source":554,"target":370},{"edgeType":"calls","source":5639,"target":2345},{"edgeType":"calls","source":1175,"target":146},{"edgeType":"calls","source":5222,"target":473},{"edgeType":"contains","source":349,"target":409},{"edgeType":"contains","source":928,"target":3601},{"edgeType":"calls","source":3824,"target":474},{"edgeType":"contains","source":6651,"target":6937},{"edgeType":"calls","source":1572,"target":1580},{"edgeType":"contains","source":4000,"target":4557},{"edgeType":"calls","source":3729,"target":248},{"edgeType":"calls","source":6194,"target":5223},{"edgeType":"calls","source":6357,"target":170},{"edgeType":"calls","source":4992,"target":170},{"edgeType":"contains","source":2662,"target":2670},{"edgeType":"contains","source":16,"target":132},{"edgeType":"calls","source":6728,"target":6606},{"edgeType":"imports","source":4664,"target":78},{"edgeType":"contains","source":6651,"target":6914},{"edgeType":"contains","source":745,"target":788},{"edgeType":"contains","source":713,"target":723},{"edgeType":"calls","source":1406,"target":1403},{"edgeType":"calls","source":6559,"target":6560},{"edgeType":"contains","source":349,"target":379},{"edgeType":"calls","source":2562,"target":2564},{"edgeType":"calls","source":6859,"target":431},{"edgeType":"calls","source":6688,"target":447},{"edgeType":"calls","source":6837,"target":56},{"edgeType":"calls","source":2326,"target":1424},{"edgeType":"imports","source":5380,"target":79},{"edgeType":"contains","source":3509,"target":3897},{"edgeType":"contains","source":5196,"target":5508},{"edgeType":"contains","source":1605,"target":1612},{"edgeType":"contains","source":1440,"target":1442},{"edgeType":"contains","source":2662,"target":2671},{"edgeType":"imports","source":4664,"target":79},{"edgeType":"calls","source":6883,"target":2859},{"edgeType":"calls","source":1572,"target":1541},{"edgeType":"contains","source":745,"target":787},{"edgeType":"calls","source":1239,"target":1294},{"edgeType":"extends","source":2286,"target":36},{"edgeType":"contains","source":713,"target":722},{"edgeType":"calls","source":1162,"target":509},{"edgeType":"contains","source":349,"target":378},{"edgeType":"contains","source":2331,"target":2361},{"edgeType":"contains","source":1605,"target":1613},{"edgeType":"calls","source":6688,"target":448},{"edgeType":"contains","source":184,"target":208},{"edgeType":"calls","source":2265,"target":2259},{"edgeType":"calls","source":2326,"target":1425},{"edgeType":"calls","source":6206,"target":588},{"edgeType":"contains","source":1440,"target":1443},{"edgeType":"contains","source":1302,"target":4664},{"edgeType":"calls","source":7025,"target":572},{"edgeType":"calls","source":3640,"target":2969},{"edgeType":"contains","source":4000,"target":4529},{"edgeType":"contains","source":2030,"target":1119},{"edgeType":"calls","source":2794,"target":2769},{"edgeType":"calls","source":5913,"target":157},{"edgeType":"calls","source":4931,"target":1002},{"edgeType":"calls","source":895,"target":333},{"edgeType":"contains","source":745,"target":790},{"edgeType":"contains","source":713,"target":725},{"edgeType":"calls","source":3244,"target":3618},{"edgeType":"contains","source":430,"target":1042},{"edgeType":"calls","source":1208,"target":144},{"edgeType":"calls","source":5365,"target":3404},{"edgeType":"calls","source":5373,"target":3156},{"edgeType":"calls","source":4133,"target":370},{"edgeType":"imports","source":4459,"target":2207},{"edgeType":"calls","source":6493,"target":6494},{"edgeType":"contains","source":1605,"target":1610},{"edgeType":"calls","source":7025,"target":573},{"edgeType":"calls","source":1525,"target":886},{"edgeType":"calls","source":3640,"target":2970},{"edgeType":"calls","source":895,"target":332},{"edgeType":"imports","source":5616,"target":166},{"edgeType":"contains","source":2898,"target":2752},{"edgeType":"calls","source":1572,"target":1543},{"edgeType":"contains","source":745,"target":789},{"edgeType":"contains","source":713,"target":724},{"edgeType":"contains","source":4545,"target":4546},{"edgeType":"calls","source":1242,"target":146},{"edgeType":"calls","source":2562,"target":2563},{"edgeType":"contains","source":3166,"target":2900},{"edgeType":"calls","source":6803,"target":56},{"edgeType":"contains","source":3975,"target":4246},{"edgeType":"calls","source":4133,"target":371},{"edgeType":"imports","source":3166,"target":3173},{"edgeType":"contains","source":1605,"target":1611},{"edgeType":"contains","source":1440,"target":1441},{"edgeType":"calls","source":2326,"target":1423},{"edgeType":"calls","source":1572,"target":481},{"edgeType":"calls","source":4381,"target":1137},{"edgeType":"contains","source":6064,"target":6080},{"edgeType":"contains","source":745,"target":792},{"edgeType":"contains","source":713,"target":727},{"edgeType":"calls","source":1811,"target":471},{"edgeType":"imports","source":3949,"target":49},{"edgeType":"contains","source":429,"target":1075},{"edgeType":"calls","source":3662,"target":171},{"edgeType":"extends","source":172,"target":36},{"edgeType":"calls","source":6995,"target":447},{"edgeType":"calls","source":1542,"target":354},{"edgeType":"calls","source":525,"target":170},{"edgeType":"calls","source":3244,"target":3615},{"edgeType":"contains","source":1605,"target":1616},{"edgeType":"calls","source":4581,"target":4451},{"edgeType":"calls","source":4133,"target":368},{"edgeType":"calls","source":1162,"target":506},{"edgeType":"contains","source":1440,"target":1446},{"edgeType":"contains","source":1031,"target":1439},{"edgeType":"contains","source":1473,"target":1480},{"edgeType":"calls","source":1583,"target":1196},{"edgeType":"contains","source":3290,"target":3291},{"edgeType":"calls","source":1572,"target":480},{"edgeType":"calls","source":2859,"target":2867},{"edgeType":"contains","source":3975,"target":4252},{"edgeType":"contains","source":745,"target":791},{"edgeType":"contains","source":6656,"target":6756},{"edgeType":"contains","source":713,"target":726},{"edgeType":"contains","source":2299,"target":2301},{"edgeType":"contains","source":349,"target":383},{"edgeType":"calls","source":6995,"target":448},{"edgeType":"calls","source":1162,"target":505},{"edgeType":"contains","source":1473,"target":1481},{"edgeType":"calls","source":4133,"target":369},{"edgeType":"contains","source":1605,"target":1617},{"edgeType":"contains","source":1440,"target":1447},{"edgeType":"calls","source":2506,"target":1126},{"edgeType":"contains","source":2662,"target":2672},{"edgeType":"contains","source":6824,"target":6834},{"edgeType":"contains","source":349,"target":386},{"edgeType":"contains","source":6651,"target":6912},{"edgeType":"calls","source":1747,"target":1400},{"edgeType":"calls","source":1602,"target":1667},{"edgeType":"calls","source":1162,"target":508},{"edgeType":"calls","source":4133,"target":366},{"edgeType":"contains","source":1605,"target":1614},{"edgeType":"contains","source":745,"target":794},{"edgeType":"contains","source":713,"target":729},{"edgeType":"contains","source":1440,"target":1444},{"edgeType":"contains","source":1473,"target":1478},{"edgeType":"calls","source":4841,"target":4845},{"edgeType":"contains","source":713,"target":728},{"edgeType":"contains","source":349,"target":385},{"edgeType":"contains","source":6651,"target":6913},{"edgeType":"calls","source":3662,"target":170},{"edgeType":"calls","source":6780,"target":2887},{"edgeType":"contains","source":1605,"target":1615},{"edgeType":"calls","source":1162,"target":507},{"edgeType":"contains","source":745,"target":793},{"edgeType":"contains","source":1440,"target":1445},{"edgeType":"contains","source":1473,"target":1479},{"edgeType":"calls","source":4876,"target":588},{"edgeType":"calls","source":525,"target":171},{"edgeType":"calls","source":2562,"target":2559},{"edgeType":"contains","source":3351,"target":3511},{"edgeType":"calls","source":4615,"target":4451},{"edgeType":"extends","source":3241,"target":36},{"edgeType":"imports","source":2581,"target":179},{"edgeType":"calls","source":1572,"target":1534},{"edgeType":"calls","source":2456,"target":556},{"edgeType":"calls","source":1572,"target":477},{"edgeType":"contains","source":349,"target":388},{"edgeType":"calls","source":6087,"target":1099},{"edgeType":"contains","source":1907,"target":2828},{"edgeType":"contains","source":185,"target":187},{"edgeType":"calls","source":6727,"target":303},{"edgeType":"calls","source":6728,"target":3443},{"edgeType":"contains","source":3949,"target":4006},{"edgeType":"calls","source":4201,"target":370},{"edgeType":"calls","source":4133,"target":364},{"edgeType":"contains","source":745,"target":796},{"edgeType":"contains","source":1605,"target":1620},{"edgeType":"contains","source":1440,"target":1450},{"edgeType":"contains","source":1473,"target":1484},{"edgeType":"contains","source":4706,"target":4851},{"edgeType":"calls","source":1162,"target":502},{"edgeType":"contains","source":6557,"target":6666},{"edgeType":"calls","source":1572,"target":1533},{"edgeType":"calls","source":2456,"target":557},{"edgeType":"calls","source":1572,"target":476},{"edgeType":"contains","source":4478,"target":4519},{"edgeType":"contains","source":1605,"target":1621},{"edgeType":"contains","source":349,"target":387},{"edgeType":"contains","source":185,"target":186},{"edgeType":"contains","source":1907,"target":2829},{"edgeType":"calls","source":6727,"target":304},{"edgeType":"contains","source":1473,"target":1485},{"edgeType":"calls","source":4851,"target":304},{"edgeType":"imports","source":2176,"target":49},{"edgeType":"contains","source":745,"target":795},{"edgeType":"contains","source":2266,"target":2271},{"edgeType":"calls","source":4194,"target":588},{"edgeType":"calls","source":4201,"target":371},{"edgeType":"contains","source":713,"target":730},{"edgeType":"calls","source":3189,"target":3203},{"edgeType":"contains","source":4380,"target":4386},{"edgeType":"contains","source":1440,"target":1451},{"edgeType":"contains","source":3351,"target":3517},{"edgeType":"calls","source":1195,"target":535},{"edgeType":"calls","source":2892,"target":2897},{"edgeType":"contains","source":5196,"target":5515},{"edgeType":"calls","source":4667,"target":2837},{"edgeType":"contains","source":2879,"target":3351},{"edgeType":"contains","source":6557,"target":6667},{"edgeType":"calls","source":1572,"target":479},{"edgeType":"contains","source":5272,"target":5273},{"edgeType":"contains","source":349,"target":390},{"edgeType":"contains","source":4478,"target":4518},{"edgeType":"calls","source":4283,"target":3112},{"edgeType":"imports","source":4391,"target":78},{"edgeType":"calls","source":4201,"target":368},{"edgeType":"calls","source":4851,"target":303},{"edgeType":"contains","source":745,"target":798},{"edgeType":"contains","source":2266,"target":2268},{"edgeType":"contains","source":1440,"target":1448},{"edgeType":"contains","source":1473,"target":1482},{"edgeType":"calls","source":1162,"target":504},{"edgeType":"calls","source":5469,"target":171},{"edgeType":"contains","source":1605,"target":1618},{"edgeType":"calls","source":4912,"target":4754},{"edgeType":"contains","source":2761,"target":2778},{"edgeType":"calls","source":5015,"target":2618},{"edgeType":"contains","source":3351,"target":3516},{"edgeType":"calls","source":1572,"target":478},{"edgeType":"contains","source":349,"target":389},{"edgeType":"contains","source":4502,"target":4830},{"edgeType":"calls","source":2456,"target":2669},{"edgeType":"calls","source":4283,"target":3111},{"edgeType":"calls","source":6688,"target":1515},{"edgeType":"calls","source":4183,"target":4097},{"edgeType":"imports","source":4391,"target":79},{"edgeType":"contains","source":185,"target":188},{"edgeType":"contains","source":745,"target":797},{"edgeType":"calls","source":4201,"target":369},{"edgeType":"contains","source":1605,"target":1619},{"edgeType":"contains","source":1440,"target":1449},{"edgeType":"contains","source":1473,"target":1483},{"edgeType":"calls","source":5469,"target":170},{"edgeType":"calls","source":1162,"target":503},{"edgeType":"calls","source":1042,"target":1052},{"edgeType":"contains","source":3351,"target":3515},{"edgeType":"contains","source":6604,"target":3097},{"edgeType":"calls","source":354,"target":177},{"edgeType":"calls","source":1041,"target":1078},{"edgeType":"calls","source":4448,"target":4337},{"edgeType":"calls","source":1769,"target":1765},{"edgeType":"calls","source":6801,"target":1184},{"edgeType":"contains","source":349,"target":392},{"edgeType":"imports","source":2494,"target":2872},{"edgeType":"calls","source":1572,"target":1530},{"edgeType":"contains","source":3975,"target":4261},{"edgeType":"contains","source":1605,"target":1624},{"edgeType":"contains","source":4000,"target":4543},{"edgeType":"calls","source":4201,"target":366},{"edgeType":"calls","source":4049,"target":4021},{"edgeType":"contains","source":745,"target":800},{"edgeType":"calls","source":4915,"target":431},{"edgeType":"contains","source":1440,"target":1454},{"edgeType":"contains","source":1473,"target":1488},{"edgeType":"imports","source":1379,"target":1498},{"edgeType":"contains","source":428,"target":6399},{"edgeType":"calls","source":890,"target":474},{"edgeType":"calls","source":895,"target":319},{"edgeType":"contains","source":2662,"target":2682},{"edgeType":"calls","source":2986,"target":2092},{"edgeType":"calls","source":4610,"target":371},{"edgeType":"calls","source":2456,"target":553},{"edgeType":"calls","source":4446,"target":4398},{"edgeType":"contains","source":4478,"target":4523},{"edgeType":"contains","source":2331,"target":2374},{"edgeType":"extends","source":5287,"target":36},{"edgeType":"contains","source":349,"target":391},{"edgeType":"calls","source":2545,"target":965},{"edgeType":"calls","source":4384,"target":2092},{"edgeType":"contains","source":1473,"target":1489},{"edgeType":"contains","source":1605,"target":1625},{"edgeType":"calls","source":6241,"target":548},{"edgeType":"calls","source":6955,"target":6982},{"edgeType":"contains","source":2068,"target":2071},{"edgeType":"contains","source":745,"target":799},{"edgeType":"contains","source":1440,"target":1455},{"edgeType":"contains","source":3351,"target":3521},{"edgeType":"calls","source":890,"target":473},{"edgeType":"calls","source":895,"target":318},{"edgeType":"calls","source":6998,"target":364},{"edgeType":"calls","source":5415,"target":2899},{"edgeType":"contains","source":4706,"target":4854},{"edgeType":"contains","source":349,"target":394},{"edgeType":"calls","source":4610,"target":370},{"edgeType":"contains","source":2331,"target":2371},{"edgeType":"calls","source":4384,"target":2091},{"edgeType":"contains","source":1605,"target":1622},{"edgeType":"calls","source":4201,"target":364},{"edgeType":"contains","source":1440,"target":1452},{"edgeType":"calls","source":6955,"target":6983},{"edgeType":"contains","source":52,"target":88},{"edgeType":"calls","source":5801,"target":445},{"edgeType":"calls","source":6958,"target":548},{"edgeType":"calls","source":3035,"target":571},{"edgeType":"contains","source":745,"target":802},{"edgeType":"imports","source":5410,"target":4432},{"edgeType":"calls","source":3189,"target":3196},{"edgeType":"imports","source":5410,"target":4434},{"edgeType":"calls","source":3892,"target":431},{"edgeType":"contains","source":349,"target":393},{"edgeType":"contains","source":5196,"target":5518},{"edgeType":"calls","source":4610,"target":369},{"edgeType":"contains","source":6557,"target":6664},{"edgeType":"contains","source":3188,"target":3288},{"edgeType":"contains","source":1605,"target":1623},{"edgeType":"calls","source":3618,"target":3640},{"edgeType":"calls","source":5735,"target":5662},{"edgeType":"imports","source":4528,"target":3236},{"edgeType":"calls","source":2131,"target":56},{"edgeType":"contains","source":1440,"target":1453},{"edgeType":"contains","source":1473,"target":1487},{"edgeType":"contains","source":52,"target":87},{"edgeType":"calls","source":1320,"target":886},{"edgeType":"calls","source":4872,"target":4932},{"edgeType":"calls","source":7030,"target":431},{"edgeType":"contains","source":2266,"target":2273},{"edgeType":"contains","source":3351,"target":3519},{"edgeType":"contains","source":4380,"target":4388},{"edgeType":"contains","source":2599,"target":3577},{"edgeType":"calls","source":2986,"target":2091},{"edgeType":"contains","source":6604,"target":3093},{"edgeType":"calls","source":6998,"target":366},{"edgeType":"calls","source":890,"target":475},{"edgeType":"calls","source":3226,"target":3107},{"edgeType":"calls","source":5138,"target":5142},{"edgeType":"contains","source":745,"target":801},{"edgeType":"imports","source":5380,"target":78},{"edgeType":"contains","source":3013,"target":4457},{"edgeType":"contains","source":5754,"target":6164},{"edgeType":"contains","source":1732,"target":1886},{"edgeType":"imports","source":4528,"target":49},{"edgeType":"contains","source":349,"target":363},{"edgeType":"contains","source":5040,"target":5043},{"edgeType":"contains","source":1031,"target":1419},{"edgeType":"contains","source":1076,"target":1081},{"edgeType":"calls","source":2305,"target":2091},{"edgeType":"calls","source":6658,"target":303},{"edgeType":"calls","source":6462,"target":2151},{"edgeType":"calls","source":4220,"target":4035},{"edgeType":"contains","source":4115,"target":4121},{"edgeType":"imports","source":4619,"target":4627},{"edgeType":"contains","source":30,"target":2853},{"edgeType":"calls","source":5093,"target":2341},{"edgeType":"calls","source":1003,"target":171},{"edgeType":"imports","source":130,"target":2142},{"edgeType":"contains","source":349,"target":362},{"edgeType":"contains","source":3013,"target":4458},{"edgeType":"contains","source":6476,"target":7038},{"edgeType":"calls","source":6658,"target":304},{"edgeType":"calls","source":4679,"target":4603},{"edgeType":"calls","source":1808,"target":584},{"edgeType":"contains","source":5910,"target":3443},{"edgeType":"imports","source":1814,"target":1732},{"edgeType":"contains","source":6956,"target":6957},{"edgeType":"calls","source":2305,"target":2092},{"edgeType":"calls","source":347,"target":422},{"edgeType":"contains","source":1379,"target":2260},{"edgeType":"imports","source":1415,"target":1417},{"edgeType":"contains","source":6097,"target":6103},{"edgeType":"extends","source":4131,"target":4132},{"edgeType":"calls","source":5630,"target":1548},{"edgeType":"contains","source":6064,"target":6069},{"edgeType":"calls","source":1003,"target":170},{"edgeType":"calls","source":7139,"target":1249},{"edgeType":"calls","source":3227,"target":2047},{"edgeType":"contains","source":6476,"target":7039},{"edgeType":"extends","source":6616,"target":36},{"edgeType":"calls","source":1748,"target":333},{"edgeType":"contains","source":977,"target":981},{"edgeType":"contains","source":5040,"target":5041},{"edgeType":"contains","source":3241,"target":3729},{"edgeType":"contains","source":1907,"target":2801},{"edgeType":"contains","source":6064,"target":6070},{"edgeType":"calls","source":2848,"target":1112},{"edgeType":"contains","source":2591,"target":2738},{"edgeType":"contains","source":30,"target":2855},{"edgeType":"calls","source":1586,"target":1126},{"edgeType":"calls","source":5630,"target":1547},{"edgeType":"calls","source":7139,"target":1250},{"edgeType":"contains","source":349,"target":365},{"edgeType":"contains","source":977,"target":980},{"edgeType":"calls","source":3851,"target":3845},{"edgeType":"imports","source":3166,"target":1043},{"edgeType":"contains","source":1076,"target":1082},{"edgeType":"contains","source":6476,"target":7040},{"edgeType":"calls","source":6694,"target":4475},{"edgeType":"calls","source":1685,"target":171},{"edgeType":"calls","source":1748,"target":332},{"edgeType":"contains","source":3013,"target":4456},{"edgeType":"calls","source":4246,"target":56},{"edgeType":"contains","source":4839,"target":4928},{"edgeType":"calls","source":746,"target":740},{"edgeType":"contains","source":3,"target":520},{"edgeType":"calls","source":2848,"target":1113},{"edgeType":"calls","source":1685,"target":170},{"edgeType":"imports","source":130,"target":2141},{"edgeType":"calls","source":5325,"target":431},{"edgeType":"calls","source":5630,"target":1546},{"edgeType":"calls","source":1208,"target":1216},{"edgeType":"calls","source":1175,"target":1177},{"edgeType":"calls","source":485,"target":369},{"edgeType":"calls","source":1135,"target":303},{"edgeType":"extends","source":3820,"target":36},{"edgeType":"contains","source":977,"target":983},{"edgeType":"imports","source":4459,"target":78},{"edgeType":"imports","source":6539,"target":78},{"edgeType":"calls","source":1093,"target":548},{"edgeType":"calls","source":2874,"target":303},{"edgeType":"calls","source":2533,"target":304},{"edgeType":"contains","source":3975,"target":4237},{"edgeType":"imports","source":1379,"target":1473},{"edgeType":"calls","source":2874,"target":304},{"edgeType":"contains","source":6097,"target":6098},{"edgeType":"contains","source":4558,"target":4133},{"edgeType":"calls","source":1824,"target":84},{"edgeType":"calls","source":6694,"target":4477},{"edgeType":"calls","source":5630,"target":1545},{"edgeType":"contains","source":349,"target":367},{"edgeType":"calls","source":485,"target":368},{"edgeType":"calls","source":3227,"target":2046},{"edgeType":"imports","source":4459,"target":79},{"edgeType":"contains","source":977,"target":982},{"edgeType":"contains","source":4875,"target":4876},{"edgeType":"extends","source":5218,"target":36},{"edgeType":"calls","source":5013,"target":588},{"edgeType":"calls","source":4841,"target":4863},{"edgeType":"contains","source":6064,"target":6065},{"edgeType":"contains","source":3775,"target":5151},{"edgeType":"calls","source":1412,"target":171},{"edgeType":"contains","source":4432,"target":4867},{"edgeType":"calls","source":7072,"target":1216},{"edgeType":"contains","source":321,"target":177},{"edgeType":"calls","source":6902,"target":144},{"edgeType":"contains","source":6656,"target":6739},{"edgeType":"calls","source":7032,"target":342},{"edgeType":"calls","source":5670,"target":304},{"edgeType":"calls","source":3223,"target":3224},{"edgeType":"calls","source":4916,"target":422},{"edgeType":"contains","source":977,"target":985},{"edgeType":"calls","source":2763,"target":571},{"edgeType":"calls","source":347,"target":421},{"edgeType":"calls","source":485,"target":371},{"edgeType":"contains","source":3975,"target":4235},{"edgeType":"calls","source":2923,"target":897},{"edgeType":"contains","source":6064,"target":6066},{"edgeType":"calls","source":2251,"target":588},{"edgeType":"calls","source":5670,"target":303},{"edgeType":"contains","source":4432,"target":4866},{"edgeType":"calls","source":6728,"target":6596},{"edgeType":"calls","source":1175,"target":1178},{"edgeType":"calls","source":485,"target":370},{"edgeType":"imports","source":2581,"target":147},{"edgeType":"contains","source":5754,"target":6163},{"edgeType":"contains","source":977,"target":984},{"edgeType":"calls","source":1135,"target":304},{"edgeType":"calls","source":1109,"target":1110},{"edgeType":"imports","source":6539,"target":79},{"edgeType":"contains","source":2860,"target":2861},{"edgeType":"calls","source":4230,"target":548},{"edgeType":"calls","source":4620,"target":84},{"edgeType":"calls","source":2533,"target":303},{"edgeType":"calls","source":4916,"target":421},{"edgeType":"contains","source":6064,"target":6067},{"edgeType":"contains","source":1836,"target":1837},{"edgeType":"imports","source":2736,"target":2741},{"edgeType":"calls","source":6527,"target":144},{"edgeType":"contains","source":713,"target":715},{"edgeType":"calls","source":1175,"target":1173},{"edgeType":"calls","source":1422,"target":915},{"edgeType":"contains","source":977,"target":987},{"edgeType":"calls","source":6274,"target":5889},{"edgeType":"calls","source":3128,"target":2996},{"edgeType":"calls","source":2572,"target":148},{"edgeType":"calls","source":2962,"target":1799},{"edgeType":"contains","source":1076,"target":1089},{"edgeType":"calls","source":3026,"target":2987},{"edgeType":"contains","source":5196,"target":5500},{"edgeType":"contains","source":6656,"target":6750},{"edgeType":"imports","source":2494,"target":2859},{"edgeType":"calls","source":4336,"target":431},{"edgeType":"contains","source":4432,"target":4872},{"edgeType":"calls","source":5300,"target":144},{"edgeType":"imports","source":6610,"target":1036},{"edgeType":"calls","source":7058,"target":596},{"edgeType":"calls","source":3487,"target":3494},{"edgeType":"calls","source":6868,"target":144},{"edgeType":"calls","source":6786,"target":572},{"edgeType":"calls","source":3295,"target":3105},{"edgeType":"calls","source":485,"target":364},{"edgeType":"contains","source":977,"target":986},{"edgeType":"contains","source":6656,"target":6752},{"edgeType":"calls","source":5220,"target":509},{"edgeType":"calls","source":2370,"target":1126},{"edgeType":"calls","source":2163,"target":144},{"edgeType":"contains","source":6064,"target":6077},{"edgeType":"calls","source":1770,"target":1753},{"edgeType":"calls","source":6786,"target":573},{"edgeType":"calls","source":1241,"target":1243},{"edgeType":"calls","source":4016,"target":4006},{"edgeType":"contains","source":713,"target":717},{"edgeType":"calls","source":6463,"target":1073},{"edgeType":"calls","source":6493,"target":143},{"edgeType":"calls","source":1354,"target":911},{"edgeType":"calls","source":1142,"target":84},{"edgeType":"calls","source":1140,"target":146},{"edgeType":"calls","source":2572,"target":146},{"edgeType":"calls","source":2601,"target":304},{"edgeType":"contains","source":2761,"target":2762},{"edgeType":"contains","source":1076,"target":1091},{"edgeType":"contains","source":977,"target":989},{"edgeType":"calls","source":5220,"target":508},{"edgeType":"contains","source":349,"target":373},{"edgeType":"contains","source":4706,"target":4832},{"edgeType":"calls","source":2326,"target":1430},{"edgeType":"calls","source":1412,"target":170},{"edgeType":"imports","source":6604,"target":167},{"edgeType":"imports","source":4619,"target":4621},{"edgeType":"calls","source":580,"target":592},{"edgeType":"calls","source":4881,"target":445},{"edgeType":"calls","source":7065,"target":6724},{"edgeType":"calls","source":4753,"target":4413},{"edgeType":"calls","source":1354,"target":910},{"edgeType":"contains","source":713,"target":716},{"edgeType":"calls","source":485,"target":366},{"edgeType":"calls","source":3475,"target":1751},{"edgeType":"contains","source":977,"target":988},{"edgeType":"calls","source":2572,"target":147},{"edgeType":"contains","source":4875,"target":4878},{"edgeType":"contains","source":3351,"target":3498},{"edgeType":"calls","source":3824,"target":445},{"edgeType":"contains","source":5285,"target":5909},{"edgeType":"calls","source":5220,"target":507},{"edgeType":"contains","source":2331,"target":2351},{"edgeType":"contains","source":181,"target":295},{"edgeType":"contains","source":4115,"target":4126},{"edgeType":"contains","source":745,"target":784},{"edgeType":"contains","source":713,"target":719},{"edgeType":"calls","source":6445,"target":584},{"edgeType":"extends","source":1297,"target":36},{"edgeType":"contains","source":4307,"target":5580},{"edgeType":"contains","source":977,"target":991},{"edgeType":"calls","source":5220,"target":505},{"edgeType":"contains","source":2662,"target":2666},{"edgeType":"calls","source":5056,"target":304},{"edgeType":"calls","source":5220,"target":506},{"edgeType":"calls","source":5299,"target":171},{"edgeType":"calls","source":2326,"target":1428},{"edgeType":"contains","source":2331,"target":2356},{"edgeType":"calls","source":1602,"target":1673},{"edgeType":"contains","source":349,"target":375},{"edgeType":"contains","source":3975,"target":4245},{"edgeType":"imports","source":4619,"target":4623},{"edgeType":"contains","source":1605,"target":1608},{"edgeType":"contains","source":181,"target":298},{"edgeType":"contains","source":4000,"target":4527},{"edgeType":"calls","source":2265,"target":2262},{"edgeType":"contains","source":1836,"target":1846},{"edgeType":"contains","source":745,"target":783},{"edgeType":"calls","source":4051,"target":3977},{"edgeType":"contains","source":713,"target":718},{"edgeType":"calls","source":4881,"target":443},{"edgeType":"calls","source":2606,"target":148},{"edgeType":"contains","source":4307,"target":5579},{"edgeType":"calls","source":2601,"target":303},{"edgeType":"calls","source":5504,"target":157},{"edgeType":"calls","source":5220,"target":504},{"edgeType":"calls","source":5056,"target":303},{"edgeType":"contains","source":4611,"target":4612},{"edgeType":"calls","source":1195,"target":548},{"edgeType":"contains","source":977,"target":990},{"edgeType":"calls","source":5299,"target":170},{"edgeType":"calls","source":5222,"target":1500},{"edgeType":"contains","source":3836,"target":4325},{"edgeType":"contains","source":1076,"target":1092},{"edgeType":"calls","source":3155,"target":1099},{"edgeType":"calls","source":3824,"target":443},{"edgeType":"contains","source":349,"target":374},{"edgeType":"calls","source":6728,"target":6603},{"edgeType":"calls","source":6860,"target":2511},{"edgeType":"calls","source":2326,"target":1429},{"edgeType":"contains","source":6651,"target":6902},{"edgeType":"contains","source":3975,"target":4244},{"edgeType":"imports","source":4619,"target":4624},{"edgeType":"contains","source":1605,"target":1609},{"edgeType":"contains","source":1302,"target":6770},{"edgeType":"contains","source":5,"target":4699},{"edgeType":"contains","source":3013,"target":4467},{"edgeType":"calls","source":5061,"target":147},{"edgeType":"contains","source":745,"target":786},{"edgeType":"contains","source":713,"target":721},{"edgeType":"calls","source":5220,"target":503},{"edgeType":"contains","source":349,"target":377},{"edgeType":"contains","source":1076,"target":1095},{"edgeType":"contains","source":977,"target":993},{"edgeType":"contains","source":2331,"target":2354},{"edgeType":"calls","source":2326,"target":1426},{"edgeType":"imports","source":4619,"target":4625},{"edgeType":"contains","source":1605,"target":1606},{"edgeType":"calls","source":1793,"target":1039},{"edgeType":"contains","source":713,"target":720},{"edgeType":"calls","source":4992,"target":171},{"edgeType":"imports","source":3726,"target":598},{"edgeType":"contains","source":3351,"target":3502},{"edgeType":"contains","source":2662,"target":2665},{"edgeType":"imports","source":2843,"target":2604},{"edgeType":"contains","source":977,"target":992},{"edgeType":"calls","source":5220,"target":502},{"edgeType":"contains","source":745,"target":785},{"edgeType":"contains","source":6656,"target":6749},{"edgeType":"imports","source":4619,"target":4626},{"edgeType":"contains","source":349,"target":376},{"edgeType":"contains","source":5285,"target":5913},{"edgeType":"calls","source":6749,"target":2783},{"edgeType":"contains","source":1605,"target":1607},{"edgeType":"calls","source":4040,"target":1144},{"edgeType":"calls","source":2326,"target":1427},{"edgeType":"calls","source":4116,"target":4170},{"edgeType":"contains","source":3173,"target":3180},{"edgeType":"calls","source":5399,"target":4565},{"edgeType":"contains","source":1037,"target":1745},{"edgeType":"contains","source":3626,"target":3936},{"edgeType":"calls","source":1793,"target":1132},{"edgeType":"calls","source":1078,"target":1099},{"edgeType":"contains","source":1379,"target":1714},{"edgeType":"contains","source":4717,"target":4997},{"edgeType":"contains","source":1907,"target":2259},{"edgeType":"contains","source":1984,"target":1986},{"edgeType":"calls","source":2634,"target":431},{"edgeType":"calls","source":2295,"target":370},{"edgeType":"calls","source":5739,"target":5652},{"edgeType":"calls","source":5529,"target":4762},{"edgeType":"calls","source":4184,"target":1006},{"edgeType":"calls","source":3284,"target":366},{"edgeType":"contains","source":5287,"target":5296},{"edgeType":"contains","source":3460,"target":3796},{"edgeType":"calls","source":1142,"target":171},{"edgeType":"contains","source":6047,"target":6051},{"edgeType":"calls","source":550,"target":554},{"edgeType":"calls","source":2295,"target":371},{"edgeType":"contains","source":4717,"target":4996},{"edgeType":"calls","source":144,"target":456},{"edgeType":"contains","source":6245,"target":6255},{"edgeType":"contains","source":1037,"target":1747},{"edgeType":"imports","source":1379,"target":203},{"edgeType":"contains","source":3173,"target":3178},{"edgeType":"calls","source":6998,"target":6793},{"edgeType":"calls","source":3024,"target":3137},{"edgeType":"contains","source":5616,"target":5671},{"edgeType":"calls","source":1080,"target":1040},{"edgeType":"calls","source":5408,"target":56},{"edgeType":"calls","source":2499,"target":2500},{"edgeType":"contains","source":6047,"target":6052},{"edgeType":"calls","source":6087,"target":147},{"edgeType":"contains","source":1302,"target":6213},{"edgeType":"extends","source":3847,"target":36},{"edgeType":"calls","source":4388,"target":4193},{"edgeType":"calls","source":2295,"target":368},{"edgeType":"contains","source":3173,"target":3179},{"edgeType":"imports","source":1379,"target":202},{"edgeType":"contains","source":1037,"target":1746},{"edgeType":"calls","source":3284,"target":364},{"edgeType":"calls","source":5371,"target":144},{"edgeType":"contains","source":1415,"target":1654},{"edgeType":"calls","source":5877,"target":5599},{"edgeType":"contains","source":1984,"target":1985},{"edgeType":"contains","source":4091,"target":4317},{"edgeType":"contains","source":4196,"target":4233},{"edgeType":"contains","source":4131,"target":4134},{"edgeType":"contains","source":4307,"target":5020},{"edgeType":"calls","source":5739,"target":5649},{"edgeType":"calls","source":2295,"target":369},{"edgeType":"contains","source":4717,"target":4994},{"edgeType":"contains","source":4691,"target":4743},{"edgeType":"contains","source":200,"target":213},{"edgeType":"calls","source":2982,"target":209},{"edgeType":"contains","source":3828,"target":2963},{"edgeType":"contains","source":2843,"target":2844},{"edgeType":"contains","source":3173,"target":3184},{"edgeType":"contains","source":1037,"target":1749},{"edgeType":"calls","source":3128,"target":968},{"edgeType":"contains","source":3236,"target":3345},{"edgeType":"contains","source":5780,"target":5866},{"edgeType":"contains","source":3367,"target":3513},{"edgeType":"calls","source":1477,"target":354},{"edgeType":"contains","source":5748,"target":5801},{"edgeType":"contains","source":1984,"target":1990},{"edgeType":"contains","source":2742,"target":2803},{"edgeType":"contains","source":2736,"target":2989},{"edgeType":"calls","source":6992,"target":6982},{"edgeType":"imports","source":3814,"target":4003},{"edgeType":"contains","source":3834,"target":3835},{"edgeType":"contains","source":33,"target":105},{"edgeType":"contains","source":3867,"target":3869},{"edgeType":"calls","source":2704,"target":371},{"edgeType":"calls","source":2295,"target":366},{"edgeType":"contains","source":2961,"target":3415},{"edgeType":"calls","source":213,"target":426},{"edgeType":"calls","source":2982,"target":210},{"edgeType":"calls","source":4995,"target":171},{"edgeType":"calls","source":1274,"target":304},{"edgeType":"contains","source":5550,"target":5598},{"edgeType":"contains","source":5617,"target":5635},{"edgeType":"contains","source":3949,"target":4497},{"edgeType":"contains","source":3981,"target":4562},{"edgeType":"contains","source":1947,"target":2081},{"edgeType":"calls","source":1274,"target":303},{"edgeType":"calls","source":6992,"target":6983},{"edgeType":"contains","source":3867,"target":3868},{"edgeType":"contains","source":30,"target":4425},{"edgeType":"calls","source":4995,"target":170},{"edgeType":"calls","source":5200,"target":157},{"edgeType":"calls","source":7078,"target":1146},{"edgeType":"calls","source":3156,"target":1155},{"edgeType":"contains","source":3173,"target":3182},{"edgeType":"calls","source":3420,"target":371},{"edgeType":"contains","source":5287,"target":5299},{"edgeType":"calls","source":4723,"target":146},{"edgeType":"calls","source":1142,"target":170},{"edgeType":"calls","source":2565,"target":2564},{"edgeType":"extends","source":5908,"target":5910},{"edgeType":"contains","source":4717,"target":4999},{"edgeType":"calls","source":3195,"target":3117},{"edgeType":"contains","source":6245,"target":6252},{"edgeType":"calls","source":4070,"target":304},{"edgeType":"calls","source":4078,"target":56},{"edgeType":"contains","source":4196,"target":4238},{"edgeType":"calls","source":2704,"target":369},{"edgeType":"calls","source":2610,"target":2226},{"edgeType":"contains","source":162,"target":3507},{"edgeType":"calls","source":2862,"target":2871},{"edgeType":"calls","source":2295,"target":364},{"edgeType":"contains","source":5780,"target":5869},{"edgeType":"calls","source":2268,"target":144},{"edgeType":"contains","source":4957,"target":4958},{"edgeType":"calls","source":6602,"target":4276},{"edgeType":"calls","source":6533,"target":6415},{"edgeType":"contains","source":3173,"target":3183},{"edgeType":"calls","source":6733,"target":215},{"edgeType":"calls","source":7078,"target":1147},{"edgeType":"calls","source":6998,"target":2570},{"edgeType":"contains","source":5287,"target":5298},{"edgeType":"contains","source":1037,"target":1750},{"edgeType":"calls","source":6633,"target":144},{"edgeType":"extends","source":2756,"target":36},{"edgeType":"contains","source":3236,"target":3344},{"edgeType":"contains","source":1379,"target":1717},{"edgeType":"contains","source":3367,"target":3510},{"edgeType":"contains","source":4717,"target":4998},{"edgeType":"contains","source":6047,"target":6049},{"edgeType":"calls","source":4042,"target":3287},{"edgeType":"contains","source":1907,"target":2262},{"edgeType":"calls","source":1986,"target":431},{"edgeType":"calls","source":7078,"target":1148},{"edgeType":"calls","source":4007,"target":144},{"edgeType":"contains","source":4558,"target":4642},{"edgeType":"calls","source":2704,"target":370},{"edgeType":"calls","source":2610,"target":2227},{"edgeType":"extends","source":3813,"target":36},{"edgeType":"calls","source":3729,"target":303},{"edgeType":"calls","source":4249,"target":4267},{"edgeType":"calls","source":2862,"target":2868},{"edgeType":"contains","source":3626,"target":3944},{"edgeType":"calls","source":3156,"target":1153},{"edgeType":"calls","source":6602,"target":4277},{"edgeType":"contains","source":2961,"target":3418},{"edgeType":"calls","source":1538,"target":573},{"edgeType":"calls","source":6546,"target":2842},{"edgeType":"calls","source":6435,"target":5226},{"edgeType":"calls","source":550,"target":547},{"edgeType":"contains","source":6604,"target":6760},{"edgeType":"calls","source":3420,"target":368},{"edgeType":"contains","source":5380,"target":5593},{"edgeType":"contains","source":4558,"target":4649},{"edgeType":"calls","source":1142,"target":164},{"edgeType":"contains","source":3981,"target":4567},{"edgeType":"contains","source":4957,"target":4964},{"edgeType":"calls","source":3729,"target":304},{"edgeType":"calls","source":6728,"target":6714},{"edgeType":"calls","source":4249,"target":4266},{"edgeType":"contains","source":6437,"target":5596},{"edgeType":"calls","source":5092,"target":4559},{"edgeType":"calls","source":6602,"target":4278},{"edgeType":"calls","source":1538,"target":572},{"edgeType":"calls","source":3420,"target":370},{"edgeType":"imports","source":153,"target":166},{"edgeType":"calls","source":1739,"target":1740},{"edgeType":"calls","source":550,"target":546},{"edgeType":"calls","source":4070,"target":303},{"edgeType":"calls","source":2565,"target":2563},{"edgeType":"contains","source":6604,"target":6761},{"edgeType":"calls","source":3420,"target":369},{"edgeType":"contains","source":5287,"target":5304},{"edgeType":"calls","source":7033,"target":431},{"edgeType":"contains","source":1654,"target":1655},{"edgeType":"contains","source":3735,"target":3736},{"edgeType":"calls","source":2704,"target":368},{"edgeType":"calls","source":2610,"target":2225},{"edgeType":"contains","source":3981,"target":4566},{"edgeType":"calls","source":2370,"target":148},{"edgeType":"contains","source":41,"target":4091},{"edgeType":"contains","source":2961,"target":3416},{"edgeType":"calls","source":4249,"target":4265},{"edgeType":"calls","source":213,"target":425},{"edgeType":"calls","source":2265,"target":1289},{"edgeType":"contains","source":3626,"target":3942},{"edgeType":"calls","source":3860,"target":2582},{"edgeType":"contains","source":2742,"target":2806},{"edgeType":"calls","source":6602,"target":4279},{"edgeType":"calls","source":6729,"target":342},{"edgeType":"imports","source":2201,"target":2212},{"edgeType":"contains","source":6604,"target":6762},{"edgeType":"calls","source":3420,"target":366},{"edgeType":"contains","source":3270,"target":3350},{"edgeType":"calls","source":4170,"target":371},{"edgeType":"contains","source":1907,"target":2265},{"edgeType":"contains","source":2736,"target":2991},{"edgeType":"calls","source":4447,"target":4470},{"edgeType":"calls","source":600,"target":56},{"edgeType":"calls","source":2862,"target":2866},{"edgeType":"calls","source":4725,"target":1137},{"edgeType":"calls","source":6602,"target":4280},{"edgeType":"calls","source":213,"target":424},{"edgeType":"calls","source":6827,"target":1533},{"edgeType":"calls","source":4444,"target":333},{"edgeType":"calls","source":4317,"target":1099},{"edgeType":"calls","source":6940,"target":144},{"edgeType":"calls","source":5901,"target":5904},{"edgeType":"contains","source":2744,"target":2745},{"edgeType":"calls","source":1721,"target":1243},{"edgeType":"calls","source":1524,"target":1008},{"edgeType":"contains","source":6604,"target":6764},{"edgeType":"calls","source":1948,"target":548},{"edgeType":"contains","source":3981,"target":4564},{"edgeType":"contains","source":6604,"target":6763},{"edgeType":"calls","source":6837,"target":6509},{"edgeType":"imports","source":2961,"target":2963},{"edgeType":"calls","source":1142,"target":165},{"edgeType":"calls","source":6969,"target":303},{"edgeType":"contains","source":340,"target":1163},{"edgeType":"contains","source":3867,"target":3870},{"edgeType":"contains","source":1947,"target":2083},{"edgeType":"contains","source":1984,"target":1993},{"edgeType":"imports","source":3867,"target":3408},{"edgeType":"contains","source":4196,"target":4241},{"edgeType":"calls","source":597,"target":148},{"edgeType":"calls","source":2704,"target":366},{"edgeType":"calls","source":3023,"target":3158},{"edgeType":"calls","source":2265,"target":1287},{"edgeType":"calls","source":6602,"target":4281},{"edgeType":"calls","source":4444,"target":332},{"edgeType":"imports","source":2494,"target":2641},{"edgeType":"contains","source":4668,"target":1244},{"edgeType":"calls","source":4170,"target":369},{"edgeType":"contains","source":6047,"target":6054},{"edgeType":"calls","source":2090,"target":369},{"edgeType":"contains","source":3173,"target":3192},{"edgeType":"contains","source":4668,"target":1243},{"edgeType":"contains","source":5287,"target":5309},{"edgeType":"calls","source":3420,"target":364},{"edgeType":"contains","source":6245,"target":6258},{"edgeType":"calls","source":3311,"target":572},{"edgeType":"calls","source":6969,"target":304},{"edgeType":"contains","source":1984,"target":1998},{"edgeType":"calls","source":4959,"target":4451},{"edgeType":"contains","source":1555,"target":1556},{"edgeType":"calls","source":1142,"target":160},{"edgeType":"contains","source":1654,"target":1658},{"edgeType":"contains","source":42,"target":1947},{"edgeType":"calls","source":3023,"target":3159},{"edgeType":"calls","source":2265,"target":1288},{"edgeType":"calls","source":4595,"target":935},{"edgeType":"contains","source":5550,"target":5606},{"edgeType":"calls","source":2370,"target":147},{"edgeType":"calls","source":4482,"target":210},{"edgeType":"calls","source":144,"target":443},{"edgeType":"contains","source":2961,"target":3423},{"edgeType":"calls","source":5901,"target":5902},{"edgeType":"contains","source":2736,"target":2999},{"edgeType":"calls","source":2090,"target":368},{"edgeType":"calls","source":5471,"target":4433},{"edgeType":"calls","source":2704,"target":364},{"edgeType":"calls","source":2626,"target":1725},{"edgeType":"calls","source":4170,"target":370},{"edgeType":"calls","source":3311,"target":573},{"edgeType":"calls","source":5511,"target":2136},{"edgeType":"contains","source":1984,"target":1999},{"edgeType":"calls","source":2575,"target":1192},{"edgeType":"calls","source":1142,"target":159},{"edgeType":"calls","source":4482,"target":209},{"edgeType":"contains","source":5,"target":5211},{"edgeType":"calls","source":4595,"target":934},{"edgeType":"calls","source":2265,"target":1285},{"edgeType":"calls","source":2090,"target":371},{"edgeType":"calls","source":3573,"target":3018},{"edgeType":"contains","source":1984,"target":1996},{"edgeType":"calls","source":1163,"target":568},{"edgeType":"contains","source":1654,"target":1656},{"edgeType":"calls","source":6935,"target":303},{"edgeType":"contains","source":2070,"target":2501},{"edgeType":"contains","source":1947,"target":2086},{"edgeType":"imports","source":1415,"target":147},{"edgeType":"calls","source":6631,"target":6556},{"edgeType":"contains","source":3,"target":5272},{"edgeType":"calls","source":2265,"target":1286},{"edgeType":"calls","source":144,"target":445},{"edgeType":"calls","source":4170,"target":368},{"edgeType":"calls","source":2090,"target":370},{"edgeType":"contains","source":1037,"target":1758},{"edgeType":"contains","source":6604,"target":6759},{"edgeType":"calls","source":4756,"target":171},{"edgeType":"contains","source":1654,"target":1657},{"edgeType":"calls","source":6935,"target":304},{"edgeType":"calls","source":1142,"target":161},{"edgeType":"contains","source":3981,"target":4568},{"edgeType":"calls","source":4993,"target":4451},{"edgeType":"extends","source":6097,"target":36},{"edgeType":"contains","source":6286,"target":3909},{"edgeType":"contains","source":4192,"target":4343},{"edgeType":"contains","source":4196,"target":4219},{"edgeType":"calls","source":1723,"target":148},{"edgeType":"contains","source":3954,"target":4322},{"edgeType":"contains","source":2898,"target":4289},{"edgeType":"calls","source":6551,"target":548},{"edgeType":"calls","source":483,"target":534},{"edgeType":"calls","source":2808,"target":339},{"edgeType":"contains","source":4988,"target":5036},{"edgeType":"calls","source":5237,"target":5375},{"edgeType":"contains","source":3626,"target":3920},{"edgeType":"calls","source":5876,"target":364},{"edgeType":"contains","source":4717,"target":4980},{"edgeType":"contains","source":6375,"target":6436},{"edgeType":"calls","source":1418,"target":1145},{"edgeType":"contains","source":6476,"target":6477},{"edgeType":"calls","source":4841,"target":4966},{"edgeType":"calls","source":4863,"target":56},{"edgeType":"contains","source":2898,"target":4290},{"edgeType":"calls","source":947,"target":948},{"edgeType":"calls","source":5237,"target":5374},{"edgeType":"contains","source":4091,"target":4301},{"edgeType":"contains","source":4196,"target":4217},{"edgeType":"contains","source":33,"target":86},{"edgeType":"calls","source":142,"target":537},{"edgeType":"contains","source":2898,"target":4287},{"edgeType":"imports","source":5473,"target":3293},{"edgeType":"contains","source":5748,"target":5791},{"edgeType":"contains","source":6476,"target":6478},{"edgeType":"calls","source":2808,"target":337},{"edgeType":"calls","source":1209,"target":1285},{"edgeType":"calls","source":6827,"target":6793},{"edgeType":"contains","source":3626,"target":3918},{"edgeType":"contains","source":3365,"target":4608},{"edgeType":"contains","source":2898,"target":4288},{"edgeType":"calls","source":3986,"target":3987},{"edgeType":"calls","source":1813,"target":1587},{"edgeType":"calls","source":4144,"target":146},{"edgeType":"calls","source":4243,"target":248},{"edgeType":"calls","source":2808,"target":338},{"edgeType":"contains","source":6476,"target":6479},{"edgeType":"contains","source":5748,"target":5792},{"edgeType":"contains","source":3626,"target":3917},{"edgeType":"calls","source":1209,"target":1284},{"edgeType":"contains","source":4558,"target":4629},{"edgeType":"contains","source":6375,"target":6431},{"edgeType":"calls","source":4207,"target":304},{"edgeType":"contains","source":6539,"target":6632},{"edgeType":"calls","source":144,"target":469},{"edgeType":"calls","source":6644,"target":5069},{"edgeType":"contains","source":3371,"target":3373},{"edgeType":"extends","source":4665,"target":36},{"edgeType":"contains","source":2599,"target":2993},{"edgeType":"calls","source":1131,"target":525},{"edgeType":"contains","source":4196,"target":4222},{"edgeType":"contains","source":2314,"target":2315},{"edgeType":"calls","source":454,"target":371},{"edgeType":"contains","source":3626,"target":3923},{"edgeType":"contains","source":139,"target":3143},{"edgeType":"contains","source":4988,"target":5039},{"edgeType":"calls","source":2931,"target":1808},{"edgeType":"calls","source":3677,"target":879},{"edgeType":"calls","source":3123,"target":84},{"edgeType":"calls","source":3008,"target":2592},{"edgeType":"contains","source":5748,"target":5786},{"edgeType":"calls","source":6644,"target":5070},{"edgeType":"contains","source":5452,"target":5453},{"edgeType":"calls","source":1041,"target":147},{"edgeType":"calls","source":1723,"target":146},{"edgeType":"contains","source":6375,"target":6433},{"edgeType":"contains","source":30,"target":4411},{"edgeType":"contains","source":6539,"target":6634},{"edgeType":"calls","source":4223,"target":4035},{"edgeType":"contains","source":4988,"target":5038},{"edgeType":"calls","source":6998,"target":2553},{"edgeType":"calls","source":5712,"target":157},{"edgeType":"contains","source":5748,"target":5787},{"edgeType":"calls","source":6644,"target":5071},{"edgeType":"calls","source":1041,"target":146},{"edgeType":"calls","source":7135,"target":421},{"edgeType":"calls","source":3866,"target":304},{"edgeType":"calls","source":2780,"target":144},{"edgeType":"contains","source":4192,"target":4344},{"edgeType":"calls","source":4207,"target":303},{"edgeType":"contains","source":340,"target":1143},{"edgeType":"calls","source":2193,"target":372},{"edgeType":"contains","source":5748,"target":5788},{"edgeType":"contains","source":4988,"target":5037},{"edgeType":"extends","source":2244,"target":36},{"edgeType":"calls","source":3866,"target":303},{"edgeType":"contains","source":5463,"target":2996},{"edgeType":"calls","source":6791,"target":1572},{"edgeType":"calls","source":6644,"target":5072},{"edgeType":"calls","source":6485,"target":1545},{"edgeType":"calls","source":3193,"target":3194},{"edgeType":"calls","source":1178,"target":1179},{"edgeType":"calls","source":7135,"target":422},{"edgeType":"calls","source":4241,"target":303},{"edgeType":"contains","source":5748,"target":5797},{"edgeType":"calls","source":454,"target":368},{"edgeType":"contains","source":4196,"target":4227},{"edgeType":"contains","source":3954,"target":4330},{"edgeType":"contains","source":5617,"target":5630},{"edgeType":"contains","source":6245,"target":6246},{"edgeType":"contains","source":6375,"target":6444},{"edgeType":"contains","source":4717,"target":4989},{"edgeType":"calls","source":6644,"target":5073},{"edgeType":"calls","source":5632,"target":4749},{"edgeType":"calls","source":1722,"target":170},{"edgeType":"calls","source":5491,"target":4892},{"edgeType":"calls","source":6485,"target":1546},{"edgeType":"contains","source":3954,"target":4329},{"edgeType":"contains","source":5353,"target":5356},{"edgeType":"contains","source":5287,"target":5288},{"edgeType":"contains","source":33,"target":91},{"edgeType":"calls","source":1111,"target":84},{"edgeType":"calls","source":4241,"target":304},{"edgeType":"calls","source":4976,"target":5001},{"edgeType":"contains","source":2898,"target":3241},{"edgeType":"calls","source":6644,"target":5074},{"edgeType":"contains","source":6375,"target":6445},{"edgeType":"contains","source":6245,"target":6247},{"edgeType":"calls","source":5142,"target":5140},{"edgeType":"contains","source":6476,"target":6485},{"edgeType":"contains","source":2736,"target":2978},{"edgeType":"calls","source":3325,"target":3331},{"edgeType":"calls","source":6485,"target":1547},{"edgeType":"contains","source":3954,"target":4328},{"edgeType":"calls","source":3284,"target":371},{"edgeType":"calls","source":454,"target":370},{"edgeType":"contains","source":33,"target":94},{"edgeType":"calls","source":2801,"target":545},{"edgeType":"calls","source":6808,"target":1048},{"edgeType":"calls","source":6862,"target":431},{"edgeType":"contains","source":5550,"target":5595},{"edgeType":"contains","source":6476,"target":6486},{"edgeType":"contains","source":952,"target":145},{"edgeType":"calls","source":6485,"target":1548},{"edgeType":"contains","source":1947,"target":2066},{"edgeType":"calls","source":1244,"target":1248},{"edgeType":"contains","source":3954,"target":4327},{"edgeType":"contains","source":5463,"target":3001},{"edgeType":"contains","source":2540,"target":596},{"edgeType":"calls","source":4447,"target":4485},{"edgeType":"calls","source":454,"target":369},{"edgeType":"contains","source":5617,"target":5633},{"edgeType":"contains","source":5732,"target":6296},{"edgeType":"calls","source":4305,"target":431},{"edgeType":"calls","source":5673,"target":304},{"edgeType":"calls","source":1722,"target":171},{"edgeType":"contains","source":3173,"target":3176},{"edgeType":"calls","source":454,"target":364},{"edgeType":"calls","source":3284,"target":369},{"edgeType":"calls","source":1100,"target":422},{"edgeType":"calls","source":4919,"target":422},{"edgeType":"calls","source":4751,"target":4573},{"edgeType":"contains","source":3,"target":1027},{"edgeType":"calls","source":3756,"target":535},{"edgeType":"calls","source":1653,"target":1248},{"edgeType":"contains","source":6476,"target":6480},{"edgeType":"calls","source":5673,"target":303},{"edgeType":"calls","source":4029,"target":528},{"edgeType":"calls","source":1411,"target":1350},{"edgeType":"contains","source":3173,"target":3177},{"edgeType":"calls","source":3284,"target":370},{"edgeType":"contains","source":5287,"target":5292},{"edgeType":"calls","source":5032,"target":3260},{"edgeType":"calls","source":1100,"target":421},{"edgeType":"calls","source":2931,"target":1799},{"edgeType":"calls","source":4919,"target":421},{"edgeType":"contains","source":3952,"target":167},{"edgeType":"contains","source":6377,"target":6379},{"edgeType":"imports","source":2201,"target":79},{"edgeType":"contains","source":6476,"target":6481},{"edgeType":"contains","source":5748,"target":5794},{"edgeType":"calls","source":6644,"target":5078},{"edgeType":"contains","source":1037,"target":1739},{"edgeType":"imports","source":6770,"target":79},{"edgeType":"contains","source":951,"target":3352},{"edgeType":"contains","source":3173,"target":3174},{"edgeType":"contains","source":5287,"target":5291},{"edgeType":"contains","source":200,"target":207},{"edgeType":"calls","source":454,"target":366},{"edgeType":"contains","source":3952,"target":166},{"edgeType":"contains","source":33,"target":99},{"edgeType":"contains","source":6377,"target":6380},{"edgeType":"imports","source":2201,"target":78},{"edgeType":"contains","source":5617,"target":5628},{"edgeType":"calls","source":6611,"target":6102},{"edgeType":"contains","source":4717,"target":4991},{"edgeType":"imports","source":4691,"target":49},{"edgeType":"imports","source":6770,"target":78},{"edgeType":"contains","source":1037,"target":1742},{"edgeType":"contains","source":5353,"target":5358},{"edgeType":"calls","source":3284,"target":368},{"edgeType":"calls","source":3311,"target":588},{"edgeType":"contains","source":5748,"target":5796},{"edgeType":"contains","source":2070,"target":2485},{"edgeType":"contains","source":5617,"target":5629},{"edgeType":"contains","source":4196,"target":4229},{"edgeType":"contains","source":6476,"target":6483},{"edgeType":"calls","source":3941,"target":84},{"edgeType":"calls","source":4029,"target":527},{"edgeType":"imports","source":2070,"target":2072},{"edgeType":"contains","source":3205,"target":3212},{"edgeType":"calls","source":6894,"target":469},{"edgeType":"calls","source":3349,"target":431},{"edgeType":"contains","source":1848,"target":1940},{"edgeType":"calls","source":1580,"target":303},{"edgeType":"contains","source":1907,"target":2225},{"edgeType":"calls","source":3219,"target":2347},{"edgeType":"contains","source":5458,"target":6306},{"edgeType":"calls","source":4590,"target":1071},{"edgeType":"calls","source":6734,"target":144},{"edgeType":"calls","source":4413,"target":4444},{"edgeType":"contains","source":4091,"target":1116},{"edgeType":"calls","source":3951,"target":3966},{"edgeType":"extends","source":2075,"target":36},{"edgeType":"calls","source":4401,"target":588},{"edgeType":"calls","source":6358,"target":171},{"edgeType":"contains","source":6471,"target":6614},{"edgeType":"contains","source":2688,"target":212},{"edgeType":"contains","source":6471,"target":6615},{"edgeType":"contains","source":5895,"target":3330},{"edgeType":"contains","source":2898,"target":4274},{"edgeType":"extends","source":3473,"target":36},{"edgeType":"extends","source":6669,"target":6667},{"edgeType":"contains","source":1907,"target":2226},{"edgeType":"contains","source":5550,"target":5569},{"edgeType":"contains","source":5458,"target":6307},{"edgeType":"calls","source":5141,"target":5129},{"edgeType":"contains","source":2147,"target":2186},{"edgeType":"contains","source":1907,"target":2227},{"edgeType":"calls","source":1985,"target":431},{"edgeType":"calls","source":530,"target":84},{"edgeType":"calls","source":4171,"target":318},{"edgeType":"calls","source":6358,"target":170},{"edgeType":"contains","source":926,"target":927},{"edgeType":"contains","source":5285,"target":5324},{"edgeType":"calls","source":2837,"target":445},{"edgeType":"contains","source":3205,"target":3210},{"edgeType":"contains","source":1190,"target":1199},{"edgeType":"calls","source":897,"target":337},{"edgeType":"calls","source":5141,"target":5128},{"edgeType":"calls","source":5288,"target":571},{"edgeType":"calls","source":3219,"target":2345},{"edgeType":"calls","source":3219,"target":2344},{"edgeType":"calls","source":1759,"target":1098},{"edgeType":"contains","source":30,"target":1220},{"edgeType":"calls","source":4376,"target":304},{"edgeType":"calls","source":6135,"target":1797},{"edgeType":"contains","source":4668,"target":1196},{"edgeType":"calls","source":5065,"target":84},{"edgeType":"contains","source":3205,"target":3211},{"edgeType":"calls","source":3566,"target":3216},{"edgeType":"calls","source":4852,"target":4573},{"edgeType":"calls","source":1580,"target":304},{"edgeType":"contains","source":3954,"target":4302},{"edgeType":"contains","source":1989,"target":1796},{"edgeType":"contains","source":1848,"target":1939},{"edgeType":"calls","source":5441,"target":56},{"edgeType":"calls","source":3219,"target":2346},{"edgeType":"calls","source":6569,"target":2091},{"edgeType":"contains","source":30,"target":1219},{"edgeType":"extends","source":336,"target":36},{"edgeType":"calls","source":4376,"target":303},{"edgeType":"calls","source":2837,"target":443},{"edgeType":"contains","source":1190,"target":1201},{"edgeType":"calls","source":6729,"target":303},{"edgeType":"contains","source":599,"target":1552},{"edgeType":"calls","source":6569,"target":2092},{"edgeType":"calls","source":5404,"target":144},{"edgeType":"calls","source":6157,"target":56},{"edgeType":"contains","source":3954,"target":4310},{"edgeType":"contains","source":4091,"target":2177},{"edgeType":"calls","source":3219,"target":2342},{"edgeType":"calls","source":3924,"target":571},{"edgeType":"calls","source":4040,"target":146},{"edgeType":"calls","source":4042,"target":84},{"edgeType":"calls","source":4171,"target":313},{"edgeType":"calls","source":5794,"target":1795},{"edgeType":"calls","source":1720,"target":1243},{"edgeType":"calls","source":5801,"target":5806},{"edgeType":"calls","source":6729,"target":304},{"edgeType":"calls","source":3219,"target":2343},{"edgeType":"contains","source":599,"target":1551},{"edgeType":"contains","source":5550,"target":5565},{"edgeType":"calls","source":4817,"target":371},{"edgeType":"contains","source":1818,"target":1819},{"edgeType":"contains","source":100,"target":108},{"edgeType":"calls","source":4116,"target":4133},{"edgeType":"calls","source":594,"target":210},{"edgeType":"calls","source":2326,"target":1487},{"edgeType":"calls","source":2301,"target":144},{"edgeType":"calls","source":2329,"target":333},{"edgeType":"calls","source":144,"target":421},{"edgeType":"calls","source":5867,"target":588},{"edgeType":"contains","source":4988,"target":5022},{"edgeType":"calls","source":6936,"target":6572},{"edgeType":"contains","source":1123,"target":1166},{"edgeType":"calls","source":1587,"target":84},{"edgeType":"calls","source":5655,"target":1875},{"edgeType":"calls","source":4750,"target":333},{"edgeType":"contains","source":1302,"target":3013},{"edgeType":"calls","source":4817,"target":370},{"edgeType":"contains","source":1907,"target":2228},{"edgeType":"calls","source":6296,"target":6329},{"edgeType":"contains","source":3954,"target":4308},{"edgeType":"calls","source":6118,"target":4434},{"edgeType":"calls","source":4171,"target":311},{"edgeType":"extends","source":1513,"target":1605},{"edgeType":"contains","source":4558,"target":4610},{"edgeType":"calls","source":2014,"target":588},{"edgeType":"calls","source":2084,"target":532},{"edgeType":"calls","source":144,"target":422},{"edgeType":"contains","source":6471,"target":6612},{"edgeType":"contains","source":4988,"target":5021},{"edgeType":"calls","source":1416,"target":1156},{"edgeType":"contains","source":5550,"target":5567},{"edgeType":"calls","source":4750,"target":332},{"edgeType":"calls","source":4817,"target":369},{"edgeType":"calls","source":3219,"target":2341},{"edgeType":"contains","source":599,"target":1553},{"edgeType":"contains","source":4717,"target":4965},{"edgeType":"calls","source":4171,"target":312},{"edgeType":"calls","source":4817,"target":4597},{"edgeType":"calls","source":2730,"target":588},{"edgeType":"calls","source":4715,"target":4588},{"edgeType":"calls","source":2326,"target":1485},{"edgeType":"contains","source":4558,"target":4609},{"edgeType":"contains","source":2879,"target":3813},{"edgeType":"calls","source":1653,"target":146},{"edgeType":"calls","source":961,"target":457},{"edgeType":"calls","source":6964,"target":421},{"edgeType":"contains","source":6375,"target":6427},{"edgeType":"contains","source":3626,"target":3911},{"edgeType":"contains","source":1037,"target":1720},{"edgeType":"calls","source":7041,"target":148},{"edgeType":"calls","source":3720,"target":3720},{"edgeType":"calls","source":1870,"target":1875},{"edgeType":"calls","source":4817,"target":368},{"edgeType":"calls","source":350,"target":372},{"edgeType":"contains","source":5732,"target":6277},{"edgeType":"contains","source":41,"target":885},{"edgeType":"contains","source":4988,"target":5027},{"edgeType":"calls","source":2329,"target":332},{"edgeType":"calls","source":6964,"target":422},{"edgeType":"contains","source":6375,"target":6428},{"edgeType":"contains","source":1037,"target":1719},{"edgeType":"contains","source":2736,"target":2962},{"edgeType":"contains","source":1123,"target":1167},{"edgeType":"calls","source":5637,"target":5601},{"edgeType":"contains","source":517,"target":926},{"edgeType":"contains","source":4717,"target":4971},{"edgeType":"contains","source":2314,"target":5473},{"edgeType":"calls","source":1143,"target":1156},{"edgeType":"contains","source":3800,"target":3802},{"edgeType":"contains","source":2147,"target":2194},{"edgeType":"contains","source":4988,"target":5026},{"edgeType":"contains","source":6375,"target":6429},{"edgeType":"calls","source":2369,"target":146},{"edgeType":"calls","source":1749,"target":1400},{"edgeType":"calls","source":5559,"target":2733},{"edgeType":"calls","source":3729,"target":268},{"edgeType":"calls","source":4039,"target":171},{"edgeType":"calls","source":4171,"target":307},{"edgeType":"contains","source":3800,"target":3801},{"edgeType":"contains","source":340,"target":1131},{"edgeType":"calls","source":2765,"target":555},{"edgeType":"calls","source":4817,"target":366},{"edgeType":"calls","source":594,"target":209},{"edgeType":"calls","source":961,"target":458},{"edgeType":"calls","source":4314,"target":2216},{"edgeType":"calls","source":4384,"target":3217},{"edgeType":"imports","source":2070,"target":2077},{"edgeType":"contains","source":1037,"target":1721},{"edgeType":"contains","source":4091,"target":2178},{"edgeType":"calls","source":7032,"target":431},{"edgeType":"contains","source":3833,"target":3834},{"edgeType":"calls","source":4477,"target":4563},{"edgeType":"contains","source":5895,"target":3341},{"edgeType":"calls","source":596,"target":146},{"edgeType":"calls","source":4878,"target":588},{"edgeType":"contains","source":100,"target":1174},{"edgeType":"calls","source":4385,"target":1071},{"edgeType":"contains","source":2599,"target":2984},{"edgeType":"contains","source":2742,"target":2779},{"edgeType":"contains","source":2898,"target":4285},{"edgeType":"calls","source":5594,"target":588},{"edgeType":"calls","source":4203,"target":370},{"edgeType":"calls","source":549,"target":541},{"edgeType":"contains","source":5473,"target":567},{"edgeType":"calls","source":484,"target":442},{"edgeType":"calls","source":3299,"target":911},{"edgeType":"calls","source":3159,"target":3137},{"edgeType":"calls","source":2870,"target":469},{"edgeType":"calls","source":4817,"target":364},{"edgeType":"contains","source":2147,"target":2198},{"edgeType":"calls","source":3826,"target":431},{"edgeType":"calls","source":2370,"target":114},{"edgeType":"calls","source":4542,"target":431},{"edgeType":"contains","source":1037,"target":1723},{"edgeType":"calls","source":1936,"target":1938},{"edgeType":"calls","source":4039,"target":170},{"edgeType":"contains","source":2742,"target":2780},{"edgeType":"calls","source":1416,"target":1145},{"edgeType":"calls","source":4203,"target":371},{"edgeType":"calls","source":6826,"target":6819},{"edgeType":"calls","source":6728,"target":6686},{"edgeType":"contains","source":41,"target":5116},{"edgeType":"calls","source":5018,"target":1531},{"edgeType":"contains","source":4192,"target":4337},{"edgeType":"contains","source":30,"target":2289},{"edgeType":"imports","source":2070,"target":2074},{"edgeType":"imports","source":153,"target":192},{"edgeType":"contains","source":2742,"target":2777},{"edgeType":"contains","source":2677,"target":2678},{"edgeType":"calls","source":6489,"target":354},{"edgeType":"calls","source":4203,"target":368},{"edgeType":"contains","source":2898,"target":4283},{"edgeType":"calls","source":4171,"target":303},{"edgeType":"calls","source":4912,"target":588},{"edgeType":"contains","source":1037,"target":1726},{"edgeType":"calls","source":2731,"target":548},{"edgeType":"contains","source":5,"target":6235},{"edgeType":"calls","source":6877,"target":1011},{"edgeType":"calls","source":5424,"target":571},{"edgeType":"calls","source":2993,"target":2996},{"edgeType":"contains","source":6375,"target":6426},{"edgeType":"contains","source":2147,"target":2196},{"edgeType":"contains","source":41,"target":3004},{"edgeType":"contains","source":4192,"target":4336},{"edgeType":"contains","source":4196,"target":4212},{"edgeType":"imports","source":153,"target":193},{"edgeType":"contains","source":4717,"target":4974},{"edgeType":"contains","source":2599,"target":2983},{"edgeType":"calls","source":6110,"target":445},{"edgeType":"extends","source":6508,"target":36},{"edgeType":"calls","source":4171,"target":304},{"edgeType":"calls","source":1348,"target":84},{"edgeType":"calls","source":4203,"target":369},{"edgeType":"calls","source":6959,"target":2698},{"edgeType":"calls","source":2799,"target":555},{"edgeType":"contains","source":4691,"target":4722},{"edgeType":"calls","source":3299,"target":910},{"edgeType":"contains","source":3833,"target":3838},{"edgeType":"contains","source":2206,"target":2453},{"edgeType":"contains","source":3,"target":5209},{"edgeType":"contains","source":6375,"target":6402},{"edgeType":"calls","source":6488,"target":354},{"edgeType":"extends","source":5723,"target":36},{"edgeType":"calls","source":6825,"target":6820},{"edgeType":"contains","source":5910,"target":6019},{"edgeType":"contains","source":3072,"target":3090},{"edgeType":"contains","source":6097,"target":2336},{"edgeType":"calls","source":7068,"target":6686},{"edgeType":"calls","source":3349,"target":447},{"edgeType":"calls","source":4756,"target":170},{"edgeType":"contains","source":1305,"target":1845},{"edgeType":"extends","source":6064,"target":36},{"edgeType":"calls","source":2265,"target":1284},{"edgeType":"contains","source":920,"target":1093},{"edgeType":"calls","source":2090,"target":364},{"edgeType":"calls","source":4170,"target":366},{"edgeType":"contains","source":3072,"target":3091},{"edgeType":"contains","source":5910,"target":6020},{"edgeType":"imports","source":2237,"target":49},{"edgeType":"calls","source":3349,"target":448},{"edgeType":"contains","source":3949,"target":4443},{"edgeType":"calls","source":5131,"target":171},{"edgeType":"contains","source":5448,"target":5540},{"edgeType":"calls","source":4959,"target":4446},{"edgeType":"contains","source":2147,"target":2166},{"edgeType":"contains","source":6771,"target":6813},{"edgeType":"contains","source":6375,"target":6404},{"edgeType":"calls","source":2083,"target":584},{"edgeType":"calls","source":2158,"target":370},{"edgeType":"extends","source":4359,"target":36},{"edgeType":"contains","source":6508,"target":6510},{"edgeType":"contains","source":4558,"target":4589},{"edgeType":"calls","source":4818,"target":4588},{"edgeType":"contains","source":3072,"target":3088},{"edgeType":"calls","source":5637,"target":339},{"edgeType":"contains","source":1037,"target":1697},{"edgeType":"contains","source":5910,"target":6021},{"edgeType":"calls","source":3767,"target":171},{"edgeType":"calls","source":5131,"target":170},{"edgeType":"contains","source":5550,"target":5554},{"edgeType":"contains","source":1848,"target":1922},{"edgeType":"calls","source":3093,"target":3096},{"edgeType":"calls","source":6933,"target":303},{"edgeType":"calls","source":6992,"target":588},{"edgeType":"calls","source":7042,"target":1152},{"edgeType":"extends","source":5416,"target":36},{"edgeType":"contains","source":4921,"target":4963},{"edgeType":"contains","source":1305,"target":1843},{"edgeType":"contains","source":5910,"target":6022},{"edgeType":"contains","source":6541,"target":6545},{"edgeType":"contains","source":6375,"target":6405},{"edgeType":"calls","source":4170,"target":364},{"edgeType":"calls","source":2090,"target":366},{"edgeType":"calls","source":2158,"target":371},{"edgeType":"contains","source":1037,"target":1696},{"edgeType":"contains","source":6508,"target":6511},{"edgeType":"calls","source":5529,"target":4743},{"edgeType":"contains","source":951,"target":6476},{"edgeType":"imports","source":130,"target":886},{"edgeType":"contains","source":3072,"target":3089},{"edgeType":"calls","source":550,"target":540},{"edgeType":"calls","source":5637,"target":338},{"edgeType":"calls","source":6933,"target":304},{"edgeType":"calls","source":6098,"target":1902},{"edgeType":"contains","source":5448,"target":5546},{"edgeType":"extends","source":6814,"target":36},{"edgeType":"calls","source":3919,"target":3914},{"edgeType":"contains","source":4668,"target":1186},{"edgeType":"contains","source":453,"target":777},{"edgeType":"calls","source":468,"target":962},{"edgeType":"calls","source":7000,"target":342},{"edgeType":"contains","source":5910,"target":6015},{"edgeType":"contains","source":3072,"target":3094},{"edgeType":"contains","source":5908,"target":7134},{"edgeType":"calls","source":2158,"target":368},{"edgeType":"calls","source":1357,"target":886},{"edgeType":"calls","source":5637,"target":337},{"edgeType":"contains","source":1305,"target":1849},{"edgeType":"contains","source":3370,"target":3371},{"edgeType":"calls","source":5459,"target":570},{"edgeType":"calls","source":4681,"target":4603},{"edgeType":"contains","source":3954,"target":4292},{"edgeType":"imports","source":2494,"target":534},{"edgeType":"calls","source":2158,"target":369},{"edgeType":"calls","source":2156,"target":431},{"edgeType":"contains","source":3072,"target":3095},{"edgeType":"contains","source":5910,"target":6016},{"edgeType":"calls","source":4976,"target":4972},{"edgeType":"calls","source":2862,"target":2857},{"edgeType":"calls","source":4952,"target":431},{"edgeType":"calls","source":4852,"target":4588},{"edgeType":"contains","source":5285,"target":5312},{"edgeType":"calls","source":3767,"target":170},{"edgeType":"contains","source":5732,"target":6249},{"edgeType":"extends","source":2552,"target":36},{"edgeType":"contains","source":1305,"target":1850},{"edgeType":"contains","source":5448,"target":5544},{"edgeType":"contains","source":3981,"target":4511},{"edgeType":"contains","source":2206,"target":2455},{"edgeType":"contains","source":6771,"target":6809},{"edgeType":"contains","source":6375,"target":6400},{"edgeType":"contains","source":6607,"target":6608},{"edgeType":"contains","source":3072,"target":3092},{"edgeType":"contains","source":5910,"target":6017},{"edgeType":"calls","source":6977,"target":1057},{"edgeType":"calls","source":2158,"target":366},{"edgeType":"calls","source":4942,"target":740},{"edgeType":"extends","source":6439,"target":36},{"edgeType":"calls","source":3227,"target":3167},{"edgeType":"contains","source":1305,"target":1847},{"edgeType":"calls","source":4647,"target":4598},{"edgeType":"contains","source":24,"target":335},{"edgeType":"calls","source":5867,"target":5889},{"edgeType":"contains","source":3981,"target":4510},{"edgeType":"contains","source":6375,"target":6401},{"edgeType":"calls","source":6289,"target":2320},{"edgeType":"contains","source":2206,"target":2456},{"edgeType":"calls","source":468,"target":963},{"edgeType":"contains","source":5910,"target":6018},{"edgeType":"contains","source":2898,"target":4259},{"edgeType":"calls","source":5131,"target":165},{"edgeType":"contains","source":3601,"target":3606},{"edgeType":"contains","source":5448,"target":5542},{"edgeType":"contains","source":5550,"target":5551},{"edgeType":"contains","source":6607,"target":6618},{"edgeType":"calls","source":1345,"target":1254},{"edgeType":"contains","source":2581,"target":350},{"edgeType":"contains","source":4668,"target":1190},{"edgeType":"calls","source":1208,"target":1273},{"edgeType":"calls","source":6216,"target":354},{"edgeType":"calls","source":5131,"target":164},{"edgeType":"calls","source":6914,"target":898},{"edgeType":"imports","source":6373,"target":2900},{"edgeType":"contains","source":5550,"target":5560},{"edgeType":"calls","source":2158,"target":364},{"edgeType":"calls","source":1800,"target":890},{"edgeType":"calls","source":2131,"target":144},{"edgeType":"calls","source":5300,"target":210},{"edgeType":"calls","source":3963,"target":431},{"edgeType":"contains","source":3072,"target":3098},{"edgeType":"calls","source":1755,"target":171},{"edgeType":"contains","source":3954,"target":4296},{"edgeType":"calls","source":1208,"target":1272},{"edgeType":"calls","source":1243,"target":1244},{"edgeType":"calls","source":2506,"target":147},{"edgeType":"contains","source":5,"target":1983},{"edgeType":"calls","source":6838,"target":84},{"edgeType":"calls","source":5300,"target":209},{"edgeType":"calls","source":5672,"target":304},{"edgeType":"calls","source":6033,"target":1797},{"edgeType":"calls","source":1755,"target":170},{"edgeType":"calls","source":6591,"target":342},{"edgeType":"contains","source":1190,"target":1191},{"edgeType":"imports","source":2961,"target":2981},{"edgeType":"contains","source":3954,"target":4295},{"edgeType":"contains","source":6160,"target":6735},{"edgeType":"contains","source":32,"target":92},{"edgeType":"calls","source":3106,"target":571},{"edgeType":"calls","source":2253,"target":588},{"edgeType":"calls","source":2333,"target":2336},{"edgeType":"calls","source":5672,"target":303},{"edgeType":"contains","source":1305,"target":1851},{"edgeType":"calls","source":1486,"target":56},{"edgeType":"calls","source":3932,"target":333},{"edgeType":"imports","source":4691,"target":78},{"edgeType":"calls","source":6361,"target":84},{"edgeType":"contains","source":2147,"target":2175},{"edgeType":"contains","source":199,"target":200},{"edgeType":"contains","source":4394,"target":4396},{"edgeType":"calls","source":5334,"target":210},{"edgeType":"extends","source":4632,"target":36},{"edgeType":"contains","source":1305,"target":1852},{"edgeType":"imports","source":130,"target":894},{"edgeType":"contains","source":3205,"target":3208},{"edgeType":"imports","source":4691,"target":79},{"edgeType":"calls","source":1421,"target":1008},{"edgeType":"imports","source":2961,"target":2979},{"edgeType":"calls","source":7074,"target":170},{"edgeType":"contains","source":5154,"target":5155},{"edgeType":"contains","source":5,"target":931},{"edgeType":"calls","source":2968,"target":2732},{"edgeType":"calls","source":897,"target":339},{"edgeType":"extends","source":1086,"target":36},{"edgeType":"contains","source":5,"target":3046},{"edgeType":"contains","source":100,"target":101},{"edgeType":"calls","source":5334,"target":209},{"edgeType":"calls","source":6939,"target":1184},{"edgeType":"imports","source":6530,"target":2265},{"edgeType":"contains","source":3072,"target":3102},{"edgeType":"calls","source":6587,"target":469},{"edgeType":"calls","source":2130,"target":171},{"edgeType":"contains","source":4558,"target":4603},{"edgeType":"calls","source":7074,"target":171},{"edgeType":"contains","source":3205,"target":3209},{"edgeType":"calls","source":897,"target":338},{"edgeType":"contains","source":5,"target":3044},{"edgeType":"contains","source":1848,"target":1937},{"edgeType":"contains","source":6375,"target":6408},{"edgeType":"calls","source":5336,"target":146},{"edgeType":"calls","source":5365,"target":304},{"edgeType":"calls","source":3997,"target":431},{"edgeType":"calls","source":3932,"target":332},{"edgeType":"contains","source":1848,"target":1934},{"edgeType":"calls","source":4197,"target":571},{"edgeType":"contains","source":3205,"target":3206},{"edgeType":"contains","source":1190,"target":1195},{"edgeType":"calls","source":1208,"target":1271},{"edgeType":"calls","source":1142,"target":146},{"edgeType":"contains","source":4196,"target":4197},{"edgeType":"calls","source":6782,"target":2882},{"edgeType":"calls","source":5365,"target":303},{"edgeType":"imports","source":2203,"target":49},{"edgeType":"calls","source":4386,"target":4226},{"edgeType":"contains","source":5550,"target":5558},{"edgeType":"calls","source":6797,"target":303},{"edgeType":"imports","source":130,"target":889},{"edgeType":"calls","source":6486,"target":431},{"edgeType":"calls","source":4171,"target":319},{"edgeType":"contains","source":3205,"target":3207},{"edgeType":"contains","source":1848,"target":1935},{"edgeType":"calls","source":4899,"target":1006},{"edgeType":"calls","source":1354,"target":972},{"edgeType":"calls","source":2974,"target":431},{"edgeType":"contains","source":32,"target":6438},{"edgeType":"calls","source":6996,"target":6819},{"edgeType":"calls","source":2830,"target":2781},{"edgeType":"contains","source":6375,"target":6410},{"edgeType":"calls","source":1653,"target":1216},{"edgeType":"imports","source":3496,"target":131},{"edgeType":"contains","source":100,"target":102},{"edgeType":"contains","source":6442,"target":6447},{"edgeType":"calls","source":6652,"target":571},{"edgeType":"contains","source":4394,"target":4400},{"edgeType":"calls","source":6797,"target":304},{"edgeType":"calls","source":2186,"target":548},{"edgeType":"contains","source":4717,"target":4957},{"edgeType":"calls","source":1758,"target":1132},{"edgeType":"contains","source":5054,"target":5080},{"edgeType":"calls","source":4018,"target":4006},{"edgeType":"calls","source":2130,"target":170},{"edgeType":"calls","source":4753,"target":4573},{"edgeType":"contains","source":2376,"target":2452},{"edgeType":"contains","source":5910,"target":6002},{"edgeType":"contains","source":3072,"target":3074},{"edgeType":"calls","source":524,"target":370},{"edgeType":"contains","source":5054,"target":5055},{"edgeType":"calls","source":1172,"target":366},{"edgeType":"contains","source":5647,"target":5699},{"edgeType":"calls","source":894,"target":527},{"edgeType":"calls","source":6486,"target":6874},{"edgeType":"calls","source":5334,"target":304},{"edgeType":"contains","source":6111,"target":6114},{"edgeType":"contains","source":6106,"target":6269},{"edgeType":"calls","source":2537,"target":1390},{"edgeType":"contains","source":6045,"target":6046},{"edgeType":"calls","source":1543,"target":1549},{"edgeType":"calls","source":4384,"target":157},{"edgeType":"contains","source":6771,"target":6794},{"edgeType":"contains","source":4459,"target":4472},{"edgeType":"calls","source":2734,"target":2683},{"edgeType":"calls","source":6219,"target":3522},{"edgeType":"contains","source":5910,"target":6003},{"edgeType":"calls","source":2601,"target":2578},{"edgeType":"calls","source":5673,"target":364},{"edgeType":"contains","source":3072,"target":3075},{"edgeType":"contains","source":5647,"target":5700},{"edgeType":"calls","source":2537,"target":1391},{"edgeType":"contains","source":3949,"target":4426},{"edgeType":"calls","source":1818,"target":422},{"edgeType":"calls","source":6600,"target":170},{"edgeType":"contains","source":33,"target":34},{"edgeType":"contains","source":1379,"target":592},{"edgeType":"calls","source":3756,"target":598},{"edgeType":"calls","source":5334,"target":303},{"edgeType":"calls","source":4652,"target":304},{"edgeType":"contains","source":4091,"target":4253},{"edgeType":"calls","source":524,"target":369},{"edgeType":"contains","source":5024,"target":4926},{"edgeType":"calls","source":5673,"target":5649},{"edgeType":"calls","source":2833,"target":2782},{"edgeType":"calls","source":4724,"target":4413},{"edgeType":"contains","source":5910,"target":6004},{"edgeType":"calls","source":6565,"target":6541},{"edgeType":"contains","source":7003,"target":7004},{"edgeType":"calls","source":2979,"target":370},{"edgeType":"contains","source":5647,"target":5701},{"edgeType":"extends","source":5024,"target":4839},{"edgeType":"calls","source":1172,"target":368},{"edgeType":"calls","source":1053,"target":886},{"edgeType":"contains","source":1683,"target":1735},{"edgeType":"calls","source":6728,"target":431},{"edgeType":"calls","source":5125,"target":4666},{"edgeType":"contains","source":4921,"target":4947},{"edgeType":"calls","source":6600,"target":171},{"edgeType":"calls","source":2537,"target":1388},{"edgeType":"contains","source":2212,"target":2249},{"edgeType":"contains","source":6771,"target":6796},{"edgeType":"calls","source":4652,"target":303},{"edgeType":"calls","source":2261,"target":431},{"edgeType":"contains","source":6471,"target":6584},{"edgeType":"contains","source":2376,"target":2451},{"edgeType":"contains","source":3072,"target":3073},{"edgeType":"contains","source":5153,"target":5154},{"edgeType":"calls","source":524,"target":371},{"edgeType":"contains","source":5910,"target":6005},{"edgeType":"calls","source":2979,"target":371},{"edgeType":"contains","source":7003,"target":7005},{"edgeType":"contains","source":4091,"target":4250},{"edgeType":"contains","source":1848,"target":1906},{"edgeType":"calls","source":894,"target":528},{"edgeType":"calls","source":5042,"target":1953},{"edgeType":"contains","source":6106,"target":6272},{"edgeType":"contains","source":1305,"target":1827},{"edgeType":"extends","source":1186,"target":1202},{"edgeType":"calls","source":2537,"target":1389},{"edgeType":"contains","source":5910,"target":6006},{"edgeType":"contains","source":5910,"target":5998},{"edgeType":"contains","source":3072,"target":3078},{"edgeType":"calls","source":2979,"target":368},{"edgeType":"contains","source":3166,"target":1221},{"edgeType":"contains","source":4921,"target":4954},{"edgeType":"calls","source":5534,"target":442},{"edgeType":"calls","source":1208,"target":303},{"edgeType":"calls","source":1404,"target":569},{"edgeType":"calls","source":5339,"target":144},{"edgeType":"calls","source":6587,"target":576},{"edgeType":"calls","source":2606,"target":304},{"edgeType":"calls","source":1956,"target":369},{"edgeType":"calls","source":1765,"target":1005},{"edgeType":"calls","source":1781,"target":509},{"edgeType":"contains","source":6210,"target":6212},{"edgeType":"calls","source":2326,"target":528},{"edgeType":"calls","source":524,"target":366},{"edgeType":"contains","source":2244,"target":2320},{"edgeType":"calls","source":4336,"target":584},{"edgeType":"calls","source":4218,"target":4242},{"edgeType":"contains","source":6771,"target":6790},{"edgeType":"calls","source":6688,"target":6959},{"edgeType":"contains","source":5910,"target":5999},{"edgeType":"contains","source":2961,"target":3349},{"edgeType":"contains","source":3072,"target":3079},{"edgeType":"calls","source":6728,"target":6776},{"edgeType":"imports","source":4668,"target":1908},{"edgeType":"contains","source":4988,"target":4990},{"edgeType":"calls","source":968,"target":342},{"edgeType":"calls","source":2979,"target":369},{"edgeType":"calls","source":6486,"target":6879},{"edgeType":"contains","source":5448,"target":5528},{"edgeType":"calls","source":6104,"target":1797},{"edgeType":"calls","source":1956,"target":368},{"edgeType":"calls","source":1781,"target":508},{"edgeType":"calls","source":4588,"target":4398},{"edgeType":"contains","source":6770,"target":6822},{"edgeType":"calls","source":6215,"target":5755},{"edgeType":"contains","source":2376,"target":2454},{"edgeType":"contains","source":3072,"target":3076},{"edgeType":"calls","source":4218,"target":4239},{"edgeType":"calls","source":1345,"target":1343},{"edgeType":"contains","source":5910,"target":6000},{"edgeType":"calls","source":5850,"target":157},{"edgeType":"calls","source":2979,"target":366},{"edgeType":"calls","source":4752,"target":4598},{"edgeType":"calls","source":6569,"target":6421},{"edgeType":"calls","source":1172,"target":364},{"edgeType":"calls","source":6633,"target":209},{"edgeType":"contains","source":5448,"target":5527},{"edgeType":"calls","source":354,"target":353},{"edgeType":"calls","source":1818,"target":421},{"edgeType":"calls","source":1042,"target":165},{"edgeType":"calls","source":6055,"target":144},{"edgeType":"calls","source":524,"target":368},{"edgeType":"contains","source":6771,"target":6792},{"edgeType":"contains","source":41,"target":1907},{"edgeType":"calls","source":1956,"target":371},{"edgeType":"calls","source":6361,"target":171},{"edgeType":"contains","source":4459,"target":4474},{"edgeType":"contains","source":3072,"target":3077},{"edgeType":"calls","source":4225,"target":4021},{"edgeType":"contains","source":5910,"target":6001},{"edgeType":"calls","source":5714,"target":144},{"edgeType":"imports","source":5410,"target":49},{"edgeType":"calls","source":2963,"target":2977},{"edgeType":"imports","source":4352,"target":78},{"edgeType":"contains","source":5647,"target":5698},{"edgeType":"calls","source":6633,"target":210},{"edgeType":"calls","source":1208,"target":304},{"edgeType":"extends","source":1683,"target":1654},{"edgeType":"calls","source":2606,"target":303},{"edgeType":"calls","source":1042,"target":164},{"edgeType":"imports","source":4352,"target":79},{"edgeType":"calls","source":7078,"target":157},{"edgeType":"calls","source":6829,"target":6819},{"edgeType":"calls","source":1991,"target":342},{"edgeType":"calls","source":1956,"target":370},{"edgeType":"calls","source":6361,"target":170},{"edgeType":"imports","source":22,"target":51},{"edgeType":"calls","source":2326,"target":527},{"edgeType":"calls","source":2979,"target":364},{"edgeType":"contains","source":2244,"target":2324},{"edgeType":"contains","source":5780,"target":1584},{"edgeType":"calls","source":4337,"target":548},{"edgeType":"contains","source":2907,"target":2912},{"edgeType":"calls","source":2888,"target":1071},{"edgeType":"imports","source":6319,"target":4623},{"edgeType":"calls","source":6976,"target":148},{"edgeType":"calls","source":1708,"target":1711},{"edgeType":"contains","source":3460,"target":3739},{"edgeType":"calls","source":1781,"target":505},{"edgeType":"calls","source":1582,"target":332},{"edgeType":"contains","source":7003,"target":7010},{"edgeType":"calls","source":1241,"target":332},{"edgeType":"contains","source":3949,"target":4436},{"edgeType":"calls","source":5444,"target":1113},{"edgeType":"calls","source":6138,"target":1797},{"edgeType":"calls","source":1886,"target":421},{"edgeType":"contains","source":30,"target":136},{"edgeType":"calls","source":4752,"target":4596},{"edgeType":"contains","source":2376,"target":2460},{"edgeType":"contains","source":5910,"target":6011},{"edgeType":"calls","source":6249,"target":5755},{"edgeType":"contains","source":5908,"target":7130},{"edgeType":"contains","source":4091,"target":4262},{"edgeType":"contains","source":7003,"target":7011},{"edgeType":"calls","source":6727,"target":469},{"edgeType":"calls","source":5103,"target":1113},{"edgeType":"calls","source":1708,"target":1710},{"edgeType":"calls","source":1781,"target":504},{"edgeType":"contains","source":3072,"target":3083},{"edgeType":"calls","source":1956,"target":364},{"edgeType":"calls","source":5444,"target":1112},{"edgeType":"calls","source":5504,"target":309},{"edgeType":"calls","source":5404,"target":3409},{"edgeType":"contains","source":1848,"target":1917},{"edgeType":"contains","source":5448,"target":5532},{"edgeType":"contains","source":6106,"target":6278},{"edgeType":"contains","source":5748,"target":5749},{"edgeType":"extends","source":5452,"target":36},{"edgeType":"contains","source":5910,"target":6012},{"edgeType":"contains","source":5908,"target":7131},{"edgeType":"calls","source":5103,"target":1112},{"edgeType":"contains","source":7003,"target":7012},{"edgeType":"imports","source":2581,"target":2126},{"edgeType":"imports","source":6319,"target":4625},{"edgeType":"contains","source":6471,"target":6591},{"edgeType":"calls","source":3756,"target":3758},{"edgeType":"contains","source":4921,"target":4956},{"edgeType":"calls","source":1242,"target":304},{"edgeType":"contains","source":3072,"target":3080},{"edgeType":"calls","source":1248,"target":1175},{"edgeType":"calls","source":5543,"target":157},{"edgeType":"contains","source":5908,"target":7132},{"edgeType":"calls","source":1242,"target":303},{"edgeType":"calls","source":1781,"target":507},{"edgeType":"calls","source":6152,"target":304},{"edgeType":"imports","source":5473,"target":5481},{"edgeType":"contains","source":6106,"target":6279},{"edgeType":"contains","source":2376,"target":2458},{"edgeType":"contains","source":4091,"target":4260},{"edgeType":"calls","source":524,"target":364},{"edgeType":"contains","source":5910,"target":6013},{"edgeType":"contains","source":4192,"target":4300},{"edgeType":"calls","source":5797,"target":1795},{"edgeType":"calls","source":4218,"target":4234},{"edgeType":"imports","source":6286,"target":5647},{"edgeType":"imports","source":6319,"target":4624},{"edgeType":"calls","source":1708,"target":1712},{"edgeType":"calls","source":1781,"target":506},{"edgeType":"contains","source":3072,"target":3081},{"edgeType":"calls","source":1582,"target":333},{"edgeType":"calls","source":1886,"target":422},{"edgeType":"contains","source":5910,"target":6014},{"edgeType":"contains","source":5908,"target":7133},{"edgeType":"calls","source":1241,"target":333},{"edgeType":"calls","source":5470,"target":304},{"edgeType":"contains","source":5448,"target":5530},{"edgeType":"calls","source":3311,"target":2755},{"edgeType":"calls","source":6152,"target":303},{"edgeType":"calls","source":1956,"target":366},{"edgeType":"calls","source":6728,"target":6783},{"edgeType":"imports","source":3807,"target":49},{"edgeType":"calls","source":2837,"target":537},{"edgeType":"contains","source":4558,"target":4580},{"edgeType":"imports","source":6319,"target":4627},{"edgeType":"calls","source":5310,"target":2092},{"edgeType":"contains","source":1305,"target":1840},{"edgeType":"calls","source":3822,"target":3824},{"edgeType":"contains","source":3072,"target":3086},{"edgeType":"calls","source":2071,"target":2082},{"edgeType":"contains","source":7003,"target":7006},{"edgeType":"contains","source":2742,"target":2746},{"edgeType":"contains","source":920,"target":1090},{"edgeType":"calls","source":1774,"target":1775},{"edgeType":"extends","source":5040,"target":1186},{"edgeType":"contains","source":6106,"target":6273},{"edgeType":"calls","source":5470,"target":303},{"edgeType":"calls","source":6688,"target":6967},{"edgeType":"contains","source":5910,"target":6007},{"edgeType":"contains","source":5908,"target":7126},{"edgeType":"imports","source":6319,"target":4626},{"edgeType":"contains","source":5780,"target":5809},{"edgeType":"contains","source":1305,"target":1841},{"edgeType":"contains","source":5732,"target":6240},{"edgeType":"calls","source":5310,"target":2091},{"edgeType":"contains","source":4717,"target":4943},{"edgeType":"contains","source":3072,"target":3087},{"edgeType":"extends","source":1732,"target":1202},{"edgeType":"contains","source":7003,"target":7007},{"edgeType":"calls","source":6194,"target":56},{"edgeType":"calls","source":5441,"target":144},{"edgeType":"contains","source":2376,"target":2465},{"edgeType":"extends","source":3367,"target":3368},{"edgeType":"contains","source":5910,"target":6008},{"edgeType":"contains","source":5908,"target":7127},{"edgeType":"calls","source":2732,"target":2733},{"edgeType":"calls","source":4818,"target":431},{"edgeType":"calls","source":3773,"target":56},{"edgeType":"contains","source":6471,"target":6587},{"edgeType":"contains","source":3,"target":5207},{"edgeType":"calls","source":2370,"target":210},{"edgeType":"contains","source":3072,"target":3084},{"edgeType":"calls","source":6533,"target":146},{"edgeType":"calls","source":1781,"target":503},{"edgeType":"calls","source":1345,"target":1335},{"edgeType":"calls","source":5648,"target":1126},{"edgeType":"contains","source":2736,"target":2930},{"edgeType":"calls","source":4106,"target":303},{"edgeType":"contains","source":7003,"target":7008},{"edgeType":"calls","source":1708,"target":1709},{"edgeType":"contains","source":4921,"target":4960},{"edgeType":"calls","source":1256,"target":922},{"edgeType":"calls","source":1248,"target":1170},{"edgeType":"contains","source":1032,"target":1848},{"edgeType":"calls","source":5504,"target":304},{"edgeType":"calls","source":5534,"target":431},{"edgeType":"contains","source":2376,"target":2462},{"edgeType":"calls","source":4902,"target":5225},{"edgeType":"contains","source":5910,"target":6009},{"edgeType":"contains","source":5908,"target":7128},{"edgeType":"calls","source":4446,"target":333},{"edgeType":"calls","source":6758,"target":571},{"edgeType":"contains","source":5732,"target":6242},{"edgeType":"contains","source":3072,"target":3085},{"edgeType":"contains","source":2736,"target":2931},{"edgeType":"calls","source":6045,"target":445},{"edgeType":"contains","source":7003,"target":7009},{"edgeType":"calls","source":1723,"target":1243},{"edgeType":"calls","source":1781,"target":502},{"edgeType":"calls","source":4106,"target":304},{"edgeType":"contains","source":4717,"target":4940},{"edgeType":"calls","source":5504,"target":303},{"edgeType":"calls","source":5065,"target":171},{"edgeType":"calls","source":6970,"target":4570},{"edgeType":"contains","source":6106,"target":6276},{"edgeType":"contains","source":5910,"target":6010},{"edgeType":"contains","source":5908,"target":7129},{"edgeType":"calls","source":354,"target":371},{"edgeType":"contains","source":3496,"target":3655},{"edgeType":"contains","source":4788,"target":4828},{"edgeType":"contains","source":1305,"target":1811},{"edgeType":"contains","source":3368,"target":3395},{"edgeType":"contains","source":5,"target":5114},{"edgeType":"contains","source":1302,"target":2961},{"edgeType":"imports","source":5166,"target":190},{"edgeType":"contains","source":4558,"target":4559},{"edgeType":"calls","source":4107,"target":303},{"edgeType":"contains","source":2540,"target":2637},{"edgeType":"contains","source":6459,"target":6936},{"edgeType":"contains","source":5910,"target":5986},{"edgeType":"contains","source":453,"target":739},{"edgeType":"calls","source":3455,"target":431},{"edgeType":"calls","source":1517,"target":1314},{"edgeType":"calls","source":6827,"target":1572},{"edgeType":"calls","source":3214,"target":503},{"edgeType":"calls","source":6932,"target":431},{"edgeType":"imports","source":2494,"target":2686},{"edgeType":"contains","source":3496,"target":3656},{"edgeType":"calls","source":6902,"target":304},{"edgeType":"contains","source":5592,"target":6331},{"edgeType":"contains","source":3496,"target":3654},{"edgeType":"calls","source":354,"target":370},{"edgeType":"contains","source":1305,"target":1812},{"edgeType":"contains","source":3368,"target":3394},{"edgeType":"contains","source":2212,"target":2235},{"edgeType":"calls","source":4107,"target":304},{"edgeType":"calls","source":4080,"target":84},{"edgeType":"contains","source":2540,"target":2638},{"edgeType":"calls","source":6046,"target":445},{"edgeType":"calls","source":1411,"target":371},{"edgeType":"contains","source":5910,"target":5987},{"edgeType":"contains","source":453,"target":738},{"edgeType":"imports","source":2203,"target":79},{"edgeType":"contains","source":41,"target":6111},{"edgeType":"calls","source":3214,"target":504},{"edgeType":"calls","source":5164,"target":304},{"edgeType":"contains","source":1683,"target":1722},{"edgeType":"imports","source":4528,"target":3056},{"edgeType":"contains","source":3496,"target":3653},{"edgeType":"calls","source":6566,"target":2265},{"edgeType":"contains","source":5,"target":3002},{"edgeType":"calls","source":4386,"target":4337},{"edgeType":"contains","source":3368,"target":3393},{"edgeType":"calls","source":1808,"target":1809},{"edgeType":"calls","source":4384,"target":171},{"edgeType":"contains","source":4788,"target":4826},{"edgeType":"contains","source":6459,"target":6938},{"edgeType":"contains","source":6471,"target":6567},{"edgeType":"contains","source":6459,"target":6939},{"edgeType":"calls","source":1292,"target":892},{"edgeType":"calls","source":4753,"target":4588},{"edgeType":"imports","source":2203,"target":78},{"edgeType":"imports","source":2201,"target":2254},{"edgeType":"contains","source":5910,"target":5988},{"edgeType":"contains","source":5592,"target":6333},{"edgeType":"calls","source":4794,"target":146},{"edgeType":"imports","source":4528,"target":3057},{"edgeType":"calls","source":5164,"target":303},{"edgeType":"imports","source":6530,"target":190},{"edgeType":"contains","source":1848,"target":1889},{"edgeType":"contains","source":3496,"target":3652},{"edgeType":"calls","source":6046,"target":443},{"edgeType":"contains","source":2212,"target":2233},{"edgeType":"contains","source":4359,"target":4382},{"edgeType":"contains","source":3368,"target":3392},{"edgeType":"calls","source":1524,"target":1099},{"edgeType":"calls","source":4384,"target":170},{"edgeType":"contains","source":453,"target":741},{"edgeType":"contains","source":6604,"target":6673},{"edgeType":"contains","source":2540,"target":2636},{"edgeType":"calls","source":2106,"target":2082},{"edgeType":"contains","source":4668,"target":1145},{"edgeType":"contains","source":6471,"target":6568},{"edgeType":"calls","source":6946,"target":1057},{"edgeType":"calls","source":1292,"target":891},{"edgeType":"contains","source":2540,"target":2635},{"edgeType":"contains","source":453,"target":740},{"edgeType":"contains","source":435,"target":1298},{"edgeType":"calls","source":5514,"target":2136},{"edgeType":"contains","source":5910,"target":5989},{"edgeType":"calls","source":2533,"target":2587},{"edgeType":"calls","source":3214,"target":502},{"edgeType":"calls","source":4577,"target":528},{"edgeType":"calls","source":2533,"target":2583},{"edgeType":"contains","source":453,"target":744},{"edgeType":"calls","source":2086,"target":584},{"edgeType":"contains","source":5910,"target":5982},{"edgeType":"imports","source":2237,"target":79},{"edgeType":"calls","source":6458,"target":354},{"edgeType":"extends","source":5756,"target":2213},{"edgeType":"contains","source":1717,"target":1728},{"edgeType":"contains","source":1037,"target":1666},{"edgeType":"contains","source":3030,"target":1192},{"edgeType":"contains","source":5732,"target":6215},{"edgeType":"calls","source":1411,"target":368},{"edgeType":"calls","source":3118,"target":304},{"edgeType":"calls","source":6486,"target":6862},{"edgeType":"calls","source":1312,"target":1323},{"edgeType":"contains","source":1420,"target":1422},{"edgeType":"contains","source":5416,"target":5447},{"edgeType":"calls","source":1125,"target":777},{"edgeType":"calls","source":4577,"target":527},{"edgeType":"contains","source":3,"target":951},{"edgeType":"contains","source":5,"target":3003},{"edgeType":"contains","source":2212,"target":2239},{"edgeType":"contains","source":6471,"target":6561},{"edgeType":"contains","source":6459,"target":6933},{"edgeType":"calls","source":4516,"target":304},{"edgeType":"contains","source":429,"target":430},{"edgeType":"contains","source":4391,"target":4453},{"edgeType":"calls","source":354,"target":366},{"edgeType":"extends","source":3563,"target":438},{"edgeType":"contains","source":5910,"target":5983},{"edgeType":"imports","source":2237,"target":78},{"edgeType":"contains","source":1717,"target":1729},{"edgeType":"contains","source":1037,"target":1665},{"edgeType":"calls","source":5724,"target":4080},{"edgeType":"calls","source":6533,"target":6463},{"edgeType":"calls","source":5077,"target":883},{"edgeType":"contains","source":5592,"target":6328},{"edgeType":"contains","source":3496,"target":3659},{"edgeType":"contains","source":5416,"target":5446},{"edgeType":"calls","source":354,"target":369},{"edgeType":"contains","source":3368,"target":3397},{"edgeType":"calls","source":4646,"target":4729},{"edgeType":"calls","source":7140,"target":1388},{"edgeType":"calls","source":4516,"target":303},{"edgeType":"calls","source":4519,"target":210},{"edgeType":"contains","source":453,"target":746},{"edgeType":"contains","source":4558,"target":4561},{"edgeType":"contains","source":2540,"target":2639},{"edgeType":"calls","source":5589,"target":5093},{"edgeType":"calls","source":1411,"target":370},{"edgeType":"contains","source":5910,"target":5984},{"edgeType":"calls","source":6864,"target":431},{"edgeType":"contains","source":3166,"target":1202},{"edgeType":"imports","source":6319,"target":4621},{"edgeType":"calls","source":354,"target":368},{"edgeType":"contains","source":4788,"target":4829},{"edgeType":"contains","source":3368,"target":3396},{"edgeType":"calls","source":7140,"target":1389},{"edgeType":"calls","source":3809,"target":3194},{"edgeType":"calls","source":4519,"target":209},{"edgeType":"contains","source":2210,"target":2299},{"edgeType":"calls","source":4864,"target":84},{"edgeType":"extends","source":1186,"target":1190},{"edgeType":"contains","source":6459,"target":6935},{"edgeType":"contains","source":4558,"target":4560},{"edgeType":"calls","source":1411,"target":369},{"edgeType":"contains","source":5910,"target":5985},{"edgeType":"contains","source":3732,"target":3740},{"edgeType":"contains","source":885,"target":1094},{"edgeType":"calls","source":3118,"target":303},{"edgeType":"contains","source":3496,"target":3657},{"edgeType":"contains","source":1420,"target":1421},{"edgeType":"calls","source":7140,"target":1390},{"edgeType":"calls","source":1270,"target":507},{"edgeType":"contains","source":6770,"target":6817},{"edgeType":"calls","source":3128,"target":3161},{"edgeType":"contains","source":2641,"target":2685},{"edgeType":"calls","source":7030,"target":572},{"edgeType":"calls","source":2332,"target":354},{"edgeType":"contains","source":5910,"target":5994},{"edgeType":"calls","source":2372,"target":171},{"edgeType":"contains","source":6342,"target":6344},{"edgeType":"contains","source":6375,"target":6378},{"edgeType":"calls","source":5876,"target":422},{"edgeType":"contains","source":6471,"target":6573},{"edgeType":"calls","source":1411,"target":364},{"edgeType":"calls","source":7140,"target":1391},{"edgeType":"calls","source":1270,"target":506},{"edgeType":"calls","source":6999,"target":6819},{"edgeType":"contains","source":4668,"target":1156},{"edgeType":"calls","source":7030,"target":573},{"edgeType":"contains","source":5910,"target":5995},{"edgeType":"contains","source":2212,"target":2243},{"edgeType":"contains","source":6342,"target":6345},{"edgeType":"contains","source":2860,"target":3296},{"edgeType":"calls","source":2105,"target":2107},{"edgeType":"calls","source":5876,"target":421},{"edgeType":"calls","source":6532,"target":6498},{"edgeType":"extends","source":4940,"target":36},{"edgeType":"calls","source":1346,"target":1321},{"edgeType":"calls","source":3272,"target":2923},{"edgeType":"calls","source":3922,"target":3914},{"edgeType":"contains","source":3949,"target":4417},{"edgeType":"calls","source":7102,"target":2570},{"edgeType":"calls","source":7140,"target":1392},{"edgeType":"contains","source":4722,"target":4766},{"edgeType":"contains","source":2212,"target":2240},{"edgeType":"contains","source":5910,"target":5996},{"edgeType":"imports","source":4352,"target":49},{"edgeType":"calls","source":5237,"target":146},{"edgeType":"contains","source":1717,"target":1730},{"edgeType":"imports","source":6432,"target":49},{"edgeType":"calls","source":3123,"target":1200},{"edgeType":"contains","source":1037,"target":1672},{"edgeType":"calls","source":1270,"target":509},{"edgeType":"contains","source":6770,"target":6819},{"edgeType":"calls","source":3756,"target":603},{"edgeType":"calls","source":3586,"target":588},{"edgeType":"calls","source":1411,"target":366},{"edgeType":"calls","source":5673,"target":371},{"edgeType":"calls","source":1114,"target":1116},{"edgeType":"calls","source":7140,"target":1393},{"edgeType":"calls","source":1180,"target":1184},{"edgeType":"calls","source":4584,"target":304},{"edgeType":"calls","source":2372,"target":170},{"edgeType":"calls","source":354,"target":364},{"edgeType":"contains","source":5910,"target":5997},{"edgeType":"contains","source":952,"target":1135},{"edgeType":"contains","source":1717,"target":1731},{"edgeType":"extends","source":2860,"target":36},{"edgeType":"calls","source":5673,"target":370},{"edgeType":"contains","source":4921,"target":4938},{"edgeType":"calls","source":1270,"target":508},{"edgeType":"contains","source":6771,"target":6789},{"edgeType":"contains","source":1848,"target":1903},{"edgeType":"contains","source":3236,"target":3271},{"edgeType":"calls","source":6837,"target":6559},{"edgeType":"calls","source":1172,"target":370},{"edgeType":"calls","source":4243,"target":303},{"edgeType":"calls","source":1270,"target":503},{"edgeType":"calls","source":746,"target":891},{"edgeType":"contains","source":5910,"target":5990},{"edgeType":"calls","source":2537,"target":1394},{"edgeType":"calls","source":4584,"target":303},{"edgeType":"contains","source":6286,"target":3847},{"edgeType":"calls","source":7140,"target":1394},{"edgeType":"contains","source":2212,"target":2247},{"edgeType":"contains","source":2147,"target":2148},{"edgeType":"imports","source":2070,"target":1036},{"edgeType":"calls","source":6531,"target":6532},{"edgeType":"calls","source":5673,"target":369},{"edgeType":"contains","source":1305,"target":1824},{"edgeType":"contains","source":5592,"target":6335},{"edgeType":"calls","source":1817,"target":458},{"edgeType":"contains","source":6770,"target":6814},{"edgeType":"calls","source":1270,"target":502},{"edgeType":"calls","source":4243,"target":304},{"edgeType":"contains","source":5910,"target":5991},{"edgeType":"contains","source":6604,"target":6675},{"edgeType":"contains","source":1683,"target":1734},{"edgeType":"calls","source":1172,"target":369},{"edgeType":"contains","source":1848,"target":1904},{"edgeType":"contains","source":6459,"target":6942},{"edgeType":"contains","source":2244,"target":2313},{"edgeType":"contains","source":5592,"target":6336},{"edgeType":"calls","source":5673,"target":368},{"edgeType":"calls","source":3875,"target":84},{"edgeType":"calls","source":1775,"target":1759},{"edgeType":"calls","source":1817,"target":457},{"edgeType":"contains","source":5285,"target":5287},{"edgeType":"calls","source":1270,"target":505},{"edgeType":"calls","source":6134,"target":5103},{"edgeType":"contains","source":3270,"target":3272},{"edgeType":"contains","source":1123,"target":1125},{"edgeType":"contains","source":4558,"target":4569},{"edgeType":"calls","source":1180,"target":1181},{"edgeType":"calls","source":3327,"target":3328},{"edgeType":"calls","source":1136,"target":431},{"edgeType":"calls","source":2537,"target":1392},{"edgeType":"calls","source":2533,"target":2573},{"edgeType":"calls","source":3128,"target":3155},{"edgeType":"contains","source":5910,"target":5992},{"edgeType":"contains","source":2312,"target":2316},{"edgeType":"contains","source":2212,"target":2245},{"edgeType":"contains","source":2213,"target":2214},{"edgeType":"imports","source":6286,"target":5636},{"edgeType":"calls","source":4591,"target":84},{"edgeType":"contains","source":6471,"target":6571},{"edgeType":"contains","source":6459,"target":6943},{"edgeType":"calls","source":4336,"target":590},{"edgeType":"calls","source":4218,"target":4248},{"edgeType":"calls","source":1360,"target":886},{"edgeType":"contains","source":1037,"target":1676},{"edgeType":"calls","source":4102,"target":443},{"edgeType":"calls","source":1270,"target":504},{"edgeType":"calls","source":4714,"target":4726},{"edgeType":"contains","source":3949,"target":4420},{"edgeType":"calls","source":5646,"target":146},{"edgeType":"calls","source":4102,"target":445},{"edgeType":"calls","source":1172,"target":371},{"edgeType":"calls","source":5673,"target":366},{"edgeType":"contains","source":5910,"target":5993},{"edgeType":"calls","source":2537,"target":1393},{"edgeType":"calls","source":6931,"target":6819},{"edgeType":"calls","source":5032,"target":3324},{"edgeType":"calls","source":4690,"target":4413},{"edgeType":"contains","source":3981,"target":4485},{"edgeType":"calls","source":746,"target":892},{"edgeType":"contains","source":41,"target":2955},{"edgeType":"contains","source":6342,"target":6343},{"edgeType":"contains","source":2213,"target":2215},{"edgeType":"contains","source":1305,"target":1823},{"edgeType":"calls","source":4218,"target":4247},{"edgeType":"contains","source":1037,"target":1675},{"edgeType":"contains","source":920,"target":1074},{"edgeType":"calls","source":7043,"target":144},{"edgeType":"contains","source":5910,"target":5969},{"edgeType":"contains","source":3236,"target":3242},{"edgeType":"calls","source":1239,"target":370},{"edgeType":"calls","source":5336,"target":2323},{"edgeType":"contains","source":1848,"target":1874},{"edgeType":"calls","source":1131,"target":547},{"edgeType":"calls","source":5093,"target":342},{"edgeType":"contains","source":32,"target":33},{"edgeType":"calls","source":4485,"target":164},{"edgeType":"calls","source":6562,"target":1314},{"edgeType":"contains","source":3368,"target":3379},{"edgeType":"contains","source":4095,"target":4097},{"edgeType":"contains","source":4139,"target":2733},{"edgeType":"calls","source":6633,"target":170},{"edgeType":"imports","source":3030,"target":3032},{"edgeType":"contains","source":2212,"target":2218},{"edgeType":"calls","source":3989,"target":1797},{"edgeType":"contains","source":2641,"target":2660},{"edgeType":"calls","source":4310,"target":304},{"edgeType":"contains","source":4717,"target":4898},{"edgeType":"calls","source":6157,"target":5411},{"edgeType":"calls","source":2626,"target":2827},{"edgeType":"contains","source":5910,"target":5970},{"edgeType":"contains","source":3236,"target":3243},{"edgeType":"calls","source":5529,"target":4795},{"edgeType":"calls","source":1239,"target":369},{"edgeType":"calls","source":2533,"target":2539},{"edgeType":"contains","source":5410,"target":5612},{"edgeType":"calls","source":1205,"target":366},{"edgeType":"calls","source":1135,"target":422},{"edgeType":"contains","source":3,"target":1988},{"edgeType":"calls","source":6633,"target":171},{"edgeType":"contains","source":41,"target":3981},{"edgeType":"imports","source":3166,"target":3043},{"edgeType":"contains","source":3368,"target":3378},{"edgeType":"contains","source":2212,"target":2219},{"edgeType":"imports","source":3030,"target":3031},{"edgeType":"contains","source":4359,"target":4368},{"edgeType":"contains","source":6438,"target":6515},{"edgeType":"calls","source":4310,"target":303},{"edgeType":"calls","source":2885,"target":80},{"edgeType":"calls","source":6282,"target":2592},{"edgeType":"contains","source":5910,"target":5971},{"edgeType":"contains","source":5592,"target":6316},{"edgeType":"calls","source":6938,"target":6572},{"edgeType":"calls","source":1205,"target":369},{"edgeType":"calls","source":5075,"target":898},{"edgeType":"calls","source":6863,"target":6783},{"edgeType":"contains","source":1848,"target":1872},{"edgeType":"calls","source":6728,"target":6740},{"edgeType":"calls","source":4495,"target":3023},{"edgeType":"contains","source":2212,"target":2216},{"edgeType":"calls","source":2578,"target":84},{"edgeType":"calls","source":4615,"target":4588},{"edgeType":"contains","source":3368,"target":3377},{"edgeType":"contains","source":1302,"target":4000},{"edgeType":"contains","source":4359,"target":4367},{"edgeType":"contains","source":2641,"target":2658},{"edgeType":"calls","source":4169,"target":1500},{"edgeType":"contains","source":6604,"target":6655},{"edgeType":"calls","source":4184,"target":2092},{"edgeType":"calls","source":1410,"target":1412},{"edgeType":"contains","source":5910,"target":5972},{"edgeType":"calls","source":1205,"target":368},{"edgeType":"extends","source":4839,"target":36},{"edgeType":"extends","source":6851,"target":36},{"edgeType":"calls","source":881,"target":898},{"edgeType":"calls","source":1239,"target":371},{"edgeType":"calls","source":6728,"target":6741},{"edgeType":"calls","source":6767,"target":4475},{"edgeType":"calls","source":5338,"target":144},{"edgeType":"contains","source":3368,"target":3376},{"edgeType":"contains","source":2641,"target":2659},{"edgeType":"extends","source":3441,"target":36},{"edgeType":"contains","source":3030,"target":3284},{"edgeType":"contains","source":2872,"target":2897},{"edgeType":"calls","source":4315,"target":144},{"edgeType":"calls","source":6728,"target":6742},{"edgeType":"calls","source":3662,"target":303},{"edgeType":"contains","source":957,"target":959},{"edgeType":"calls","source":1239,"target":366},{"edgeType":"contains","source":3496,"target":3643},{"edgeType":"contains","source":5910,"target":5965},{"edgeType":"calls","source":3292,"target":146},{"edgeType":"contains","source":1305,"target":1799},{"edgeType":"contains","source":3368,"target":3383},{"edgeType":"calls","source":3161,"target":2092},{"edgeType":"extends","source":3032,"target":36},{"edgeType":"contains","source":3,"target":936},{"edgeType":"calls","source":2269,"target":148},{"edgeType":"contains","source":2641,"target":2664},{"edgeType":"imports","source":5410,"target":78},{"edgeType":"calls","source":6431,"target":84},{"edgeType":"contains","source":5910,"target":5966},{"edgeType":"calls","source":6767,"target":4477},{"edgeType":"calls","source":3635,"target":84},{"edgeType":"contains","source":6539,"target":6551},{"edgeType":"calls","source":3662,"target":304},{"edgeType":"contains","source":957,"target":958},{"edgeType":"contains","source":1848,"target":1879},{"edgeType":"calls","source":7068,"target":431},{"edgeType":"contains","source":3496,"target":3642},{"edgeType":"calls","source":6534,"target":6415},{"edgeType":"calls","source":6688,"target":2698},{"edgeType":"calls","source":6117,"target":304},{"edgeType":"contains","source":3368,"target":3382},{"edgeType":"calls","source":1239,"target":364},{"edgeType":"contains","source":30,"target":98},{"edgeType":"contains","source":4192,"target":4264},{"edgeType":"calls","source":4184,"target":2091},{"edgeType":"calls","source":530,"target":146},{"edgeType":"imports","source":5410,"target":79},{"edgeType":"calls","source":487,"target":422},{"edgeType":"contains","source":5910,"target":5967},{"edgeType":"contains","source":3496,"target":3641},{"edgeType":"calls","source":1352,"target":1093},{"edgeType":"contains","source":5592,"target":6312},{"edgeType":"calls","source":1120,"target":886},{"edgeType":"calls","source":1135,"target":421},{"edgeType":"calls","source":1239,"target":368},{"edgeType":"calls","source":6117,"target":303},{"edgeType":"contains","source":3368,"target":3381},{"edgeType":"contains","source":4192,"target":4263},{"edgeType":"contains","source":2212,"target":2220},{"edgeType":"calls","source":525,"target":304},{"edgeType":"contains","source":6438,"target":6512},{"edgeType":"calls","source":2610,"target":2259},{"edgeType":"calls","source":6429,"target":144},{"edgeType":"contains","source":4668,"target":1134},{"edgeType":"contains","source":5910,"target":5968},{"edgeType":"contains","source":957,"target":960},{"edgeType":"contains","source":1848,"target":1877},{"edgeType":"calls","source":1205,"target":364},{"edgeType":"calls","source":1349,"target":1185},{"edgeType":"contains","source":5592,"target":6313},{"edgeType":"calls","source":1115,"target":1039},{"edgeType":"contains","source":1305,"target":1798},{"edgeType":"contains","source":1303,"target":1860},{"edgeType":"calls","source":3161,"target":2091},{"edgeType":"contains","source":3368,"target":3380},{"edgeType":"calls","source":1844,"target":1695},{"edgeType":"contains","source":4095,"target":4098},{"edgeType":"imports","source":5166,"target":4474},{"edgeType":"calls","source":525,"target":303},{"edgeType":"contains","source":2641,"target":2663},{"edgeType":"calls","source":157,"target":84},{"edgeType":"contains","source":952,"target":1118},{"edgeType":"calls","source":6632,"target":6551},{"edgeType":"imports","source":6604,"target":49},{"edgeType":"calls","source":5201,"target":157},{"edgeType":"contains","source":3496,"target":3647},{"edgeType":"contains","source":4788,"target":4820},{"edgeType":"imports","source":1907,"target":1914},{"edgeType":"contains","source":3949,"target":4403},{"edgeType":"contains","source":2641,"target":2668},{"edgeType":"calls","source":1991,"target":304},{"edgeType":"contains","source":4788,"target":4819},{"edgeType":"calls","source":4101,"target":431},{"edgeType":"imports","source":3807,"target":79},{"edgeType":"calls","source":4655,"target":171},{"edgeType":"contains","source":5910,"target":5978},{"edgeType":"contains","source":4192,"target":4269},{"edgeType":"calls","source":2575,"target":171},{"edgeType":"calls","source":5796,"target":1795},{"edgeType":"contains","source":6459,"target":6929},{"edgeType":"contains","source":1037,"target":1653},{"edgeType":"contains","source":3496,"target":3646},{"edgeType":"contains","source":3368,"target":3386},{"edgeType":"calls","source":7102,"target":2553},{"edgeType":"calls","source":5444,"target":2136},{"edgeType":"calls","source":6926,"target":6952},{"edgeType":"calls","source":1991,"target":303},{"edgeType":"calls","source":1132,"target":1563},{"edgeType":"calls","source":6828,"target":6819},{"edgeType":"contains","source":5,"target":5105},{"edgeType":"contains","source":5910,"target":5979},{"edgeType":"contains","source":4095,"target":4104},{"edgeType":"contains","source":4075,"target":3667},{"edgeType":"calls","source":4655,"target":170},{"edgeType":"calls","source":5876,"target":371},{"edgeType":"contains","source":3030,"target":3292},{"edgeType":"contains","source":6459,"target":6930},{"edgeType":"contains","source":3496,"target":3645},{"edgeType":"calls","source":5605,"target":5601},{"edgeType":"contains","source":3368,"target":3385},{"edgeType":"calls","source":3632,"target":3341},{"edgeType":"calls","source":1248,"target":84},{"edgeType":"extends","source":5726,"target":36},{"edgeType":"calls","source":6946,"target":1048},{"edgeType":"calls","source":7000,"target":431},{"edgeType":"calls","source":487,"target":421},{"edgeType":"contains","source":5910,"target":5980},{"edgeType":"contains","source":5592,"target":6325},{"edgeType":"calls","source":5876,"target":370},{"edgeType":"contains","source":957,"target":964},{"edgeType":"calls","source":4292,"target":4021},{"edgeType":"contains","source":3496,"target":3644},{"edgeType":"contains","source":4921,"target":4922},{"edgeType":"calls","source":6087,"target":171},{"edgeType":"calls","source":1418,"target":1156},{"edgeType":"contains","source":6771,"target":6773},{"edgeType":"contains","source":3368,"target":3384},{"edgeType":"calls","source":1962,"target":147},{"edgeType":"calls","source":1209,"target":1292},{"edgeType":"contains","source":4095,"target":4102},{"edgeType":"calls","source":5471,"target":4468},{"edgeType":"contains","source":4788,"target":4816},{"edgeType":"contains","source":5780,"target":5783},{"edgeType":"calls","source":2575,"target":170},{"edgeType":"contains","source":5910,"target":5981},{"edgeType":"contains","source":30,"target":6446},{"edgeType":"calls","source":2645,"target":114},{"edgeType":"calls","source":5739,"target":5673},{"edgeType":"contains","source":6471,"target":6552},{"edgeType":"calls","source":5092,"target":4589},{"edgeType":"contains","source":3496,"target":3651},{"edgeType":"contains","source":5910,"target":5973},{"edgeType":"calls","source":6087,"target":170},{"edgeType":"contains","source":3368,"target":3391},{"edgeType":"contains","source":5592,"target":6318},{"edgeType":"contains","source":4788,"target":4824},{"edgeType":"calls","source":5876,"target":369},{"edgeType":"contains","source":453,"target":735},{"edgeType":"imports","source":2898,"target":2900},{"edgeType":"calls","source":1209,"target":1287},{"edgeType":"calls","source":2907,"target":445},{"edgeType":"calls","source":6936,"target":303},{"edgeType":"contains","source":5910,"target":5974},{"edgeType":"contains","source":30,"target":2221},{"edgeType":"calls","source":4790,"target":210},{"edgeType":"contains","source":5732,"target":6207},{"edgeType":"contains","source":2212,"target":2231},{"edgeType":"contains","source":3496,"target":3650},{"edgeType":"calls","source":4317,"target":4301},{"edgeType":"contains","source":4788,"target":4823},{"edgeType":"contains","source":1305,"target":1808},{"edgeType":"calls","source":3821,"target":3823},{"edgeType":"contains","source":3368,"target":3390},{"edgeType":"calls","source":5672,"target":5635},{"edgeType":"calls","source":3677,"target":888},{"edgeType":"calls","source":5876,"target":368},{"edgeType":"contains","source":453,"target":734},{"edgeType":"calls","source":4078,"target":84},{"edgeType":"calls","source":6289,"target":4477},{"edgeType":"contains","source":5910,"target":5975},{"edgeType":"contains","source":3732,"target":3734},{"edgeType":"calls","source":1209,"target":1286},{"edgeType":"calls","source":6936,"target":304},{"edgeType":"contains","source":3981,"target":4471},{"edgeType":"calls","source":4790,"target":209},{"edgeType":"calls","source":6926,"target":6956},{"edgeType":"contains","source":3954,"target":4251},{"edgeType":"imports","source":1907,"target":1908},{"edgeType":"contains","source":3496,"target":3649},{"edgeType":"extends","source":6817,"target":36},{"edgeType":"contains","source":4788,"target":4822},{"edgeType":"contains","source":3368,"target":3389},{"edgeType":"contains","source":1379,"target":568},{"edgeType":"calls","source":4104,"target":332},{"edgeType":"calls","source":4751,"target":4588},{"edgeType":"calls","source":1209,"target":1289},{"edgeType":"contains","source":1717,"target":1718},{"edgeType":"calls","source":5237,"target":5377},{"edgeType":"contains","source":6604,"target":6659},{"edgeType":"calls","source":6728,"target":6753},{"edgeType":"contains","source":5910,"target":5976},{"edgeType":"calls","source":2870,"target":533},{"edgeType":"calls","source":2907,"target":443},{"edgeType":"contains","source":3981,"target":4470},{"edgeType":"calls","source":2984,"target":170},{"edgeType":"contains","source":6459,"target":6927},{"edgeType":"contains","source":5592,"target":6321},{"edgeType":"calls","source":5358,"target":568},{"edgeType":"contains","source":3496,"target":3648},{"edgeType":"contains","source":4788,"target":4821},{"edgeType":"contains","source":3368,"target":3388},{"edgeType":"calls","source":5876,"target":366},{"edgeType":"calls","source":4104,"target":333},{"edgeType":"calls","source":600,"target":84},{"edgeType":"contains","source":4668,"target":1141},{"edgeType":"calls","source":1209,"target":1288},{"edgeType":"calls","source":1244,"target":1260},{"edgeType":"contains","source":6604,"target":6660},{"edgeType":"calls","source":5472,"target":4433},{"edgeType":"calls","source":5237,"target":5376},{"edgeType":"contains","source":5910,"target":5977},{"edgeType":"calls","source":6902,"target":303},{"edgeType":"calls","source":2984,"target":171},{"edgeType":"contains","source":4075,"target":3669},{"edgeType":"contains","source":6106,"target":6243},{"edgeType":"extends","source":6032,"target":36},{"edgeType":"contains","source":3,"target":3029},{"edgeType":"calls","source":4446,"target":332},{"edgeType":"calls","source":4291,"target":3023},{"edgeType":"calls","source":2329,"target":422},{"edgeType":"contains","source":2872,"target":2882},{"edgeType":"contains","source":4788,"target":4795},{"edgeType":"contains","source":4717,"target":4882},{"edgeType":"contains","source":4502,"target":5204},{"edgeType":"calls","source":4086,"target":4092},{"edgeType":"contains","source":5910,"target":5953},{"edgeType":"calls","source":594,"target":298},{"edgeType":"contains","source":1947,"target":1960},{"edgeType":"imports","source":2581,"target":2136},{"edgeType":"calls","source":6959,"target":6960},{"edgeType":"calls","source":5065,"target":170},{"edgeType":"contains","source":5,"target":2966},{"edgeType":"contains","source":3496,"target":3621},{"edgeType":"calls","source":1052,"target":897},{"edgeType":"calls","source":1690,"target":146},{"edgeType":"calls","source":2370,"target":209},{"edgeType":"calls","source":6045,"target":443},{"edgeType":"contains","source":2641,"target":2645},{"edgeType":"contains","source":1186,"target":1237},{"edgeType":"contains","source":4502,"target":5203},{"edgeType":"calls","source":749,"target":777},{"edgeType":"contains","source":5910,"target":5954},{"edgeType":"calls","source":1213,"target":1191},{"edgeType":"contains","source":3297,"target":3449},{"edgeType":"calls","source":2533,"target":2556},{"edgeType":"contains","source":5679,"target":5716},{"edgeType":"calls","source":4649,"target":4609},{"edgeType":"contains","source":1947,"target":1961},{"edgeType":"calls","source":1349,"target":146},{"edgeType":"calls","source":2996,"target":3001},{"edgeType":"calls","source":2897,"target":2899},{"edgeType":"contains","source":3496,"target":3620},{"edgeType":"calls","source":7068,"target":6754},{"edgeType":"calls","source":7058,"target":7064},{"edgeType":"calls","source":1587,"target":171},{"edgeType":"contains","source":1417,"target":1475},{"edgeType":"contains","source":4722,"target":4725},{"edgeType":"contains","source":6438,"target":6499},{"edgeType":"contains","source":6539,"target":6540},{"edgeType":"calls","source":2837,"target":528},{"edgeType":"calls","source":5510,"target":5399},{"edgeType":"contains","source":4502,"target":5202},{"edgeType":"calls","source":2873,"target":469},{"edgeType":"contains","source":5910,"target":5955},{"edgeType":"contains","source":5679,"target":5717},{"edgeType":"calls","source":3453,"target":458},{"edgeType":"calls","source":6795,"target":2533},{"edgeType":"calls","source":6931,"target":431},{"edgeType":"calls","source":1587,"target":170},{"edgeType":"contains","source":2641,"target":2643},{"edgeType":"calls","source":2329,"target":421},{"edgeType":"contains","source":2872,"target":2881},{"edgeType":"contains","source":2540,"target":2602},{"edgeType":"calls","source":5605,"target":339},{"edgeType":"contains","source":2314,"target":5380},{"edgeType":"contains","source":4502,"target":5201},{"edgeType":"contains","source":5910,"target":5956},{"edgeType":"contains","source":4075,"target":3640},{"edgeType":"contains","source":5448,"target":5472},{"edgeType":"contains","source":5679,"target":5718},{"edgeType":"contains","source":3981,"target":4440},{"edgeType":"calls","source":3023,"target":3219},{"edgeType":"contains","source":4717,"target":4886},{"edgeType":"contains","source":5679,"target":5710},{"edgeType":"contains","source":3981,"target":4447},{"edgeType":"calls","source":1726,"target":84},{"edgeType":"calls","source":7058,"target":7066},{"edgeType":"calls","source":5913,"target":304},{"edgeType":"calls","source":4518,"target":210},{"edgeType":"contains","source":428,"target":429},{"edgeType":"contains","source":5908,"target":7068},{"edgeType":"calls","source":4752,"target":4584},{"edgeType":"calls","source":4899,"target":1084},{"edgeType":"contains","source":1848,"target":1862},{"edgeType":"calls","source":5605,"target":338},{"edgeType":"contains","source":5679,"target":5711},{"edgeType":"extends","source":440,"target":36},{"edgeType":"contains","source":5910,"target":5949},{"edgeType":"contains","source":2872,"target":2887},{"edgeType":"calls","source":5913,"target":303},{"edgeType":"calls","source":4435,"target":1725},{"edgeType":"calls","source":4518,"target":209},{"edgeType":"calls","source":6089,"target":5417},{"edgeType":"contains","source":6619,"target":2997},{"edgeType":"calls","source":2326,"target":2626},{"edgeType":"calls","source":2837,"target":527},{"edgeType":"contains","source":5910,"target":5950},{"edgeType":"calls","source":2802,"target":555},{"edgeType":"calls","source":4752,"target":4583},{"edgeType":"calls","source":3453,"target":457},{"edgeType":"calls","source":5605,"target":337},{"edgeType":"calls","source":1695,"target":1043},{"edgeType":"calls","source":6840,"target":84},{"edgeType":"calls","source":3023,"target":3217},{"edgeType":"calls","source":6597,"target":6560},{"edgeType":"calls","source":3194,"target":3198},{"edgeType":"extends","source":3236,"target":36},{"edgeType":"calls","source":6296,"target":56},{"edgeType":"calls","source":594,"target":295},{"edgeType":"calls","source":4269,"target":527},{"edgeType":"contains","source":2540,"target":2606},{"edgeType":"calls","source":2530,"target":527},{"edgeType":"contains","source":5910,"target":5951},{"edgeType":"calls","source":3008,"target":508},{"edgeType":"contains","source":3954,"target":4225},{"edgeType":"calls","source":7063,"target":571},{"edgeType":"contains","source":1947,"target":1962},{"edgeType":"contains","source":5647,"target":5648},{"edgeType":"calls","source":6804,"target":144},{"edgeType":"calls","source":3463,"target":144},{"edgeType":"calls","source":1080,"target":1084},{"edgeType":"calls","source":6541,"target":898},{"edgeType":"calls","source":2530,"target":528},{"edgeType":"calls","source":4269,"target":528},{"edgeType":"calls","source":142,"target":565},{"edgeType":"contains","source":4502,"target":5206},{"edgeType":"contains","source":4502,"target":5205},{"edgeType":"contains","source":5910,"target":5952},{"edgeType":"contains","source":5166,"target":2591},{"edgeType":"calls","source":3008,"target":509},{"edgeType":"contains","source":3166,"target":1170},{"edgeType":"calls","source":7063,"target":572},{"edgeType":"imports","source":3807,"target":78},{"edgeType":"calls","source":3124,"target":84},{"edgeType":"contains","source":1641,"target":879},{"edgeType":"calls","source":5461,"target":571},{"edgeType":"calls","source":483,"target":559},{"edgeType":"calls","source":3311,"target":2740},{"edgeType":"contains","source":1848,"target":1866},{"edgeType":"calls","source":3161,"target":3162},{"edgeType":"contains","source":2673,"target":3774},{"edgeType":"calls","source":7063,"target":573},{"edgeType":"contains","source":6286,"target":3818},{"edgeType":"contains","source":5910,"target":5961},{"edgeType":"contains","source":5908,"target":6023},{"edgeType":"contains","source":2311,"target":2312},{"edgeType":"calls","source":6863,"target":431},{"edgeType":"calls","source":4224,"target":4035},{"edgeType":"contains","source":4359,"target":4361},{"edgeType":"calls","source":3008,"target":506},{"edgeType":"contains","source":3166,"target":1175},{"edgeType":"contains","source":5416,"target":5418},{"edgeType":"calls","source":3194,"target":3197},{"edgeType":"contains","source":1848,"target":1867},{"edgeType":"calls","source":1063,"target":548},{"edgeType":"imports","source":6432,"target":78},{"edgeType":"contains","source":2060,"target":580},{"edgeType":"calls","source":4485,"target":171},{"edgeType":"contains","source":5910,"target":5962},{"edgeType":"contains","source":4359,"target":4360},{"edgeType":"calls","source":5742,"target":5599},{"edgeType":"imports","source":6432,"target":79},{"edgeType":"calls","source":5092,"target":4609},{"edgeType":"calls","source":3008,"target":507},{"edgeType":"calls","source":5143,"target":5142},{"edgeType":"calls","source":6296,"target":6382},{"edgeType":"calls","source":4655,"target":4413},{"edgeType":"contains","source":5416,"target":5417},{"edgeType":"calls","source":3462,"target":171},{"edgeType":"contains","source":2641,"target":2650},{"edgeType":"contains","source":1848,"target":1864},{"edgeType":"extends","source":713,"target":36},{"edgeType":"calls","source":2797,"target":2816},{"edgeType":"calls","source":4953,"target":1517},{"edgeType":"contains","source":5910,"target":5963},{"edgeType":"contains","source":3,"target":5153},{"edgeType":"calls","source":3008,"target":504},{"edgeType":"calls","source":5672,"target":5654},{"edgeType":"calls","source":4485,"target":170},{"edgeType":"contains","source":3166,"target":1173},{"edgeType":"calls","source":6784,"target":2882},{"edgeType":"contains","source":6438,"target":6508},{"edgeType":"calls","source":5336,"target":215},{"edgeType":"contains","source":3367,"target":3398},{"edgeType":"calls","source":6863,"target":6776},{"edgeType":"calls","source":4088,"target":4021},{"edgeType":"extends","source":3543,"target":36},{"edgeType":"contains","source":5910,"target":5964},{"edgeType":"contains","source":5592,"target":6309},{"edgeType":"calls","source":3008,"target":505},{"edgeType":"contains","source":6459,"target":6915},{"edgeType":"calls","source":1345,"target":1321},{"edgeType":"calls","source":3872,"target":146},{"edgeType":"calls","source":1311,"target":1318},{"edgeType":"calls","source":6258,"target":171},{"edgeType":"contains","source":2540,"target":2616},{"edgeType":"contains","source":5218,"target":5219},{"edgeType":"contains","source":3236,"target":3238},{"edgeType":"calls","source":1205,"target":371},{"edgeType":"contains","source":6638,"target":6644},{"edgeType":"calls","source":5065,"target":157},{"edgeType":"calls","source":1041,"target":170},{"edgeType":"contains","source":1907,"target":2155},{"edgeType":"calls","source":4944,"target":737},{"edgeType":"contains","source":30,"target":90},{"edgeType":"calls","source":2797,"target":2814},{"edgeType":"extends","source":1815,"target":1816},{"edgeType":"contains","source":6438,"target":6502},{"edgeType":"contains","source":3,"target":5156},{"edgeType":"calls","source":3008,"target":502},{"edgeType":"contains","source":5679,"target":5719},{"edgeType":"contains","source":1641,"target":888},{"edgeType":"contains","source":5910,"target":5957},{"edgeType":"contains","source":4359,"target":4365},{"edgeType":"contains","source":3368,"target":3375},{"edgeType":"contains","source":1379,"target":554},{"edgeType":"extends","source":2077,"target":36},{"edgeType":"contains","source":4722,"target":4739},{"edgeType":"calls","source":6444,"target":1797},{"edgeType":"calls","source":4851,"target":448},{"edgeType":"contains","source":1848,"target":1871},{"edgeType":"calls","source":6258,"target":170},{"edgeType":"calls","source":3462,"target":170},{"edgeType":"extends","source":2141,"target":167},{"edgeType":"calls","source":6206,"target":3896},{"edgeType":"calls","source":2797,"target":2815},{"edgeType":"contains","source":30,"target":89},{"edgeType":"contains","source":5910,"target":5958},{"edgeType":"calls","source":1205,"target":370},{"edgeType":"calls","source":4953,"target":1514},{"edgeType":"contains","source":6440,"target":6441},{"edgeType":"calls","source":3008,"target":503},{"edgeType":"contains","source":3368,"target":3374},{"edgeType":"contains","source":1122,"target":1123},{"edgeType":"contains","source":5473,"target":483},{"edgeType":"calls","source":4851,"target":447},{"edgeType":"contains","source":5410,"target":5607},{"edgeType":"contains","source":5910,"target":5959},{"edgeType":"contains","source":32,"target":6373},{"edgeType":"contains","source":6539,"target":6544},{"edgeType":"calls","source":426,"target":210},{"edgeType":"extends","source":4873,"target":36},{"edgeType":"calls","source":3224,"target":146},{"edgeType":"calls","source":6964,"target":6819},{"edgeType":"calls","source":2978,"target":372},{"edgeType":"contains","source":2872,"target":2892},{"edgeType":"contains","source":3166,"target":1177},{"edgeType":"calls","source":6484,"target":559},{"edgeType":"contains","source":3954,"target":4232},{"edgeType":"contains","source":3236,"target":3237},{"edgeType":"contains","source":1848,"target":1869},{"edgeType":"calls","source":6296,"target":4275},{"edgeType":"contains","source":2540,"target":2615},{"edgeType":"calls","source":4581,"target":4588},{"edgeType":"calls","source":426,"target":209},{"edgeType":"calls","source":1041,"target":171},{"edgeType":"contains","source":5910,"target":5960},{"edgeType":"contains","source":5,"target":1923},{"edgeType":"contains","source":3,"target":928},{"edgeType":"calls","source":4485,"target":165},{"edgeType":"calls","source":3955,"target":1797},{"edgeType":"calls","source":2226,"target":431},{"edgeType":"contains","source":4788,"target":4804},{"edgeType":"contains","source":3166,"target":1178},{"edgeType":"imports","source":130,"target":1795},{"edgeType":"contains","source":5910,"target":5936},{"edgeType":"calls","source":5651,"target":56},{"edgeType":"contains","source":2376,"target":2386},{"edgeType":"contains","source":5250,"target":5255},{"edgeType":"calls","source":6934,"target":6793},{"edgeType":"calls","source":883,"target":934},{"edgeType":"calls","source":1079,"target":144},{"edgeType":"calls","source":4652,"target":4599},{"edgeType":"calls","source":6896,"target":572},{"edgeType":"imports","source":4668,"target":1704},{"edgeType":"contains","source":2863,"target":6315},{"edgeType":"contains","source":6459,"target":6887},{"edgeType":"calls","source":1308,"target":443},{"edgeType":"contains","source":5910,"target":5937},{"edgeType":"contains","source":7100,"target":7101},{"edgeType":"calls","source":3232,"target":3167},{"edgeType":"contains","source":5250,"target":5254},{"edgeType":"contains","source":4091,"target":2072},{"edgeType":"calls","source":3220,"target":368},{"edgeType":"calls","source":6865,"target":6819},{"edgeType":"calls","source":4764,"target":1126},{"edgeType":"calls","source":6896,"target":573},{"edgeType":"calls","source":2361,"target":571},{"edgeType":"calls","source":2134,"target":209},{"edgeType":"calls","source":1822,"target":364},{"edgeType":"contains","source":5250,"target":5253},{"edgeType":"calls","source":6688,"target":7022},{"edgeType":"contains","source":5910,"target":5938},{"edgeType":"contains","source":7100,"target":7102},{"edgeType":"imports","source":5232,"target":78},{"edgeType":"calls","source":1138,"target":431},{"edgeType":"calls","source":7037,"target":431},{"edgeType":"calls","source":6640,"target":1111},{"edgeType":"contains","source":3949,"target":4359},{"edgeType":"calls","source":5020,"target":588},{"edgeType":"calls","source":3024,"target":1155},{"edgeType":"contains","source":3496,"target":3604},{"edgeType":"contains","source":4192,"target":4226},{"edgeType":"calls","source":3911,"target":84},{"edgeType":"contains","source":5,"target":2953},{"edgeType":"calls","source":144,"target":591},{"edgeType":"calls","source":4620,"target":304},{"edgeType":"calls","source":4591,"target":146},{"edgeType":"calls","source":1697,"target":1071},{"edgeType":"calls","source":1308,"target":445},{"edgeType":"contains","source":5250,"target":5252},{"edgeType":"calls","source":6862,"target":572},{"edgeType":"contains","source":5217,"target":5218},{"edgeType":"calls","source":6723,"target":4881},{"edgeType":"contains","source":7100,"target":7103},{"edgeType":"contains","source":5910,"target":5939},{"edgeType":"calls","source":5532,"target":571},{"edgeType":"calls","source":5480,"target":1126},{"edgeType":"contains","source":4091,"target":4184},{"edgeType":"calls","source":3220,"target":366},{"edgeType":"calls","source":6702,"target":4475},{"edgeType":"calls","source":883,"target":935},{"edgeType":"contains","source":2070,"target":2358},{"edgeType":"imports","source":5232,"target":79},{"edgeType":"calls","source":4620,"target":303},{"edgeType":"calls","source":1822,"target":366},{"edgeType":"contains","source":328,"target":341},{"edgeType":"calls","source":4968,"target":84},{"edgeType":"calls","source":6862,"target":573},{"edgeType":"extends","source":1409,"target":437},{"edgeType":"calls","source":3024,"target":1153},{"edgeType":"imports","source":2879,"target":79},{"edgeType":"calls","source":6831,"target":6819},{"edgeType":"contains","source":5250,"target":5259},{"edgeType":"calls","source":1317,"target":161},{"edgeType":"contains","source":3496,"target":3610},{"edgeType":"contains","source":5910,"target":5932},{"edgeType":"calls","source":5336,"target":304},{"edgeType":"contains","source":1947,"target":1948},{"edgeType":"contains","source":6459,"target":6883},{"edgeType":"calls","source":6702,"target":4477},{"edgeType":"extends","source":1409,"target":438},{"edgeType":"contains","source":3004,"target":3007},{"edgeType":"imports","source":2879,"target":78},{"edgeType":"calls","source":6729,"target":469},{"edgeType":"contains","source":5250,"target":5258},{"edgeType":"calls","source":3220,"target":364},{"edgeType":"calls","source":1317,"target":160},{"edgeType":"contains","source":5910,"target":5933},{"edgeType":"calls","source":5336,"target":303},{"edgeType":"contains","source":2070,"target":2364},{"edgeType":"calls","source":1766,"target":1039},{"edgeType":"contains","source":41,"target":3952},{"edgeType":"calls","source":4693,"target":152},{"edgeType":"contains","source":5910,"target":5934},{"edgeType":"contains","source":5250,"target":5257},{"edgeType":"calls","source":6976,"target":212},{"edgeType":"calls","source":2735,"target":2711},{"edgeType":"calls","source":3452,"target":568},{"edgeType":"contains","source":41,"target":2898},{"edgeType":"contains","source":5910,"target":5935},{"edgeType":"contains","source":6604,"target":6619},{"edgeType":"calls","source":4959,"target":4588},{"edgeType":"contains","source":5250,"target":5256},{"edgeType":"contains","source":5388,"target":978},{"edgeType":"contains","source":1186,"target":1227},{"edgeType":"calls","source":6606,"target":56},{"edgeType":"calls","source":2974,"target":588},{"edgeType":"calls","source":6486,"target":6947},{"edgeType":"contains","source":3954,"target":4207},{"edgeType":"contains","source":2070,"target":2362},{"edgeType":"calls","source":1550,"target":333},{"edgeType":"calls","source":157,"target":177},{"edgeType":"contains","source":6459,"target":6895},{"edgeType":"extends","source":6084,"target":5617},{"edgeType":"contains","source":2872,"target":2874},{"edgeType":"contains","source":3496,"target":3614},{"edgeType":"contains","source":1186,"target":1230},{"edgeType":"contains","source":1947,"target":1952},{"edgeType":"calls","source":1958,"target":369},{"edgeType":"contains","source":5910,"target":5945},{"edgeType":"contains","source":2540,"target":2595},{"edgeType":"contains","source":328,"target":345},{"edgeType":"imports","source":1379,"target":80},{"edgeType":"calls","source":1550,"target":332},{"edgeType":"contains","source":30,"target":6411},{"edgeType":"calls","source":2735,"target":2710},{"edgeType":"contains","source":6459,"target":6896},{"edgeType":"contains","source":3496,"target":3613},{"edgeType":"contains","source":4691,"target":5678},{"edgeType":"calls","source":1172,"target":422},{"edgeType":"calls","source":6145,"target":588},{"edgeType":"calls","source":1958,"target":368},{"edgeType":"contains","source":163,"target":174},{"edgeType":"contains","source":5910,"target":5946},{"edgeType":"contains","source":5908,"target":7065},{"edgeType":"calls","source":2983,"target":304},{"edgeType":"contains","source":5679,"target":5708},{"edgeType":"imports","source":1379,"target":79},{"edgeType":"contains","source":3004,"target":894},{"edgeType":"calls","source":6833,"target":421},{"edgeType":"calls","source":6877,"target":114},{"edgeType":"calls","source":4993,"target":4588},{"edgeType":"calls","source":5063,"target":304},{"edgeType":"calls","source":4963,"target":2347},{"edgeType":"calls","source":6473,"target":1011},{"edgeType":"contains","source":1302,"target":3975},{"edgeType":"calls","source":1184,"target":1111},{"edgeType":"calls","source":1413,"target":354},{"edgeType":"calls","source":1317,"target":159},{"edgeType":"calls","source":3567,"target":170},{"edgeType":"contains","source":2070,"target":2365},{"edgeType":"extends","source":5241,"target":36},{"edgeType":"calls","source":1958,"target":371},{"edgeType":"calls","source":6913,"target":56},{"edgeType":"contains","source":4502,"target":5194},{"edgeType":"contains","source":5910,"target":5947},{"edgeType":"calls","source":6461,"target":304},{"edgeType":"extends","source":1779,"target":1654},{"edgeType":"imports","source":1379,"target":78},{"edgeType":"calls","source":4963,"target":2346},{"edgeType":"contains","source":3004,"target":895},{"edgeType":"calls","source":6833,"target":422},{"edgeType":"contains","source":2872,"target":2873},{"edgeType":"calls","source":5063,"target":303},{"edgeType":"calls","source":3567,"target":171},{"edgeType":"contains","source":1186,"target":1231},{"edgeType":"contains","source":3228,"target":3464},{"edgeType":"contains","source":6770,"target":6771},{"edgeType":"contains","source":3496,"target":3611},{"edgeType":"contains","source":1379,"target":532},{"edgeType":"calls","source":5432,"target":1548},{"edgeType":"calls","source":1958,"target":370},{"edgeType":"contains","source":2540,"target":2594},{"edgeType":"calls","source":6252,"target":5725},{"edgeType":"contains","source":2070,"target":2366},{"edgeType":"calls","source":6461,"target":303},{"edgeType":"calls","source":6464,"target":210},{"edgeType":"calls","source":2297,"target":431},{"edgeType":"contains","source":163,"target":176},{"edgeType":"contains","source":5910,"target":5948},{"edgeType":"contains","source":139,"target":923},{"edgeType":"contains","source":2872,"target":2878},{"edgeType":"calls","source":4963,"target":2345},{"edgeType":"calls","source":144,"target":576},{"edgeType":"contains","source":5910,"target":5940},{"edgeType":"contains","source":4788,"target":4791},{"edgeType":"calls","source":5681,"target":171},{"edgeType":"calls","source":4106,"target":371},{"edgeType":"calls","source":5432,"target":1547},{"edgeType":"contains","source":4502,"target":5200},{"edgeType":"calls","source":3215,"target":509},{"edgeType":"contains","source":5448,"target":5471},{"edgeType":"calls","source":6862,"target":582},{"edgeType":"calls","source":6464,"target":209},{"edgeType":"calls","source":2566,"target":545},{"edgeType":"calls","source":2983,"target":303},{"edgeType":"contains","source":1417,"target":1474},{"edgeType":"contains","source":5910,"target":5941},{"edgeType":"calls","source":5681,"target":170},{"edgeType":"extends","source":6980,"target":36},{"edgeType":"contains","source":4691,"target":5683},{"edgeType":"contains","source":2674,"target":2675},{"edgeType":"contains","source":1186,"target":1233},{"edgeType":"calls","source":1720,"target":1400},{"edgeType":"calls","source":3636,"target":144},{"edgeType":"contains","source":1848,"target":1855},{"edgeType":"calls","source":1958,"target":364},{"edgeType":"calls","source":5432,"target":1546},{"edgeType":"contains","source":4691,"target":5682},{"edgeType":"contains","source":5910,"target":5942},{"edgeType":"contains","source":3796,"target":3831},{"edgeType":"calls","source":4963,"target":2344},{"edgeType":"contains","source":1683,"target":1685},{"edgeType":"calls","source":6932,"target":527},{"edgeType":"contains","source":5,"target":1905},{"edgeType":"contains","source":41,"target":6074},{"edgeType":"contains","source":3981,"target":4438},{"edgeType":"contains","source":163,"target":178},{"edgeType":"calls","source":4693,"target":144},{"edgeType":"contains","source":6459,"target":6893},{"edgeType":"imports","source":130,"target":1797},{"edgeType":"contains","source":3496,"target":3616},{"edgeType":"calls","source":5163,"target":4599},{"edgeType":"contains","source":4788,"target":4789},{"edgeType":"calls","source":4106,"target":369},{"edgeType":"contains","source":1815,"target":1818},{"edgeType":"contains","source":4717,"target":4875},{"edgeType":"calls","source":5432,"target":1545},{"edgeType":"calls","source":1172,"target":421},{"edgeType":"imports","source":4668,"target":1702},{"edgeType":"contains","source":4502,"target":5198},{"edgeType":"contains","source":5910,"target":5943},{"edgeType":"calls","source":6808,"target":144},{"edgeType":"calls","source":3215,"target":507},{"edgeType":"calls","source":2578,"target":171},{"edgeType":"calls","source":4963,"target":2343},{"edgeType":"calls","source":4729,"target":84},{"edgeType":"calls","source":454,"target":482},{"edgeType":"contains","source":3981,"target":4437},{"edgeType":"calls","source":4756,"target":304},{"edgeType":"calls","source":6932,"target":528},{"edgeType":"calls","source":5013,"target":5020},{"edgeType":"contains","source":6459,"target":6894},{"edgeType":"calls","source":4011,"target":144},{"edgeType":"calls","source":1958,"target":366},{"edgeType":"calls","source":533,"target":146},{"edgeType":"calls","source":535,"target":84},{"edgeType":"calls","source":4106,"target":370},{"edgeType":"contains","source":1186,"target":1235},{"edgeType":"calls","source":1990,"target":431},{"edgeType":"calls","source":5472,"target":304},{"edgeType":"contains","source":5878,"target":5879},{"edgeType":"calls","source":3215,"target":508},{"edgeType":"calls","source":4963,"target":2342},{"edgeType":"contains","source":5910,"target":5944},{"edgeType":"calls","source":4756,"target":303},{"edgeType":"extends","source":4797,"target":36},{"edgeType":"contains","source":4886,"target":4895},{"edgeType":"calls","source":2366,"target":431},{"edgeType":"calls","source":2373,"target":1271},{"edgeType":"contains","source":2640,"target":2642},{"edgeType":"calls","source":3977,"target":171},{"edgeType":"contains","source":3030,"target":3236},{"edgeType":"contains","source":4788,"target":4762},{"edgeType":"calls","source":4048,"target":84},{"edgeType":"calls","source":568,"target":146},{"edgeType":"contains","source":5910,"target":5920},{"edgeType":"contains","source":1186,"target":1205},{"edgeType":"calls","source":1221,"target":1043},{"edgeType":"calls","source":6281,"target":2740},{"edgeType":"calls","source":5433,"target":1545},{"edgeType":"calls","source":1116,"target":1127},{"edgeType":"calls","source":1151,"target":1099},{"edgeType":"calls","source":7139,"target":422},{"edgeType":"contains","source":5592,"target":6265},{"edgeType":"contains","source":3598,"target":3599},{"edgeType":"contains","source":3796,"target":3803},{"edgeType":"calls","source":4789,"target":369},{"edgeType":"contains","source":4886,"target":4894},{"edgeType":"extends","source":4115,"target":36},{"edgeType":"calls","source":1726,"target":1243},{"edgeType":"calls","source":6486,"target":582},{"edgeType":"calls","source":6495,"target":303},{"edgeType":"calls","source":2373,"target":1272},{"edgeType":"contains","source":6432,"target":6651},{"edgeType":"calls","source":4012,"target":144},{"edgeType":"contains","source":1186,"target":1204},{"edgeType":"contains","source":5910,"target":5921},{"edgeType":"calls","source":5480,"target":1144},{"edgeType":"calls","source":1080,"target":1185},{"edgeType":"calls","source":4789,"target":368},{"edgeType":"calls","source":6495,"target":304},{"edgeType":"contains","source":1513,"target":1637},{"edgeType":"calls","source":1522,"target":171},{"edgeType":"contains","source":2673,"target":2674},{"edgeType":"contains","source":4886,"target":4893},{"edgeType":"calls","source":6914,"target":1057},{"edgeType":"contains","source":4579,"target":4896},{"edgeType":"imports","source":6459,"target":79},{"edgeType":"contains","source":1037,"target":1598},{"edgeType":"contains","source":5910,"target":5922},{"edgeType":"imports","source":6286,"target":157},{"edgeType":"extends","source":6502,"target":36},{"edgeType":"calls","source":1244,"target":1389},{"edgeType":"calls","source":1312,"target":338},{"edgeType":"contains","source":4091,"target":4169},{"edgeType":"calls","source":4655,"target":1350},{"edgeType":"calls","source":5162,"target":431},{"edgeType":"calls","source":7068,"target":6854},{"edgeType":"calls","source":6498,"target":212},{"edgeType":"calls","source":2183,"target":1875},{"edgeType":"calls","source":1422,"target":1156},{"edgeType":"calls","source":4296,"target":4021},{"edgeType":"calls","source":1522,"target":170},{"edgeType":"calls","source":3715,"target":893},{"edgeType":"calls","source":1721,"target":1400},{"edgeType":"contains","source":6604,"target":6607},{"edgeType":"extends","source":2376,"target":36},{"edgeType":"calls","source":3977,"target":170},{"edgeType":"imports","source":6459,"target":78},{"edgeType":"calls","source":1312,"target":337},{"edgeType":"contains","source":1037,"target":1597},{"edgeType":"contains","source":5732,"target":6156},{"edgeType":"contains","source":3029,"target":6437},{"edgeType":"contains","source":5910,"target":5923},{"edgeType":"calls","source":1244,"target":1388},{"edgeType":"calls","source":4789,"target":366},{"edgeType":"calls","source":2834,"target":2835},{"edgeType":"contains","source":5592,"target":6260},{"edgeType":"contains","source":1379,"target":2626},{"edgeType":"contains","source":2640,"target":2646},{"edgeType":"calls","source":4109,"target":303},{"edgeType":"contains","source":1037,"target":1600},{"edgeType":"contains","source":5117,"target":5137},{"edgeType":"contains","source":928,"target":2865},{"edgeType":"contains","source":3952,"target":2142},{"edgeType":"calls","source":1248,"target":1259},{"edgeType":"contains","source":6075,"target":6086},{"edgeType":"contains","source":3466,"target":3467},{"edgeType":"contains","source":5910,"target":5916},{"edgeType":"contains","source":5592,"target":6261},{"edgeType":"calls","source":7001,"target":6819},{"edgeType":"contains","source":2540,"target":2576},{"edgeType":"contains","source":6471,"target":6495},{"edgeType":"contains","source":2581,"target":1305},{"edgeType":"calls","source":468,"target":1126},{"edgeType":"calls","source":4109,"target":304},{"edgeType":"contains","source":1037,"target":1599},{"edgeType":"calls","source":4922,"target":2583},{"edgeType":"contains","source":3796,"target":3806},{"edgeType":"calls","source":2777,"target":372},{"edgeType":"calls","source":6832,"target":431},{"edgeType":"calls","source":5707,"target":445},{"edgeType":"calls","source":4789,"target":364},{"edgeType":"contains","source":5732,"target":6150},{"edgeType":"contains","source":3952,"target":2141},{"edgeType":"contains","source":3297,"target":3420},{"edgeType":"calls","source":2877,"target":1500},{"edgeType":"contains","source":5910,"target":5917},{"edgeType":"calls","source":2998,"target":3034},{"edgeType":"calls","source":5880,"target":5652},{"edgeType":"calls","source":5238,"target":4413},{"edgeType":"contains","source":4886,"target":4897},{"edgeType":"contains","source":5592,"target":6262},{"edgeType":"contains","source":5723,"target":1144},{"edgeType":"calls","source":4330,"target":4021},{"edgeType":"calls","source":4384,"target":2347},{"edgeType":"contains","source":2640,"target":2644},{"edgeType":"contains","source":5910,"target":5918},{"edgeType":"contains","source":3814,"target":4304},{"edgeType":"calls","source":5602,"target":528},{"edgeType":"calls","source":6657,"target":572},{"edgeType":"contains","source":1186,"target":1211},{"edgeType":"calls","source":6541,"target":6282},{"edgeType":"calls","source":2998,"target":917},{"edgeType":"contains","source":6075,"target":6088},{"edgeType":"contains","source":5679,"target":5680},{"edgeType":"calls","source":972,"target":304},{"edgeType":"imports","source":1379,"target":49},{"edgeType":"contains","source":5592,"target":6263},{"edgeType":"contains","source":30,"target":50},{"edgeType":"calls","source":4384,"target":2346},{"edgeType":"extends","source":3993,"target":3820},{"edgeType":"contains","source":5910,"target":5919},{"edgeType":"contains","source":3796,"target":3804},{"edgeType":"calls","source":5707,"target":443},{"edgeType":"calls","source":6700,"target":6639},{"edgeType":"calls","source":604,"target":84},{"edgeType":"contains","source":4349,"target":6744},{"edgeType":"contains","source":3166,"target":80},{"edgeType":"calls","source":4817,"target":551},{"edgeType":"calls","source":1248,"target":1260},{"edgeType":"calls","source":5602,"target":527},{"edgeType":"calls","source":5516,"target":2136},{"edgeType":"calls","source":6657,"target":573},{"edgeType":"calls","source":972,"target":303},{"edgeType":"contains","source":5592,"target":6264},{"edgeType":"contains","source":3598,"target":3600},{"edgeType":"contains","source":5679,"target":5681},{"edgeType":"contains","source":2540,"target":2579},{"edgeType":"contains","source":5910,"target":5928},{"edgeType":"calls","source":4384,"target":2345},{"edgeType":"contains","source":3048,"target":572},{"edgeType":"contains","source":6439,"target":6442},{"edgeType":"contains","source":3796,"target":3811},{"edgeType":"calls","source":1011,"target":146},{"edgeType":"calls","source":5162,"target":425},{"edgeType":"contains","source":5604,"target":1673},{"edgeType":"calls","source":3773,"target":144},{"edgeType":"contains","source":1186,"target":1213},{"edgeType":"calls","source":1414,"target":337},{"edgeType":"imports","source":5410,"target":5103},{"edgeType":"calls","source":1149,"target":1152},{"edgeType":"contains","source":4719,"target":4794},{"edgeType":"calls","source":4567,"target":4070},{"edgeType":"calls","source":6863,"target":6873},{"edgeType":"calls","source":7117,"target":56},{"edgeType":"calls","source":1062,"target":678},{"edgeType":"calls","source":4817,"target":548},{"edgeType":"calls","source":1045,"target":148},{"edgeType":"contains","source":5910,"target":5929},{"edgeType":"calls","source":3999,"target":3710},{"edgeType":"calls","source":4384,"target":2344},{"edgeType":"contains","source":6373,"target":6375},{"edgeType":"contains","source":3048,"target":573},{"edgeType":"calls","source":144,"target":596},{"edgeType":"contains","source":1037,"target":1603},{"edgeType":"calls","source":2784,"target":2265},{"edgeType":"calls","source":3434,"target":84},{"edgeType":"contains","source":1186,"target":1212},{"edgeType":"calls","source":5162,"target":424},{"edgeType":"calls","source":1422,"target":1145},{"edgeType":"imports","source":2494,"target":2495},{"edgeType":"contains","source":4691,"target":5661},{"edgeType":"contains","source":5448,"target":5449},{"edgeType":"contains","source":2070,"target":2348},{"edgeType":"contains","source":2540,"target":2577},{"edgeType":"calls","source":4926,"target":339},{"edgeType":"calls","source":4226,"target":898},{"edgeType":"imports","source":1989,"target":179},{"edgeType":"calls","source":7002,"target":6793},{"edgeType":"calls","source":4384,"target":2343},{"edgeType":"contains","source":5910,"target":5930},{"edgeType":"contains","source":5277,"target":179},{"edgeType":"calls","source":883,"target":945},{"edgeType":"contains","source":1186,"target":1215},{"edgeType":"calls","source":1414,"target":339},{"edgeType":"contains","source":4719,"target":4792},{"edgeType":"calls","source":1770,"target":930},{"edgeType":"extends","source":3228,"target":3229},{"edgeType":"calls","source":4926,"target":338},{"edgeType":"calls","source":4923,"target":431},{"edgeType":"calls","source":4864,"target":146},{"edgeType":"contains","source":5910,"target":5931},{"edgeType":"calls","source":4384,"target":2342},{"edgeType":"calls","source":4523,"target":147},{"edgeType":"contains","source":328,"target":330},{"edgeType":"contains","source":1186,"target":1214},{"edgeType":"calls","source":1414,"target":338},{"edgeType":"calls","source":1239,"target":473},{"edgeType":"contains","source":4579,"target":4911},{"edgeType":"contains","source":5250,"target":5251},{"edgeType":"calls","source":3220,"target":371},{"edgeType":"calls","source":1074,"target":303},{"edgeType":"contains","source":4091,"target":4183},{"edgeType":"calls","source":4926,"target":337},{"edgeType":"imports","source":4091,"target":3715},{"edgeType":"contains","source":3954,"target":4202},{"edgeType":"contains","source":2176,"target":3297},{"edgeType":"calls","source":4384,"target":2341},{"edgeType":"contains","source":4391,"target":4397},{"edgeType":"contains","source":3496,"target":3602},{"edgeType":"contains","source":5910,"target":5924},{"edgeType":"calls","source":1822,"target":369},{"edgeType":"calls","source":1755,"target":332},{"edgeType":"contains","source":1186,"target":1217},{"edgeType":"calls","source":1256,"target":1002},{"edgeType":"imports","source":6824,"target":3555},{"edgeType":"calls","source":5365,"target":2583},{"edgeType":"contains","source":4579,"target":4910},{"edgeType":"contains","source":5448,"target":5454},{"edgeType":"extends","source":5268,"target":2359},{"edgeType":"calls","source":6602,"target":170},{"edgeType":"calls","source":2833,"target":1799},{"edgeType":"contains","source":5910,"target":5925},{"edgeType":"contains","source":5895,"target":3219},{"edgeType":"calls","source":3127,"target":84},{"edgeType":"calls","source":1822,"target":368},{"edgeType":"contains","source":2739,"target":2757},{"edgeType":"calls","source":1171,"target":469},{"edgeType":"calls","source":1239,"target":475},{"edgeType":"calls","source":3220,"target":369},{"edgeType":"contains","source":5910,"target":5926},{"edgeType":"extends","source":3297,"target":36},{"edgeType":"calls","source":7041,"target":303},{"edgeType":"contains","source":6439,"target":6440},{"edgeType":"contains","source":5732,"target":6159},{"edgeType":"contains","source":2898,"target":3110},{"edgeType":"contains","source":6459,"target":6877},{"edgeType":"calls","source":6602,"target":171},{"edgeType":"calls","source":6486,"target":596},{"edgeType":"calls","source":1347,"target":1355},{"edgeType":"calls","source":2134,"target":210},{"edgeType":"calls","source":1822,"target":371},{"edgeType":"calls","source":1239,"target":474},{"edgeType":"contains","source":3954,"target":4199},{"edgeType":"calls","source":1149,"target":1150},{"edgeType":"contains","source":4719,"target":4796},{"edgeType":"calls","source":1074,"target":304},{"edgeType":"calls","source":3220,"target":370},{"edgeType":"contains","source":5910,"target":5927},{"edgeType":"calls","source":6737,"target":215},{"edgeType":"calls","source":7041,"target":304},{"edgeType":"calls","source":5745,"target":5599},{"edgeType":"calls","source":1755,"target":333},{"edgeType":"contains","source":2739,"target":2755},{"edgeType":"contains","source":2736,"target":2848},{"edgeType":"calls","source":1822,"target":370},{"edgeType":"calls","source":3809,"target":1137},{"edgeType":"contains","source":1779,"target":1833},{"edgeType":"contains","source":3300,"target":3306},{"edgeType":"extends","source":7015,"target":36},{"edgeType":"calls","source":6959,"target":2814},{"edgeType":"calls","source":6837,"target":6596},{"edgeType":"contains","source":5732,"target":6136},{"edgeType":"calls","source":1759,"target":171},{"edgeType":"calls","source":4600,"target":893},{"edgeType":"imports","source":349,"target":324},{"edgeType":"contains","source":1383,"target":1425},{"edgeType":"contains","source":1302,"target":2879},{"edgeType":"calls","source":4337,"target":590},{"edgeType":"contains","source":6438,"target":6448},{"edgeType":"calls","source":1830,"target":84},{"edgeType":"contains","source":1779,"target":1834},{"edgeType":"calls","source":6378,"target":1797},{"edgeType":"calls","source":3328,"target":3329},{"edgeType":"contains","source":3300,"target":3307},{"edgeType":"calls","source":7078,"target":183},{"edgeType":"calls","source":6959,"target":2815},{"edgeType":"calls","source":6837,"target":6597},{"edgeType":"contains","source":5732,"target":6137},{"edgeType":"calls","source":1759,"target":170},{"edgeType":"contains","source":3496,"target":3572},{"edgeType":"contains","source":4192,"target":4194},{"edgeType":"contains","source":129,"target":130},{"edgeType":"calls","source":454,"target":458},{"edgeType":"contains","source":1383,"target":1426},{"edgeType":"contains","source":4378,"target":4770},{"edgeType":"contains","source":6459,"target":6855},{"edgeType":"calls","source":6037,"target":1797},{"edgeType":"calls","source":6977,"target":144},{"edgeType":"contains","source":3300,"target":3304},{"edgeType":"calls","source":5681,"target":148},{"edgeType":"calls","source":6959,"target":2816},{"edgeType":"calls","source":4881,"target":4864},{"edgeType":"contains","source":5592,"target":6250},{"edgeType":"contains","source":4192,"target":4193},{"edgeType":"calls","source":3729,"target":3579},{"edgeType":"contains","source":30,"target":31},{"edgeType":"contains","source":1383,"target":1423},{"edgeType":"contains","source":3496,"target":3571},{"edgeType":"calls","source":4451,"target":4453},{"edgeType":"contains","source":6075,"target":6076},{"edgeType":"contains","source":5116,"target":5145},{"edgeType":"calls","source":4337,"target":588},{"edgeType":"contains","source":6471,"target":6484},{"edgeType":"contains","source":6459,"target":6856},{"edgeType":"calls","source":1818,"target":458},{"edgeType":"contains","source":4579,"target":4879},{"edgeType":"contains","source":1037,"target":1581},{"edgeType":"contains","source":3300,"target":3305},{"edgeType":"calls","source":6864,"target":6819},{"edgeType":"calls","source":3195,"target":2165},{"edgeType":"contains","source":5732,"target":6139},{"edgeType":"contains","source":1383,"target":1424},{"edgeType":"contains","source":4378,"target":4768},{"edgeType":"contains","source":3496,"target":3570},{"edgeType":"calls","source":372,"target":888},{"edgeType":"calls","source":1818,"target":457},{"edgeType":"extends","source":2173,"target":36},{"edgeType":"calls","source":4865,"target":4301},{"edgeType":"calls","source":1550,"target":304},{"edgeType":"calls","source":883,"target":897},{"edgeType":"contains","source":3952,"target":2125},{"edgeType":"calls","source":1580,"target":431},{"edgeType":"calls","source":1544,"target":1547},{"edgeType":"calls","source":354,"target":384},{"edgeType":"imports","source":3867,"target":147},{"edgeType":"contains","source":1383,"target":1429},{"edgeType":"calls","source":4760,"target":157},{"edgeType":"calls","source":4583,"target":4587},{"edgeType":"extends","source":190,"target":205},{"edgeType":"calls","source":487,"target":489},{"edgeType":"contains","source":1037,"target":1583},{"edgeType":"calls","source":4240,"target":422},{"edgeType":"calls","source":6722,"target":4881},{"edgeType":"calls","source":1550,"target":303},{"edgeType":"calls","source":6837,"target":6601},{"edgeType":"imports","source":4691,"target":1030},{"edgeType":"contains","source":5732,"target":6133},{"edgeType":"calls","source":1544,"target":1546},{"edgeType":"contains","source":3952,"target":2124},{"edgeType":"contains","source":5410,"target":5550},{"edgeType":"contains","source":3496,"target":3576},{"edgeType":"contains","source":5612,"target":5625},{"edgeType":"calls","source":4595,"target":1043},{"edgeType":"contains","source":1383,"target":1430},{"edgeType":"calls","source":4583,"target":4586},{"edgeType":"extends","source":3229,"target":3245},{"edgeType":"contains","source":2275,"target":2318},{"edgeType":"calls","source":487,"target":488},{"edgeType":"calls","source":4001,"target":431},{"edgeType":"calls","source":2169,"target":144},{"edgeType":"calls","source":4240,"target":421},{"edgeType":"contains","source":4579,"target":4885},{"edgeType":"calls","source":6456,"target":431},{"edgeType":"calls","source":2121,"target":571},{"edgeType":"calls","source":6728,"target":6810},{"edgeType":"contains","source":3300,"target":3308},{"edgeType":"calls","source":6830,"target":6819},{"edgeType":"contains","source":3952,"target":2123},{"edgeType":"calls","source":6602,"target":146},{"edgeType":"contains","source":1779,"target":1835},{"edgeType":"contains","source":1383,"target":1427},{"edgeType":"contains","source":2070,"target":2328},{"edgeType":"contains","source":3496,"target":3575},{"edgeType":"calls","source":6115,"target":431},{"edgeType":"calls","source":4617,"target":4588},{"edgeType":"calls","source":4583,"target":4585},{"edgeType":"calls","source":454,"target":457},{"edgeType":"calls","source":3762,"target":3609},{"edgeType":"calls","source":5742,"target":5652},{"edgeType":"calls","source":4337,"target":584},{"edgeType":"calls","source":2298,"target":370},{"edgeType":"calls","source":2921,"target":84},{"edgeType":"calls","source":2978,"target":431},{"edgeType":"contains","source":955,"target":956},{"edgeType":"contains","source":3300,"target":3309},{"edgeType":"calls","source":1544,"target":1548},{"edgeType":"contains","source":3867,"target":529},{"edgeType":"contains","source":1383,"target":1428},{"edgeType":"calls","source":4583,"target":4584},{"edgeType":"contains","source":3496,"target":3574},{"edgeType":"calls","source":2298,"target":371},{"edgeType":"calls","source":4376,"target":431},{"edgeType":"contains","source":4691,"target":5639},{"edgeType":"contains","source":4378,"target":4779},{"edgeType":"calls","source":2269,"target":209},{"edgeType":"contains","source":5592,"target":6256},{"edgeType":"calls","source":2963,"target":893},{"edgeType":"contains","source":4886,"target":4887},{"edgeType":"calls","source":6602,"target":148},{"edgeType":"calls","source":1782,"target":507},{"edgeType":"calls","source":1584,"target":303},{"edgeType":"contains","source":1383,"target":1433},{"edgeType":"calls","source":1243,"target":303},{"edgeType":"contains","source":32,"target":1032},{"edgeType":"calls","source":372,"target":879},{"edgeType":"calls","source":354,"target":380},{"edgeType":"calls","source":6433,"target":84},{"edgeType":"calls","source":2298,"target":368},{"edgeType":"contains","source":435,"target":1223},{"edgeType":"calls","source":2269,"target":210},{"edgeType":"contains","source":5592,"target":6257},{"edgeType":"calls","source":6938,"target":303},{"edgeType":"calls","source":6896,"target":548},{"edgeType":"calls","source":1782,"target":506},{"edgeType":"contains","source":1513,"target":1632},{"edgeType":"imports","source":5166,"target":3205},{"edgeType":"contains","source":1383,"target":1434},{"edgeType":"calls","source":4568,"target":3990},{"edgeType":"calls","source":3955,"target":3967},{"edgeType":"calls","source":5880,"target":5599},{"edgeType":"contains","source":435,"target":1222},{"edgeType":"calls","source":6938,"target":304},{"edgeType":"calls","source":6914,"target":1048},{"edgeType":"contains","source":2077,"target":2118},{"edgeType":"calls","source":2298,"target":369},{"edgeType":"contains","source":6075,"target":6083},{"edgeType":"contains","source":5732,"target":6146},{"edgeType":"calls","source":6688,"target":6997},{"edgeType":"calls","source":1544,"target":1545},{"edgeType":"contains","source":1383,"target":1431},{"edgeType":"calls","source":4039,"target":303},{"edgeType":"calls","source":3387,"target":431},{"edgeType":"contains","source":3954,"target":4180},{"edgeType":"calls","source":1782,"target":509},{"edgeType":"calls","source":3215,"target":2592},{"edgeType":"calls","source":3214,"target":509},{"edgeType":"contains","source":3952,"target":2128},{"edgeType":"calls","source":6431,"target":144},{"edgeType":"contains","source":435,"target":1225},{"edgeType":"calls","source":354,"target":382},{"edgeType":"calls","source":2569,"target":421},{"edgeType":"contains","source":3,"target":6160},{"edgeType":"calls","source":2298,"target":366},{"edgeType":"calls","source":2308,"target":56},{"edgeType":"contains","source":5732,"target":6147},{"edgeType":"contains","source":928,"target":2854},{"edgeType":"contains","source":5592,"target":6259},{"edgeType":"contains","source":3952,"target":2126},{"edgeType":"contains","source":1383,"target":1432},{"edgeType":"calls","source":1584,"target":304},{"edgeType":"calls","source":4039,"target":304},{"edgeType":"imports","source":3981,"target":4003},{"edgeType":"calls","source":1243,"target":304},{"edgeType":"calls","source":1782,"target":508},{"edgeType":"contains","source":2077,"target":2116},{"edgeType":"calls","source":354,"target":381},{"edgeType":"calls","source":2569,"target":422},{"edgeType":"contains","source":435,"target":1224},{"edgeType":"contains","source":4378,"target":4776},{"edgeType":"calls","source":3024,"target":1112},{"edgeType":"contains","source":1513,"target":1635},{"edgeType":"contains","source":2275,"target":2325},{"edgeType":"contains","source":5732,"target":6140},{"edgeType":"contains","source":2739,"target":2740},{"edgeType":"contains","source":2736,"target":2833},{"edgeType":"calls","source":6055,"target":171},{"edgeType":"calls","source":6472,"target":1011},{"edgeType":"contains","source":1383,"target":1437},{"edgeType":"calls","source":1808,"target":1811},{"edgeType":"calls","source":1782,"target":503},{"edgeType":"calls","source":1742,"target":1743},{"edgeType":"calls","source":1363,"target":807},{"edgeType":"contains","source":6075,"target":6078},{"edgeType":"calls","source":3214,"target":507},{"edgeType":"contains","source":4091,"target":996},{"edgeType":"contains","source":6459,"target":6858},{"edgeType":"contains","source":1513,"target":1636},{"edgeType":"calls","source":2298,"target":364},{"edgeType":"calls","source":3024,"target":1113},{"edgeType":"contains","source":5732,"target":6141},{"edgeType":"calls","source":5237,"target":1216},{"edgeType":"calls","source":5227,"target":2583},{"edgeType":"contains","source":1383,"target":1438},{"edgeType":"contains","source":1302,"target":3949},{"edgeType":"calls","source":6055,"target":170},{"edgeType":"calls","source":1782,"target":502},{"edgeType":"contains","source":5166,"target":2552},{"edgeType":"calls","source":1808,"target":1810},{"edgeType":"contains","source":6075,"target":6079},{"edgeType":"imports","source":2494,"target":2540},{"edgeType":"calls","source":1363,"target":806},{"edgeType":"calls","source":3214,"target":508},{"edgeType":"calls","source":4919,"target":2618},{"edgeType":"calls","source":6465,"target":144},{"edgeType":"contains","source":4432,"target":5222},{"edgeType":"calls","source":4881,"target":4853},{"edgeType":"calls","source":6841,"target":144},{"edgeType":"contains","source":435,"target":1226},{"edgeType":"calls","source":897,"target":454},{"edgeType":"calls","source":2612,"target":144},{"edgeType":"contains","source":32,"target":3152},{"edgeType":"contains","source":6459,"target":6860},{"edgeType":"contains","source":1513,"target":1633},{"edgeType":"contains","source":4378,"target":4781},{"edgeType":"contains","source":2860,"target":3215},{"edgeType":"imports","source":1415,"target":49},{"edgeType":"calls","source":4285,"target":3244},{"edgeType":"contains","source":1383,"target":1435},{"edgeType":"calls","source":1782,"target":505},{"edgeType":"calls","source":1248,"target":146},{"edgeType":"contains","source":2736,"target":2830},{"edgeType":"contains","source":3796,"target":3797},{"edgeType":"contains","source":4432,"target":5221},{"edgeType":"calls","source":3214,"target":505},{"edgeType":"calls","source":2837,"target":565},{"edgeType":"calls","source":1543,"target":1571},{"edgeType":"contains","source":1513,"target":1634},{"edgeType":"contains","source":1383,"target":1436},{"edgeType":"calls","source":1782,"target":504},{"edgeType":"contains","source":4886,"target":4888},{"edgeType":"calls","source":1719,"target":1400},{"edgeType":"contains","source":6075,"target":6081},{"edgeType":"calls","source":1114,"target":1128},{"edgeType":"contains","source":2070,"target":2337},{"edgeType":"calls","source":3214,"target":506},{"edgeType":"calls","source":7139,"target":421},{"edgeType":"contains","source":4432,"target":5220},{"edgeType":"calls","source":4762,"target":84},{"edgeType":"calls","source":5139,"target":1113},{"edgeType":"contains","source":4691,"target":5622},{"edgeType":"contains","source":6834,"target":6840},{"edgeType":"imports","source":5732,"target":5734},{"edgeType":"contains","source":3166,"target":2158},{"edgeType":"calls","source":5672,"target":445},{"edgeType":"contains","source":3241,"target":4061},{"edgeType":"contains","source":5277,"target":2254},{"edgeType":"calls","source":5472,"target":303},{"edgeType":"calls","source":4963,"target":2341},{"edgeType":"calls","source":5104,"target":84},{"edgeType":"calls","source":3215,"target":505},{"edgeType":"calls","source":6688,"target":6971},{"edgeType":"calls","source":4761,"target":147},{"edgeType":"calls","source":6728,"target":6788},{"edgeType":"imports","source":2879,"target":3270},{"edgeType":"calls","source":6465,"target":2257},{"edgeType":"contains","source":2275,"target":2297},{"edgeType":"calls","source":6147,"target":2632},{"edgeType":"calls","source":6050,"target":354},{"edgeType":"calls","source":4106,"target":368},{"edgeType":"contains","source":3241,"target":4062},{"edgeType":"contains","source":4091,"target":4137},{"edgeType":"calls","source":3215,"target":506},{"edgeType":"calls","source":2578,"target":170},{"edgeType":"calls","source":5139,"target":1112},{"edgeType":"contains","source":5612,"target":5613},{"edgeType":"calls","source":1114,"target":1155},{"edgeType":"calls","source":6533,"target":6492},{"edgeType":"contains","source":5732,"target":6121},{"edgeType":"contains","source":2275,"target":2294},{"edgeType":"contains","source":6834,"target":6842},{"edgeType":"calls","source":157,"target":171},{"edgeType":"calls","source":6465,"target":2258},{"edgeType":"extends","source":5870,"target":1691},{"edgeType":"contains","source":4691,"target":5620},{"edgeType":"calls","source":5747,"target":2347},{"edgeType":"contains","source":6459,"target":6839},{"edgeType":"calls","source":2105,"target":2145},{"edgeType":"calls","source":6147,"target":2631},{"edgeType":"calls","source":5742,"target":5673},{"edgeType":"calls","source":2024,"target":431},{"edgeType":"calls","source":468,"target":1101},{"edgeType":"calls","source":5672,"target":443},{"edgeType":"imports","source":6286,"target":190},{"edgeType":"calls","source":1354,"target":1117},{"edgeType":"calls","source":2610,"target":1289},{"edgeType":"contains","source":1714,"target":1716},{"edgeType":"contains","source":3673,"target":4410},{"edgeType":"calls","source":3215,"target":503},{"edgeType":"calls","source":4863,"target":3325},{"edgeType":"contains","source":5612,"target":5614},{"edgeType":"contains","source":6834,"target":6843},{"edgeType":"calls","source":6087,"target":3433},{"edgeType":"calls","source":5747,"target":2346},{"edgeType":"calls","source":157,"target":170},{"edgeType":"calls","source":4106,"target":366},{"edgeType":"calls","source":6047,"target":445},{"edgeType":"contains","source":3241,"target":4060},{"edgeType":"calls","source":2602,"target":2595},{"edgeType":"calls","source":2604,"target":2533},{"edgeType":"calls","source":6465,"target":171},{"edgeType":"calls","source":2683,"target":84},{"edgeType":"contains","source":1648,"target":1649},{"edgeType":"contains","source":4091,"target":4135},{"edgeType":"calls","source":4761,"target":144},{"edgeType":"contains","source":3828,"target":3832},{"edgeType":"calls","source":3215,"target":504},{"edgeType":"imports","source":3013,"target":3341},{"edgeType":"contains","source":5612,"target":5615},{"edgeType":"contains","source":3461,"target":3588},{"edgeType":"contains","source":6280,"target":7097},{"edgeType":"contains","source":5705,"target":1667},{"edgeType":"calls","source":2610,"target":1286},{"edgeType":"calls","source":5747,"target":2345},{"edgeType":"calls","source":157,"target":165},{"edgeType":"contains","source":2540,"target":2542},{"edgeType":"calls","source":6087,"target":3432},{"edgeType":"calls","source":6701,"target":6572},{"edgeType":"calls","source":6465,"target":170},{"edgeType":"calls","source":5747,"target":2344},{"edgeType":"contains","source":3241,"target":4065},{"edgeType":"contains","source":1815,"target":1762},{"edgeType":"contains","source":6074,"target":6084},{"edgeType":"calls","source":6047,"target":443},{"edgeType":"contains","source":6280,"target":7098},{"edgeType":"calls","source":3860,"target":591},{"edgeType":"contains","source":2075,"target":2159},{"edgeType":"calls","source":2610,"target":1287},{"edgeType":"calls","source":5854,"target":84},{"edgeType":"calls","source":4486,"target":210},{"edgeType":"calls","source":157,"target":164},{"edgeType":"calls","source":6087,"target":3431},{"edgeType":"calls","source":4106,"target":364},{"edgeType":"contains","source":2540,"target":2543},{"edgeType":"calls","source":4896,"target":4413},{"edgeType":"calls","source":5747,"target":2343},{"edgeType":"extends","source":4389,"target":36},{"edgeType":"calls","source":917,"target":916},{"edgeType":"calls","source":2610,"target":1288},{"edgeType":"contains","source":3993,"target":4008},{"edgeType":"calls","source":3215,"target":502},{"edgeType":"imports","source":6557,"target":4474},{"edgeType":"imports","source":5895,"target":2801},{"edgeType":"calls","source":2610,"target":1284},{"edgeType":"calls","source":4486,"target":209},{"edgeType":"calls","source":143,"target":601},{"edgeType":"contains","source":4579,"target":4868},{"edgeType":"contains","source":6735,"target":6736},{"edgeType":"calls","source":5747,"target":2342},{"edgeType":"contains","source":3241,"target":4063},{"edgeType":"calls","source":3418,"target":548},{"edgeType":"calls","source":1248,"target":171},{"edgeType":"calls","source":2610,"target":1285},{"edgeType":"calls","source":4758,"target":1289},{"edgeType":"calls","source":4816,"target":548},{"edgeType":"calls","source":3998,"target":3710},{"edgeType":"contains","source":2540,"target":2541},{"edgeType":"calls","source":6795,"target":2604},{"edgeType":"calls","source":5747,"target":2341},{"edgeType":"contains","source":3166,"target":3218},{"edgeType":"contains","source":3241,"target":4064},{"edgeType":"calls","source":6976,"target":164},{"edgeType":"calls","source":1248,"target":170},{"edgeType":"calls","source":1114,"target":1153},{"edgeType":"calls","source":3244,"target":2769},{"edgeType":"calls","source":4758,"target":1288},{"edgeType":"imports","source":4668,"target":1713},{"edgeType":"contains","source":2275,"target":2304},{"edgeType":"calls","source":2326,"target":573},{"edgeType":"calls","source":157,"target":161},{"edgeType":"calls","source":2837,"target":588},{"edgeType":"calls","source":3008,"target":572},{"edgeType":"calls","source":6976,"target":165},{"edgeType":"contains","source":5732,"target":6128},{"edgeType":"calls","source":5582,"target":56},{"edgeType":"contains","source":3460,"target":3624},{"edgeType":"contains","source":3241,"target":4069},{"edgeType":"contains","source":3366,"target":3367},{"edgeType":"imports","source":3981,"target":3984},{"edgeType":"calls","source":4758,"target":1287},{"edgeType":"contains","source":6834,"target":6849},{"edgeType":"calls","source":1103,"target":431},{"edgeType":"contains","source":2736,"target":2813},{"edgeType":"extends","source":6060,"target":36},{"edgeType":"calls","source":4206,"target":431},{"edgeType":"calls","source":4022,"target":4021},{"edgeType":"contains","source":4378,"target":4761},{"edgeType":"calls","source":157,"target":160},{"edgeType":"contains","source":5116,"target":5138},{"edgeType":"contains","source":5612,"target":5621},{"edgeType":"calls","source":3008,"target":573},{"edgeType":"calls","source":5235,"target":1299},{"edgeType":"calls","source":4758,"target":1286},{"edgeType":"calls","source":4690,"target":4451},{"edgeType":"imports","source":6824,"target":1473},{"edgeType":"calls","source":4112,"target":171},{"edgeType":"contains","source":2540,"target":2544},{"edgeType":"contains","source":2275,"target":2302},{"edgeType":"calls","source":2373,"target":171},{"edgeType":"calls","source":2501,"target":431},{"edgeType":"calls","source":4388,"target":4300},{"edgeType":"contains","source":4378,"target":4760},{"edgeType":"contains","source":920,"target":972},{"edgeType":"extends","source":2275,"target":36},{"edgeType":"calls","source":3097,"target":3096},{"edgeType":"contains","source":6834,"target":6850},{"edgeType":"calls","source":4758,"target":1285},{"edgeType":"calls","source":5480,"target":1101},{"edgeType":"contains","source":2540,"target":2545},{"edgeType":"calls","source":2326,"target":572},{"edgeType":"contains","source":4502,"target":5144},{"edgeType":"contains","source":4378,"target":4759},{"edgeType":"calls","source":330,"target":84},{"edgeType":"contains","source":5732,"target":6131},{"edgeType":"calls","source":6532,"target":6533},{"edgeType":"calls","source":3860,"target":584},{"edgeType":"calls","source":950,"target":948},{"edgeType":"imports","source":153,"target":49},{"edgeType":"calls","source":3126,"target":84},{"edgeType":"extends","source":6026,"target":36},{"edgeType":"contains","source":3241,"target":4074},{"edgeType":"calls","source":4758,"target":1284},{"edgeType":"calls","source":1292,"target":911},{"edgeType":"calls","source":1080,"target":84},{"edgeType":"calls","source":4926,"target":304},{"edgeType":"calls","source":6451,"target":596},{"edgeType":"contains","source":885,"target":1002},{"edgeType":"contains","source":2275,"target":2309},{"edgeType":"contains","source":4291,"target":4293},{"edgeType":"contains","source":3496,"target":3569},{"edgeType":"calls","source":3520,"target":551},{"edgeType":"contains","source":5546,"target":5548},{"edgeType":"calls","source":3635,"target":157},{"edgeType":"contains","source":6834,"target":6845},{"edgeType":"contains","source":1779,"target":1830},{"edgeType":"calls","source":4112,"target":170},{"edgeType":"calls","source":1292,"target":910},{"edgeType":"calls","source":4066,"target":3710},{"edgeType":"contains","source":4579,"target":4877},{"edgeType":"calls","source":6631,"target":6637},{"edgeType":"contains","source":5,"target":3969},{"edgeType":"calls","source":4926,"target":303},{"edgeType":"calls","source":7002,"target":421},{"edgeType":"imports","source":3981,"target":3988},{"edgeType":"contains","source":139,"target":6158},{"edgeType":"calls","source":4724,"target":4451},{"edgeType":"calls","source":6932,"target":6819},{"edgeType":"contains","source":2210,"target":2211},{"edgeType":"contains","source":2275,"target":2310},{"edgeType":"calls","source":2373,"target":170},{"edgeType":"contains","source":3496,"target":3568},{"edgeType":"calls","source":4947,"target":4938},{"edgeType":"contains","source":3166,"target":3228},{"edgeType":"imports","source":579,"target":582},{"edgeType":"contains","source":5116,"target":5142},{"edgeType":"contains","source":4691,"target":5632},{"edgeType":"calls","source":1082,"target":1081},{"edgeType":"calls","source":6780,"target":962},{"edgeType":"calls","source":7002,"target":422},{"edgeType":"contains","source":2275,"target":2306},{"edgeType":"calls","source":157,"target":159},{"edgeType":"contains","source":162,"target":163},{"edgeType":"contains","source":6471,"target":6472},{"edgeType":"calls","source":5672,"target":431},{"edgeType":"calls","source":3577,"target":1953},{"edgeType":"contains","source":3241,"target":4071},{"edgeType":"contains","source":3241,"target":4073},{"edgeType":"contains","source":6834,"target":6847},{"edgeType":"calls","source":6631,"target":6639},{"edgeType":"calls","source":6780,"target":963},{"edgeType":"calls","source":6728,"target":6803},{"edgeType":"contains","source":6438,"target":6439},{"edgeType":"contains","source":6471,"target":6473},{"edgeType":"calls","source":1347,"target":1321},{"edgeType":"contains","source":5612,"target":5619},{"edgeType":"contains","source":5458,"target":6165},{"edgeType":"contains","source":5116,"target":5140},{"edgeType":"contains","source":3241,"target":4072},{"edgeType":"contains","source":1779,"target":1800},{"edgeType":"calls","source":6975,"target":303},{"edgeType":"calls","source":4184,"target":146},{"edgeType":"calls","source":4059,"target":4021},{"edgeType":"contains","source":579,"target":946},{"edgeType":"calls","source":4243,"target":431},{"edgeType":"calls","source":6258,"target":332},{"edgeType":"calls","source":1084,"target":1112},{"edgeType":"calls","source":4584,"target":431},{"edgeType":"calls","source":4963,"target":309},{"edgeType":"contains","source":30,"target":6338},{"edgeType":"calls","source":6833,"target":6819},{"edgeType":"contains","source":1977,"target":2004},{"edgeType":"contains","source":3981,"target":1189},{"edgeType":"contains","source":2275,"target":2280},{"edgeType":"contains","source":6280,"target":7085},{"edgeType":"calls","source":1765,"target":84},{"edgeType":"calls","source":1757,"target":1389},{"edgeType":"contains","source":4579,"target":4848},{"edgeType":"calls","source":1958,"target":1500},{"edgeType":"contains","source":5215,"target":5216},{"edgeType":"calls","source":6975,"target":304},{"edgeType":"calls","source":6374,"target":963},{"edgeType":"contains","source":1977,"target":2005},{"edgeType":"calls","source":460,"target":371},{"edgeType":"calls","source":4970,"target":1148},{"edgeType":"contains","source":2070,"target":2293},{"edgeType":"contains","source":6280,"target":7086},{"edgeType":"extends","source":3879,"target":36},{"edgeType":"calls","source":5546,"target":4433},{"edgeType":"calls","source":1757,"target":1388},{"edgeType":"calls","source":3809,"target":144},{"edgeType":"contains","source":1086,"target":1087},{"edgeType":"calls","source":6912,"target":144},{"edgeType":"contains","source":4502,"target":5120},{"edgeType":"calls","source":1084,"target":1114},{"edgeType":"contains","source":162,"target":4362},{"edgeType":"calls","source":6374,"target":962},{"edgeType":"calls","source":6868,"target":6793},{"edgeType":"contains","source":30,"target":6340},{"edgeType":"calls","source":6670,"target":4475},{"edgeType":"contains","source":1977,"target":2002},{"edgeType":"extends","source":1083,"target":36},{"edgeType":"calls","source":4970,"target":1147},{"edgeType":"calls","source":5000,"target":4446},{"edgeType":"contains","source":6280,"target":7087},{"edgeType":"contains","source":4389,"target":4395},{"edgeType":"calls","source":1757,"target":1391},{"edgeType":"contains","source":4717,"target":4797},{"edgeType":"contains","source":5871,"target":6025},{"edgeType":"contains","source":5908,"target":6992},{"edgeType":"calls","source":4090,"target":4116},{"edgeType":"calls","source":7000,"target":588},{"edgeType":"contains","source":4502,"target":5119},{"edgeType":"calls","source":1084,"target":1113},{"edgeType":"contains","source":30,"target":6339},{"edgeType":"calls","source":4970,"target":1146},{"edgeType":"contains","source":3596,"target":3608},{"edgeType":"calls","source":4561,"target":84},{"edgeType":"calls","source":4588,"target":304},{"edgeType":"contains","source":3460,"target":3596},{"edgeType":"calls","source":2305,"target":1314},{"edgeType":"calls","source":4422,"target":165},{"edgeType":"contains","source":6280,"target":7088},{"edgeType":"calls","source":3926,"target":3914},{"edgeType":"calls","source":1812,"target":1799},{"edgeType":"calls","source":1757,"target":1390},{"edgeType":"calls","source":4103,"target":3710},{"edgeType":"calls","source":6281,"target":4900},{"edgeType":"calls","source":6912,"target":146},{"edgeType":"calls","source":3430,"target":3432},{"edgeType":"calls","source":460,"target":368},{"edgeType":"imports","source":5166,"target":78},{"edgeType":"calls","source":4422,"target":164},{"edgeType":"calls","source":4588,"target":303},{"edgeType":"calls","source":1349,"target":1348},{"edgeType":"calls","source":3430,"target":3433},{"edgeType":"calls","source":6878,"target":144},{"edgeType":"contains","source":1814,"target":2834},{"edgeType":"contains","source":5908,"target":6986},{"edgeType":"contains","source":6280,"target":7082},{"edgeType":"calls","source":5334,"target":431},{"edgeType":"imports","source":5166,"target":79},{"edgeType":"calls","source":7016,"target":1152},{"edgeType":"imports","source":2176,"target":1853},{"edgeType":"contains","source":4579,"target":4852},{"edgeType":"calls","source":3560,"target":457},{"edgeType":"contains","source":5116,"target":5117},{"edgeType":"contains","source":182,"target":575},{"edgeType":"contains","source":3241,"target":4047},{"edgeType":"calls","source":460,"target":370},{"edgeType":"imports","source":6530,"target":78},{"edgeType":"contains","source":1814,"target":2831},{"edgeType":"contains","source":6280,"target":7083},{"edgeType":"contains","source":2275,"target":2282},{"edgeType":"calls","source":4314,"target":339},{"edgeType":"calls","source":3430,"target":3431},{"edgeType":"calls","source":4740,"target":5101},{"edgeType":"calls","source":3560,"target":458},{"edgeType":"calls","source":2579,"target":2329},{"edgeType":"contains","source":5380,"target":5388},{"edgeType":"contains","source":1977,"target":2007},{"edgeType":"contains","source":3596,"target":3612},{"edgeType":"calls","source":1115,"target":148},{"edgeType":"contains","source":2077,"target":2079},{"edgeType":"calls","source":1797,"target":146},{"edgeType":"calls","source":460,"target":369},{"edgeType":"calls","source":6879,"target":3287},{"edgeType":"calls","source":4314,"target":338},{"edgeType":"calls","source":1955,"target":533},{"edgeType":"calls","source":2803,"target":2781},{"edgeType":"calls","source":6456,"target":528},{"edgeType":"calls","source":6462,"target":342},{"edgeType":"calls","source":1514,"target":1515},{"edgeType":"contains","source":30,"target":5289},{"edgeType":"calls","source":3628,"target":3632},{"edgeType":"calls","source":6541,"target":6366},{"edgeType":"contains","source":3596,"target":3619},{"edgeType":"calls","source":460,"target":364},{"edgeType":"contains","source":3993,"target":3997},{"edgeType":"contains","source":4091,"target":4130},{"edgeType":"calls","source":6087,"target":339},{"edgeType":"contains","source":27,"target":97},{"edgeType":"calls","source":4035,"target":1585},{"edgeType":"calls","source":4240,"target":515},{"edgeType":"calls","source":4314,"target":337},{"edgeType":"contains","source":6280,"target":7093},{"edgeType":"calls","source":6456,"target":527},{"edgeType":"calls","source":3560,"target":2570},{"edgeType":"contains","source":6900,"target":6901},{"edgeType":"calls","source":3113,"target":571},{"edgeType":"contains","source":5473,"target":2511},{"edgeType":"calls","source":6087,"target":338},{"edgeType":"contains","source":27,"target":96},{"edgeType":"extends","source":1186,"target":1076},{"edgeType":"contains","source":6280,"target":7094},{"edgeType":"calls","source":4240,"target":516},{"edgeType":"imports","source":1379,"target":147},{"edgeType":"calls","source":4752,"target":4726},{"edgeType":"contains","source":3596,"target":3617},{"edgeType":"calls","source":3325,"target":339},{"edgeType":"calls","source":3325,"target":338},{"edgeType":"calls","source":6087,"target":337},{"edgeType":"calls","source":460,"target":366},{"edgeType":"calls","source":3932,"target":548},{"edgeType":"calls","source":3824,"target":3896},{"edgeType":"calls","source":4240,"target":513},{"edgeType":"extends","source":5550,"target":36},{"edgeType":"calls","source":5046,"target":1953},{"edgeType":"calls","source":4291,"target":1046},{"edgeType":"calls","source":6591,"target":591},{"edgeType":"calls","source":2825,"target":1041},{"edgeType":"contains","source":1814,"target":2836},{"edgeType":"contains","source":6834,"target":6835},{"edgeType":"calls","source":4035,"target":1584},{"edgeType":"contains","source":3993,"target":3994},{"edgeType":"calls","source":6839,"target":303},{"edgeType":"contains","source":2275,"target":2287},{"edgeType":"calls","source":4240,"target":514},{"edgeType":"contains","source":4389,"target":4402},{"edgeType":"imports","source":1379,"target":1202},{"edgeType":"contains","source":182,"target":581},{"edgeType":"contains","source":2275,"target":2292},{"edgeType":"calls","source":6559,"target":527},{"edgeType":"calls","source":5745,"target":5652},{"edgeType":"contains","source":3596,"target":3623},{"edgeType":"extends","source":6666,"target":6664},{"edgeType":"calls","source":1830,"target":171},{"edgeType":"calls","source":1881,"target":1761},{"edgeType":"calls","source":6839,"target":304},{"edgeType":"contains","source":6280,"target":7089},{"edgeType":"calls","source":7138,"target":548},{"edgeType":"calls","source":6705,"target":6572},{"edgeType":"contains","source":3993,"target":4001},{"edgeType":"calls","source":530,"target":304},{"edgeType":"calls","source":3662,"target":461},{"edgeType":"calls","source":3638,"target":148},{"edgeType":"calls","source":6559,"target":528},{"edgeType":"contains","source":3596,"target":3622},{"edgeType":"calls","source":1830,"target":170},{"edgeType":"calls","source":3325,"target":337},{"edgeType":"calls","source":530,"target":303},{"edgeType":"calls","source":5876,"target":5818},{"edgeType":"contains","source":2688,"target":1117},{"edgeType":"contains","source":1714,"target":1715},{"edgeType":"contains","source":6280,"target":7090},{"edgeType":"calls","source":6400,"target":144},{"edgeType":"calls","source":2604,"target":2605},{"edgeType":"calls","source":596,"target":371},{"edgeType":"calls","source":6906,"target":342},{"edgeType":"calls","source":4995,"target":4588},{"edgeType":"calls","source":5876,"target":5817},{"edgeType":"calls","source":3824,"target":3892},{"edgeType":"calls","source":3625,"target":548},{"edgeType":"calls","source":3272,"target":3034},{"edgeType":"calls","source":3295,"target":2321},{"edgeType":"calls","source":3434,"target":126},{"edgeType":"calls","source":3284,"target":548},{"edgeType":"contains","source":6280,"target":7091},{"edgeType":"contains","source":3828,"target":3829},{"edgeType":"calls","source":6463,"target":304},{"edgeType":"calls","source":7117,"target":144},{"edgeType":"calls","source":4394,"target":4193},{"edgeType":"contains","source":2275,"target":2290},{"edgeType":"contains","source":5,"target":3956},{"edgeType":"calls","source":3697,"target":431},{"edgeType":"extends","source":606,"target":36},{"edgeType":"calls","source":5876,"target":5816},{"edgeType":"calls","source":5310,"target":3278},{"edgeType":"calls","source":6463,"target":303},{"edgeType":"contains","source":4091,"target":4131},{"edgeType":"contains","source":6280,"target":7092},{"edgeType":"calls","source":887,"target":893},{"edgeType":"contains","source":6459,"target":6804},{"edgeType":"contains","source":4691,"target":5589},{"edgeType":"contains","source":2902,"target":2910},{"edgeType":"calls","source":3697,"target":3632},{"edgeType":"calls","source":529,"target":364},{"edgeType":"calls","source":5504,"target":467},{"edgeType":"contains","source":2502,"target":2625},{"edgeType":"calls","source":1108,"target":384},{"edgeType":"contains","source":4139,"target":503},{"edgeType":"calls","source":6464,"target":304},{"edgeType":"calls","source":6863,"target":588},{"edgeType":"calls","source":2610,"target":1390},{"edgeType":"calls","source":6804,"target":303},{"edgeType":"calls","source":2329,"target":588},{"edgeType":"calls","source":4384,"target":304},{"edgeType":"calls","source":2998,"target":3104},{"edgeType":"calls","source":7136,"target":582},{"edgeType":"contains","source":4719,"target":4720},{"edgeType":"calls","source":1797,"target":165},{"edgeType":"calls","source":3357,"target":431},{"edgeType":"calls","source":5504,"target":466},{"edgeType":"calls","source":4017,"target":1112},{"edgeType":"calls","source":536,"target":146},{"edgeType":"calls","source":565,"target":304},{"edgeType":"contains","source":6530,"target":6718},{"edgeType":"calls","source":2094,"target":471},{"edgeType":"calls","source":4570,"target":1938},{"edgeType":"calls","source":6464,"target":303},{"edgeType":"calls","source":6804,"target":304},{"edgeType":"imports","source":2843,"target":190},{"edgeType":"calls","source":2704,"target":2705},{"edgeType":"contains","source":4139,"target":502},{"edgeType":"calls","source":2610,"target":1391},{"edgeType":"calls","source":4711,"target":1795},{"edgeType":"calls","source":4655,"target":4588},{"edgeType":"calls","source":5138,"target":2298},{"edgeType":"contains","source":2902,"target":2908},{"edgeType":"calls","source":5296,"target":571},{"edgeType":"contains","source":3461,"target":3549},{"edgeType":"calls","source":4384,"target":303},{"edgeType":"extends","source":191,"target":189},{"edgeType":"calls","source":1525,"target":144},{"edgeType":"calls","source":529,"target":366},{"edgeType":"contains","source":6530,"target":6719},{"edgeType":"contains","source":2502,"target":2623},{"edgeType":"calls","source":5504,"target":465},{"edgeType":"calls","source":1218,"target":147},{"edgeType":"contains","source":30,"target":5266},{"edgeType":"calls","source":6606,"target":6443},{"edgeType":"calls","source":2626,"target":892},{"edgeType":"calls","source":2610,"target":1388},{"edgeType":"imports","source":3166,"target":1803},{"edgeType":"calls","source":6584,"target":2897},{"edgeType":"contains","source":2902,"target":2909},{"edgeType":"contains","source":41,"target":3867},{"edgeType":"calls","source":3045,"target":588},{"edgeType":"contains","source":4378,"target":4718},{"edgeType":"calls","source":5281,"target":2092},{"edgeType":"contains","source":6459,"target":6807},{"edgeType":"contains","source":6799,"target":6838},{"edgeType":"contains","source":6530,"target":6720},{"edgeType":"calls","source":5504,"target":464},{"edgeType":"calls","source":5409,"target":3409},{"edgeType":"contains","source":2502,"target":2624},{"edgeType":"contains","source":2581,"target":175},{"edgeType":"calls","source":1218,"target":146},{"edgeType":"calls","source":2616,"target":146},{"edgeType":"contains","source":30,"target":5265},{"edgeType":"calls","source":2610,"target":1389},{"edgeType":"contains","source":1977,"target":1987},{"edgeType":"calls","source":4688,"target":4620},{"edgeType":"calls","source":6969,"target":6819},{"edgeType":"calls","source":5281,"target":2091},{"edgeType":"contains","source":4139,"target":507},{"edgeType":"imports","source":42,"target":340},{"edgeType":"calls","source":3710,"target":1111},{"edgeType":"contains","source":2502,"target":2630},{"edgeType":"calls","source":6840,"target":248},{"edgeType":"contains","source":4432,"target":5165},{"edgeType":"calls","source":2740,"target":527},{"edgeType":"calls","source":6690,"target":2784},{"edgeType":"contains","source":2502,"target":2629},{"edgeType":"calls","source":5504,"target":463},{"edgeType":"contains","source":6530,"target":6713},{"edgeType":"calls","source":3332,"target":144},{"edgeType":"contains","source":1977,"target":1992},{"edgeType":"calls","source":1108,"target":380},{"edgeType":"contains","source":1417,"target":326},{"edgeType":"calls","source":1797,"target":161},{"edgeType":"imports","source":5166,"target":2177},{"edgeType":"contains","source":3461,"target":3554},{"edgeType":"contains","source":6459,"target":6801},{"edgeType":"calls","source":2740,"target":528},{"edgeType":"calls","source":6206,"target":6183},{"edgeType":"contains","source":4432,"target":5164},{"edgeType":"calls","source":5504,"target":462},{"edgeType":"calls","source":5450,"target":2136},{"edgeType":"contains","source":3981,"target":4347},{"edgeType":"contains","source":3241,"target":4033},{"edgeType":"contains","source":4139,"target":506},{"edgeType":"calls","source":2626,"target":891},{"edgeType":"contains","source":3563,"target":3564},{"edgeType":"calls","source":4035,"target":1604},{"edgeType":"calls","source":4321,"target":4366},{"edgeType":"calls","source":1797,"target":164},{"edgeType":"contains","source":4719,"target":4723},{"edgeType":"contains","source":2502,"target":2627},{"edgeType":"calls","source":565,"target":303},{"edgeType":"calls","source":6501,"target":6531},{"edgeType":"contains","source":4432,"target":5163},{"edgeType":"calls","source":5787,"target":144},{"edgeType":"contains","source":6530,"target":6715},{"edgeType":"calls","source":1209,"target":422},{"edgeType":"calls","source":1103,"target":537},{"edgeType":"calls","source":1108,"target":382},{"edgeType":"contains","source":4139,"target":505},{"edgeType":"contains","source":3596,"target":3597},{"edgeType":"calls","source":877,"target":144},{"edgeType":"calls","source":5107,"target":84},{"edgeType":"calls","source":7136,"target":588},{"edgeType":"calls","source":6053,"target":354},{"edgeType":"calls","source":1723,"target":1400},{"edgeType":"calls","source":7063,"target":737},{"edgeType":"calls","source":6837,"target":6686},{"edgeType":"contains","source":3461,"target":3552},{"edgeType":"calls","source":1535,"target":886},{"edgeType":"calls","source":4482,"target":431},{"edgeType":"contains","source":2902,"target":2913},{"edgeType":"contains","source":2502,"target":2628},{"edgeType":"contains","source":3241,"target":4031},{"edgeType":"contains","source":4139,"target":504},{"edgeType":"calls","source":5129,"target":458},{"edgeType":"contains","source":3981,"target":4345},{"edgeType":"calls","source":1209,"target":421},{"edgeType":"calls","source":1108,"target":381},{"edgeType":"contains","source":4091,"target":4113},{"edgeType":"contains","source":2502,"target":2634},{"edgeType":"calls","source":5745,"target":5673},{"edgeType":"calls","source":4218,"target":157},{"edgeType":"calls","source":127,"target":133},{"edgeType":"contains","source":4378,"target":4730},{"edgeType":"calls","source":6241,"target":6152},{"edgeType":"imports","source":5166,"target":49},{"edgeType":"calls","source":5032,"target":3464},{"edgeType":"calls","source":5129,"target":457},{"edgeType":"contains","source":3241,"target":4036},{"edgeType":"calls","source":5504,"target":2573},{"edgeType":"contains","source":3596,"target":3603},{"edgeType":"contains","source":1977,"target":1997},{"edgeType":"calls","source":2572,"target":2560},{"edgeType":"calls","source":6772,"target":4475},{"edgeType":"extends","source":5686,"target":36},{"edgeType":"calls","source":6932,"target":572},{"edgeType":"calls","source":5023,"target":571},{"edgeType":"calls","source":2779,"target":372},{"edgeType":"calls","source":6722,"target":1797},{"edgeType":"calls","source":3743,"target":84},{"edgeType":"calls","source":3741,"target":146},{"edgeType":"calls","source":5512,"target":210},{"edgeType":"contains","source":3496,"target":3531},{"edgeType":"calls","source":3112,"target":2733},{"edgeType":"calls","source":1797,"target":160},{"edgeType":"extends","source":192,"target":166},{"edgeType":"contains","source":1977,"target":1994},{"edgeType":"contains","source":4139,"target":509},{"edgeType":"calls","source":535,"target":171},{"edgeType":"calls","source":6932,"target":573},{"edgeType":"contains","source":6280,"target":7078},{"edgeType":"calls","source":6486,"target":7000},{"edgeType":"contains","source":181,"target":593},{"edgeType":"calls","source":6569,"target":6541},{"edgeType":"calls","source":5512,"target":209},{"edgeType":"calls","source":1797,"target":159},{"edgeType":"contains","source":579,"target":939},{"edgeType":"imports","source":5473,"target":49},{"edgeType":"contains","source":4139,"target":508},{"edgeType":"contains","source":1977,"target":1995},{"edgeType":"calls","source":535,"target":170},{"edgeType":"calls","source":6772,"target":4477},{"edgeType":"calls","source":4035,"target":1601},{"edgeType":"calls","source":127,"target":134},{"edgeType":"calls","source":6425,"target":445},{"edgeType":"contains","source":2502,"target":2633},{"edgeType":"imports","source":6530,"target":49},{"edgeType":"contains","source":6459,"target":6816},{"edgeType":"calls","source":5887,"target":210},{"edgeType":"contains","source":3496,"target":3529},{"edgeType":"calls","source":3231,"target":3267},{"edgeType":"contains","source":3241,"target":4041},{"edgeType":"calls","source":2572,"target":2555},{"edgeType":"contains","source":1977,"target":2000},{"edgeType":"contains","source":3981,"target":1185},{"edgeType":"contains","source":1814,"target":2825},{"edgeType":"calls","source":2501,"target":528},{"edgeType":"contains","source":2275,"target":2276},{"edgeType":"calls","source":5887,"target":209},{"edgeType":"calls","source":2878,"target":469},{"edgeType":"imports","source":153,"target":79},{"edgeType":"calls","source":2976,"target":1659},{"edgeType":"calls","source":1757,"target":1393},{"edgeType":"extends","source":328,"target":180},{"edgeType":"calls","source":5379,"target":5387},{"edgeType":"calls","source":7000,"target":582},{"edgeType":"contains","source":2688,"target":1101},{"edgeType":"contains","source":1977,"target":2001},{"edgeType":"calls","source":6911,"target":170},{"edgeType":"calls","source":6425,"target":443},{"edgeType":"calls","source":7068,"target":588},{"edgeType":"calls","source":6867,"target":6819},{"edgeType":"contains","source":181,"target":594},{"edgeType":"calls","source":1757,"target":1392},{"edgeType":"contains","source":1302,"target":2843},{"edgeType":"contains","source":3013,"target":3710},{"edgeType":"calls","source":3434,"target":146},{"edgeType":"contains","source":2736,"target":2781},{"edgeType":"contains","source":2070,"target":2286},{"edgeType":"calls","source":6863,"target":6944},{"edgeType":"contains","source":30,"target":5279},{"edgeType":"calls","source":6787,"target":1901},{"edgeType":"calls","source":6911,"target":171},{"edgeType":"contains","source":6459,"target":6811},{"edgeType":"calls","source":1531,"target":1002},{"edgeType":"contains","source":4378,"target":4732},{"edgeType":"calls","source":6605,"target":144},{"edgeType":"calls","source":3434,"target":2257},{"edgeType":"contains","source":3166,"target":1078},{"edgeType":"calls","source":1598,"target":1039},{"edgeType":"imports","source":3166,"target":1807},{"edgeType":"calls","source":6946,"target":144},{"edgeType":"calls","source":6258,"target":333},{"edgeType":"contains","source":2736,"target":2782},{"edgeType":"extends","source":3606,"target":36},{"edgeType":"calls","source":4925,"target":431},{"edgeType":"contains","source":4579,"target":4842},{"edgeType":"calls","source":6902,"target":6793},{"edgeType":"calls","source":6725,"target":4881},{"edgeType":"calls","source":2501,"target":527},{"edgeType":"calls","source":6704,"target":4475},{"edgeType":"contains","source":4389,"target":4390},{"edgeType":"contains","source":4378,"target":4731},{"edgeType":"imports","source":153,"target":78},{"edgeType":"calls","source":3434,"target":2258},{"edgeType":"calls","source":1757,"target":1394},{"edgeType":"contains","source":3365,"target":3366},{"edgeType":"calls","source":6979,"target":146},{"edgeType":"contains","source":4474,"target":4900},{"edgeType":"calls","source":6151,"target":445},{"edgeType":"extends","source":3408,"target":3043},{"edgeType":"calls","source":1363,"target":886},{"edgeType":"calls","source":1141,"target":369},{"edgeType":"calls","source":3219,"target":431},{"edgeType":"calls","source":4926,"target":366},{"edgeType":"contains","source":190,"target":288},{"edgeType":"calls","source":741,"target":84},{"edgeType":"contains","source":5,"target":3908},{"edgeType":"calls","source":2329,"target":2652},{"edgeType":"calls","source":5163,"target":4647},{"edgeType":"contains","source":4378,"target":4705},{"edgeType":"contains","source":2702,"target":2751},{"edgeType":"calls","source":2198,"target":371},{"edgeType":"calls","source":3842,"target":144},{"edgeType":"calls","source":6945,"target":144},{"edgeType":"calls","source":3330,"target":3333},{"edgeType":"calls","source":6977,"target":209},{"edgeType":"calls","source":1414,"target":1418},{"edgeType":"calls","source":1141,"target":368},{"edgeType":"calls","source":4646,"target":589},{"edgeType":"contains","source":3818,"target":4094},{"edgeType":"calls","source":5000,"target":4413},{"edgeType":"contains","source":190,"target":287},{"edgeType":"contains","source":193,"target":194},{"edgeType":"calls","source":4740,"target":5074},{"edgeType":"contains","source":3626,"target":3704},{"edgeType":"calls","source":2329,"target":2653},{"edgeType":"calls","source":2307,"target":164},{"edgeType":"calls","source":6151,"target":443},{"edgeType":"calls","source":5880,"target":5673},{"edgeType":"contains","source":2898,"target":4075},{"edgeType":"calls","source":4740,"target":5073},{"edgeType":"extends","source":2901,"target":2902},{"edgeType":"calls","source":6977,"target":210},{"edgeType":"calls","source":4246,"target":303},{"edgeType":"calls","source":6385,"target":588},{"edgeType":"calls","source":2103,"target":146},{"edgeType":"contains","source":2702,"target":2749},{"edgeType":"calls","source":1141,"target":371},{"edgeType":"calls","source":5378,"target":5379},{"edgeType":"calls","source":1033,"target":548},{"edgeType":"calls","source":6832,"target":6819},{"edgeType":"contains","source":190,"target":290},{"edgeType":"contains","source":193,"target":197},{"edgeType":"contains","source":3818,"target":4093},{"edgeType":"contains","source":130,"target":2150},{"edgeType":"calls","source":4926,"target":364},{"edgeType":"calls","source":2198,"target":369},{"edgeType":"contains","source":3229,"target":3324},{"edgeType":"contains","source":6799,"target":6820},{"edgeType":"contains","source":6530,"target":6704},{"edgeType":"calls","source":4740,"target":5072},{"edgeType":"calls","source":4864,"target":171},{"edgeType":"contains","source":5313,"target":5314},{"edgeType":"calls","source":4246,"target":304},{"edgeType":"calls","source":6486,"target":6976},{"edgeType":"calls","source":2504,"target":2511},{"edgeType":"calls","source":1141,"target":370},{"edgeType":"contains","source":193,"target":196},{"edgeType":"contains","source":190,"target":289},{"edgeType":"contains","source":130,"target":2149},{"edgeType":"calls","source":6670,"target":215},{"edgeType":"calls","source":4902,"target":5335},{"edgeType":"contains","source":5,"target":3910},{"edgeType":"calls","source":6474,"target":1006},{"edgeType":"contains","source":3726,"target":3773},{"edgeType":"contains","source":6106,"target":6107},{"edgeType":"calls","source":2198,"target":370},{"edgeType":"extends","source":27,"target":36},{"edgeType":"contains","source":3818,"target":4099},{"edgeType":"contains","source":4502,"target":5093},{"edgeType":"calls","source":4740,"target":5071},{"edgeType":"calls","source":4864,"target":170},{"edgeType":"extends","source":2073,"target":36},{"edgeType":"extends","source":6676,"target":36},{"edgeType":"contains","source":190,"target":292},{"edgeType":"contains","source":3726,"target":3780},{"edgeType":"calls","source":3123,"target":1288},{"edgeType":"calls","source":3123,"target":1289},{"edgeType":"contains","source":5,"target":3913},{"edgeType":"contains","source":6459,"target":6784},{"edgeType":"calls","source":1721,"target":354},{"edgeType":"calls","source":2514,"target":84},{"edgeType":"contains","source":4502,"target":5092},{"edgeType":"calls","source":4740,"target":5070},{"edgeType":"calls","source":2703,"target":568},{"edgeType":"calls","source":6940,"target":303},{"edgeType":"calls","source":5678,"target":304},{"edgeType":"calls","source":1243,"target":1430},{"edgeType":"contains","source":190,"target":291},{"edgeType":"calls","source":3295,"target":2300},{"edgeType":"calls","source":917,"target":965},{"edgeType":"contains","source":5908,"target":6953},{"edgeType":"calls","source":5235,"target":1352},{"edgeType":"calls","source":1141,"target":364},{"edgeType":"contains","source":3726,"target":3779},{"edgeType":"calls","source":1142,"target":333},{"edgeType":"calls","source":2372,"target":2373},{"edgeType":"calls","source":1080,"target":1197},{"edgeType":"calls","source":3194,"target":146},{"edgeType":"contains","source":6459,"target":6785},{"edgeType":"contains","source":6604,"target":3347},{"edgeType":"calls","source":2198,"target":368},{"edgeType":"calls","source":5678,"target":303},{"edgeType":"calls","source":1348,"target":1349},{"edgeType":"contains","source":4474,"target":4902},{"edgeType":"contains","source":4579,"target":4818},{"edgeType":"calls","source":4740,"target":5069},{"edgeType":"contains","source":30,"target":6311},{"edgeType":"contains","source":6530,"target":6699},{"edgeType":"contains","source":190,"target":294},{"edgeType":"calls","source":6940,"target":304},{"edgeType":"contains","source":3954,"target":4109},{"edgeType":"calls","source":3123,"target":1286},{"edgeType":"contains","source":5908,"target":6954},{"edgeType":"calls","source":4617,"target":4654},{"edgeType":"calls","source":4667,"target":2047},{"edgeType":"contains","source":2702,"target":2753},{"edgeType":"calls","source":1414,"target":1416},{"edgeType":"contains","source":2311,"target":5362},{"edgeType":"contains","source":190,"target":293},{"edgeType":"calls","source":5162,"target":442},{"edgeType":"calls","source":3023,"target":3330},{"edgeType":"calls","source":1141,"target":366},{"edgeType":"contains","source":3818,"target":4096},{"edgeType":"calls","source":3123,"target":1287},{"edgeType":"calls","source":1045,"target":171},{"edgeType":"contains","source":5908,"target":6955},{"edgeType":"calls","source":1045,"target":170},{"edgeType":"contains","source":2070,"target":2263},{"edgeType":"calls","source":4667,"target":2046},{"edgeType":"calls","source":4568,"target":4058},{"edgeType":"calls","source":2600,"target":588},{"edgeType":"calls","source":4617,"target":4653},{"edgeType":"contains","source":6459,"target":6787},{"edgeType":"calls","source":2198,"target":366},{"edgeType":"contains","source":2702,"target":2754},{"edgeType":"calls","source":4317,"target":212},{"edgeType":"contains","source":920,"target":921},{"edgeType":"calls","source":3123,"target":1284},{"edgeType":"calls","source":1243,"target":1427},{"edgeType":"calls","source":5371,"target":304},{"edgeType":"calls","source":2570,"target":2572},{"edgeType":"calls","source":2264,"target":431},{"edgeType":"calls","source":1543,"target":582},{"edgeType":"calls","source":5045,"target":1953},{"edgeType":"calls","source":6662,"target":469},{"edgeType":"contains","source":2902,"target":2903},{"edgeType":"calls","source":4902,"target":1101},{"edgeType":"calls","source":1241,"target":431},{"edgeType":"calls","source":3123,"target":1285},{"edgeType":"calls","source":1243,"target":1426},{"edgeType":"calls","source":5371,"target":303},{"edgeType":"contains","source":1977,"target":1981},{"edgeType":"calls","source":1119,"target":1041},{"edgeType":"contains","source":6530,"target":6710},{"edgeType":"calls","source":2198,"target":364},{"edgeType":"calls","source":5137,"target":157},{"edgeType":"calls","source":1243,"target":1429},{"edgeType":"calls","source":1142,"target":332},{"edgeType":"contains","source":4091,"target":4095},{"edgeType":"extends","source":1698,"target":36},{"edgeType":"calls","source":6117,"target":431},{"edgeType":"contains","source":1977,"target":1978},{"edgeType":"calls","source":6087,"target":304},{"edgeType":"calls","source":2305,"target":215},{"edgeType":"calls","source":5746,"target":304},{"edgeType":"contains","source":30,"target":6314},{"edgeType":"contains","source":920,"target":922},{"edgeType":"calls","source":6561,"target":431},{"edgeType":"calls","source":1243,"target":1428},{"edgeType":"calls","source":5512,"target":1216},{"edgeType":"calls","source":1882,"target":1702},{"edgeType":"contains","source":1977,"target":1979},{"edgeType":"calls","source":6087,"target":303},{"edgeType":"calls","source":7063,"target":7067},{"edgeType":"contains","source":4378,"target":4710},{"edgeType":"contains","source":2902,"target":2906},{"edgeType":"calls","source":965,"target":527},{"edgeType":"calls","source":5746,"target":303},{"edgeType":"contains","source":3241,"target":4024},{"edgeType":"calls","source":3666,"target":303},{"edgeType":"calls","source":1244,"target":1391},{"edgeType":"contains","source":6106,"target":6108},{"edgeType":"contains","source":1779,"target":1780},{"edgeType":"imports","source":5410,"target":5223},{"edgeType":"contains","source":3819,"target":4077},{"edgeType":"contains","source":2502,"target":2621},{"edgeType":"contains","source":2581,"target":172},{"edgeType":"calls","source":6462,"target":304},{"edgeType":"calls","source":3666,"target":304},{"edgeType":"calls","source":4382,"target":304},{"edgeType":"contains","source":4378,"target":4716},{"edgeType":"calls","source":3008,"target":2732},{"edgeType":"extends","source":4767,"target":36},{"edgeType":"contains","source":3461,"target":3546},{"edgeType":"calls","source":5471,"target":4599},{"edgeType":"calls","source":1244,"target":1390},{"edgeType":"calls","source":5433,"target":1548},{"edgeType":"contains","source":2502,"target":2622},{"edgeType":"calls","source":1312,"target":339},{"edgeType":"imports","source":3726,"target":3520},{"edgeType":"calls","source":6838,"target":303},{"edgeType":"calls","source":6462,"target":303},{"edgeType":"calls","source":7068,"target":572},{"edgeType":"calls","source":4441,"target":588},{"edgeType":"calls","source":749,"target":883},{"edgeType":"contains","source":2902,"target":2904},{"edgeType":"calls","source":4382,"target":303},{"edgeType":"calls","source":2373,"target":1273},{"edgeType":"calls","source":3409,"target":2983},{"edgeType":"calls","source":1244,"target":1394},{"edgeType":"calls","source":1243,"target":1425},{"edgeType":"calls","source":4789,"target":371},{"edgeType":"calls","source":3420,"target":527},{"edgeType":"calls","source":5433,"target":1547},{"edgeType":"calls","source":1244,"target":1393},{"edgeType":"calls","source":1243,"target":1424},{"edgeType":"calls","source":3332,"target":84},{"edgeType":"contains","source":2502,"target":2619},{"edgeType":"calls","source":6433,"target":144},{"edgeType":"calls","source":7068,"target":573},{"edgeType":"calls","source":6838,"target":304},{"edgeType":"calls","source":6868,"target":431},{"edgeType":"calls","source":6908,"target":248},{"edgeType":"contains","source":2902,"target":2905},{"edgeType":"calls","source":965,"target":528},{"edgeType":"calls","source":5885,"target":4447},{"edgeType":"contains","source":4691,"target":5581},{"edgeType":"contains","source":6799,"target":6825},{"edgeType":"calls","source":1244,"target":1392},{"edgeType":"calls","source":1243,"target":1423},{"edgeType":"calls","source":3420,"target":528},{"edgeType":"calls","source":5407,"target":3409},{"edgeType":"calls","source":5433,"target":1546},{"edgeType":"contains","source":2502,"target":2620},{"edgeType":"calls","source":2616,"target":84},{"edgeType":"calls","source":4789,"target":370},{"edgeType":"calls","source":2205,"target":170},{"edgeType":"calls","source":3892,"target":3896},{"edgeType":"calls","source":596,"target":368},{"edgeType":"contains","source":3229,"target":3310},{"edgeType":"calls","source":1312,"target":369},{"edgeType":"contains","source":3241,"target":3995},{"edgeType":"calls","source":1248,"target":1296},{"edgeType":"contains","source":2581,"target":143},{"edgeType":"contains","source":4459,"target":5348},{"edgeType":"calls","source":6138,"target":6149},{"edgeType":"calls","source":4520,"target":4513},{"edgeType":"calls","source":876,"target":144},{"edgeType":"contains","source":190,"target":271},{"edgeType":"calls","source":4682,"target":548},{"edgeType":"calls","source":2735,"target":2767},{"edgeType":"contains","source":2237,"target":2352},{"edgeType":"contains","source":4378,"target":4687},{"edgeType":"calls","source":2205,"target":171},{"edgeType":"calls","source":5280,"target":2092},{"edgeType":"calls","source":5238,"target":4451},{"edgeType":"calls","source":5886,"target":4447},{"edgeType":"calls","source":3434,"target":125},{"edgeType":"contains","source":6074,"target":1795},{"edgeType":"calls","source":1312,"target":368},{"edgeType":"calls","source":6904,"target":342},{"edgeType":"contains","source":4459,"target":5347},{"edgeType":"calls","source":5445,"target":148},{"edgeType":"calls","source":5107,"target":56},{"edgeType":"contains","source":190,"target":270},{"edgeType":"calls","source":886,"target":890},{"edgeType":"contains","source":2237,"target":2349},{"edgeType":"extends","source":5448,"target":36},{"edgeType":"calls","source":878,"target":84},{"edgeType":"calls","source":5280,"target":2091},{"edgeType":"contains","source":6667,"target":6668},{"edgeType":"calls","source":4106,"target":431},{"edgeType":"contains","source":5081,"target":5091},{"edgeType":"calls","source":1159,"target":886},{"edgeType":"calls","source":1312,"target":371},{"edgeType":"contains","source":4474,"target":4881},{"edgeType":"contains","source":4459,"target":5346},{"edgeType":"calls","source":7033,"target":572},{"edgeType":"contains","source":190,"target":273},{"edgeType":"calls","source":6602,"target":1249},{"edgeType":"calls","source":6803,"target":303},{"edgeType":"calls","source":6808,"target":148},{"edgeType":"calls","source":596,"target":370},{"edgeType":"calls","source":6486,"target":5902},{"edgeType":"contains","source":2237,"target":2350},{"edgeType":"contains","source":4378,"target":4685},{"edgeType":"contains","source":3726,"target":3756},{"edgeType":"calls","source":4420,"target":210},{"edgeType":"calls","source":7135,"target":582},{"edgeType":"contains","source":5081,"target":5090},{"edgeType":"calls","source":5801,"target":1795},{"edgeType":"contains","source":6599,"target":6663},{"edgeType":"contains","source":3954,"target":4088},{"edgeType":"calls","source":596,"target":369},{"edgeType":"calls","source":594,"target":431},{"edgeType":"calls","source":535,"target":146},{"edgeType":"calls","source":490,"target":484},{"edgeType":"contains","source":6074,"target":1797},{"edgeType":"calls","source":6767,"target":4591},{"edgeType":"contains","source":2581,"target":142},{"edgeType":"calls","source":1312,"target":370},{"edgeType":"calls","source":5504,"target":431},{"edgeType":"calls","source":5533,"target":589},{"edgeType":"contains","source":3793,"target":3794},{"edgeType":"calls","source":7033,"target":573},{"edgeType":"calls","source":4761,"target":210},{"edgeType":"calls","source":2602,"target":1604},{"edgeType":"calls","source":6803,"target":304},{"edgeType":"calls","source":2735,"target":2766},{"edgeType":"calls","source":4817,"target":588},{"edgeType":"contains","source":190,"target":272},{"edgeType":"contains","source":1942,"target":1982},{"edgeType":"calls","source":6569,"target":159},{"edgeType":"calls","source":6602,"target":1250},{"edgeType":"imports","source":6770,"target":49},{"edgeType":"calls","source":1818,"target":535},{"edgeType":"calls","source":3842,"target":157},{"edgeType":"contains","source":2237,"target":2355},{"edgeType":"calls","source":2509,"target":2369},{"edgeType":"calls","source":7117,"target":84},{"edgeType":"calls","source":4420,"target":209},{"edgeType":"contains","source":2736,"target":2742},{"edgeType":"calls","source":4859,"target":342},{"edgeType":"calls","source":6606,"target":6412},{"edgeType":"contains","source":3229,"target":3314},{"edgeType":"calls","source":596,"target":364},{"edgeType":"calls","source":1527,"target":1099},{"edgeType":"contains","source":190,"target":275},{"edgeType":"contains","source":4139,"target":474},{"edgeType":"calls","source":4761,"target":209},{"edgeType":"calls","source":5141,"target":1113},{"edgeType":"contains","source":3562,"target":3563},{"edgeType":"calls","source":6569,"target":160},{"edgeType":"imports","source":2494,"target":2582},{"edgeType":"calls","source":6995,"target":1753},{"edgeType":"calls","source":2096,"target":372},{"edgeType":"calls","source":6723,"target":4900},{"edgeType":"contains","source":3229,"target":3315},{"edgeType":"calls","source":1221,"target":1071},{"edgeType":"calls","source":1591,"target":171},{"edgeType":"contains","source":4139,"target":473},{"edgeType":"contains","source":190,"target":274},{"edgeType":"calls","source":6569,"target":161},{"edgeType":"extends","source":4698,"target":36},{"edgeType":"calls","source":1312,"target":364},{"edgeType":"calls","source":5141,"target":1112},{"edgeType":"contains","source":2237,"target":2353},{"edgeType":"calls","source":4035,"target":1571},{"edgeType":"contains","source":6799,"target":6800},{"edgeType":"calls","source":3999,"target":573},{"edgeType":"calls","source":4240,"target":501},{"edgeType":"calls","source":4817,"target":4813},{"edgeType":"contains","source":3229,"target":3312},{"edgeType":"calls","source":596,"target":366},{"edgeType":"calls","source":6281,"target":4881},{"edgeType":"calls","source":569,"target":146},{"edgeType":"calls","source":3716,"target":889},{"edgeType":"contains","source":190,"target":277},{"edgeType":"calls","source":3399,"target":146},{"edgeType":"calls","source":6049,"target":445},{"edgeType":"calls","source":7140,"target":431},{"edgeType":"calls","source":4728,"target":171},{"edgeType":"calls","source":3740,"target":147},{"edgeType":"contains","source":952,"target":966},{"edgeType":"extends","source":6471,"target":36},{"edgeType":"contains","source":4579,"target":4800},{"edgeType":"calls","source":4817,"target":4812},{"edgeType":"calls","source":1312,"target":366},{"edgeType":"contains","source":4459,"target":5349},{"edgeType":"calls","source":3560,"target":2555},{"edgeType":"contains","source":3229,"target":3313},{"edgeType":"contains","source":190,"target":276},{"edgeType":"calls","source":5238,"target":4444},{"edgeType":"calls","source":7047,"target":144},{"edgeType":"calls","source":4728,"target":170},{"edgeType":"contains","source":5,"target":3900},{"edgeType":"calls","source":2305,"target":2347},{"edgeType":"contains","source":4579,"target":4808},{"edgeType":"calls","source":4182,"target":183},{"edgeType":"calls","source":6152,"target":422},{"edgeType":"contains","source":4502,"target":5081},{"edgeType":"contains","source":6459,"target":6780},{"edgeType":"contains","source":3818,"target":4087},{"edgeType":"contains","source":190,"target":279},{"edgeType":"contains","source":3229,"target":3318},{"edgeType":"calls","source":3330,"target":3340},{"edgeType":"calls","source":5162,"target":458},{"edgeType":"calls","source":965,"target":548},{"edgeType":"calls","source":1597,"target":1039},{"edgeType":"contains","source":3626,"target":3697},{"edgeType":"imports","source":5473,"target":78},{"edgeType":"calls","source":6049,"target":443},{"edgeType":"calls","source":3999,"target":572},{"edgeType":"calls","source":6152,"target":421},{"edgeType":"contains","source":5,"target":3899},{"edgeType":"contains","source":2237,"target":2360},{"edgeType":"imports","source":6530,"target":79},{"edgeType":"contains","source":4432,"target":5136},{"edgeType":"contains","source":4432,"target":5135},{"edgeType":"calls","source":3560,"target":2553},{"edgeType":"contains","source":6502,"target":6505},{"edgeType":"contains","source":3867,"target":453},{"edgeType":"contains","source":952,"target":968},{"edgeType":"calls","source":4892,"target":371},{"edgeType":"calls","source":6743,"target":56},{"edgeType":"contains","source":190,"target":278},{"edgeType":"contains","source":2863,"target":5152},{"edgeType":"calls","source":3330,"target":3341},{"edgeType":"calls","source":5162,"target":457},{"edgeType":"calls","source":1718,"target":458},{"edgeType":"contains","source":3229,"target":3319},{"edgeType":"imports","source":5473,"target":79},{"edgeType":"calls","source":1354,"target":1172},{"edgeType":"calls","source":1818,"target":533},{"edgeType":"contains","source":30,"target":1013},{"edgeType":"contains","source":2206,"target":2261},{"edgeType":"calls","source":4892,"target":369},{"edgeType":"contains","source":2237,"target":2357},{"edgeType":"calls","source":4392,"target":4242},{"edgeType":"calls","source":2305,"target":1288},{"edgeType":"calls","source":2305,"target":2345},{"edgeType":"contains","source":3166,"target":1041},{"edgeType":"contains","source":3867,"target":452},{"edgeType":"contains","source":4432,"target":5134},{"edgeType":"calls","source":5076,"target":1008},{"edgeType":"contains","source":3818,"target":4085},{"edgeType":"contains","source":6459,"target":6782},{"edgeType":"contains","source":190,"target":281},{"edgeType":"contains","source":6502,"target":6506},{"edgeType":"calls","source":5854,"target":144},{"edgeType":"contains","source":3229,"target":3316},{"edgeType":"calls","source":4892,"target":370},{"edgeType":"calls","source":4872,"target":2047},{"edgeType":"calls","source":5095,"target":4647},{"edgeType":"calls","source":1591,"target":170},{"edgeType":"imports","source":2201,"target":49},{"edgeType":"calls","source":3330,"target":3338},{"edgeType":"contains","source":3562,"target":3565},{"edgeType":"contains","source":4139,"target":475},{"edgeType":"contains","source":5,"target":3901},{"edgeType":"calls","source":7028,"target":7078},{"edgeType":"calls","source":4926,"target":371},{"edgeType":"calls","source":4892,"target":368},{"edgeType":"contains","source":4378,"target":4693},{"edgeType":"calls","source":2305,"target":1289},{"edgeType":"calls","source":2305,"target":2346},{"edgeType":"contains","source":4579,"target":4805},{"edgeType":"calls","source":6701,"target":303},{"edgeType":"contains","source":3867,"target":451},{"edgeType":"contains","source":3818,"target":4084},{"edgeType":"contains","source":4432,"target":5133},{"edgeType":"contains","source":6502,"target":6507},{"edgeType":"contains","source":190,"target":280},{"edgeType":"calls","source":4872,"target":2046},{"edgeType":"contains","source":3229,"target":3317},{"edgeType":"contains","source":3726,"target":3765},{"edgeType":"calls","source":1261,"target":886},{"edgeType":"calls","source":3330,"target":3339},{"edgeType":"contains","source":2702,"target":2747},{"edgeType":"calls","source":1150,"target":1151},{"edgeType":"calls","source":4926,"target":370},{"edgeType":"calls","source":4740,"target":5079},{"edgeType":"calls","source":2329,"target":2656},{"edgeType":"calls","source":2305,"target":2343},{"edgeType":"contains","source":6799,"target":6806},{"edgeType":"contains","source":2237,"target":2363},{"edgeType":"contains","source":325,"target":327},{"edgeType":"calls","source":6701,"target":304},{"edgeType":"contains","source":190,"target":283},{"edgeType":"contains","source":130,"target":2143},{"edgeType":"contains","source":4355,"target":4357},{"edgeType":"calls","source":2305,"target":1286},{"edgeType":"contains","source":3229,"target":3322},{"edgeType":"calls","source":3330,"target":3336},{"edgeType":"contains","source":3241,"target":4009},{"edgeType":"imports","source":5285,"target":2741},{"edgeType":"contains","source":4619,"target":4628},{"edgeType":"contains","source":2702,"target":2748},{"edgeType":"calls","source":6117,"target":445},{"edgeType":"calls","source":4926,"target":369},{"edgeType":"calls","source":4892,"target":366},{"edgeType":"calls","source":4740,"target":5078},{"edgeType":"calls","source":2305,"target":1287},{"edgeType":"calls","source":2305,"target":2344},{"edgeType":"calls","source":4495,"target":1046},{"edgeType":"contains","source":190,"target":282},{"edgeType":"calls","source":6670,"target":2323},{"edgeType":"calls","source":6738,"target":215},{"edgeType":"calls","source":5235,"target":304},{"edgeType":"calls","source":3330,"target":3337},{"edgeType":"contains","source":3229,"target":3323},{"edgeType":"calls","source":3330,"target":3334},{"edgeType":"calls","source":3467,"target":144},{"edgeType":"calls","source":4123,"target":4120},{"edgeType":"calls","source":4926,"target":368},{"edgeType":"extends","source":3229,"target":3300},{"edgeType":"contains","source":2311,"target":5353},{"edgeType":"contains","source":6459,"target":6777},{"edgeType":"extends","source":5312,"target":36},{"edgeType":"contains","source":190,"target":286},{"edgeType":"contains","source":190,"target":285},{"edgeType":"calls","source":2307,"target":165},{"edgeType":"calls","source":2305,"target":1284},{"edgeType":"calls","source":5712,"target":5599},{"edgeType":"calls","source":2305,"target":2341},{"edgeType":"contains","source":3626,"target":3699},{"edgeType":"calls","source":5235,"target":303},{"edgeType":"calls","source":2329,"target":2654},{"edgeType":"calls","source":3155,"target":303},{"edgeType":"contains","source":3818,"target":4089},{"edgeType":"contains","source":3496,"target":3501},{"edgeType":"calls","source":1718,"target":457},{"edgeType":"contains","source":3229,"target":3320},{"edgeType":"calls","source":3330,"target":3335},{"edgeType":"calls","source":1818,"target":528},{"edgeType":"calls","source":6117,"target":443},{"edgeType":"calls","source":2329,"target":2655},{"edgeType":"calls","source":6486,"target":6972},{"edgeType":"contains","source":5,"target":3905},{"edgeType":"calls","source":6866,"target":6819},{"edgeType":"calls","source":6534,"target":6541},{"edgeType":"contains","source":6530,"target":6692},{"edgeType":"calls","source":4892,"target":364},{"edgeType":"calls","source":6704,"target":6556},{"edgeType":"contains","source":6502,"target":6503},{"edgeType":"contains","source":190,"target":284},{"edgeType":"contains","source":3726,"target":3769},{"edgeType":"calls","source":2305,"target":1285},{"edgeType":"calls","source":2305,"target":2342},{"edgeType":"calls","source":3155,"target":304},{"edgeType":"calls","source":1818,"target":527},{"edgeType":"contains","source":3229,"target":3321},{"edgeType":"calls","source":354,"target":553},{"edgeType":"contains","source":4767,"target":4769},{"edgeType":"calls","source":2809,"target":555},{"edgeType":"extends","source":1106,"target":180},{"edgeType":"calls","source":2837,"target":2858},{"edgeType":"contains","source":3166,"target":3661},{"edgeType":"calls","source":711,"target":56},{"edgeType":"calls","source":1583,"target":507},{"edgeType":"calls","source":886,"target":974},{"edgeType":"contains","source":602,"target":695},{"edgeType":"contains","source":4432,"target":4583},{"edgeType":"contains","source":5758,"target":5760},{"edgeType":"contains","source":5756,"target":5822},{"edgeType":"calls","source":3420,"target":2755},{"edgeType":"contains","source":4139,"target":4153},{"edgeType":"imports","source":4307,"target":79},{"edgeType":"contains","source":4003,"target":4141},{"edgeType":"calls","source":6880,"target":144},{"edgeType":"calls","source":4049,"target":170},{"edgeType":"calls","source":6694,"target":4853},{"edgeType":"contains","source":1297,"target":1350},{"edgeType":"contains","source":1229,"target":1344},{"edgeType":"contains","source":4898,"target":4935},{"edgeType":"calls","source":5893,"target":84},{"edgeType":"calls","source":1583,"target":506},{"edgeType":"calls","source":4368,"target":4021},{"edgeType":"contains","source":4668,"target":437},{"edgeType":"contains","source":602,"target":694},{"edgeType":"extends","source":6771,"target":36},{"edgeType":"contains","source":5758,"target":5761},{"edgeType":"contains","source":5756,"target":5823},{"edgeType":"contains","source":336,"target":484},{"edgeType":"contains","source":4003,"target":4140},{"edgeType":"contains","source":4002,"target":4171},{"edgeType":"contains","source":4139,"target":4152},{"edgeType":"contains","source":3606,"target":3761},{"edgeType":"calls","source":4176,"target":1515},{"edgeType":"contains","source":6280,"target":6492},{"edgeType":"contains","source":602,"target":698},{"edgeType":"calls","source":6366,"target":2333},{"edgeType":"calls","source":4958,"target":528},{"edgeType":"calls","source":5062,"target":475},{"edgeType":"contains","source":6683,"target":6684},{"edgeType":"contains","source":901,"target":942},{"edgeType":"calls","source":6541,"target":84},{"edgeType":"calls","source":4756,"target":448},{"edgeType":"contains","source":1926,"target":1932},{"edgeType":"contains","source":602,"target":697},{"edgeType":"calls","source":1756,"target":431},{"edgeType":"imports","source":182,"target":49},{"edgeType":"calls","source":1600,"target":1039},{"edgeType":"calls","source":1597,"target":1132},{"edgeType":"contains","source":4139,"target":4151},{"edgeType":"calls","source":1583,"target":509},{"edgeType":"contains","source":2176,"target":3695},{"edgeType":"contains","source":5758,"target":5762},{"edgeType":"contains","source":5756,"target":5824},{"edgeType":"contains","source":3606,"target":3760},{"edgeType":"contains","source":6280,"target":6493},{"edgeType":"calls","source":6882,"target":84},{"edgeType":"calls","source":6939,"target":431},{"edgeType":"calls","source":5062,"target":474},{"edgeType":"contains","source":1379,"target":1977},{"edgeType":"calls","source":4756,"target":447},{"edgeType":"calls","source":4958,"target":527},{"edgeType":"calls","source":1583,"target":508},{"edgeType":"contains","source":4003,"target":4138},{"edgeType":"calls","source":3034,"target":3093},{"edgeType":"contains","source":602,"target":696},{"edgeType":"contains","source":4139,"target":4150},{"edgeType":"contains","source":5758,"target":5763},{"edgeType":"contains","source":5756,"target":5825},{"edgeType":"contains","source":5,"target":2291},{"edgeType":"contains","source":4139,"target":4157},{"edgeType":"calls","source":6846,"target":144},{"edgeType":"contains","source":5756,"target":5817},{"edgeType":"contains","source":4668,"target":4671},{"edgeType":"calls","source":2537,"target":527},{"edgeType":"calls","source":5062,"target":473},{"edgeType":"contains","source":1229,"target":1347},{"edgeType":"contains","source":602,"target":700},{"edgeType":"contains","source":6980,"target":6984},{"edgeType":"contains","source":4635,"target":4637},{"edgeType":"imports","source":1303,"target":179},{"edgeType":"contains","source":4432,"target":4587},{"edgeType":"calls","source":1583,"target":503},{"edgeType":"calls","source":426,"target":431},{"edgeType":"contains","source":4898,"target":4939},{"edgeType":"contains","source":4139,"target":4156},{"edgeType":"calls","source":6700,"target":443},{"edgeType":"contains","source":5756,"target":5818},{"edgeType":"contains","source":1297,"target":1354},{"edgeType":"contains","source":602,"target":699},{"edgeType":"calls","source":2537,"target":528},{"edgeType":"calls","source":5379,"target":1216},{"edgeType":"calls","source":2825,"target":56},{"edgeType":"calls","source":5002,"target":4446},{"edgeType":"contains","source":6980,"target":6985},{"edgeType":"contains","source":4635,"target":4636},{"edgeType":"extends","source":3072,"target":1605},{"edgeType":"contains","source":4767,"target":4772},{"edgeType":"calls","source":1583,"target":502},{"edgeType":"extends","source":3818,"target":3847},{"edgeType":"contains","source":3809,"target":3816},{"edgeType":"contains","source":5,"target":2296},{"edgeType":"contains","source":4139,"target":4155},{"edgeType":"calls","source":1354,"target":1262},{"edgeType":"contains","source":5756,"target":5819},{"edgeType":"calls","source":5513,"target":1289},{"edgeType":"contains","source":1297,"target":1351},{"edgeType":"contains","source":1229,"target":1345},{"edgeType":"calls","source":2881,"target":431},{"edgeType":"contains","source":602,"target":702},{"edgeType":"contains","source":4767,"target":4771},{"edgeType":"contains","source":2915,"target":2988},{"edgeType":"calls","source":7078,"target":354},{"edgeType":"contains","source":4668,"target":440},{"edgeType":"calls","source":1583,"target":505},{"edgeType":"imports","source":42,"target":157},{"edgeType":"imports","source":5166,"target":5167},{"edgeType":"contains","source":4003,"target":4143},{"edgeType":"calls","source":4231,"target":4035},{"edgeType":"contains","source":5756,"target":5820},{"edgeType":"imports","source":1814,"target":190},{"edgeType":"calls","source":5379,"target":5442},{"edgeType":"calls","source":5513,"target":1288},{"edgeType":"calls","source":3453,"target":1727},{"edgeType":"calls","source":6700,"target":445},{"edgeType":"extends","source":5748,"target":36},{"edgeType":"contains","source":1297,"target":1352},{"edgeType":"imports","source":3352,"target":79},{"edgeType":"contains","source":602,"target":701},{"edgeType":"contains","source":1229,"target":1346},{"edgeType":"calls","source":1051,"target":84},{"edgeType":"calls","source":4953,"target":3849},{"edgeType":"contains","source":4898,"target":4937},{"edgeType":"contains","source":6980,"target":6987},{"edgeType":"calls","source":1583,"target":504},{"edgeType":"contains","source":4668,"target":439},{"edgeType":"contains","source":336,"target":490},{"edgeType":"contains","source":4432,"target":4584},{"edgeType":"calls","source":4436,"target":4021},{"edgeType":"calls","source":6841,"target":303},{"edgeType":"contains","source":5756,"target":5821},{"edgeType":"calls","source":5890,"target":171},{"edgeType":"contains","source":4139,"target":4154},{"edgeType":"calls","source":2859,"target":1111},{"edgeType":"contains","source":4139,"target":4161},{"edgeType":"calls","source":5513,"target":1287},{"edgeType":"calls","source":5735,"target":1804},{"edgeType":"calls","source":3024,"target":224},{"edgeType":"contains","source":6280,"target":6498},{"edgeType":"contains","source":440,"target":441},{"edgeType":"contains","source":602,"target":704},{"edgeType":"contains","source":6432,"target":7071},{"edgeType":"contains","source":6450,"target":6514},{"edgeType":"contains","source":6432,"target":7072},{"edgeType":"calls","source":1780,"target":1791},{"edgeType":"contains","source":5758,"target":5768},{"edgeType":"contains","source":5756,"target":5830},{"edgeType":"calls","source":426,"target":427},{"edgeType":"imports","source":3166,"target":575},{"edgeType":"calls","source":4588,"target":4593},{"edgeType":"calls","source":6871,"target":431},{"edgeType":"contains","source":5380,"target":2686},{"edgeType":"calls","source":525,"target":529},{"edgeType":"calls","source":5890,"target":170},{"edgeType":"calls","source":6841,"target":304},{"edgeType":"calls","source":6093,"target":2333},{"edgeType":"contains","source":3,"target":1302},{"edgeType":"contains","source":4139,"target":4160},{"edgeType":"contains","source":2494,"target":3362},{"edgeType":"contains","source":901,"target":947},{"edgeType":"calls","source":5513,"target":1286},{"edgeType":"contains","source":602,"target":703},{"edgeType":"contains","source":5758,"target":5769},{"edgeType":"contains","source":5756,"target":5831},{"edgeType":"contains","source":439,"target":470},{"edgeType":"calls","source":4423,"target":4422},{"edgeType":"calls","source":4589,"target":4561},{"edgeType":"calls","source":4090,"target":4175},{"edgeType":"calls","source":1354,"target":1258},{"edgeType":"contains","source":4767,"target":4775},{"edgeType":"calls","source":5652,"target":147},{"edgeType":"calls","source":4763,"target":4451},{"edgeType":"contains","source":4139,"target":4159},{"edgeType":"calls","source":5131,"target":442},{"edgeType":"calls","source":5513,"target":1285},{"edgeType":"contains","source":6518,"target":6522},{"edgeType":"imports","source":2581,"target":1796},{"edgeType":"contains","source":336,"target":496},{"edgeType":"calls","source":5237,"target":4556},{"edgeType":"contains","source":336,"target":495},{"edgeType":"calls","source":4597,"target":84},{"edgeType":"contains","source":901,"target":950},{"edgeType":"contains","source":5758,"target":5770},{"edgeType":"contains","source":5756,"target":5832},{"edgeType":"calls","source":6807,"target":303},{"edgeType":"calls","source":4185,"target":170},{"edgeType":"calls","source":4112,"target":319},{"edgeType":"calls","source":7037,"target":572},{"edgeType":"contains","source":1732,"target":555},{"edgeType":"calls","source":6902,"target":1586},{"edgeType":"calls","source":6321,"target":548},{"edgeType":"contains","source":4139,"target":4158},{"edgeType":"contains","source":2750,"target":2823},{"edgeType":"calls","source":5652,"target":146},{"edgeType":"calls","source":1516,"target":1520},{"edgeType":"calls","source":5513,"target":1284},{"edgeType":"contains","source":6518,"target":6523},{"edgeType":"contains","source":3030,"target":485},{"edgeType":"contains","source":602,"target":705},{"edgeType":"contains","source":6280,"target":6501},{"edgeType":"calls","source":5237,"target":4554},{"edgeType":"calls","source":5370,"target":431},{"edgeType":"calls","source":5237,"target":4555},{"edgeType":"calls","source":1801,"target":84},{"edgeType":"contains","source":336,"target":494},{"edgeType":"contains","source":901,"target":949},{"edgeType":"contains","source":5593,"target":5601},{"edgeType":"contains","source":5758,"target":5771},{"edgeType":"contains","source":5756,"target":5833},{"edgeType":"calls","source":6807,"target":304},{"edgeType":"contains","source":4003,"target":4146},{"edgeType":"calls","source":4185,"target":171},{"edgeType":"calls","source":7037,"target":573},{"edgeType":"calls","source":6464,"target":342},{"edgeType":"contains","source":5362,"target":5363},{"edgeType":"calls","source":2174,"target":144},{"edgeType":"extends","source":1977,"target":1732},{"edgeType":"contains","source":6280,"target":6494},{"edgeType":"calls","source":7105,"target":5865},{"edgeType":"calls","source":4999,"target":304},{"edgeType":"imports","source":4000,"target":78},{"edgeType":"contains","source":4432,"target":4596},{"edgeType":"calls","source":1587,"target":371},{"edgeType":"calls","source":5237,"target":4553},{"edgeType":"contains","source":336,"target":498},{"edgeType":"contains","source":6616,"target":6649},{"edgeType":"calls","source":1213,"target":337},{"edgeType":"imports","source":4000,"target":79},{"edgeType":"imports","source":4717,"target":49},{"edgeType":"contains","source":1302,"target":4378},{"edgeType":"calls","source":6405,"target":56},{"edgeType":"contains","source":5593,"target":5594},{"edgeType":"calls","source":4299,"target":4035},{"edgeType":"contains","source":5758,"target":5764},{"edgeType":"contains","source":5756,"target":5826},{"edgeType":"extends","source":5612,"target":36},{"edgeType":"calls","source":5065,"target":371},{"edgeType":"contains","source":1229,"target":1356},{"edgeType":"calls","source":4317,"target":304},{"edgeType":"calls","source":4999,"target":303},{"edgeType":"contains","source":4767,"target":4780},{"edgeType":"calls","source":3034,"target":3082},{"edgeType":"contains","source":336,"target":497},{"edgeType":"calls","source":5237,"target":4552},{"edgeType":"calls","source":1587,"target":370},{"edgeType":"contains","source":440,"target":444},{"edgeType":"calls","source":6868,"target":1586},{"edgeType":"calls","source":3231,"target":146},{"edgeType":"contains","source":5895,"target":6803},{"edgeType":"calls","source":4112,"target":318},{"edgeType":"contains","source":5758,"target":5765},{"edgeType":"contains","source":5756,"target":5827},{"edgeType":"calls","source":6602,"target":6661},{"edgeType":"calls","source":469,"target":146},{"edgeType":"calls","source":471,"target":84},{"edgeType":"extends","source":2129,"target":189},{"edgeType":"calls","source":4317,"target":303},{"edgeType":"contains","source":1907,"target":2533},{"edgeType":"calls","source":5065,"target":370},{"edgeType":"calls","source":3878,"target":170},{"edgeType":"contains","source":4139,"target":4163},{"edgeType":"contains","source":437,"target":540},{"edgeType":"calls","source":5237,"target":4551},{"edgeType":"contains","source":6584,"target":6586},{"edgeType":"contains","source":5,"target":4418},{"edgeType":"contains","source":6432,"target":7069},{"edgeType":"contains","source":901,"target":954},{"edgeType":"contains","source":5758,"target":5766},{"edgeType":"contains","source":5756,"target":5828},{"edgeType":"calls","source":6115,"target":588},{"edgeType":"calls","source":4206,"target":572},{"edgeType":"calls","source":2679,"target":1400},{"edgeType":"calls","source":6781,"target":56},{"edgeType":"calls","source":2506,"target":421},{"edgeType":"contains","source":4767,"target":4778},{"edgeType":"contains","source":4139,"target":4162},{"edgeType":"calls","source":5065,"target":369},{"edgeType":"calls","source":3878,"target":171},{"edgeType":"calls","source":5237,"target":4550},{"edgeType":"contains","source":6683,"target":6689},{"edgeType":"calls","source":1549,"target":1550},{"edgeType":"contains","source":440,"target":446},{"edgeType":"calls","source":1213,"target":339},{"edgeType":"contains","source":6432,"target":7070},{"edgeType":"contains","source":6518,"target":6519},{"edgeType":"calls","source":5673,"target":548},{"edgeType":"contains","source":336,"target":499},{"edgeType":"contains","source":901,"target":953},{"edgeType":"calls","source":4704,"target":2047},{"edgeType":"calls","source":1213,"target":338},{"edgeType":"contains","source":5758,"target":5767},{"edgeType":"contains","source":5756,"target":5829},{"edgeType":"calls","source":3928,"target":3906},{"edgeType":"calls","source":4006,"target":431},{"edgeType":"calls","source":4206,"target":573},{"edgeType":"calls","source":2506,"target":422},{"edgeType":"calls","source":6461,"target":431},{"edgeType":"imports","source":4307,"target":78},{"edgeType":"extends","source":19,"target":35},{"edgeType":"contains","source":602,"target":679},{"edgeType":"contains","source":5388,"target":5585},{"edgeType":"contains","source":4003,"target":4124},{"edgeType":"contains","source":42,"target":2183},{"edgeType":"calls","source":3607,"target":146},{"edgeType":"imports","source":6557,"target":78},{"edgeType":"contains","source":6280,"target":6474},{"edgeType":"contains","source":2223,"target":2224},{"edgeType":"calls","source":3244,"target":2942},{"edgeType":"calls","source":6842,"target":248},{"edgeType":"contains","source":6432,"target":7047},{"edgeType":"contains","source":5460,"target":5468},{"edgeType":"calls","source":6116,"target":588},{"edgeType":"calls","source":2481,"target":170},{"edgeType":"calls","source":6566,"target":6690},{"edgeType":"contains","source":4898,"target":4919},{"edgeType":"contains","source":5388,"target":5584},{"edgeType":"contains","source":602,"target":678},{"edgeType":"imports","source":42,"target":147},{"edgeType":"contains","source":3841,"target":3860},{"edgeType":"contains","source":5,"target":158},{"edgeType":"imports","source":4307,"target":2177},{"edgeType":"imports","source":4307,"target":2178},{"edgeType":"calls","source":6972,"target":447},{"edgeType":"calls","source":1196,"target":892},{"edgeType":"contains","source":1031,"target":1120},{"edgeType":"contains","source":4898,"target":4918},{"edgeType":"calls","source":2481,"target":171},{"edgeType":"calls","source":1517,"target":1515},{"edgeType":"contains","source":439,"target":449},{"edgeType":"calls","source":6970,"target":6852},{"edgeType":"contains","source":2586,"target":2596},{"edgeType":"calls","source":7050,"target":6486},{"edgeType":"contains","source":5388,"target":5583},{"edgeType":"contains","source":4568,"target":4577},{"edgeType":"contains","source":602,"target":681},{"edgeType":"extends","source":2133,"target":36},{"edgeType":"calls","source":1748,"target":1753},{"edgeType":"contains","source":200,"target":459},{"edgeType":"contains","source":4304,"target":4305},{"edgeType":"calls","source":1778,"target":1880},{"edgeType":"calls","source":1087,"target":1103},{"edgeType":"contains","source":5460,"target":5470},{"edgeType":"calls","source":6972,"target":448},{"edgeType":"calls","source":2871,"target":2876},{"edgeType":"contains","source":3047,"target":3103},{"edgeType":"contains","source":1265,"target":1266},{"edgeType":"calls","source":468,"target":209},{"edgeType":"calls","source":2984,"target":431},{"edgeType":"calls","source":6907,"target":6692},{"edgeType":"contains","source":602,"target":680},{"edgeType":"calls","source":7007,"target":421},{"edgeType":"contains","source":3841,"target":3858},{"edgeType":"imports","source":6557,"target":79},{"edgeType":"extends","source":5884,"target":36},{"edgeType":"calls","source":5409,"target":304},{"edgeType":"calls","source":4453,"target":4572},{"edgeType":"contains","source":1265,"target":1267},{"edgeType":"calls","source":4764,"target":4444},{"edgeType":"calls","source":4752,"target":588},{"edgeType":"calls","source":3023,"target":3447},{"edgeType":"calls","source":7007,"target":422},{"edgeType":"contains","source":1302,"target":5410},{"edgeType":"calls","source":1292,"target":1084},{"edgeType":"contains","source":4898,"target":4923},{"edgeType":"contains","source":42,"target":2188},{"edgeType":"contains","source":6432,"target":7043},{"edgeType":"contains","source":5756,"target":516},{"edgeType":"calls","source":5409,"target":303},{"edgeType":"contains","source":602,"target":683},{"edgeType":"calls","source":5041,"target":84},{"edgeType":"calls","source":1162,"target":886},{"edgeType":"calls","source":4600,"target":4242},{"edgeType":"calls","source":4232,"target":4021},{"edgeType":"contains","source":5388,"target":5588},{"edgeType":"contains","source":4003,"target":4127},{"edgeType":"calls","source":597,"target":431},{"edgeType":"contains","source":6432,"target":7044},{"edgeType":"calls","source":6774,"target":4475},{"edgeType":"imports","source":3030,"target":533},{"edgeType":"calls","source":4568,"target":4176},{"edgeType":"contains","source":602,"target":682},{"edgeType":"contains","source":5460,"target":5465},{"edgeType":"calls","source":1248,"target":333},{"edgeType":"calls","source":2871,"target":2875},{"edgeType":"calls","source":2803,"target":1812},{"edgeType":"contains","source":5196,"target":5197},{"edgeType":"contains","source":5388,"target":5587},{"edgeType":"calls","source":1805,"target":1039},{"edgeType":"calls","source":6973,"target":421},{"edgeType":"calls","source":1196,"target":891},{"edgeType":"calls","source":1412,"target":537},{"edgeType":"contains","source":1302,"target":2237},{"edgeType":"contains","source":5460,"target":5466},{"edgeType":"contains","source":602,"target":685},{"edgeType":"contains","source":5388,"target":5586},{"edgeType":"calls","source":6774,"target":4477},{"edgeType":"calls","source":6973,"target":422},{"edgeType":"contains","source":43,"target":44},{"edgeType":"contains","source":6286,"target":6287},{"edgeType":"calls","source":6296,"target":1343},{"edgeType":"contains","source":5,"target":4393},{"edgeType":"contains","source":1302,"target":4352},{"edgeType":"contains","source":5460,"target":5467},{"edgeType":"contains","source":602,"target":684},{"edgeType":"contains","source":5756,"target":5813},{"edgeType":"imports","source":3352,"target":78},{"edgeType":"contains","source":2157,"target":2164},{"edgeType":"imports","source":3981,"target":3818},{"edgeType":"contains","source":4304,"target":4315},{"edgeType":"contains","source":4196,"target":4492},{"edgeType":"contains","source":602,"target":687},{"edgeType":"calls","source":1142,"target":445},{"edgeType":"calls","source":6837,"target":6754},{"edgeType":"contains","source":5756,"target":5814},{"edgeType":"contains","source":5754,"target":5876},{"edgeType":"contains","source":6980,"target":6981},{"edgeType":"calls","source":4415,"target":458},{"edgeType":"calls","source":4035,"target":1669},{"edgeType":"calls","source":6869,"target":6819},{"edgeType":"imports","source":4502,"target":3523},{"edgeType":"calls","source":4925,"target":2618},{"edgeType":"contains","source":1926,"target":1927},{"edgeType":"contains","source":4196,"target":4491},{"edgeType":"contains","source":602,"target":686},{"edgeType":"calls","source":1347,"target":431},{"edgeType":"calls","source":1337,"target":1798},{"edgeType":"calls","source":4919,"target":4918},{"edgeType":"calls","source":1696,"target":1243},{"edgeType":"calls","source":3142,"target":2923},{"edgeType":"contains","source":5756,"target":5815},{"edgeType":"calls","source":5876,"target":2733},{"edgeType":"contains","source":3606,"target":3753},{"edgeType":"calls","source":1880,"target":1881},{"edgeType":"calls","source":4415,"target":457},{"edgeType":"calls","source":2024,"target":588},{"edgeType":"calls","source":6436,"target":171},{"edgeType":"calls","source":4896,"target":4573},{"edgeType":"contains","source":4898,"target":4925},{"edgeType":"contains","source":5,"target":2284},{"edgeType":"contains","source":2255,"target":2295},{"edgeType":"calls","source":1248,"target":332},{"edgeType":"calls","source":2914,"target":2592},{"edgeType":"calls","source":3034,"target":3100},{"edgeType":"contains","source":602,"target":689},{"edgeType":"contains","source":6432,"target":7058},{"edgeType":"contains","source":5756,"target":5816},{"edgeType":"calls","source":2298,"target":548},{"edgeType":"calls","source":6706,"target":4475},{"edgeType":"calls","source":7078,"target":342},{"edgeType":"calls","source":7058,"target":962},{"edgeType":"calls","source":6436,"target":170},{"edgeType":"calls","source":2705,"target":2730},{"edgeType":"calls","source":6409,"target":5226},{"edgeType":"calls","source":3710,"target":1171},{"edgeType":"contains","source":4304,"target":4312},{"edgeType":"calls","source":3034,"target":3101},{"edgeType":"contains","source":602,"target":688},{"edgeType":"calls","source":1154,"target":1126},{"edgeType":"calls","source":1062,"target":807},{"edgeType":"calls","source":4766,"target":144},{"edgeType":"calls","source":7072,"target":1586},{"edgeType":"calls","source":354,"target":557},{"edgeType":"calls","source":7058,"target":963},{"edgeType":"contains","source":602,"target":691},{"edgeType":"contains","source":1926,"target":1930},{"edgeType":"contains","source":4139,"target":4149},{"edgeType":"contains","source":4196,"target":4496},{"edgeType":"calls","source":1062,"target":806},{"edgeType":"calls","source":1087,"target":1088},{"edgeType":"calls","source":6052,"target":445},{"edgeType":"contains","source":3841,"target":3872},{"edgeType":"calls","source":354,"target":556},{"edgeType":"contains","source":5756,"target":5810},{"edgeType":"calls","source":6717,"target":965},{"edgeType":"calls","source":6706,"target":4477},{"edgeType":"contains","source":1926,"target":1931},{"edgeType":"contains","source":602,"target":690},{"edgeType":"contains","source":1860,"target":1863},{"edgeType":"calls","source":2781,"target":372},{"edgeType":"contains","source":5,"target":2285},{"edgeType":"contains","source":4139,"target":4148},{"edgeType":"calls","source":3034,"target":3099},{"edgeType":"contains","source":6319,"target":6327},{"edgeType":"contains","source":5,"target":6516},{"edgeType":"calls","source":6946,"target":209},{"edgeType":"calls","source":6914,"target":144},{"edgeType":"calls","source":1142,"target":443},{"edgeType":"calls","source":4049,"target":171},{"edgeType":"contains","source":3030,"target":472},{"edgeType":"contains","source":4898,"target":4930},{"edgeType":"contains","source":5756,"target":5811},{"edgeType":"calls","source":2373,"target":332},{"edgeType":"calls","source":4518,"target":431},{"edgeType":"calls","source":6602,"target":303},{"edgeType":"contains","source":602,"target":693},{"edgeType":"calls","source":5859,"target":84},{"edgeType":"contains","source":4100,"target":4299},{"edgeType":"contains","source":1926,"target":1928},{"edgeType":"calls","source":947,"target":146},{"edgeType":"contains","source":4139,"target":4147},{"edgeType":"contains","source":139,"target":1304},{"edgeType":"calls","source":6946,"target":210},{"edgeType":"contains","source":5756,"target":5812},{"edgeType":"contains","source":5908,"target":6385},{"edgeType":"calls","source":6052,"target":443},{"edgeType":"calls","source":2779,"target":431},{"edgeType":"calls","source":6602,"target":304},{"edgeType":"calls","source":2373,"target":333},{"edgeType":"calls","source":354,"target":558},{"edgeType":"contains","source":602,"target":692},{"edgeType":"calls","source":3743,"target":144},{"edgeType":"contains","source":1926,"target":1929},{"edgeType":"calls","source":3034,"target":3097},{"edgeType":"contains","source":4196,"target":4493},{"edgeType":"contains","source":439,"target":460},{"edgeType":"calls","source":1337,"target":1796},{"edgeType":"contains","source":901,"target":907},{"edgeType":"calls","source":4185,"target":148},{"edgeType":"calls","source":4180,"target":303},{"edgeType":"calls","source":3142,"target":2884},{"edgeType":"contains","source":5618,"target":553},{"edgeType":"calls","source":6601,"target":303},{"edgeType":"contains","source":3246,"target":3262},{"edgeType":"contains","source":5380,"target":1588},{"edgeType":"contains","source":5285,"target":5590},{"edgeType":"calls","source":4346,"target":443},{"edgeType":"contains","source":602,"target":662},{"edgeType":"contains","source":6549,"target":6574},{"edgeType":"contains","source":5895,"target":3594},{"edgeType":"contains","source":4397,"target":4578},{"edgeType":"calls","source":5513,"target":4433},{"edgeType":"extends","source":996,"target":451},{"edgeType":"contains","source":2176,"target":3665},{"edgeType":"calls","source":2071,"target":144},{"edgeType":"calls","source":5440,"target":353},{"edgeType":"calls","source":6258,"target":364},{"edgeType":"contains","source":6432,"target":7031},{"edgeType":"calls","source":4180,"target":304},{"edgeType":"calls","source":4241,"target":527},{"edgeType":"calls","source":4617,"target":1554},{"edgeType":"contains","source":1297,"target":1317},{"edgeType":"contains","source":1379,"target":889},{"edgeType":"calls","source":2782,"target":303},{"edgeType":"contains","source":3048,"target":3059},{"edgeType":"calls","source":6601,"target":304},{"edgeType":"contains","source":3246,"target":3263},{"edgeType":"contains","source":3245,"target":3294},{"edgeType":"contains","source":602,"target":661},{"edgeType":"calls","source":7138,"target":570},{"edgeType":"contains","source":6549,"target":6575},{"edgeType":"calls","source":7111,"target":350},{"edgeType":"contains","source":3775,"target":3776},{"edgeType":"contains","source":5895,"target":3595},{"edgeType":"calls","source":1218,"target":1221},{"edgeType":"contains","source":3543,"target":3567},{"edgeType":"extends","source":5604,"target":5593},{"edgeType":"calls","source":3497,"target":333},{"edgeType":"calls","source":5310,"target":3325},{"edgeType":"calls","source":1073,"target":431},{"edgeType":"contains","source":6432,"target":7032},{"edgeType":"contains","source":1379,"target":3000},{"edgeType":"contains","source":901,"target":909},{"edgeType":"calls","source":2602,"target":1652},{"edgeType":"calls","source":749,"target":961},{"edgeType":"contains","source":3246,"target":3260},{"edgeType":"contains","source":5166,"target":6106},{"edgeType":"contains","source":6610,"target":6799},{"edgeType":"calls","source":3001,"target":3025},{"edgeType":"contains","source":1793,"target":1794},{"edgeType":"calls","source":7069,"target":596},{"edgeType":"contains","source":602,"target":664},{"edgeType":"calls","source":5235,"target":4593},{"edgeType":"calls","source":5227,"target":4841},{"edgeType":"extends","source":4351,"target":36},{"edgeType":"contains","source":3808,"target":3809},{"edgeType":"contains","source":4397,"target":4576},{"edgeType":"contains","source":154,"target":1868},{"edgeType":"contains","source":901,"target":908},{"edgeType":"contains","source":5618,"target":556},{"edgeType":"contains","source":3246,"target":3261},{"edgeType":"calls","source":2787,"target":146},{"edgeType":"contains","source":602,"target":663},{"edgeType":"contains","source":3874,"target":3876},{"edgeType":"contains","source":4797,"target":4859},{"edgeType":"contains","source":3841,"target":3842},{"edgeType":"contains","source":4397,"target":4575},{"edgeType":"contains","source":2176,"target":3663},{"edgeType":"contains","source":5723,"target":5750},{"edgeType":"calls","source":6087,"target":5662},{"edgeType":"calls","source":741,"target":146},{"edgeType":"calls","source":3434,"target":170},{"edgeType":"contains","source":602,"target":667},{"edgeType":"calls","source":1143,"target":369},{"edgeType":"contains","source":3048,"target":3062},{"edgeType":"calls","source":6504,"target":2257},{"edgeType":"calls","source":1084,"target":84},{"edgeType":"calls","source":1087,"target":1048},{"edgeType":"calls","source":4832,"target":171},{"edgeType":"calls","source":6474,"target":1073},{"edgeType":"calls","source":3119,"target":422},{"edgeType":"contains","source":6074,"target":6497},{"edgeType":"calls","source":3876,"target":209},{"edgeType":"extends","source":6165,"target":6166},{"edgeType":"calls","source":3696,"target":2618},{"edgeType":"contains","source":3246,"target":3266},{"edgeType":"contains","source":5388,"target":5572},{"edgeType":"contains","source":41,"target":2201},{"edgeType":"extends","source":4517,"target":180},{"edgeType":"calls","source":3497,"target":332},{"edgeType":"calls","source":3231,"target":3293},{"edgeType":"calls","source":3434,"target":171},{"edgeType":"calls","source":6884,"target":1048},{"edgeType":"contains","source":5723,"target":5751},{"edgeType":"contains","source":2981,"target":3026},{"edgeType":"contains","source":602,"target":666},{"edgeType":"calls","source":3215,"target":2732},{"edgeType":"calls","source":6504,"target":2258},{"edgeType":"contains","source":2552,"target":2584},{"edgeType":"contains","source":3048,"target":3063},{"edgeType":"calls","source":4832,"target":170},{"edgeType":"calls","source":1143,"target":368},{"edgeType":"calls","source":6504,"target":144},{"edgeType":"contains","source":5380,"target":534},{"edgeType":"contains","source":602,"target":665},{"edgeType":"contains","source":5388,"target":5571},{"edgeType":"contains","source":4003,"target":4111},{"edgeType":"calls","source":3876,"target":210},{"edgeType":"calls","source":5876,"target":5859},{"edgeType":"contains","source":9,"target":25},{"edgeType":"contains","source":2176,"target":3666},{"edgeType":"contains","source":4196,"target":4469},{"edgeType":"contains","source":5756,"target":501},{"edgeType":"calls","source":3468,"target":171},{"edgeType":"contains","source":5723,"target":5752},{"edgeType":"calls","source":1143,"target":371},{"edgeType":"contains","source":3048,"target":3060},{"edgeType":"contains","source":602,"target":669},{"edgeType":"calls","source":6533,"target":303},{"edgeType":"contains","source":4797,"target":4865},{"edgeType":"calls","source":6932,"target":6961},{"edgeType":"imports","source":6074,"target":308},{"edgeType":"contains","source":3246,"target":3264},{"edgeType":"imports","source":182,"target":78},{"edgeType":"calls","source":2198,"target":431},{"edgeType":"contains","source":4003,"target":4110},{"edgeType":"calls","source":1823,"target":431},{"edgeType":"calls","source":6243,"target":6108},{"edgeType":"contains","source":6432,"target":7029},{"edgeType":"contains","source":5723,"target":5753},{"edgeType":"contains","source":3048,"target":3061},{"edgeType":"calls","source":6541,"target":56},{"edgeType":"calls","source":6533,"target":304},{"edgeType":"contains","source":6814,"target":6815},{"edgeType":"contains","source":602,"target":668},{"edgeType":"calls","source":1143,"target":370},{"edgeType":"contains","source":5285,"target":5591},{"edgeType":"calls","source":3119,"target":421},{"edgeType":"contains","source":3246,"target":3265},{"edgeType":"contains","source":5380,"target":1589},{"edgeType":"imports","source":182,"target":79},{"edgeType":"contains","source":3841,"target":3846},{"edgeType":"contains","source":1303,"target":2195},{"edgeType":"contains","source":41,"target":2206},{"edgeType":"contains","source":602,"target":671},{"edgeType":"calls","source":4954,"target":4841},{"edgeType":"calls","source":1143,"target":364},{"edgeType":"calls","source":3971,"target":431},{"edgeType":"contains","source":5754,"target":5859},{"edgeType":"contains","source":5884,"target":6057},{"edgeType":"contains","source":3048,"target":3066},{"edgeType":"calls","source":3762,"target":568},{"edgeType":"calls","source":2606,"target":2579},{"edgeType":"contains","source":5463,"target":1137},{"edgeType":"calls","source":4184,"target":170},{"edgeType":"calls","source":6959,"target":5069},{"edgeType":"imports","source":4717,"target":78},{"edgeType":"calls","source":2076,"target":2097},{"edgeType":"contains","source":4797,"target":4870},{"edgeType":"calls","source":3468,"target":170},{"edgeType":"calls","source":5163,"target":475},{"edgeType":"contains","source":602,"target":670},{"edgeType":"contains","source":4665,"target":4734},{"edgeType":"contains","source":3841,"target":3852},{"edgeType":"contains","source":3166,"target":3637},{"edgeType":"contains","source":3048,"target":3067},{"edgeType":"contains","source":5884,"target":6058},{"edgeType":"contains","source":5285,"target":5597},{"edgeType":"calls","source":529,"target":371},{"edgeType":"contains","source":5360,"target":5386},{"edgeType":"contains","source":5388,"target":5575},{"edgeType":"calls","source":4184,"target":171},{"edgeType":"calls","source":4312,"target":431},{"edgeType":"imports","source":4717,"target":79},{"edgeType":"contains","source":5460,"target":5461},{"edgeType":"calls","source":6959,"target":5070},{"edgeType":"contains","source":4797,"target":4869},{"edgeType":"contains","source":1303,"target":2193},{"edgeType":"contains","source":2586,"target":2588},{"edgeType":"calls","source":5163,"target":474},{"edgeType":"calls","source":5520,"target":2092},{"edgeType":"contains","source":602,"target":673},{"edgeType":"calls","source":5369,"target":431},{"edgeType":"contains","source":6432,"target":7041},{"edgeType":"contains","source":3808,"target":3817},{"edgeType":"contains","source":3048,"target":3064},{"edgeType":"contains","source":1028,"target":1208},{"edgeType":"contains","source":3246,"target":3268},{"edgeType":"calls","source":6734,"target":2533},{"edgeType":"contains","source":5388,"target":5574},{"edgeType":"contains","source":5756,"target":514},{"edgeType":"calls","source":6959,"target":5071},{"edgeType":"calls","source":2043,"target":1006},{"edgeType":"calls","source":5520,"target":2091},{"edgeType":"calls","source":5163,"target":473},{"edgeType":"imports","source":5410,"target":1853},{"edgeType":"calls","source":1143,"target":366},{"edgeType":"extends","source":748,"target":750},{"edgeType":"contains","source":602,"target":672},{"edgeType":"contains","source":1028,"target":1207},{"edgeType":"contains","source":3048,"target":3065},{"edgeType":"calls","source":4620,"target":4622},{"edgeType":"contains","source":5756,"target":515},{"edgeType":"calls","source":1938,"target":2146},{"edgeType":"calls","source":6907,"target":342},{"edgeType":"calls","source":6959,"target":5072},{"edgeType":"contains","source":602,"target":675},{"edgeType":"contains","source":5360,"target":5392},{"edgeType":"contains","source":5618,"target":557},{"edgeType":"calls","source":2076,"target":2092},{"edgeType":"calls","source":5569,"target":571},{"edgeType":"calls","source":3489,"target":571},{"edgeType":"calls","source":2610,"target":1394},{"edgeType":"calls","source":1243,"target":431},{"edgeType":"contains","source":3048,"target":3070},{"edgeType":"contains","source":4898,"target":4915},{"edgeType":"calls","source":6959,"target":5073},{"edgeType":"calls","source":529,"target":368},{"edgeType":"contains","source":5360,"target":5391},{"edgeType":"contains","source":602,"target":674},{"edgeType":"imports","source":4391,"target":3847},{"edgeType":"calls","source":6552,"target":2892},{"edgeType":"contains","source":1988,"target":5277},{"edgeType":"extends","source":748,"target":752},{"edgeType":"contains","source":2176,"target":3677},{"edgeType":"contains","source":4403,"target":4404},{"edgeType":"calls","source":5379,"target":5403},{"edgeType":"contains","source":6616,"target":6617},{"edgeType":"calls","source":4005,"target":431},{"edgeType":"contains","source":3048,"target":3071},{"edgeType":"contains","source":3808,"target":3822},{"edgeType":"contains","source":3543,"target":3581},{"edgeType":"calls","source":6258,"target":3522},{"edgeType":"calls","source":6959,"target":5074},{"edgeType":"calls","source":7075,"target":421},{"edgeType":"calls","source":6672,"target":6572},{"edgeType":"contains","source":3241,"target":3430},{"edgeType":"contains","source":1303,"target":2197},{"edgeType":"extends","source":5730,"target":1691},{"edgeType":"contains","source":602,"target":677},{"edgeType":"contains","source":6280,"target":6463},{"edgeType":"contains","source":4003,"target":4118},{"edgeType":"calls","source":886,"target":930},{"edgeType":"calls","source":3766,"target":3609},{"edgeType":"contains","source":2552,"target":2589},{"edgeType":"calls","source":2610,"target":1392},{"edgeType":"contains","source":3048,"target":3068},{"edgeType":"calls","source":4017,"target":1113},{"edgeType":"calls","source":6801,"target":6802},{"edgeType":"calls","source":7002,"target":571},{"edgeType":"calls","source":7075,"target":422},{"edgeType":"calls","source":6435,"target":148},{"edgeType":"calls","source":529,"target":370},{"edgeType":"calls","source":6586,"target":2897},{"edgeType":"calls","source":2308,"target":2298},{"edgeType":"contains","source":602,"target":676},{"edgeType":"contains","source":5,"target":156},{"edgeType":"calls","source":4917,"target":4924},{"edgeType":"calls","source":2076,"target":2091},{"edgeType":"calls","source":5379,"target":5401},{"edgeType":"contains","source":2552,"target":2590},{"edgeType":"calls","source":2610,"target":1393},{"edgeType":"contains","source":3048,"target":3069},{"edgeType":"calls","source":4770,"target":2082},{"edgeType":"calls","source":1766,"target":1132},{"edgeType":"imports","source":4668,"target":547},{"edgeType":"calls","source":6085,"target":5712},{"edgeType":"calls","source":6401,"target":144},{"edgeType":"calls","source":7084,"target":144},{"edgeType":"contains","source":3246,"target":3273},{"edgeType":"contains","source":3166,"target":3639},{"edgeType":"calls","source":4763,"target":4413},{"edgeType":"calls","source":529,"target":369},{"edgeType":"calls","source":6561,"target":469},{"edgeType":"calls","source":3710,"target":1148},{"edgeType":"contains","source":3245,"target":3277},{"edgeType":"contains","source":2552,"target":2562},{"edgeType":"contains","source":602,"target":646},{"edgeType":"imports","source":599,"target":882},{"edgeType":"calls","source":5065,"target":368},{"edgeType":"contains","source":2581,"target":3777},{"edgeType":"contains","source":520,"target":6359},{"edgeType":"contains","source":6213,"target":6403},{"edgeType":"contains","source":1989,"target":2045},{"edgeType":"contains","source":2255,"target":2256},{"edgeType":"calls","source":4704,"target":2046},{"edgeType":"calls","source":4112,"target":313},{"edgeType":"calls","source":4040,"target":431},{"edgeType":"calls","source":1962,"target":369},{"edgeType":"contains","source":6450,"target":6456},{"edgeType":"calls","source":4933,"target":1289},{"edgeType":"calls","source":6436,"target":148},{"edgeType":"contains","source":3245,"target":3276},{"edgeType":"contains","source":5029,"target":5053},{"edgeType":"contains","source":5166,"target":6091},{"edgeType":"contains","source":3246,"target":3247},{"edgeType":"contains","source":3245,"target":3278},{"edgeType":"contains","source":602,"target":645},{"edgeType":"calls","source":1587,"target":366},{"edgeType":"contains","source":5285,"target":5573},{"edgeType":"calls","source":1589,"target":304},{"edgeType":"imports","source":4668,"target":533},{"edgeType":"contains","source":4664,"target":4740},{"edgeType":"contains","source":2581,"target":3778},{"edgeType":"contains","source":4474,"target":5345},{"edgeType":"calls","source":3420,"target":2740},{"edgeType":"contains","source":5029,"target":5052},{"edgeType":"contains","source":2222,"target":2223},{"edgeType":"calls","source":1962,"target":368},{"edgeType":"calls","source":6110,"target":1797},{"edgeType":"calls","source":1248,"target":304},{"edgeType":"imports","source":3166,"target":1639},{"edgeType":"calls","source":6402,"target":144},{"edgeType":"contains","source":1028,"target":1180},{"edgeType":"calls","source":4933,"target":1288},{"edgeType":"contains","source":1302,"target":2203},{"edgeType":"calls","source":4764,"target":4413},{"edgeType":"imports","source":3166,"target":582},{"edgeType":"calls","source":2366,"target":528},{"edgeType":"contains","source":5360,"target":5361},{"edgeType":"calls","source":4452,"target":342},{"edgeType":"contains","source":2552,"target":2560},{"edgeType":"contains","source":602,"target":648},{"edgeType":"contains","source":4698,"target":4742},{"edgeType":"calls","source":5248,"target":2092},{"edgeType":"contains","source":4474,"target":5344},{"edgeType":"contains","source":2206,"target":601},{"edgeType":"contains","source":200,"target":426},{"edgeType":"calls","source":3710,"target":1146},{"edgeType":"calls","source":1587,"target":369},{"edgeType":"contains","source":5029,"target":5051},{"edgeType":"calls","source":1962,"target":371},{"edgeType":"calls","source":1955,"target":588},{"edgeType":"calls","source":1244,"target":431},{"edgeType":"calls","source":6801,"target":431},{"edgeType":"calls","source":4112,"target":311},{"edgeType":"contains","source":6213,"target":6406},{"edgeType":"calls","source":4933,"target":1287},{"edgeType":"calls","source":5065,"target":366},{"edgeType":"calls","source":6779,"target":56},{"edgeType":"calls","source":6633,"target":354},{"edgeType":"contains","source":4698,"target":4741},{"edgeType":"calls","source":1587,"target":368},{"edgeType":"contains","source":3366,"target":582},{"edgeType":"contains","source":5393,"target":5394},{"edgeType":"imports","source":4668,"target":535},{"edgeType":"contains","source":602,"target":647},{"edgeType":"calls","source":7120,"target":56},{"edgeType":"calls","source":5248,"target":2091},{"edgeType":"calls","source":4347,"target":425},{"edgeType":"contains","source":4474,"target":5343},{"edgeType":"calls","source":1322,"target":1184},{"edgeType":"imports","source":2581,"target":1803},{"edgeType":"contains","source":5884,"target":6035},{"edgeType":"calls","source":3710,"target":1147},{"edgeType":"calls","source":1962,"target":370},{"edgeType":"calls","source":4112,"target":312},{"edgeType":"contains","source":5029,"target":5050},{"edgeType":"contains","source":4921,"target":5227},{"edgeType":"contains","source":6213,"target":6407},{"edgeType":"contains","source":3110,"target":3232},{"edgeType":"imports","source":4717,"target":4301},{"edgeType":"contains","source":1297,"target":1299},{"edgeType":"calls","source":4933,"target":1286},{"edgeType":"contains","source":3245,"target":3275},{"edgeType":"contains","source":3245,"target":3281},{"edgeType":"contains","source":3246,"target":3250},{"edgeType":"contains","source":2552,"target":2566},{"edgeType":"contains","source":2599,"target":1109},{"edgeType":"calls","source":2373,"target":309},{"edgeType":"calls","source":4347,"target":424},{"edgeType":"extends","source":5593,"target":1691},{"edgeType":"imports","source":2581,"target":1802},{"edgeType":"calls","source":2081,"target":1962},{"edgeType":"calls","source":3946,"target":170},{"edgeType":"calls","source":6715,"target":3099},{"edgeType":"contains","source":108,"target":109},{"edgeType":"extends","source":1691,"target":36},{"edgeType":"calls","source":6436,"target":144},{"edgeType":"calls","source":468,"target":170},{"edgeType":"contains","source":602,"target":650},{"edgeType":"calls","source":5065,"target":364},{"edgeType":"calls","source":2602,"target":1667},{"edgeType":"calls","source":4933,"target":1285},{"edgeType":"calls","source":1068,"target":596},{"edgeType":"imports","source":4668,"target":537},{"edgeType":"contains","source":6082,"target":6233},{"edgeType":"contains","source":3110,"target":3239},{"edgeType":"contains","source":5195,"target":5196},{"edgeType":"calls","source":6906,"target":6692},{"edgeType":"contains","source":3246,"target":3251},{"edgeType":"contains","source":3245,"target":3282},{"edgeType":"calls","source":5282,"target":2092},{"edgeType":"contains","source":602,"target":649},{"edgeType":"calls","source":2366,"target":527},{"edgeType":"contains","source":4139,"target":935},{"edgeType":"calls","source":7006,"target":421},{"edgeType":"contains","source":3674,"target":3723},{"edgeType":"contains","source":4137,"target":4168},{"edgeType":"contains","source":200,"target":427},{"edgeType":"calls","source":1962,"target":364},{"edgeType":"calls","source":3946,"target":171},{"edgeType":"calls","source":5888,"target":4447},{"edgeType":"calls","source":1354,"target":1242},{"edgeType":"calls","source":6715,"target":3100},{"edgeType":"calls","source":2608,"target":2539},{"edgeType":"calls","source":5445,"target":210},{"edgeType":"contains","source":585,"target":3290},{"edgeType":"calls","source":5400,"target":548},{"edgeType":"contains","source":4698,"target":4747},{"edgeType":"calls","source":2870,"target":2873},{"edgeType":"calls","source":4933,"target":1284},{"edgeType":"contains","source":5261,"target":5263},{"edgeType":"contains","source":3245,"target":3279},{"edgeType":"contains","source":3246,"target":3248},{"edgeType":"calls","source":5282,"target":2091},{"edgeType":"calls","source":1589,"target":303},{"edgeType":"contains","source":5360,"target":5365},{"edgeType":"calls","source":7006,"target":422},{"edgeType":"contains","source":3674,"target":3722},{"edgeType":"contains","source":4137,"target":4167},{"edgeType":"contains","source":4139,"target":934},{"edgeType":"calls","source":4086,"target":56},{"edgeType":"calls","source":4112,"target":307},{"edgeType":"calls","source":6569,"target":6570},{"edgeType":"calls","source":1248,"target":303},{"edgeType":"calls","source":1243,"target":458},{"edgeType":"contains","source":1303,"target":2173},{"edgeType":"calls","source":5445,"target":209},{"edgeType":"contains","source":602,"target":652},{"edgeType":"contains","source":4698,"target":4746},{"edgeType":"calls","source":4690,"target":4588},{"edgeType":"contains","source":1028,"target":1187},{"edgeType":"contains","source":3246,"target":3249},{"edgeType":"contains","source":3245,"target":3280},{"edgeType":"contains","source":5261,"target":5262},{"edgeType":"calls","source":7047,"target":209},{"edgeType":"calls","source":1587,"target":364},{"edgeType":"contains","source":4698,"target":4745},{"edgeType":"contains","source":5393,"target":5398},{"edgeType":"imports","source":5410,"target":5020},{"edgeType":"contains","source":5884,"target":6031},{"edgeType":"calls","source":1962,"target":366},{"edgeType":"contains","source":3,"target":3365},{"edgeType":"calls","source":537,"target":146},{"edgeType":"calls","source":1243,"target":457},{"edgeType":"contains","source":6432,"target":7013},{"edgeType":"contains","source":3674,"target":3721},{"edgeType":"calls","source":3494,"target":2553},{"edgeType":"contains","source":602,"target":651},{"edgeType":"calls","source":468,"target":171},{"edgeType":"calls","source":5451,"target":2136},{"edgeType":"calls","source":2998,"target":3131},{"edgeType":"calls","source":7044,"target":303},{"edgeType":"calls","source":7047,"target":210},{"edgeType":"calls","source":468,"target":165},{"edgeType":"calls","source":2616,"target":171},{"edgeType":"contains","source":200,"target":432},{"edgeType":"contains","source":3246,"target":3254},{"edgeType":"calls","source":5876,"target":588},{"edgeType":"contains","source":5285,"target":5582},{"edgeType":"calls","source":6807,"target":6593},{"edgeType":"calls","source":6129,"target":144},{"edgeType":"contains","source":5,"target":135},{"edgeType":"contains","source":9,"target":11},{"edgeType":"calls","source":6435,"target":171},{"edgeType":"extends","source":6499,"target":36},{"edgeType":"contains","source":3,"target":2311},{"edgeType":"contains","source":2552,"target":2570},{"edgeType":"imports","source":3013,"target":49},{"edgeType":"calls","source":1008,"target":338},{"edgeType":"contains","source":602,"target":654},{"edgeType":"contains","source":6450,"target":6464},{"edgeType":"calls","source":3105,"target":2982},{"edgeType":"calls","source":1218,"target":170},{"edgeType":"calls","source":1244,"target":421},{"edgeType":"imports","source":3166,"target":1648},{"edgeType":"calls","source":7044,"target":304},{"edgeType":"calls","source":468,"target":164},{"edgeType":"extends","source":1238,"target":340},{"edgeType":"calls","source":4752,"target":548},{"edgeType":"contains","source":3246,"target":3255},{"edgeType":"contains","source":3245,"target":3286},{"edgeType":"calls","source":4453,"target":304},{"edgeType":"calls","source":4483,"target":431},{"edgeType":"imports","source":2898,"target":442},{"edgeType":"calls","source":6435,"target":170},{"edgeType":"contains","source":9,"target":10},{"edgeType":"calls","source":4724,"target":4588},{"edgeType":"calls","source":6640,"target":144},{"edgeType":"contains","source":602,"target":653},{"edgeType":"calls","source":1008,"target":337},{"edgeType":"calls","source":5093,"target":548},{"edgeType":"contains","source":967,"target":969},{"edgeType":"contains","source":3110,"target":3240},{"edgeType":"contains","source":5748,"target":6030},{"edgeType":"calls","source":2537,"target":2618},{"edgeType":"contains","source":3245,"target":3283},{"edgeType":"contains","source":3246,"target":3252},{"edgeType":"calls","source":6258,"target":371},{"edgeType":"calls","source":2373,"target":303},{"edgeType":"calls","source":4453,"target":303},{"edgeType":"calls","source":1822,"target":1532},{"edgeType":"calls","source":2265,"target":480},{"edgeType":"calls","source":6937,"target":6793},{"edgeType":"calls","source":2899,"target":910},{"edgeType":"calls","source":6728,"target":588},{"edgeType":"calls","source":3699,"target":421},{"edgeType":"calls","source":4853,"target":588},{"edgeType":"contains","source":3,"target":199},{"edgeType":"contains","source":3,"target":3370},{"edgeType":"calls","source":1262,"target":922},{"edgeType":"calls","source":3358,"target":422},{"edgeType":"contains","source":602,"target":656},{"edgeType":"contains","source":5166,"target":6097},{"edgeType":"calls","source":6051,"target":445},{"edgeType":"calls","source":2616,"target":170},{"edgeType":"contains","source":200,"target":433},{"edgeType":"contains","source":3246,"target":3253},{"edgeType":"contains","source":5884,"target":6043},{"edgeType":"calls","source":6258,"target":370},{"edgeType":"calls","source":2373,"target":304},{"edgeType":"calls","source":2265,"target":481},{"edgeType":"contains","source":6074,"target":6496},{"edgeType":"calls","source":1354,"target":1240},{"edgeType":"calls","source":2899,"target":911},{"edgeType":"calls","source":3537,"target":1216},{"edgeType":"calls","source":6730,"target":527},{"edgeType":"imports","source":2176,"target":2739},{"edgeType":"calls","source":3699,"target":422},{"edgeType":"calls","source":1244,"target":422},{"edgeType":"calls","source":3779,"target":56},{"edgeType":"contains","source":2552,"target":2569},{"edgeType":"calls","source":5140,"target":146},{"edgeType":"contains","source":602,"target":655},{"edgeType":"calls","source":1008,"target":339},{"edgeType":"calls","source":1218,"target":171},{"edgeType":"calls","source":1103,"target":565},{"edgeType":"calls","source":6088,"target":354},{"edgeType":"calls","source":1119,"target":1121},{"edgeType":"calls","source":1185,"target":1189},{"edgeType":"contains","source":967,"target":971},{"edgeType":"contains","source":4898,"target":4899},{"edgeType":"calls","source":6258,"target":369},{"edgeType":"calls","source":6226,"target":304},{"edgeType":"imports","source":42,"target":183},{"edgeType":"calls","source":6730,"target":528},{"edgeType":"contains","source":3246,"target":3258},{"edgeType":"calls","source":530,"target":353},{"edgeType":"contains","source":5732,"target":6520},{"edgeType":"contains","source":5380,"target":2641},{"edgeType":"contains","source":602,"target":658},{"edgeType":"calls","source":4321,"target":165},{"edgeType":"calls","source":2265,"target":478},{"edgeType":"contains","source":2050,"target":2281},{"edgeType":"contains","source":3874,"target":3875},{"edgeType":"imports","source":599,"target":886},{"edgeType":"calls","source":1349,"target":333},{"edgeType":"contains","source":6432,"target":7018},{"edgeType":"calls","source":1599,"target":1039},{"edgeType":"contains","source":4397,"target":4574},{"edgeType":"contains","source":967,"target":970},{"edgeType":"calls","source":1152,"target":1154},{"edgeType":"calls","source":6051,"target":443},{"edgeType":"calls","source":6226,"target":303},{"edgeType":"contains","source":901,"target":902},{"edgeType":"contains","source":41,"target":4307},{"edgeType":"calls","source":3830,"target":588},{"edgeType":"calls","source":6258,"target":368},{"edgeType":"contains","source":3246,"target":3259},{"edgeType":"calls","source":2265,"target":479},{"edgeType":"contains","source":5732,"target":6521},{"edgeType":"calls","source":4490,"target":210},{"edgeType":"imports","source":2879,"target":3141},{"edgeType":"contains","source":4000,"target":4196},{"edgeType":"calls","source":4321,"target":164},{"edgeType":"contains","source":3,"target":2314},{"edgeType":"contains","source":5,"target":138},{"edgeType":"calls","source":4901,"target":3325},{"edgeType":"contains","source":2495,"target":1171},{"edgeType":"calls","source":1349,"target":332},{"edgeType":"calls","source":3358,"target":421},{"edgeType":"contains","source":602,"target":657},{"edgeType":"contains","source":4397,"target":4573},{"edgeType":"contains","source":2316,"target":2489},{"edgeType":"imports","source":599,"target":884},{"edgeType":"calls","source":4241,"target":528},{"edgeType":"calls","source":2782,"target":304},{"edgeType":"contains","source":3246,"target":3256},{"edgeType":"calls","source":2848,"target":372},{"edgeType":"calls","source":4490,"target":209},{"edgeType":"calls","source":2265,"target":476},{"edgeType":"calls","source":4346,"target":445},{"edgeType":"contains","source":602,"target":660},{"edgeType":"calls","source":5044,"target":1005},{"edgeType":"contains","source":3940,"target":3941},{"edgeType":"imports","source":5592,"target":5712},{"edgeType":"contains","source":4921,"target":5240},{"edgeType":"contains","source":5,"target":141},{"edgeType":"contains","source":6450,"target":6462},{"edgeType":"contains","source":6432,"target":7020},{"edgeType":"calls","source":5502,"target":548},{"edgeType":"contains","source":2552,"target":2572},{"edgeType":"calls","source":6258,"target":366},{"edgeType":"imports","source":2581,"target":1807},{"edgeType":"contains","source":3246,"target":3257},{"edgeType":"contains","source":602,"target":659},{"edgeType":"imports","source":5195,"target":49},{"edgeType":"calls","source":2265,"target":477},{"edgeType":"contains","source":4921,"target":5239},{"edgeType":"calls","source":1263,"target":886},{"edgeType":"imports","source":3166,"target":1641},{"edgeType":"contains","source":6350,"target":6368},{"edgeType":"contains","source":6280,"target":6424},{"edgeType":"calls","source":4863,"target":370},{"edgeType":"calls","source":6569,"target":4565},{"edgeType":"calls","source":468,"target":256},{"edgeType":"contains","source":602,"target":629},{"edgeType":"calls","source":3721,"target":889},{"edgeType":"calls","source":2265,"target":573},{"edgeType":"calls","source":2978,"target":2782},{"edgeType":"imports","source":4668,"target":1638},{"edgeType":"contains","source":4698,"target":4727},{"edgeType":"contains","source":40,"target":82},{"edgeType":"contains","source":453,"target":1020},{"edgeType":"contains","source":6280,"target":6425},{"edgeType":"calls","source":6877,"target":303},{"edgeType":"calls","source":6054,"target":445},{"edgeType":"contains","source":1415,"target":1854},{"edgeType":"calls","source":4863,"target":369},{"edgeType":"imports","source":1303,"target":1305},{"edgeType":"contains","source":3014,"target":3023},{"edgeType":"calls","source":4557,"target":4570},{"edgeType":"calls","source":2238,"target":354},{"edgeType":"contains","source":4002,"target":4105},{"edgeType":"contains","source":5473,"target":2899},{"edgeType":"imports","source":4640,"target":4621},{"edgeType":"contains","source":602,"target":628},{"edgeType":"calls","source":6863,"target":6023},{"edgeType":"contains","source":2050,"target":2253},{"edgeType":"contains","source":3,"target":1228},{"edgeType":"contains","source":3807,"target":3808},{"edgeType":"contains","source":453,"target":1019},{"edgeType":"contains","source":2070,"target":2690},{"edgeType":"extends","source":4318,"target":36},{"edgeType":"calls","source":6877,"target":304},{"edgeType":"calls","source":4863,"target":368},{"edgeType":"imports","source":4640,"target":4623},{"edgeType":"calls","source":2787,"target":244},{"edgeType":"calls","source":4394,"target":4337},{"edgeType":"contains","source":453,"target":1022},{"edgeType":"contains","source":602,"target":631},{"edgeType":"contains","source":1825,"target":1826},{"edgeType":"calls","source":6054,"target":443},{"edgeType":"calls","source":1755,"target":528},{"edgeType":"calls","source":3849,"target":1147},{"edgeType":"contains","source":5723,"target":5724},{"edgeType":"contains","source":2050,"target":2250},{"edgeType":"contains","source":2981,"target":2987},{"edgeType":"imports","source":4640,"target":4624},{"edgeType":"calls","source":4656,"target":442},{"edgeType":"calls","source":2265,"target":572},{"edgeType":"contains","source":5380,"target":5780},{"edgeType":"contains","source":453,"target":1021},{"edgeType":"contains","source":602,"target":630},{"edgeType":"contains","source":3873,"target":3874},{"edgeType":"calls","source":5288,"target":1991},{"edgeType":"calls","source":1317,"target":364},{"edgeType":"calls","source":1755,"target":527},{"edgeType":"calls","source":3849,"target":1148},{"edgeType":"calls","source":4215,"target":370},{"edgeType":"extends","source":6091,"target":36},{"edgeType":"contains","source":602,"target":634},{"edgeType":"calls","source":6466,"target":354},{"edgeType":"calls","source":1078,"target":369},{"edgeType":"calls","source":2983,"target":508},{"edgeType":"contains","source":4635,"target":4571},{"edgeType":"calls","source":4863,"target":366},{"edgeType":"imports","source":4640,"target":4625},{"edgeType":"calls","source":2793,"target":1113},{"edgeType":"contains","source":453,"target":1024},{"edgeType":"calls","source":2983,"target":509},{"edgeType":"contains","source":2581,"target":3764},{"edgeType":"contains","source":602,"target":633},{"edgeType":"calls","source":2198,"target":532},{"edgeType":"contains","source":6638,"target":6949},{"edgeType":"contains","source":4100,"target":4243},{"edgeType":"contains","source":2070,"target":2693},{"edgeType":"contains","source":6280,"target":6420},{"edgeType":"contains","source":2070,"target":2694},{"edgeType":"calls","source":1412,"target":584},{"edgeType":"contains","source":2176,"target":3636},{"edgeType":"contains","source":4307,"target":5224},{"edgeType":"calls","source":4215,"target":371},{"edgeType":"calls","source":2882,"target":469},{"edgeType":"calls","source":5065,"target":445},{"edgeType":"contains","source":3013,"target":4115},{"edgeType":"calls","source":1078,"target":368},{"edgeType":"contains","source":1028,"target":1168},{"edgeType":"calls","source":2787,"target":1300},{"edgeType":"imports","source":4640,"target":4626},{"edgeType":"contains","source":453,"target":1023},{"edgeType":"contains","source":2540,"target":1865},{"edgeType":"calls","source":4379,"target":571},{"edgeType":"contains","source":6638,"target":6950},{"edgeType":"contains","source":602,"target":632},{"edgeType":"calls","source":372,"target":56},{"edgeType":"imports","source":3867,"target":49},{"edgeType":"calls","source":3849,"target":1146},{"edgeType":"contains","source":6280,"target":6421},{"edgeType":"contains","source":5,"target":113},{"edgeType":"calls","source":4863,"target":364},{"edgeType":"calls","source":5589,"target":56},{"edgeType":"calls","source":4215,"target":368},{"edgeType":"contains","source":4307,"target":5223},{"edgeType":"calls","source":1078,"target":371},{"edgeType":"imports","source":4640,"target":4627},{"edgeType":"contains","source":602,"target":636},{"edgeType":"contains","source":2981,"target":2990},{"edgeType":"contains","source":3014,"target":3024},{"edgeType":"calls","source":2983,"target":506},{"edgeType":"calls","source":1599,"target":1132},{"edgeType":"contains","source":6638,"target":6951},{"edgeType":"calls","source":5235,"target":1517},{"edgeType":"calls","source":6605,"target":6627},{"edgeType":"contains","source":6280,"target":6422},{"edgeType":"calls","source":1758,"target":431},{"edgeType":"contains","source":4002,"target":4108},{"edgeType":"contains","source":2176,"target":3634},{"edgeType":"calls","source":4215,"target":369},{"edgeType":"calls","source":5065,"target":443},{"edgeType":"contains","source":602,"target":635},{"edgeType":"calls","source":1078,"target":370},{"edgeType":"calls","source":4761,"target":354},{"edgeType":"calls","source":2793,"target":1112},{"edgeType":"calls","source":4801,"target":171},{"edgeType":"calls","source":2983,"target":507},{"edgeType":"calls","source":4892,"target":4749},{"edgeType":"contains","source":453,"target":1025},{"edgeType":"calls","source":3534,"target":3510},{"edgeType":"contains","source":2070,"target":2692},{"edgeType":"calls","source":5893,"target":144},{"edgeType":"calls","source":4215,"target":366},{"edgeType":"calls","source":2822,"target":210},{"edgeType":"calls","source":5372,"target":2553},{"edgeType":"contains","source":6350,"target":6376},{"edgeType":"calls","source":2983,"target":504},{"edgeType":"contains","source":2552,"target":2554},{"edgeType":"calls","source":4801,"target":170},{"edgeType":"contains","source":602,"target":638},{"edgeType":"contains","source":4698,"target":4736},{"edgeType":"contains","source":6549,"target":6550},{"edgeType":"contains","source":3110,"target":3225},{"edgeType":"contains","source":5884,"target":6024},{"edgeType":"contains","source":5029,"target":5045},{"edgeType":"calls","source":468,"target":248},{"edgeType":"calls","source":4404,"target":4021},{"edgeType":"calls","source":6605,"target":6629},{"edgeType":"imports","source":6245,"target":5596},{"edgeType":"contains","source":6770,"target":7099},{"edgeType":"calls","source":1328,"target":1070},{"edgeType":"contains","source":4196,"target":4441},{"edgeType":"contains","source":2552,"target":2555},{"edgeType":"contains","source":602,"target":637},{"edgeType":"calls","source":1262,"target":1002},{"edgeType":"contains","source":4698,"target":4735},{"edgeType":"calls","source":1078,"target":364},{"edgeType":"calls","source":2983,"target":505},{"edgeType":"contains","source":4474,"target":5336},{"edgeType":"calls","source":5235,"target":1514},{"edgeType":"calls","source":4363,"target":4234},{"edgeType":"contains","source":5285,"target":5564},{"edgeType":"calls","source":4530,"target":114},{"edgeType":"contains","source":3110,"target":3226},{"edgeType":"contains","source":3543,"target":3544},{"edgeType":"calls","source":4933,"target":304},{"edgeType":"calls","source":3023,"target":319},{"edgeType":"calls","source":2983,"target":502},{"edgeType":"contains","source":602,"target":640},{"edgeType":"calls","source":3194,"target":303},{"edgeType":"calls","source":3194,"target":304},{"edgeType":"imports","source":6074,"target":329},{"edgeType":"calls","source":6974,"target":6819},{"edgeType":"contains","source":4002,"target":4112},{"edgeType":"calls","source":4126,"target":4179},{"edgeType":"calls","source":4251,"target":304},{"edgeType":"calls","source":6233,"target":171},{"edgeType":"calls","source":2822,"target":209},{"edgeType":"calls","source":4933,"target":303},{"edgeType":"calls","source":6541,"target":159},{"edgeType":"calls","source":2983,"target":503},{"edgeType":"contains","source":2552,"target":2553},{"edgeType":"contains","source":5029,"target":5042},{"edgeType":"contains","source":602,"target":639},{"edgeType":"calls","source":1078,"target":366},{"edgeType":"contains","source":6450,"target":6451},{"edgeType":"calls","source":6804,"target":6805},{"edgeType":"calls","source":6233,"target":170},{"edgeType":"calls","source":4215,"target":364},{"edgeType":"calls","source":6712,"target":144},{"edgeType":"contains","source":1989,"target":2041},{"edgeType":"contains","source":602,"target":642},{"edgeType":"calls","source":6541,"target":160},{"edgeType":"contains","source":6350,"target":6372},{"edgeType":"contains","source":4474,"target":5342},{"edgeType":"contains","source":2552,"target":2558},{"edgeType":"contains","source":3674,"target":3716},{"edgeType":"contains","source":5029,"target":5049},{"edgeType":"calls","source":468,"target":244},{"edgeType":"calls","source":2575,"target":2578},{"edgeType":"calls","source":3812,"target":170},{"edgeType":"imports","source":5166,"target":996},{"edgeType":"calls","source":6541,"target":161},{"edgeType":"calls","source":6954,"target":6385},{"edgeType":"calls","source":3023,"target":318},{"edgeType":"contains","source":2552,"target":2559},{"edgeType":"calls","source":5222,"target":1912},{"edgeType":"contains","source":602,"target":641},{"edgeType":"contains","source":6770,"target":7095},{"edgeType":"calls","source":1354,"target":1317},{"edgeType":"calls","source":5238,"target":4588},{"edgeType":"contains","source":5029,"target":5048},{"edgeType":"calls","source":7010,"target":421},{"edgeType":"calls","source":3812,"target":171},{"edgeType":"calls","source":1981,"target":1963},{"edgeType":"calls","source":4251,"target":303},{"edgeType":"calls","source":3635,"target":370},{"edgeType":"calls","source":7068,"target":6023},{"edgeType":"contains","source":602,"target":644},{"edgeType":"imports","source":3726,"target":184},{"edgeType":"calls","source":1328,"target":1069},{"edgeType":"calls","source":3540,"target":144},{"edgeType":"contains","source":6770,"target":7096},{"edgeType":"contains","source":336,"target":434},{"edgeType":"extends","source":3841,"target":36},{"edgeType":"calls","source":4656,"target":431},{"edgeType":"contains","source":5029,"target":5047},{"edgeType":"contains","source":996,"target":1114},{"edgeType":"contains","source":3110,"target":3227},{"edgeType":"calls","source":7010,"target":422},{"edgeType":"calls","source":5785,"target":5599},{"edgeType":"calls","source":6678,"target":144},{"edgeType":"calls","source":4597,"target":146},{"edgeType":"contains","source":602,"target":643},{"edgeType":"extends","source":4898,"target":36},{"edgeType":"calls","source":3635,"target":371},{"edgeType":"contains","source":4698,"target":4737},{"edgeType":"calls","source":5372,"target":431},{"edgeType":"calls","source":5227,"target":4926},{"edgeType":"calls","source":4692,"target":371},{"edgeType":"calls","source":2643,"target":469},{"edgeType":"contains","source":5029,"target":5046},{"edgeType":"calls","source":1801,"target":146},{"edgeType":"calls","source":6336,"target":144},{"edgeType":"calls","source":6374,"target":6398},{"edgeType":"calls","source":6609,"target":170},{"edgeType":"contains","source":602,"target":613},{"edgeType":"contains","source":5463,"target":3194},{"edgeType":"imports","source":4668,"target":565},{"edgeType":"contains","source":6770,"target":7073},{"edgeType":"contains","source":6213,"target":6370},{"edgeType":"calls","source":3766,"target":568},{"edgeType":"imports","source":5895,"target":582},{"edgeType":"calls","source":2577,"target":431},{"edgeType":"contains","source":205,"target":235},{"edgeType":"calls","source":6772,"target":370},{"edgeType":"calls","source":7009,"target":422},{"edgeType":"calls","source":4529,"target":171},{"edgeType":"contains","source":5166,"target":7115},{"edgeType":"calls","source":909,"target":342},{"edgeType":"contains","source":5463,"target":3193},{"edgeType":"contains","source":602,"target":612},{"edgeType":"calls","source":2859,"target":146},{"edgeType":"contains","source":3,"target":154},{"edgeType":"calls","source":5655,"target":146},{"edgeType":"calls","source":5245,"target":171},{"edgeType":"contains","source":6213,"target":6371},{"edgeType":"contains","source":4528,"target":4695},{"edgeType":"contains","source":205,"target":234},{"edgeType":"calls","source":6772,"target":371},{"edgeType":"extends","source":1044,"target":36},{"edgeType":"calls","source":6045,"target":1797},{"edgeType":"calls","source":1045,"target":354},{"edgeType":"contains","source":6770,"target":7074},{"edgeType":"contains","source":5166,"target":7114},{"edgeType":"calls","source":4529,"target":170},{"edgeType":"contains","source":2688,"target":425},{"edgeType":"contains","source":602,"target":615},{"edgeType":"calls","source":7047,"target":303},{"edgeType":"calls","source":5245,"target":170},{"edgeType":"contains","source":4528,"target":4694},{"edgeType":"contains","source":4100,"target":4220},{"edgeType":"contains","source":5,"target":2209},{"edgeType":"contains","source":205,"target":238},{"edgeType":"calls","source":1812,"target":892},{"edgeType":"contains","source":6350,"target":6354},{"edgeType":"contains","source":5166,"target":7113},{"edgeType":"calls","source":4973,"target":146},{"edgeType":"calls","source":6569,"target":3494},{"edgeType":"contains","source":6770,"target":7075},{"edgeType":"calls","source":2609,"target":2608},{"edgeType":"calls","source":2907,"target":2884},{"edgeType":"calls","source":7047,"target":304},{"edgeType":"calls","source":4932,"target":4587},{"edgeType":"contains","source":602,"target":614},{"edgeType":"calls","source":3118,"target":571},{"edgeType":"contains","source":5,"target":2208},{"edgeType":"contains","source":4500,"target":4504},{"edgeType":"extends","source":451,"target":452},{"edgeType":"calls","source":3459,"target":571},{"edgeType":"contains","source":205,"target":237},{"edgeType":"contains","source":205,"target":236},{"edgeType":"calls","source":1062,"target":886},{"edgeType":"calls","source":1812,"target":891},{"edgeType":"contains","source":6448,"target":6488},{"edgeType":"contains","source":5166,"target":7112},{"edgeType":"contains","source":1415,"target":1836},{"edgeType":"contains","source":6770,"target":7076},{"edgeType":"contains","source":996,"target":1084},{"edgeType":"calls","source":4800,"target":4451},{"edgeType":"calls","source":6940,"target":6793},{"edgeType":"contains","source":602,"target":617},{"edgeType":"contains","source":205,"target":240},{"edgeType":"contains","source":4196,"target":4422},{"edgeType":"contains","source":5,"target":4326},{"edgeType":"calls","source":6672,"target":303},{"edgeType":"calls","source":6295,"target":2500},{"edgeType":"calls","source":1119,"target":171},{"edgeType":"contains","source":2898,"target":3434},{"edgeType":"calls","source":6871,"target":6819},{"edgeType":"calls","source":2270,"target":431},{"edgeType":"contains","source":602,"target":616},{"edgeType":"calls","source":6030,"target":144},{"edgeType":"calls","source":3854,"target":1008},{"edgeType":"calls","source":1882,"target":1886},{"edgeType":"contains","source":205,"target":239},{"edgeType":"contains","source":30,"target":4607},{"edgeType":"contains","source":6213,"target":6367},{"edgeType":"contains","source":5,"target":4324},{"edgeType":"extends","source":4113,"target":36},{"edgeType":"contains","source":6448,"target":6482},{"edgeType":"calls","source":6672,"target":304},{"edgeType":"calls","source":6494,"target":537},{"edgeType":"calls","source":1119,"target":170},{"edgeType":"imports","source":1379,"target":1041},{"edgeType":"calls","source":5102,"target":4599},{"edgeType":"contains","source":5260,"target":5261},{"edgeType":"calls","source":896,"target":744},{"edgeType":"contains","source":4698,"target":4713},{"edgeType":"calls","source":4384,"target":431},{"edgeType":"contains","source":4100,"target":4224},{"edgeType":"contains","source":205,"target":242},{"edgeType":"calls","source":1870,"target":147},{"edgeType":"calls","source":1958,"target":590},{"edgeType":"calls","source":2609,"target":2604},{"edgeType":"calls","source":6207,"target":5226},{"edgeType":"calls","source":1299,"target":935},{"edgeType":"contains","source":602,"target":619},{"edgeType":"calls","source":298,"target":256},{"edgeType":"calls","source":2615,"target":304},{"edgeType":"imports","source":4668,"target":571},{"edgeType":"calls","source":594,"target":593},{"edgeType":"contains","source":5293,"target":5294},{"edgeType":"contains","source":6213,"target":6369},{"edgeType":"contains","source":205,"target":241},{"edgeType":"calls","source":3633,"target":3629},{"edgeType":"contains","source":4100,"target":4223},{"edgeType":"extends","source":5705,"target":5647},{"edgeType":"calls","source":6405,"target":144},{"edgeType":"calls","source":1299,"target":934},{"edgeType":"calls","source":5372,"target":2570},{"edgeType":"contains","source":602,"target":618},{"edgeType":"imports","source":4378,"target":49},{"edgeType":"contains","source":5458,"target":5463},{"edgeType":"calls","source":472,"target":146},{"edgeType":"contains","source":4459,"target":4729},{"edgeType":"calls","source":5221,"target":5136},{"edgeType":"calls","source":471,"target":171},{"edgeType":"contains","source":205,"target":244},{"edgeType":"contains","source":6111,"target":3198},{"edgeType":"calls","source":6688,"target":5096},{"edgeType":"calls","source":1882,"target":1883},{"edgeType":"calls","source":2045,"target":2115},{"edgeType":"calls","source":1317,"target":371},{"edgeType":"contains","source":4100,"target":4231},{"edgeType":"contains","source":602,"target":621},{"edgeType":"contains","source":6280,"target":6416},{"edgeType":"contains","source":6770,"target":7081},{"edgeType":"calls","source":5000,"target":4588},{"edgeType":"calls","source":2990,"target":304},{"edgeType":"calls","source":4917,"target":1876},{"edgeType":"calls","source":298,"target":248},{"edgeType":"calls","source":1770,"target":1126},{"edgeType":"calls","source":5221,"target":5135},{"edgeType":"calls","source":4525,"target":4513},{"edgeType":"calls","source":471,"target":170},{"edgeType":"calls","source":1591,"target":333},{"edgeType":"calls","source":6970,"target":6925},{"edgeType":"calls","source":6157,"target":431},{"edgeType":"contains","source":205,"target":243},{"edgeType":"contains","source":3,"target":162},{"edgeType":"calls","source":2045,"target":2114},{"edgeType":"contains","source":41,"target":42},{"edgeType":"calls","source":1412,"target":596},{"edgeType":"calls","source":6612,"target":1111},{"edgeType":"calls","source":4035,"target":3849},{"edgeType":"calls","source":5688,"target":171},{"edgeType":"calls","source":1591,"target":332},{"edgeType":"contains","source":6350,"target":6361},{"edgeType":"calls","source":2615,"target":303},{"edgeType":"contains","source":6280,"target":6417},{"edgeType":"contains","source":602,"target":620},{"edgeType":"calls","source":1317,"target":370},{"edgeType":"contains","source":1031,"target":1062},{"edgeType":"calls","source":2787,"target":1313},{"edgeType":"contains","source":4668,"target":1420},{"edgeType":"contains","source":6610,"target":6757},{"edgeType":"calls","source":5028,"target":548},{"edgeType":"calls","source":5223,"target":1901},{"edgeType":"calls","source":5221,"target":5134},{"edgeType":"calls","source":5373,"target":422},{"edgeType":"contains","source":205,"target":246},{"edgeType":"calls","source":4042,"target":458},{"edgeType":"calls","source":4447,"target":588},{"edgeType":"calls","source":1882,"target":1885},{"edgeType":"calls","source":6108,"target":892},{"edgeType":"calls","source":4800,"target":4444},{"edgeType":"contains","source":2070,"target":2679},{"edgeType":"calls","source":6541,"target":142},{"edgeType":"contains","source":2201,"target":2846},{"edgeType":"calls","source":5688,"target":170},{"edgeType":"contains","source":2981,"target":2977},{"edgeType":"contains","source":453,"target":1014},{"edgeType":"contains","source":2581,"target":3750},{"edgeType":"contains","source":602,"target":623},{"edgeType":"calls","source":5142,"target":2298},{"edgeType":"contains","source":6350,"target":6362},{"edgeType":"contains","source":1028,"target":1158},{"edgeType":"calls","source":5891,"target":4447},{"edgeType":"calls","source":5373,"target":421},{"edgeType":"calls","source":1600,"target":56},{"edgeType":"contains","source":5260,"target":5264},{"edgeType":"contains","source":205,"target":245},{"edgeType":"calls","source":6108,"target":891},{"edgeType":"contains","source":3739,"target":3791},{"edgeType":"calls","source":1882,"target":1884},{"edgeType":"calls","source":1948,"target":1952},{"edgeType":"calls","source":6374,"target":1101},{"edgeType":"contains","source":4196,"target":4423},{"edgeType":"contains","source":6770,"target":7084},{"edgeType":"calls","source":3398,"target":3510},{"edgeType":"imports","source":5195,"target":78},{"edgeType":"contains","source":1302,"target":2176},{"edgeType":"contains","source":5,"target":2217},{"edgeType":"contains","source":2201,"target":2847},{"edgeType":"calls","source":2990,"target":303},{"edgeType":"contains","source":2581,"target":3751},{"edgeType":"contains","source":6638,"target":6948},{"edgeType":"contains","source":602,"target":622},{"edgeType":"calls","source":5077,"target":84},{"edgeType":"imports","source":3013,"target":79},{"edgeType":"calls","source":1822,"target":568},{"edgeType":"contains","source":3014,"target":3018},{"edgeType":"contains","source":30,"target":4616},{"edgeType":"contains","source":1032,"target":1037},{"edgeType":"contains","source":1028,"target":1161},{"edgeType":"calls","source":2096,"target":530},{"edgeType":"imports","source":5195,"target":79},{"edgeType":"contains","source":6350,"target":6356},{"edgeType":"contains","source":2050,"target":2248},{"edgeType":"contains","source":453,"target":1016},{"edgeType":"calls","source":5163,"target":588},{"edgeType":"contains","source":6770,"target":7077},{"edgeType":"contains","source":6448,"target":6489},{"edgeType":"calls","source":3024,"target":303},{"edgeType":"imports","source":3013,"target":78},{"edgeType":"contains","source":602,"target":625},{"edgeType":"calls","source":6882,"target":144},{"edgeType":"contains","source":205,"target":247},{"edgeType":"calls","source":1959,"target":548},{"edgeType":"contains","source":5029,"target":5032},{"edgeType":"contains","source":1028,"target":1160},{"edgeType":"calls","source":7072,"target":596},{"edgeType":"calls","source":4042,"target":457},{"edgeType":"calls","source":2845,"target":568},{"edgeType":"calls","source":6528,"target":548},{"edgeType":"contains","source":6350,"target":6357},{"edgeType":"contains","source":4003,"target":4070},{"edgeType":"contains","source":6280,"target":6413},{"edgeType":"calls","source":1317,"target":366},{"edgeType":"calls","source":3024,"target":304},{"edgeType":"contains","source":453,"target":1015},{"edgeType":"calls","source":2997,"target":84},{"edgeType":"contains","source":4196,"target":4429},{"edgeType":"calls","source":1257,"target":1169},{"edgeType":"contains","source":602,"target":624},{"edgeType":"calls","source":1349,"target":431},{"edgeType":"contains","source":2981,"target":2982},{"edgeType":"contains","source":5029,"target":5031},{"edgeType":"calls","source":2787,"target":248},{"edgeType":"calls","source":4182,"target":342},{"edgeType":"contains","source":602,"target":627},{"edgeType":"calls","source":5000,"target":354},{"edgeType":"calls","source":1539,"target":886},{"edgeType":"contains","source":6280,"target":6414},{"edgeType":"contains","source":6082,"target":6210},{"edgeType":"calls","source":1317,"target":369},{"edgeType":"contains","source":453,"target":1018},{"edgeType":"contains","source":5029,"target":5030},{"edgeType":"contains","source":3014,"target":3017},{"edgeType":"calls","source":576,"target":84},{"edgeType":"contains","source":6111,"target":3197},{"edgeType":"calls","source":4863,"target":371},{"edgeType":"contains","source":3674,"target":3696},{"edgeType":"calls","source":2045,"target":2112},{"edgeType":"calls","source":4486,"target":431},{"edgeType":"calls","source":4302,"target":4021},{"edgeType":"calls","source":2808,"target":2770},{"edgeType":"calls","source":4226,"target":4263},{"edgeType":"contains","source":602,"target":626},{"edgeType":"calls","source":7110,"target":2592},{"edgeType":"contains","source":4003,"target":4068},{"edgeType":"contains","source":6280,"target":6415},{"edgeType":"contains","source":139,"target":181},{"edgeType":"contains","source":6770,"target":7080},{"edgeType":"calls","source":1317,"target":368},{"edgeType":"calls","source":4758,"target":421},{"edgeType":"contains","source":205,"target":219},{"edgeType":"contains","source":4830,"target":4831},{"edgeType":"calls","source":7019,"target":1152},{"edgeType":"calls","source":4739,"target":4181},{"edgeType":"contains","source":5285,"target":5524},{"edgeType":"calls","source":4519,"target":431},{"edgeType":"calls","source":6542,"target":84},{"edgeType":"calls","source":2607,"target":508},{"edgeType":"calls","source":6435,"target":2344},{"edgeType":"calls","source":7140,"target":573},{"edgeType":"calls","source":2914,"target":505},{"edgeType":"contains","source":6770,"target":7056},{"edgeType":"contains","source":3,"target":139},{"edgeType":"calls","source":1350,"target":364},{"edgeType":"contains","source":5,"target":2191},{"edgeType":"calls","source":3430,"target":364},{"edgeType":"calls","source":3780,"target":84},{"edgeType":"calls","source":3662,"target":571},{"edgeType":"contains","source":4100,"target":4206},{"edgeType":"calls","source":1598,"target":1132},{"edgeType":"calls","source":2607,"target":509},{"edgeType":"contains","source":205,"target":218},{"edgeType":"calls","source":6940,"target":431},{"edgeType":"calls","source":1187,"target":1188},{"edgeType":"imports","source":2879,"target":49},{"edgeType":"calls","source":460,"target":470},{"edgeType":"calls","source":4589,"target":4602},{"edgeType":"contains","source":5324,"target":5371},{"edgeType":"calls","source":6435,"target":2345},{"edgeType":"calls","source":1583,"target":1596},{"edgeType":"calls","source":4447,"target":548},{"edgeType":"contains","source":6770,"target":7057},{"edgeType":"calls","source":2914,"target":506},{"edgeType":"contains","source":5,"target":2190},{"edgeType":"contains","source":3839,"target":3840},{"edgeType":"calls","source":1517,"target":1528},{"edgeType":"contains","source":4378,"target":5100},{"edgeType":"imports","source":3867,"target":78},{"edgeType":"contains","source":3606,"target":3662},{"edgeType":"calls","source":1955,"target":1695},{"edgeType":"calls","source":1962,"target":421},{"edgeType":"calls","source":4194,"target":2047},{"edgeType":"contains","source":1032,"target":2067},{"edgeType":"contains","source":996,"target":1069},{"edgeType":"calls","source":2914,"target":502},{"edgeType":"contains","source":6770,"target":7059},{"edgeType":"calls","source":6274,"target":6275},{"edgeType":"contains","source":3408,"target":3458},{"edgeType":"calls","source":2607,"target":506},{"edgeType":"calls","source":6435,"target":2346},{"edgeType":"contains","source":1379,"target":2934},{"edgeType":"contains","source":5324,"target":5370},{"edgeType":"contains","source":2055,"target":2062},{"edgeType":"calls","source":1350,"target":366},{"edgeType":"calls","source":3816,"target":3194},{"edgeType":"contains","source":205,"target":221},{"edgeType":"imports","source":3867,"target":79},{"edgeType":"contains","source":205,"target":220},{"edgeType":"contains","source":6770,"target":7060},{"edgeType":"calls","source":2914,"target":503},{"edgeType":"contains","source":5324,"target":5369},{"edgeType":"calls","source":6435,"target":2347},{"edgeType":"calls","source":460,"target":472},{"edgeType":"calls","source":2607,"target":507},{"edgeType":"contains","source":3408,"target":3457},{"edgeType":"calls","source":2914,"target":504},{"edgeType":"contains","source":3904,"target":3937},{"edgeType":"contains","source":4378,"target":5098},{"edgeType":"calls","source":592,"target":603},{"edgeType":"calls","source":6662,"target":596},{"edgeType":"calls","source":6717,"target":1005},{"edgeType":"calls","source":2607,"target":504},{"edgeType":"contains","source":4830,"target":4835},{"edgeType":"contains","source":6770,"target":7052},{"edgeType":"contains","source":6085,"target":6090},{"edgeType":"calls","source":2298,"target":570},{"edgeType":"contains","source":3674,"target":3675},{"edgeType":"contains","source":205,"target":223},{"edgeType":"calls","source":3743,"target":170},{"edgeType":"calls","source":5712,"target":5725},{"edgeType":"calls","source":4028,"target":4021},{"edgeType":"calls","source":6879,"target":212},{"edgeType":"calls","source":4194,"target":2046},{"edgeType":"calls","source":6813,"target":144},{"edgeType":"contains","source":996,"target":1070},{"edgeType":"calls","source":1187,"target":1184},{"edgeType":"calls","source":2607,"target":505},{"edgeType":"contains","source":6770,"target":7053},{"edgeType":"contains","source":5380,"target":2582},{"edgeType":"contains","source":4635,"target":4536},{"edgeType":"calls","source":1760,"target":333},{"edgeType":"calls","source":5133,"target":4647},{"edgeType":"contains","source":4378,"target":5104},{"edgeType":"contains","source":2070,"target":2661},{"edgeType":"contains","source":205,"target":222},{"edgeType":"calls","source":3743,"target":171},{"edgeType":"contains","source":6448,"target":6466},{"edgeType":"calls","source":4197,"target":893},{"edgeType":"calls","source":6813,"target":145},{"edgeType":"contains","source":3626,"target":4103},{"edgeType":"calls","source":1241,"target":570},{"edgeType":"calls","source":2607,"target":502},{"edgeType":"contains","source":4830,"target":4833},{"edgeType":"contains","source":1031,"target":1045},{"edgeType":"contains","source":1064,"target":1079},{"edgeType":"contains","source":996,"target":1073},{"edgeType":"imports","source":2736,"target":1305},{"edgeType":"calls","source":4530,"target":84},{"edgeType":"calls","source":3159,"target":303},{"edgeType":"contains","source":5285,"target":5526},{"edgeType":"imports","source":5232,"target":49},{"edgeType":"contains","source":5463,"target":4236},{"edgeType":"calls","source":4485,"target":422},{"edgeType":"extends","source":325,"target":184},{"edgeType":"contains","source":6770,"target":7054},{"edgeType":"calls","source":3696,"target":568},{"edgeType":"contains","source":205,"target":225},{"edgeType":"calls","source":6872,"target":431},{"edgeType":"calls","source":5901,"target":4092},{"edgeType":"contains","source":2201,"target":2826},{"edgeType":"calls","source":6327,"target":4627},{"edgeType":"contains","source":4797,"target":4798},{"edgeType":"calls","source":2607,"target":503},{"edgeType":"calls","source":2848,"target":431},{"edgeType":"contains","source":5166,"target":7100},{"edgeType":"calls","source":4934,"target":1300},{"edgeType":"calls","source":5003,"target":4446},{"edgeType":"contains","source":5324,"target":5373},{"edgeType":"calls","source":3159,"target":304},{"edgeType":"contains","source":4668,"target":340},{"edgeType":"contains","source":2495,"target":1111},{"edgeType":"contains","source":6770,"target":7055},{"edgeType":"calls","source":4485,"target":421},{"edgeType":"calls","source":1517,"target":1526},{"edgeType":"calls","source":6688,"target":5079},{"edgeType":"contains","source":2314,"target":2494},{"edgeType":"contains","source":205,"target":224},{"edgeType":"calls","source":4932,"target":304},{"edgeType":"contains","source":1379,"target":1887},{"edgeType":"calls","source":4934,"target":1299},{"edgeType":"calls","source":2882,"target":431},{"edgeType":"calls","source":6327,"target":4626},{"edgeType":"calls","source":1145,"target":369},{"edgeType":"contains","source":4528,"target":4688},{"edgeType":"contains","source":452,"target":1026},{"edgeType":"contains","source":5166,"target":7107},{"edgeType":"imports","source":6476,"target":582},{"edgeType":"contains","source":205,"target":227},{"edgeType":"calls","source":7120,"target":144},{"edgeType":"calls","source":2043,"target":1070},{"edgeType":"contains","source":4830,"target":4838},{"edgeType":"calls","source":1352,"target":1350},{"edgeType":"contains","source":6213,"target":6363},{"edgeType":"calls","source":4932,"target":303},{"edgeType":"calls","source":5415,"target":5414},{"edgeType":"calls","source":6327,"target":4625},{"edgeType":"calls","source":592,"target":598},{"edgeType":"imports","source":181,"target":190},{"edgeType":"extends","source":4558,"target":36},{"edgeType":"calls","source":4922,"target":4841},{"edgeType":"contains","source":4632,"target":4634},{"edgeType":"calls","source":1145,"target":368},{"edgeType":"contains","source":4698,"target":4702},{"edgeType":"contains","source":5166,"target":7106},{"edgeType":"contains","source":205,"target":226},{"edgeType":"calls","source":6781,"target":84},{"edgeType":"contains","source":4196,"target":4407},{"edgeType":"calls","source":3541,"target":84},{"edgeType":"contains","source":6213,"target":6364},{"edgeType":"calls","source":6421,"target":4902},{"edgeType":"contains","source":106,"target":127},{"edgeType":"contains","source":4698,"target":4701},{"edgeType":"contains","source":452,"target":1029},{"edgeType":"calls","source":1145,"target":371},{"edgeType":"contains","source":4632,"target":4633},{"edgeType":"contains","source":4830,"target":4837},{"edgeType":"contains","source":5166,"target":7105},{"edgeType":"calls","source":3968,"target":588},{"edgeType":"calls","source":1760,"target":332},{"edgeType":"contains","source":3110,"target":3190},{"edgeType":"contains","source":4668,"target":1402},{"edgeType":"contains","source":4378,"target":5107},{"edgeType":"contains","source":205,"target":229},{"edgeType":"contains","source":5679,"target":3892},{"edgeType":"calls","source":6772,"target":364},{"edgeType":"calls","source":1825,"target":431},{"edgeType":"calls","source":4896,"target":4588},{"edgeType":"calls","source":4739,"target":4170},{"edgeType":"contains","source":2584,"target":2585},{"edgeType":"contains","source":4665,"target":4666},{"edgeType":"contains","source":4797,"target":4802},{"edgeType":"contains","source":6213,"target":6365},{"edgeType":"calls","source":1145,"target":370},{"edgeType":"contains","source":4830,"target":4836},{"edgeType":"calls","source":5310,"target":210},{"edgeType":"contains","source":5166,"target":7104},{"edgeType":"contains","source":3110,"target":3191},{"edgeType":"contains","source":5473,"target":2872},{"edgeType":"contains","source":205,"target":228},{"edgeType":"calls","source":6881,"target":157},{"edgeType":"calls","source":4956,"target":4841},{"edgeType":"calls","source":5646,"target":5649},{"edgeType":"calls","source":6494,"target":527},{"edgeType":"contains","source":6213,"target":6358},{"edgeType":"calls","source":6973,"target":6819},{"edgeType":"calls","source":4764,"target":4451},{"edgeType":"contains","source":4668,"target":1409},{"edgeType":"contains","source":6770,"target":7061},{"edgeType":"contains","source":4528,"target":4692},{"edgeType":"calls","source":5310,"target":209},{"edgeType":"contains","source":4528,"target":2578},{"edgeType":"contains","source":602,"target":609},{"edgeType":"contains","source":4378,"target":5113},{"edgeType":"calls","source":4004,"target":527},{"edgeType":"calls","source":1145,"target":364},{"edgeType":"calls","source":2606,"target":1584},{"edgeType":"calls","source":6023,"target":304},{"edgeType":"contains","source":205,"target":231},{"edgeType":"extends","source":2922,"target":1076},{"edgeType":"contains","source":5166,"target":7111},{"edgeType":"calls","source":4435,"target":3023},{"edgeType":"calls","source":6445,"target":6275},{"edgeType":"calls","source":6772,"target":366},{"edgeType":"contains","source":3408,"target":3471},{"edgeType":"contains","source":2688,"target":424},{"edgeType":"calls","source":6494,"target":528},{"edgeType":"calls","source":5655,"target":84},{"edgeType":"contains","source":602,"target":608},{"edgeType":"contains","source":6770,"target":7062},{"edgeType":"calls","source":468,"target":210},{"edgeType":"contains","source":928,"target":3186},{"edgeType":"extends","source":3808,"target":36},{"edgeType":"contains","source":4378,"target":5112},{"edgeType":"calls","source":4004,"target":528},{"edgeType":"calls","source":6023,"target":303},{"edgeType":"contains","source":205,"target":230},{"edgeType":"contains","source":1027,"target":6459},{"edgeType":"contains","source":5166,"target":7110},{"edgeType":"contains","source":3408,"target":3472},{"edgeType":"contains","source":3509,"target":3512},{"edgeType":"contains","source":602,"target":611},{"edgeType":"calls","source":1517,"target":1519},{"edgeType":"calls","source":2806,"target":2781},{"edgeType":"calls","source":2778,"target":2592},{"edgeType":"imports","source":3030,"target":1713},{"edgeType":"calls","source":1361,"target":1070},{"edgeType":"extends","source":189,"target":180},{"edgeType":"contains","source":452,"target":1033},{"edgeType":"contains","source":6770,"target":7063},{"edgeType":"contains","source":4500,"target":4501},{"edgeType":"calls","source":1145,"target":366},{"edgeType":"contains","source":4378,"target":5111},{"edgeType":"contains","source":205,"target":233},{"edgeType":"contains","source":1031,"target":1053},{"edgeType":"contains","source":5166,"target":7109},{"edgeType":"calls","source":4689,"target":4660},{"edgeType":"contains","source":5463,"target":3187},{"edgeType":"calls","source":6772,"target":368},{"edgeType":"calls","source":6385,"target":6023},{"edgeType":"calls","source":777,"target":146},{"edgeType":"contains","source":602,"target":610},{"edgeType":"calls","source":2253,"target":898},{"edgeType":"calls","source":1517,"target":1518},{"edgeType":"calls","source":6953,"target":6385},{"edgeType":"contains","source":5,"target":2204},{"edgeType":"contains","source":2070,"target":2667},{"edgeType":"calls","source":5653,"target":144},{"edgeType":"contains","source":6448,"target":6475},{"edgeType":"contains","source":4528,"target":4689},{"edgeType":"calls","source":1401,"target":886},{"edgeType":"contains","source":4691,"target":4921},{"edgeType":"calls","source":6704,"target":4591},{"edgeType":"contains","source":205,"target":232},{"edgeType":"contains","source":5166,"target":7108},{"edgeType":"calls","source":7009,"target":421},{"edgeType":"contains","source":996,"target":1080},{"edgeType":"contains","source":5285,"target":5533},{"edgeType":"contains","source":1814,"target":2147},{"edgeType":"calls","source":6772,"target":369},{"edgeType":"calls","source":7051,"target":6486},{"edgeType":"calls","source":3023,"target":313},{"edgeType":"extends","source":452,"target":453},{"edgeType":"contains","source":4432,"target":4468},{"edgeType":"contains","source":6280,"target":6374},{"edgeType":"calls","source":3635,"target":368},{"edgeType":"calls","source":4692,"target":370},{"edgeType":"contains","source":996,"target":1050},{"edgeType":"imports","source":5166,"target":2072},{"edgeType":"extends","source":4830,"target":36},{"edgeType":"calls","source":3635,"target":369},{"edgeType":"calls","source":5313,"target":144},{"edgeType":"contains","source":3838,"target":3854},{"edgeType":"contains","source":3,"target":4349},{"edgeType":"imports","source":3814,"target":3818},{"edgeType":"contains","source":6349,"target":6351},{"edgeType":"contains","source":920,"target":1291},{"edgeType":"calls","source":7008,"target":421},{"edgeType":"contains","source":3460,"target":3945},{"edgeType":"contains","source":3110,"target":3168},{"edgeType":"calls","source":471,"target":146},{"edgeType":"calls","source":4692,"target":369},{"edgeType":"calls","source":3023,"target":311},{"edgeType":"calls","source":2987,"target":370},{"edgeType":"extends","source":2068,"target":36},{"edgeType":"contains","source":2736,"target":3132},{"edgeType":"contains","source":4631,"target":4639},{"edgeType":"calls","source":7008,"target":422},{"edgeType":"calls","source":3635,"target":366},{"edgeType":"contains","source":4432,"target":4466},{"edgeType":"contains","source":6349,"target":6352},{"edgeType":"contains","source":3626,"target":4083},{"edgeType":"calls","source":6894,"target":2899},{"edgeType":"contains","source":3838,"target":3853},{"edgeType":"calls","source":4692,"target":368},{"edgeType":"calls","source":2987,"target":371},{"edgeType":"calls","source":3023,"target":312},{"edgeType":"calls","source":2269,"target":431},{"edgeType":"contains","source":2736,"target":3133},{"edgeType":"contains","source":4528,"target":4660},{"edgeType":"contains","source":4631,"target":4638},{"edgeType":"contains","source":4432,"target":4465},{"edgeType":"imports","source":5895,"target":5901},{"edgeType":"calls","source":1187,"target":1206},{"edgeType":"calls","source":4660,"target":4530},{"edgeType":"contains","source":920,"target":1293},{"edgeType":"calls","source":6725,"target":1797},{"edgeType":"calls","source":4689,"target":4688},{"edgeType":"contains","source":6250,"target":6251},{"edgeType":"contains","source":996,"target":1051},{"edgeType":"calls","source":6705,"target":303},{"edgeType":"calls","source":4008,"target":431},{"edgeType":"contains","source":6349,"target":6353},{"edgeType":"contains","source":6448,"target":6455},{"edgeType":"imports","source":4378,"target":78},{"edgeType":"calls","source":6775,"target":4475},{"edgeType":"calls","source":5035,"target":304},{"edgeType":"contains","source":1027,"target":6432},{"edgeType":"contains","source":5324,"target":5352},{"edgeType":"contains","source":3460,"target":3943},{"edgeType":"contains","source":5380,"target":5730},{"edgeType":"contains","source":2581,"target":3715},{"edgeType":"calls","source":4199,"target":4021},{"edgeType":"calls","source":3635,"target":364},{"edgeType":"contains","source":172,"target":173},{"edgeType":"calls","source":6571,"target":6572},{"edgeType":"imports","source":4378,"target":79},{"edgeType":"calls","source":6705,"target":304},{"edgeType":"calls","source":5035,"target":303},{"edgeType":"calls","source":2987,"target":368},{"edgeType":"contains","source":1229,"target":1232},{"edgeType":"calls","source":4692,"target":366},{"edgeType":"calls","source":2987,"target":369},{"edgeType":"calls","source":5660,"target":1011},{"edgeType":"contains","source":6448,"target":6449},{"edgeType":"extends","source":3739,"target":36},{"edgeType":"calls","source":6404,"target":144},{"edgeType":"calls","source":1152,"target":171},{"edgeType":"calls","source":5093,"target":4845},{"edgeType":"calls","source":942,"target":342},{"edgeType":"contains","source":5388,"target":5488},{"edgeType":"contains","source":2599,"target":3155},{"edgeType":"calls","source":1419,"target":354},{"edgeType":"contains","source":2286,"target":2288},{"edgeType":"contains","source":106,"target":107},{"edgeType":"contains","source":3110,"target":3169},{"edgeType":"calls","source":4692,"target":364},{"edgeType":"calls","source":3023,"target":307},{"edgeType":"calls","source":3055,"target":372},{"edgeType":"calls","source":2987,"target":366},{"edgeType":"contains","source":451,"target":1038},{"edgeType":"calls","source":6870,"target":6819},{"edgeType":"calls","source":6028,"target":171},{"edgeType":"contains","source":139,"target":140},{"edgeType":"imports","source":6459,"target":49},{"edgeType":"contains","source":3626,"target":4086},{"edgeType":"extends","source":602,"target":36},{"edgeType":"calls","source":883,"target":56},{"edgeType":"extends","source":3057,"target":36},{"edgeType":"calls","source":7042,"target":431},{"edgeType":"calls","source":1697,"target":1243},{"edgeType":"contains","source":1028,"target":1124},{"edgeType":"calls","source":5299,"target":571},{"edgeType":"calls","source":3720,"target":1953},{"edgeType":"contains","source":5473,"target":2859},{"edgeType":"contains","source":1854,"target":1944},{"edgeType":"calls","source":6148,"target":3849},{"edgeType":"calls","source":2083,"target":1962},{"edgeType":"calls","source":6028,"target":170},{"edgeType":"calls","source":6087,"target":455},{"edgeType":"calls","source":4800,"target":4413},{"edgeType":"contains","source":6213,"target":6346},{"edgeType":"contains","source":2055,"target":2056},{"edgeType":"contains","source":32,"target":3460},{"edgeType":"calls","source":2987,"target":364},{"edgeType":"contains","source":5116,"target":2298},{"edgeType":"contains","source":2581,"target":3719},{"edgeType":"contains","source":6770,"target":7048},{"edgeType":"extends","source":2648,"target":36},{"edgeType":"calls","source":4934,"target":1316},{"edgeType":"calls","source":1726,"target":1400},{"edgeType":"contains","source":3029,"target":4631},{"edgeType":"contains","source":3145,"target":3149},{"edgeType":"contains","source":3166,"target":3555},{"edgeType":"imports","source":1989,"target":147},{"edgeType":"contains","source":3,"target":129},{"edgeType":"contains","source":1854,"target":1945},{"edgeType":"contains","source":2055,"target":2057},{"edgeType":"calls","source":4934,"target":1315},{"edgeType":"calls","source":6595,"target":548},{"edgeType":"contains","source":4196,"target":4392},{"edgeType":"calls","source":1242,"target":548},{"edgeType":"contains","source":2581,"target":3720},{"edgeType":"calls","source":1550,"target":1570},{"edgeType":"calls","source":1350,"target":371},{"edgeType":"contains","source":6770,"target":7049},{"edgeType":"contains","source":2681,"target":2734},{"edgeType":"calls","source":3935,"target":571},{"edgeType":"contains","source":3145,"target":3146},{"edgeType":"calls","source":6108,"target":6144},{"edgeType":"contains","source":6770,"target":7050},{"edgeType":"extends","source":193,"target":36},{"edgeType":"contains","source":1229,"target":1234},{"edgeType":"calls","source":1152,"target":170},{"edgeType":"calls","source":3430,"target":370},{"edgeType":"calls","source":1241,"target":582},{"edgeType":"calls","source":5422,"target":2041},{"edgeType":"calls","source":5162,"target":588},{"edgeType":"calls","source":1881,"target":1882},{"edgeType":"imports","source":4668,"target":1650},{"edgeType":"calls","source":4259,"target":4268},{"edgeType":"calls","source":6833,"target":571},{"edgeType":"calls","source":6108,"target":6143},{"edgeType":"contains","source":3904,"target":3928},{"edgeType":"calls","source":1412,"target":565},{"edgeType":"contains","source":6770,"target":7051},{"edgeType":"contains","source":2070,"target":2647},{"edgeType":"calls","source":4934,"target":1313},{"edgeType":"calls","source":3710,"target":147},{"edgeType":"calls","source":1187,"target":1198},{"edgeType":"calls","source":3430,"target":371},{"edgeType":"contains","source":996,"target":1063},{"edgeType":"contains","source":4378,"target":5097},{"edgeType":"calls","source":2513,"target":2369},{"edgeType":"imports","source":4668,"target":1651},{"edgeType":"contains","source":1031,"target":1035},{"edgeType":"calls","source":601,"target":332},{"edgeType":"contains","source":1379,"target":2932},{"edgeType":"calls","source":6108,"target":6142},{"edgeType":"calls","source":2914,"target":509},{"edgeType":"calls","source":2797,"target":965},{"edgeType":"calls","source":3430,"target":368},{"edgeType":"calls","source":5137,"target":304},{"edgeType":"contains","source":4632,"target":4622},{"edgeType":"calls","source":1350,"target":368},{"edgeType":"calls","source":6087,"target":450},{"edgeType":"contains","source":1031,"target":1034},{"edgeType":"calls","source":1962,"target":422},{"edgeType":"contains","source":3110,"target":3181},{"edgeType":"contains","source":928,"target":6341},{"edgeType":"contains","source":1064,"target":1068},{"edgeType":"contains","source":1854,"target":1949},{"edgeType":"contains","source":3904,"target":3934},{"edgeType":"contains","source":1379,"target":2933},{"edgeType":"contains","source":6250,"target":6253},{"edgeType":"contains","source":3408,"target":3455},{"edgeType":"calls","source":6435,"target":2341},{"edgeType":"contains","source":1854,"target":1950},{"edgeType":"calls","source":3430,"target":369},{"edgeType":"calls","source":5137,"target":303},{"edgeType":"contains","source":205,"target":217},{"edgeType":"contains","source":3166,"target":3556},{"edgeType":"contains","source":3145,"target":3150},{"edgeType":"contains","source":3904,"target":3933},{"edgeType":"contains","source":5410,"target":5871},{"edgeType":"calls","source":6435,"target":2342},{"edgeType":"calls","source":4868,"target":4413},{"edgeType":"calls","source":2914,"target":507},{"edgeType":"contains","source":6250,"target":6254},{"edgeType":"contains","source":6448,"target":6458},{"edgeType":"calls","source":1350,"target":370},{"edgeType":"calls","source":3430,"target":366},{"edgeType":"calls","source":4758,"target":422},{"edgeType":"contains","source":205,"target":216},{"edgeType":"contains","source":5127,"target":5130},{"edgeType":"calls","source":601,"target":333},{"edgeType":"calls","source":1958,"target":548},{"edgeType":"calls","source":4144,"target":431},{"edgeType":"calls","source":6241,"target":6244},{"edgeType":"calls","source":6662,"target":591},{"edgeType":"calls","source":2914,"target":508},{"edgeType":"calls","source":6435,"target":2343},{"edgeType":"contains","source":3408,"target":3453},{"edgeType":"calls","source":7140,"target":572},{"edgeType":"contains","source":1989,"target":1991},{"edgeType":"contains","source":2055,"target":2059},{"edgeType":"calls","source":1350,"target":369},{"edgeType":"calls","source":1348,"target":431},{"edgeType":"calls","source":596,"target":582},{"edgeType":"imports","source":5166,"target":5029},{"edgeType":"contains","source":5324,"target":5339},{"edgeType":"calls","source":6277,"target":5226},{"edgeType":"calls","source":3715,"target":84},{"edgeType":"calls","source":3026,"target":303},{"edgeType":"contains","source":3838,"target":3839},{"edgeType":"contains","source":5686,"target":5746},{"edgeType":"calls","source":4770,"target":147},{"edgeType":"calls","source":6739,"target":2533},{"edgeType":"contains","source":5324,"target":5338},{"edgeType":"calls","source":4923,"target":4918},{"edgeType":"contains","source":3904,"target":3906},{"edgeType":"contains","source":2736,"target":3118},{"edgeType":"calls","source":3026,"target":304},{"edgeType":"contains","source":30,"target":3496},{"edgeType":"calls","source":1292,"target":146},{"edgeType":"calls","source":5454,"target":84},{"edgeType":"contains","source":920,"target":1278},{"edgeType":"contains","source":3626,"target":4066},{"edgeType":"contains","source":5732,"target":6435},{"edgeType":"calls","source":1758,"target":502},{"edgeType":"calls","source":596,"target":584},{"edgeType":"calls","source":569,"target":364},{"edgeType":"imports","source":1303,"target":49},{"edgeType":"imports","source":6111,"target":49},{"edgeType":"contains","source":6213,"target":6323},{"edgeType":"contains","source":3,"target":2222},{"edgeType":"contains","source":4432,"target":5506},{"edgeType":"contains","source":920,"target":1277},{"edgeType":"calls","source":6811,"target":303},{"edgeType":"calls","source":6059,"target":354},{"edgeType":"calls","source":5886,"target":431},{"edgeType":"calls","source":6677,"target":6572},{"edgeType":"contains","source":6213,"target":6324},{"edgeType":"calls","source":1599,"target":144},{"edgeType":"contains","source":2201,"target":2789},{"edgeType":"calls","source":5227,"target":5005},{"edgeType":"calls","source":3372,"target":146},{"edgeType":"contains","source":4432,"target":5505},{"edgeType":"calls","source":1322,"target":1332},{"edgeType":"calls","source":4770,"target":144},{"edgeType":"calls","source":1322,"target":1327},{"edgeType":"calls","source":6811,"target":304},{"edgeType":"calls","source":2045,"target":1112},{"edgeType":"calls","source":6567,"target":469},{"edgeType":"contains","source":5686,"target":5741},{"edgeType":"contains","source":920,"target":1280},{"edgeType":"contains","source":4988,"target":961},{"edgeType":"contains","source":928,"target":5260},{"edgeType":"contains","source":1691,"target":1692},{"edgeType":"contains","source":3739,"target":3741},{"edgeType":"calls","source":5227,"target":5004},{"edgeType":"calls","source":7117,"target":332},{"edgeType":"calls","source":4841,"target":56},{"edgeType":"contains","source":920,"target":1279},{"edgeType":"calls","source":1322,"target":1326},{"edgeType":"calls","source":2778,"target":588},{"edgeType":"calls","source":4763,"target":4588},{"edgeType":"contains","source":5380,"target":5720},{"edgeType":"contains","source":1691,"target":1693},{"edgeType":"calls","source":6777,"target":303},{"edgeType":"calls","source":1733,"target":212},{"edgeType":"calls","source":7117,"target":333},{"edgeType":"contains","source":102,"target":214},{"edgeType":"contains","source":30,"target":3503},{"edgeType":"contains","source":5686,"target":5743},{"edgeType":"calls","source":6496,"target":558},{"edgeType":"contains","source":920,"target":1282},{"edgeType":"calls","source":567,"target":422},{"edgeType":"contains","source":5324,"target":5341},{"edgeType":"calls","source":4396,"target":4337},{"edgeType":"calls","source":3112,"target":1859},{"edgeType":"calls","source":5246,"target":4413},{"edgeType":"calls","source":1322,"target":1329},{"edgeType":"calls","source":6777,"target":304},{"edgeType":"calls","source":5785,"target":5673},{"edgeType":"calls","source":1586,"target":1601},{"edgeType":"extends","source":4414,"target":36},{"edgeType":"calls","source":6533,"target":469},{"edgeType":"calls","source":2045,"target":1113},{"edgeType":"extends","source":3732,"target":36},{"edgeType":"contains","source":920,"target":1281},{"edgeType":"calls","source":567,"target":421},{"edgeType":"calls","source":6690,"target":888},{"edgeType":"calls","source":6541,"target":6564},{"edgeType":"contains","source":6114,"target":6218},{"edgeType":"contains","source":6213,"target":6320},{"edgeType":"extends","source":2266,"target":36},{"edgeType":"contains","source":30,"target":3505},{"edgeType":"calls","source":6418,"target":4035},{"edgeType":"calls","source":6289,"target":2732},{"edgeType":"contains","source":6280,"target":6366},{"edgeType":"calls","source":3330,"target":384},{"edgeType":"calls","source":1078,"target":431},{"edgeType":"calls","source":2848,"target":527},{"edgeType":"calls","source":2817,"target":431},{"edgeType":"calls","source":5102,"target":4647},{"edgeType":"calls","source":2246,"target":2277},{"edgeType":"calls","source":5749,"target":445},{"edgeType":"contains","source":6213,"target":6330},{"edgeType":"contains","source":30,"target":3504},{"edgeType":"calls","source":6435,"target":319},{"edgeType":"calls","source":4933,"target":4599},{"edgeType":"contains","source":4631,"target":4632},{"edgeType":"calls","source":4933,"target":371},{"edgeType":"contains","source":920,"target":1283},{"edgeType":"calls","source":2848,"target":528},{"edgeType":"calls","source":6888,"target":2151},{"edgeType":"calls","source":7012,"target":421},{"edgeType":"calls","source":4933,"target":370},{"edgeType":"calls","source":6602,"target":447},{"edgeType":"imports","source":2176,"target":2591},{"edgeType":"contains","source":37,"target":119},{"edgeType":"contains","source":41,"target":3166},{"edgeType":"calls","source":6435,"target":318},{"edgeType":"contains","source":3460,"target":3935},{"edgeType":"calls","source":3330,"target":382},{"edgeType":"contains","source":4664,"target":4665},{"edgeType":"imports","source":6213,"target":49},{"edgeType":"calls","source":5144,"target":171},{"edgeType":"calls","source":7012,"target":422},{"edgeType":"extends","source":2641,"target":36},{"edgeType":"calls","source":2511,"target":2516},{"edgeType":"contains","source":5,"target":6396},{"edgeType":"calls","source":5749,"target":443},{"edgeType":"contains","source":1691,"target":1694},{"edgeType":"calls","source":2135,"target":431},{"edgeType":"calls","source":6602,"target":448},{"edgeType":"calls","source":4933,"target":369},{"edgeType":"calls","source":4872,"target":146},{"edgeType":"contains","source":6213,"target":6332},{"edgeType":"contains","source":30,"target":3506},{"edgeType":"calls","source":3475,"target":3287},{"edgeType":"calls","source":1322,"target":1324},{"edgeType":"calls","source":6977,"target":6793},{"edgeType":"calls","source":5200,"target":548},{"edgeType":"imports","source":3047,"target":3072},{"edgeType":"calls","source":5144,"target":170},{"edgeType":"contains","source":1028,"target":1108},{"edgeType":"calls","source":4531,"target":147},{"edgeType":"contains","source":4528,"target":4651},{"edgeType":"contains","source":3673,"target":3674},{"edgeType":"extends","source":4380,"target":36},{"edgeType":"extends","source":2008,"target":1691},{"edgeType":"contains","source":3904,"target":3912},{"edgeType":"calls","source":4967,"target":371},{"edgeType":"calls","source":2826,"target":148},{"edgeType":"calls","source":2824,"target":210},{"edgeType":"calls","source":2821,"target":303},{"edgeType":"contains","source":2736,"target":3130},{"edgeType":"calls","source":4933,"target":368},{"edgeType":"contains","source":1302,"target":3188},{"edgeType":"contains","source":4002,"target":4052},{"edgeType":"calls","source":1586,"target":1591},{"edgeType":"contains","source":435,"target":468},{"edgeType":"calls","source":3330,"target":380},{"edgeType":"contains","source":4532,"target":4535},{"edgeType":"calls","source":3156,"target":488},{"edgeType":"calls","source":5162,"target":1725},{"edgeType":"contains","source":4432,"target":4464},{"edgeType":"contains","source":4432,"target":4463},{"edgeType":"calls","source":3878,"target":304},{"edgeType":"calls","source":1718,"target":1727},{"edgeType":"calls","source":529,"target":533},{"edgeType":"calls","source":6717,"target":56},{"edgeType":"calls","source":1964,"target":443},{"edgeType":"calls","source":2821,"target":304},{"edgeType":"calls","source":4967,"target":370},{"edgeType":"contains","source":6213,"target":6326},{"edgeType":"calls","source":5346,"target":4477},{"edgeType":"calls","source":3330,"target":381},{"edgeType":"calls","source":1356,"target":1321},{"edgeType":"calls","source":5117,"target":4176},{"edgeType":"calls","source":3156,"target":489},{"edgeType":"calls","source":5202,"target":4713},{"edgeType":"contains","source":4432,"target":4462},{"edgeType":"calls","source":468,"target":309},{"edgeType":"contains","source":5,"target":6397},{"edgeType":"extends","source":6460,"target":36},{"edgeType":"contains","source":5324,"target":5350},{"edgeType":"contains","source":3460,"target":3939},{"edgeType":"calls","source":4967,"target":369},{"edgeType":"calls","source":4933,"target":366},{"edgeType":"calls","source":4781,"target":5078},{"edgeType":"contains","source":4631,"target":4635},{"edgeType":"contains","source":4532,"target":4533},{"edgeType":"calls","source":3142,"target":3034},{"edgeType":"contains","source":4432,"target":4461},{"edgeType":"contains","source":920,"target":1290},{"edgeType":"calls","source":1964,"target":445},{"edgeType":"contains","source":3508,"target":3509},{"edgeType":"calls","source":6435,"target":313},{"edgeType":"contains","source":2736,"target":3129},{"edgeType":"contains","source":3460,"target":3938},{"edgeType":"calls","source":4967,"target":368},{"edgeType":"calls","source":4874,"target":3251},{"edgeType":"calls","source":2824,"target":209},{"edgeType":"calls","source":5346,"target":4475},{"edgeType":"contains","source":4528,"target":4656},{"edgeType":"calls","source":1082,"target":304},{"edgeType":"calls","source":1082,"target":303},{"edgeType":"contains","source":996,"target":1047},{"edgeType":"imports","source":599,"target":736},{"edgeType":"contains","source":4432,"target":4460},{"edgeType":"contains","source":5380,"target":1498},{"edgeType":"calls","source":3878,"target":303},{"edgeType":"calls","source":6435,"target":312},{"edgeType":"contains","source":3626,"target":4078},{"edgeType":"calls","source":6442,"target":1185},{"edgeType":"contains","source":2599,"target":3120},{"edgeType":"contains","source":2051,"target":2138},{"edgeType":"contains","source":38,"target":61},{"edgeType":"contains","source":4432,"target":5492},{"edgeType":"contains","source":2176,"target":3548},{"edgeType":"calls","source":5280,"target":210},{"edgeType":"extends","source":742,"target":745},{"edgeType":"contains","source":6213,"target":6304},{"edgeType":"contains","source":3601,"target":3770},{"edgeType":"contains","source":3030,"target":3500},{"edgeType":"calls","source":1029,"target":917},{"edgeType":"calls","source":1752,"target":1759},{"edgeType":"calls","source":6640,"target":6642},{"edgeType":"imports","source":5380,"target":1549},{"edgeType":"contains","source":3441,"target":3445},{"edgeType":"calls","source":6632,"target":548},{"edgeType":"calls","source":1521,"target":1520},{"edgeType":"calls","source":4995,"target":588},{"edgeType":"contains","source":38,"target":60},{"edgeType":"calls","source":5280,"target":209},{"edgeType":"contains","source":2051,"target":2139},{"edgeType":"contains","source":920,"target":1258},{"edgeType":"imports","source":1032,"target":1036},{"edgeType":"calls","source":6640,"target":6643},{"edgeType":"contains","source":1379,"target":2888},{"edgeType":"calls","source":601,"target":443},{"edgeType":"contains","source":3408,"target":3410},{"edgeType":"calls","source":6289,"target":2755},{"edgeType":"calls","source":1521,"target":1523},{"edgeType":"calls","source":2923,"target":339},{"edgeType":"calls","source":2914,"target":2732},{"edgeType":"contains","source":38,"target":63},{"edgeType":"calls","source":3871,"target":548},{"edgeType":"contains","source":4432,"target":5490},{"edgeType":"calls","source":5341,"target":431},{"edgeType":"contains","source":4432,"target":4433},{"edgeType":"calls","source":434,"target":338},{"edgeType":"calls","source":3271,"target":3292},{"edgeType":"contains","source":5732,"target":6419},{"edgeType":"imports","source":3047,"target":3048},{"edgeType":"calls","source":1770,"target":146},{"edgeType":"calls","source":6541,"target":6542},{"edgeType":"contains","source":3601,"target":3768},{"edgeType":"calls","source":4590,"target":458},{"edgeType":"contains","source":1379,"target":2885},{"edgeType":"contains","source":2648,"target":2657},{"edgeType":"contains","source":4002,"target":4020},{"edgeType":"contains","source":38,"target":62},{"edgeType":"contains","source":2176,"target":3547},{"edgeType":"contains","source":4432,"target":5489},{"edgeType":"calls","source":434,"target":337},{"edgeType":"extends","source":6664,"target":36},{"edgeType":"calls","source":1882,"target":1958},{"edgeType":"contains","source":1028,"target":1083},{"edgeType":"calls","source":601,"target":445},{"edgeType":"calls","source":6542,"target":170},{"edgeType":"calls","source":4941,"target":146},{"edgeType":"calls","source":4590,"target":457},{"edgeType":"contains","source":1379,"target":2886},{"edgeType":"contains","source":3441,"target":3442},{"edgeType":"contains","source":5324,"target":5327},{"edgeType":"contains","source":6770,"target":7003},{"edgeType":"calls","source":2923,"target":337},{"edgeType":"contains","source":5380,"target":5705},{"edgeType":"contains","source":4432,"target":5496},{"edgeType":"calls","source":4960,"target":4841},{"edgeType":"contains","source":2599,"target":3124},{"edgeType":"calls","source":6835,"target":601},{"edgeType":"contains","source":38,"target":65},{"edgeType":"calls","source":3955,"target":56},{"edgeType":"contains","source":3981,"target":4678},{"edgeType":"contains","source":6546,"target":6548},{"edgeType":"contains","source":6579,"target":6582},{"edgeType":"contains","source":181,"target":918},{"edgeType":"calls","source":7005,"target":5901},{"edgeType":"contains","source":2176,"target":3553},{"edgeType":"contains","source":5720,"target":5728},{"edgeType":"calls","source":3303,"target":3355},{"edgeType":"calls","source":4791,"target":4795},{"edgeType":"calls","source":6542,"target":171},{"edgeType":"contains","source":1028,"target":1086},{"edgeType":"imports","source":2050,"target":128},{"edgeType":"calls","source":2579,"target":431},{"edgeType":"contains","source":5324,"target":5326},{"edgeType":"calls","source":4347,"target":588},{"edgeType":"calls","source":2148,"target":2165},{"edgeType":"calls","source":2923,"target":338},{"edgeType":"calls","source":2084,"target":2035},{"edgeType":"contains","source":2581,"target":512},{"edgeType":"calls","source":3418,"target":2963},{"edgeType":"contains","source":4432,"target":5495},{"edgeType":"contains","source":38,"target":64},{"edgeType":"calls","source":5746,"target":558},{"edgeType":"contains","source":4002,"target":4026},{"edgeType":"calls","source":535,"target":371},{"edgeType":"contains","source":920,"target":1262},{"edgeType":"calls","source":3303,"target":3356},{"edgeType":"calls","source":6047,"target":1797},{"edgeType":"contains","source":3408,"target":3414},{"edgeType":"calls","source":6495,"target":572},{"edgeType":"calls","source":4874,"target":3278},{"edgeType":"calls","source":2784,"target":2533},{"edgeType":"contains","source":2736,"target":3106},{"edgeType":"calls","source":4688,"target":588},{"edgeType":"contains","source":5324,"target":5325},{"edgeType":"contains","source":2599,"target":3122},{"edgeType":"contains","source":4432,"target":5494},{"edgeType":"calls","source":1354,"target":1411},{"edgeType":"contains","source":2051,"target":2140},{"edgeType":"contains","source":38,"target":67},{"edgeType":"contains","source":2176,"target":3550},{"edgeType":"calls","source":5746,"target":557},{"edgeType":"contains","source":2879,"target":3955},{"edgeType":"calls","source":5411,"target":371},{"edgeType":"calls","source":6606,"target":303},{"edgeType":"calls","source":6495,"target":573},{"edgeType":"calls","source":2897,"target":84},{"edgeType":"contains","source":3408,"target":3413},{"edgeType":"contains","source":5195,"target":6152},{"edgeType":"imports","source":130,"target":452},{"edgeType":"contains","source":2599,"target":3123},{"edgeType":"contains","source":4432,"target":5493},{"edgeType":"contains","source":38,"target":66},{"edgeType":"calls","source":5746,"target":556},{"edgeType":"contains","source":41,"target":3145},{"edgeType":"contains","source":3601,"target":3771},{"edgeType":"calls","source":6606,"target":304},{"edgeType":"calls","source":5411,"target":370},{"edgeType":"contains","source":3408,"target":3412},{"edgeType":"contains","source":3441,"target":3446},{"edgeType":"contains","source":1228,"target":1229},{"edgeType":"contains","source":6513,"target":6526},{"edgeType":"contains","source":451,"target":1008},{"edgeType":"contains","source":3366,"target":1549},{"edgeType":"calls","source":1758,"target":508},{"edgeType":"contains","source":38,"target":69},{"edgeType":"contains","source":5686,"target":5737},{"edgeType":"contains","source":1415,"target":1779},{"edgeType":"contains","source":1379,"target":2895},{"edgeType":"contains","source":38,"target":70},{"edgeType":"calls","source":569,"target":371},{"edgeType":"calls","source":2612,"target":2575},{"edgeType":"calls","source":535,"target":368},{"edgeType":"calls","source":5411,"target":369},{"edgeType":"calls","source":3349,"target":2982},{"edgeType":"calls","source":1121,"target":171},{"edgeType":"imports","source":2750,"target":2752},{"edgeType":"contains","source":2599,"target":3128},{"edgeType":"calls","source":1192,"target":84},{"edgeType":"contains","source":1032,"target":2023},{"edgeType":"calls","source":4729,"target":371},{"edgeType":"contains","source":6770,"target":7015},{"edgeType":"calls","source":1758,"target":507},{"edgeType":"calls","source":2268,"target":555},{"edgeType":"contains","source":4432,"target":5499},{"edgeType":"calls","source":5316,"target":142},{"edgeType":"contains","source":3166,"target":3522},{"edgeType":"contains","source":5324,"target":5330},{"edgeType":"contains","source":5686,"target":5738},{"edgeType":"contains","source":3366,"target":1550},{"edgeType":"calls","source":1755,"target":1657},{"edgeType":"calls","source":6884,"target":144},{"edgeType":"calls","source":3933,"target":3906},{"edgeType":"contains","source":3,"target":2210},{"edgeType":"contains","source":38,"target":68},{"edgeType":"contains","source":1379,"target":2896},{"edgeType":"contains","source":30,"target":3488},{"edgeType":"calls","source":5672,"target":733},{"edgeType":"calls","source":569,"target":370},{"edgeType":"calls","source":3481,"target":1005},{"edgeType":"calls","source":7068,"target":7125},{"edgeType":"calls","source":5411,"target":368},{"edgeType":"calls","source":4729,"target":370},{"edgeType":"calls","source":1222,"target":210},{"edgeType":"calls","source":2613,"target":431},{"edgeType":"calls","source":1121,"target":170},{"edgeType":"contains","source":928,"target":5250},{"edgeType":"calls","source":6913,"target":303},{"edgeType":"contains","source":4432,"target":5498},{"edgeType":"contains","source":5324,"target":5329},{"edgeType":"contains","source":336,"target":347},{"edgeType":"calls","source":4401,"target":4194},{"edgeType":"contains","source":5388,"target":5459},{"edgeType":"calls","source":1439,"target":886},{"edgeType":"calls","source":4202,"target":4021},{"edgeType":"calls","source":5746,"target":553},{"edgeType":"contains","source":2070,"target":2612},{"edgeType":"contains","source":2051,"target":2144},{"edgeType":"calls","source":1666,"target":1248},{"edgeType":"calls","source":6602,"target":431},{"edgeType":"calls","source":535,"target":370},{"edgeType":"contains","source":38,"target":72},{"edgeType":"contains","source":3,"target":100},{"edgeType":"calls","source":5672,"target":732},{"edgeType":"contains","source":1379,"target":2893},{"edgeType":"contains","source":885,"target":1297},{"edgeType":"contains","source":920,"target":1269},{"edgeType":"calls","source":3271,"target":3284},{"edgeType":"calls","source":4729,"target":369},{"edgeType":"contains","source":3043,"target":2046},{"edgeType":"calls","source":6913,"target":304},{"edgeType":"contains","source":3166,"target":3520},{"edgeType":"extends","source":5607,"target":36},{"edgeType":"calls","source":2313,"target":215},{"edgeType":"calls","source":4401,"target":4193},{"edgeType":"contains","source":336,"target":346},{"edgeType":"contains","source":4432,"target":5497},{"edgeType":"calls","source":4415,"target":588},{"edgeType":"calls","source":1758,"target":509},{"edgeType":"contains","source":2070,"target":2613},{"edgeType":"contains","source":38,"target":71},{"edgeType":"contains","source":2070,"target":2614},{"edgeType":"calls","source":535,"target":369},{"edgeType":"calls","source":6145,"target":6152},{"edgeType":"contains","source":6084,"target":6087},{"edgeType":"contains","source":1379,"target":2894},{"edgeType":"contains","source":3043,"target":2047},{"edgeType":"calls","source":4729,"target":368},{"edgeType":"calls","source":5411,"target":366},{"edgeType":"contains","source":2599,"target":3127},{"edgeType":"calls","source":1758,"target":504},{"edgeType":"calls","source":6887,"target":1111},{"edgeType":"calls","source":2579,"target":422},{"edgeType":"contains","source":3030,"target":1399},{"edgeType":"calls","source":4729,"target":366},{"edgeType":"calls","source":569,"target":366},{"edgeType":"calls","source":4176,"target":596},{"edgeType":"contains","source":2736,"target":3113},{"edgeType":"extends","source":2125,"target":167},{"edgeType":"contains","source":5686,"target":5733},{"edgeType":"contains","source":38,"target":74},{"edgeType":"contains","source":2201,"target":2786},{"edgeType":"contains","source":4631,"target":4620},{"edgeType":"calls","source":5002,"target":4588},{"edgeType":"contains","source":4432,"target":5503},{"edgeType":"calls","source":1758,"target":503},{"edgeType":"calls","source":3682,"target":56},{"edgeType":"contains","source":5324,"target":5334},{"edgeType":"contains","source":3460,"target":3924},{"edgeType":"calls","source":6568,"target":431},{"edgeType":"contains","source":38,"target":73},{"edgeType":"calls","source":4781,"target":5096},{"edgeType":"contains","source":4003,"target":4004},{"edgeType":"contains","source":4139,"target":1902},{"edgeType":"calls","source":3348,"target":1953},{"edgeType":"calls","source":5411,"target":364},{"edgeType":"contains","source":4691,"target":4873},{"edgeType":"calls","source":6887,"target":56},{"edgeType":"calls","source":1758,"target":506},{"edgeType":"calls","source":4729,"target":364},{"edgeType":"contains","source":3166,"target":3523},{"edgeType":"contains","source":5732,"target":6423},{"edgeType":"contains","source":5380,"target":2540},{"edgeType":"calls","source":2086,"target":1962},{"edgeType":"calls","source":5635,"target":1875},{"edgeType":"calls","source":569,"target":369},{"edgeType":"extends","source":6630,"target":36},{"edgeType":"contains","source":6286,"target":4048},{"edgeType":"calls","source":537,"target":304},{"edgeType":"calls","source":535,"target":366},{"edgeType":"contains","source":38,"target":76},{"edgeType":"calls","source":1222,"target":209},{"edgeType":"calls","source":881,"target":210},{"edgeType":"calls","source":1758,"target":505},{"edgeType":"calls","source":5245,"target":4451},{"edgeType":"contains","source":4432,"target":5501},{"edgeType":"calls","source":6690,"target":1936},{"edgeType":"calls","source":2579,"target":421},{"edgeType":"calls","source":535,"target":364},{"edgeType":"contains","source":5324,"target":5332},{"edgeType":"calls","source":6690,"target":879},{"edgeType":"extends","source":1736,"target":1654},{"edgeType":"contains","source":5686,"target":5736},{"edgeType":"contains","source":1302,"target":5285},{"edgeType":"contains","source":38,"target":75},{"edgeType":"calls","source":5513,"target":4599},{"edgeType":"contains","source":1988,"target":1989},{"edgeType":"contains","source":3,"target":103},{"edgeType":"calls","source":537,"target":303},{"edgeType":"calls","source":569,"target":368},{"edgeType":"calls","source":881,"target":209},{"edgeType":"calls","source":7136,"target":7137},{"edgeType":"contains","source":2176,"target":3560},{"edgeType":"calls","source":3349,"target":2977},{"edgeType":"calls","source":6133,"target":144},{"edgeType":"calls","source":2610,"target":481},{"edgeType":"calls","source":4726,"target":422},{"edgeType":"contains","source":1037,"target":1844},{"edgeType":"calls","source":1825,"target":504},{"edgeType":"calls","source":1109,"target":502},{"edgeType":"calls","source":330,"target":339},{"edgeType":"extends","source":5363,"target":2359},{"edgeType":"calls","source":4394,"target":144},{"edgeType":"contains","source":1415,"target":1754},{"edgeType":"contains","source":1379,"target":2870},{"edgeType":"calls","source":4363,"target":3219},{"edgeType":"contains","source":4002,"target":4007},{"edgeType":"calls","source":6837,"target":6861},{"edgeType":"calls","source":4994,"target":571},{"edgeType":"contains","source":4397,"target":4446},{"edgeType":"contains","source":6213,"target":6288},{"edgeType":"calls","source":4726,"target":421},{"edgeType":"calls","source":1825,"target":503},{"edgeType":"contains","source":920,"target":1242},{"edgeType":"calls","source":330,"target":338},{"edgeType":"contains","source":3460,"target":3895},{"edgeType":"calls","source":4932,"target":4606},{"edgeType":"calls","source":5885,"target":431},{"edgeType":"imports","source":6111,"target":79},{"edgeType":"calls","source":1825,"target":502},{"edgeType":"calls","source":1695,"target":304},{"edgeType":"contains","source":4397,"target":4445},{"edgeType":"contains","source":4397,"target":4444},{"edgeType":"contains","source":5,"target":6355},{"edgeType":"calls","source":1109,"target":504},{"edgeType":"calls","source":3271,"target":3243},{"edgeType":"calls","source":3872,"target":2582},{"edgeType":"calls","source":4182,"target":371},{"edgeType":"calls","source":1825,"target":506},{"edgeType":"calls","source":3972,"target":3710},{"edgeType":"calls","source":595,"target":582},{"edgeType":"contains","source":3460,"target":3894},{"edgeType":"calls","source":2610,"target":479},{"edgeType":"calls","source":2305,"target":421},{"edgeType":"contains","source":6213,"target":6290},{"edgeType":"calls","source":1586,"target":1572},{"edgeType":"imports","source":3981,"target":575},{"edgeType":"calls","source":3677,"target":170},{"edgeType":"calls","source":2610,"target":480},{"edgeType":"calls","source":3272,"target":3213},{"edgeType":"calls","source":4832,"target":304},{"edgeType":"calls","source":1109,"target":503},{"edgeType":"calls","source":1825,"target":505},{"edgeType":"calls","source":6055,"target":445},{"edgeType":"contains","source":3460,"target":3893},{"edgeType":"contains","source":1379,"target":2869},{"edgeType":"calls","source":4734,"target":171},{"edgeType":"calls","source":3677,"target":171},{"edgeType":"extends","source":3563,"target":1076},{"edgeType":"calls","source":2246,"target":2251},{"edgeType":"calls","source":2305,"target":422},{"edgeType":"calls","source":7047,"target":354},{"edgeType":"calls","source":5162,"target":1702},{"edgeType":"contains","source":2051,"target":2121},{"edgeType":"imports","source":2050,"target":179},{"edgeType":"contains","source":2119,"target":2127},{"edgeType":"contains","source":6213,"target":6291},{"edgeType":"calls","source":1258,"target":1169},{"edgeType":"calls","source":4832,"target":303},{"edgeType":"calls","source":4182,"target":369},{"edgeType":"contains","source":5884,"target":5912},{"edgeType":"calls","source":6569,"target":4602},{"edgeType":"calls","source":6688,"target":913},{"edgeType":"calls","source":2610,"target":477},{"edgeType":"calls","source":4734,"target":170},{"edgeType":"imports","source":4717,"target":2072},{"edgeType":"calls","source":1603,"target":1039},{"edgeType":"calls","source":1600,"target":1132},{"edgeType":"extends","source":4722,"target":36},{"edgeType":"calls","source":1824,"target":530},{"edgeType":"contains","source":4100,"target":4144},{"edgeType":"calls","source":6055,"target":443},{"edgeType":"contains","source":4397,"target":4450},{"edgeType":"calls","source":5245,"target":4413},{"edgeType":"contains","source":2176,"target":3537},{"edgeType":"calls","source":4182,"target":370},{"edgeType":"calls","source":2610,"target":478},{"edgeType":"calls","source":4752,"target":1725},{"edgeType":"calls","source":2279,"target":2283},{"edgeType":"contains","source":4717,"target":5099},{"edgeType":"imports","source":1303,"target":79},{"edgeType":"contains","source":4432,"target":5478},{"edgeType":"calls","source":6840,"target":431},{"edgeType":"contains","source":2312,"target":2492},{"edgeType":"contains","source":5,"target":3185},{"edgeType":"contains","source":1947,"target":2180},{"edgeType":"imports","source":6245,"target":157},{"edgeType":"calls","source":6474,"target":6492},{"edgeType":"calls","source":6728,"target":732},{"edgeType":"calls","source":1156,"target":1157},{"edgeType":"contains","source":5884,"target":5914},{"edgeType":"contains","source":1379,"target":1815},{"edgeType":"calls","source":330,"target":337},{"edgeType":"contains","source":3460,"target":3898},{"edgeType":"contains","source":5285,"target":5460},{"edgeType":"contains","source":6770,"target":6988},{"edgeType":"imports","source":1303,"target":78},{"edgeType":"contains","source":4432,"target":5477},{"edgeType":"calls","source":1695,"target":303},{"edgeType":"contains","source":2879,"target":3940},{"edgeType":"calls","source":6728,"target":733},{"edgeType":"calls","source":1312,"target":548},{"edgeType":"calls","source":4182,"target":368},{"edgeType":"calls","source":5519,"target":144},{"edgeType":"calls","source":6494,"target":588},{"edgeType":"contains","source":996,"target":1006},{"edgeType":"calls","source":4932,"target":4599},{"edgeType":"calls","source":2610,"target":476},{"edgeType":"contains","source":6114,"target":5128},{"edgeType":"imports","source":5410,"target":3847},{"edgeType":"imports","source":2736,"target":49},{"edgeType":"contains","source":2312,"target":2490},{"edgeType":"contains","source":2119,"target":2131},{"edgeType":"contains","source":2176,"target":3535},{"edgeType":"calls","source":3303,"target":3302},{"edgeType":"contains","source":2176,"target":3540},{"edgeType":"calls","source":5075,"target":165},{"edgeType":"calls","source":3292,"target":472},{"edgeType":"calls","source":1008,"target":454},{"edgeType":"calls","source":3193,"target":370},{"edgeType":"calls","source":4591,"target":371},{"edgeType":"contains","source":4459,"target":4646},{"edgeType":"contains","source":4432,"target":5483},{"edgeType":"contains","source":3626,"target":4044},{"edgeType":"contains","source":3601,"target":3762},{"edgeType":"calls","source":7117,"target":303},{"edgeType":"calls","source":6975,"target":6819},{"edgeType":"contains","source":5679,"target":3824},{"edgeType":"contains","source":5732,"target":6409},{"edgeType":"calls","source":4930,"target":431},{"edgeType":"contains","source":2050,"target":2162},{"edgeType":"calls","source":4182,"target":366},{"edgeType":"contains","source":3460,"target":3903},{"edgeType":"contains","source":2648,"target":2651},{"edgeType":"extends","source":5029,"target":36},{"edgeType":"imports","source":6213,"target":79},{"edgeType":"contains","source":2879,"target":3946},{"edgeType":"contains","source":2844,"target":2917},{"edgeType":"calls","source":5075,"target":164},{"edgeType":"calls","source":6976,"target":447},{"edgeType":"contains","source":4432,"target":5482},{"edgeType":"calls","source":3193,"target":371},{"edgeType":"calls","source":4591,"target":370},{"edgeType":"contains","source":5686,"target":5722},{"edgeType":"calls","source":7117,"target":304},{"edgeType":"contains","source":38,"target":55},{"edgeType":"imports","source":6245,"target":147},{"edgeType":"calls","source":2963,"target":1155},{"edgeType":"calls","source":4591,"target":4597},{"edgeType":"calls","source":3342,"target":2091},{"edgeType":"imports","source":2736,"target":2177},{"edgeType":"calls","source":3193,"target":368},{"edgeType":"calls","source":6976,"target":448},{"edgeType":"calls","source":2509,"target":431},{"edgeType":"calls","source":4591,"target":369},{"edgeType":"calls","source":2006,"target":171},{"edgeType":"contains","source":38,"target":54},{"edgeType":"extends","source":2924,"target":2925},{"edgeType":"calls","source":4182,"target":364},{"edgeType":"calls","source":3609,"target":157},{"edgeType":"calls","source":3342,"target":2092},{"edgeType":"imports","source":5380,"target":537},{"edgeType":"contains","source":1379,"target":2877},{"edgeType":"calls","source":6955,"target":6385},{"edgeType":"contains","source":2648,"target":2649},{"edgeType":"contains","source":2681,"target":2683},{"edgeType":"contains","source":6476,"target":6602},{"edgeType":"contains","source":6546,"target":6547},{"edgeType":"calls","source":4591,"target":368},{"edgeType":"calls","source":3193,"target":369},{"edgeType":"calls","source":7011,"target":421},{"edgeType":"contains","source":4397,"target":4451},{"edgeType":"calls","source":1793,"target":431},{"edgeType":"contains","source":5720,"target":5727},{"edgeType":"contains","source":2050,"target":2160},{"edgeType":"contains","source":1947,"target":2182},{"edgeType":"calls","source":2006,"target":170},{"edgeType":"contains","source":4002,"target":4012},{"edgeType":"calls","source":5546,"target":4587},{"edgeType":"contains","source":38,"target":57},{"edgeType":"calls","source":4934,"target":304},{"edgeType":"calls","source":6440,"target":1185},{"edgeType":"calls","source":2963,"target":1153},{"edgeType":"contains","source":2844,"target":2920},{"edgeType":"contains","source":2813,"target":2824},{"edgeType":"contains","source":4432,"target":5487},{"edgeType":"calls","source":6839,"target":469},{"edgeType":"calls","source":7011,"target":422},{"edgeType":"calls","source":4655,"target":1554},{"edgeType":"calls","source":5747,"target":5755},{"edgeType":"contains","source":6213,"target":6292},{"edgeType":"contains","source":1379,"target":2883},{"edgeType":"contains","source":3601,"target":3766},{"edgeType":"calls","source":4126,"target":4210},{"edgeType":"contains","source":2681,"target":2689},{"edgeType":"contains","source":1303,"target":2068},{"edgeType":"contains","source":38,"target":56},{"edgeType":"contains","source":6213,"target":6293},{"edgeType":"calls","source":4892,"target":548},{"edgeType":"calls","source":4934,"target":303},{"edgeType":"calls","source":2998,"target":1126},{"edgeType":"contains","source":2176,"target":3545},{"edgeType":"contains","source":6744,"target":6745},{"edgeType":"calls","source":3193,"target":366},{"edgeType":"contains","source":4432,"target":5486},{"edgeType":"calls","source":4591,"target":366},{"edgeType":"extends","source":2540,"target":36},{"edgeType":"calls","source":6708,"target":303},{"edgeType":"contains","source":5720,"target":5721},{"edgeType":"calls","source":6542,"target":164},{"edgeType":"calls","source":4126,"target":4211},{"edgeType":"contains","source":38,"target":59},{"edgeType":"calls","source":5502,"target":4892},{"edgeType":"contains","source":6213,"target":6294},{"edgeType":"contains","source":2176,"target":3542},{"edgeType":"imports","source":5592,"target":5596},{"edgeType":"contains","source":2844,"target":2918},{"edgeType":"contains","source":2813,"target":2822},{"edgeType":"calls","source":5339,"target":431},{"edgeType":"calls","source":1770,"target":84},{"edgeType":"contains","source":4432,"target":5485},{"edgeType":"contains","source":920,"target":1257},{"edgeType":"contains","source":3606,"target":3609},{"edgeType":"calls","source":530,"target":471},{"edgeType":"contains","source":1558,"target":1560},{"edgeType":"imports","source":6111,"target":78},{"edgeType":"calls","source":1963,"target":1500},{"edgeType":"calls","source":6708,"target":304},{"edgeType":"contains","source":5463,"target":3121},{"edgeType":"imports","source":4502,"target":4503},{"edgeType":"calls","source":6542,"target":165},{"edgeType":"calls","source":2877,"target":1704},{"edgeType":"contains","source":2070,"target":2601},{"edgeType":"calls","source":1354,"target":1352},{"edgeType":"contains","source":38,"target":58},{"edgeType":"calls","source":1533,"target":1088},{"edgeType":"calls","source":6915,"target":6572},{"edgeType":"contains","source":6213,"target":6295},{"edgeType":"contains","source":2844,"target":2919},{"edgeType":"calls","source":3193,"target":364},{"edgeType":"calls","source":6640,"target":6641},{"edgeType":"contains","source":4432,"target":5484},{"edgeType":"contains","source":920,"target":1256},{"edgeType":"contains","source":1558,"target":1561},{"edgeType":"calls","source":4591,"target":364},{"edgeType":"contains","source":3738,"target":3744},{"edgeType":"calls","source":5144,"target":165},{"edgeType":"calls","source":5134,"target":475},{"edgeType":"contains","source":1854,"target":1870},{"edgeType":"calls","source":4933,"target":364},{"edgeType":"contains","source":2844,"target":2891},{"edgeType":"contains","source":6213,"target":6271},{"edgeType":"contains","source":5732,"target":6384},{"edgeType":"calls","source":6609,"target":171},{"edgeType":"calls","source":6494,"target":565},{"edgeType":"calls","source":6435,"target":311},{"edgeType":"contains","source":1302,"target":2070},{"edgeType":"calls","source":6464,"target":469},{"edgeType":"calls","source":5144,"target":164},{"edgeType":"calls","source":5134,"target":474},{"edgeType":"imports","source":4717,"target":996},{"edgeType":"calls","source":4967,"target":366},{"edgeType":"calls","source":1011,"target":384},{"edgeType":"contains","source":2070,"target":2574},{"edgeType":"contains","source":5,"target":5278},{"edgeType":"calls","source":4871,"target":171},{"edgeType":"contains","source":5380,"target":2495},{"edgeType":"contains","source":3460,"target":3879},{"edgeType":"calls","source":5134,"target":473},{"edgeType":"calls","source":5656,"target":147},{"edgeType":"calls","source":1586,"target":1589},{"edgeType":"contains","source":5895,"target":3447},{"edgeType":"contains","source":4307,"target":5103},{"edgeType":"contains","source":2581,"target":2586},{"edgeType":"calls","source":1718,"target":1725},{"edgeType":"calls","source":6732,"target":588},{"edgeType":"calls","source":4781,"target":5074},{"edgeType":"contains","source":1032,"target":1984},{"edgeType":"calls","source":4871,"target":170},{"edgeType":"contains","source":1814,"target":2051},{"edgeType":"contains","source":1415,"target":1736},{"edgeType":"calls","source":4599,"target":146},{"edgeType":"calls","source":4530,"target":171},{"edgeType":"contains","source":3440,"target":3441},{"edgeType":"extends","source":3596,"target":36},{"edgeType":"calls","source":6872,"target":6819},{"edgeType":"contains","source":2051,"target":2104},{"edgeType":"contains","source":1947,"target":2157},{"edgeType":"calls","source":5656,"target":146},{"edgeType":"contains","source":41,"target":2050},{"edgeType":"contains","source":2843,"target":2921},{"edgeType":"contains","source":6213,"target":6274},{"edgeType":"calls","source":1685,"target":1690},{"edgeType":"contains","source":5884,"target":5903},{"edgeType":"calls","source":1586,"target":1588},{"edgeType":"calls","source":1121,"target":147},{"edgeType":"calls","source":1124,"target":1111},{"edgeType":"calls","source":4700,"target":4413},{"edgeType":"calls","source":1718,"target":1724},{"edgeType":"contains","source":2899,"target":3299},{"edgeType":"calls","source":4781,"target":5073},{"edgeType":"calls","source":4967,"target":364},{"edgeType":"calls","source":2610,"target":2611},{"edgeType":"contains","source":3473,"target":3474},{"edgeType":"calls","source":4530,"target":170},{"edgeType":"contains","source":6213,"target":6267},{"edgeType":"calls","source":1011,"target":381},{"edgeType":"contains","source":1815,"target":2026},{"edgeType":"calls","source":1665,"target":1248},{"edgeType":"contains","source":4091,"target":4406},{"edgeType":"calls","source":5643,"target":548},{"edgeType":"calls","source":534,"target":370},{"edgeType":"calls","source":3430,"target":442},{"edgeType":"calls","source":1959,"target":590},{"edgeType":"contains","source":3460,"target":3884},{"edgeType":"contains","source":5884,"target":5896},{"edgeType":"calls","source":3181,"target":2876},{"edgeType":"calls","source":6647,"target":1111},{"edgeType":"contains","source":5616,"target":5748},{"edgeType":"calls","source":6435,"target":307},{"edgeType":"contains","source":5686,"target":5692},{"edgeType":"calls","source":4781,"target":5072},{"edgeType":"contains","source":6213,"target":6268},{"edgeType":"calls","source":1011,"target":380},{"edgeType":"calls","source":4321,"target":304},{"edgeType":"calls","source":6852,"target":1099},{"edgeType":"calls","source":5509,"target":2587},{"edgeType":"contains","source":4091,"target":4405},{"edgeType":"contains","source":4196,"target":4321},{"edgeType":"calls","source":534,"target":369},{"edgeType":"calls","source":1209,"target":584},{"edgeType":"contains","source":5884,"target":5897},{"edgeType":"calls","source":3272,"target":56},{"edgeType":"calls","source":4781,"target":5071},{"edgeType":"contains","source":3473,"target":3480},{"edgeType":"contains","source":5686,"target":5693},{"edgeType":"contains","source":5356,"target":5357},{"edgeType":"calls","source":4321,"target":303},{"edgeType":"calls","source":5656,"target":1200},{"edgeType":"contains","source":2070,"target":2575},{"edgeType":"imports","source":6213,"target":78},{"edgeType":"contains","source":5686,"target":5694},{"edgeType":"calls","source":3298,"target":304},{"edgeType":"calls","source":3328,"target":431},{"edgeType":"contains","source":5884,"target":5898},{"edgeType":"calls","source":4901,"target":3464},{"edgeType":"contains","source":3473,"target":3479},{"edgeType":"calls","source":4781,"target":5070},{"edgeType":"calls","source":468,"target":304},{"edgeType":"contains","source":928,"target":5212},{"edgeType":"contains","source":1815,"target":2025},{"edgeType":"calls","source":1011,"target":382},{"edgeType":"calls","source":5336,"target":548},{"edgeType":"calls","source":6825,"target":1938},{"edgeType":"contains","source":6213,"target":6270},{"edgeType":"contains","source":2176,"target":3518},{"edgeType":"extends","source":6699,"target":36},{"edgeType":"calls","source":6838,"target":6820},{"edgeType":"contains","source":5732,"target":6383},{"edgeType":"calls","source":534,"target":371},{"edgeType":"calls","source":4183,"target":353},{"edgeType":"contains","source":5884,"target":5899},{"edgeType":"calls","source":6408,"target":84},{"edgeType":"contains","source":3473,"target":3478},{"edgeType":"calls","source":4922,"target":4926},{"edgeType":"calls","source":4781,"target":5069},{"edgeType":"calls","source":468,"target":303},{"edgeType":"calls","source":5202,"target":4701},{"edgeType":"calls","source":4370,"target":1953},{"edgeType":"calls","source":2246,"target":146},{"edgeType":"calls","source":2248,"target":84},{"edgeType":"contains","source":41,"target":6286},{"edgeType":"contains","source":2051,"target":2113},{"edgeType":"calls","source":1805,"target":1132},{"edgeType":"calls","source":4044,"target":431},{"edgeType":"contains","source":3460,"target":3888},{"edgeType":"contains","source":2119,"target":2120},{"edgeType":"calls","source":5681,"target":422},{"edgeType":"calls","source":3272,"target":3222},{"edgeType":"calls","source":534,"target":366},{"edgeType":"calls","source":2616,"target":304},{"edgeType":"calls","source":4726,"target":431},{"edgeType":"calls","source":5103,"target":371},{"edgeType":"contains","source":453,"target":912},{"edgeType":"contains","source":3110,"target":3111},{"edgeType":"calls","source":2471,"target":571},{"edgeType":"contains","source":1947,"target":2167},{"edgeType":"contains","source":1420,"target":1592},{"edgeType":"calls","source":6090,"target":5712},{"edgeType":"calls","source":3272,"target":3223},{"edgeType":"calls","source":5546,"target":4606},{"edgeType":"calls","source":5681,"target":421},{"edgeType":"calls","source":5103,"target":370},{"edgeType":"calls","source":3298,"target":303},{"edgeType":"imports","source":6245,"target":128},{"edgeType":"contains","source":2581,"target":2597},{"edgeType":"calls","source":1109,"target":509},{"edgeType":"contains","source":1037,"target":1838},{"edgeType":"calls","source":2370,"target":528},{"edgeType":"contains","source":453,"target":915},{"edgeType":"calls","source":1486,"target":1510},{"edgeType":"calls","source":1532,"target":84},{"edgeType":"calls","source":6837,"target":6854},{"edgeType":"calls","source":1959,"target":588},{"edgeType":"calls","source":2731,"target":965},{"edgeType":"imports","source":6074,"target":147},{"edgeType":"calls","source":6371,"target":171},{"edgeType":"calls","source":534,"target":368},{"edgeType":"calls","source":5103,"target":369},{"edgeType":"calls","source":4956,"target":4926},{"edgeType":"contains","source":1238,"target":1946},{"edgeType":"contains","source":3030,"target":3473},{"edgeType":"calls","source":3153,"target":568},{"edgeType":"calls","source":5785,"target":5652},{"edgeType":"contains","source":5884,"target":5911},{"edgeType":"imports","source":4307,"target":2072},{"edgeType":"calls","source":4384,"target":3630},{"edgeType":"contains","source":453,"target":914},{"edgeType":"calls","source":7108,"target":568},{"edgeType":"contains","source":3,"target":1122},{"edgeType":"calls","source":6371,"target":170},{"edgeType":"calls","source":6242,"target":5226},{"edgeType":"contains","source":1420,"target":1590},{"edgeType":"calls","source":1414,"target":569},{"edgeType":"calls","source":2616,"target":303},{"edgeType":"calls","source":2806,"target":1812},{"edgeType":"calls","source":5103,"target":368},{"edgeType":"calls","source":1825,"target":508},{"edgeType":"calls","source":1093,"target":1002},{"edgeType":"calls","source":1109,"target":506},{"edgeType":"calls","source":468,"target":293},{"edgeType":"contains","source":6610,"target":6653},{"edgeType":"calls","source":4729,"target":333},{"edgeType":"contains","source":1947,"target":2170},{"edgeType":"calls","source":4448,"target":588},{"edgeType":"calls","source":4347,"target":548},{"edgeType":"contains","source":1815,"target":2034},{"edgeType":"calls","source":3609,"target":170},{"edgeType":"calls","source":7069,"target":7064},{"edgeType":"contains","source":1947,"target":2171},{"edgeType":"contains","source":453,"target":917},{"edgeType":"imports","source":3145,"target":49},{"edgeType":"calls","source":1825,"target":507},{"edgeType":"contains","source":1037,"target":1839},{"edgeType":"calls","source":1109,"target":505},{"edgeType":"contains","source":453,"target":916},{"edgeType":"calls","source":4729,"target":332},{"edgeType":"calls","source":4794,"target":431},{"edgeType":"contains","source":3030,"target":3481},{"edgeType":"contains","source":41,"target":5232},{"edgeType":"contains","source":5,"target":6348},{"edgeType":"contains","source":5748,"target":5893},{"edgeType":"calls","source":2370,"target":527},{"edgeType":"calls","source":6774,"target":354},{"edgeType":"contains","source":3460,"target":3891},{"edgeType":"contains","source":1947,"target":2172},{"edgeType":"calls","source":3609,"target":171},{"edgeType":"calls","source":5103,"target":366},{"edgeType":"contains","source":3110,"target":3112},{"edgeType":"contains","source":162,"target":6769},{"edgeType":"contains","source":1028,"target":1064},{"edgeType":"imports","source":4091,"target":315},{"edgeType":"contains","source":1037,"target":1842},{"edgeType":"calls","source":1959,"target":584},{"edgeType":"contains","source":1947,"target":2168},{"edgeType":"imports","source":42,"target":49},{"edgeType":"contains","source":5884,"target":5906},{"edgeType":"contains","source":2119,"target":2122},{"edgeType":"imports","source":6604,"target":1691},{"edgeType":"contains","source":1420,"target":1593},{"edgeType":"calls","source":7069,"target":7066},{"edgeType":"calls","source":5063,"target":548},{"edgeType":"calls","source":2983,"target":548},{"edgeType":"calls","source":534,"target":364},{"edgeType":"contains","source":6770,"target":6980},{"edgeType":"calls","source":1109,"target":508},{"edgeType":"contains","source":6610,"target":6656},{"edgeType":"calls","source":1825,"target":509},{"edgeType":"contains","source":920,"target":1240},{"edgeType":"calls","source":4865,"target":342},{"edgeType":"extends","source":2126,"target":167},{"edgeType":"calls","source":6567,"target":431},{"edgeType":"contains","source":5884,"target":5907},{"edgeType":"contains","source":3460,"target":3889},{"edgeType":"contains","source":5,"target":8},{"edgeType":"contains","source":1420,"target":1594},{"edgeType":"contains","source":3440,"target":3452},{"edgeType":"calls","source":5103,"target":364},{"edgeType":"calls","source":749,"target":1097},{"edgeType":"calls","source":600,"target":431},{"edgeType":"contains","source":2581,"target":2599},{"edgeType":"calls","source":2996,"target":146},{"edgeType":"calls","source":1109,"target":507},{"edgeType":"calls","source":1094,"target":1066},{"edgeType":"calls","source":1697,"target":1400},{"edgeType":"calls","source":1761,"target":473},{"edgeType":"contains","source":2879,"target":3904},{"edgeType":"contains","source":3236,"target":3407},{"edgeType":"contains","source":4717,"target":5063},{"edgeType":"calls","source":6281,"target":5168},{"edgeType":"calls","source":887,"target":84},{"edgeType":"contains","source":2051,"target":2089},{"edgeType":"contains","source":2070,"target":2557},{"edgeType":"contains","source":36,"target":74},{"edgeType":"contains","source":6214,"target":6224},{"edgeType":"contains","source":4397,"target":4413},{"edgeType":"contains","source":3043,"target":3049},{"edgeType":"calls","source":1094,"target":1065},{"edgeType":"calls","source":4642,"target":4181},{"edgeType":"contains","source":5612,"target":5860},{"edgeType":"calls","source":4058,"target":1146},{"edgeType":"calls","source":1532,"target":171},{"edgeType":"contains","source":4091,"target":4385},{"edgeType":"contains","source":4100,"target":4106},{"edgeType":"contains","source":36,"target":73},{"edgeType":"contains","source":5884,"target":5885},{"edgeType":"calls","source":3343,"target":56},{"edgeType":"contains","source":6214,"target":6225},{"edgeType":"calls","source":6509,"target":6559},{"edgeType":"calls","source":1761,"target":475},{"edgeType":"calls","source":2547,"target":2531},{"edgeType":"calls","source":2614,"target":454},{"edgeType":"calls","source":6134,"target":210},{"edgeType":"calls","source":4051,"target":303},{"edgeType":"calls","source":4437,"target":4193},{"edgeType":"calls","source":1952,"target":1953},{"edgeType":"calls","source":3710,"target":303},{"edgeType":"calls","source":4805,"target":4413},{"edgeType":"contains","source":36,"target":76},{"edgeType":"contains","source":2176,"target":3497},{"edgeType":"contains","source":5,"target":3151},{"edgeType":"calls","source":895,"target":895},{"edgeType":"contains","source":5884,"target":5886},{"edgeType":"calls","source":3346,"target":1017},{"edgeType":"calls","source":5304,"target":571},{"edgeType":"calls","source":1224,"target":209},{"edgeType":"calls","source":6992,"target":6385},{"edgeType":"calls","source":7078,"target":548},{"edgeType":"calls","source":7120,"target":303},{"edgeType":"calls","source":3399,"target":431},{"edgeType":"calls","source":6134,"target":209},{"edgeType":"calls","source":1094,"target":1067},{"edgeType":"calls","source":4740,"target":84},{"edgeType":"calls","source":4051,"target":304},{"edgeType":"contains","source":5218,"target":5385},{"edgeType":"extends","source":1075,"target":1076},{"edgeType":"calls","source":1761,"target":474},{"edgeType":"calls","source":3759,"target":1957},{"edgeType":"calls","source":4081,"target":431},{"edgeType":"contains","source":3236,"target":3406},{"edgeType":"contains","source":3626,"target":3999},{"edgeType":"calls","source":6477,"target":146},{"edgeType":"contains","source":3,"target":41},{"edgeType":"calls","source":3710,"target":304},{"edgeType":"contains","source":36,"target":75},{"edgeType":"contains","source":2051,"target":2088},{"edgeType":"calls","source":4868,"target":4573},{"edgeType":"imports","source":4691,"target":1853},{"edgeType":"calls","source":4932,"target":475},{"edgeType":"contains","source":6214,"target":6227},{"edgeType":"calls","source":7120,"target":304},{"edgeType":"calls","source":1011,"target":469},{"edgeType":"contains","source":6084,"target":1801},{"edgeType":"calls","source":1129,"target":1039},{"edgeType":"calls","source":4725,"target":548},{"edgeType":"calls","source":6138,"target":84},{"edgeType":"extends","source":976,"target":977},{"edgeType":"calls","source":4770,"target":210},{"edgeType":"calls","source":2071,"target":372},{"edgeType":"calls","source":4932,"target":473},{"edgeType":"contains","source":3043,"target":3052},{"edgeType":"calls","source":4426,"target":304},{"edgeType":"contains","source":5612,"target":5855},{"edgeType":"contains","source":6286,"target":3988},{"edgeType":"calls","source":2248,"target":171},{"edgeType":"contains","source":4717,"target":5067},{"edgeType":"calls","source":939,"target":582},{"edgeType":"calls","source":4932,"target":474},{"edgeType":"contains","source":2736,"target":3055},{"edgeType":"contains","source":2051,"target":2093},{"edgeType":"contains","source":2070,"target":2561},{"edgeType":"calls","source":5107,"target":4562},{"edgeType":"calls","source":4770,"target":209},{"edgeType":"calls","source":1111,"target":534},{"edgeType":"calls","source":4726,"target":4744},{"edgeType":"calls","source":4868,"target":342},{"edgeType":"contains","source":3043,"target":3053},{"edgeType":"extends","source":5405,"target":36},{"edgeType":"calls","source":4426,"target":303},{"edgeType":"contains","source":6082,"target":6085},{"edgeType":"calls","source":4925,"target":4918},{"edgeType":"contains","source":4717,"target":5066},{"edgeType":"calls","source":3045,"target":2948},{"edgeType":"contains","source":6280,"target":6289},{"edgeType":"calls","source":5222,"target":5224},{"edgeType":"calls","source":6753,"target":56},{"edgeType":"calls","source":4801,"target":304},{"edgeType":"contains","source":3043,"target":3050},{"edgeType":"calls","source":6136,"target":144},{"edgeType":"calls","source":2783,"target":2610},{"edgeType":"calls","source":6296,"target":3640},{"edgeType":"contains","source":5647,"target":1601},{"edgeType":"calls","source":525,"target":733},{"edgeType":"calls","source":1532,"target":170},{"edgeType":"contains","source":1920,"target":1924},{"edgeType":"calls","source":5131,"target":1702},{"edgeType":"contains","source":3836,"target":3837},{"edgeType":"contains","source":6610,"target":6630},{"edgeType":"calls","source":5222,"target":5223},{"edgeType":"calls","source":6682,"target":144},{"edgeType":"calls","source":4801,"target":303},{"edgeType":"calls","source":6551,"target":2091},{"edgeType":"calls","source":5454,"target":144},{"edgeType":"calls","source":7110,"target":2732},{"edgeType":"calls","source":1093,"target":1094},{"edgeType":"calls","source":1991,"target":1796},{"edgeType":"calls","source":4495,"target":3447},{"edgeType":"calls","source":4874,"target":3325},{"edgeType":"contains","source":5612,"target":5858},{"edgeType":"contains","source":3043,"target":3051},{"edgeType":"calls","source":580,"target":84},{"edgeType":"calls","source":4766,"target":4559},{"edgeType":"calls","source":4860,"target":588},{"edgeType":"calls","source":525,"target":732},{"edgeType":"contains","source":1920,"target":1925},{"edgeType":"imports","source":5380,"target":582},{"edgeType":"calls","source":5888,"target":431},{"edgeType":"calls","source":2248,"target":170},{"edgeType":"calls","source":4490,"target":431},{"edgeType":"calls","source":5242,"target":4602},{"edgeType":"contains","source":6214,"target":6223},{"edgeType":"contains","source":30,"target":3436},{"edgeType":"calls","source":6551,"target":2092},{"edgeType":"contains","source":453,"target":896},{"edgeType":"calls","source":3128,"target":370},{"edgeType":"contains","source":520,"target":3047},{"edgeType":"calls","source":5247,"target":4446},{"edgeType":"imports","source":4668,"target":4669},{"edgeType":"contains","source":5686,"target":5688},{"edgeType":"contains","source":30,"target":3438},{"edgeType":"calls","source":1270,"target":886},{"edgeType":"calls","source":2783,"target":2609},{"edgeType":"contains","source":6375,"target":6527},{"edgeType":"calls","source":2845,"target":2801},{"edgeType":"contains","source":6644,"target":6645},{"edgeType":"calls","source":4976,"target":161},{"edgeType":"calls","source":3128,"target":371},{"edgeType":"calls","source":6087,"target":1659},{"edgeType":"contains","source":2051,"target":2098},{"edgeType":"contains","source":2201,"target":2730},{"edgeType":"calls","source":6248,"target":1953},{"edgeType":"calls","source":6945,"target":6793},{"edgeType":"calls","source":4976,"target":160},{"edgeType":"contains","source":3043,"target":3054},{"edgeType":"calls","source":2975,"target":2997},{"edgeType":"calls","source":5134,"target":548},{"edgeType":"contains","source":5884,"target":5894},{"edgeType":"calls","source":3128,"target":368},{"edgeType":"contains","source":5686,"target":5690},{"edgeType":"calls","source":6677,"target":303},{"edgeType":"calls","source":6662,"target":2882},{"edgeType":"contains","source":2051,"target":2095},{"edgeType":"contains","source":6286,"target":4003},{"edgeType":"contains","source":6213,"target":6266},{"edgeType":"imports","source":3726,"target":49},{"edgeType":"contains","source":2680,"target":2681},{"edgeType":"calls","source":2511,"target":469},{"edgeType":"calls","source":3024,"target":421},{"edgeType":"calls","source":4976,"target":159},{"edgeType":"contains","source":1854,"target":1861},{"edgeType":"calls","source":3024,"target":422},{"edgeType":"calls","source":6602,"target":6857},{"edgeType":"calls","source":3128,"target":369},{"edgeType":"calls","source":6677,"target":304},{"edgeType":"calls","source":6413,"target":6374},{"edgeType":"contains","source":2051,"target":2101},{"edgeType":"calls","source":4899,"target":431},{"edgeType":"calls","source":741,"target":369},{"edgeType":"calls","source":6374,"target":1216},{"edgeType":"calls","source":6994,"target":1048},{"edgeType":"calls","source":2984,"target":601},{"edgeType":"calls","source":4642,"target":4170},{"edgeType":"calls","source":3128,"target":366},{"edgeType":"imports","source":6245,"target":183},{"edgeType":"contains","source":2315,"target":2373},{"edgeType":"extends","source":3988,"target":1691},{"edgeType":"calls","source":6614,"target":144},{"edgeType":"contains","source":6214,"target":6228},{"edgeType":"contains","source":1947,"target":2154},{"edgeType":"contains","source":5388,"target":5415},{"edgeType":"contains","source":5884,"target":5888},{"edgeType":"imports","source":4502,"target":4534},{"edgeType":"contains","source":2051,"target":2102},{"edgeType":"calls","source":741,"target":368},{"edgeType":"calls","source":4383,"target":571},{"edgeType":"contains","source":5388,"target":5414},{"edgeType":"contains","source":6214,"target":6229},{"edgeType":"calls","source":4246,"target":588},{"edgeType":"calls","source":7008,"target":5901},{"edgeType":"contains","source":2070,"target":2567},{"edgeType":"contains","source":6214,"target":6230},{"edgeType":"calls","source":5513,"target":422},{"edgeType":"calls","source":741,"target":371},{"edgeType":"contains","source":520,"target":940},{"edgeType":"calls","source":1603,"target":1132},{"edgeType":"calls","source":4561,"target":4565},{"edgeType":"contains","source":5124,"target":5141},{"edgeType":"contains","source":1037,"target":1825},{"edgeType":"contains","source":5388,"target":5413},{"edgeType":"contains","source":6082,"target":6094},{"edgeType":"contains","source":1557,"target":1558},{"edgeType":"imports","source":6437,"target":575},{"edgeType":"contains","source":2070,"target":2568},{"edgeType":"contains","source":2051,"target":2100},{"edgeType":"calls","source":741,"target":370},{"edgeType":"contains","source":6214,"target":6231},{"edgeType":"contains","source":6437,"target":5660},{"edgeType":"calls","source":5513,"target":421},{"edgeType":"calls","source":5543,"target":548},{"edgeType":"calls","source":7110,"target":2740},{"edgeType":"extends","source":745,"target":748},{"edgeType":"calls","source":3128,"target":364},{"edgeType":"contains","source":2315,"target":2372},{"edgeType":"contains","source":5,"target":5276},{"edgeType":"calls","source":6580,"target":144},{"edgeType":"contains","source":5388,"target":5412},{"edgeType":"contains","source":1815,"target":2017},{"edgeType":"contains","source":5686,"target":5687},{"edgeType":"contains","source":5884,"target":5891},{"edgeType":"calls","source":4892,"target":4905},{"edgeType":"contains","source":2736,"target":3035},{"edgeType":"contains","source":36,"target":57},{"edgeType":"imports","source":42,"target":80},{"edgeType":"contains","source":3,"target":23},{"edgeType":"contains","source":2050,"target":2103},{"edgeType":"calls","source":1239,"target":1873},{"edgeType":"contains","source":4165,"target":4189},{"edgeType":"calls","source":7007,"target":5901},{"edgeType":"calls","source":3195,"target":431},{"edgeType":"imports","source":3145,"target":78},{"edgeType":"contains","source":3626,"target":3986},{"edgeType":"contains","source":5420,"target":5451},{"edgeType":"imports","source":4091,"target":351},{"edgeType":"calls","source":4892,"target":4904},{"edgeType":"contains","source":4165,"target":4188},{"edgeType":"contains","source":36,"target":56},{"edgeType":"calls","source":5652,"target":5656},{"edgeType":"imports","source":6824,"target":190},{"edgeType":"contains","source":2581,"target":442},{"edgeType":"contains","source":2176,"target":3483},{"edgeType":"calls","source":1339,"target":886},{"edgeType":"contains","source":5612,"target":5844},{"edgeType":"calls","source":6712,"target":4477},{"edgeType":"contains","source":1037,"target":1793},{"edgeType":"contains","source":5,"target":6302},{"edgeType":"calls","source":601,"target":509},{"edgeType":"calls","source":6579,"target":144},{"edgeType":"contains","source":3626,"target":3985},{"edgeType":"calls","source":4044,"target":3710},{"edgeType":"contains","source":5420,"target":5450},{"edgeType":"contains","source":1379,"target":1765},{"edgeType":"extends","source":1402,"target":437},{"edgeType":"contains","source":3439,"target":3440},{"edgeType":"calls","source":4892,"target":4903},{"edgeType":"contains","source":2736,"target":3033},{"edgeType":"contains","source":4165,"target":4187},{"edgeType":"contains","source":36,"target":59},{"edgeType":"imports","source":42,"target":78},{"edgeType":"contains","source":2201,"target":2705},{"edgeType":"calls","source":6947,"target":364},{"edgeType":"contains","source":6375,"target":6504},{"edgeType":"calls","source":1046,"target":458},{"edgeType":"calls","source":3231,"target":370},{"edgeType":"contains","source":5,"target":6305},{"edgeType":"extends","source":3904,"target":36},{"edgeType":"imports","source":3828,"target":49},{"edgeType":"contains","source":5612,"target":5845},{"edgeType":"calls","source":6678,"target":4475},{"edgeType":"calls","source":5861,"target":2347},{"edgeType":"calls","source":2010,"target":171},{"edgeType":"calls","source":4078,"target":3710},{"edgeType":"imports","source":42,"target":79},{"edgeType":"contains","source":4165,"target":4186},{"edgeType":"contains","source":36,"target":58},{"edgeType":"calls","source":5861,"target":2346},{"edgeType":"contains","source":2879,"target":3886},{"edgeType":"calls","source":3231,"target":371},{"edgeType":"contains","source":41,"target":6245},{"edgeType":"calls","source":1046,"target":457},{"edgeType":"calls","source":4629,"target":371},{"edgeType":"contains","source":4391,"target":4579},{"edgeType":"calls","source":3872,"target":584},{"edgeType":"calls","source":4047,"target":3615},{"edgeType":"extends","source":1836,"target":1779},{"edgeType":"calls","source":2010,"target":170},{"edgeType":"contains","source":3626,"target":3983},{"edgeType":"contains","source":6213,"target":6234},{"edgeType":"calls","source":5861,"target":2345},{"edgeType":"contains","source":1754,"target":1770},{"edgeType":"calls","source":4868,"target":4588},{"edgeType":"contains","source":36,"target":61},{"edgeType":"contains","source":6676,"target":6680},{"edgeType":"calls","source":6858,"target":1011},{"edgeType":"calls","source":6606,"target":6709},{"edgeType":"calls","source":6678,"target":4477},{"edgeType":"calls","source":6947,"target":366},{"edgeType":"contains","source":2176,"target":3486},{"edgeType":"calls","source":3231,"target":368},{"edgeType":"calls","source":1145,"target":554},{"edgeType":"calls","source":1962,"target":596},{"edgeType":"calls","source":4629,"target":370},{"edgeType":"calls","source":601,"target":506},{"edgeType":"contains","source":5388,"target":5390},{"edgeType":"calls","source":5861,"target":2344},{"edgeType":"calls","source":4933,"target":1515},{"edgeType":"contains","source":6676,"target":6681},{"edgeType":"contains","source":36,"target":60},{"edgeType":"calls","source":1737,"target":171},{"edgeType":"contains","source":2176,"target":3487},{"edgeType":"calls","source":2514,"target":2513},{"edgeType":"calls","source":6569,"target":1515},{"edgeType":"contains","source":5,"target":5249},{"edgeType":"calls","source":3231,"target":369},{"edgeType":"calls","source":1962,"target":1652},{"edgeType":"calls","source":4443,"target":4021},{"edgeType":"calls","source":2683,"target":445},{"edgeType":"calls","source":601,"target":505},{"edgeType":"calls","source":4629,"target":369},{"edgeType":"contains","source":5217,"target":5405},{"edgeType":"imports","source":5380,"target":565},{"edgeType":"contains","source":5388,"target":5389},{"edgeType":"contains","source":6213,"target":6236},{"edgeType":"contains","source":2050,"target":2105},{"edgeType":"calls","source":4274,"target":1859},{"edgeType":"calls","source":5861,"target":2343},{"edgeType":"contains","source":36,"target":63},{"edgeType":"contains","source":2176,"target":3484},{"edgeType":"contains","source":4397,"target":4399},{"edgeType":"calls","source":6947,"target":368},{"edgeType":"contains","source":5,"target":6310},{"edgeType":"calls","source":6887,"target":1171},{"edgeType":"calls","source":6915,"target":303},{"edgeType":"calls","source":4628,"target":4627},{"edgeType":"calls","source":3231,"target":366},{"edgeType":"imports","source":6604,"target":1732},{"edgeType":"calls","source":601,"target":508},{"edgeType":"contains","source":952,"target":1264},{"edgeType":"calls","source":4629,"target":368},{"edgeType":"contains","source":5380,"target":5636},{"edgeType":"calls","source":6947,"target":369},{"edgeType":"calls","source":5861,"target":2342},{"edgeType":"extends","source":2813,"target":36},{"edgeType":"contains","source":4165,"target":4190},{"edgeType":"contains","source":36,"target":62},{"edgeType":"contains","source":6213,"target":6237},{"edgeType":"calls","source":6671,"target":469},{"edgeType":"contains","source":2176,"target":3485},{"edgeType":"calls","source":6915,"target":304},{"edgeType":"calls","source":1359,"target":1321},{"edgeType":"contains","source":4397,"target":4398},{"edgeType":"contains","source":5,"target":6308},{"edgeType":"contains","source":5748,"target":5854},{"edgeType":"calls","source":4628,"target":4626},{"edgeType":"contains","source":5218,"target":5372},{"edgeType":"calls","source":601,"target":507},{"edgeType":"calls","source":4672,"target":1148},{"edgeType":"calls","source":4401,"target":4264},{"edgeType":"calls","source":2683,"target":443},{"edgeType":"calls","source":2547,"target":431},{"edgeType":"calls","source":6947,"target":370},{"edgeType":"contains","source":3241,"target":3244},{"edgeType":"calls","source":5861,"target":2341},{"edgeType":"calls","source":6808,"target":6793},{"edgeType":"contains","source":4459,"target":4597},{"edgeType":"contains","source":5388,"target":5395},{"edgeType":"calls","source":7084,"target":351},{"edgeType":"contains","source":36,"target":65},{"edgeType":"calls","source":3804,"target":571},{"edgeType":"contains","source":2051,"target":2080},{"edgeType":"contains","source":5,"target":3140},{"edgeType":"calls","source":601,"target":502},{"edgeType":"calls","source":530,"target":589},{"edgeType":"imports","source":130,"target":532},{"edgeType":"calls","source":1161,"target":1111},{"edgeType":"contains","source":6214,"target":6216},{"edgeType":"contains","source":6280,"target":6284},{"edgeType":"calls","source":4629,"target":366},{"edgeType":"calls","source":3231,"target":364},{"edgeType":"calls","source":4628,"target":4625},{"edgeType":"calls","source":4672,"target":1147},{"edgeType":"calls","source":6947,"target":371},{"edgeType":"contains","source":4528,"target":1400},{"edgeType":"contains","source":3,"target":30},{"edgeType":"contains","source":36,"target":64},{"edgeType":"calls","source":6606,"target":6714},{"edgeType":"calls","source":6287,"target":3932},{"edgeType":"contains","source":6280,"target":6285},{"edgeType":"contains","source":1302,"target":5217},{"edgeType":"contains","source":6214,"target":6217},{"edgeType":"calls","source":1160,"target":84},{"edgeType":"calls","source":4672,"target":1146},{"edgeType":"contains","source":1037,"target":1805},{"edgeType":"calls","source":6911,"target":431},{"edgeType":"calls","source":3195,"target":421},{"edgeType":"calls","source":5123,"target":5133},{"edgeType":"contains","source":4558,"target":4697},{"edgeType":"calls","source":5660,"target":114},{"edgeType":"calls","source":4044,"target":528},{"edgeType":"calls","source":1737,"target":170},{"edgeType":"contains","source":36,"target":67},{"edgeType":"calls","source":6514,"target":1111},{"edgeType":"contains","source":36,"target":68},{"edgeType":"contains","source":1379,"target":2827},{"edgeType":"contains","source":3029,"target":4528},{"edgeType":"calls","source":4629,"target":364},{"edgeType":"imports","source":2736,"target":79},{"edgeType":"calls","source":601,"target":504},{"edgeType":"calls","source":6739,"target":2593},{"edgeType":"extends","source":3461,"target":36},{"edgeType":"contains","source":162,"target":6731},{"edgeType":"imports","source":2736,"target":78},{"edgeType":"calls","source":3195,"target":422},{"edgeType":"contains","source":5420,"target":5457},{"edgeType":"contains","source":4558,"target":4696},{"edgeType":"contains","source":4391,"target":4588},{"edgeType":"calls","source":3907,"target":548},{"edgeType":"contains","source":36,"target":66},{"edgeType":"contains","source":3,"target":32},{"edgeType":"contains","source":30,"target":1310},{"edgeType":"contains","source":103,"target":104},{"edgeType":"calls","source":530,"target":590},{"edgeType":"contains","source":6214,"target":6219},{"edgeType":"calls","source":5510,"target":4762},{"edgeType":"calls","source":1111,"target":548},{"edgeType":"calls","source":3238,"target":146},{"edgeType":"contains","source":6375,"target":6513},{"edgeType":"contains","source":928,"target":6239},{"edgeType":"calls","source":601,"target":503},{"edgeType":"calls","source":2784,"target":2593},{"edgeType":"contains","source":6610,"target":6620},{"edgeType":"calls","source":1886,"target":1887},{"edgeType":"calls","source":5722,"target":304},{"edgeType":"contains","source":5380,"target":5647},{"edgeType":"calls","source":1962,"target":588},{"edgeType":"contains","source":3626,"target":3998},{"edgeType":"contains","source":2051,"target":2085},{"edgeType":"contains","source":36,"target":70},{"edgeType":"calls","source":5722,"target":303},{"edgeType":"contains","source":2176,"target":3495},{"edgeType":"calls","source":3544,"target":170},{"edgeType":"calls","source":5411,"target":431},{"edgeType":"calls","source":917,"target":215},{"edgeType":"calls","source":2884,"target":547},{"edgeType":"contains","source":5285,"target":5420},{"edgeType":"calls","source":2252,"target":56},{"edgeType":"calls","source":512,"target":84},{"edgeType":"extends","source":1654,"target":36},{"edgeType":"calls","source":4044,"target":527},{"edgeType":"contains","source":36,"target":69},{"edgeType":"contains","source":5612,"target":5848},{"edgeType":"contains","source":6280,"target":6281},{"edgeType":"contains","source":5,"target":3144},{"edgeType":"contains","source":103,"target":106},{"edgeType":"calls","source":6468,"target":431},{"edgeType":"calls","source":3544,"target":171},{"edgeType":"calls","source":530,"target":584},{"edgeType":"calls","source":1224,"target":210},{"edgeType":"calls","source":5440,"target":588},{"edgeType":"contains","source":5124,"target":5125},{"edgeType":"calls","source":4058,"target":1147},{"edgeType":"contains","source":5388,"target":5397},{"edgeType":"contains","source":6280,"target":6282},{"edgeType":"contains","source":6247,"target":6248},{"edgeType":"contains","source":4100,"target":4101},{"edgeType":"contains","source":36,"target":72},{"edgeType":"contains","source":4691,"target":4806},{"edgeType":"contains","source":4331,"target":4339},{"edgeType":"calls","source":6671,"target":1534},{"edgeType":"contains","source":5157,"target":5158},{"edgeType":"contains","source":5388,"target":5396},{"edgeType":"calls","source":4417,"target":588},{"edgeType":"calls","source":6117,"target":1797},{"edgeType":"imports","source":4459,"target":568},{"edgeType":"calls","source":4058,"target":1148},{"edgeType":"contains","source":6280,"target":6283},{"edgeType":"calls","source":6281,"target":5169},{"edgeType":"contains","source":2051,"target":2084},{"edgeType":"contains","source":36,"target":71},{"edgeType":"imports","source":3145,"target":79},{"edgeType":"calls","source":4915,"target":1006},{"edgeType":"contains","source":5612,"target":5850},{"edgeType":"contains","source":4717,"target":5056},{"edgeType":"calls","source":1158,"target":144},{"edgeType":"calls","source":1195,"target":1111},{"edgeType":"contains","source":5166,"target":2739},{"edgeType":"calls","source":6133,"target":210},{"edgeType":"calls","source":2546,"target":2531},{"edgeType":"calls","source":6541,"target":4475},{"edgeType":"contains","source":928,"target":929},{"edgeType":"calls","source":1793,"target":505},{"edgeType":"contains","source":5218,"target":5355},{"edgeType":"imports","source":5166,"target":3014},{"edgeType":"calls","source":2259,"target":1915},{"edgeType":"calls","source":1542,"target":886},{"edgeType":"calls","source":7042,"target":572},{"edgeType":"contains","source":35,"target":72},{"edgeType":"contains","source":2070,"target":2524},{"edgeType":"contains","source":1947,"target":2109},{"edgeType":"contains","source":1984,"target":2019},{"edgeType":"calls","source":3409,"target":1147},{"edgeType":"calls","source":3189,"target":568},{"edgeType":"contains","source":2315,"target":2329},{"edgeType":"calls","source":6133,"target":209},{"edgeType":"calls","source":1793,"target":504},{"edgeType":"calls","source":4590,"target":475},{"edgeType":"calls","source":434,"target":351},{"edgeType":"calls","source":4230,"target":4236},{"edgeType":"calls","source":6407,"target":171},{"edgeType":"contains","source":1984,"target":2020},{"edgeType":"calls","source":7042,"target":573},{"edgeType":"contains","source":35,"target":71},{"edgeType":"contains","source":1947,"target":2110},{"edgeType":"contains","source":4000,"target":4002},{"edgeType":"calls","source":1354,"target":371},{"edgeType":"calls","source":3409,"target":1148},{"edgeType":"calls","source":2998,"target":148},{"edgeType":"calls","source":5246,"target":4451},{"edgeType":"calls","source":1793,"target":507},{"edgeType":"calls","source":1078,"target":474},{"edgeType":"contains","source":6373,"target":6549},{"edgeType":"contains","source":3735,"target":3759},{"edgeType":"calls","source":6194,"target":431},{"edgeType":"calls","source":1696,"target":1400},{"edgeType":"contains","source":5024,"target":5025},{"edgeType":"calls","source":6541,"target":4477},{"edgeType":"calls","source":3946,"target":354},{"edgeType":"calls","source":4527,"target":313},{"edgeType":"calls","source":6568,"target":469},{"edgeType":"contains","source":3949,"target":4524},{"edgeType":"calls","source":6407,"target":170},{"edgeType":"calls","source":4590,"target":474},{"edgeType":"contains","source":3,"target":9},{"edgeType":"calls","source":5102,"target":1515},{"edgeType":"imports","source":42,"target":128},{"edgeType":"contains","source":35,"target":74},{"edgeType":"contains","source":4717,"target":5028},{"edgeType":"calls","source":3434,"target":370},{"edgeType":"calls","source":1078,"target":473},{"edgeType":"calls","source":1690,"target":528},{"edgeType":"extends","source":5636,"target":5593},{"edgeType":"calls","source":1793,"target":506},{"edgeType":"calls","source":2259,"target":1914},{"edgeType":"contains","source":1654,"target":1677},{"edgeType":"calls","source":4590,"target":473},{"edgeType":"calls","source":4527,"target":312},{"edgeType":"imports","source":4668,"target":485},{"edgeType":"contains","source":1947,"target":2108},{"edgeType":"calls","source":2998,"target":146},{"edgeType":"contains","source":1984,"target":2018},{"edgeType":"contains","source":35,"target":73},{"edgeType":"calls","source":4930,"target":2618},{"edgeType":"imports","source":42,"target":1186},{"edgeType":"calls","source":1690,"target":527},{"edgeType":"calls","source":972,"target":588},{"edgeType":"imports","source":4307,"target":49},{"edgeType":"calls","source":6959,"target":2091},{"edgeType":"calls","source":1252,"target":364},{"edgeType":"calls","source":3434,"target":371},{"edgeType":"calls","source":5457,"target":2136},{"edgeType":"calls","source":3409,"target":1146},{"edgeType":"calls","source":1224,"target":170},{"edgeType":"calls","source":6265,"target":342},{"edgeType":"calls","source":6135,"target":144},{"edgeType":"contains","source":1302,"target":5195},{"edgeType":"calls","source":4262,"target":1126},{"edgeType":"contains","source":1037,"target":1782},{"edgeType":"imports","source":3352,"target":49},{"edgeType":"contains","source":3371,"target":3422},{"edgeType":"calls","source":4562,"target":4511},{"edgeType":"calls","source":4527,"target":311},{"edgeType":"contains","source":5617,"target":5667},{"edgeType":"extends","source":5674,"target":180},{"edgeType":"calls","source":5794,"target":144},{"edgeType":"calls","source":5003,"target":354},{"edgeType":"calls","source":4944,"target":1126},{"edgeType":"contains","source":4717,"target":5034},{"edgeType":"contains","source":35,"target":76},{"edgeType":"calls","source":1354,"target":368},{"edgeType":"calls","source":3434,"target":368},{"edgeType":"calls","source":6959,"target":2092},{"edgeType":"contains","source":3626,"target":3972},{"edgeType":"calls","source":1940,"target":171},{"edgeType":"calls","source":6206,"target":1113},{"edgeType":"calls","source":1047,"target":371},{"edgeType":"contains","source":1037,"target":1781},{"edgeType":"contains","source":3371,"target":3421},{"edgeType":"contains","source":4691,"target":4782},{"edgeType":"contains","source":1754,"target":1755},{"edgeType":"contains","source":4717,"target":5033},{"edgeType":"contains","source":4165,"target":4176},{"edgeType":"calls","source":3418,"target":2979},{"edgeType":"contains","source":35,"target":75},{"edgeType":"contains","source":4558,"target":4677},{"edgeType":"calls","source":6939,"target":6941},{"edgeType":"calls","source":3434,"target":369},{"edgeType":"calls","source":3974,"target":3710},{"edgeType":"calls","source":3434,"target":366},{"edgeType":"extends","source":837,"target":36},{"edgeType":"calls","source":1793,"target":503},{"edgeType":"calls","source":6206,"target":1112},{"edgeType":"contains","source":1037,"target":1784},{"edgeType":"calls","source":2778,"target":2732},{"edgeType":"calls","source":2952,"target":509},{"edgeType":"calls","source":597,"target":582},{"edgeType":"contains","source":1415,"target":1690},{"edgeType":"contains","source":1947,"target":2111},{"edgeType":"contains","source":1984,"target":2021},{"edgeType":"calls","source":1354,"target":370},{"edgeType":"calls","source":1793,"target":502},{"edgeType":"calls","source":1260,"target":1170},{"edgeType":"calls","source":1224,"target":171},{"edgeType":"calls","source":1143,"target":568},{"edgeType":"contains","source":2844,"target":2845},{"edgeType":"contains","source":1037,"target":1783},{"edgeType":"calls","source":4764,"target":4588},{"edgeType":"contains","source":1984,"target":2022},{"edgeType":"calls","source":4263,"target":4264},{"edgeType":"calls","source":5103,"target":422},{"edgeType":"imports","source":130,"target":568},{"edgeType":"contains","source":4558,"target":4675},{"edgeType":"calls","source":1354,"target":369},{"edgeType":"calls","source":6134,"target":171},{"edgeType":"contains","source":3,"target":12},{"edgeType":"calls","source":6717,"target":84},{"edgeType":"calls","source":3434,"target":364},{"edgeType":"calls","source":1224,"target":1223},{"edgeType":"calls","source":6247,"target":1953},{"edgeType":"calls","source":1354,"target":364},{"edgeType":"calls","source":1047,"target":368},{"edgeType":"calls","source":2952,"target":507},{"edgeType":"imports","source":3726,"target":79},{"edgeType":"contains","source":1037,"target":1786},{"edgeType":"calls","source":4527,"target":307},{"edgeType":"calls","source":5103,"target":421},{"edgeType":"calls","source":4328,"target":2248},{"edgeType":"calls","source":5247,"target":4413},{"edgeType":"contains","source":6111,"target":6221},{"edgeType":"calls","source":6134,"target":170},{"edgeType":"calls","source":3635,"target":475},{"edgeType":"calls","source":1761,"target":431},{"edgeType":"extends","source":745,"target":775},{"edgeType":"calls","source":1224,"target":1222},{"edgeType":"calls","source":567,"target":448},{"edgeType":"contains","source":3371,"target":3425},{"edgeType":"contains","source":6676,"target":6677},{"edgeType":"contains","source":2736,"target":3028},{"edgeType":"calls","source":2952,"target":508},{"edgeType":"contains","source":1037,"target":1785},{"edgeType":"contains","source":4558,"target":4681},{"edgeType":"calls","source":5291,"target":1991},{"edgeType":"contains","source":3,"target":14},{"edgeType":"contains","source":6111,"target":6222},{"edgeType":"contains","source":102,"target":116},{"edgeType":"calls","source":4876,"target":56},{"edgeType":"calls","source":2796,"target":1113},{"edgeType":"calls","source":1940,"target":170},{"edgeType":"imports","source":2203,"target":1853},{"edgeType":"calls","source":1354,"target":366},{"edgeType":"contains","source":6245,"target":6297},{"edgeType":"calls","source":1224,"target":1225},{"edgeType":"contains","source":6213,"target":6232},{"edgeType":"calls","source":2952,"target":505},{"edgeType":"calls","source":434,"target":346},{"edgeType":"calls","source":1047,"target":370},{"edgeType":"contains","source":3371,"target":3424},{"edgeType":"contains","source":1037,"target":1788},{"edgeType":"calls","source":4892,"target":4845},{"edgeType":"contains","source":952,"target":1252},{"edgeType":"calls","source":6979,"target":421},{"edgeType":"contains","source":1754,"target":1756},{"edgeType":"calls","source":3635,"target":473},{"edgeType":"calls","source":3704,"target":448},{"edgeType":"calls","source":4032,"target":4021},{"edgeType":"contains","source":2070,"target":2530},{"edgeType":"contains","source":2844,"target":2849},{"edgeType":"extends","source":4313,"target":2212},{"edgeType":"contains","source":6245,"target":6298},{"edgeType":"calls","source":6976,"target":6857},{"edgeType":"contains","source":3626,"target":3974},{"edgeType":"contains","source":952,"target":1251},{"edgeType":"contains","source":585,"target":1001},{"edgeType":"calls","source":1047,"target":369},{"edgeType":"contains","source":1032,"target":1942},{"edgeType":"contains","source":1037,"target":1787},{"edgeType":"calls","source":2952,"target":506},{"edgeType":"extends","source":1860,"target":36},{"edgeType":"calls","source":6807,"target":469},{"edgeType":"contains","source":1754,"target":1757},{"edgeType":"contains","source":4558,"target":4679},{"edgeType":"contains","source":4717,"target":5035},{"edgeType":"calls","source":6979,"target":422},{"edgeType":"calls","source":4429,"target":171},{"edgeType":"contains","source":4631,"target":4530},{"edgeType":"calls","source":3635,"target":474},{"edgeType":"contains","source":3735,"target":3767},{"edgeType":"calls","source":6647,"target":144},{"edgeType":"contains","source":3,"target":16},{"edgeType":"calls","source":5672,"target":1804},{"edgeType":"contains","source":4165,"target":4185},{"edgeType":"calls","source":2952,"target":503},{"edgeType":"contains","source":1037,"target":1790},{"edgeType":"calls","source":4429,"target":170},{"edgeType":"contains","source":1379,"target":1760},{"edgeType":"contains","source":3460,"target":3841},{"edgeType":"calls","source":2796,"target":1112},{"edgeType":"calls","source":4902,"target":304},{"edgeType":"calls","source":4932,"target":431},{"edgeType":"calls","source":1525,"target":1400},{"edgeType":"calls","source":2952,"target":504},{"edgeType":"calls","source":3342,"target":1099},{"edgeType":"contains","source":4558,"target":4686},{"edgeType":"calls","source":5201,"target":548},{"edgeType":"contains","source":1037,"target":1789},{"edgeType":"calls","source":1041,"target":548},{"edgeType":"calls","source":434,"target":339},{"edgeType":"calls","source":468,"target":342},{"edgeType":"calls","source":3704,"target":447},{"edgeType":"contains","source":3,"target":21},{"edgeType":"contains","source":36,"target":55},{"edgeType":"calls","source":4902,"target":303},{"edgeType":"calls","source":567,"target":447},{"edgeType":"calls","source":4725,"target":4733},{"edgeType":"calls","source":530,"target":537},{"edgeType":"calls","source":4700,"target":4451},{"edgeType":"calls","source":1047,"target":366},{"edgeType":"contains","source":1037,"target":1792},{"edgeType":"extends","source":321,"target":184},{"edgeType":"contains","source":5285,"target":5402},{"edgeType":"calls","source":1882,"target":1963},{"edgeType":"contains","source":3626,"target":3980},{"edgeType":"contains","source":2050,"target":2097},{"edgeType":"calls","source":2079,"target":84},{"edgeType":"calls","source":6258,"target":548},{"edgeType":"contains","source":36,"target":54},{"edgeType":"extends","source":5679,"target":36},{"edgeType":"calls","source":5648,"target":431},{"edgeType":"calls","source":2952,"target":502},{"edgeType":"contains","source":952,"target":1255},{"edgeType":"calls","source":1047,"target":364},{"edgeType":"calls","source":6712,"target":4475},{"edgeType":"contains","source":6111,"target":6220},{"edgeType":"contains","source":5420,"target":5444},{"edgeType":"imports","source":4668,"target":1538},{"edgeType":"contains","source":3626,"target":3979},{"edgeType":"imports","source":4000,"target":49},{"edgeType":"contains","source":35,"target":55},{"edgeType":"imports","source":4668,"target":3637},{"edgeType":"imports","source":4502,"target":4555},{"edgeType":"contains","source":4668,"target":1248},{"edgeType":"calls","source":1213,"target":532},{"edgeType":"contains","source":1654,"target":1662},{"edgeType":"contains","source":3735,"target":3745},{"edgeType":"contains","source":2961,"target":3426},{"edgeType":"contains","source":5617,"target":5655},{"edgeType":"calls","source":5707,"target":1804},{"edgeType":"contains","source":35,"target":54},{"edgeType":"calls","source":7063,"target":962},{"edgeType":"calls","source":741,"target":364},{"edgeType":"contains","source":1984,"target":2003},{"edgeType":"imports","source":4502,"target":4556},{"edgeType":"contains","source":2176,"target":3450},{"edgeType":"contains","source":4558,"target":4657},{"edgeType":"calls","source":1358,"target":1321},{"edgeType":"contains","source":1654,"target":1663},{"edgeType":"contains","source":2961,"target":3427},{"edgeType":"calls","source":3932,"target":3978},{"edgeType":"contains","source":1379,"target":1732},{"edgeType":"calls","source":4067,"target":4021},{"edgeType":"imports","source":4668,"target":3639},{"edgeType":"calls","source":4230,"target":3194},{"edgeType":"calls","source":7063,"target":963},{"edgeType":"imports","source":4668,"target":2582},{"edgeType":"contains","source":35,"target":57},{"edgeType":"calls","source":5281,"target":210},{"edgeType":"calls","source":994,"target":980},{"edgeType":"calls","source":7006,"target":5901},{"edgeType":"calls","source":1084,"target":304},{"edgeType":"calls","source":2579,"target":2580},{"edgeType":"contains","source":5618,"target":5626},{"edgeType":"calls","source":6671,"target":431},{"edgeType":"contains","source":3949,"target":4508},{"edgeType":"contains","source":5287,"target":5311},{"edgeType":"contains","source":3626,"target":3951},{"edgeType":"contains","source":1654,"target":1660},{"edgeType":"calls","source":5068,"target":1527},{"edgeType":"contains","source":35,"target":56},{"edgeType":"calls","source":2899,"target":3231},{"edgeType":"calls","source":4932,"target":1515},{"edgeType":"calls","source":4867,"target":4587},{"edgeType":"calls","source":741,"target":366},{"edgeType":"calls","source":5281,"target":209},{"edgeType":"calls","source":1338,"target":886},{"edgeType":"calls","source":5373,"target":528},{"edgeType":"extends","source":6599,"target":36},{"edgeType":"calls","source":1084,"target":303},{"edgeType":"contains","source":5618,"target":5627},{"edgeType":"calls","source":2329,"target":1875},{"edgeType":"calls","source":530,"target":565},{"edgeType":"contains","source":1420,"target":1516},{"edgeType":"contains","source":1654,"target":1661},{"edgeType":"contains","source":1984,"target":2006},{"edgeType":"calls","source":2975,"target":2986},{"edgeType":"contains","source":4691,"target":4767},{"edgeType":"contains","source":35,"target":59},{"edgeType":"contains","source":3952,"target":193},{"edgeType":"calls","source":5373,"target":527},{"edgeType":"contains","source":6604,"target":6765},{"edgeType":"calls","source":1152,"target":304},{"edgeType":"calls","source":4144,"target":572},{"edgeType":"contains","source":2898,"target":3269},{"edgeType":"imports","source":6557,"target":49},{"edgeType":"contains","source":3173,"target":3200},{"edgeType":"contains","source":1420,"target":1521},{"edgeType":"contains","source":5420,"target":5422},{"edgeType":"contains","source":35,"target":58},{"edgeType":"contains","source":3952,"target":192},{"edgeType":"contains","source":2050,"target":2075},{"edgeType":"contains","source":6375,"target":6465},{"edgeType":"contains","source":6604,"target":6766},{"edgeType":"calls","source":3204,"target":3287},{"edgeType":"contains","source":3735,"target":3748},{"edgeType":"calls","source":4144,"target":573},{"edgeType":"contains","source":3828,"target":2979},{"edgeType":"calls","source":1152,"target":303},{"edgeType":"calls","source":4942,"target":146},{"edgeType":"calls","source":2371,"target":571},{"edgeType":"contains","source":3173,"target":3201},{"edgeType":"calls","source":2546,"target":431},{"edgeType":"contains","source":5612,"target":5807},{"edgeType":"calls","source":4429,"target":4422},{"edgeType":"calls","source":6806,"target":6820},{"edgeType":"contains","source":5380,"target":5604},{"edgeType":"imports","source":4668,"target":472},{"edgeType":"contains","source":35,"target":61},{"edgeType":"calls","source":3803,"target":571},{"edgeType":"calls","source":3542,"target":2320},{"edgeType":"extends","source":6667,"target":36},{"edgeType":"contains","source":1654,"target":1664},{"edgeType":"calls","source":4191,"target":170},{"edgeType":"contains","source":3735,"target":3747},{"edgeType":"contains","source":2879,"target":3856},{"edgeType":"calls","source":4471,"target":4176},{"edgeType":"contains","source":4558,"target":4659},{"edgeType":"contains","source":35,"target":60},{"edgeType":"calls","source":6841,"target":6793},{"edgeType":"imports","source":3726,"target":78},{"edgeType":"calls","source":5725,"target":183},{"edgeType":"contains","source":920,"target":1165},{"edgeType":"contains","source":3735,"target":3746},{"edgeType":"calls","source":4191,"target":171},{"edgeType":"contains","source":3173,"target":3199},{"edgeType":"contains","source":1420,"target":1520},{"edgeType":"contains","source":5617,"target":5654},{"edgeType":"contains","source":1122,"target":1245},{"edgeType":"contains","source":1037,"target":1766},{"edgeType":"calls","source":2899,"target":56},{"edgeType":"calls","source":3670,"target":3635},{"edgeType":"contains","source":35,"target":63},{"edgeType":"calls","source":536,"target":370},{"edgeType":"contains","source":5674,"target":3896},{"edgeType":"calls","source":1252,"target":371},{"edgeType":"contains","source":6213,"target":6214},{"edgeType":"calls","source":6374,"target":146},{"edgeType":"contains","source":3367,"target":3534},{"edgeType":"contains","source":5029,"target":4863},{"edgeType":"calls","source":2545,"target":2571},{"edgeType":"calls","source":4933,"target":422},{"edgeType":"calls","source":2746,"target":568},{"edgeType":"contains","source":1654,"target":1671},{"edgeType":"contains","source":3735,"target":3752},{"edgeType":"extends","source":2030,"target":36},{"edgeType":"contains","source":35,"target":62},{"edgeType":"calls","source":1722,"target":1656},{"edgeType":"contains","source":5617,"target":5664},{"edgeType":"calls","source":536,"target":369},{"edgeType":"calls","source":1252,"target":370},{"edgeType":"calls","source":4933,"target":421},{"edgeType":"contains","source":3949,"target":4516},{"edgeType":"contains","source":5420,"target":5425},{"edgeType":"contains","source":5617,"target":5665},{"edgeType":"calls","source":1770,"target":171},{"edgeType":"contains","source":35,"target":65},{"edgeType":"calls","source":4864,"target":445},{"edgeType":"contains","source":1654,"target":1668},{"edgeType":"contains","source":1420,"target":1523},{"edgeType":"contains","source":3173,"target":3202},{"edgeType":"contains","source":3828,"target":2981},{"edgeType":"contains","source":35,"target":64},{"edgeType":"calls","source":3934,"target":3906},{"edgeType":"extends","source":2128,"target":167},{"edgeType":"calls","source":1770,"target":170},{"edgeType":"imports","source":4502,"target":4550},{"edgeType":"calls","source":6033,"target":144},{"edgeType":"calls","source":536,"target":371},{"edgeType":"calls","source":4034,"target":3977},{"edgeType":"contains","source":1420,"target":1524},{"edgeType":"contains","source":6114,"target":6115},{"edgeType":"imports","source":5195,"target":1036},{"edgeType":"calls","source":6410,"target":84},{"edgeType":"calls","source":6445,"target":56},{"edgeType":"calls","source":4933,"target":4647},{"edgeType":"calls","source":2555,"target":146},{"edgeType":"contains","source":920,"target":1169},{"edgeType":"contains","source":3030,"target":3408},{"edgeType":"calls","source":1793,"target":509},{"edgeType":"calls","source":1756,"target":1656},{"edgeType":"calls","source":6877,"target":2511},{"edgeType":"calls","source":4527,"target":319},{"edgeType":"contains","source":3949,"target":4522},{"edgeType":"imports","source":4502,"target":4551},{"edgeType":"contains","source":1654,"target":1674},{"edgeType":"contains","source":3735,"target":3757},{"edgeType":"contains","source":35,"target":68},{"edgeType":"calls","source":1416,"target":568},{"edgeType":"calls","source":4864,"target":443},{"edgeType":"contains","source":2051,"target":2052},{"edgeType":"calls","source":536,"target":366},{"edgeType":"extends","source":184,"target":185},{"edgeType":"calls","source":3542,"target":2313},{"edgeType":"calls","source":1603,"target":56},{"edgeType":"contains","source":920,"target":1172},{"edgeType":"calls","source":1223,"target":209},{"edgeType":"calls","source":894,"target":895},{"edgeType":"contains","source":4668,"target":1260},{"edgeType":"calls","source":5104,"target":2516},{"edgeType":"calls","source":1078,"target":475},{"edgeType":"calls","source":1793,"target":508},{"edgeType":"calls","source":1827,"target":511},{"edgeType":"calls","source":3720,"target":2082},{"edgeType":"calls","source":4527,"target":318},{"edgeType":"calls","source":536,"target":364},{"edgeType":"contains","source":41,"target":5166},{"edgeType":"contains","source":3949,"target":4521},{"edgeType":"imports","source":4502,"target":4552},{"edgeType":"contains","source":35,"target":66},{"edgeType":"calls","source":4083,"target":342},{"edgeType":"calls","source":4212,"target":571},{"edgeType":"contains","source":2051,"target":2053},{"edgeType":"contains","source":35,"target":67},{"edgeType":"calls","source":6408,"target":144},{"edgeType":"calls","source":1252,"target":366},{"edgeType":"calls","source":1260,"target":1175},{"edgeType":"calls","source":6606,"target":6686},{"edgeType":"contains","source":3141,"target":3142},{"edgeType":"calls","source":1591,"target":431},{"edgeType":"contains","source":5156,"target":5157},{"edgeType":"calls","source":1532,"target":146},{"edgeType":"imports","source":4502,"target":4553},{"edgeType":"imports","source":6530,"target":1936},{"edgeType":"contains","source":3735,"target":3755},{"edgeType":"contains","source":3,"target":5},{"edgeType":"imports","source":3828,"target":78},{"edgeType":"contains","source":35,"target":70},{"edgeType":"calls","source":536,"target":368},{"edgeType":"calls","source":1191,"target":146},{"edgeType":"calls","source":3023,"target":431},{"edgeType":"calls","source":5003,"target":4588},{"edgeType":"calls","source":2975,"target":2976},{"edgeType":"calls","source":3342,"target":1112},{"edgeType":"calls","source":1252,"target":369},{"edgeType":"contains","source":1027,"target":1028},{"edgeType":"contains","source":1984,"target":2013},{"edgeType":"imports","source":4502,"target":4554},{"edgeType":"calls","source":6296,"target":1500},{"edgeType":"contains","source":1415,"target":1683},{"edgeType":"calls","source":2105,"target":351},{"edgeType":"contains","source":5617,"target":5662},{"edgeType":"contains","source":4165,"target":4166},{"edgeType":"contains","source":35,"target":69},{"edgeType":"imports","source":3828,"target":79},{"edgeType":"calls","source":1223,"target":210},{"edgeType":"contains","source":4717,"target":5023},{"edgeType":"calls","source":3342,"target":1113},{"edgeType":"calls","source":2984,"target":584},{"edgeType":"calls","source":1252,"target":368},{"edgeType":"calls","source":6750,"target":209},{"edgeType":"imports","source":1028,"target":1044},{"edgeType":"contains","source":3351,"target":3476},{"edgeType":"calls","source":3887,"target":170},{"edgeType":"contains","source":4706,"target":4810},{"edgeType":"calls","source":4704,"target":212},{"edgeType":"contains","source":1907,"target":2787},{"edgeType":"contains","source":3,"target":3673},{"edgeType":"calls","source":6561,"target":2897},{"edgeType":"calls","source":4666,"target":333},{"edgeType":"calls","source":4385,"target":588},{"edgeType":"calls","source":4346,"target":1797},{"edgeType":"contains","source":6245,"target":5725},{"edgeType":"calls","source":4017,"target":368},{"edgeType":"contains","source":4544,"target":4547},{"edgeType":"contains","source":2495,"target":2529},{"edgeType":"contains","source":4478,"target":4479},{"edgeType":"calls","source":2777,"target":1812},{"edgeType":"calls","source":2817,"target":572},{"edgeType":"calls","source":1477,"target":886},{"edgeType":"imports","source":130,"target":1399},{"edgeType":"calls","source":5652,"target":421},{"edgeType":"calls","source":3023,"target":528},{"edgeType":"imports","source":2581,"target":2582},{"edgeType":"calls","source":2848,"target":2782},{"edgeType":"calls","source":3303,"target":304},{"edgeType":"calls","source":1125,"target":171},{"edgeType":"calls","source":4960,"target":4961},{"edgeType":"calls","source":3887,"target":171},{"edgeType":"calls","source":1125,"target":170},{"edgeType":"calls","source":6747,"target":303},{"edgeType":"calls","source":6750,"target":210},{"edgeType":"calls","source":4666,"target":332},{"edgeType":"calls","source":3937,"target":3906},{"edgeType":"calls","source":601,"target":558},{"edgeType":"contains","source":6651,"target":6882},{"edgeType":"imports","source":2070,"target":452},{"edgeType":"contains","source":6558,"target":6594},{"edgeType":"calls","source":512,"target":146},{"edgeType":"calls","source":4017,"target":369},{"edgeType":"contains","source":1031,"target":1401},{"edgeType":"contains","source":6460,"target":6461},{"edgeType":"calls","source":1535,"target":144},{"edgeType":"contains","source":3808,"target":4107},{"edgeType":"calls","source":2817,"target":573},{"edgeType":"imports","source":2070,"target":453},{"edgeType":"imports","source":130,"target":1400},{"edgeType":"calls","source":3581,"target":2257},{"edgeType":"calls","source":7120,"target":368},{"edgeType":"imports","source":599,"target":602},{"edgeType":"calls","source":1218,"target":458},{"edgeType":"contains","source":6084,"target":6490},{"edgeType":"calls","source":5354,"target":144},{"edgeType":"calls","source":6747,"target":304},{"edgeType":"calls","source":4017,"target":366},{"edgeType":"calls","source":2295,"target":1953},{"edgeType":"contains","source":6558,"target":6595},{"edgeType":"contains","source":4544,"target":4545},{"edgeType":"extends","source":4132,"target":185},{"edgeType":"contains","source":1736,"target":1744},{"edgeType":"calls","source":3578,"target":2347},{"edgeType":"imports","source":130,"target":340},{"edgeType":"calls","source":568,"target":528},{"edgeType":"calls","source":2962,"target":303},{"edgeType":"calls","source":7120,"target":369},{"edgeType":"calls","source":6843,"target":6842},{"edgeType":"calls","source":6947,"target":447},{"edgeType":"calls","source":5125,"target":5129},{"edgeType":"contains","source":6084,"target":6491},{"edgeType":"calls","source":6602,"target":572},{"edgeType":"contains","source":6651,"target":6884},{"edgeType":"calls","source":4802,"target":342},{"edgeType":"contains","source":2562,"target":2565},{"edgeType":"contains","source":4502,"target":4788},{"edgeType":"contains","source":976,"target":994},{"edgeType":"calls","source":568,"target":527},{"edgeType":"contains","source":1075,"target":1096},{"edgeType":"contains","source":5686,"target":6145},{"edgeType":"calls","source":3023,"target":527},{"edgeType":"calls","source":6752,"target":2265},{"edgeType":"calls","source":7120,"target":370},{"edgeType":"calls","source":2962,"target":304},{"edgeType":"calls","source":3303,"target":303},{"edgeType":"calls","source":5125,"target":5128},{"edgeType":"calls","source":5425,"target":1113},{"edgeType":"calls","source":6947,"target":448},{"edgeType":"calls","source":1169,"target":922},{"edgeType":"calls","source":1093,"target":1164},{"edgeType":"calls","source":4017,"target":364},{"edgeType":"calls","source":4595,"target":4644},{"edgeType":"calls","source":6602,"target":573},{"edgeType":"contains","source":4478,"target":4483},{"edgeType":"calls","source":4296,"target":171},{"edgeType":"calls","source":6336,"target":354},{"edgeType":"calls","source":2305,"target":2698},{"edgeType":"calls","source":3578,"target":2345},{"edgeType":"calls","source":2996,"target":304},{"edgeType":"contains","source":5196,"target":5479},{"edgeType":"calls","source":5092,"target":5093},{"edgeType":"calls","source":7120,"target":371},{"edgeType":"contains","source":1509,"target":1388},{"edgeType":"calls","source":6843,"target":6844},{"edgeType":"imports","source":6459,"target":2872},{"edgeType":"extends","source":4478,"target":36},{"edgeType":"calls","source":5425,"target":1112},{"edgeType":"calls","source":6772,"target":4817},{"edgeType":"calls","source":4755,"target":1797},{"edgeType":"contains","source":6988,"target":7001},{"edgeType":"contains","source":4478,"target":4482},{"edgeType":"contains","source":4558,"target":4116},{"edgeType":"extends","source":3796,"target":36},{"edgeType":"calls","source":533,"target":548},{"edgeType":"contains","source":6651,"target":6878},{"edgeType":"calls","source":1524,"target":1538},{"edgeType":"contains","source":6558,"target":6589},{"edgeType":"contains","source":162,"target":1918},{"edgeType":"calls","source":3578,"target":2346},{"edgeType":"contains","source":1509,"target":1389},{"edgeType":"calls","source":1009,"target":591},{"edgeType":"extends","source":2739,"target":36},{"edgeType":"imports","source":6530,"target":2784},{"edgeType":"contains","source":5285,"target":5890},{"edgeType":"calls","source":7078,"target":6960},{"edgeType":"calls","source":7106,"target":6092},{"edgeType":"calls","source":5451,"target":304},{"edgeType":"calls","source":6136,"target":210},{"edgeType":"contains","source":4000,"target":4500},{"edgeType":"calls","source":1818,"target":1941},{"edgeType":"calls","source":601,"target":557},{"edgeType":"contains","source":4544,"target":4549},{"edgeType":"calls","source":4070,"target":4004},{"edgeType":"calls","source":6445,"target":144},{"edgeType":"contains","source":4478,"target":4481},{"edgeType":"contains","source":4307,"target":5553},{"edgeType":"contains","source":162,"target":1921},{"edgeType":"contains","source":1736,"target":1748},{"edgeType":"calls","source":6810,"target":6812},{"edgeType":"calls","source":1218,"target":457},{"edgeType":"calls","source":3341,"target":3348},{"edgeType":"calls","source":3578,"target":2343},{"edgeType":"calls","source":5451,"target":303},{"edgeType":"calls","source":6136,"target":209},{"edgeType":"contains","source":1814,"target":2502},{"edgeType":"contains","source":6651,"target":6880},{"edgeType":"contains","source":4544,"target":4548},{"edgeType":"calls","source":601,"target":556},{"edgeType":"calls","source":4296,"target":170},{"edgeType":"contains","source":4478,"target":4480},{"edgeType":"calls","source":6479,"target":146},{"edgeType":"contains","source":349,"target":352},{"edgeType":"imports","source":130,"target":336},{"edgeType":"calls","source":3578,"target":2344},{"edgeType":"imports","source":5380,"target":3555},{"edgeType":"calls","source":2996,"target":303},{"edgeType":"calls","source":3103,"target":157},{"edgeType":"contains","source":5592,"target":5884},{"edgeType":"contains","source":1075,"target":1100},{"edgeType":"contains","source":5473,"target":3231},{"edgeType":"calls","source":6415,"target":6374},{"edgeType":"contains","source":6656,"target":6734},{"edgeType":"calls","source":1292,"target":1328},{"edgeType":"contains","source":2591,"target":2732},{"edgeType":"calls","source":4102,"target":1953},{"edgeType":"contains","source":4478,"target":4487},{"edgeType":"contains","source":18,"target":45},{"edgeType":"contains","source":349,"target":355},{"edgeType":"calls","source":6281,"target":6283},{"edgeType":"calls","source":600,"target":582},{"edgeType":"contains","source":1509,"target":1392},{"edgeType":"calls","source":6879,"target":447},{"edgeType":"calls","source":3024,"target":489},{"edgeType":"calls","source":4401,"target":84},{"edgeType":"contains","source":6460,"target":6468},{"edgeType":"extends","source":45,"target":47},{"edgeType":"calls","source":5316,"target":1316},{"edgeType":"calls","source":3578,"target":2341},{"edgeType":"calls","source":1832,"target":1500},{"edgeType":"contains","source":4478,"target":4486},{"edgeType":"contains","source":2495,"target":2538},{"edgeType":"contains","source":2330,"target":2368},{"edgeType":"calls","source":434,"target":442},{"edgeType":"calls","source":6281,"target":6282},{"edgeType":"calls","source":4999,"target":571},{"edgeType":"calls","source":4533,"target":4447},{"edgeType":"contains","source":4091,"target":2741},{"edgeType":"calls","source":6879,"target":448},{"edgeType":"contains","source":1509,"target":1393},{"edgeType":"contains","source":6460,"target":6469},{"edgeType":"calls","source":5316,"target":1315},{"edgeType":"imports","source":130,"target":351},{"edgeType":"calls","source":5509,"target":4845},{"edgeType":"calls","source":3578,"target":2342},{"edgeType":"calls","source":7010,"target":5901},{"edgeType":"calls","source":5433,"target":5086},{"edgeType":"contains","source":2495,"target":2535},{"edgeType":"contains","source":349,"target":357},{"edgeType":"contains","source":2331,"target":2334},{"edgeType":"calls","source":601,"target":553},{"edgeType":"calls","source":468,"target":448},{"edgeType":"contains","source":1509,"target":1390},{"edgeType":"contains","source":976,"target":1003},{"edgeType":"contains","source":6460,"target":6470},{"edgeType":"contains","source":1075,"target":1105},{"edgeType":"calls","source":5797,"target":144},{"edgeType":"contains","source":349,"target":356},{"edgeType":"calls","source":468,"target":447},{"edgeType":"contains","source":4313,"target":4314},{"edgeType":"calls","source":3024,"target":488},{"edgeType":"calls","source":6612,"target":6613},{"edgeType":"contains","source":1509,"target":1391},{"edgeType":"calls","source":4477,"target":1953},{"edgeType":"calls","source":3475,"target":3419},{"edgeType":"calls","source":1350,"target":588},{"edgeType":"contains","source":1075,"target":1104},{"edgeType":"calls","source":5454,"target":4433},{"edgeType":"contains","source":1076,"target":1077},{"edgeType":"contains","source":1174,"target":1210},{"edgeType":"contains","source":349,"target":359},{"edgeType":"calls","source":5033,"target":571},{"edgeType":"contains","source":3975,"target":4228},{"edgeType":"contains","source":1732,"target":1882},{"edgeType":"contains","source":52,"target":53},{"edgeType":"calls","source":6787,"target":3303},{"edgeType":"contains","source":3351,"target":3489},{"edgeType":"contains","source":4115,"target":4117},{"edgeType":"calls","source":6611,"target":303},{"edgeType":"contains","source":5593,"target":1630},{"edgeType":"extends","source":6558,"target":36},{"edgeType":"calls","source":3341,"target":3343},{"edgeType":"contains","source":4478,"target":4490},{"edgeType":"calls","source":6953,"target":3443},{"edgeType":"contains","source":349,"target":358},{"edgeType":"calls","source":4765,"target":422},{"edgeType":"calls","source":4530,"target":4536},{"edgeType":"calls","source":3729,"target":2942},{"edgeType":"calls","source":3123,"target":588},{"edgeType":"contains","source":5,"target":4680},{"edgeType":"contains","source":2591,"target":2737},{"edgeType":"calls","source":6137,"target":171},{"edgeType":"calls","source":6611,"target":304},{"edgeType":"contains","source":1031,"target":1413},{"edgeType":"extends","source":2330,"target":36},{"edgeType":"contains","source":349,"target":361},{"edgeType":"calls","source":2765,"target":1112},{"edgeType":"contains","source":2641,"target":1184},{"edgeType":"contains","source":4478,"target":4489},{"edgeType":"calls","source":3442,"target":209},{"edgeType":"contains","source":2330,"target":2369},{"edgeType":"calls","source":4765,"target":421},{"edgeType":"contains","source":1732,"target":1880},{"edgeType":"contains","source":3,"target":517},{"edgeType":"contains","source":2133,"target":2134},{"edgeType":"contains","source":30,"target":2851},{"edgeType":"contains","source":1509,"target":1394},{"edgeType":"calls","source":6708,"target":469},{"edgeType":"calls","source":4400,"target":4337},{"edgeType":"calls","source":4044,"target":573},{"edgeType":"calls","source":4358,"target":354},{"edgeType":"calls","source":5867,"target":84},{"edgeType":"calls","source":1797,"target":469},{"edgeType":"calls","source":6137,"target":170},{"edgeType":"contains","source":3166,"target":2880},{"edgeType":"calls","source":2765,"target":1113},{"edgeType":"contains","source":6651,"target":6888},{"edgeType":"extends","source":6607,"target":1691},{"edgeType":"contains","source":4478,"target":4488},{"edgeType":"contains","source":349,"target":360},{"edgeType":"calls","source":3442,"target":210},{"edgeType":"contains","source":2330,"target":2370},{"edgeType":"contains","source":1732,"target":1881},{"edgeType":"contains","source":4000,"target":4507},{"edgeType":"calls","source":2899,"target":3301},{"edgeType":"contains","source":30,"target":2850},{"edgeType":"calls","source":4477,"target":892},{"edgeType":"contains","source":6460,"target":6467},{"edgeType":"imports","source":130,"target":1402},{"edgeType":"calls","source":1748,"target":930},{"edgeType":"contains","source":1031,"target":1386},{"edgeType":"contains","source":5138,"target":5143},{"edgeType":"contains","source":3244,"target":3605},{"edgeType":"calls","source":4910,"target":4413},{"edgeType":"calls","source":4497,"target":304},{"edgeType":"contains","source":4873,"target":4901},{"edgeType":"contains","source":2956,"target":3019},{"edgeType":"imports","source":1907,"target":205},{"edgeType":"contains","source":1031,"target":1385},{"edgeType":"extends","source":4375,"target":36},{"edgeType":"calls","source":6888,"target":144},{"edgeType":"contains","source":6988,"target":6989},{"edgeType":"calls","source":5409,"target":571},{"edgeType":"calls","source":6702,"target":4853},{"edgeType":"calls","source":1331,"target":1200},{"edgeType":"calls","source":1026,"target":84},{"edgeType":"contains","source":3508,"target":3877},{"edgeType":"contains","source":5,"target":423},{"edgeType":"contains","source":3351,"target":3459},{"edgeType":"calls","source":4497,"target":303},{"edgeType":"calls","source":1696,"target":455},{"edgeType":"contains","source":6558,"target":6577},{"edgeType":"calls","source":298,"target":455},{"edgeType":"contains","source":5,"target":6768},{"edgeType":"contains","source":3057,"target":3058},{"edgeType":"contains","source":1174,"target":1183},{"edgeType":"calls","source":1052,"target":339},{"edgeType":"contains","source":6558,"target":6578},{"edgeType":"calls","source":4220,"target":431},{"edgeType":"calls","source":4867,"target":1515},{"edgeType":"contains","source":5196,"target":5456},{"edgeType":"contains","source":1174,"target":1182},{"edgeType":"calls","source":1239,"target":883},{"edgeType":"calls","source":6947,"target":431},{"edgeType":"calls","source":1052,"target":338},{"edgeType":"calls","source":1052,"target":337},{"edgeType":"calls","source":5235,"target":3849},{"edgeType":"calls","source":6513,"target":144},{"edgeType":"contains","source":6558,"target":6579},{"edgeType":"contains","source":579,"target":600},{"edgeType":"contains","source":6245,"target":5712},{"edgeType":"calls","source":2106,"target":431},{"edgeType":"calls","source":4206,"target":4035},{"edgeType":"contains","source":6554,"target":6696},{"edgeType":"calls","source":5655,"target":5626},{"edgeType":"calls","source":3710,"target":384},{"edgeType":"contains","source":2925,"target":2928},{"edgeType":"calls","source":7117,"target":447},{"edgeType":"contains","source":5285,"target":5875},{"edgeType":"calls","source":7044,"target":596},{"edgeType":"calls","source":468,"target":467},{"edgeType":"calls","source":6129,"target":445},{"edgeType":"contains","source":6476,"target":7000},{"edgeType":"contains","source":6554,"target":6697},{"edgeType":"calls","source":2154,"target":2111},{"edgeType":"contains","source":2925,"target":2929},{"edgeType":"contains","source":4940,"target":4942},{"edgeType":"calls","source":1341,"target":886},{"edgeType":"calls","source":1292,"target":1348},{"edgeType":"contains","source":5196,"target":5462},{"edgeType":"calls","source":1694,"target":1570},{"edgeType":"calls","source":7117,"target":448},{"edgeType":"calls","source":6874,"target":582},{"edgeType":"imports","source":3013,"target":1853},{"edgeType":"calls","source":468,"target":466},{"edgeType":"contains","source":2586,"target":1810},{"edgeType":"calls","source":4768,"target":354},{"edgeType":"calls","source":7107,"target":7101},{"edgeType":"calls","source":6304,"target":304},{"edgeType":"contains","source":6459,"target":6471},{"edgeType":"calls","source":534,"target":534},{"edgeType":"calls","source":3710,"target":382},{"edgeType":"contains","source":4940,"target":4941},{"edgeType":"contains","source":2925,"target":2926},{"edgeType":"contains","source":2924,"target":2957},{"edgeType":"calls","source":5655,"target":339},{"edgeType":"calls","source":6808,"target":1572},{"edgeType":"contains","source":3351,"target":3462},{"edgeType":"extends","source":6114,"target":36},{"edgeType":"calls","source":6129,"target":443},{"edgeType":"calls","source":4035,"target":4048},{"edgeType":"calls","source":4224,"target":303},{"edgeType":"calls","source":567,"target":571},{"edgeType":"calls","source":4536,"target":146},{"edgeType":"calls","source":6304,"target":303},{"edgeType":"contains","source":5,"target":4658},{"edgeType":"contains","source":6604,"target":3034},{"edgeType":"contains","source":6554,"target":6698},{"edgeType":"contains","source":2925,"target":2927},{"edgeType":"calls","source":5622,"target":304},{"edgeType":"calls","source":5655,"target":338},{"edgeType":"calls","source":1591,"target":537},{"edgeType":"contains","source":579,"target":604},{"edgeType":"calls","source":6303,"target":333},{"edgeType":"calls","source":4224,"target":304},{"edgeType":"calls","source":2456,"target":2261},{"edgeType":"calls","source":3710,"target":380},{"edgeType":"contains","source":6988,"target":6996},{"edgeType":"calls","source":2374,"target":571},{"edgeType":"calls","source":298,"target":447},{"edgeType":"calls","source":3058,"target":508},{"edgeType":"calls","source":5655,"target":337},{"edgeType":"calls","source":1808,"target":147},{"edgeType":"calls","source":5284,"target":210},{"edgeType":"contains","source":3351,"target":3468},{"edgeType":"calls","source":5622,"target":303},{"edgeType":"imports","source":5380,"target":3523},{"edgeType":"calls","source":6303,"target":332},{"edgeType":"contains","source":2495,"target":2520},{"edgeType":"contains","source":1736,"target":1738},{"edgeType":"calls","source":298,"target":448},{"edgeType":"contains","source":3867,"target":3328},{"edgeType":"calls","source":468,"target":463},{"edgeType":"calls","source":6879,"target":431},{"edgeType":"calls","source":3710,"target":381},{"edgeType":"calls","source":6822,"target":84},{"edgeType":"calls","source":5284,"target":209},{"edgeType":"calls","source":3058,"target":509},{"edgeType":"calls","source":1810,"target":84},{"edgeType":"calls","source":1690,"target":1690},{"edgeType":"contains","source":6558,"target":6585},{"edgeType":"calls","source":3231,"target":431},{"edgeType":"contains","source":2495,"target":2521},{"edgeType":"extends","source":5720,"target":1691},{"edgeType":"calls","source":4599,"target":304},{"edgeType":"calls","source":468,"target":462},{"edgeType":"calls","source":4738,"target":4451},{"edgeType":"calls","source":3058,"target":506},{"edgeType":"contains","source":5,"target":4662},{"edgeType":"calls","source":2198,"target":1797},{"edgeType":"contains","source":4806,"target":4871},{"edgeType":"calls","source":5245,"target":4588},{"edgeType":"calls","source":1696,"target":450},{"edgeType":"contains","source":428,"target":6347},{"edgeType":"calls","source":298,"target":450},{"edgeType":"calls","source":3243,"target":56},{"edgeType":"calls","source":4591,"target":551},{"edgeType":"calls","source":4599,"target":303},{"edgeType":"calls","source":468,"target":465},{"edgeType":"contains","source":5,"target":4661},{"edgeType":"calls","source":4336,"target":4226},{"edgeType":"calls","source":3058,"target":507},{"edgeType":"contains","source":6988,"target":6999},{"edgeType":"calls","source":6874,"target":588},{"edgeType":"calls","source":5318,"target":210},{"edgeType":"contains","source":3166,"target":1802},{"edgeType":"contains","source":3949,"target":3954},{"edgeType":"contains","source":1736,"target":1737},{"edgeType":"contains","source":4474,"target":4591},{"edgeType":"calls","source":468,"target":464},{"edgeType":"calls","source":4760,"target":596},{"edgeType":"imports","source":4307,"target":1908},{"edgeType":"contains","source":3,"target":1555},{"edgeType":"calls","source":3058,"target":504},{"edgeType":"calls","source":5318,"target":209},{"edgeType":"calls","source":6885,"target":248},{"edgeType":"calls","source":6571,"target":469},{"edgeType":"calls","source":7117,"target":2570},{"edgeType":"contains","source":6651,"target":6868},{"edgeType":"contains","source":5285,"target":5883},{"edgeType":"imports","source":4528,"target":1399},{"edgeType":"contains","source":1907,"target":2783},{"edgeType":"imports","source":1814,"target":2035},{"edgeType":"extends","source":4921,"target":36},{"edgeType":"contains","source":5,"target":4663},{"edgeType":"calls","source":3058,"target":505},{"edgeType":"calls","source":468,"target":457},{"edgeType":"calls","source":7120,"target":364},{"edgeType":"calls","source":4263,"target":146},{"edgeType":"contains","source":1907,"target":2784},{"edgeType":"calls","source":468,"target":458},{"edgeType":"contains","source":162,"target":2967},{"edgeType":"calls","source":2780,"target":2781},{"edgeType":"contains","source":3,"target":1557},{"edgeType":"calls","source":1886,"target":1955},{"edgeType":"calls","source":3925,"target":2165},{"edgeType":"contains","source":4841,"target":4847},{"edgeType":"calls","source":4052,"target":342},{"edgeType":"calls","source":4017,"target":370},{"edgeType":"contains","source":5196,"target":5469},{"edgeType":"calls","source":3581,"target":2258},{"edgeType":"calls","source":5408,"target":588},{"edgeType":"calls","source":4777,"target":66},{"edgeType":"calls","source":6956,"target":164},{"edgeType":"calls","source":468,"target":461},{"edgeType":"extends","source":5671,"target":36},{"edgeType":"calls","source":3058,"target":502},{"edgeType":"calls","source":4915,"target":1073},{"edgeType":"calls","source":6569,"target":4762},{"edgeType":"calls","source":4017,"target":371},{"edgeType":"contains","source":4841,"target":4846},{"edgeType":"calls","source":5652,"target":422},{"edgeType":"imports","source":1028,"target":1030},{"edgeType":"calls","source":4042,"target":3824},{"edgeType":"calls","source":4960,"target":4962},{"edgeType":"calls","source":6956,"target":165},{"edgeType":"calls","source":3058,"target":503},{"edgeType":"contains","source":3867,"target":3329},{"edgeType":"calls","source":7120,"target":366},{"edgeType":"calls","source":1830,"target":481},{"edgeType":"calls","source":468,"target":421},{"edgeType":"calls","source":6780,"target":303},{"edgeType":"contains","source":4075,"target":4254},{"edgeType":"contains","source":2924,"target":2938},{"edgeType":"calls","source":1938,"target":304},{"edgeType":"contains","source":2495,"target":2496},{"edgeType":"contains","source":2581,"target":887},{"edgeType":"contains","source":996,"target":1397},{"edgeType":"calls","source":1418,"target":568},{"edgeType":"contains","source":2359,"target":2483},{"edgeType":"contains","source":5732,"target":5740},{"edgeType":"calls","source":3677,"target":304},{"edgeType":"calls","source":7112,"target":582},{"edgeType":"calls","source":6979,"target":6819},{"edgeType":"calls","source":1830,"target":480},{"edgeType":"calls","source":1130,"target":1039},{"edgeType":"calls","source":3955,"target":144},{"edgeType":"calls","source":1938,"target":303},{"edgeType":"calls","source":6780,"target":304},{"edgeType":"calls","source":3638,"target":3629},{"edgeType":"contains","source":2924,"target":2939},{"edgeType":"extends","source":1717,"target":36},{"edgeType":"contains","source":4691,"target":5241},{"edgeType":"contains","source":2495,"target":2497},{"edgeType":"calls","source":6410,"target":144},{"edgeType":"calls","source":1422,"target":1500},{"edgeType":"contains","source":996,"target":1396},{"edgeType":"contains","source":3847,"target":3922},{"edgeType":"contains","source":2359,"target":2484},{"edgeType":"imports","source":2050,"target":49},{"edgeType":"contains","source":3013,"target":4408},{"edgeType":"calls","source":3272,"target":3347},{"edgeType":"calls","source":895,"target":925},{"edgeType":"contains","source":3975,"target":4182},{"edgeType":"calls","source":5058,"target":5060},{"edgeType":"calls","source":3989,"target":144},{"edgeType":"contains","source":1498,"target":1689},{"edgeType":"calls","source":3911,"target":448},{"edgeType":"contains","source":1305,"target":1330},{"edgeType":"contains","source":2924,"target":2936},{"edgeType":"contains","source":2922,"target":2998},{"edgeType":"contains","source":6558,"target":6562},{"edgeType":"contains","source":6459,"target":6460},{"edgeType":"calls","source":6473,"target":304},{"edgeType":"contains","source":5196,"target":5440},{"edgeType":"calls","source":2704,"target":2983},{"edgeType":"calls","source":5058,"target":5059},{"edgeType":"calls","source":468,"target":422},{"edgeType":"contains","source":1305,"target":1331},{"edgeType":"contains","source":41,"target":349},{"edgeType":"calls","source":6034,"target":171},{"edgeType":"contains","source":1238,"target":1294},{"edgeType":"contains","source":2924,"target":2937},{"edgeType":"calls","source":6473,"target":303},{"edgeType":"calls","source":5033,"target":548},{"edgeType":"contains","source":5196,"target":5439},{"edgeType":"contains","source":996,"target":1398},{"edgeType":"calls","source":3677,"target":303},{"edgeType":"contains","source":2359,"target":2482},{"edgeType":"contains","source":213,"target":302},{"edgeType":"imports","source":4706,"target":166},{"edgeType":"calls","source":6955,"target":6509},{"edgeType":"calls","source":5134,"target":588},{"edgeType":"contains","source":4139,"target":160},{"edgeType":"contains","source":1305,"target":1336},{"edgeType":"contains","source":4075,"target":4258},{"edgeType":"calls","source":4705,"target":144},{"edgeType":"calls","source":1797,"target":443},{"edgeType":"calls","source":6034,"target":170},{"edgeType":"calls","source":1830,"target":477},{"edgeType":"calls","source":2031,"target":588},{"edgeType":"contains","source":3847,"target":3927},{"edgeType":"calls","source":6444,"target":144},{"edgeType":"calls","source":1544,"target":886},{"edgeType":"calls","source":4317,"target":545},{"edgeType":"contains","source":2924,"target":2942},{"edgeType":"calls","source":1262,"target":1172},{"edgeType":"contains","source":1305,"target":1337},{"edgeType":"contains","source":3351,"target":3448},{"edgeType":"calls","source":5425,"target":2136},{"edgeType":"contains","source":4139,"target":159},{"edgeType":"contains","source":4075,"target":4257},{"edgeType":"calls","source":1248,"target":548},{"edgeType":"calls","source":1830,"target":476},{"edgeType":"calls","source":3911,"target":447},{"edgeType":"calls","source":5896,"target":4447},{"edgeType":"calls","source":6409,"target":171},{"edgeType":"contains","source":4411,"target":4412},{"edgeType":"calls","source":6478,"target":146},{"edgeType":"calls","source":566,"target":549},{"edgeType":"calls","source":5082,"target":84},{"edgeType":"calls","source":5077,"target":1296},{"edgeType":"calls","source":3586,"target":3122},{"edgeType":"contains","source":2924,"target":2943},{"edgeType":"contains","source":3847,"target":3926},{"edgeType":"calls","source":5062,"target":4932},{"edgeType":"calls","source":6602,"target":2656},{"edgeType":"calls","source":4773,"target":148},{"edgeType":"contains","source":4075,"target":4256},{"edgeType":"contains","source":4806,"target":4850},{"edgeType":"calls","source":1797,"target":445},{"edgeType":"extends","source":967,"target":36},{"edgeType":"calls","source":1830,"target":479},{"edgeType":"calls","source":582,"target":56},{"edgeType":"calls","source":6409,"target":170},{"edgeType":"contains","source":6651,"target":6846},{"edgeType":"contains","source":2495,"target":2498},{"edgeType":"imports","source":2879,"target":2884},{"edgeType":"contains","source":2956,"target":3005},{"edgeType":"calls","source":886,"target":146},{"edgeType":"contains","source":2924,"target":2940},{"edgeType":"contains","source":1814,"target":2468},{"edgeType":"calls","source":3817,"target":2300},{"edgeType":"calls","source":1248,"target":551},{"edgeType":"contains","source":5410,"target":6209},{"edgeType":"contains","source":4075,"target":4255},{"edgeType":"contains","source":4806,"target":4849},{"edgeType":"calls","source":1830,"target":478},{"edgeType":"contains","source":2359,"target":2486},{"edgeType":"calls","source":2832,"target":1126},{"edgeType":"contains","source":2956,"target":3006},{"edgeType":"contains","source":2924,"target":2941},{"edgeType":"calls","source":5223,"target":5224},{"edgeType":"contains","source":5410,"target":6208},{"edgeType":"calls","source":566,"target":546},{"edgeType":"contains","source":5402,"target":5407},{"edgeType":"contains","source":6557,"target":6599},{"edgeType":"contains","source":2495,"target":2504},{"edgeType":"calls","source":6946,"target":6793},{"edgeType":"calls","source":4197,"target":2146},{"edgeType":"contains","source":3847,"target":3931},{"edgeType":"contains","source":184,"target":152},{"edgeType":"calls","source":4564,"target":4511},{"edgeType":"calls","source":2963,"target":2347},{"edgeType":"contains","source":2924,"target":2946},{"edgeType":"contains","source":2956,"target":3011},{"edgeType":"calls","source":7022,"target":209},{"edgeType":"calls","source":3860,"target":965},{"edgeType":"calls","source":5432,"target":5086},{"edgeType":"calls","source":1863,"target":506},{"edgeType":"extends","source":2331,"target":36},{"edgeType":"imports","source":3030,"target":331},{"edgeType":"calls","source":5432,"target":5085},{"edgeType":"contains","source":5285,"target":5862},{"edgeType":"contains","source":4411,"target":4416},{"edgeType":"calls","source":6449,"target":1041},{"edgeType":"calls","source":6464,"target":576},{"edgeType":"contains","source":3847,"target":3930},{"edgeType":"contains","source":2924,"target":2947},{"edgeType":"calls","source":7022,"target":210},{"edgeType":"contains","source":4806,"target":4855},{"edgeType":"contains","source":3351,"target":3451},{"edgeType":"contains","source":2956,"target":3012},{"edgeType":"calls","source":1863,"target":505},{"edgeType":"imports","source":3004,"target":79},{"edgeType":"calls","source":5526,"target":56},{"edgeType":"calls","source":1863,"target":509},{"edgeType":"calls","source":2014,"target":56},{"edgeType":"calls","source":6296,"target":3669},{"edgeType":"contains","source":3847,"target":3929},{"edgeType":"calls","source":2963,"target":2344},{"edgeType":"calls","source":4766,"target":4589},{"edgeType":"contains","source":41,"target":1415},{"edgeType":"contains","source":2956,"target":3009},{"edgeType":"contains","source":132,"target":709},{"edgeType":"calls","source":2963,"target":2345},{"edgeType":"contains","source":2924,"target":2944},{"edgeType":"calls","source":3932,"target":1902},{"edgeType":"calls","source":1863,"target":508},{"edgeType":"contains","source":6554,"target":6695},{"edgeType":"contains","source":5402,"target":5404},{"edgeType":"contains","source":4139,"target":161},{"edgeType":"imports","source":3004,"target":78},{"edgeType":"calls","source":6912,"target":6793},{"edgeType":"contains","source":2330,"target":2333},{"edgeType":"contains","source":5730,"target":1585},{"edgeType":"contains","source":4378,"target":4380},{"edgeType":"calls","source":5018,"target":5233},{"edgeType":"contains","source":2956,"target":3010},{"edgeType":"calls","source":2963,"target":2346},{"edgeType":"contains","source":2924,"target":2945},{"edgeType":"contains","source":1031,"target":1378},{"edgeType":"calls","source":6546,"target":170},{"edgeType":"calls","source":1863,"target":507},{"edgeType":"contains","source":3013,"target":4414},{"edgeType":"calls","source":4856,"target":1797},{"edgeType":"contains","source":5196,"target":5455},{"edgeType":"calls","source":7117,"target":2553},{"edgeType":"calls","source":7009,"target":5901},{"edgeType":"imports","source":4528,"target":4620},{"edgeType":"calls","source":6986,"target":3443},{"edgeType":"calls","source":530,"target":601},{"edgeType":"calls","source":4892,"target":4909},{"edgeType":"calls","source":2963,"target":2342},{"edgeType":"contains","source":3351,"target":3456},{"edgeType":"contains","source":5732,"target":5744},{"edgeType":"contains","source":579,"target":595},{"edgeType":"calls","source":3715,"target":171},{"edgeType":"calls","source":1863,"target":502},{"edgeType":"imports","source":5285,"target":179},{"edgeType":"contains","source":1031,"target":1381},{"edgeType":"contains","source":2924,"target":2950},{"edgeType":"calls","source":6546,"target":171},{"edgeType":"contains","source":2956,"target":3015},{"edgeType":"contains","source":3123,"target":3125},{"edgeType":"contains","source":1174,"target":1176},{"edgeType":"calls","source":2963,"target":2343},{"edgeType":"calls","source":4892,"target":4908},{"edgeType":"imports","source":2898,"target":190},{"edgeType":"contains","source":2956,"target":3016},{"edgeType":"contains","source":599,"target":1031},{"edgeType":"contains","source":2924,"target":2951},{"edgeType":"calls","source":2079,"target":147},{"edgeType":"contains","source":1031,"target":1380},{"edgeType":"calls","source":4800,"target":4588},{"edgeType":"contains","source":4558,"target":4090},{"edgeType":"calls","source":6878,"target":6793},{"edgeType":"contains","source":1031,"target":1384},{"edgeType":"calls","source":4878,"target":56},{"edgeType":"contains","source":162,"target":2954},{"edgeType":"contains","source":6554,"target":6690},{"edgeType":"contains","source":5402,"target":5409},{"edgeType":"imports","source":1907,"target":1313},{"edgeType":"calls","source":4892,"target":4907},{"edgeType":"contains","source":6359,"target":6393},{"edgeType":"contains","source":132,"target":713},{"edgeType":"calls","source":1863,"target":504},{"edgeType":"contains","source":3351,"target":3454},{"edgeType":"contains","source":579,"target":597},{"edgeType":"calls","source":6089,"target":568},{"edgeType":"contains","source":2924,"target":2948},{"edgeType":"calls","source":4218,"target":431},{"edgeType":"calls","source":7044,"target":591},{"edgeType":"calls","source":1226,"target":1224},{"edgeType":"calls","source":2887,"target":469},{"edgeType":"contains","source":3847,"target":3932},{"edgeType":"calls","source":4892,"target":4906},{"edgeType":"calls","source":2963,"target":2341},{"edgeType":"calls","source":5018,"target":5228},{"edgeType":"contains","source":5732,"target":5747},{"edgeType":"calls","source":3715,"target":170},{"edgeType":"calls","source":6583,"target":84},{"edgeType":"calls","source":1863,"target":503},{"edgeType":"contains","source":1031,"target":1382},{"edgeType":"imports","source":435,"target":436},{"edgeType":"contains","source":2924,"target":2949},{"edgeType":"contains","source":1031,"target":1353},{"edgeType":"calls","source":2799,"target":1113},{"edgeType":"calls","source":3566,"target":591},{"edgeType":"contains","source":2359,"target":2467},{"edgeType":"calls","source":3373,"target":3403},{"edgeType":"calls","source":1524,"target":1527},{"edgeType":"calls","source":2704,"target":3001},{"edgeType":"calls","source":896,"target":911},{"edgeType":"calls","source":2963,"target":1314},{"edgeType":"calls","source":941,"target":573},{"edgeType":"calls","source":1093,"target":1147},{"edgeType":"contains","source":17,"target":19},{"edgeType":"calls","source":1801,"target":339},{"edgeType":"calls","source":1093,"target":1146},{"edgeType":"calls","source":1118,"target":371},{"edgeType":"contains","source":1297,"target":1564},{"edgeType":"calls","source":4477,"target":891},{"edgeType":"calls","source":6808,"target":1533},{"edgeType":"contains","source":2263,"target":2272},{"edgeType":"contains","source":6476,"target":6972},{"edgeType":"calls","source":1400,"target":1142},{"edgeType":"calls","source":941,"target":572},{"edgeType":"calls","source":896,"target":910},{"edgeType":"calls","source":6646,"target":6556},{"edgeType":"calls","source":1118,"target":370},{"edgeType":"contains","source":1297,"target":1565},{"edgeType":"calls","source":6670,"target":527},{"edgeType":"calls","source":1801,"target":338},{"edgeType":"calls","source":4044,"target":572},{"edgeType":"calls","source":298,"target":422},{"edgeType":"contains","source":3013,"target":4389},{"edgeType":"imports","source":3981,"target":2540},{"edgeType":"contains","source":3975,"target":4164},{"edgeType":"calls","source":6670,"target":528},{"edgeType":"calls","source":3817,"target":2321},{"edgeType":"contains","source":16,"target":52},{"edgeType":"contains","source":1297,"target":1562},{"edgeType":"calls","source":6546,"target":144},{"edgeType":"contains","source":2263,"target":2270},{"edgeType":"calls","source":3704,"target":3710},{"edgeType":"calls","source":4935,"target":431},{"edgeType":"contains","source":2359,"target":2466},{"edgeType":"calls","source":2799,"target":1112},{"edgeType":"calls","source":6887,"target":144},{"edgeType":"contains","source":5380,"target":6061},{"edgeType":"contains","source":5616,"target":6151},{"edgeType":"calls","source":1093,"target":1148},{"edgeType":"contains","source":4113,"target":4114},{"edgeType":"contains","source":6817,"target":6973},{"edgeType":"calls","source":4535,"target":147},{"edgeType":"imports","source":130,"target":354},{"edgeType":"calls","source":2158,"target":1953},{"edgeType":"contains","source":1031,"target":1357},{"edgeType":"calls","source":4801,"target":4584},{"edgeType":"calls","source":1656,"target":1659},{"edgeType":"calls","source":5341,"target":528},{"edgeType":"contains","source":1498,"target":1679},{"edgeType":"calls","source":7025,"target":1152},{"edgeType":"contains","source":1297,"target":1568},{"edgeType":"contains","source":6161,"target":6162},{"edgeType":"calls","source":6484,"target":1011},{"edgeType":"calls","source":2514,"target":431},{"edgeType":"contains","source":6651,"target":6827},{"edgeType":"calls","source":434,"target":431},{"edgeType":"calls","source":6334,"target":4627},{"edgeType":"calls","source":6994,"target":1057},{"edgeType":"contains","source":5908,"target":6606},{"edgeType":"calls","source":941,"target":568},{"edgeType":"calls","source":4801,"target":4583},{"edgeType":"calls","source":1656,"target":1658},{"edgeType":"calls","source":5341,"target":527},{"edgeType":"contains","source":1498,"target":1680},{"edgeType":"calls","source":6544,"target":6551},{"edgeType":"contains","source":1297,"target":1569},{"edgeType":"calls","source":6841,"target":1572},{"edgeType":"contains","source":5410,"target":6194},{"edgeType":"calls","source":1118,"target":366},{"edgeType":"contains","source":4806,"target":4834},{"edgeType":"calls","source":2614,"target":2617},{"edgeType":"calls","source":4194,"target":146},{"edgeType":"contains","source":2176,"target":2860},{"edgeType":"calls","source":6464,"target":596},{"edgeType":"contains","source":4432,"target":4801},{"edgeType":"calls","source":6334,"target":4626},{"edgeType":"calls","source":470,"target":371},{"edgeType":"contains","source":4391,"target":5015},{"edgeType":"contains","source":2359,"target":2472},{"edgeType":"imports","source":130,"target":1409},{"edgeType":"contains","source":2359,"target":2469},{"edgeType":"contains","source":996,"target":1387},{"edgeType":"contains","source":2955,"target":3020},{"edgeType":"contains","source":2922,"target":2986},{"edgeType":"calls","source":5283,"target":210},{"edgeType":"contains","source":1075,"target":1052},{"edgeType":"contains","source":5596,"target":5709},{"edgeType":"contains","source":1297,"target":1566},{"edgeType":"calls","source":1118,"target":369},{"edgeType":"calls","source":1801,"target":337},{"edgeType":"contains","source":742,"target":804},{"edgeType":"calls","source":533,"target":535},{"edgeType":"contains","source":2263,"target":2274},{"edgeType":"calls","source":6334,"target":4625},{"edgeType":"calls","source":298,"target":421},{"edgeType":"imports","source":3004,"target":49},{"edgeType":"contains","source":2359,"target":2470},{"edgeType":"contains","source":3847,"target":3907},{"edgeType":"calls","source":5757,"target":5599},{"edgeType":"calls","source":2148,"target":148},{"edgeType":"contains","source":2955,"target":3021},{"edgeType":"calls","source":5283,"target":209},{"edgeType":"contains","source":1498,"target":1678},{"edgeType":"calls","source":1340,"target":886},{"edgeType":"contains","source":1297,"target":1567},{"edgeType":"imports","source":5116,"target":128},{"edgeType":"calls","source":1118,"target":368},{"edgeType":"contains","source":6817,"target":6969},{"edgeType":"contains","source":742,"target":803},{"edgeType":"calls","source":4876,"target":142},{"edgeType":"extends","source":3626,"target":36},{"edgeType":"calls","source":6890,"target":56},{"edgeType":"contains","source":6817,"target":6979},{"edgeType":"contains","source":4806,"target":4840},{"edgeType":"calls","source":3477,"target":171},{"edgeType":"contains","source":5196,"target":5434},{"edgeType":"calls","source":4832,"target":448},{"edgeType":"contains","source":1920,"target":1286},{"edgeType":"calls","source":3477,"target":170},{"edgeType":"imports","source":5380,"target":3556},{"edgeType":"contains","source":5380,"target":6072},{"edgeType":"imports","source":6604,"target":5780},{"edgeType":"contains","source":4113,"target":4125},{"edgeType":"calls","source":1125,"target":146},{"edgeType":"calls","source":470,"target":368},{"edgeType":"calls","source":471,"target":337},{"edgeType":"contains","source":1498,"target":1684},{"edgeType":"calls","source":6819,"target":6486},{"edgeType":"extends","source":2160,"target":36},{"edgeType":"contains","source":1297,"target":1573},{"edgeType":"contains","source":1305,"target":1325},{"edgeType":"contains","source":1031,"target":1360},{"edgeType":"contains","source":3975,"target":4174},{"edgeType":"calls","source":4832,"target":447},{"edgeType":"contains","source":1920,"target":1287},{"edgeType":"contains","source":5380,"target":6071},{"edgeType":"calls","source":6148,"target":5103},{"edgeType":"contains","source":742,"target":805},{"edgeType":"contains","source":3847,"target":3914},{"edgeType":"calls","source":4291,"target":3475},{"edgeType":"calls","source":4963,"target":4841},{"edgeType":"calls","source":1801,"target":333},{"edgeType":"calls","source":3546,"target":144},{"edgeType":"contains","source":1498,"target":1681},{"edgeType":"calls","source":1656,"target":1657},{"edgeType":"contains","source":1031,"target":1363},{"edgeType":"calls","source":1524,"target":1521},{"edgeType":"contains","source":3975,"target":4173},{"edgeType":"contains","source":1920,"target":1284},{"edgeType":"calls","source":2615,"target":2579},{"edgeType":"calls","source":1236,"target":935},{"edgeType":"contains","source":6651,"target":6841},{"edgeType":"imports","source":2879,"target":2880},{"edgeType":"calls","source":4230,"target":1137},{"edgeType":"calls","source":2079,"target":171},{"edgeType":"contains","source":4502,"target":4748},{"edgeType":"calls","source":6464,"target":591},{"edgeType":"contains","source":4391,"target":5018},{"edgeType":"contains","source":2359,"target":2473},{"edgeType":"calls","source":470,"target":370},{"edgeType":"calls","source":471,"target":339},{"edgeType":"imports","source":4091,"target":179},{"edgeType":"contains","source":4307,"target":5507},{"edgeType":"contains","source":2263,"target":2279},{"edgeType":"contains","source":1498,"target":1682},{"edgeType":"imports","source":1907,"target":1300},{"edgeType":"contains","source":2677,"target":5301},{"edgeType":"calls","source":1801,"target":332},{"edgeType":"contains","source":4873,"target":4874},{"edgeType":"calls","source":5662,"target":84},{"edgeType":"contains","source":1920,"target":1285},{"edgeType":"calls","source":1236,"target":934},{"edgeType":"contains","source":437,"target":749},{"edgeType":"contains","source":3975,"target":4172},{"edgeType":"calls","source":2079,"target":170},{"edgeType":"calls","source":1118,"target":364},{"edgeType":"calls","source":4590,"target":548},{"edgeType":"contains","source":4113,"target":4122},{"edgeType":"calls","source":470,"target":369},{"edgeType":"calls","source":471,"target":338},{"edgeType":"contains","source":2359,"target":2474},{"edgeType":"imports","source":1303,"target":996},{"edgeType":"calls","source":6785,"target":144},{"edgeType":"contains","source":4113,"target":4129},{"edgeType":"contains","source":1498,"target":1687},{"edgeType":"calls","source":2559,"target":84},{"edgeType":"calls","source":1524,"target":458},{"edgeType":"contains","source":4806,"target":4844},{"edgeType":"contains","source":5232,"target":5379},{"edgeType":"contains","source":3847,"target":3919},{"edgeType":"contains","source":5196,"target":5438},{"edgeType":"calls","source":1295,"target":157},{"edgeType":"contains","source":6817,"target":6974},{"edgeType":"contains","source":2359,"target":2479},{"edgeType":"calls","source":1524,"target":457},{"edgeType":"calls","source":470,"target":364},{"edgeType":"calls","source":2921,"target":2604},{"edgeType":"contains","source":5,"target":4630},{"edgeType":"calls","source":5123,"target":5163},{"edgeType":"contains","source":6476,"target":6976},{"edgeType":"contains","source":5616,"target":6153},{"edgeType":"contains","source":1498,"target":1688},{"edgeType":"contains","source":4307,"target":5513},{"edgeType":"calls","source":1887,"target":1888},{"edgeType":"calls","source":4338,"target":958},{"edgeType":"calls","source":6445,"target":6457},{"edgeType":"imports","source":130,"target":1420},{"edgeType":"calls","source":6534,"target":527},{"edgeType":"contains","source":4806,"target":4843},{"edgeType":"contains","source":2924,"target":2935},{"edgeType":"contains","source":4873,"target":4880},{"edgeType":"calls","source":4766,"target":4603},{"edgeType":"contains","source":5232,"target":5378},{"edgeType":"calls","source":7110,"target":2755},{"edgeType":"contains","source":5196,"target":5437},{"edgeType":"calls","source":6410,"target":148},{"edgeType":"contains","source":6817,"target":6975},{"edgeType":"calls","source":532,"target":555},{"edgeType":"contains","source":2359,"target":2480},{"edgeType":"calls","source":4926,"target":4928},{"edgeType":"calls","source":2912,"target":2884},{"edgeType":"contains","source":3975,"target":4178},{"edgeType":"calls","source":4805,"target":4451},{"edgeType":"calls","source":6680,"target":6572},{"edgeType":"calls","source":6822,"target":56},{"edgeType":"contains","source":1297,"target":1574},{"edgeType":"calls","source":6534,"target":528},{"edgeType":"contains","source":996,"target":1395},{"edgeType":"contains","source":3188,"target":3204},{"edgeType":"calls","source":4738,"target":4413},{"edgeType":"contains","source":5196,"target":5436},{"edgeType":"calls","source":5681,"target":548},{"edgeType":"contains","source":2359,"target":2477},{"edgeType":"calls","source":470,"target":366},{"edgeType":"contains","source":3975,"target":4177},{"edgeType":"contains","source":1920,"target":1288},{"edgeType":"contains","source":1498,"target":1686},{"edgeType":"contains","source":1297,"target":1575},{"edgeType":"extends","source":340,"target":437},{"edgeType":"calls","source":3710,"target":342},{"edgeType":"contains","source":6817,"target":6978},{"edgeType":"calls","source":2253,"target":56},{"edgeType":"contains","source":5196,"target":5435},{"edgeType":"calls","source":4014,"target":431},{"edgeType":"calls","source":6469,"target":431},{"edgeType":"contains","source":5380,"target":6073},{"edgeType":"contains","source":1920,"target":1289},{"edgeType":"contains","source":3847,"target":3916},{"edgeType":"contains","source":4806,"target":4815},{"edgeType":"contains","source":2206,"target":2965},{"edgeType":"calls","source":1818,"target":2009},{"edgeType":"contains","source":6280,"target":6688},{"edgeType":"contains","source":6557,"target":6558},{"edgeType":"contains","source":3116,"target":3295},{"edgeType":"extends","source":2123,"target":167},{"edgeType":"calls","source":6374,"target":303},{"edgeType":"contains","source":996,"target":1364},{"edgeType":"contains","source":4391,"target":4995},{"edgeType":"contains","source":2359,"target":2450},{"edgeType":"imports","source":435,"target":466},{"edgeType":"calls","source":6774,"target":4817},{"edgeType":"contains","source":5596,"target":5695},{"edgeType":"contains","source":4806,"target":4814},{"edgeType":"calls","source":6688,"target":84},{"edgeType":"calls","source":4672,"target":212},{"edgeType":"calls","source":4470,"target":1189},{"edgeType":"calls","source":2252,"target":2298},{"edgeType":"calls","source":7029,"target":84},{"edgeType":"calls","source":3549,"target":144},{"edgeType":"calls","source":883,"target":339},{"edgeType":"extends","source":5196,"target":36},{"edgeType":"contains","source":5596,"target":5696},{"edgeType":"imports","source":2879,"target":2922},{"edgeType":"imports","source":435,"target":467},{"edgeType":"calls","source":4874,"target":3464},{"edgeType":"calls","source":4880,"target":3278},{"edgeType":"calls","source":2962,"target":372},{"edgeType":"calls","source":998,"target":1005},{"edgeType":"imports","source":435,"target":464},{"edgeType":"calls","source":5354,"target":210},{"edgeType":"calls","source":4291,"target":3566},{"edgeType":"contains","source":3808,"target":4040},{"edgeType":"contains","source":1031,"target":1338},{"edgeType":"contains","source":996,"target":1366},{"edgeType":"contains","source":162,"target":3965},{"edgeType":"contains","source":4391,"target":4993},{"edgeType":"contains","source":2359,"target":2448},{"edgeType":"contains","source":5596,"target":5697},{"edgeType":"calls","source":5354,"target":209},{"edgeType":"imports","source":435,"target":465},{"edgeType":"contains","source":2206,"target":2964},{"edgeType":"contains","source":4375,"target":4431},{"edgeType":"imports","source":2050,"target":79},{"edgeType":"contains","source":6476,"target":5901},{"edgeType":"contains","source":996,"target":1365},{"edgeType":"calls","source":4808,"target":4451},{"edgeType":"contains","source":2359,"target":2449},{"edgeType":"contains","source":4391,"target":4992},{"edgeType":"extends","source":179,"target":180},{"edgeType":"calls","source":6845,"target":6847},{"edgeType":"extends","source":3116,"target":36},{"edgeType":"calls","source":5117,"target":157},{"edgeType":"imports","source":435,"target":462},{"edgeType":"calls","source":2329,"target":963},{"edgeType":"imports","source":2050,"target":78},{"edgeType":"contains","source":4307,"target":4432},{"edgeType":"contains","source":4391,"target":5000},{"edgeType":"calls","source":4299,"target":144},{"edgeType":"imports","source":6824,"target":79},{"edgeType":"contains","source":1031,"target":1340},{"edgeType":"contains","source":2956,"target":2974},{"edgeType":"contains","source":996,"target":1368},{"edgeType":"calls","source":4702,"target":4565},{"edgeType":"calls","source":6845,"target":6848},{"edgeType":"calls","source":2997,"target":339},{"edgeType":"calls","source":1196,"target":146},{"edgeType":"calls","source":5237,"target":4891},{"edgeType":"imports","source":435,"target":463},{"edgeType":"contains","source":5596,"target":5691},{"edgeType":"contains","source":6280,"target":6685},{"edgeType":"calls","source":2584,"target":2572},{"edgeType":"contains","source":6656,"target":6657},{"edgeType":"contains","source":996,"target":1367},{"edgeType":"calls","source":6853,"target":259},{"edgeType":"contains","source":3781,"target":3825},{"edgeType":"contains","source":1031,"target":1339},{"edgeType":"imports","source":6824,"target":78},{"edgeType":"contains","source":5908,"target":3419},{"edgeType":"imports","source":1028,"target":49},{"edgeType":"calls","source":4597,"target":4646},{"edgeType":"contains","source":1379,"target":1121},{"edgeType":"calls","source":1672,"target":1248},{"edgeType":"calls","source":7012,"target":5901},{"edgeType":"calls","source":1956,"target":1957},{"edgeType":"calls","source":6215,"target":5226},{"edgeType":"contains","source":6623,"target":6624},{"edgeType":"calls","source":5103,"target":588},{"edgeType":"contains","source":1031,"target":1342},{"edgeType":"contains","source":996,"target":1370},{"edgeType":"extends","source":4988,"target":1202},{"edgeType":"calls","source":2997,"target":337},{"edgeType":"calls","source":4842,"target":4451},{"edgeType":"calls","source":5094,"target":5095},{"edgeType":"calls","source":883,"target":338},{"edgeType":"calls","source":3430,"target":2769},{"edgeType":"calls","source":5237,"target":4890},{"edgeType":"calls","source":1781,"target":1039},{"edgeType":"calls","source":3992,"target":147},{"edgeType":"calls","source":2594,"target":146},{"edgeType":"calls","source":4597,"target":4645},{"edgeType":"contains","source":3351,"target":3411},{"edgeType":"contains","source":6280,"target":6687},{"edgeType":"contains","source":32,"target":599},{"edgeType":"imports","source":5592,"target":4447},{"edgeType":"imports","source":435,"target":461},{"edgeType":"calls","source":2329,"target":962},{"edgeType":"contains","source":5,"target":6721},{"edgeType":"contains","source":185,"target":84},{"edgeType":"contains","source":1031,"target":1341},{"edgeType":"contains","source":2956,"target":2973},{"edgeType":"calls","source":2997,"target":338},{"edgeType":"calls","source":6959,"target":146},{"edgeType":"extends","source":2128,"target":2129},{"edgeType":"contains","source":996,"target":1369},{"edgeType":"calls","source":883,"target":337},{"edgeType":"calls","source":6584,"target":144},{"edgeType":"calls","source":1162,"target":144},{"edgeType":"calls","source":5237,"target":4889},{"edgeType":"contains","source":5380,"target":6056},{"edgeType":"contains","source":2359,"target":2459},{"edgeType":"calls","source":2616,"target":2632},{"edgeType":"contains","source":5908,"target":6601},{"edgeType":"contains","source":2263,"target":2264},{"edgeType":"calls","source":6647,"target":6648},{"edgeType":"calls","source":4963,"target":4926},{"edgeType":"contains","source":2922,"target":2975},{"edgeType":"contains","source":5730,"target":5777},{"edgeType":"contains","source":5596,"target":5703},{"edgeType":"calls","source":6749,"target":6657},{"edgeType":"contains","source":996,"target":1372},{"edgeType":"calls","source":1325,"target":371},{"edgeType":"contains","source":1305,"target":1308},{"edgeType":"calls","source":4597,"target":4643},{"edgeType":"calls","source":4723,"target":737},{"edgeType":"calls","source":6978,"target":5901},{"edgeType":"calls","source":1325,"target":370},{"edgeType":"calls","source":6955,"target":3443},{"edgeType":"calls","source":6108,"target":84},{"edgeType":"contains","source":4502,"target":4733},{"edgeType":"calls","source":6249,"target":5226},{"edgeType":"contains","source":41,"target":1379},{"edgeType":"contains","source":5730,"target":5778},{"edgeType":"contains","source":4391,"target":5003},{"edgeType":"contains","source":437,"target":731},{"edgeType":"contains","source":5596,"target":5704},{"edgeType":"contains","source":996,"target":1371},{"edgeType":"contains","source":5458,"target":5754},{"edgeType":"extends","source":1816,"target":180},{"edgeType":"calls","source":3369,"target":431},{"edgeType":"calls","source":5597,"target":1126},{"edgeType":"calls","source":469,"target":483},{"edgeType":"calls","source":5461,"target":1113},{"edgeType":"calls","source":3911,"target":3710},{"edgeType":"calls","source":2732,"target":1148},{"edgeType":"contains","source":4391,"target":5002},{"edgeType":"contains","source":2359,"target":2457},{"edgeType":"contains","source":182,"target":183},{"edgeType":"contains","source":4307,"target":4434},{"edgeType":"contains","source":5908,"target":6603},{"edgeType":"calls","source":4300,"target":4336},{"edgeType":"calls","source":3023,"target":584},{"edgeType":"calls","source":5076,"target":1421},{"edgeType":"contains","source":6817,"target":6964},{"edgeType":"contains","source":996,"target":1374},{"edgeType":"imports","source":6604,"target":547},{"edgeType":"calls","source":6550,"target":144},{"edgeType":"contains","source":3351,"target":3417},{"edgeType":"calls","source":4801,"target":431},{"edgeType":"calls","source":1130,"target":1132},{"edgeType":"extends","source":3014,"target":36},{"edgeType":"calls","source":1196,"target":1200},{"edgeType":"calls","source":5461,"target":1112},{"edgeType":"calls","source":1097,"target":1098},{"edgeType":"calls","source":4085,"target":431},{"edgeType":"calls","source":4916,"target":1094},{"edgeType":"calls","source":2616,"target":2631},{"edgeType":"calls","source":6416,"target":6413},{"edgeType":"contains","source":996,"target":1373},{"edgeType":"contains","source":2359,"target":2463},{"edgeType":"calls","source":1292,"target":333},{"edgeType":"calls","source":4935,"target":2618},{"edgeType":"contains","source":5908,"target":6597},{"edgeType":"calls","source":4433,"target":4439},{"edgeType":"calls","source":2584,"target":2563},{"edgeType":"calls","source":2732,"target":1146},{"edgeType":"calls","source":1676,"target":56},{"edgeType":"contains","source":5730,"target":5773},{"edgeType":"contains","source":6476,"target":5902},{"edgeType":"calls","source":298,"target":493},{"edgeType":"contains","source":1305,"target":1312},{"edgeType":"contains","source":4706,"target":4756},{"edgeType":"contains","source":4806,"target":4827},{"edgeType":"contains","source":996,"target":1376},{"edgeType":"calls","source":5801,"target":84},{"edgeType":"calls","source":1325,"target":366},{"edgeType":"calls","source":1292,"target":332},{"edgeType":"contains","source":2359,"target":2464},{"edgeType":"imports","source":6245,"target":49},{"edgeType":"contains","source":182,"target":184},{"edgeType":"calls","source":2584,"target":2564},{"edgeType":"calls","source":2732,"target":1147},{"edgeType":"calls","source":298,"target":492},{"edgeType":"contains","source":2263,"target":2269},{"edgeType":"contains","source":996,"target":1375},{"edgeType":"imports","source":2581,"target":537},{"edgeType":"contains","source":4706,"target":4755},{"edgeType":"calls","source":1325,"target":369},{"edgeType":"calls","source":1079,"target":596},{"edgeType":"contains","source":2359,"target":2461},{"edgeType":"calls","source":5093,"target":5118},{"edgeType":"contains","source":6359,"target":6360},{"edgeType":"contains","source":6476,"target":5904},{"edgeType":"contains","source":5730,"target":5775},{"edgeType":"extends","source":4719,"target":36},{"edgeType":"calls","source":4401,"target":144},{"edgeType":"contains","source":940,"target":1000},{"edgeType":"contains","source":4806,"target":4825},{"edgeType":"calls","source":568,"target":580},{"edgeType":"contains","source":3188,"target":3189},{"edgeType":"calls","source":1325,"target":368},{"edgeType":"calls","source":6675,"target":502},{"edgeType":"contains","source":5730,"target":5776},{"edgeType":"calls","source":6606,"target":527},{"edgeType":"contains","source":5596,"target":5702},{"edgeType":"calls","source":4310,"target":4021},{"edgeType":"contains","source":1297,"target":1559},{"edgeType":"contains","source":996,"target":1377},{"edgeType":"calls","source":5757,"target":5673},{"edgeType":"contains","source":940,"target":999},{"edgeType":"contains","source":3781,"target":3805},{"edgeType":"contains","source":3808,"target":4025},{"edgeType":"calls","source":5569,"target":963},{"edgeType":"contains","source":1031,"target":1320},{"edgeType":"contains","source":996,"target":1348},{"edgeType":"calls","source":569,"target":577},{"edgeType":"contains","source":2359,"target":2434},{"edgeType":"calls","source":5488,"target":303},{"edgeType":"contains","source":9,"target":6576},{"edgeType":"calls","source":6753,"target":3337},{"edgeType":"imports","source":2879,"target":2907},{"edgeType":"calls","source":6685,"target":160},{"edgeType":"contains","source":16,"target":17},{"edgeType":"contains","source":1297,"target":1531},{"edgeType":"contains","source":4139,"target":1164},{"edgeType":"contains","source":3352,"target":3363},{"edgeType":"calls","source":6603,"target":588},{"edgeType":"contains","source":1031,"target":1319},{"edgeType":"calls","source":4106,"target":4035},{"edgeType":"contains","source":2359,"target":2435},{"edgeType":"calls","source":5589,"target":342},{"edgeType":"calls","source":5569,"target":962},{"edgeType":"calls","source":535,"target":573},{"edgeType":"calls","source":6753,"target":3338},{"edgeType":"contains","source":5410,"target":6157},{"edgeType":"contains","source":5726,"target":5877},{"edgeType":"imports","source":6530,"target":2829},{"edgeType":"calls","source":6934,"target":898},{"edgeType":"calls","source":6685,"target":161},{"edgeType":"calls","source":7084,"target":6819},{"edgeType":"calls","source":4606,"target":161},{"edgeType":"calls","source":471,"target":443},{"edgeType":"calls","source":4495,"target":431},{"edgeType":"imports","source":3981,"target":1515},{"edgeType":"contains","source":4671,"target":4754},{"edgeType":"extends","source":2263,"target":36},{"edgeType":"calls","source":3342,"target":3404},{"edgeType":"contains","source":2359,"target":2432},{"edgeType":"calls","source":5414,"target":481},{"edgeType":"calls","source":5015,"target":165},{"edgeType":"calls","source":6753,"target":3339},{"edgeType":"calls","source":6591,"target":962},{"edgeType":"contains","source":1297,"target":1529},{"edgeType":"calls","source":4606,"target":160},{"edgeType":"contains","source":996,"target":1349},{"edgeType":"calls","source":5015,"target":164},{"edgeType":"contains","source":2359,"target":2433},{"edgeType":"contains","source":182,"target":157},{"edgeType":"calls","source":471,"target":445},{"edgeType":"calls","source":5414,"target":480},{"edgeType":"contains","source":5463,"target":5576},{"edgeType":"calls","source":995,"target":56},{"edgeType":"calls","source":6753,"target":3340},{"edgeType":"calls","source":4606,"target":159},{"edgeType":"calls","source":6591,"target":963},{"edgeType":"extends","source":4002,"target":36},{"edgeType":"calls","source":6140,"target":171},{"edgeType":"calls","source":3980,"target":3710},{"edgeType":"calls","source":5524,"target":5525},{"edgeType":"contains","source":2359,"target":2438},{"edgeType":"contains","source":3808,"target":4029},{"edgeType":"calls","source":746,"target":371},{"edgeType":"contains","source":2956,"target":2958},{"edgeType":"calls","source":5414,"target":479},{"edgeType":"calls","source":3244,"target":3269},{"edgeType":"calls","source":6753,"target":170},{"edgeType":"imports","source":1814,"target":1036},{"edgeType":"calls","source":372,"target":338},{"edgeType":"calls","source":4269,"target":4263},{"edgeType":"calls","source":6140,"target":170},{"edgeType":"contains","source":4391,"target":4982},{"edgeType":"contains","source":162,"target":3950},{"edgeType":"calls","source":6881,"target":431},{"edgeType":"calls","source":746,"target":370},{"edgeType":"calls","source":5656,"target":5660},{"edgeType":"calls","source":6753,"target":171},{"edgeType":"calls","source":5564,"target":56},{"edgeType":"calls","source":6827,"target":1048},{"edgeType":"calls","source":5414,"target":478},{"edgeType":"contains","source":1297,"target":1536},{"edgeType":"extends","source":6082,"target":36},{"edgeType":"calls","source":1085,"target":431},{"edgeType":"contains","source":5463,"target":5570},{"edgeType":"contains","source":6160,"target":6161},{"edgeType":"contains","source":3947,"target":3948},{"edgeType":"contains","source":139,"target":435},{"edgeType":"contains","source":4671,"target":4758},{"edgeType":"calls","source":372,"target":337},{"edgeType":"contains","source":2359,"target":2439},{"edgeType":"calls","source":6475,"target":354},{"edgeType":"contains","source":3808,"target":4027},{"edgeType":"contains","source":2359,"target":2436},{"edgeType":"calls","source":2802,"target":1113},{"edgeType":"calls","source":5656,"target":5659},{"edgeType":"calls","source":5445,"target":573},{"edgeType":"calls","source":1169,"target":1002},{"edgeType":"calls","source":5414,"target":477},{"edgeType":"contains","source":599,"target":976},{"edgeType":"calls","source":4600,"target":4570},{"edgeType":"calls","source":535,"target":572},{"edgeType":"contains","source":2922,"target":2952},{"edgeType":"contains","source":4671,"target":4757},{"edgeType":"contains","source":2359,"target":2437},{"edgeType":"calls","source":5902,"target":146},{"edgeType":"calls","source":1097,"target":1119},{"edgeType":"calls","source":5445,"target":572},{"edgeType":"calls","source":5414,"target":476},{"edgeType":"calls","source":6506,"target":431},{"edgeType":"calls","source":372,"target":339},{"edgeType":"calls","source":7050,"target":6822},{"edgeType":"contains","source":3352,"target":3364},{"edgeType":"calls","source":6955,"target":6596},{"edgeType":"calls","source":6845,"target":6835},{"edgeType":"calls","source":4877,"target":210},{"edgeType":"extends","source":1854,"target":36},{"edgeType":"contains","source":4706,"target":4728},{"edgeType":"calls","source":3753,"target":170},{"edgeType":"extends","source":7003,"target":36},{"edgeType":"contains","source":4806,"target":4807},{"edgeType":"contains","source":6887,"target":6890},{"edgeType":"contains","source":4839,"target":4841},{"edgeType":"calls","source":1804,"target":337},{"edgeType":"calls","source":6573,"target":469},{"edgeType":"contains","source":3351,"target":3402},{"edgeType":"calls","source":3447,"target":2257},{"edgeType":"calls","source":4433,"target":4460},{"edgeType":"calls","source":4877,"target":209},{"edgeType":"contains","source":3,"target":428},{"edgeType":"contains","source":2359,"target":2442},{"edgeType":"calls","source":3753,"target":171},{"edgeType":"calls","source":2802,"target":1112},{"edgeType":"contains","source":3781,"target":3812},{"edgeType":"contains","source":6476,"target":6947},{"edgeType":"calls","source":1770,"target":333},{"edgeType":"contains","source":1297,"target":1540},{"edgeType":"calls","source":3447,"target":2258},{"edgeType":"calls","source":4599,"target":4598},{"edgeType":"calls","source":4810,"target":171},{"edgeType":"calls","source":4770,"target":354},{"edgeType":"imports","source":6824,"target":49},{"edgeType":"calls","source":746,"target":366},{"edgeType":"calls","source":4881,"target":84},{"edgeType":"contains","source":2359,"target":2443},{"edgeType":"calls","source":6775,"target":551},{"edgeType":"calls","source":746,"target":369},{"edgeType":"calls","source":5077,"target":3520},{"edgeType":"calls","source":965,"target":979},{"edgeType":"contains","source":1297,"target":1537},{"edgeType":"contains","source":3351,"target":3400},{"edgeType":"contains","source":6887,"target":6892},{"edgeType":"contains","source":6651,"target":6808},{"edgeType":"calls","source":6992,"target":6509},{"edgeType":"calls","source":4810,"target":170},{"edgeType":"calls","source":1804,"target":339},{"edgeType":"calls","source":4128,"target":170},{"edgeType":"calls","source":6374,"target":309},{"edgeType":"contains","source":2359,"target":2440},{"edgeType":"contains","source":5596,"target":5689},{"edgeType":"calls","source":746,"target":368},{"edgeType":"contains","source":3781,"target":3810},{"edgeType":"calls","source":6853,"target":248},{"edgeType":"calls","source":6649,"target":6572},{"edgeType":"extends","source":4957,"target":36},{"edgeType":"calls","source":965,"target":978},{"edgeType":"extends","source":2502,"target":36},{"edgeType":"imports","source":2494,"target":49},{"edgeType":"calls","source":3822,"target":144},{"edgeType":"contains","source":3351,"target":3399},{"edgeType":"calls","source":1197,"target":1185},{"edgeType":"calls","source":1804,"target":338},{"edgeType":"calls","source":4128,"target":171},{"edgeType":"contains","source":2359,"target":2441},{"edgeType":"contains","source":5726,"target":5880},{"edgeType":"calls","source":4321,"target":528},{"edgeType":"contains","source":1302,"target":5616},{"edgeType":"contains","source":4375,"target":4430},{"edgeType":"contains","source":4806,"target":4811},{"edgeType":"contains","source":5463,"target":5577},{"edgeType":"calls","source":3640,"target":3669},{"edgeType":"calls","source":6242,"target":171},{"edgeType":"contains","source":2359,"target":2446},{"edgeType":"calls","source":2859,"target":2511},{"edgeType":"calls","source":6955,"target":6601},{"edgeType":"calls","source":4490,"target":573},{"edgeType":"calls","source":4321,"target":527},{"edgeType":"calls","source":6496,"target":1804},{"edgeType":"calls","source":5867,"target":5453},{"edgeType":"contains","source":5463,"target":5578},{"edgeType":"calls","source":1812,"target":84},{"edgeType":"calls","source":3311,"target":3298},{"edgeType":"imports","source":6074,"target":49},{"edgeType":"calls","source":6242,"target":170},{"edgeType":"contains","source":2359,"target":2447},{"edgeType":"calls","source":449,"target":56},{"edgeType":"calls","source":4490,"target":572},{"edgeType":"contains","source":6604,"target":2976},{"edgeType":"contains","source":4375,"target":4428},{"edgeType":"calls","source":5247,"target":4588},{"edgeType":"extends","source":2468,"target":36},{"edgeType":"contains","source":578,"target":579},{"edgeType":"calls","source":1770,"target":332},{"edgeType":"contains","source":4806,"target":4809},{"edgeType":"calls","source":3640,"target":3667},{"edgeType":"calls","source":1692,"target":1693},{"edgeType":"calls","source":536,"target":533},{"edgeType":"calls","source":6845,"target":6842},{"edgeType":"calls","source":7063,"target":84},{"edgeType":"calls","source":4010,"target":3824},{"edgeType":"calls","source":4660,"target":588},{"edgeType":"contains","source":2359,"target":2444},{"edgeType":"calls","source":4673,"target":4413},{"edgeType":"calls","source":5094,"target":5102},{"edgeType":"contains","source":2206,"target":2960},{"edgeType":"contains","source":4375,"target":4427},{"edgeType":"contains","source":5730,"target":5759},{"edgeType":"contains","source":996,"target":1361},{"edgeType":"calls","source":6374,"target":304},{"edgeType":"calls","source":2117,"target":144},{"edgeType":"calls","source":4218,"target":548},{"edgeType":"calls","source":746,"target":364},{"edgeType":"contains","source":2359,"target":2445},{"edgeType":"calls","source":1096,"target":84},{"edgeType":"calls","source":3780,"target":3520},{"edgeType":"contains","source":5463,"target":5556},{"edgeType":"calls","source":4530,"target":4582},{"edgeType":"contains","source":1297,"target":1514},{"edgeType":"calls","source":6206,"target":1250},{"edgeType":"contains","source":4706,"target":4711},{"edgeType":"calls","source":4841,"target":2341},{"edgeType":"contains","source":2359,"target":2417},{"edgeType":"calls","source":569,"target":528},{"edgeType":"contains","source":3241,"target":3615},{"edgeType":"imports","source":2176,"target":2552},{"edgeType":"calls","source":6688,"target":4279},{"edgeType":"contains","source":1732,"target":1771},{"edgeType":"contains","source":775,"target":782},{"edgeType":"contains","source":5463,"target":5557},{"edgeType":"calls","source":1672,"target":1216},{"edgeType":"calls","source":1955,"target":1956},{"edgeType":"calls","source":6206,"target":1249},{"edgeType":"contains","source":2686,"target":2852},{"edgeType":"contains","source":1732,"target":1772},{"edgeType":"calls","source":2784,"target":572},{"edgeType":"contains","source":3166,"target":1713},{"edgeType":"calls","source":6410,"target":210},{"edgeType":"contains","source":2359,"target":2418},{"edgeType":"calls","source":569,"target":527},{"edgeType":"calls","source":6807,"target":591},{"edgeType":"calls","source":6688,"target":4280},{"edgeType":"calls","source":3214,"target":3097},{"edgeType":"contains","source":3781,"target":3788},{"edgeType":"contains","source":4706,"target":4709},{"edgeType":"extends","source":2060,"target":36},{"edgeType":"contains","source":6589,"target":6592},{"edgeType":"contains","source":4640,"target":4641},{"edgeType":"calls","source":6410,"target":209},{"edgeType":"calls","source":6378,"target":144},{"edgeType":"extends","source":2124,"target":167},{"edgeType":"contains","source":5895,"target":5908},{"edgeType":"calls","source":5625,"target":1289},{"edgeType":"contains","source":2359,"target":2415},{"edgeType":"calls","source":6688,"target":4281},{"edgeType":"calls","source":472,"target":366},{"edgeType":"calls","source":6678,"target":4591},{"edgeType":"contains","source":2030,"target":2044},{"edgeType":"contains","source":1732,"target":1769},{"edgeType":"imports","source":2581,"target":565},{"edgeType":"calls","source":5141,"target":4666},{"edgeType":"contains","source":3781,"target":3787},{"edgeType":"calls","source":6685,"target":146},{"edgeType":"calls","source":472,"target":364},{"edgeType":"extends","source":3141,"target":1409},{"edgeType":"calls","source":4016,"target":431},{"edgeType":"calls","source":5625,"target":1288},{"edgeType":"contains","source":4391,"target":4959},{"edgeType":"contains","source":2359,"target":2416},{"edgeType":"calls","source":3142,"target":3213},{"edgeType":"extends","source":2742,"target":36},{"edgeType":"contains","source":3813,"target":3851},{"edgeType":"calls","source":6751,"target":215},{"edgeType":"calls","source":6811,"target":469},{"edgeType":"calls","source":434,"target":480},{"edgeType":"calls","source":4511,"target":3053},{"edgeType":"calls","source":5757,"target":5652},{"edgeType":"calls","source":2071,"target":471},{"edgeType":"calls","source":534,"target":551},{"edgeType":"calls","source":2246,"target":332},{"edgeType":"contains","source":6851,"target":6920},{"edgeType":"calls","source":4207,"target":4021},{"edgeType":"contains","source":2359,"target":2421},{"edgeType":"contains","source":1732,"target":1775},{"edgeType":"calls","source":5661,"target":171},{"edgeType":"calls","source":5625,"target":1287},{"edgeType":"extends","source":180,"target":185},{"edgeType":"calls","source":6680,"target":303},{"edgeType":"calls","source":5123,"target":5222},{"edgeType":"contains","source":1302,"target":5592},{"edgeType":"contains","source":2686,"target":2856},{"edgeType":"calls","source":4511,"target":3052},{"edgeType":"contains","source":6851,"target":6921},{"edgeType":"calls","source":4420,"target":588},{"edgeType":"contains","source":6651,"target":6779},{"edgeType":"contains","source":2359,"target":2423},{"edgeType":"contains","source":4432,"target":4752},{"edgeType":"calls","source":434,"target":479},{"edgeType":"calls","source":2246,"target":333},{"edgeType":"contains","source":2359,"target":2422},{"edgeType":"contains","source":6651,"target":6778},{"edgeType":"contains","source":3781,"target":3792},{"edgeType":"contains","source":1732,"target":1776},{"edgeType":"imports","source":130,"target":438},{"edgeType":"calls","source":5661,"target":170},{"edgeType":"calls","source":5625,"target":1286},{"edgeType":"calls","source":5123,"target":5221},{"edgeType":"calls","source":3214,"target":3093},{"edgeType":"calls","source":6680,"target":304},{"edgeType":"contains","source":2030,"target":2048},{"edgeType":"contains","source":5596,"target":5659},{"edgeType":"contains","source":3975,"target":4119},{"edgeType":"calls","source":4511,"target":3051},{"edgeType":"contains","source":6851,"target":6922},{"edgeType":"contains","source":1732,"target":1773},{"edgeType":"calls","source":5077,"target":304},{"edgeType":"contains","source":2359,"target":2419},{"edgeType":"calls","source":5757,"target":5649},{"edgeType":"calls","source":6747,"target":342},{"edgeType":"extends","source":4788,"target":36},{"edgeType":"calls","source":5123,"target":5220},{"edgeType":"calls","source":5625,"target":1285},{"edgeType":"calls","source":6777,"target":469},{"edgeType":"calls","source":1152,"target":422},{"edgeType":"imports","source":1028,"target":79},{"edgeType":"contains","source":2030,"target":2049},{"edgeType":"calls","source":4739,"target":210},{"edgeType":"calls","source":434,"target":481},{"edgeType":"calls","source":6115,"target":893},{"edgeType":"calls","source":1152,"target":421},{"edgeType":"contains","source":1297,"target":1517},{"edgeType":"contains","source":6851,"target":6923},{"edgeType":"calls","source":6914,"target":6793},{"edgeType":"calls","source":4808,"target":4413},{"edgeType":"contains","source":4541,"target":4542},{"edgeType":"contains","source":4706,"target":4712},{"edgeType":"contains","source":6651,"target":6781},{"edgeType":"calls","source":5077,"target":303},{"edgeType":"contains","source":3781,"target":3790},{"edgeType":"imports","source":5458,"target":179},{"edgeType":"contains","source":1732,"target":1774},{"edgeType":"contains","source":3813,"target":3855},{"edgeType":"contains","source":3808,"target":4010},{"edgeType":"contains","source":5908,"target":6559},{"edgeType":"contains","source":2359,"target":2420},{"edgeType":"contains","source":3241,"target":3618},{"edgeType":"calls","source":5625,"target":1284},{"edgeType":"calls","source":5721,"target":422},{"edgeType":"imports","source":6111,"target":4247},{"edgeType":"calls","source":6419,"target":5226},{"edgeType":"extends","source":901,"target":36},{"edgeType":"imports","source":4668,"target":1399},{"edgeType":"calls","source":4739,"target":209},{"edgeType":"calls","source":7011,"target":5901},{"edgeType":"extends","source":2981,"target":36},{"edgeType":"calls","source":1325,"target":338},{"edgeType":"calls","source":6241,"target":157},{"edgeType":"contains","source":2030,"target":2054},{"edgeType":"calls","source":434,"target":476},{"edgeType":"imports","source":6245,"target":79},{"edgeType":"calls","source":4707,"target":144},{"edgeType":"contains","source":2359,"target":2426},{"edgeType":"calls","source":4453,"target":2733},{"edgeType":"calls","source":912,"target":457},{"edgeType":"contains","source":182,"target":147},{"edgeType":"calls","source":5861,"target":309},{"edgeType":"contains","source":5726,"target":5868},{"edgeType":"extends","source":2640,"target":36},{"edgeType":"calls","source":5721,"target":421},{"edgeType":"contains","source":6651,"target":6791},{"edgeType":"calls","source":4700,"target":4588},{"edgeType":"calls","source":1325,"target":337},{"edgeType":"calls","source":6371,"target":354},{"edgeType":"calls","source":5013,"target":170},{"edgeType":"contains","source":2359,"target":2427},{"edgeType":"calls","source":6480,"target":146},{"edgeType":"calls","source":6409,"target":2347},{"edgeType":"imports","source":6245,"target":78},{"edgeType":"calls","source":6743,"target":469},{"edgeType":"calls","source":5013,"target":171},{"edgeType":"calls","source":5084,"target":84},{"edgeType":"calls","source":6995,"target":56},{"edgeType":"contains","source":5463,"target":5566},{"edgeType":"contains","source":3509,"target":3772},{"edgeType":"contains","source":3352,"target":3354},{"edgeType":"calls","source":6583,"target":144},{"edgeType":"contains","source":1238,"target":1239},{"edgeType":"calls","source":4088,"target":304},{"edgeType":"contains","source":5410,"target":6148},{"edgeType":"calls","source":6880,"target":6793},{"edgeType":"calls","source":6409,"target":2346},{"edgeType":"calls","source":4842,"target":4413},{"edgeType":"calls","source":434,"target":478},{"edgeType":"calls","source":536,"target":487},{"edgeType":"contains","source":2359,"target":2424},{"edgeType":"calls","source":6682,"target":4475},{"edgeType":"calls","source":917,"target":304},{"edgeType":"calls","source":5092,"target":5120},{"edgeType":"contains","source":1732,"target":1777},{"edgeType":"imports","source":3460,"target":1853},{"edgeType":"contains","source":3781,"target":3795},{"edgeType":"contains","source":6817,"target":6931},{"edgeType":"contains","source":3352,"target":3353},{"edgeType":"calls","source":3330,"target":548},{"edgeType":"calls","source":6954,"target":3443},{"edgeType":"contains","source":4502,"target":4698},{"edgeType":"calls","source":6409,"target":2345},{"edgeType":"calls","source":4595,"target":4670},{"edgeType":"contains","source":2359,"target":2425},{"edgeType":"calls","source":434,"target":477},{"edgeType":"calls","source":534,"target":548},{"edgeType":"contains","source":5596,"target":5673},{"edgeType":"calls","source":6580,"target":6581},{"edgeType":"calls","source":912,"target":458},{"edgeType":"calls","source":917,"target":303},{"edgeType":"contains","source":1732,"target":1778},{"edgeType":"contains","source":5463,"target":5568},{"edgeType":"contains","source":5458,"target":5723},{"edgeType":"calls","source":5092,"target":5119},{"edgeType":"contains","source":6817,"target":6932},{"edgeType":"calls","source":1325,"target":339},{"edgeType":"calls","source":1294,"target":1295},{"edgeType":"calls","source":7135,"target":1004},{"edgeType":"contains","source":1860,"target":2043},{"edgeType":"calls","source":6878,"target":1572},{"edgeType":"calls","source":6409,"target":2344},{"edgeType":"contains","source":2359,"target":2430},{"edgeType":"contains","source":6651,"target":6786},{"edgeType":"calls","source":3023,"target":548},{"edgeType":"calls","source":887,"target":170},{"edgeType":"contains","source":2030,"target":2058},{"edgeType":"calls","source":6753,"target":3333},{"edgeType":"calls","source":6682,"target":4477},{"edgeType":"calls","source":4301,"target":1099},{"edgeType":"contains","source":1037,"target":1129},{"edgeType":"calls","source":6846,"target":6793},{"edgeType":"calls","source":4088,"target":303},{"edgeType":"contains","source":2359,"target":2431},{"edgeType":"calls","source":6409,"target":2343},{"edgeType":"calls","source":2661,"target":144},{"edgeType":"contains","source":6604,"target":2959},{"edgeType":"calls","source":6753,"target":3334},{"edgeType":"extends","source":6834,"target":36},{"edgeType":"calls","source":5861,"target":304},{"edgeType":"calls","source":5656,"target":5602},{"edgeType":"calls","source":5891,"target":431},{"edgeType":"contains","source":5268,"target":5269},{"edgeType":"calls","source":3413,"target":84},{"edgeType":"contains","source":4706,"target":4721},{"edgeType":"calls","source":1263,"target":144},{"edgeType":"calls","source":6409,"target":2342},{"edgeType":"calls","source":6753,"target":3335},{"edgeType":"contains","source":3781,"target":3799},{"edgeType":"contains","source":2359,"target":2428},{"edgeType":"contains","source":1379,"target":1097},{"edgeType":"contains","source":5463,"target":5563},{"edgeType":"calls","source":5861,"target":303},{"edgeType":"calls","source":1739,"target":1243},{"edgeType":"contains","source":5301,"target":5302},{"edgeType":"calls","source":5478,"target":548},{"edgeType":"calls","source":6409,"target":2341},{"edgeType":"contains","source":3781,"target":3798},{"edgeType":"contains","source":2359,"target":2429},{"edgeType":"calls","source":6753,"target":3336},{"edgeType":"calls","source":887,"target":171},{"edgeType":"calls","source":6685,"target":159},{"edgeType":"extends","source":5402,"target":36},{"edgeType":"imports","source":4668,"target":3520},{"edgeType":"contains","source":1379,"target":1098},{"edgeType":"contains","source":1297,"target":1526},{"edgeType":"contains","source":3351,"target":3387},{"edgeType":"contains","source":1037,"target":1130},{"edgeType":"calls","source":4264,"target":160},{"edgeType":"calls","source":4136,"target":4128},{"edgeType":"calls","source":2779,"target":1799},{"edgeType":"contains","source":4391,"target":4946},{"edgeType":"contains","source":2359,"target":2401},{"edgeType":"calls","source":3442,"target":3444},{"edgeType":"contains","source":5410,"target":6125},{"edgeType":"calls","source":4758,"target":2816},{"edgeType":"contains","source":1860,"target":2014},{"edgeType":"calls","source":6959,"target":1146},{"edgeType":"calls","source":1768,"target":371},{"edgeType":"calls","source":1697,"target":458},{"edgeType":"calls","source":469,"target":473},{"edgeType":"calls","source":6550,"target":84},{"edgeType":"imports","source":3013,"target":3014},{"edgeType":"calls","source":3710,"target":421},{"edgeType":"calls","source":2730,"target":148},{"edgeType":"calls","source":4264,"target":161},{"edgeType":"contains","source":4507,"target":4520},{"edgeType":"contains","source":4391,"target":4945},{"edgeType":"contains","source":2359,"target":2402},{"edgeType":"contains","source":5410,"target":6124},{"edgeType":"calls","source":4758,"target":2815},{"edgeType":"calls","source":1163,"target":1156},{"edgeType":"calls","source":6959,"target":1147},{"edgeType":"contains","source":5596,"target":5646},{"edgeType":"contains","source":4988,"target":1236},{"edgeType":"calls","source":1768,"target":370},{"edgeType":"calls","source":6513,"target":6517},{"edgeType":"contains","source":2030,"target":2031},{"edgeType":"contains","source":3,"target":3557},{"edgeType":"calls","source":1697,"target":457},{"edgeType":"calls","source":6414,"target":6415},{"edgeType":"calls","source":6546,"target":209},{"edgeType":"calls","source":4433,"target":4434},{"edgeType":"calls","source":3710,"target":422},{"edgeType":"calls","source":6094,"target":509},{"edgeType":"calls","source":3979,"target":3710},{"edgeType":"calls","source":6237,"target":304},{"edgeType":"contains","source":928,"target":1307},{"edgeType":"contains","source":2359,"target":2399},{"edgeType":"contains","source":5267,"target":5271},{"edgeType":"calls","source":469,"target":475},{"edgeType":"contains","source":5410,"target":6123},{"edgeType":"calls","source":4758,"target":2814},{"edgeType":"contains","source":1732,"target":1752},{"edgeType":"calls","source":6892,"target":1111},{"edgeType":"calls","source":4911,"target":4413},{"edgeType":"calls","source":6879,"target":457},{"edgeType":"contains","source":1860,"target":2012},{"edgeType":"calls","source":6959,"target":1148},{"edgeType":"contains","source":6851,"target":6909},{"edgeType":"calls","source":298,"target":491},{"edgeType":"calls","source":6711,"target":380},{"edgeType":"contains","source":6060,"target":6062},{"edgeType":"calls","source":6546,"target":210},{"edgeType":"calls","source":5904,"target":1113},{"edgeType":"contains","source":2686,"target":2832},{"edgeType":"calls","source":6296,"target":588},{"edgeType":"calls","source":6094,"target":508},{"edgeType":"calls","source":6237,"target":303},{"edgeType":"calls","source":4264,"target":159},{"edgeType":"contains","source":5267,"target":5270},{"edgeType":"calls","source":2789,"target":431},{"edgeType":"contains","source":3166,"target":1695},{"edgeType":"calls","source":1325,"target":364},{"edgeType":"calls","source":5785,"target":573},{"edgeType":"contains","source":2359,"target":2400},{"edgeType":"calls","source":2604,"target":1938},{"edgeType":"contains","source":5410,"target":6122},{"edgeType":"calls","source":6711,"target":381},{"edgeType":"calls","source":6546,"target":6553},{"edgeType":"contains","source":3808,"target":3989},{"edgeType":"calls","source":6879,"target":458},{"edgeType":"calls","source":6094,"target":507},{"edgeType":"contains","source":6060,"target":6063},{"edgeType":"calls","source":469,"target":474},{"edgeType":"calls","source":5904,"target":1112},{"edgeType":"contains","source":4391,"target":4950},{"edgeType":"contains","source":2359,"target":2405},{"edgeType":"contains","source":2955,"target":2956},{"edgeType":"contains","source":3166,"target":1700},{"edgeType":"calls","source":3618,"target":3269},{"edgeType":"contains","source":940,"target":941},{"edgeType":"calls","source":5785,"target":572},{"edgeType":"calls","source":6711,"target":382},{"edgeType":"calls","source":1165,"target":1090},{"edgeType":"calls","source":6094,"target":506},{"edgeType":"contains","source":4988,"target":1241},{"edgeType":"contains","source":4012,"target":4015},{"edgeType":"contains","source":6450,"target":6650},{"edgeType":"contains","source":4507,"target":4525},{"edgeType":"contains","source":6851,"target":6903},{"edgeType":"calls","source":5652,"target":2580},{"edgeType":"contains","source":4391,"target":4949},{"edgeType":"contains","source":2359,"target":2406},{"edgeType":"contains","source":1732,"target":1759},{"edgeType":"contains","source":3166,"target":1701},{"edgeType":"extends","source":4135,"target":180},{"edgeType":"contains","source":2922,"target":2923},{"edgeType":"calls","source":2989,"target":571},{"edgeType":"calls","source":6546,"target":6555},{"edgeType":"calls","source":6094,"target":505},{"edgeType":"contains","source":42,"target":1295},{"edgeType":"calls","source":4720,"target":1875},{"edgeType":"calls","source":1768,"target":366},{"edgeType":"contains","source":3,"target":3561},{"edgeType":"contains","source":3,"target":4618},{"edgeType":"calls","source":568,"target":570},{"edgeType":"contains","source":885,"target":1587},{"edgeType":"calls","source":4387,"target":571},{"edgeType":"contains","source":4391,"target":4948},{"edgeType":"contains","source":2359,"target":2403},{"edgeType":"imports","source":5380,"target":2580},{"edgeType":"contains","source":3166,"target":1698},{"edgeType":"extends","source":775,"target":752},{"edgeType":"contains","source":5410,"target":6127},{"edgeType":"calls","source":6711,"target":384},{"edgeType":"contains","source":2030,"target":2032},{"edgeType":"calls","source":6094,"target":504},{"edgeType":"contains","source":5596,"target":5643},{"edgeType":"calls","source":1768,"target":369},{"edgeType":"calls","source":4591,"target":588},{"edgeType":"contains","source":6851,"target":6905},{"edgeType":"calls","source":4269,"target":4226},{"edgeType":"calls","source":6679,"target":6662},{"edgeType":"calls","source":6880,"target":431},{"edgeType":"contains","source":2359,"target":2404},{"edgeType":"imports","source":1415,"target":750},{"edgeType":"calls","source":4937,"target":431},{"edgeType":"extends","source":2055,"target":180},{"edgeType":"calls","source":5062,"target":5012},{"edgeType":"contains","source":3509,"target":3749},{"edgeType":"contains","source":2030,"target":2033},{"edgeType":"calls","source":3295,"target":596},{"edgeType":"calls","source":6207,"target":171},{"edgeType":"calls","source":1697,"target":455},{"edgeType":"calls","source":6094,"target":503},{"edgeType":"calls","source":1768,"target":368},{"edgeType":"imports","source":5166,"target":2872},{"edgeType":"contains","source":41,"target":4502},{"edgeType":"extends","source":5366,"target":5363},{"edgeType":"calls","source":2268,"target":1776},{"edgeType":"calls","source":2175,"target":431},{"edgeType":"contains","source":3166,"target":1704},{"edgeType":"contains","source":6851,"target":6916},{"edgeType":"calls","source":1697,"target":450},{"edgeType":"contains","source":3351,"target":3369},{"edgeType":"calls","source":1591,"target":565},{"edgeType":"calls","source":6207,"target":170},{"edgeType":"calls","source":3142,"target":3222},{"edgeType":"calls","source":6094,"target":502},{"edgeType":"contains","source":3847,"target":3849},{"edgeType":"contains","source":2030,"target":2038},{"edgeType":"contains","source":2359,"target":2409},{"edgeType":"imports","source":6074,"target":79},{"edgeType":"contains","source":1732,"target":1763},{"edgeType":"contains","source":3813,"target":3844},{"edgeType":"contains","source":6851,"target":6917},{"edgeType":"calls","source":6023,"target":588},{"edgeType":"calls","source":1362,"target":1321},{"edgeType":"contains","source":1297,"target":1507},{"edgeType":"calls","source":4591,"target":4813},{"edgeType":"contains","source":1860,"target":2024},{"edgeType":"calls","source":5390,"target":1184},{"edgeType":"calls","source":3142,"target":3223},{"edgeType":"calls","source":1152,"target":431},{"edgeType":"contains","source":1732,"target":1764},{"edgeType":"imports","source":1028,"target":78},{"edgeType":"contains","source":2030,"target":2039},{"edgeType":"calls","source":4136,"target":4120},{"edgeType":"calls","source":2682,"target":571},{"edgeType":"imports","source":6074,"target":78},{"edgeType":"calls","source":472,"target":371},{"edgeType":"contains","source":4391,"target":4953},{"edgeType":"contains","source":2359,"target":2410},{"edgeType":"contains","source":885,"target":1595},{"edgeType":"imports","source":6373,"target":325},{"edgeType":"contains","source":6851,"target":6918},{"edgeType":"contains","source":3166,"target":1702},{"edgeType":"calls","source":6572,"target":469},{"edgeType":"contains","source":2030,"target":2036},{"edgeType":"calls","source":4841,"target":2347},{"edgeType":"calls","source":4591,"target":4812},{"edgeType":"contains","source":2359,"target":2407},{"edgeType":"contains","source":5596,"target":5656},{"edgeType":"contains","source":1732,"target":1761},{"edgeType":"contains","source":775,"target":776},{"edgeType":"calls","source":5194,"target":5144},{"edgeType":"calls","source":1342,"target":886},{"edgeType":"calls","source":1768,"target":364},{"edgeType":"contains","source":6851,"target":6919},{"edgeType":"contains","source":5410,"target":6130},{"edgeType":"contains","source":2030,"target":2037},{"edgeType":"calls","source":4048,"target":2618},{"edgeType":"calls","source":6297,"target":548},{"edgeType":"contains","source":5730,"target":5731},{"edgeType":"calls","source":5000,"target":588},{"edgeType":"calls","source":4880,"target":3251},{"edgeType":"calls","source":4841,"target":2346},{"edgeType":"calls","source":4878,"target":142},{"edgeType":"contains","source":4391,"target":4951},{"edgeType":"contains","source":2359,"target":2408},{"edgeType":"calls","source":6782,"target":303},{"edgeType":"contains","source":3543,"target":3763},{"edgeType":"contains","source":775,"target":779},{"edgeType":"calls","source":5316,"target":304},{"edgeType":"contains","source":5596,"target":5649},{"edgeType":"calls","source":5246,"target":4588},{"edgeType":"contains","source":4706,"target":4707},{"edgeType":"contains","source":3166,"target":1708},{"edgeType":"calls","source":3923,"target":148},{"edgeType":"contains","source":4671,"target":1563},{"edgeType":"contains","source":6851,"target":6911},{"edgeType":"calls","source":2886,"target":584},{"edgeType":"contains","source":2359,"target":2413},{"edgeType":"calls","source":472,"target":368},{"edgeType":"contains","source":1732,"target":1767},{"edgeType":"contains","source":1988,"target":5458},{"edgeType":"calls","source":4841,"target":2345},{"edgeType":"contains","source":3781,"target":3785},{"edgeType":"contains","source":3813,"target":3850},{"edgeType":"calls","source":2781,"target":2782},{"edgeType":"contains","source":2030,"target":2042},{"edgeType":"calls","source":5316,"target":303},{"edgeType":"contains","source":775,"target":778},{"edgeType":"calls","source":6782,"target":304},{"edgeType":"calls","source":1823,"target":1824},{"edgeType":"contains","source":3351,"target":3372},{"edgeType":"contains","source":2359,"target":2414},{"edgeType":"contains","source":1732,"target":1768},{"edgeType":"calls","source":6810,"target":6836},{"edgeType":"calls","source":4761,"target":596},{"edgeType":"calls","source":4841,"target":2344},{"edgeType":"contains","source":775,"target":781},{"edgeType":"contains","source":1302,"target":6638},{"edgeType":"calls","source":6688,"target":4276},{"edgeType":"calls","source":2559,"target":148},{"edgeType":"contains","source":1037,"target":1115},{"edgeType":"imports","source":2494,"target":79},{"edgeType":"contains","source":1297,"target":1508},{"edgeType":"calls","source":2784,"target":573},{"edgeType":"contains","source":951,"target":5895},{"edgeType":"contains","source":5473,"target":1011},{"edgeType":"calls","source":2105,"target":484},{"edgeType":"calls","source":3447,"target":3274},{"edgeType":"contains","source":2030,"target":2040},{"edgeType":"calls","source":1125,"target":210},{"edgeType":"calls","source":1035,"target":886},{"edgeType":"contains","source":2359,"target":2411},{"edgeType":"calls","source":2615,"target":1584},{"edgeType":"contains","source":3813,"target":3848},{"edgeType":"contains","source":15,"target":29},{"edgeType":"calls","source":472,"target":370},{"edgeType":"calls","source":3025,"target":501},{"edgeType":"calls","source":4841,"target":2343},{"edgeType":"calls","source":4933,"target":548},{"edgeType":"calls","source":6569,"target":4795},{"edgeType":"contains","source":775,"target":780},{"edgeType":"calls","source":6688,"target":4277},{"edgeType":"contains","source":5596,"target":5652},{"edgeType":"contains","source":996,"target":1328},{"edgeType":"imports","source":2494,"target":78},{"edgeType":"calls","source":4841,"target":2342},{"edgeType":"contains","source":5410,"target":6134},{"edgeType":"calls","source":1163,"target":1145},{"edgeType":"contains","source":3781,"target":3782},{"edgeType":"calls","source":1125,"target":209},{"edgeType":"calls","source":472,"target":369},{"edgeType":"calls","source":6688,"target":4278},{"edgeType":"contains","source":2359,"target":2412},{"edgeType":"extends","source":1037,"target":36},{"edgeType":"contains","source":15,"target":28},{"edgeType":"contains","source":47,"target":63},{"edgeType":"contains","source":3509,"target":3731},{"edgeType":"extends","source":437,"target":439},{"edgeType":"contains","source":2591,"target":2592},{"edgeType":"contains","source":1031,"target":1270},{"edgeType":"contains","source":3152,"target":3170},{"edgeType":"calls","source":6242,"target":2347},{"edgeType":"calls","source":4164,"target":171},{"edgeType":"contains","source":4391,"target":4929},{"edgeType":"contains","source":5167,"target":5185},{"edgeType":"contains","source":2359,"target":2384},{"edgeType":"calls","source":6780,"target":469},{"edgeType":"contains","source":2050,"target":336},{"edgeType":"calls","source":1223,"target":436},{"edgeType":"calls","source":7032,"target":1113},{"edgeType":"calls","source":4841,"target":4554},{"edgeType":"contains","source":5452,"target":5865},{"edgeType":"calls","source":3008,"target":1126},{"edgeType":"contains","source":5458,"target":5679},{"edgeType":"extends","source":3270,"target":1409},{"edgeType":"contains","source":2756,"target":2763},{"edgeType":"calls","source":6242,"target":2346},{"edgeType":"contains","source":3152,"target":3171},{"edgeType":"calls","source":2090,"target":1041},{"edgeType":"contains","source":2359,"target":2385},{"edgeType":"contains","source":4432,"target":4714},{"edgeType":"contains","source":5167,"target":5184},{"edgeType":"imports","source":5166,"target":537},{"edgeType":"calls","source":4841,"target":4553},{"edgeType":"calls","source":6649,"target":303},{"edgeType":"contains","source":47,"target":62},{"edgeType":"calls","source":5092,"target":4170},{"edgeType":"calls","source":6551,"target":170},{"edgeType":"contains","source":47,"target":65},{"edgeType":"contains","source":1228,"target":5732},{"edgeType":"calls","source":5714,"target":1801},{"edgeType":"contains","source":2756,"target":2760},{"edgeType":"contains","source":6604,"target":2922},{"edgeType":"calls","source":6242,"target":2345},{"edgeType":"calls","source":2704,"target":2091},{"edgeType":"contains","source":5167,"target":5183},{"edgeType":"calls","source":6473,"target":469},{"edgeType":"contains","source":4391,"target":4927},{"edgeType":"contains","source":2359,"target":2382},{"edgeType":"calls","source":6649,"target":304},{"edgeType":"contains","source":3976,"target":4051},{"edgeType":"calls","source":4841,"target":4552},{"edgeType":"contains","source":5452,"target":5867},{"edgeType":"contains","source":47,"target":64},{"edgeType":"imports","source":5285,"target":2136},{"edgeType":"contains","source":1302,"target":6610},{"edgeType":"calls","source":6551,"target":171},{"edgeType":"extends","source":1848,"target":36},{"edgeType":"contains","source":1498,"target":1591},{"edgeType":"calls","source":3907,"target":3909},{"edgeType":"contains","source":2686,"target":2817},{"edgeType":"contains","source":5167,"target":5182},{"edgeType":"contains","source":4988,"target":1218},{"edgeType":"contains","source":6450,"target":6640},{"edgeType":"calls","source":2704,"target":2092},{"edgeType":"calls","source":4766,"target":4762},{"edgeType":"calls","source":6242,"target":2344},{"edgeType":"calls","source":4164,"target":170},{"edgeType":"calls","source":4220,"target":548},{"edgeType":"contains","source":2359,"target":2383},{"edgeType":"contains","source":5410,"target":6105},{"edgeType":"calls","source":6746,"target":469},{"edgeType":"calls","source":1098,"target":84},{"edgeType":"extends","source":6656,"target":36},{"edgeType":"calls","source":2784,"target":2783},{"edgeType":"contains","source":3976,"target":4050},{"edgeType":"calls","source":4841,"target":4551},{"edgeType":"calls","source":4595,"target":548},{"edgeType":"contains","source":47,"target":67},{"edgeType":"contains","source":6450,"target":6633},{"edgeType":"contains","source":5458,"target":5674},{"edgeType":"calls","source":2650,"target":591},{"edgeType":"calls","source":1958,"target":1959},{"edgeType":"contains","source":2599,"target":3405},{"edgeType":"calls","source":6242,"target":2343},{"edgeType":"contains","source":4474,"target":4475},{"edgeType":"contains","source":606,"target":708},{"edgeType":"calls","source":4841,"target":4550},{"edgeType":"contains","source":5167,"target":5189},{"edgeType":"calls","source":6706,"target":4881},{"edgeType":"contains","source":2359,"target":2388},{"edgeType":"calls","source":3609,"target":3630},{"edgeType":"calls","source":5694,"target":304},{"edgeType":"calls","source":5044,"target":371},{"edgeType":"contains","source":6026,"target":6036},{"edgeType":"calls","source":1130,"target":144},{"edgeType":"contains","source":5410,"target":6112},{"edgeType":"contains","source":47,"target":66},{"edgeType":"contains","source":5452,"target":5861},{"edgeType":"calls","source":3743,"target":535},{"edgeType":"calls","source":6242,"target":2342},{"edgeType":"imports","source":132,"target":144},{"edgeType":"calls","source":6055,"target":1797},{"edgeType":"imports","source":5616,"target":5617},{"edgeType":"calls","source":5694,"target":303},{"edgeType":"contains","source":2359,"target":2389},{"edgeType":"contains","source":5167,"target":5188},{"edgeType":"calls","source":6880,"target":1602},{"edgeType":"contains","source":3152,"target":3175},{"edgeType":"calls","source":4703,"target":4599},{"edgeType":"contains","source":1402,"target":1403},{"edgeType":"calls","source":5044,"target":370},{"edgeType":"contains","source":606,"target":710},{"edgeType":"contains","source":5617,"target":1804},{"edgeType":"calls","source":1595,"target":1587},{"edgeType":"contains","source":47,"target":69},{"edgeType":"calls","source":6242,"target":2341},{"edgeType":"contains","source":5167,"target":5187},{"edgeType":"calls","source":1413,"target":886},{"edgeType":"calls","source":6410,"target":304},{"edgeType":"calls","source":5044,"target":369},{"edgeType":"contains","source":4391,"target":4931},{"edgeType":"calls","source":2962,"target":431},{"edgeType":"contains","source":3152,"target":3172},{"edgeType":"calls","source":6964,"target":56},{"edgeType":"contains","source":3549,"target":3551},{"edgeType":"calls","source":5163,"target":5136},{"edgeType":"contains","source":47,"target":68},{"edgeType":"contains","source":5452,"target":5863},{"edgeType":"calls","source":6862,"target":4276},{"edgeType":"calls","source":6410,"target":303},{"edgeType":"calls","source":4330,"target":304},{"edgeType":"contains","source":2359,"target":2387},{"edgeType":"calls","source":5044,"target":368},{"edgeType":"contains","source":5167,"target":5186},{"edgeType":"contains","source":5410,"target":6109},{"edgeType":"calls","source":5163,"target":5135},{"edgeType":"contains","source":2599,"target":3409},{"edgeType":"contains","source":5366,"target":5367},{"edgeType":"contains","source":6074,"target":5617},{"edgeType":"calls","source":1213,"target":738},{"edgeType":"calls","source":1766,"target":508},{"edgeType":"contains","source":4507,"target":4513},{"edgeType":"contains","source":47,"target":71},{"edgeType":"calls","source":298,"target":563},{"edgeType":"calls","source":6862,"target":4277},{"edgeType":"contains","source":2359,"target":2393},{"edgeType":"calls","source":4330,"target":303},{"edgeType":"contains","source":1402,"target":1406},{"edgeType":"calls","source":1766,"target":507},{"edgeType":"calls","source":5163,"target":5134},{"edgeType":"contains","source":5167,"target":5193},{"edgeType":"extends","source":1064,"target":36},{"edgeType":"contains","source":5410,"target":6116},{"edgeType":"contains","source":1814,"target":2376},{"edgeType":"contains","source":47,"target":70},{"edgeType":"calls","source":298,"target":562},{"edgeType":"contains","source":132,"target":606},{"edgeType":"calls","source":6862,"target":4278},{"edgeType":"contains","source":2359,"target":2394},{"edgeType":"calls","source":5044,"target":366},{"edgeType":"contains","source":4375,"target":4376},{"edgeType":"contains","source":1498,"target":1602},{"edgeType":"calls","source":207,"target":212},{"edgeType":"calls","source":6688,"target":159},{"edgeType":"contains","source":6450,"target":6647},{"edgeType":"contains","source":1402,"target":1407},{"edgeType":"contains","source":5166,"target":6280},{"edgeType":"calls","source":5227,"target":2092},{"edgeType":"calls","source":1766,"target":506},{"edgeType":"contains","source":5167,"target":5192},{"edgeType":"extends","source":3245,"target":3246},{"edgeType":"calls","source":4107,"target":4042},{"edgeType":"imports","source":4668,"target":1170},{"edgeType":"calls","source":6862,"target":4279},{"edgeType":"calls","source":6959,"target":215},{"edgeType":"contains","source":47,"target":73},{"edgeType":"contains","source":4474,"target":4477},{"edgeType":"calls","source":6252,"target":6255},{"edgeType":"contains","source":4408,"target":4409},{"edgeType":"contains","source":2359,"target":2391},{"edgeType":"contains","source":2359,"target":2390},{"edgeType":"calls","source":6606,"target":588},{"edgeType":"calls","source":6688,"target":160},{"edgeType":"calls","source":5653,"target":512},{"edgeType":"calls","source":5227,"target":2091},{"edgeType":"calls","source":1222,"target":461},{"edgeType":"contains","source":5167,"target":5191},{"edgeType":"contains","source":1402,"target":1404},{"edgeType":"calls","source":1132,"target":1136},{"edgeType":"calls","source":1766,"target":509},{"edgeType":"contains","source":47,"target":72},{"edgeType":"calls","source":6947,"target":588},{"edgeType":"calls","source":6937,"target":898},{"edgeType":"calls","source":6879,"target":582},{"edgeType":"calls","source":6888,"target":303},{"edgeType":"calls","source":4219,"target":571},{"edgeType":"calls","source":6862,"target":4280},{"edgeType":"contains","source":4474,"target":4476},{"edgeType":"calls","source":4710,"target":147},{"edgeType":"calls","source":298,"target":564},{"edgeType":"contains","source":2359,"target":2392},{"edgeType":"contains","source":4391,"target":4934},{"edgeType":"calls","source":143,"target":84},{"edgeType":"contains","source":5167,"target":5190},{"edgeType":"calls","source":6688,"target":161},{"edgeType":"calls","source":5044,"target":364},{"edgeType":"contains","source":5410,"target":6113},{"edgeType":"extends","source":4474,"target":36},{"edgeType":"calls","source":550,"target":146},{"edgeType":"calls","source":3213,"target":3214},{"edgeType":"calls","source":4184,"target":596},{"edgeType":"calls","source":6888,"target":304},{"edgeType":"contains","source":2359,"target":2397},{"edgeType":"calls","source":6954,"target":6714},{"edgeType":"contains","source":47,"target":75},{"edgeType":"contains","source":41,"target":6604},{"edgeType":"calls","source":6862,"target":4281},{"edgeType":"calls","source":207,"target":209},{"edgeType":"contains","source":3,"target":4611},{"edgeType":"contains","source":4307,"target":4375},{"edgeType":"calls","source":6451,"target":6452},{"edgeType":"contains","source":3351,"target":3357},{"edgeType":"calls","source":1766,"target":503},{"edgeType":"calls","source":1697,"target":528},{"edgeType":"contains","source":1860,"target":2011},{"edgeType":"contains","source":3219,"target":3221},{"edgeType":"contains","source":5267,"target":5268},{"edgeType":"contains","source":5410,"target":6120},{"edgeType":"contains","source":2359,"target":2398},{"edgeType":"contains","source":47,"target":74},{"edgeType":"calls","source":6935,"target":962},{"edgeType":"calls","source":4734,"target":458},{"edgeType":"calls","source":6484,"target":6487},{"edgeType":"calls","source":1697,"target":527},{"edgeType":"calls","source":5653,"target":509},{"edgeType":"calls","source":1766,"target":502},{"edgeType":"extends","source":3110,"target":36},{"edgeType":"contains","source":5410,"target":6119},{"edgeType":"contains","source":4432,"target":4726},{"edgeType":"contains","source":2359,"target":2395},{"edgeType":"calls","source":5087,"target":84},{"edgeType":"calls","source":4734,"target":457},{"edgeType":"calls","source":4710,"target":144},{"edgeType":"calls","source":6935,"target":963},{"edgeType":"calls","source":207,"target":211},{"edgeType":"calls","source":6543,"target":431},{"edgeType":"calls","source":1766,"target":505},{"edgeType":"contains","source":1402,"target":1408},{"edgeType":"extends","source":4137,"target":4139},{"edgeType":"contains","source":885,"target":1582},{"edgeType":"contains","source":3013,"target":4318},{"edgeType":"calls","source":5509,"target":4972},{"edgeType":"calls","source":5653,"target":508},{"edgeType":"imports","source":4668,"target":1175},{"edgeType":"calls","source":1131,"target":1163},{"edgeType":"calls","source":6108,"target":2258},{"edgeType":"contains","source":5410,"target":6118},{"edgeType":"calls","source":6992,"target":6596},{"edgeType":"contains","source":2359,"target":2396},{"edgeType":"contains","source":47,"target":76},{"edgeType":"calls","source":2679,"target":1797},{"edgeType":"contains","source":2206,"target":2911},{"edgeType":"calls","source":207,"target":210},{"edgeType":"calls","source":5144,"target":431},{"edgeType":"calls","source":6675,"target":568},{"edgeType":"calls","source":2090,"target":2087},{"edgeType":"extends","source":437,"target":452},{"edgeType":"calls","source":1766,"target":504},{"edgeType":"calls","source":6108,"target":2257},{"edgeType":"calls","source":5655,"target":445},{"edgeType":"calls","source":5653,"target":507},{"edgeType":"contains","source":3043,"target":1275},{"edgeType":"contains","source":3152,"target":3154},{"edgeType":"imports","source":6476,"target":78},{"edgeType":"contains","source":4391,"target":4913},{"edgeType":"contains","source":5167,"target":5169},{"edgeType":"calls","source":3347,"target":146},{"edgeType":"calls","source":471,"target":510},{"edgeType":"contains","source":2128,"target":2130},{"edgeType":"calls","source":3055,"target":1799},{"edgeType":"extends","source":2490,"target":2316},{"edgeType":"calls","source":298,"target":588},{"edgeType":"contains","source":1269,"target":1276},{"edgeType":"contains","source":6817,"target":6871},{"edgeType":"contains","source":5167,"target":5168},{"edgeType":"calls","source":471,"target":509},{"edgeType":"calls","source":946,"target":582},{"edgeType":"calls","source":968,"target":958},{"edgeType":"contains","source":6817,"target":6872},{"edgeType":"calls","source":4739,"target":4559},{"edgeType":"calls","source":2045,"target":342},{"edgeType":"contains","source":3218,"target":3220},{"edgeType":"imports","source":952,"target":78},{"edgeType":"contains","source":5,"target":6636},{"edgeType":"calls","source":1096,"target":164},{"edgeType":"contains","source":3976,"target":4034},{"edgeType":"calls","source":6726,"target":1071},{"edgeType":"calls","source":3142,"target":157},{"edgeType":"calls","source":1602,"target":333},{"edgeType":"contains","source":14,"target":15},{"edgeType":"calls","source":5759,"target":422},{"edgeType":"contains","source":6476,"target":6874},{"edgeType":"contains","source":3152,"target":3153},{"edgeType":"calls","source":1242,"target":922},{"edgeType":"imports","source":6476,"target":79},{"edgeType":"contains","source":5410,"target":6089},{"edgeType":"contains","source":5,"target":6635},{"edgeType":"imports","source":952,"target":79},{"edgeType":"calls","source":6779,"target":1543},{"edgeType":"calls","source":1602,"target":332},{"edgeType":"calls","source":4337,"target":4336},{"edgeType":"contains","source":6026,"target":6027},{"edgeType":"imports","source":2736,"target":1853},{"edgeType":"calls","source":5759,"target":421},{"edgeType":"contains","source":6604,"target":2907},{"edgeType":"imports","source":130,"target":192},{"edgeType":"contains","source":4432,"target":4703},{"edgeType":"contains","source":4391,"target":4917},{"edgeType":"contains","source":5167,"target":5173},{"edgeType":"calls","source":4738,"target":4588},{"edgeType":"calls","source":576,"target":422},{"edgeType":"contains","source":1498,"target":1580},{"edgeType":"imports","source":1379,"target":1638},{"edgeType":"calls","source":5144,"target":458},{"edgeType":"calls","source":471,"target":506},{"edgeType":"contains","source":6817,"target":6867},{"edgeType":"calls","source":4126,"target":304},{"edgeType":"contains","source":3867,"target":1076},{"edgeType":"contains","source":5167,"target":5172},{"edgeType":"contains","source":4391,"target":4916},{"edgeType":"calls","source":6455,"target":1041},{"edgeType":"contains","source":2915,"target":3107},{"edgeType":"calls","source":5559,"target":5562},{"edgeType":"extends","source":5871,"target":36},{"edgeType":"calls","source":5144,"target":457},{"edgeType":"calls","source":1576,"target":1132},{"edgeType":"contains","source":5410,"target":6095},{"edgeType":"calls","source":469,"target":567},{"edgeType":"calls","source":471,"target":505},{"edgeType":"contains","source":2176,"target":2761},{"edgeType":"calls","source":576,"target":421},{"edgeType":"calls","source":4467,"target":304},{"edgeType":"contains","source":5167,"target":5171},{"edgeType":"contains","source":6554,"target":6566},{"edgeType":"calls","source":6880,"target":1586},{"edgeType":"calls","source":5559,"target":5561},{"edgeType":"calls","source":4597,"target":4729},{"edgeType":"contains","source":6286,"target":6418},{"edgeType":"calls","source":471,"target":508},{"edgeType":"calls","source":2699,"target":144},{"edgeType":"contains","source":5,"target":4526},{"edgeType":"calls","source":4467,"target":303},{"edgeType":"contains","source":6817,"target":6869},{"edgeType":"contains","source":5908,"target":6509},{"edgeType":"imports","source":3166,"target":147},{"edgeType":"calls","source":4872,"target":431},{"edgeType":"contains","source":3152,"target":3157},{"edgeType":"contains","source":5167,"target":5170},{"edgeType":"imports","source":4391,"target":1297},{"edgeType":"calls","source":997,"target":56},{"edgeType":"calls","source":471,"target":507},{"edgeType":"calls","source":4126,"target":303},{"edgeType":"contains","source":6817,"target":6870},{"edgeType":"extends","source":1984,"target":36},{"edgeType":"contains","source":4307,"target":5411},{"edgeType":"calls","source":4914,"target":4413},{"edgeType":"contains","source":5167,"target":5177},{"edgeType":"calls","source":471,"target":502},{"edgeType":"contains","source":5410,"target":6100},{"edgeType":"calls","source":6087,"target":1875},{"edgeType":"contains","source":3976,"target":4045},{"edgeType":"contains","source":3879,"target":3881},{"edgeType":"contains","source":47,"target":55},{"edgeType":"calls","source":2762,"target":303},{"edgeType":"contains","source":5908,"target":3348},{"edgeType":"calls","source":4973,"target":2583},{"edgeType":"contains","source":1031,"target":1261},{"edgeType":"calls","source":2762,"target":304},{"edgeType":"calls","source":5247,"target":431},{"edgeType":"contains","source":3152,"target":3163},{"edgeType":"contains","source":6817,"target":6881},{"edgeType":"contains","source":5167,"target":5176},{"edgeType":"contains","source":5410,"target":6099},{"edgeType":"contains","source":3879,"target":3880},{"edgeType":"contains","source":47,"target":54},{"edgeType":"calls","source":6994,"target":170},{"edgeType":"contains","source":2359,"target":2377},{"edgeType":"calls","source":7078,"target":7079},{"edgeType":"contains","source":5166,"target":2035},{"edgeType":"contains","source":1654,"target":974},{"edgeType":"calls","source":6617,"target":6572},{"edgeType":"calls","source":2849,"target":2889},{"edgeType":"contains","source":2915,"target":3108},{"edgeType":"imports","source":885,"target":49},{"edgeType":"contains","source":6851,"target":6885},{"edgeType":"contains","source":3152,"target":3160},{"edgeType":"contains","source":996,"target":1292},{"edgeType":"contains","source":5167,"target":5175},{"edgeType":"calls","source":4649,"target":4170},{"edgeType":"calls","source":471,"target":504},{"edgeType":"extends","source":1947,"target":1186},{"edgeType":"contains","source":47,"target":57},{"edgeType":"calls","source":6994,"target":171},{"edgeType":"contains","source":6026,"target":6034},{"edgeType":"contains","source":1654,"target":975},{"edgeType":"contains","source":5167,"target":5174},{"edgeType":"contains","source":2915,"target":3109},{"edgeType":"calls","source":2849,"target":2890},{"edgeType":"imports","source":3030,"target":147},{"edgeType":"contains","source":1031,"target":1263},{"edgeType":"calls","source":471,"target":503},{"edgeType":"calls","source":4674,"target":4451},{"edgeType":"contains","source":47,"target":56},{"edgeType":"contains","source":30,"target":2697},{"edgeType":"calls","source":7029,"target":144},{"edgeType":"contains","source":4432,"target":4704},{"edgeType":"contains","source":5908,"target":3343},{"edgeType":"calls","source":5891,"target":548},{"edgeType":"calls","source":5075,"target":475},{"edgeType":"calls","source":6551,"target":164},{"edgeType":"calls","source":3512,"target":304},{"edgeType":"contains","source":2756,"target":2758},{"edgeType":"contains","source":5167,"target":5181},{"edgeType":"calls","source":5379,"target":564},{"edgeType":"calls","source":7058,"target":303},{"edgeType":"contains","source":6026,"target":6028},{"edgeType":"contains","source":2359,"target":2380},{"edgeType":"contains","source":47,"target":59},{"edgeType":"calls","source":6688,"target":146},{"edgeType":"contains","source":5878,"target":1103},{"edgeType":"calls","source":5075,"target":474},{"edgeType":"calls","source":6551,"target":165},{"edgeType":"contains","source":5167,"target":5180},{"edgeType":"calls","source":5379,"target":563},{"edgeType":"contains","source":2756,"target":2759},{"edgeType":"calls","source":3824,"target":146},{"edgeType":"calls","source":2087,"target":1138},{"edgeType":"contains","source":2359,"target":2381},{"edgeType":"contains","source":47,"target":58},{"edgeType":"calls","source":4881,"target":146},{"edgeType":"calls","source":2485,"target":431},{"edgeType":"calls","source":7058,"target":304},{"edgeType":"contains","source":1498,"target":1586},{"edgeType":"calls","source":5075,"target":473},{"edgeType":"calls","source":4982,"target":4413},{"edgeType":"calls","source":2186,"target":183},{"edgeType":"contains","source":5167,"target":5179},{"edgeType":"calls","source":5379,"target":562},{"edgeType":"extends","source":2255,"target":2212},{"edgeType":"contains","source":3152,"target":3164},{"edgeType":"calls","source":4708,"target":4451},{"edgeType":"imports","source":2581,"target":321},{"edgeType":"contains","source":3879,"target":3883},{"edgeType":"imports","source":4706,"target":1036},{"edgeType":"calls","source":3302,"target":469},{"edgeType":"calls","source":2122,"target":56},{"edgeType":"contains","source":3813,"target":3815},{"edgeType":"calls","source":4841,"target":4556},{"edgeType":"calls","source":604,"target":605},{"edgeType":"calls","source":2561,"target":2300},{"edgeType":"contains","source":2359,"target":2378},{"edgeType":"contains","source":47,"target":61},{"edgeType":"contains","source":45,"target":123},{"edgeType":"calls","source":5015,"target":4446},{"edgeType":"contains","source":6476,"target":6879},{"edgeType":"calls","source":3512,"target":303},{"edgeType":"contains","source":3152,"target":3165},{"edgeType":"contains","source":5167,"target":5178},{"edgeType":"contains","source":3976,"target":4046},{"edgeType":"contains","source":5410,"target":6101},{"edgeType":"contains","source":3879,"target":3882},{"edgeType":"contains","source":1732,"target":1733},{"edgeType":"calls","source":4841,"target":4555},{"edgeType":"contains","source":2359,"target":2379},{"edgeType":"contains","source":47,"target":60},{"edgeType":"contains","source":45,"target":122},{"edgeType":"calls","source":7032,"target":1112},{"edgeType":"contains","source":14,"target":26},{"edgeType":"contains","source":30,"target":2701},{"edgeType":"contains","source":3,"target":3508},{"edgeType":"contains","source":736,"target":869},{"edgeType":"contains","source":2688,"target":2723},{"edgeType":"contains","source":6651,"target":6716},{"edgeType":"contains","source":6653,"target":6654},{"edgeType":"contains","source":2872,"target":3361},{"edgeType":"calls","source":6994,"target":144},{"edgeType":"calls","source":6207,"target":2342},{"edgeType":"calls","source":1499,"target":303},{"edgeType":"contains","source":5410,"target":6075},{"edgeType":"calls","source":1131,"target":1141},{"edgeType":"contains","source":13,"target":27},{"edgeType":"calls","source":2834,"target":144},{"edgeType":"calls","source":1131,"target":84},{"edgeType":"calls","source":4674,"target":4413},{"edgeType":"calls","source":4702,"target":4602},{"edgeType":"calls","source":5162,"target":5139},{"edgeType":"contains","source":736,"target":868},{"edgeType":"contains","source":6280,"target":6590},{"edgeType":"contains","source":4671,"target":4672},{"edgeType":"imports","source":5592,"target":49},{"edgeType":"contains","source":6450,"target":6605},{"edgeType":"contains","source":2688,"target":2724},{"edgeType":"contains","source":6651,"target":6717},{"edgeType":"calls","source":6207,"target":2341},{"edgeType":"calls","source":6277,"target":171},{"edgeType":"imports","source":1379,"target":1691},{"edgeType":"calls","source":6881,"target":6819},{"edgeType":"contains","source":736,"target":871},{"edgeType":"contains","source":2872,"target":3359},{"edgeType":"contains","source":2688,"target":2721},{"edgeType":"calls","source":6277,"target":170},{"edgeType":"contains","source":6620,"target":6622},{"edgeType":"calls","source":6333,"target":548},{"edgeType":"calls","source":3468,"target":571},{"edgeType":"contains","source":2581,"target":1809},{"edgeType":"calls","source":1131,"target":1143},{"edgeType":"calls","source":1124,"target":303},{"edgeType":"calls","source":4469,"target":4422},{"edgeType":"contains","source":736,"target":870},{"edgeType":"imports","source":5217,"target":49},{"edgeType":"contains","source":936,"target":1012},{"edgeType":"contains","source":2688,"target":2722},{"edgeType":"contains","source":3116,"target":3195},{"edgeType":"calls","source":6054,"target":1797},{"edgeType":"calls","source":1813,"target":84},{"edgeType":"contains","source":6620,"target":6623},{"edgeType":"contains","source":2872,"target":3360},{"edgeType":"contains","source":5195,"target":6395},{"edgeType":"calls","source":1499,"target":304},{"edgeType":"extends","source":2872,"target":36},{"edgeType":"calls","source":4708,"target":4413},{"edgeType":"contains","source":5596,"target":5599},{"edgeType":"calls","source":2260,"target":2078},{"edgeType":"calls","source":4005,"target":4006},{"edgeType":"extends","source":4075,"target":2916},{"edgeType":"calls","source":5893,"target":445},{"edgeType":"calls","source":2104,"target":571},{"edgeType":"imports","source":3819,"target":49},{"edgeType":"contains","source":736,"target":873},{"edgeType":"contains","source":2688,"target":2727},{"edgeType":"contains","source":1028,"target":1334},{"edgeType":"contains","source":6651,"target":6711},{"edgeType":"calls","source":1532,"target":333},{"edgeType":"calls","source":2931,"target":304},{"edgeType":"contains","source":3166,"target":1650},{"edgeType":"calls","source":3272,"target":303},{"edgeType":"contains","source":2688,"target":2728},{"edgeType":"calls","source":1782,"target":1039},{"edgeType":"contains","source":6604,"target":2884},{"edgeType":"contains","source":4618,"target":6319},{"edgeType":"contains","source":736,"target":872},{"edgeType":"calls","source":1532,"target":332},{"edgeType":"contains","source":1028,"target":1333},{"edgeType":"contains","source":3166,"target":1651},{"edgeType":"imports","source":4668,"target":157},{"edgeType":"calls","source":5077,"target":371},{"edgeType":"calls","source":1172,"target":922},{"edgeType":"calls","source":3272,"target":304},{"edgeType":"calls","source":6585,"target":144},{"edgeType":"calls","source":3890,"target":170},{"edgeType":"calls","source":6882,"target":6793},{"edgeType":"calls","source":5893,"target":443},{"edgeType":"extends","source":6350,"target":36},{"edgeType":"calls","source":1876,"target":1299},{"edgeType":"contains","source":736,"target":875},{"edgeType":"contains","source":2688,"target":2725},{"edgeType":"calls","source":6152,"target":6155},{"edgeType":"calls","source":6811,"target":2652},{"edgeType":"calls","source":5077,"target":370},{"edgeType":"calls","source":2998,"target":339},{"edgeType":"contains","source":928,"target":1265},{"edgeType":"calls","source":2780,"target":1812},{"edgeType":"imports","source":2898,"target":49},{"edgeType":"imports","source":6432,"target":1498},{"edgeType":"calls","source":5288,"target":171},{"edgeType":"calls","source":6542,"target":421},{"edgeType":"calls","source":1797,"target":576},{"edgeType":"calls","source":4018,"target":431},{"edgeType":"calls","source":7041,"target":1865},{"edgeType":"calls","source":3890,"target":171},{"edgeType":"contains","source":736,"target":874},{"edgeType":"calls","source":6152,"target":6154},{"edgeType":"calls","source":2279,"target":431},{"edgeType":"contains","source":2688,"target":2726},{"edgeType":"calls","source":5077,"target":369},{"edgeType":"calls","source":5075,"target":431},{"edgeType":"calls","source":2931,"target":303},{"edgeType":"calls","source":6811,"target":2653},{"edgeType":"calls","source":6542,"target":422},{"edgeType":"calls","source":5288,"target":170},{"edgeType":"contains","source":5616,"target":6032},{"edgeType":"calls","source":5445,"target":588},{"edgeType":"extends","source":1031,"target":36},{"edgeType":"contains","source":6620,"target":6628},{"edgeType":"calls","source":535,"target":582},{"edgeType":"imports","source":1415,"target":1641},{"edgeType":"imports","source":6432,"target":2540},{"edgeType":"imports","source":1379,"target":1700},{"edgeType":"calls","source":4363,"target":304},{"edgeType":"calls","source":5077,"target":368},{"edgeType":"calls","source":2138,"target":571},{"edgeType":"calls","source":2998,"target":337},{"edgeType":"calls","source":6800,"target":1938},{"edgeType":"calls","source":6926,"target":146},{"edgeType":"imports","source":2176,"target":1305},{"edgeType":"calls","source":6605,"target":584},{"edgeType":"calls","source":5379,"target":2632},{"edgeType":"contains","source":6817,"target":6864},{"edgeType":"calls","source":4363,"target":303},{"edgeType":"extends","source":6214,"target":36},{"edgeType":"calls","source":2820,"target":571},{"edgeType":"calls","source":2998,"target":338},{"edgeType":"calls","source":6600,"target":1797},{"edgeType":"contains","source":1302,"target":1303},{"edgeType":"calls","source":1154,"target":422},{"edgeType":"contains","source":2688,"target":2729},{"edgeType":"calls","source":5379,"target":2631},{"edgeType":"calls","source":1197,"target":146},{"edgeType":"calls","source":7030,"target":1152},{"edgeType":"contains","source":4618,"target":6322},{"edgeType":"contains","source":520,"target":6518},{"edgeType":"calls","source":4176,"target":3984},{"edgeType":"imports","source":1415,"target":1639},{"edgeType":"imports","source":1379,"target":1698},{"edgeType":"contains","source":3775,"target":3915},{"edgeType":"calls","source":5077,"target":366},{"edgeType":"contains","source":6817,"target":6865},{"edgeType":"calls","source":5378,"target":548},{"edgeType":"contains","source":1558,"target":1820},{"edgeType":"extends","source":438,"target":451},{"edgeType":"calls","source":1154,"target":421},{"edgeType":"calls","source":1131,"target":1134},{"edgeType":"calls","source":5419,"target":333},{"edgeType":"imports","source":4668,"target":147},{"edgeType":"calls","source":6846,"target":1572},{"edgeType":"calls","source":535,"target":583},{"edgeType":"imports","source":1415,"target":1638},{"edgeType":"calls","source":4442,"target":4194},{"edgeType":"calls","source":2837,"target":1099},{"edgeType":"contains","source":6817,"target":6866},{"edgeType":"calls","source":3710,"target":3632},{"edgeType":"contains","source":1558,"target":1821},{"edgeType":"contains","source":6817,"target":6859},{"edgeType":"calls","source":2083,"target":157},{"edgeType":"calls","source":5419,"target":332},{"edgeType":"contains","source":2686,"target":2797},{"edgeType":"calls","source":1197,"target":1197},{"edgeType":"calls","source":2782,"target":2800},{"edgeType":"calls","source":4765,"target":4750},{"edgeType":"contains","source":6554,"target":6556},{"edgeType":"calls","source":4442,"target":4193},{"edgeType":"calls","source":4709,"target":144},{"edgeType":"extends","source":4100,"target":36},{"edgeType":"contains","source":1498,"target":1572},{"edgeType":"calls","source":2998,"target":333},{"edgeType":"calls","source":5077,"target":364},{"edgeType":"calls","source":6417,"target":6416},{"edgeType":"contains","source":5596,"target":5600},{"edgeType":"calls","source":5242,"target":4762},{"edgeType":"imports","source":5166,"target":565},{"edgeType":"calls","source":6887,"target":303},{"edgeType":"contains","source":6620,"target":6625},{"edgeType":"imports","source":1379,"target":1695},{"edgeType":"calls","source":3430,"target":2794},{"edgeType":"contains","source":6620,"target":6626},{"edgeType":"calls","source":6887,"target":304},{"edgeType":"calls","source":2585,"target":2563},{"edgeType":"contains","source":41,"target":4459},{"edgeType":"calls","source":7032,"target":2151},{"edgeType":"calls","source":2877,"target":910},{"edgeType":"calls","source":890,"target":146},{"edgeType":"contains","source":5878,"target":1088},{"edgeType":"contains","source":6476,"target":6862},{"edgeType":"calls","source":945,"target":555},{"edgeType":"calls","source":6605,"target":590},{"edgeType":"imports","source":5285,"target":49},{"edgeType":"contains","source":5596,"target":5602},{"edgeType":"contains","source":5592,"target":5726},{"edgeType":"calls","source":3720,"target":146},{"edgeType":"calls","source":5488,"target":304},{"edgeType":"calls","source":2877,"target":911},{"edgeType":"calls","source":2888,"target":570},{"edgeType":"contains","source":2495,"target":1318},{"edgeType":"calls","source":2991,"target":548},{"edgeType":"calls","source":2585,"target":2564},{"edgeType":"calls","source":208,"target":146},{"edgeType":"calls","source":2320,"target":2323},{"edgeType":"calls","source":2998,"target":332},{"edgeType":"extends","source":2254,"target":180},{"edgeType":"imports","source":2843,"target":2801},{"edgeType":"extends","source":2915,"target":2916},{"edgeType":"calls","source":604,"target":582},{"edgeType":"calls","source":5653,"target":506},{"edgeType":"contains","source":3352,"target":1149},{"edgeType":"calls","source":2786,"target":2705},{"edgeType":"calls","source":1742,"target":1243},{"edgeType":"calls","source":6606,"target":528},{"edgeType":"contains","source":736,"target":852},{"edgeType":"calls","source":6675,"target":503},{"edgeType":"contains","source":7015,"target":7042},{"edgeType":"contains","source":1498,"target":1543},{"edgeType":"contains","source":4307,"target":4313},{"edgeType":"calls","source":5222,"target":5411},{"edgeType":"contains","source":2688,"target":2706},{"edgeType":"calls","source":1359,"target":431},{"edgeType":"contains","source":5195,"target":6381},{"edgeType":"calls","source":5655,"target":443},{"edgeType":"calls","source":5653,"target":505},{"edgeType":"contains","source":3352,"target":1150},{"edgeType":"calls","source":1132,"target":1126},{"edgeType":"calls","source":2883,"target":2870},{"edgeType":"calls","source":6675,"target":504},{"edgeType":"contains","source":736,"target":851},{"edgeType":"calls","source":6371,"target":4643},{"edgeType":"contains","source":2688,"target":2707},{"edgeType":"calls","source":6030,"target":445},{"edgeType":"calls","source":5653,"target":504},{"edgeType":"contains","source":4505,"target":4515},{"edgeType":"calls","source":6675,"target":505},{"edgeType":"calls","source":6911,"target":588},{"edgeType":"calls","source":6724,"target":6385},{"edgeType":"contains","source":1498,"target":1541},{"edgeType":"contains","source":736,"target":854},{"edgeType":"contains","source":9,"target":137},{"edgeType":"calls","source":6541,"target":431},{"edgeType":"calls","source":7065,"target":6385},{"edgeType":"contains","source":6091,"target":6092},{"edgeType":"calls","source":3753,"target":209},{"edgeType":"calls","source":5653,"target":503},{"edgeType":"calls","source":4880,"target":3325},{"edgeType":"calls","source":1354,"target":588},{"edgeType":"contains","source":4505,"target":4514},{"edgeType":"contains","source":3811,"target":3830},{"edgeType":"calls","source":6675,"target":506},{"edgeType":"contains","source":1907,"target":2604},{"edgeType":"calls","source":4879,"target":4413},{"edgeType":"calls","source":6030,"target":443},{"edgeType":"contains","source":736,"target":853},{"edgeType":"calls","source":6371,"target":4645},{"edgeType":"contains","source":1379,"target":2060},{"edgeType":"contains","source":6091,"target":6093},{"edgeType":"contains","source":7015,"target":7045},{"edgeType":"calls","source":3629,"target":883},{"edgeType":"calls","source":3753,"target":210},{"edgeType":"contains","source":1037,"target":1039},{"edgeType":"extends","source":6554,"target":36},{"edgeType":"contains","source":5195,"target":6386},{"edgeType":"calls","source":2794,"target":339},{"edgeType":"calls","source":594,"target":888},{"edgeType":"calls","source":5653,"target":502},{"edgeType":"contains","source":1907,"target":2609},{"edgeType":"calls","source":6675,"target":507},{"edgeType":"calls","source":1797,"target":591},{"edgeType":"calls","source":372,"target":371},{"edgeType":"contains","source":6280,"target":6569},{"edgeType":"calls","source":2111,"target":370},{"edgeType":"contains","source":736,"target":856},{"edgeType":"contains","source":2688,"target":2710},{"edgeType":"calls","source":5044,"target":353},{"edgeType":"calls","source":6883,"target":2516},{"edgeType":"contains","source":6610,"target":6910},{"edgeType":"calls","source":6838,"target":1797},{"edgeType":"calls","source":4766,"target":4743},{"edgeType":"calls","source":3475,"target":3541},{"edgeType":"calls","source":711,"target":431},{"edgeType":"calls","source":4682,"target":4176},{"edgeType":"contains","source":1907,"target":2610},{"edgeType":"contains","source":3352,"target":1154},{"edgeType":"calls","source":6778,"target":1543},{"edgeType":"calls","source":6675,"target":508},{"edgeType":"contains","source":736,"target":855},{"edgeType":"calls","source":1132,"target":1121},{"edgeType":"calls","source":3112,"target":3167},{"edgeType":"calls","source":372,"target":370},{"edgeType":"calls","source":7051,"target":6822},{"edgeType":"contains","source":46,"target":48},{"edgeType":"contains","source":569,"target":747},{"edgeType":"calls","source":2111,"target":369},{"edgeType":"extends","source":40,"target":81},{"edgeType":"calls","source":6141,"target":171},{"edgeType":"contains","source":2688,"target":2711},{"edgeType":"calls","source":6684,"target":6572},{"edgeType":"contains","source":5232,"target":5237},{"edgeType":"calls","source":2794,"target":337},{"edgeType":"contains","source":3352,"target":1151},{"edgeType":"calls","source":6675,"target":509},{"edgeType":"calls","source":6727,"target":1011},{"edgeType":"calls","source":6141,"target":170},{"edgeType":"imports","source":3814,"target":190},{"edgeType":"calls","source":174,"target":169},{"edgeType":"calls","source":2045,"target":304},{"edgeType":"contains","source":736,"target":858},{"edgeType":"contains","source":2688,"target":2708},{"edgeType":"calls","source":6685,"target":6542},{"edgeType":"calls","source":2794,"target":338},{"edgeType":"contains","source":4432,"target":4667},{"edgeType":"contains","source":5232,"target":5236},{"edgeType":"contains","source":3352,"target":1152},{"edgeType":"contains","source":1907,"target":2608},{"edgeType":"imports","source":6610,"target":190},{"edgeType":"extends","source":5463,"target":36},{"edgeType":"imports","source":5166,"target":4788},{"edgeType":"contains","source":5,"target":3435},{"edgeType":"imports","source":2176,"target":2330},{"edgeType":"calls","source":6210,"target":144},{"edgeType":"contains","source":2688,"target":2709},{"edgeType":"calls","source":2045,"target":303},{"edgeType":"contains","source":736,"target":857},{"edgeType":"calls","source":2111,"target":371},{"edgeType":"contains","source":5726,"target":5785},{"edgeType":"calls","source":107,"target":125},{"edgeType":"imports","source":5166,"target":545},{"edgeType":"contains","source":1028,"target":1322},{"edgeType":"calls","source":4805,"target":4588},{"edgeType":"calls","source":3477,"target":303},{"edgeType":"contains","source":5195,"target":6390},{"edgeType":"contains","source":3166,"target":1638},{"edgeType":"calls","source":1733,"target":457},{"edgeType":"extends","source":2599,"target":36},{"edgeType":"calls","source":4017,"target":475},{"edgeType":"calls","source":4601,"target":4570},{"edgeType":"contains","source":2688,"target":2714},{"edgeType":"calls","source":2111,"target":366},{"edgeType":"calls","source":2795,"target":304},{"edgeType":"contains","source":837,"target":900},{"edgeType":"calls","source":4166,"target":84},{"edgeType":"contains","source":736,"target":860},{"edgeType":"calls","source":4595,"target":528},{"edgeType":"calls","source":2158,"target":2082},{"edgeType":"extends","source":7100,"target":36},{"edgeType":"calls","source":2991,"target":571},{"edgeType":"calls","source":3477,"target":304},{"edgeType":"contains","source":5195,"target":6389},{"edgeType":"calls","source":6659,"target":1008},{"edgeType":"calls","source":6550,"target":1216},{"edgeType":"contains","source":2688,"target":2715},{"edgeType":"calls","source":4673,"target":4451},{"edgeType":"calls","source":1938,"target":1500},{"edgeType":"contains","source":5,"target":3437},{"edgeType":"calls","source":347,"target":84},{"edgeType":"contains","source":837,"target":899},{"edgeType":"imports","source":4668,"target":128},{"edgeType":"contains","source":736,"target":859},{"edgeType":"calls","source":576,"target":384},{"edgeType":"calls","source":372,"target":366},{"edgeType":"calls","source":4595,"target":527},{"edgeType":"calls","source":2256,"target":2216},{"edgeType":"calls","source":4963,"target":4973},{"edgeType":"calls","source":5062,"target":5075},{"edgeType":"contains","source":5195,"target":6388},{"edgeType":"contains","source":6851,"target":6852},{"edgeType":"contains","source":2688,"target":2712},{"edgeType":"calls","source":5854,"target":5892},{"edgeType":"calls","source":6132,"target":445},{"edgeType":"calls","source":4017,"target":473},{"edgeType":"calls","source":4912,"target":212},{"edgeType":"contains","source":736,"target":862},{"edgeType":"calls","source":2111,"target":368},{"edgeType":"calls","source":6976,"target":1753},{"edgeType":"calls","source":372,"target":369},{"edgeType":"calls","source":4467,"target":4494},{"edgeType":"calls","source":107,"target":126},{"edgeType":"calls","source":3008,"target":1099},{"edgeType":"contains","source":6851,"target":6853},{"edgeType":"calls","source":1733,"target":458},{"edgeType":"contains","source":5195,"target":6387},{"edgeType":"calls","source":5670,"target":2082},{"edgeType":"contains","source":2688,"target":2713},{"edgeType":"calls","source":6207,"target":2347},{"edgeType":"calls","source":4017,"target":474},{"edgeType":"calls","source":2795,"target":303},{"edgeType":"calls","source":4939,"target":431},{"edgeType":"contains","source":736,"target":861},{"edgeType":"calls","source":6993,"target":170},{"edgeType":"calls","source":4880,"target":146},{"edgeType":"calls","source":372,"target":368},{"edgeType":"contains","source":736,"target":865},{"edgeType":"calls","source":4970,"target":4754},{"edgeType":"contains","source":1379,"target":2073},{"edgeType":"contains","source":5195,"target":6394},{"edgeType":"imports","source":4091,"target":49},{"edgeType":"calls","source":576,"target":381},{"edgeType":"calls","source":3348,"target":1126},{"edgeType":"contains","source":3408,"target":482},{"edgeType":"calls","source":4083,"target":3710},{"edgeType":"calls","source":6132,"target":443},{"edgeType":"calls","source":6207,"target":2346},{"edgeType":"calls","source":6265,"target":548},{"edgeType":"contains","source":7015,"target":7046},{"edgeType":"contains","source":2688,"target":2718},{"edgeType":"calls","source":735,"target":737},{"edgeType":"calls","source":6993,"target":171},{"edgeType":"contains","source":42,"target":1238},{"edgeType":"calls","source":4568,"target":304},{"edgeType":"contains","source":2872,"target":3358},{"edgeType":"calls","source":5139,"target":571},{"edgeType":"contains","source":736,"target":864},{"edgeType":"contains","source":2688,"target":2720},{"edgeType":"calls","source":3826,"target":2165},{"edgeType":"calls","source":1759,"target":1760},{"edgeType":"calls","source":576,"target":380},{"edgeType":"calls","source":594,"target":879},{"edgeType":"contains","source":1814,"target":2331},{"edgeType":"calls","source":1378,"target":886},{"edgeType":"contains","source":2688,"target":2719},{"edgeType":"calls","source":6207,"target":2345},{"edgeType":"contains","source":736,"target":863},{"edgeType":"calls","source":1124,"target":304},{"edgeType":"contains","source":1698,"target":1699},{"edgeType":"calls","source":1154,"target":431},{"edgeType":"calls","source":4568,"target":303},{"edgeType":"calls","source":4880,"target":144},{"edgeType":"calls","source":2684,"target":571},{"edgeType":"contains","source":736,"target":867},{"edgeType":"contains","source":5195,"target":6392},{"edgeType":"contains","source":5463,"target":5480},{"edgeType":"imports","source":885,"target":78},{"edgeType":"contains","source":1076,"target":897},{"edgeType":"calls","source":6207,"target":2344},{"edgeType":"contains","source":6091,"target":6096},{"edgeType":"extends","source":5756,"target":5758},{"edgeType":"contains","source":2688,"target":2716},{"edgeType":"calls","source":2111,"target":364},{"edgeType":"contains","source":6322,"target":6334},{"edgeType":"contains","source":885,"target":1532},{"edgeType":"contains","source":736,"target":866},{"edgeType":"imports","source":885,"target":79},{"edgeType":"contains","source":5195,"target":6391},{"edgeType":"calls","source":6207,"target":2343},{"edgeType":"contains","source":2688,"target":2717},{"edgeType":"calls","source":4198,"target":144},{"edgeType":"calls","source":372,"target":364},{"edgeType":"calls","source":576,"target":382},{"edgeType":"calls","source":7065,"target":56},{"edgeType":"calls","source":2984,"target":2992},{"edgeType":"contains","source":837,"target":876},{"edgeType":"contains","source":736,"target":836},{"edgeType":"calls","source":372,"target":457},{"edgeType":"calls","source":1795,"target":1797},{"edgeType":"calls","source":1861,"target":1865},{"edgeType":"imports","source":3819,"target":78},{"edgeType":"contains","source":3166,"target":3727},{"edgeType":"calls","source":6135,"target":445},{"edgeType":"imports","source":5217,"target":78},{"edgeType":"calls","source":372,"target":458},{"edgeType":"contains","source":6106,"target":3494},{"edgeType":"calls","source":883,"target":472},{"edgeType":"calls","source":4569,"target":368},{"edgeType":"calls","source":6617,"target":303},{"edgeType":"calls","source":6486,"target":6478},{"edgeType":"calls","source":2984,"target":2993},{"edgeType":"imports","source":4502,"target":3218},{"edgeType":"calls","source":2984,"target":879},{"edgeType":"calls","source":4569,"target":366},{"edgeType":"contains","source":736,"target":835},{"edgeType":"extends","source":4537,"target":4478},{"edgeType":"calls","source":5221,"target":4466},{"edgeType":"calls","source":1535,"target":1400},{"edgeType":"calls","source":3475,"target":457},{"edgeType":"contains","source":6610,"target":6898},{"edgeType":"imports","source":3819,"target":79},{"edgeType":"calls","source":1299,"target":1316},{"edgeType":"contains","source":6610,"target":6897},{"edgeType":"calls","source":6916,"target":548},{"edgeType":"contains","source":4432,"target":4648},{"edgeType":"calls","source":2786,"target":2789},{"edgeType":"imports","source":5217,"target":79},{"edgeType":"calls","source":4842,"target":4588},{"edgeType":"contains","source":41,"target":182},{"edgeType":"calls","source":4562,"target":584},{"edgeType":"calls","source":6486,"target":6479},{"edgeType":"calls","source":6617,"target":304},{"edgeType":"contains","source":5,"target":1301},{"edgeType":"contains","source":736,"target":838},{"edgeType":"contains","source":2752,"target":2818},{"edgeType":"calls","source":6135,"target":443},{"edgeType":"contains","source":837,"target":878},{"edgeType":"calls","source":3860,"target":146},{"edgeType":"contains","source":6610,"target":6899},{"edgeType":"calls","source":4086,"target":3710},{"edgeType":"calls","source":6934,"target":1048},{"edgeType":"contains","source":4432,"target":4647},{"edgeType":"calls","source":6486,"target":6480},{"edgeType":"calls","source":484,"target":159},{"edgeType":"calls","source":4739,"target":4609},{"edgeType":"calls","source":4569,"target":364},{"edgeType":"calls","source":4274,"target":3167},{"edgeType":"contains","source":2752,"target":2819},{"edgeType":"contains","source":6619,"target":6621},{"edgeType":"contains","source":6610,"target":6900},{"edgeType":"contains","source":837,"target":877},{"edgeType":"extends","source":4130,"target":180},{"edgeType":"calls","source":1748,"target":84},{"edgeType":"calls","source":2687,"target":571},{"edgeType":"calls","source":6486,"target":6481},{"edgeType":"calls","source":4933,"target":4936},{"edgeType":"imports","source":4502,"target":49},{"edgeType":"calls","source":6583,"target":303},{"edgeType":"contains","source":1908,"target":1500},{"edgeType":"calls","source":347,"target":171},{"edgeType":"calls","source":5131,"target":5139},{"edgeType":"calls","source":7033,"target":1152},{"edgeType":"calls","source":2498,"target":84},{"edgeType":"contains","source":2206,"target":2837},{"edgeType":"contains","source":6817,"target":6818},{"edgeType":"calls","source":4166,"target":171},{"edgeType":"contains","source":837,"target":880},{"edgeType":"contains","source":736,"target":840},{"edgeType":"calls","source":2837,"target":146},{"edgeType":"calls","source":1299,"target":1313},{"edgeType":"contains","source":5380,"target":1691},{"edgeType":"contains","source":5116,"target":4590},{"edgeType":"contains","source":1907,"target":2593},{"edgeType":"calls","source":4676,"target":4446},{"edgeType":"calls","source":6583,"target":304},{"edgeType":"contains","source":736,"target":839},{"edgeType":"calls","source":5792,"target":5788},{"edgeType":"calls","source":347,"target":170},{"edgeType":"calls","source":4415,"target":3022},{"edgeType":"contains","source":5726,"target":5757},{"edgeType":"imports","source":5895,"target":205},{"edgeType":"contains","source":2490,"target":2491},{"edgeType":"calls","source":6033,"target":431},{"edgeType":"contains","source":6651,"target":6679},{"edgeType":"contains","source":4432,"target":4652},{"edgeType":"contains","source":3014,"target":3159},{"edgeType":"calls","source":3607,"target":588},{"edgeType":"calls","source":5635,"target":84},{"edgeType":"calls","source":6486,"target":6483},{"edgeType":"calls","source":6385,"target":6443},{"edgeType":"imports","source":4528,"target":4530},{"edgeType":"calls","source":5012,"target":4599},{"edgeType":"calls","source":5792,"target":5787},{"edgeType":"contains","source":1415,"target":930},{"edgeType":"contains","source":439,"target":536},{"edgeType":"contains","source":736,"target":842},{"edgeType":"calls","source":1780,"target":146},{"edgeType":"calls","source":1299,"target":1315},{"edgeType":"extends","source":4544,"target":36},{"edgeType":"calls","source":3271,"target":431},{"edgeType":"imports","source":6604,"target":2540},{"edgeType":"contains","source":7015,"target":7025},{"edgeType":"calls","source":4449,"target":3023},{"edgeType":"contains","source":837,"target":881},{"edgeType":"calls","source":4347,"target":1957},{"edgeType":"calls","source":4166,"target":170},{"edgeType":"calls","source":1801,"target":551},{"edgeType":"contains","source":736,"target":841},{"edgeType":"calls","source":7068,"target":6412},{"edgeType":"calls","source":6378,"target":304},{"edgeType":"calls","source":1381,"target":886},{"edgeType":"calls","source":1299,"target":1314},{"edgeType":"calls","source":6486,"target":6485},{"edgeType":"contains","source":4432,"target":4650},{"edgeType":"contains","source":3166,"target":3730},{"edgeType":"contains","source":41,"target":6530},{"edgeType":"contains","source":154,"target":3027},{"edgeType":"calls","source":6792,"target":170},{"edgeType":"imports","source":1415,"target":602},{"edgeType":"calls","source":6486,"target":2257},{"edgeType":"contains","source":1498,"target":1530},{"edgeType":"calls","source":1224,"target":468},{"edgeType":"calls","source":4910,"target":4588},{"edgeType":"contains","source":6817,"target":6830},{"edgeType":"contains","source":439,"target":538},{"edgeType":"contains","source":4505,"target":4509},{"edgeType":"contains","source":736,"target":844},{"edgeType":"calls","source":177,"target":152},{"edgeType":"calls","source":6378,"target":303},{"edgeType":"contains","source":6450,"target":6580},{"edgeType":"calls","source":1517,"target":893},{"edgeType":"calls","source":1544,"target":56},{"edgeType":"contains","source":5,"target":5535},{"edgeType":"calls","source":4739,"target":4603},{"edgeType":"calls","source":6792,"target":171},{"edgeType":"calls","source":6486,"target":2258},{"edgeType":"calls","source":3024,"target":2801},{"edgeType":"calls","source":3120,"target":2996},{"edgeType":"contains","source":5,"target":1306},{"edgeType":"calls","source":4734,"target":528},{"edgeType":"contains","source":6817,"target":6831},{"edgeType":"contains","source":6610,"target":6906},{"edgeType":"contains","source":30,"target":3702},{"edgeType":"contains","source":736,"target":843},{"edgeType":"contains","source":6280,"target":6565},{"edgeType":"calls","source":3553,"target":144},{"edgeType":"contains","source":3166,"target":565},{"edgeType":"calls","source":6827,"target":144},{"edgeType":"calls","source":2984,"target":2985},{"edgeType":"calls","source":2566,"target":84},{"edgeType":"calls","source":4734,"target":527},{"edgeType":"contains","source":6817,"target":6832},{"edgeType":"contains","source":6610,"target":6907},{"edgeType":"contains","source":736,"target":846},{"edgeType":"contains","source":5,"target":1309},{"edgeType":"calls","source":4415,"target":3017},{"edgeType":"calls","source":6724,"target":6509},{"edgeType":"contains","source":4472,"target":4473},{"edgeType":"calls","source":6758,"target":170},{"edgeType":"contains","source":3014,"target":1046},{"edgeType":"calls","source":6453,"target":6454},{"edgeType":"contains","source":1498,"target":1533},{"edgeType":"contains","source":1907,"target":1538},{"edgeType":"calls","source":3120,"target":2994},{"edgeType":"calls","source":1161,"target":304},{"edgeType":"imports","source":5285,"target":78},{"edgeType":"extends","source":1714,"target":36},{"edgeType":"contains","source":6610,"target":6908},{"edgeType":"contains","source":736,"target":845},{"edgeType":"calls","source":7065,"target":6509},{"edgeType":"calls","source":6241,"target":319},{"edgeType":"calls","source":6934,"target":1057},{"edgeType":"contains","source":2599,"target":3342},{"edgeType":"calls","source":6881,"target":6928},{"edgeType":"contains","source":4505,"target":4506},{"edgeType":"contains","source":439,"target":539},{"edgeType":"calls","source":6758,"target":171},{"edgeType":"contains","source":5,"target":5536},{"edgeType":"calls","source":5055,"target":3260},{"edgeType":"contains","source":6450,"target":6583},{"edgeType":"imports","source":2898,"target":2207},{"edgeType":"calls","source":5131,"target":5132},{"edgeType":"contains","source":6817,"target":6833},{"edgeType":"calls","source":1002,"target":1004},{"edgeType":"calls","source":5326,"target":144},{"edgeType":"calls","source":1161,"target":303},{"edgeType":"imports","source":5285,"target":79},{"edgeType":"contains","source":7015,"target":7037},{"edgeType":"contains","source":1498,"target":1534},{"edgeType":"extends","source":5124,"target":36},{"edgeType":"calls","source":5419,"target":431},{"edgeType":"contains","source":6817,"target":6826},{"edgeType":"calls","source":6241,"target":318},{"edgeType":"calls","source":3919,"target":421},{"edgeType":"contains","source":2688,"target":588},{"edgeType":"contains","source":7015,"target":7030},{"edgeType":"contains","source":2030,"target":1959},{"edgeType":"contains","source":42,"target":2278},{"edgeType":"contains","source":5,"target":5539},{"edgeType":"contains","source":736,"target":848},{"edgeType":"contains","source":5195,"target":6377},{"edgeType":"calls","source":1295,"target":371},{"edgeType":"calls","source":1132,"target":1196},{"edgeType":"calls","source":3919,"target":422},{"edgeType":"imports","source":5592,"target":78},{"edgeType":"contains","source":736,"target":847},{"edgeType":"calls","source":6827,"target":148},{"edgeType":"contains","source":4505,"target":4512},{"edgeType":"contains","source":5,"target":2367},{"edgeType":"calls","source":6374,"target":422},{"edgeType":"contains","source":5,"target":5538},{"edgeType":"calls","source":2963,"target":1518},{"edgeType":"calls","source":1882,"target":147},{"edgeType":"contains","source":6817,"target":6828},{"edgeType":"contains","source":1202,"target":1203},{"edgeType":"calls","source":1224,"target":461},{"edgeType":"calls","source":6374,"target":421},{"edgeType":"imports","source":5592,"target":79},{"edgeType":"calls","source":2676,"target":898},{"edgeType":"contains","source":736,"target":850},{"edgeType":"calls","source":2090,"target":2152},{"edgeType":"contains","source":1028,"target":1311},{"edgeType":"contains","source":5463,"target":5464},{"edgeType":"calls","source":1782,"target":1132},{"edgeType":"contains","source":6817,"target":6829},{"edgeType":"contains","source":6610,"target":6904},{"edgeType":"calls","source":6445,"target":333},{"edgeType":"contains","source":2030,"target":1958},{"edgeType":"contains","source":41,"target":6539},{"edgeType":"contains","source":154,"target":3036},{"edgeType":"calls","source":4569,"target":4580},{"edgeType":"calls","source":145,"target":84},{"edgeType":"calls","source":143,"target":146},{"edgeType":"calls","source":5861,"target":467},{"edgeType":"contains","source":736,"target":849},{"edgeType":"contains","source":7015,"target":7033},{"edgeType":"contains","source":1302,"target":6557},{"edgeType":"calls","source":5859,"target":5814},{"edgeType":"contains","source":3166,"target":3738},{"edgeType":"calls","source":1508,"target":1169},{"edgeType":"calls","source":580,"target":368},{"edgeType":"imports","source":6373,"target":166},{"edgeType":"contains","source":5410,"target":6026},{"edgeType":"calls","source":4938,"target":572},{"edgeType":"calls","source":7028,"target":1286},{"edgeType":"calls","source":6541,"target":528},{"edgeType":"contains","source":736,"target":819},{"edgeType":"calls","source":5131,"target":5160},{"edgeType":"calls","source":6953,"target":6783},{"edgeType":"calls","source":3155,"target":879},{"edgeType":"contains","source":2686,"target":2735},{"edgeType":"contains","source":3014,"target":3137},{"edgeType":"calls","source":6688,"target":6542},{"edgeType":"calls","source":3343,"target":337},{"edgeType":"calls","source":3342,"target":368},{"edgeType":"calls","source":5432,"target":56},{"edgeType":"calls","source":4222,"target":571},{"edgeType":"imports","source":1415,"target":1648},{"edgeType":"contains","source":5726,"target":5745},{"edgeType":"calls","source":7028,"target":1287},{"edgeType":"imports","source":4706,"target":49},{"edgeType":"calls","source":2886,"target":2877},{"edgeType":"contains","source":736,"target":818},{"edgeType":"contains","source":6280,"target":6541},{"edgeType":"calls","source":6882,"target":1586},{"edgeType":"calls","source":1132,"target":171},{"edgeType":"calls","source":7028,"target":1288},{"edgeType":"calls","source":6711,"target":1602},{"edgeType":"calls","source":580,"target":370},{"edgeType":"calls","source":1604,"target":337},{"edgeType":"extends","source":4782,"target":36},{"edgeType":"contains","source":736,"target":821},{"edgeType":"extends","source":2702,"target":36},{"edgeType":"contains","source":3166,"target":537},{"edgeType":"calls","source":3710,"target":584},{"edgeType":"calls","source":580,"target":369},{"edgeType":"calls","source":3342,"target":366},{"edgeType":"calls","source":1132,"target":170},{"edgeType":"calls","source":7028,"target":1289},{"edgeType":"calls","source":2861,"target":2592},{"edgeType":"contains","source":3793,"target":4355},{"edgeType":"calls","source":2801,"target":224},{"edgeType":"contains","source":42,"target":2251},{"edgeType":"contains","source":736,"target":820},{"edgeType":"contains","source":4339,"target":4342},{"edgeType":"imports","source":3981,"target":328},{"edgeType":"calls","source":1800,"target":1659},{"edgeType":"imports","source":4000,"target":1853},{"edgeType":"calls","source":6206,"target":371},{"edgeType":"contains","source":6432,"target":7116},{"edgeType":"calls","source":580,"target":364},{"edgeType":"contains","source":6610,"target":6876},{"edgeType":"contains","source":6651,"target":6662},{"edgeType":"calls","source":5117,"target":304},{"edgeType":"calls","source":6567,"target":2897},{"edgeType":"imports","source":1379,"target":1704},{"edgeType":"calls","source":930,"target":84},{"edgeType":"calls","source":922,"target":332},{"edgeType":"calls","source":4877,"target":4573},{"edgeType":"contains","source":736,"target":823},{"edgeType":"contains","source":12,"target":13},{"edgeType":"calls","source":3742,"target":1704},{"edgeType":"contains","source":5758,"target":5805},{"edgeType":"calls","source":3618,"target":3434},{"edgeType":"calls","source":6206,"target":370},{"edgeType":"contains","source":4471,"target":4484},{"edgeType":"calls","source":1517,"target":913},{"edgeType":"calls","source":3342,"target":364},{"edgeType":"calls","source":5117,"target":303},{"edgeType":"calls","source":5060,"target":4184},{"edgeType":"calls","source":5075,"target":548},{"edgeType":"contains","source":2752,"target":2808},{"edgeType":"contains","source":2060,"target":2063},{"edgeType":"contains","source":736,"target":822},{"edgeType":"contains","source":4075,"target":4076},{"edgeType":"calls","source":6206,"target":369},{"edgeType":"calls","source":6115,"target":4247},{"edgeType":"calls","source":2084,"target":248},{"edgeType":"calls","source":4848,"target":4413},{"edgeType":"calls","source":580,"target":366},{"edgeType":"calls","source":6724,"target":146},{"edgeType":"calls","source":5559,"target":342},{"edgeType":"imports","source":1379,"target":1702},{"edgeType":"calls","source":2984,"target":888},{"edgeType":"contains","source":5726,"target":5742},{"edgeType":"calls","source":5163,"target":2047},{"edgeType":"contains","source":1415,"target":1971},{"edgeType":"calls","source":3871,"target":2988},{"edgeType":"calls","source":7065,"target":146},{"edgeType":"contains","source":1379,"target":2030},{"edgeType":"calls","source":1882,"target":171},{"edgeType":"calls","source":6206,"target":368},{"edgeType":"contains","source":2981,"target":3105},{"edgeType":"calls","source":3753,"target":304},{"edgeType":"contains","source":736,"target":825},{"edgeType":"contains","source":5195,"target":6350},{"edgeType":"imports","source":4307,"target":1853},{"edgeType":"contains","source":5758,"target":5808},{"edgeType":"calls","source":922,"target":333},{"edgeType":"calls","source":4911,"target":4573},{"edgeType":"imports","source":1379,"target":1701},{"edgeType":"calls","source":883,"target":485},{"edgeType":"calls","source":5163,"target":2046},{"edgeType":"contains","source":2060,"target":2061},{"edgeType":"extends","source":4748,"target":36},{"edgeType":"calls","source":372,"target":471},{"edgeType":"calls","source":4536,"target":4571},{"edgeType":"calls","source":1882,"target":170},{"edgeType":"calls","source":7031,"target":144},{"edgeType":"contains","source":736,"target":824},{"edgeType":"contains","source":1698,"target":603},{"edgeType":"contains","source":6432,"target":7121},{"edgeType":"calls","source":3513,"target":3514},{"edgeType":"calls","source":5454,"target":4652},{"edgeType":"calls","source":3618,"target":3430},{"edgeType":"calls","source":3417,"target":148},{"edgeType":"calls","source":4810,"target":304},{"edgeType":"calls","source":4949,"target":4451},{"edgeType":"calls","source":1132,"target":1218},{"edgeType":"extends","source":6619,"target":180},{"edgeType":"imports","source":4091,"target":78},{"edgeType":"contains","source":2752,"target":2811},{"edgeType":"extends","source":1202,"target":36},{"edgeType":"calls","source":2086,"target":183},{"edgeType":"contains","source":736,"target":827},{"edgeType":"calls","source":6206,"target":366},{"edgeType":"contains","source":6432,"target":7122},{"edgeType":"calls","source":1531,"target":1532},{"edgeType":"contains","source":2915,"target":3045},{"edgeType":"imports","source":2050,"target":2055},{"edgeType":"contains","source":937,"target":938},{"edgeType":"calls","source":5867,"target":304},{"edgeType":"imports","source":2898,"target":79},{"edgeType":"calls","source":5875,"target":56},{"edgeType":"calls","source":1581,"target":1039},{"edgeType":"calls","source":1578,"target":1132},{"edgeType":"calls","source":3450,"target":183},{"edgeType":"contains","source":7015,"target":7019},{"edgeType":"calls","source":7068,"target":56},{"edgeType":"imports","source":4091,"target":79},{"edgeType":"contains","source":2752,"target":2812},{"edgeType":"calls","source":4810,"target":303},{"edgeType":"calls","source":3753,"target":303},{"edgeType":"contains","source":6610,"target":6889},{"edgeType":"calls","source":4442,"target":84},{"edgeType":"calls","source":6863,"target":1126},{"edgeType":"contains","source":736,"target":826},{"edgeType":"contains","source":6432,"target":7123},{"edgeType":"imports","source":2898,"target":78},{"edgeType":"calls","source":6688,"target":209},{"edgeType":"calls","source":5867,"target":303},{"edgeType":"calls","source":3105,"target":304},{"edgeType":"extends","source":2916,"target":2924},{"edgeType":"calls","source":6863,"target":6412},{"edgeType":"contains","source":2060,"target":2064},{"edgeType":"contains","source":3976,"target":3977},{"edgeType":"contains","source":736,"target":829},{"edgeType":"calls","source":6915,"target":572},{"edgeType":"calls","source":6055,"target":6102},{"edgeType":"calls","source":6206,"target":364},{"edgeType":"calls","source":6688,"target":210},{"edgeType":"imports","source":1379,"target":1713},{"edgeType":"contains","source":6432,"target":7124},{"edgeType":"contains","source":3166,"target":547},{"edgeType":"imports","source":5285,"target":2177},{"edgeType":"imports","source":2843,"target":2839},{"edgeType":"extends","source":736,"target":742},{"edgeType":"contains","source":2752,"target":2810},{"edgeType":"contains","source":12,"target":18},{"edgeType":"calls","source":4817,"target":84},{"edgeType":"contains","source":2060,"target":2065},{"edgeType":"contains","source":6610,"target":6891},{"edgeType":"contains","source":736,"target":828},{"edgeType":"calls","source":6915,"target":573},{"edgeType":"calls","source":4144,"target":4035},{"edgeType":"calls","source":7031,"target":148},{"edgeType":"contains","source":736,"target":832},{"edgeType":"imports","source":5285,"target":2178},{"edgeType":"contains","source":1297,"target":1411},{"edgeType":"imports","source":5166,"target":582},{"edgeType":"calls","source":7002,"target":1048},{"edgeType":"calls","source":5462,"target":171},{"edgeType":"contains","source":5410,"target":6038},{"edgeType":"imports","source":4668,"target":1221},{"edgeType":"contains","source":736,"target":831},{"edgeType":"calls","source":6782,"target":469},{"edgeType":"imports","source":3981,"target":321},{"edgeType":"contains","source":6432,"target":7117},{"edgeType":"calls","source":484,"target":161},{"edgeType":"calls","source":5859,"target":548},{"edgeType":"calls","source":3105,"target":303},{"edgeType":"contains","source":3166,"target":3724},{"edgeType":"calls","source":5462,"target":170},{"edgeType":"calls","source":4569,"target":371},{"edgeType":"contains","source":736,"target":830},{"edgeType":"contains","source":6651,"target":6671},{"edgeType":"contains","source":12,"target":20},{"edgeType":"calls","source":2735,"target":146},{"edgeType":"calls","source":484,"target":160},{"edgeType":"imports","source":1415,"target":1651},{"edgeType":"contains","source":2981,"target":3114},{"edgeType":"contains","source":736,"target":834},{"edgeType":"calls","source":2984,"target":2994},{"edgeType":"contains","source":3867,"target":1017},{"edgeType":"calls","source":998,"target":84},{"edgeType":"contains","source":7015,"target":7016},{"edgeType":"calls","source":3475,"target":458},{"edgeType":"calls","source":3779,"target":547},{"edgeType":"calls","source":5518,"target":548},{"edgeType":"extends","source":4505,"target":180},{"edgeType":"calls","source":4808,"target":4588},{"edgeType":"contains","source":6610,"target":6886},{"edgeType":"calls","source":540,"target":541},{"edgeType":"calls","source":4569,"target":370},{"edgeType":"contains","source":6432,"target":7120},{"edgeType":"imports","source":1415,"target":1650},{"edgeType":"contains","source":2981,"target":3115},{"edgeType":"calls","source":4950,"target":4413},{"edgeType":"contains","source":736,"target":833},{"edgeType":"calls","source":3510,"target":431},{"edgeType":"extends","source":439,"target":440},{"edgeType":"calls","source":6750,"target":6749},{"edgeType":"calls","source":4676,"target":4451},{"edgeType":"calls","source":1937,"target":571},{"edgeType":"contains","source":2060,"target":2069},{"edgeType":"calls","source":6486,"target":6477},{"edgeType":"calls","source":4569,"target":369},{"edgeType":"calls","source":5729,"target":5599},{"edgeType":"calls","source":5092,"target":2091},{"edgeType":"calls","source":6423,"target":5226},{"edgeType":"contains","source":5460,"target":5517},{"edgeType":"calls","source":2175,"target":555},{"edgeType":"calls","source":1508,"target":1148},{"edgeType":"calls","source":6994,"target":210},{"edgeType":"contains","source":5758,"target":5793},{"edgeType":"calls","source":4970,"target":588},{"edgeType":"imports","source":4502,"target":79},{"edgeType":"calls","source":6992,"target":3443},{"edgeType":"calls","source":6863,"target":6385},{"edgeType":"calls","source":4568,"target":366},{"edgeType":"calls","source":4568,"target":364},{"edgeType":"contains","source":3509,"target":3631},{"edgeType":"calls","source":1508,"target":1147},{"edgeType":"calls","source":6964,"target":84},{"edgeType":"contains","source":5380,"target":5881},{"edgeType":"calls","source":1380,"target":886},{"edgeType":"contains","source":4668,"target":1527},{"edgeType":"extends","source":5261,"target":36},{"edgeType":"calls","source":6747,"target":469},{"edgeType":"contains","source":5726,"target":5729},{"edgeType":"calls","source":2837,"target":1175},{"edgeType":"calls","source":1097,"target":146},{"edgeType":"contains","source":5756,"target":5856},{"edgeType":"contains","source":5460,"target":5519},{"edgeType":"imports","source":5195,"target":1853},{"edgeType":"contains","source":606,"target":607},{"edgeType":"contains","source":6651,"target":6652},{"edgeType":"contains","source":1814,"target":2266},{"edgeType":"calls","source":5652,"target":584},{"edgeType":"calls","source":4109,"target":4021},{"edgeType":"contains","source":4502,"target":4558},{"edgeType":"calls","source":3518,"target":144},{"edgeType":"extends","source":6250,"target":36},{"edgeType":"calls","source":6884,"target":6793},{"edgeType":"calls","source":350,"target":1109},{"edgeType":"calls","source":7058,"target":342},{"edgeType":"contains","source":5,"target":1268},{"edgeType":"calls","source":6485,"target":6478},{"edgeType":"contains","source":5758,"target":5795},{"edgeType":"contains","source":5756,"target":5857},{"edgeType":"calls","source":2931,"target":372},{"edgeType":"calls","source":5198,"target":5144},{"edgeType":"extends","source":4579,"target":36},{"edgeType":"calls","source":1761,"target":1762},{"edgeType":"contains","source":5285,"target":5653},{"edgeType":"calls","source":6587,"target":146},{"edgeType":"contains","source":5679,"target":4017},{"edgeType":"contains","source":736,"target":807},{"edgeType":"calls","source":5350,"target":431},{"edgeType":"calls","source":510,"target":370},{"edgeType":"calls","source":2090,"target":1071},{"edgeType":"calls","source":2705,"target":2091},{"edgeType":"calls","source":2837,"target":1170},{"edgeType":"calls","source":2870,"target":147},{"edgeType":"calls","source":6816,"target":447},{"edgeType":"calls","source":902,"target":903},{"edgeType":"calls","source":4568,"target":4590},{"edgeType":"calls","source":3409,"target":350},{"edgeType":"calls","source":4676,"target":4413},{"edgeType":"contains","source":41,"target":153},{"edgeType":"contains","source":736,"target":806},{"edgeType":"contains","source":5758,"target":5789},{"edgeType":"contains","source":5756,"target":5851},{"edgeType":"calls","source":4646,"target":1113},{"edgeType":"calls","source":4592,"target":2787},{"edgeType":"contains","source":5460,"target":5514},{"edgeType":"calls","source":510,"target":369},{"edgeType":"calls","source":2159,"target":2105},{"edgeType":"calls","source":6385,"target":56},{"edgeType":"calls","source":6816,"target":448},{"edgeType":"calls","source":6277,"target":2347},{"edgeType":"calls","source":2705,"target":2092},{"edgeType":"calls","source":4881,"target":171},{"edgeType":"contains","source":6616,"target":6674},{"edgeType":"contains","source":1498,"target":1499},{"edgeType":"contains","source":5758,"target":5790},{"edgeType":"contains","source":5756,"target":5852},{"edgeType":"imports","source":5116,"target":78},{"edgeType":"calls","source":4646,"target":1112},{"edgeType":"calls","source":4739,"target":1400},{"edgeType":"contains","source":1415,"target":1954},{"edgeType":"calls","source":1508,"target":1146},{"edgeType":"calls","source":6277,"target":2346},{"edgeType":"contains","source":736,"target":809},{"edgeType":"calls","source":4040,"target":4042},{"edgeType":"calls","source":3586,"target":146},{"edgeType":"calls","source":2899,"target":303},{"edgeType":"calls","source":3430,"target":2868},{"edgeType":"calls","source":4881,"target":170},{"edgeType":"calls","source":6881,"target":548},{"edgeType":"calls","source":2983,"target":2984},{"edgeType":"contains","source":5756,"target":5853},{"edgeType":"calls","source":902,"target":905},{"edgeType":"extends","source":2752,"target":2768},{"edgeType":"imports","source":5116,"target":79},{"edgeType":"calls","source":4442,"target":4264},{"edgeType":"contains","source":5460,"target":5516},{"edgeType":"calls","source":510,"target":371},{"edgeType":"imports","source":2494,"target":1011},{"edgeType":"calls","source":2159,"target":2103},{"edgeType":"calls","source":6277,"target":2345},{"edgeType":"contains","source":736,"target":808},{"edgeType":"calls","source":2899,"target":304},{"edgeType":"calls","source":6385,"target":6412},{"edgeType":"calls","source":902,"target":904},{"edgeType":"extends","source":4886,"target":36},{"edgeType":"calls","source":485,"target":84},{"edgeType":"calls","source":483,"target":146},{"edgeType":"contains","source":1989,"target":2136},{"edgeType":"contains","source":6280,"target":6531},{"edgeType":"contains","source":2872,"target":3303},{"edgeType":"contains","source":736,"target":811},{"edgeType":"calls","source":510,"target":366},{"edgeType":"calls","source":6277,"target":2344},{"edgeType":"calls","source":4900,"target":4864},{"edgeType":"contains","source":12,"target":6342},{"edgeType":"calls","source":2959,"target":555},{"edgeType":"calls","source":6716,"target":380},{"edgeType":"calls","source":6533,"target":2882},{"edgeType":"extends","source":4503,"target":4517},{"edgeType":"imports","source":4091,"target":128},{"edgeType":"imports","source":4091,"target":1185},{"edgeType":"calls","source":4740,"target":309},{"edgeType":"calls","source":1784,"target":1039},{"edgeType":"calls","source":1781,"target":1132},{"edgeType":"calls","source":2095,"target":911},{"edgeType":"contains","source":437,"target":566},{"edgeType":"calls","source":6889,"target":303},{"edgeType":"contains","source":736,"target":810},{"edgeType":"calls","source":6277,"target":2343},{"edgeType":"contains","source":4537,"target":4540},{"edgeType":"contains","source":6280,"target":6532},{"edgeType":"calls","source":144,"target":84},{"edgeType":"calls","source":6716,"target":381},{"edgeType":"contains","source":5758,"target":5802},{"edgeType":"calls","source":6513,"target":332},{"edgeType":"calls","source":6277,"target":2342},{"edgeType":"contains","source":736,"target":813},{"edgeType":"calls","source":2822,"target":571},{"edgeType":"calls","source":510,"target":368},{"edgeType":"calls","source":6889,"target":304},{"edgeType":"calls","source":145,"target":56},{"edgeType":"contains","source":6280,"target":6533},{"edgeType":"contains","source":437,"target":569},{"edgeType":"contains","source":4537,"target":4539},{"edgeType":"calls","source":6710,"target":568},{"edgeType":"calls","source":6716,"target":382},{"edgeType":"contains","source":1028,"target":1274},{"edgeType":"contains","source":996,"target":1209},{"edgeType":"contains","source":5758,"target":5803},{"edgeType":"calls","source":6513,"target":333},{"edgeType":"calls","source":1168,"target":1111},{"edgeType":"calls","source":5163,"target":5165},{"edgeType":"contains","source":2752,"target":2794},{"edgeType":"calls","source":2561,"target":2321},{"edgeType":"contains","source":6610,"target":6875},{"edgeType":"contains","source":2872,"target":3302},{"edgeType":"calls","source":6277,"target":2341},{"edgeType":"contains","source":736,"target":812},{"edgeType":"contains","source":4537,"target":4538},{"edgeType":"contains","source":6280,"target":6534},{"edgeType":"calls","source":6679,"target":1530},{"edgeType":"contains","source":5758,"target":5804},{"edgeType":"calls","source":6452,"target":6453},{"edgeType":"contains","source":5726,"target":5739},{"edgeType":"calls","source":1675,"target":1248},{"edgeType":"calls","source":5163,"target":5164},{"edgeType":"contains","source":1814,"target":2275},{"edgeType":"contains","source":5460,"target":5521},{"edgeType":"calls","source":3187,"target":2996},{"edgeType":"contains","source":2686,"target":2731},{"edgeType":"calls","source":6104,"target":304},{"edgeType":"contains","source":736,"target":815},{"edgeType":"calls","source":2554,"target":421},{"edgeType":"calls","source":6882,"target":1580},{"edgeType":"calls","source":6716,"target":384},{"edgeType":"contains","source":4339,"target":4341},{"edgeType":"calls","source":4338,"target":84},{"edgeType":"calls","source":142,"target":143},{"edgeType":"calls","source":4900,"target":4860},{"edgeType":"contains","source":3166,"target":535},{"edgeType":"contains","source":1415,"target":1965},{"edgeType":"contains","source":5363,"target":5364},{"edgeType":"calls","source":4752,"target":2047},{"edgeType":"contains","source":5460,"target":5522},{"edgeType":"calls","source":6104,"target":303},{"edgeType":"calls","source":1096,"target":165},{"edgeType":"contains","source":736,"target":814},{"edgeType":"calls","source":6863,"target":56},{"edgeType":"contains","source":6450,"target":6543},{"edgeType":"calls","source":2554,"target":422},{"edgeType":"contains","source":4339,"target":4340},{"edgeType":"contains","source":5758,"target":5798},{"edgeType":"contains","source":2750,"target":2862},{"edgeType":"contains","source":5758,"target":513},{"edgeType":"calls","source":4752,"target":2046},{"edgeType":"contains","source":5460,"target":5523},{"edgeType":"calls","source":3342,"target":303},{"edgeType":"calls","source":1959,"target":898},{"edgeType":"calls","source":2095,"target":910},{"edgeType":"imports","source":1907,"target":190},{"edgeType":"calls","source":7028,"target":1284},{"edgeType":"contains","source":6585,"target":6588},{"edgeType":"contains","source":12,"target":6349},{"edgeType":"calls","source":472,"target":485},{"edgeType":"calls","source":510,"target":364},{"edgeType":"contains","source":5758,"target":5799},{"edgeType":"contains","source":3166,"target":533},{"edgeType":"contains","source":736,"target":817},{"edgeType":"contains","source":4988,"target":1132},{"edgeType":"calls","source":3372,"target":431},{"edgeType":"calls","source":3342,"target":304},{"edgeType":"contains","source":42,"target":2246},{"edgeType":"calls","source":7028,"target":1285},{"edgeType":"calls","source":6679,"target":1534},{"edgeType":"calls","source":4649,"target":4181},{"edgeType":"calls","source":6781,"target":1543},{"edgeType":"contains","source":6450,"target":6546},{"edgeType":"calls","source":6541,"target":527},{"edgeType":"calls","source":917,"target":431},{"edgeType":"contains","source":736,"target":816},{"edgeType":"imports","source":4502,"target":78},{"edgeType":"contains","source":5285,"target":5640},{"edgeType":"contains","source":3836,"target":5106},{"edgeType":"calls","source":6206,"target":342},{"edgeType":"calls","source":1295,"target":368},{"edgeType":"calls","source":1124,"target":384},{"edgeType":"calls","source":6791,"target":144},{"edgeType":"calls","source":6445,"target":332},{"edgeType":"contains","source":5756,"target":5838},{"edgeType":"contains","source":5,"target":6535},{"edgeType":"contains","source":5720,"target":1669},{"edgeType":"contains","source":5,"target":4421},{"edgeType":"contains","source":2916,"target":2971},{"edgeType":"extends","source":3351,"target":36},{"edgeType":"calls","source":5735,"target":144},{"edgeType":"contains","source":3043,"target":1148},{"edgeType":"calls","source":5861,"target":466},{"edgeType":"calls","source":1299,"target":1300},{"edgeType":"calls","source":6241,"target":313},{"edgeType":"contains","source":437,"target":541},{"edgeType":"contains","source":5362,"target":5366},{"edgeType":"contains","source":2688,"target":527},{"edgeType":"contains","source":4432,"target":4599},{"edgeType":"contains","source":5756,"target":5839},{"edgeType":"calls","source":6879,"target":588},{"edgeType":"contains","source":5,"target":4419},{"edgeType":"calls","source":6820,"target":303},{"edgeType":"calls","source":2732,"target":1275},{"edgeType":"calls","source":1003,"target":963},{"edgeType":"contains","source":1302,"target":3326},{"edgeType":"calls","source":5222,"target":5476},{"edgeType":"calls","source":142,"target":171},{"edgeType":"contains","source":2916,"target":2972},{"edgeType":"calls","source":5861,"target":465},{"edgeType":"calls","source":1295,"target":370},{"edgeType":"calls","source":6241,"target":312},{"edgeType":"calls","source":6881,"target":527},{"edgeType":"calls","source":6995,"target":164},{"edgeType":"calls","source":3348,"target":146},{"edgeType":"contains","source":162,"target":3784},{"edgeType":"contains","source":4432,"target":4598},{"edgeType":"calls","source":7063,"target":170},{"edgeType":"contains","source":5,"target":6537},{"edgeType":"calls","source":6820,"target":304},{"edgeType":"contains","source":5756,"target":5840},{"edgeType":"contains","source":3043,"target":1146},{"edgeType":"extends","source":5356,"target":2359},{"edgeType":"contains","source":2916,"target":2969},{"edgeType":"calls","source":5222,"target":5475},{"edgeType":"contains","source":602,"target":714},{"edgeType":"calls","source":5861,"target":464},{"edgeType":"contains","source":1229,"target":1358},{"edgeType":"calls","source":1676,"target":1243},{"edgeType":"calls","source":1295,"target":369},{"edgeType":"calls","source":4076,"target":2948},{"edgeType":"calls","source":6241,"target":311},{"edgeType":"calls","source":6881,"target":528},{"edgeType":"calls","source":6995,"target":165},{"edgeType":"calls","source":7063,"target":171},{"edgeType":"contains","source":162,"target":3783},{"edgeType":"calls","source":5059,"target":4184},{"edgeType":"contains","source":5,"target":6536},{"edgeType":"calls","source":4914,"target":4451},{"edgeType":"contains","source":5758,"target":5779},{"edgeType":"contains","source":5756,"target":5841},{"edgeType":"contains","source":2916,"target":2970},{"edgeType":"calls","source":4542,"target":1185},{"edgeType":"calls","source":5222,"target":5474},{"edgeType":"calls","source":6992,"target":6601},{"edgeType":"imports","source":2315,"target":2319},{"edgeType":"contains","source":3043,"target":1147},{"edgeType":"calls","source":5861,"target":463},{"edgeType":"contains","source":1229,"target":1359},{"edgeType":"contains","source":6683,"target":6701},{"edgeType":"calls","source":5635,"target":1126},{"edgeType":"contains","source":1031,"target":1159},{"edgeType":"contains","source":437,"target":546},{"edgeType":"calls","source":4733,"target":548},{"edgeType":"contains","source":6518,"target":6524},{"edgeType":"calls","source":6688,"target":170},{"edgeType":"contains","source":5380,"target":5870},{"edgeType":"calls","source":1295,"target":364},{"edgeType":"calls","source":1292,"target":457},{"edgeType":"contains","source":5895,"target":6810},{"edgeType":"calls","source":1124,"target":380},{"edgeType":"calls","source":1733,"target":527},{"edgeType":"calls","source":3743,"target":3754},{"edgeType":"contains","source":5758,"target":5772},{"edgeType":"contains","source":5756,"target":5834},{"edgeType":"calls","source":5861,"target":462},{"edgeType":"contains","source":3116,"target":3119},{"edgeType":"calls","source":4739,"target":4589},{"edgeType":"contains","source":6616,"target":6658},{"edgeType":"calls","source":6688,"target":171},{"edgeType":"contains","source":6518,"target":6525},{"edgeType":"contains","source":4002,"target":4191},{"edgeType":"contains","source":5,"target":6538},{"edgeType":"calls","source":961,"target":146},{"edgeType":"calls","source":998,"target":56},{"edgeType":"calls","source":4910,"target":4573},{"edgeType":"contains","source":5,"target":4424},{"edgeType":"imports","source":1907,"target":167},{"edgeType":"contains","source":5756,"target":5835},{"edgeType":"contains","source":5593,"target":5603},{"edgeType":"calls","source":6833,"target":962},{"edgeType":"calls","source":6583,"target":6598},{"edgeType":"contains","source":439,"target":486},{"edgeType":"calls","source":1295,"target":366},{"edgeType":"contains","source":5285,"target":5642},{"edgeType":"calls","source":1124,"target":382},{"edgeType":"calls","source":6723,"target":144},{"edgeType":"contains","source":5758,"target":5774},{"edgeType":"contains","source":5756,"target":5836},{"edgeType":"calls","source":4470,"target":4471},{"edgeType":"calls","source":1003,"target":962},{"edgeType":"calls","source":1739,"target":1400},{"edgeType":"extends","source":1190,"target":439},{"edgeType":"contains","source":1229,"target":1362},{"edgeType":"contains","source":2688,"target":528},{"edgeType":"calls","source":142,"target":170},{"edgeType":"calls","source":6241,"target":307},{"edgeType":"contains","source":3116,"target":3117},{"edgeType":"calls","source":1292,"target":458},{"edgeType":"contains","source":5285,"target":5641},{"edgeType":"calls","source":6833,"target":963},{"edgeType":"contains","source":5362,"target":5368},{"edgeType":"contains","source":5756,"target":5837},{"edgeType":"calls","source":1124,"target":381},{"edgeType":"calls","source":1733,"target":528},{"edgeType":"calls","source":3811,"target":588},{"edgeType":"calls","source":6995,"target":170},{"edgeType":"calls","source":5861,"target":2573},{"edgeType":"contains","source":3047,"target":3147},{"edgeType":"calls","source":3512,"target":3512},{"edgeType":"contains","source":5758,"target":5784},{"edgeType":"contains","source":5756,"target":5846},{"edgeType":"contains","source":936,"target":937},{"edgeType":"contains","source":2916,"target":2980},{"edgeType":"calls","source":5639,"target":5226},{"edgeType":"calls","source":5533,"target":56},{"edgeType":"calls","source":1172,"target":1002},{"edgeType":"contains","source":437,"target":550},{"edgeType":"calls","source":6995,"target":171},{"edgeType":"contains","source":5756,"target":5847},{"edgeType":"contains","source":1031,"target":1162},{"edgeType":"contains","source":3047,"target":3148},{"edgeType":"calls","source":5077,"target":449},{"edgeType":"calls","source":4982,"target":4451},{"edgeType":"imports","source":2581,"target":2540},{"edgeType":"calls","source":4734,"target":4740},{"edgeType":"contains","source":1302,"target":4391},{"edgeType":"calls","source":1269,"target":1165},{"edgeType":"calls","source":5365,"target":2092},{"edgeType":"contains","source":6683,"target":6707},{"edgeType":"contains","source":3975,"target":3976},{"edgeType":"calls","source":6241,"target":304},{"edgeType":"contains","source":437,"target":549},{"edgeType":"contains","source":439,"target":487},{"edgeType":"imports","source":5116,"target":49},{"edgeType":"contains","source":4432,"target":4606},{"edgeType":"extends","source":2686,"target":2688},{"edgeType":"contains","source":200,"target":500},{"edgeType":"extends","source":453,"target":36},{"edgeType":"calls","source":883,"target":449},{"edgeType":"contains","source":5460,"target":5511},{"edgeType":"calls","source":5365,"target":2091},{"edgeType":"calls","source":6241,"target":303},{"edgeType":"calls","source":7013,"target":7014},{"edgeType":"calls","source":6682,"target":4591},{"edgeType":"contains","source":5756,"target":5849},{"edgeType":"calls","source":1577,"target":1132},{"edgeType":"calls","source":5256,"target":183},{"edgeType":"calls","source":5461,"target":171},{"edgeType":"calls","source":5461,"target":170},{"edgeType":"contains","source":1415,"target":886},{"edgeType":"calls","source":2566,"target":1126},{"edgeType":"contains","source":6616,"target":6672},{"edgeType":"imports","source":4502,"target":3228},{"edgeType":"calls","source":4568,"target":371},{"edgeType":"extends","source":3624,"target":36},{"edgeType":"extends","source":4503,"target":4505},{"edgeType":"contains","source":5756,"target":5842},{"edgeType":"calls","source":4705,"target":351},{"edgeType":"contains","source":5380,"target":5878},{"edgeType":"calls","source":4568,"target":370},{"edgeType":"calls","source":6684,"target":303},{"edgeType":"calls","source":4949,"target":4413},{"edgeType":"contains","source":1379,"target":2008},{"edgeType":"contains","source":5285,"target":5651},{"edgeType":"contains","source":5758,"target":5781},{"edgeType":"contains","source":5756,"target":5843},{"edgeType":"calls","source":7013,"target":7017},{"edgeType":"calls","source":4382,"target":4021},{"edgeType":"calls","source":6968,"target":4184},{"edgeType":"calls","source":4568,"target":369},{"edgeType":"calls","source":6420,"target":6374},{"edgeType":"calls","source":6684,"target":304},{"edgeType":"contains","source":5758,"target":5782},{"edgeType":"calls","source":4982,"target":4446},{"edgeType":"contains","source":996,"target":1197},{"edgeType":"calls","source":5445,"target":4892},{"edgeType":"contains","source":5285,"target":5650},{"edgeType":"imports","source":4706,"target":78},{"edgeType":"calls","source":6274,"target":333},{"edgeType":"calls","source":4568,"target":368},{"edgeType":"contains","source":6450,"target":6528},{"edgeType":"calls","source":5092,"target":2092},{"edgeType":"calls","source":5220,"target":4466},{"edgeType":"calls","source":3450,"target":144},{"edgeType":"imports","source":4717,"target":1853},{"edgeType":"contains","source":1415,"target":890},{"edgeType":"calls","source":6994,"target":209},{"edgeType":"imports","source":4706,"target":79},{"edgeType":"calls","source":6274,"target":332},{"edgeType":"extends","source":1476,"target":36},{"edgeType":"contains","source":6683,"target":6705},{"edgeType":"contains","source":3,"target":3439},{"edgeType":"calls","source":6757,"target":157}],"nodes":[{"groupName":"","id":3,"nodeType":"Repo","repoName":"pytest-dev#pytest#8aba863a634f40560e25055d179220f0eefabe9a"},{"id":5,"name":"doc/en/announce","nodeType":"Package"},{"id":8,"name":"release-2.9.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.9.2\n============\n\npytest is a mature Python testing tool with more than a 1100 tests\nagainst itself, passing on many different interpreters and platforms.\n\nSee below for the changes and see docs at:\n\n http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n Adam Chainz\n Benjamin Dopplinger\n Bruno Oliveira\n Florian Bruhin\n John Towler\n Martin Prusse\n Meng Jue\n MengJueM\n Omar Kohl\n Quentin Pradet\n Ronny Pfannschmidt\n Thomas Güttler\n TomV\n Tyler Goodlet\n\n\nHappy testing,\nThe py.test Development Team\n\n\n2.9.2 (compared to 2.9.1)\n---------------------------\n\n**Bug Fixes**\n\n* fix `#510`_: skip tests where one parameterize dimension was empty\n thanks Alex Stapleton for the Report and `@RonnyPfannschmidt`_ for the PR\n\n* Fix Xfail does not work with condition keyword argument.\n Thanks `@astraw38`_ for reporting the issue (`#1496`_) and `@tomviner`_\n for PR the (`#1524`_).\n\n* Fix win32 path issue when putting custom config file with absolute path\n in ``pytest.main(\"-c your_absolute_path\")``.\n\n* Fix maximum recursion depth detection when raised error class is not aware\n of unicode/encoded bytes.\n Thanks `@prusse-martin`_ for the PR (`#1506`_).\n\n* Fix ``pytest.mark.skip`` mark when used in strict mode.\n Thanks `@pquentin`_ for the PR and `@RonnyPfannschmidt`_ for\n showing how to fix the bug.\n\n* Minor improvements and fixes to the documentation.\n Thanks `@omarkohl`_ for the PR.\n\n* Fix ``--fixtures`` to show all fixture definitions as opposed to just\n one per fixture name.\n Thanks to `@hackebrot`_ for the PR.\n\n.. _#510: https://github.com/pytest-dev/pytest/issues/510\n.. _#1506: https://github.com/pytest-dev/pytest/pull/1506\n.. _#1496: https://github.com/pytest-dev/pytest/issue/1496\n.. _#1524: https://github.com/pytest-dev/pytest/issue/1524\n\n.. _@astraw38: https://github.com/astraw38\n.. _@hackebrot: https://github.com/hackebrot\n.. _@omarkohl: https://github.com/omarkohl\n.. _@pquentin: https://github.com/pquentin\n.. _@prusse-martin: https://github.com/prusse-martin\n.. _@RonnyPfannschmidt: https://github.com/RonnyPfannschmidt\n.. _@tomviner: https://github.com/tomviner\n"},{"id":9,"name":".github","nodeType":"Package"},{"id":10,"name":"PULL_REQUEST_TEMPLATE.md","nodeType":"TextFile","path":".github","text":"\n\n- [ ] Target the `master` branch for bug fixes, documentation updates and trivial changes.\n- [ ] Target the `features` branch for new features and removals/deprecations.\n- [ ] Include documentation when adding new features.\n- [ ] Include new tests or update existing tests when applicable.\n\nUnless your change is trivial or a small documentation fix (e.g., a typo or reword of a small section) please:\n\n- [ ] Create a new changelog file in the `changelog` folder, with a name like `..rst`. See [changelog/README.rst](https://github.com/pytest-dev/pytest/blob/master/changelog/README.rst) for details.\n- [ ] Add yourself to `AUTHORS` in alphabetical order;\n"},{"id":11,"name":"ISSUE_TEMPLATE.md","nodeType":"TextFile","path":".github","text":"\n\n- [ ] a detailed description of the bug or suggestion\n- [ ] output of `pip list` from the virtual environment you are using\n- [ ] pytest and operating system versions\n- [ ] minimal example if possible\n"},{"id":12,"name":"testing/example_scripts/fixtures/fill_fixtures","nodeType":"Package"},{"fileName":"test_funcarg_lookup_classlevel.py","filePath":"testing/example_scripts/fixtures/fill_fixtures","id":13,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\nclass TestClass(object):\n @pytest.fixture\n def something(self, request):\n return request.instance\n\n def test_method(self, something):\n assert something is self\n"},{"id":14,"name":"testing/example_scripts/fixtures/fill_fixtures/test_extend_fixture_conftest_module","nodeType":"Package"},{"fileName":"test_extend_fixture_conftest_module.py","filePath":"testing/example_scripts/fixtures/fill_fixtures/test_extend_fixture_conftest_module","id":15,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\n@pytest.fixture\ndef spam(spam):\n return spam * 2\n\n\ndef test_spam(spam):\n assert spam == \"spamspam\"\n"},{"id":16,"name":"doc/en/example/assertion","nodeType":"Package"},{"fileName":"test_setup_flow_example.py","filePath":"doc/en/example/assertion","id":17,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ndef setup_module(module):\n module.TestStateFullThing.classcount = 0\n\n\nclass TestStateFullThing(object):\n def setup_class(cls):\n cls.classcount += 1\n\n def teardown_class(cls):\n cls.classcount -= 1\n\n def setup_method(self, method):\n self.id = eval(method.__name__[5:])\n\n def test_42(self):\n assert self.classcount == 1\n assert self.id == 42\n\n def test_23(self):\n assert self.classcount == 1\n assert self.id == 23\n\n\ndef teardown_module(module):\n assert module.TestStateFullThing.classcount == 0\n\n\n\"\"\" For this example the control flow happens as follows::\n import test_setup_flow_example\n setup_module(test_setup_flow_example)\n setup_class(TestStateFullThing)\n instance = TestStateFullThing()\n setup_method(instance, instance.test_42)\n instance.test_42()\n setup_method(instance, instance.test_23)\n instance.test_23()\n teardown_class(TestStateFullThing)\n teardown_module(test_setup_flow_example)\n\nNote that ``setup_class(TestStateFullThing)`` is called and not\n``TestStateFullThing.setup_class()`` which would require you\nto insert ``setup_class = classmethod(setup_class)`` to make\nyour setup function callable.\n\"\"\"\n"},{"fileName":"test_extend_fixture_module_class.py","filePath":"testing/example_scripts/fixtures/fill_fixtures","id":18,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\n@pytest.fixture\ndef spam():\n return \"spam\"\n\n\nclass TestSpam(object):\n @pytest.fixture\n def spam(self, spam):\n return spam * 2\n\n def test_spam(self, spam):\n assert spam == \"spamspam\"\n"},{"className":"TestStateFullThing","col":0,"comment":"null","endLoc":22,"id":19,"nodeType":"Class","startLoc":6,"text":"class TestStateFullThing(object):\n def setup_class(cls):\n cls.classcount += 1\n\n def teardown_class(cls):\n cls.classcount -= 1\n\n def setup_method(self, method):\n self.id = eval(method.__name__[5:])\n\n def test_42(self):\n assert self.classcount == 1\n assert self.id == 42\n\n def test_23(self):\n assert self.classcount == 1\n assert self.id == 23"},{"fileName":"test_funcarg_lookup_modulelevel.py","filePath":"testing/example_scripts/fixtures/fill_fixtures","id":20,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\n@pytest.fixture\ndef something(request):\n return request.function.__name__\n\n\nclass TestClass(object):\n def test_method(self, something):\n assert something == \"test_method\"\n\n\ndef test_func(something):\n assert something == \"test_func\"\n"},{"id":21,"name":"extra/setup-py.test","nodeType":"Package"},{"fileName":"setup.py","filePath":"extra/setup-py.test","id":22,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport sys\nfrom distutils.core import setup\n\nif __name__ == \"__main__\":\n if \"sdist\" not in sys.argv[1:]:\n raise ValueError(\"please use 'pytest' pypi package instead of 'py.test'\")\n setup(\n name=\"py.test\",\n version=\"0.0\",\n description=\"please use 'pytest' for installation\",\n )\n"},{"id":23,"name":"doc/en/example/py2py3","nodeType":"Package"},{"fileName":"conftest.py","filePath":"doc/en/example/py2py3","id":24,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport sys\n\nimport pytest\n\npy3 = sys.version_info[0] >= 3\n\n\nclass DummyCollector(pytest.collect.File):\n def collect(self):\n return []\n\n\ndef pytest_pycollect_makemodule(path, parent):\n bn = path.basename\n if \"py3\" in bn and not py3 or (\"py2\" in bn and py3):\n return DummyCollector(path, parent=parent)\n"},{"id":25,"name":"labels.toml","nodeType":"TextFile","path":".github","text":"[\"os: cygwin\"]\ncolor = \"006b75\"\ndescription = \"cygwin platform-specific problem\"\nname = \"os: cygwin\"\n\n[\"os: linux\"]\ncolor = \"1d76db\"\ndescription = \"linux platform-specific problem\"\nname = \"os: linux\"\n\n[\"os: mac\"]\ncolor = \"bfdadc\"\ndescription = \"mac platform-specific problem\"\nname = \"os: mac\"\n\n[\"os: windows\"]\ncolor = \"fbca04\"\ndescription = \"windows platform-specific problem\"\nname = \"os: windows\"\n\n[\"plugin: argcomplete\"]\ncolor = \"d4c5f9\"\ndescription = \"related to the argcomplete builtin plugin\"\nname = \"plugin: argcomplete\"\n\n[\"plugin: cache\"]\ncolor = \"c7def8\"\ndescription = \"related to the cache builtin plugin\"\nname = \"plugin: cache\"\n\n[\"plugin: capture\"]\ncolor = \"1d76db\"\ndescription = \"related to the capture builtin plugin\"\nname = \"plugin: capture\"\n\n[\"plugin: debugging\"]\ncolor = \"dd52a8\"\ndescription = \"related to the debugging builtin plugin\"\nname = \"plugin: debugging\"\n\n[\"plugin: doctests\"]\ncolor = \"fad8c7\"\ndescription = \"related to the doctests builtin plugin\"\nname = \"plugin: doctests\"\n\n[\"plugin: junitxml\"]\ncolor = \"c5def5\"\ndescription = \"related to the junitxml builtin plugin\"\nname = \"plugin: junitxml\"\n\n[\"plugin: logging\"]\ncolor = \"ff5432\"\ndescription = \"related to the logging builtin plugin\"\nname = \"plugin: logging\"\n\n[\"plugin: monkeypatch\"]\ncolor = \"0e8a16\"\ndescription = \"related to the monkeypatch builtin plugin\"\nname = \"plugin: monkeypatch\"\n\n[\"plugin: nose\"]\ncolor = \"bfdadc\"\ndescription = \"related to the nose integration builtin plugin\"\nname = \"plugin: nose\"\n\n[\"plugin: pastebin\"]\ncolor = \"bfd4f2\"\ndescription = \"related to the pastebin builtin plugin\"\nname = \"plugin: pastebin\"\n\n[\"plugin: pytester\"]\ncolor = \"c5def5\"\ndescription = \"related to the pytester builtin plugin\"\nname = \"plugin: pytester\"\n\n[\"plugin: tmpdir\"]\ncolor = \"bfd4f2\"\ndescription = \"related to the tmpdir builtin plugin\"\nname = \"plugin: tmpdir\"\n\n[\"plugin: unittest\"]\ncolor = \"006b75\"\ndescription = \"related to the unittest integration builtin plugin\"\nname = \"plugin: unittest\"\n\n[\"plugin: warnings\"]\ncolor = \"fef2c0\"\ndescription = \"related to the warnings builtin plugin\"\nname = \"plugin: warnings\"\n\n[\"plugin: xdist\"]\ncolor = \"5319e7\"\ndescription = \"related to the xdist external plugin\"\nname = \"plugin: xdist\"\n\n[\"status: critical\"]\ncolor = \"e11d21\"\ndescription = \"grave problem or usability issue that affects lots of users\"\nname = \"status: critical\"\n\n[\"status: easy\"]\ncolor = \"bfe5bf\"\ndescription = \"easy issue that is friendly to new contributor\"\nname = \"status: easy\"\n\n[\"status: help wanted\"]\ncolor = \"159818\"\ndescription = \"developers would like help from experts on this topic\"\nname = \"status: help wanted\"\n\n[\"status: needs information\"]\ncolor = \"5319e7\"\ndescription = \"reporter needs to provide more information; can be closed after 2 or more weeks of inactivity\"\nname = \"status: needs information\"\n\n[\"topic: collection\"]\ncolor = \"006b75\"\ndescription = \"related to the collection phase\"\nname = \"topic: collection\"\n\n[\"topic: config\"]\ncolor = \"006b75\"\ndescription = \"related to config handling, argument parsing and config file\"\nname = \"topic: config\"\n\n[\"topic: fixtures\"]\ncolor = \"5319e7\"\ndescription = \"anything involving fixtures directly or indirectly\"\nname = \"topic: fixtures\"\n\n[\"topic: marks\"]\ncolor = \"b60205\"\ndescription = \"related to marks, either the general marks or builtin\"\nname = \"topic: marks\"\n\n[\"topic: parametrize\"]\ncolor = \"fbca04\"\ndescription = \"related to @pytest.mark.parametrize\"\nname = \"topic: parametrize\"\n\n[\"topic: reporting\"]\ncolor = \"fef2c0\"\ndescription = \"related to terminal output and user-facing messages and errors\"\nname = \"topic: reporting\"\n\n[\"topic: rewrite\"]\ncolor = \"0e8a16\"\ndescription = \"related to the assertion rewrite mechanism\"\nname = \"topic: rewrite\"\n"},{"fileName":"conftest.py","filePath":"testing/example_scripts/fixtures/fill_fixtures/test_extend_fixture_conftest_module","id":26,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\n@pytest.fixture\ndef spam():\n return \"spam\"\n"},{"className":"TestClass","col":0,"comment":"null","endLoc":11,"id":27,"nodeType":"Class","startLoc":5,"text":"class TestClass(object):\n @pytest.fixture\n def something(self, request):\n return request.instance\n\n def test_method(self, something):\n assert something is self"},{"col":0,"comment":"null","endLoc":7,"header":"@pytest.fixture\ndef spam(spam)","id":28,"name":"spam","nodeType":"Function","startLoc":5,"text":"@pytest.fixture\ndef spam(spam):\n return spam * 2"},{"col":0,"comment":"null","endLoc":11,"header":"def test_spam(spam)","id":29,"name":"test_spam","nodeType":"Function","startLoc":10,"text":"def test_spam(spam):\n assert spam == \"spamspam\""},{"id":30,"name":"doc/en","nodeType":"Package"},{"id":31,"name":"development_guide.rst","nodeType":"TextFile","path":"doc/en","text":"=================\nDevelopment Guide\n=================\n\nSome general guidelines regarding development in pytest for maintainers and contributors. Nothing here\nis set in stone and can't be changed, feel free to suggest improvements or changes in the workflow.\n\n\nCode Style\n----------\n\n* `PEP-8 `_\n* `flake8 `_ for quality checks\n* `invoke `_ to automate development tasks\n\n\nBranches\n--------\n\nWe have two long term branches:\n\n* ``master``: contains the code for the next bugfix release.\n* ``features``: contains the code with new features for the next minor release.\n\nThe official repository usually does not contain topic branches, developers and contributors should create topic\nbranches in their own forks.\n\nExceptions can be made for cases where more than one contributor is working on the same\ntopic or where it makes sense to use some automatic capability of the main repository, such as automatic docs from\n`readthedocs `_ for a branch dealing with documentation refactoring.\n\nIssues\n------\n\nAny question, feature, bug or proposal is welcome as an issue. Users are encouraged to use them whenever they need.\n\nGitHub issues should use labels to categorize them. Labels should be created sporadically, to fill a niche; we should\navoid creating labels just for the sake of creating them.\n\nEach label should include a description in the GitHub's interface stating its purpose.\n\nLabels are managed using `labels `_. All the labels in the repository\nare kept in ``.github/labels.toml``, so any changes should be via PRs to that file.\nAfter a PR is accepted and merged, one of the maintainers must manually synchronize the labels file with the\nGitHub repository.\n\nTemporary labels\n~~~~~~~~~~~~~~~~\n\nTo classify issues for a special event it is encouraged to create a temporary label. This helps those involved to find\nthe relevant issues to work on. Examples of that are sprints in Python events or global hacking events.\n\n* ``temporary: EP2017 sprint``: candidate issues or PRs tackled during the EuroPython 2017\n\nIssues created at those events should have other relevant labels added as well.\n\nThose labels should be removed after they are no longer relevant.\n\n\n.. include:: ../../HOWTORELEASE.rst\n"},{"id":32,"name":"testing/python","nodeType":"Package"},{"fileName":"show_fixtures_per_test.py","filePath":"testing/python","id":33,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\n\ndef test_no_items_should_not_show_output(testdir):\n result = testdir.runpytest(\"--fixtures-per-test\")\n assert \"fixtures used by\" not in result.stdout.str()\n assert result.ret == 0\n\n\ndef test_fixtures_in_module(testdir):\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture\n def _arg0():\n \"\"\"hidden arg0 fixture\"\"\"\n @pytest.fixture\n def arg1():\n \"\"\"arg1 docstring\"\"\"\n def test_arg1(arg1):\n pass\n '''\n )\n\n result = testdir.runpytest(\"--fixtures-per-test\", p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\n \"*fixtures used by test_arg1*\",\n \"*(test_fixtures_in_module.py:9)*\",\n \"arg1\",\n \" arg1 docstring\",\n ]\n )\n assert \"_arg0\" not in result.stdout.str()\n\n\ndef test_fixtures_in_conftest(testdir):\n testdir.makeconftest(\n '''\n import pytest\n @pytest.fixture\n def arg1():\n \"\"\"arg1 docstring\"\"\"\n @pytest.fixture\n def arg2():\n \"\"\"arg2 docstring\"\"\"\n @pytest.fixture\n def arg3(arg1, arg2):\n \"\"\"arg3\n docstring\n \"\"\"\n '''\n )\n p = testdir.makepyfile(\n \"\"\"\n def test_arg2(arg2):\n pass\n def test_arg3(arg3):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--fixtures-per-test\", p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\n \"*fixtures used by test_arg2*\",\n \"*(test_fixtures_in_conftest.py:2)*\",\n \"arg2\",\n \" arg2 docstring\",\n \"*fixtures used by test_arg3*\",\n \"*(test_fixtures_in_conftest.py:4)*\",\n \"arg1\",\n \" arg1 docstring\",\n \"arg2\",\n \" arg2 docstring\",\n \"arg3\",\n \" arg3\",\n \" docstring\",\n ]\n )\n\n\ndef test_should_show_fixtures_used_by_test(testdir):\n testdir.makeconftest(\n '''\n import pytest\n @pytest.fixture\n def arg1():\n \"\"\"arg1 from conftest\"\"\"\n @pytest.fixture\n def arg2():\n \"\"\"arg2 from conftest\"\"\"\n '''\n )\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture\n def arg1():\n \"\"\"arg1 from testmodule\"\"\"\n def test_args(arg1, arg2):\n pass\n '''\n )\n result = testdir.runpytest(\"--fixtures-per-test\", p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\n \"*fixtures used by test_args*\",\n \"*(test_should_show_fixtures_used_by_test.py:6)*\",\n \"arg1\",\n \" arg1 from testmodule\",\n \"arg2\",\n \" arg2 from conftest\",\n ]\n )\n\n\ndef test_verbose_include_private_fixtures_and_loc(testdir):\n testdir.makeconftest(\n '''\n import pytest\n @pytest.fixture\n def _arg1():\n \"\"\"_arg1 from conftest\"\"\"\n @pytest.fixture\n def arg2(_arg1):\n \"\"\"arg2 from conftest\"\"\"\n '''\n )\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture\n def arg3():\n \"\"\"arg3 from testmodule\"\"\"\n def test_args(arg2, arg3):\n pass\n '''\n )\n result = testdir.runpytest(\"--fixtures-per-test\", \"-v\", p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\n \"*fixtures used by test_args*\",\n \"*(test_verbose_include_private_fixtures_and_loc.py:6)*\",\n \"_arg1 -- conftest.py:3\",\n \" _arg1 from conftest\",\n \"arg2 -- conftest.py:6\",\n \" arg2 from conftest\",\n \"arg3 -- test_verbose_include_private_fixtures_and_loc.py:3\",\n \" arg3 from testmodule\",\n ]\n )\n\n\ndef test_doctest_items(testdir):\n testdir.makepyfile(\n '''\n def foo():\n \"\"\"\n >>> 1 + 1\n 2\n \"\"\"\n '''\n )\n testdir.maketxtfile(\n \"\"\"\n >>> 1 + 1\n 2\n \"\"\"\n )\n result = testdir.runpytest(\n \"--fixtures-per-test\", \"--doctest-modules\", \"--doctest-glob=*.txt\", \"-v\"\n )\n assert result.ret == 0\n\n result.stdout.fnmatch_lines([\"*collected 2 items*\"])\n"},{"col":0,"comment":"null","endLoc":7,"header":"def test_no_items_should_not_show_output(testdir)","id":34,"name":"test_no_items_should_not_show_output","nodeType":"Function","startLoc":4,"text":"def test_no_items_should_not_show_output(testdir):\n result = testdir.runpytest(\"--fixtures-per-test\")\n assert \"fixtures used by\" not in result.stdout.str()\n assert result.ret == 0"},{"className":"object","col":0,"comment":"null","endLoc":127,"id":35,"nodeType":"Class","startLoc":90,"text":"class object:\n __doc__: str | None\n __dict__: dict[str, Any]\n __module__: str\n __annotations__: dict[str, Any]\n @property\n def __class__(self) -> type[Self]: ...\n # Ignore errors about type mismatch between property getter and setter\n @__class__.setter\n def __class__(self, __type: type[object]) -> None: ... # noqa: F811\n def __init__(self) -> None: ...\n def __new__(cls) -> Self: ...\n # N.B. `object.__setattr__` and `object.__delattr__` are heavily special-cased by type checkers.\n # Overriding them in subclasses has different semantics, even if the override has an identical signature.\n def __setattr__(self, __name: str, __value: Any) -> None: ...\n def __delattr__(self, __name: str) -> None: ...\n def __eq__(self, __value: object) -> bool: ...\n def __ne__(self, __value: object) -> bool: ...\n def __str__(self) -> str: ... # noqa: Y029\n def __repr__(self) -> str: ... # noqa: Y029\n def __hash__(self) -> int: ...\n def __format__(self, __format_spec: str) -> str: ...\n def __getattribute__(self, __name: str) -> Any: ...\n def __sizeof__(self) -> int: ...\n # return type of pickle methods is rather hard to express in the current type system\n # see #6661 and https://docs.python.org/3/library/pickle.html#object.__reduce__\n def __reduce__(self) -> str | tuple[Any, ...]: ...\n if sys.version_info >= (3, 8):\n def __reduce_ex__(self, __protocol: SupportsIndex) -> str | tuple[Any, ...]: ...\n else:\n def __reduce_ex__(self, __protocol: int) -> str | tuple[Any, ...]: ...\n if sys.version_info >= (3, 11):\n def __getstate__(self) -> object: ...\n\n def __dir__(self) -> Iterable[str]: ...\n def __init_subclass__(cls) -> None: ...\n @classmethod\n def __subclasshook__(cls, __subclass: type) -> bool: ..."},{"className":"object","col":0,"comment":"null","endLoc":127,"id":36,"nodeType":"Class","startLoc":90,"text":"class object:\n __doc__: str | None\n __dict__: dict[str, Any]\n __module__: str\n __annotations__: dict[str, Any]\n @property\n def __class__(self) -> type[Self]: ...\n # Ignore errors about type mismatch between property getter and setter\n @__class__.setter\n def __class__(self, __type: type[object]) -> None: ... # noqa: F811\n def __init__(self) -> None: ...\n def __new__(cls) -> Self: ...\n # N.B. `object.__setattr__` and `object.__delattr__` are heavily special-cased by type checkers.\n # Overriding them in subclasses has different semantics, even if the override has an identical signature.\n def __setattr__(self, __name: str, __value: Any) -> None: ...\n def __delattr__(self, __name: str) -> None: ...\n def __eq__(self, __value: object) -> bool: ...\n def __ne__(self, __value: object) -> bool: ...\n def __str__(self) -> str: ... # noqa: Y029\n def __repr__(self) -> str: ... # noqa: Y029\n def __hash__(self) -> int: ...\n def __format__(self, __format_spec: str) -> str: ...\n def __getattribute__(self, __name: str) -> Any: ...\n def __sizeof__(self) -> int: ...\n # return type of pickle methods is rather hard to express in the current type system\n # see #6661 and https://docs.python.org/3/library/pickle.html#object.__reduce__\n def __reduce__(self) -> str | tuple[Any, ...]: ...\n if sys.version_info >= (3, 8):\n def __reduce_ex__(self, __protocol: SupportsIndex) -> str | tuple[Any, ...]: ...\n else:\n def __reduce_ex__(self, __protocol: int) -> str | tuple[Any, ...]: ...\n if sys.version_info >= (3, 11):\n def __getstate__(self) -> object: ...\n\n def __dir__(self) -> Iterable[str]: ...\n def __init_subclass__(cls) -> None: ...\n @classmethod\n def __subclasshook__(cls, __subclass: type) -> bool: ..."},{"className":"TestClass","col":0,"comment":"null","endLoc":12,"id":37,"nodeType":"Class","startLoc":10,"text":"class TestClass(object):\n def test_method(self, something):\n assert something == \"test_method\""},{"className":"object","col":0,"comment":"null","endLoc":127,"id":38,"nodeType":"Class","startLoc":90,"text":"class object:\n __doc__: str | None\n __dict__: dict[str, Any]\n __module__: str\n __annotations__: dict[str, Any]\n @property\n def __class__(self) -> type[Self]: ...\n # Ignore errors about type mismatch between property getter and setter\n @__class__.setter\n def __class__(self, __type: type[object]) -> None: ... # noqa: F811\n def __init__(self) -> None: ...\n def __new__(cls) -> Self: ...\n # N.B. `object.__setattr__` and `object.__delattr__` are heavily special-cased by type checkers.\n # Overriding them in subclasses has different semantics, even if the override has an identical signature.\n def __setattr__(self, __name: str, __value: Any) -> None: ...\n def __delattr__(self, __name: str) -> None: ...\n def __eq__(self, __value: object) -> bool: ...\n def __ne__(self, __value: object) -> bool: ...\n def __str__(self) -> str: ... # noqa: Y029\n def __repr__(self) -> str: ... # noqa: Y029\n def __hash__(self) -> int: ...\n def __format__(self, __format_spec: str) -> str: ...\n def __getattribute__(self, __name: str) -> Any: ...\n def __sizeof__(self) -> int: ...\n # return type of pickle methods is rather hard to express in the current type system\n # see #6661 and https://docs.python.org/3/library/pickle.html#object.__reduce__\n def __reduce__(self) -> str | tuple[Any, ...]: ...\n if sys.version_info >= (3, 8):\n def __reduce_ex__(self, __protocol: SupportsIndex) -> str | tuple[Any, ...]: ...\n else:\n def __reduce_ex__(self, __protocol: int) -> str | tuple[Any, ...]: ...\n if sys.version_info >= (3, 11):\n def __getstate__(self) -> object: ...\n\n def __dir__(self) -> Iterable[str]: ...\n def __init_subclass__(cls) -> None: ...\n @classmethod\n def __subclasshook__(cls, __subclass: type) -> bool: ..."},{"col":0,"comment":"null","endLoc":7,"header":"@pytest.fixture\ndef spam()","id":39,"name":"spam","nodeType":"Function","startLoc":5,"text":"@pytest.fixture\ndef spam():\n return \"spam\""},{"className":"DummyCollector","col":0,"comment":"null","endLoc":11,"id":40,"nodeType":"Class","startLoc":9,"text":"class DummyCollector(pytest.collect.File):\n def collect(self):\n return []"},{"id":41,"name":"src/_pytest","nodeType":"Package"},{"fileName":"unittest.py","filePath":"src/_pytest","id":42,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\" discovery and running of std-library \"unittest\" style tests. \"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nimport traceback\n\nimport _pytest._code\nimport pytest\nfrom _pytest.compat import getimfunc\nfrom _pytest.config import hookimpl\nfrom _pytest.outcomes import fail\nfrom _pytest.outcomes import skip\nfrom _pytest.outcomes import xfail\nfrom _pytest.python import Class\nfrom _pytest.python import Function\n\n\ndef pytest_pycollect_makeitem(collector, name, obj):\n # has unittest been imported and is obj a subclass of its TestCase?\n try:\n if not issubclass(obj, sys.modules[\"unittest\"].TestCase):\n return\n except Exception:\n return\n # yes, so let's collect it\n return UnitTestCase(name, parent=collector)\n\n\nclass UnitTestCase(Class):\n # marker for fixturemanger.getfixtureinfo()\n # to declare that our children do not support funcargs\n nofuncargs = True\n\n def collect(self):\n from unittest import TestLoader\n\n cls = self.obj\n if not getattr(cls, \"__test__\", True):\n return\n\n skipped = getattr(cls, \"__unittest_skip__\", False)\n if not skipped:\n self._inject_setup_teardown_fixtures(cls)\n self._inject_setup_class_fixture()\n\n self.session._fixturemanager.parsefactories(self, unittest=True)\n loader = TestLoader()\n foundsomething = False\n for name in loader.getTestCaseNames(self.obj):\n x = getattr(self.obj, name)\n if not getattr(x, \"__test__\", True):\n continue\n funcobj = getimfunc(x)\n yield TestCaseFunction(name, parent=self, callobj=funcobj)\n foundsomething = True\n\n if not foundsomething:\n runtest = getattr(self.obj, \"runTest\", None)\n if runtest is not None:\n ut = sys.modules.get(\"twisted.trial.unittest\", None)\n if ut is None or runtest != ut.TestCase.runTest:\n yield TestCaseFunction(\"runTest\", parent=self)\n\n def _inject_setup_teardown_fixtures(self, cls):\n \"\"\"Injects a hidden auto-use fixture to invoke setUpClass/setup_method and corresponding\n teardown functions (#517)\"\"\"\n class_fixture = _make_xunit_fixture(\n cls, \"setUpClass\", \"tearDownClass\", scope=\"class\", pass_self=False\n )\n if class_fixture:\n cls.__pytest_class_setup = class_fixture\n\n method_fixture = _make_xunit_fixture(\n cls, \"setup_method\", \"teardown_method\", scope=\"function\", pass_self=True\n )\n if method_fixture:\n cls.__pytest_method_setup = method_fixture\n\n\ndef _make_xunit_fixture(obj, setup_name, teardown_name, scope, pass_self):\n setup = getattr(obj, setup_name, None)\n teardown = getattr(obj, teardown_name, None)\n if setup is None and teardown is None:\n return None\n\n @pytest.fixture(scope=scope, autouse=True)\n def fixture(self, request):\n if getattr(self, \"__unittest_skip__\", None):\n reason = self.__unittest_skip_why__\n pytest.skip(reason)\n if setup is not None:\n if pass_self:\n setup(self, request.function)\n else:\n setup()\n yield\n if teardown is not None:\n if pass_self:\n teardown(self, request.function)\n else:\n teardown()\n\n return fixture\n\n\nclass TestCaseFunction(Function):\n nofuncargs = True\n _excinfo = None\n _testcase = None\n\n def setup(self):\n self._testcase = self.parent.obj(self.name)\n self._fix_unittest_skip_decorator()\n self._obj = getattr(self._testcase, self.name)\n if hasattr(self, \"_request\"):\n self._request._fillfixtures()\n\n def _fix_unittest_skip_decorator(self):\n \"\"\"\n The @unittest.skip decorator calls functools.wraps(self._testcase)\n The call to functools.wraps() fails unless self._testcase\n has a __name__ attribute. This is usually automatically supplied\n if the test is a function or method, but we need to add manually\n here.\n\n See issue #1169\n \"\"\"\n if sys.version_info[0] == 2:\n setattr(self._testcase, \"__name__\", self.name)\n\n def teardown(self):\n self._testcase = None\n self._obj = None\n\n def startTest(self, testcase):\n pass\n\n def _addexcinfo(self, rawexcinfo):\n # unwrap potential exception info (see twisted trial support below)\n rawexcinfo = getattr(rawexcinfo, \"_rawexcinfo\", rawexcinfo)\n try:\n excinfo = _pytest._code.ExceptionInfo(rawexcinfo)\n # invoke the attributes to trigger storing the traceback\n # trial causes some issue there\n excinfo.value\n excinfo.traceback\n except TypeError:\n try:\n try:\n values = traceback.format_exception(*rawexcinfo)\n values.insert(\n 0,\n \"NOTE: Incompatible Exception Representation, \"\n \"displaying natively:\\n\\n\",\n )\n fail(\"\".join(values), pytrace=False)\n except (fail.Exception, KeyboardInterrupt):\n raise\n except: # noqa\n fail(\n \"ERROR: Unknown Incompatible Exception \"\n \"representation:\\n%r\" % (rawexcinfo,),\n pytrace=False,\n )\n except KeyboardInterrupt:\n raise\n except fail.Exception:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n self.__dict__.setdefault(\"_excinfo\", []).append(excinfo)\n\n def addError(self, testcase, rawexcinfo):\n self._addexcinfo(rawexcinfo)\n\n def addFailure(self, testcase, rawexcinfo):\n self._addexcinfo(rawexcinfo)\n\n def addSkip(self, testcase, reason):\n try:\n skip(reason)\n except skip.Exception:\n self._skipped_by_mark = True\n self._addexcinfo(sys.exc_info())\n\n def addExpectedFailure(self, testcase, rawexcinfo, reason=\"\"):\n try:\n xfail(str(reason))\n except xfail.Exception:\n self._addexcinfo(sys.exc_info())\n\n def addUnexpectedSuccess(self, testcase, reason=\"\"):\n self._unexpectedsuccess = reason\n\n def addSuccess(self, testcase):\n pass\n\n def stopTest(self, testcase):\n pass\n\n def _handle_skip(self):\n # implements the skipping machinery (see #2137)\n # analog to pythons Lib/unittest/case.py:run\n testMethod = getattr(self._testcase, self._testcase._testMethodName)\n if getattr(self._testcase.__class__, \"__unittest_skip__\", False) or getattr(\n testMethod, \"__unittest_skip__\", False\n ):\n # If the class or method was skipped.\n skip_why = getattr(\n self._testcase.__class__, \"__unittest_skip_why__\", \"\"\n ) or getattr(testMethod, \"__unittest_skip_why__\", \"\")\n try: # PY3, unittest2 on PY2\n self._testcase._addSkip(self, self._testcase, skip_why)\n except TypeError: # PY2\n if sys.version_info[0] != 2:\n raise\n self._testcase._addSkip(self, skip_why)\n return True\n return False\n\n def runtest(self):\n if self.config.pluginmanager.get_plugin(\"pdbinvoke\") is None:\n self._testcase(result=self)\n else:\n # disables tearDown and cleanups for post mortem debugging (see #1890)\n if self._handle_skip():\n return\n self._testcase.debug()\n\n def _prunetraceback(self, excinfo):\n Function._prunetraceback(self, excinfo)\n traceback = excinfo.traceback.filter(\n lambda x: not x.frame.f_globals.get(\"__unittest\")\n )\n if traceback:\n excinfo.traceback = traceback\n\n\n@hookimpl(tryfirst=True)\ndef pytest_runtest_makereport(item, call):\n if isinstance(item, TestCaseFunction):\n if item._excinfo:\n call.excinfo = item._excinfo.pop(0)\n try:\n del call.result\n except AttributeError:\n pass\n\n\n# twisted trial support\n\n\n@hookimpl(hookwrapper=True)\ndef pytest_runtest_protocol(item):\n if isinstance(item, TestCaseFunction) and \"twisted.trial.unittest\" in sys.modules:\n ut = sys.modules[\"twisted.python.failure\"]\n Failure__init__ = ut.Failure.__init__\n check_testcase_implements_trial_reporter()\n\n def excstore(\n self, exc_value=None, exc_type=None, exc_tb=None, captureVars=None\n ):\n if exc_value is None:\n self._rawexcinfo = sys.exc_info()\n else:\n if exc_type is None:\n exc_type = type(exc_value)\n self._rawexcinfo = (exc_type, exc_value, exc_tb)\n try:\n Failure__init__(\n self, exc_value, exc_type, exc_tb, captureVars=captureVars\n )\n except TypeError:\n Failure__init__(self, exc_value, exc_type, exc_tb)\n\n ut.Failure.__init__ = excstore\n yield\n ut.Failure.__init__ = Failure__init__\n else:\n yield\n\n\ndef check_testcase_implements_trial_reporter(done=[]):\n if done:\n return\n from zope.interface import classImplements\n from twisted.trial.itrial import IReporter\n\n classImplements(TestCaseFunction, IReporter)\n done.append(1)\n"},{"fileName":"test_py2.py","filePath":"doc/en/example/py2py3","id":43,"nodeType":"File","text":"def test_exception_syntax():\n try:\n 0 / 0\n except ZeroDivisionError, e:\n assert e\n"},{"col":0,"comment":"null","endLoc":5,"header":"def test_exception_syntax()","id":44,"name":"test_exception_syntax","nodeType":"Function","startLoc":1,"text":"def test_exception_syntax():\n try:\n 0 / 0\n except ZeroDivisionError, e:\n assert e"},{"className":"TestSpam","col":0,"comment":"null","endLoc":16,"id":45,"nodeType":"Class","startLoc":10,"text":"class TestSpam(object):\n @pytest.fixture\n def spam(self, spam):\n return spam * 2\n\n def test_spam(self, spam):\n assert spam == \"spamspam\""},{"fileName":"test_py3.py","filePath":"doc/en/example/py2py3","id":46,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ndef test_exception_syntax():\n try:\n 0 / 0\n except ZeroDivisionError as e:\n assert e\n"},{"className":"object","col":0,"comment":"null","endLoc":127,"id":47,"nodeType":"Class","startLoc":90,"text":"class object:\n __doc__: str | None\n __dict__: dict[str, Any]\n __module__: str\n __annotations__: dict[str, Any]\n @property\n def __class__(self) -> type[Self]: ...\n # Ignore errors about type mismatch between property getter and setter\n @__class__.setter\n def __class__(self, __type: type[object]) -> None: ... # noqa: F811\n def __init__(self) -> None: ...\n def __new__(cls) -> Self: ...\n # N.B. `object.__setattr__` and `object.__delattr__` are heavily special-cased by type checkers.\n # Overriding them in subclasses has different semantics, even if the override has an identical signature.\n def __setattr__(self, __name: str, __value: Any) -> None: ...\n def __delattr__(self, __name: str) -> None: ...\n def __eq__(self, __value: object) -> bool: ...\n def __ne__(self, __value: object) -> bool: ...\n def __str__(self) -> str: ... # noqa: Y029\n def __repr__(self) -> str: ... # noqa: Y029\n def __hash__(self) -> int: ...\n def __format__(self, __format_spec: str) -> str: ...\n def __getattribute__(self, __name: str) -> Any: ...\n def __sizeof__(self) -> int: ...\n # return type of pickle methods is rather hard to express in the current type system\n # see #6661 and https://docs.python.org/3/library/pickle.html#object.__reduce__\n def __reduce__(self) -> str | tuple[Any, ...]: ...\n if sys.version_info >= (3, 8):\n def __reduce_ex__(self, __protocol: SupportsIndex) -> str | tuple[Any, ...]: ...\n else:\n def __reduce_ex__(self, __protocol: int) -> str | tuple[Any, ...]: ...\n if sys.version_info >= (3, 11):\n def __getstate__(self) -> object: ...\n\n def __dir__(self) -> Iterable[str]: ...\n def __init_subclass__(cls) -> None: ...\n @classmethod\n def __subclasshook__(cls, __subclass: type) -> bool: ..."},{"col":0,"comment":"null","endLoc":6,"header":"def test_exception_syntax()","id":48,"name":"test_exception_syntax","nodeType":"Function","startLoc":2,"text":"def test_exception_syntax():\n try:\n 0 / 0\n except ZeroDivisionError as e:\n assert e"},{"attributeType":"_Feature","col":0,"comment":"null","endLoc":11,"id":49,"name":"absolute_import","nodeType":"Attribute","startLoc":11,"text":"absolute_import"},{"id":50,"name":"writing_plugins.rst","nodeType":"TextFile","path":"doc/en","text":".. _plugins:\n.. _`writing-plugins`:\n\nWriting plugins\n===============\n\nIt is easy to implement `local conftest plugins`_ for your own project\nor `pip-installable plugins`_ that can be used throughout many projects,\nincluding third party projects. Please refer to :ref:`using plugins` if you\nonly want to use but not write plugins.\n\nA plugin contains one or multiple hook functions. :ref:`Writing hooks `\nexplains the basics and details of how you can write a hook function yourself.\n``pytest`` implements all aspects of configuration, collection, running and\nreporting by calling :ref:`well specified hooks ` of the following plugins:\n\n* builtin plugins: loaded from pytest's internal ``_pytest`` directory.\n\n* :ref:`external plugins `: modules discovered through\n `setuptools entry points`_\n\n* `conftest.py plugins`_: modules auto-discovered in test directories\n\nIn principle, each hook call is a ``1:N`` Python function call where ``N`` is the\nnumber of registered implementation functions for a given specification.\nAll specifications and implementations follow the ``pytest_`` prefix\nnaming convention, making them easy to distinguish and find.\n\n.. _`pluginorder`:\n\nPlugin discovery order at tool startup\n--------------------------------------\n\n``pytest`` loads plugin modules at tool startup in the following way:\n\n* by loading all builtin plugins\n\n* by loading all plugins registered through `setuptools entry points`_.\n\n* by pre-scanning the command line for the ``-p name`` option\n and loading the specified plugin before actual command line parsing.\n\n* by loading all :file:`conftest.py` files as inferred by the command line\n invocation:\n\n - if no test paths are specified use current dir as a test path\n - if exists, load ``conftest.py`` and ``test*/conftest.py`` relative\n to the directory part of the first test path.\n\n Note that pytest does not find ``conftest.py`` files in deeper nested\n sub directories at tool startup. It is usually a good idea to keep\n your ``conftest.py`` file in the top level test or project root directory.\n\n* by recursively loading all plugins specified by the\n ``pytest_plugins`` variable in ``conftest.py`` files\n\n\n.. _`pytest/plugin`: http://bitbucket.org/pytest-dev/pytest/src/tip/pytest/plugin/\n.. _`conftest.py plugins`:\n.. _`localplugin`:\n.. _`local conftest plugins`:\n\nconftest.py: local per-directory plugins\n----------------------------------------\n\nLocal ``conftest.py`` plugins contain directory-specific hook\nimplementations. Hook Session and test running activities will\ninvoke all hooks defined in ``conftest.py`` files closer to the\nroot of the filesystem. Example of implementing the\n``pytest_runtest_setup`` hook so that is called for tests in the ``a``\nsub directory but not for other directories::\n\n a/conftest.py:\n def pytest_runtest_setup(item):\n # called for running each test in 'a' directory\n print(\"setting up\", item)\n\n a/test_sub.py:\n def test_sub():\n pass\n\n test_flat.py:\n def test_flat():\n pass\n\nHere is how you might run it::\n\n     pytest test_flat.py --capture=no # will not show \"setting up\"\n pytest a/test_sub.py --capture=no # will show \"setting up\"\n\n.. note::\n If you have ``conftest.py`` files which do not reside in a\n python package directory (i.e. one containing an ``__init__.py``) then\n \"import conftest\" can be ambiguous because there might be other\n ``conftest.py`` files as well on your ``PYTHONPATH`` or ``sys.path``.\n It is thus good practice for projects to either put ``conftest.py``\n under a package scope or to never import anything from a\n ``conftest.py`` file.\n\n See also: :ref:`pythonpath`.\n\n\nWriting your own plugin\n-----------------------\n\n.. _`setuptools`: https://pypi.org/project/setuptools/\n\nIf you want to write a plugin, there are many real-life examples\nyou can copy from:\n\n* a custom collection example plugin: :ref:`yaml plugin`\n* builtin plugins which provide pytest's own functionality\n* many `external plugins `_ providing additional features\n\nAll of these plugins implement :ref:`hooks ` and/or :ref:`fixtures `\nto extend and add functionality.\n\n.. note::\n Make sure to check out the excellent\n `cookiecutter-pytest-plugin `_\n project, which is a `cookiecutter template `_\n for authoring plugins.\n\n The template provides an excellent starting point with a working plugin,\n tests running with tox, a comprehensive README file as well as a\n pre-configured entry-point.\n\nAlso consider :ref:`contributing your plugin to pytest-dev`\nonce it has some happy users other than yourself.\n\n\n.. _`setuptools entry points`:\n.. _`pip-installable plugins`:\n\nMaking your plugin installable by others\n----------------------------------------\n\nIf you want to make your plugin externally available, you\nmay define a so-called entry point for your distribution so\nthat ``pytest`` finds your plugin module. Entry points are\na feature that is provided by `setuptools`_. pytest looks up\nthe ``pytest11`` entrypoint to discover its\nplugins and you can thus make your plugin available by defining\nit in your setuptools-invocation:\n\n.. sourcecode:: python\n\n # sample ./setup.py file\n from setuptools import setup\n\n setup(\n name=\"myproject\",\n packages=[\"myproject\"],\n # the following makes a plugin available to pytest\n entry_points={\"pytest11\": [\"name_of_plugin = myproject.pluginmodule\"]},\n # custom PyPI classifier for pytest plugins\n classifiers=[\"Framework :: Pytest\"],\n )\n\nIf a package is installed this way, ``pytest`` will load\n``myproject.pluginmodule`` as a plugin which can define\n:ref:`hooks `.\n\n.. note::\n\n Make sure to include ``Framework :: Pytest`` in your list of\n `PyPI classifiers `_\n to make it easy for users to find your plugin.\n\n\n.. _assertion-rewriting:\n\nAssertion Rewriting\n-------------------\n\nOne of the main features of ``pytest`` is the use of plain assert\nstatements and the detailed introspection of expressions upon\nassertion failures. This is provided by \"assertion rewriting\" which\nmodifies the parsed AST before it gets compiled to bytecode. This is\ndone via a :pep:`302` import hook which gets installed early on when\n``pytest`` starts up and will perform this rewriting when modules get\nimported. However since we do not want to test different bytecode\nthen you will run in production this hook only rewrites test modules\nthemselves as well as any modules which are part of plugins. Any\nother imported module will not be rewritten and normal assertion\nbehaviour will happen.\n\nIf you have assertion helpers in other modules where you would need\nassertion rewriting to be enabled you need to ask ``pytest``\nexplicitly to rewrite this module before it gets imported.\n\n.. autofunction:: pytest.register_assert_rewrite\n :noindex:\n\nThis is especially important when you write a pytest plugin which is\ncreated using a package. The import hook only treats ``conftest.py``\nfiles and any modules which are listed in the ``pytest11`` entrypoint\nas plugins. As an example consider the following package::\n\n pytest_foo/__init__.py\n pytest_foo/plugin.py\n pytest_foo/helper.py\n\nWith the following typical ``setup.py`` extract:\n\n.. code-block:: python\n\n setup(..., entry_points={\"pytest11\": [\"foo = pytest_foo.plugin\"]}, ...)\n\nIn this case only ``pytest_foo/plugin.py`` will be rewritten. If the\nhelper module also contains assert statements which need to be\nrewritten it needs to be marked as such, before it gets imported.\nThis is easiest by marking it for rewriting inside the\n``__init__.py`` module, which will always be imported first when a\nmodule inside a package is imported. This way ``plugin.py`` can still\nimport ``helper.py`` normally. The contents of\n``pytest_foo/__init__.py`` will then need to look like this:\n\n.. code-block:: python\n\n import pytest\n\n pytest.register_assert_rewrite(\"pytest_foo.helper\")\n\n\nRequiring/Loading plugins in a test module or conftest file\n-----------------------------------------------------------\n\nYou can require plugins in a test module or a ``conftest.py`` file like this:\n\n.. code-block:: python\n\n pytest_plugins = [\"name1\", \"name2\"]\n\nWhen the test module or conftest plugin is loaded the specified plugins\nwill be loaded as well. Any module can be blessed as a plugin, including internal\napplication modules:\n\n.. code-block:: python\n\n pytest_plugins = \"myapp.testsupport.myplugin\"\n\n``pytest_plugins`` variables are processed recursively, so note that in the example above\nif ``myapp.testsupport.myplugin`` also declares ``pytest_plugins``, the contents\nof the variable will also be loaded as plugins, and so on.\n\n.. _`requiring plugins in non-root conftests`:\n\n.. note::\n Requiring plugins using a ``pytest_plugins`` variable in non-root\n ``conftest.py`` files is deprecated.\n\n This is important because ``conftest.py`` files implement per-directory\n hook implementations, but once a plugin is imported, it will affect the\n entire directory tree. In order to avoid confusion, defining\n ``pytest_plugins`` in any ``conftest.py`` file which is not located in the\n tests root directory is deprecated, and will raise a warning.\n\nThis mechanism makes it easy to share fixtures within applications or even\nexternal applications without the need to create external plugins using\nthe ``setuptools``'s entry point technique.\n\nPlugins imported by ``pytest_plugins`` will also automatically be marked\nfor assertion rewriting (see :func:`pytest.register_assert_rewrite`).\nHowever for this to have any effect the module must not be\nimported already; if it was already imported at the time the\n``pytest_plugins`` statement is processed, a warning will result and\nassertions inside the plugin will not be rewritten. To fix this you\ncan either call :func:`pytest.register_assert_rewrite` yourself before\nthe module is imported, or you can arrange the code to delay the\nimporting until after the plugin is registered.\n\n\nAccessing another plugin by name\n--------------------------------\n\nIf a plugin wants to collaborate with code from\nanother plugin it can obtain a reference through\nthe plugin manager like this:\n\n.. sourcecode:: python\n\n plugin = config.pluginmanager.get_plugin(\"name_of_plugin\")\n\nIf you want to look at the names of existing plugins, use\nthe ``--trace-config`` option.\n\n\n.. _registering-markers:\n\nRegistering custom markers\n--------------------------\n\nIf your plugin uses any markers, you should register them so that they appear in\npytest's help text and do not :ref:`cause spurious warnings `.\nFor example, the following plugin would register ``cool_marker`` and\n``mark_with`` for all users:\n\n.. code-block:: python\n\n def pytest_configure(config):\n config.addinivalue_line(\"markers\", \"cool_marker: this one is for cool tests.\")\n config.addinivalue_line(\n \"markers\", \"mark_with(arg, arg2): this marker takes arguments.\"\n )\n\n\nTesting plugins\n---------------\n\npytest comes with a plugin named ``pytester`` that helps you write tests for\nyour plugin code. The plugin is disabled by default, so you will have to enable\nit before you can use it.\n\nYou can do so by adding the following line to a ``conftest.py`` file in your\ntesting directory:\n\n.. code-block:: python\n\n # content of conftest.py\n\n pytest_plugins = [\"pytester\"]\n\nAlternatively you can invoke pytest with the ``-p pytester`` command line\noption.\n\nThis will allow you to use the :py:class:`testdir <_pytest.pytester.Testdir>`\nfixture for testing your plugin code.\n\nLet's demonstrate what you can do with the plugin with an example. Imagine we\ndeveloped a plugin that provides a fixture ``hello`` which yields a function\nand we can invoke this function with one optional parameter. It will return a\nstring value of ``Hello World!`` if we do not supply a value or ``Hello\n{value}!`` if we do supply a string value.\n\n.. code-block:: python\n\n # -*- coding: utf-8 -*-\n\n import pytest\n\n\n def pytest_addoption(parser):\n group = parser.getgroup(\"helloworld\")\n group.addoption(\n \"--name\",\n action=\"store\",\n dest=\"name\",\n default=\"World\",\n help='Default \"name\" for hello().',\n )\n\n\n @pytest.fixture\n def hello(request):\n name = request.config.getoption(\"name\")\n\n def _hello(name=None):\n if not name:\n name = request.config.getoption(\"name\")\n return \"Hello {name}!\".format(name=name)\n\n return _hello\n\n\nNow the ``testdir`` fixture provides a convenient API for creating temporary\n``conftest.py`` files and test files. It also allows us to run the tests and\nreturn a result object, with which we can assert the tests' outcomes.\n\n.. code-block:: python\n\n def test_hello(testdir):\n \"\"\"Make sure that our plugin works.\"\"\"\n\n # create a temporary conftest.py file\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[\n \"Brianna\",\n \"Andreas\",\n \"Floris\",\n ])\n def name(request):\n return request.param\n \"\"\"\n )\n\n # create a temporary pytest test file\n testdir.makepyfile(\n \"\"\"\n def test_hello_default(hello):\n assert hello() == \"Hello World!\"\n\n def test_hello_name(hello, name):\n assert hello(name) == \"Hello {0}!\".format(name)\n \"\"\"\n )\n\n # run all tests with pytest\n result = testdir.runpytest()\n\n # check that all 4 tests passed\n result.assert_outcomes(passed=4)\n\n\nadditionally it is possible to copy examples for an example folder before running pytest on it\n\n.. code-block:: ini\n\n # content of pytest.ini\n [pytest]\n pytester_example_dir = .\n\n\n.. code-block:: python\n\n # content of test_example.py\n\n\n def test_plugin(testdir):\n testdir.copy_example(\"test_example.py\")\n testdir.runpytest(\"-k\", \"test_example\")\n\n\n def test_example():\n pass\n\n.. code-block:: pytest\n\n $ pytest\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR, inifile: pytest.ini\n collected 2 items\n\n test_example.py .. [100%]\n\n ============================= warnings summary =============================\n test_example.py::test_plugin\n $REGENDOC_TMPDIR/test_example.py:4: PytestExperimentalApiWarning: testdir.copy_example is an experimental api that may change over time\n testdir.copy_example(\"test_example.py\")\n\n -- Docs: https://docs.pytest.org/en/latest/warnings.html\n =================== 2 passed, 1 warnings in 0.12 seconds ===================\n\nFor more information about the result object that ``runpytest()`` returns, and\nthe methods that it provides please check out the :py:class:`RunResult\n<_pytest.pytester.RunResult>` documentation.\n\n\n\n\n.. _`writinghooks`:\n\nWriting hook functions\n======================\n\n\n.. _validation:\n\nhook function validation and execution\n--------------------------------------\n\npytest calls hook functions from registered plugins for any\ngiven hook specification. Let's look at a typical hook function\nfor the ``pytest_collection_modifyitems(session, config,\nitems)`` hook which pytest calls after collection of all test items is\ncompleted.\n\nWhen we implement a ``pytest_collection_modifyitems`` function in our plugin\npytest will during registration verify that you use argument\nnames which match the specification and bail out if not.\n\nLet's look at a possible implementation:\n\n.. code-block:: python\n\n def pytest_collection_modifyitems(config, items):\n # called after collection is completed\n # you can modify the ``items`` list\n ...\n\nHere, ``pytest`` will pass in ``config`` (the pytest config object)\nand ``items`` (the list of collected test items) but will not pass\nin the ``session`` argument because we didn't list it in the function\nsignature. This dynamic \"pruning\" of arguments allows ``pytest`` to\nbe \"future-compatible\": we can introduce new hook named parameters without\nbreaking the signatures of existing hook implementations. It is one of\nthe reasons for the general long-lived compatibility of pytest plugins.\n\nNote that hook functions other than ``pytest_runtest_*`` are not\nallowed to raise exceptions. Doing so will break the pytest run.\n\n\n\n.. _firstresult:\n\nfirstresult: stop at first non-None result\n-------------------------------------------\n\nMost calls to ``pytest`` hooks result in a **list of results** which contains\nall non-None results of the called hook functions.\n\nSome hook specifications use the ``firstresult=True`` option so that the hook\ncall only executes until the first of N registered functions returns a\nnon-None result which is then taken as result of the overall hook call.\nThe remaining hook functions will not be called in this case.\n\n\nhookwrapper: executing around other hooks\n-------------------------------------------------\n\n.. currentmodule:: _pytest.core\n\n\n\npytest plugins can implement hook wrappers which wrap the execution\nof other hook implementations. A hook wrapper is a generator function\nwhich yields exactly once. When pytest invokes hooks it first executes\nhook wrappers and passes the same arguments as to the regular hooks.\n\nAt the yield point of the hook wrapper pytest will execute the next hook\nimplementations and return their result to the yield point in the form of\na :py:class:`Result ` instance which encapsulates a result or\nexception info. The yield point itself will thus typically not raise\nexceptions (unless there are bugs).\n\nHere is an example definition of a hook wrapper:\n\n.. code-block:: python\n\n import pytest\n\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_pyfunc_call(pyfuncitem):\n do_something_before_next_hook_executes()\n\n outcome = yield\n # outcome.excinfo may be None or a (cls, val, tb) tuple\n\n res = outcome.get_result() # will raise if outcome was exception\n\n post_process_result(res)\n\n outcome.force_result(new_res) # to override the return value to the plugin system\n\nNote that hook wrappers don't return results themselves, they merely\nperform tracing or other side effects around the actual hook implementations.\nIf the result of the underlying hook is a mutable object, they may modify\nthat result but it's probably better to avoid it.\n\nFor more information, consult the `pluggy documentation `_.\n\n\nHook function ordering / call example\n-------------------------------------\n\nFor any given hook specification there may be more than one\nimplementation and we thus generally view ``hook`` execution as a\n``1:N`` function call where ``N`` is the number of registered functions.\nThere are ways to influence if a hook implementation comes before or\nafter others, i.e. the position in the ``N``-sized list of functions:\n\n.. code-block:: python\n\n # Plugin 1\n @pytest.hookimpl(tryfirst=True)\n def pytest_collection_modifyitems(items):\n # will execute as early as possible\n ...\n\n\n # Plugin 2\n @pytest.hookimpl(trylast=True)\n def pytest_collection_modifyitems(items):\n # will execute as late as possible\n ...\n\n\n # Plugin 3\n @pytest.hookimpl(hookwrapper=True)\n def pytest_collection_modifyitems(items):\n # will execute even before the tryfirst one above!\n outcome = yield\n # will execute after all non-hookwrappers executed\n\nHere is the order of execution:\n\n1. Plugin3's pytest_collection_modifyitems called until the yield point\n because it is a hook wrapper.\n\n2. Plugin1's pytest_collection_modifyitems is called because it is marked\n with ``tryfirst=True``.\n\n3. Plugin2's pytest_collection_modifyitems is called because it is marked\n with ``trylast=True`` (but even without this mark it would come after\n Plugin1).\n\n4. Plugin3's pytest_collection_modifyitems then executing the code after the yield\n point. The yield receives a :py:class:`Result ` instance which encapsulates\n the result from calling the non-wrappers. Wrappers shall not modify the result.\n\nIt's possible to use ``tryfirst`` and ``trylast`` also in conjunction with\n``hookwrapper=True`` in which case it will influence the ordering of hookwrappers\namong each other.\n\n\nDeclaring new hooks\n------------------------\n\n.. currentmodule:: _pytest.hookspec\n\nPlugins and ``conftest.py`` files may declare new hooks that can then be\nimplemented by other plugins in order to alter behaviour or interact with\nthe new plugin:\n\n.. autofunction:: pytest_addhooks\n :noindex:\n\nHooks are usually declared as do-nothing functions that contain only\ndocumentation describing when the hook will be called and what return values\nare expected.\n\nFor an example, see `newhooks.py`_ from `xdist `_.\n\n.. _`newhooks.py`: https://github.com/pytest-dev/pytest-xdist/blob/974bd566c599dc6a9ea291838c6f226197208b46/xdist/newhooks.py\n\n\nOptionally using hooks from 3rd party plugins\n---------------------------------------------\n\nUsing new hooks from plugins as explained above might be a little tricky\nbecause of the standard :ref:`validation mechanism `:\nif you depend on a plugin that is not installed, validation will fail and\nthe error message will not make much sense to your users.\n\nOne approach is to defer the hook implementation to a new plugin instead of\ndeclaring the hook functions directly in your plugin module, for example:\n\n.. code-block:: python\n\n # contents of myplugin.py\n\n\n class DeferPlugin(object):\n \"\"\"Simple plugin to defer pytest-xdist hook functions.\"\"\"\n\n def pytest_testnodedown(self, node, error):\n \"\"\"standard xdist hook function.\n \"\"\"\n\n\n def pytest_configure(config):\n if config.pluginmanager.hasplugin(\"xdist\"):\n config.pluginmanager.register(DeferPlugin())\n\nThis has the added benefit of allowing you to conditionally install hooks\ndepending on which plugins are installed.\n"},{"col":0,"comment":"null","endLoc":56,"header":"def setup(\n *,\n name: str = ...,\n version: str = ...,\n description: str = ...,\n long_description: str = ...,\n author: str = ...,\n author_email: str = ...,\n maintainer: str = ...,\n maintainer_email: str = ...,\n url: str = ...,\n download_url: str = ...,\n packages: list[str] = ...,\n py_modules: list[str] = ...,\n scripts: list[str] = ...,\n ext_modules: list[Extension] = ...,\n classifiers: list[str] = ...,\n distclass: type[Distribution] = ...,\n script_name: str = ...,\n script_args: list[str] = ...,\n options: Mapping[str, Any] = ...,\n license: str = ...,\n keywords: list[str] | str = ...,\n platforms: list[str] | str = ...,\n cmdclass: Mapping[str, type[Command]] = ...,\n data_files: list[tuple[str, list[str]]] = ...,\n package_dir: Mapping[str, str] = ...,\n obsoletes: list[str] = ...,\n provides: list[str] = ...,\n requires: list[str] = ...,\n command_packages: list[str] = ...,\n command_options: Mapping[str, Mapping[str, tuple[Any, Any]]] = ...,\n package_data: Mapping[str, list[str]] = ...,\n include_package_data: bool | Literal[0, 1] = ...,\n libraries: list[str] = ...,\n headers: list[str] = ...,\n ext_package: str = ...,\n include_dirs: list[str] = ...,\n password: str = ...,\n fullname: str = ...,\n **attrs: Any,\n) -> Distribution","id":51,"name":"setup","nodeType":"Function","startLoc":15,"text":"def setup(\n *,\n name: str = ...,\n version: str = ...,\n description: str = ...,\n long_description: str = ...,\n author: str = ...,\n author_email: str = ...,\n maintainer: str = ...,\n maintainer_email: str = ...,\n url: str = ...,\n download_url: str = ...,\n packages: list[str] = ...,\n py_modules: list[str] = ...,\n scripts: list[str] = ...,\n ext_modules: list[Extension] = ...,\n classifiers: list[str] = ...,\n distclass: type[Distribution] = ...,\n script_name: str = ...,\n script_args: list[str] = ...,\n options: Mapping[str, Any] = ...,\n license: str = ...,\n keywords: list[str] | str = ...,\n platforms: list[str] | str = ...,\n cmdclass: Mapping[str, type[Command]] = ...,\n data_files: list[tuple[str, list[str]]] = ...,\n package_dir: Mapping[str, str] = ...,\n obsoletes: list[str] = ...,\n provides: list[str] = ...,\n requires: list[str] = ...,\n command_packages: list[str] = ...,\n command_options: Mapping[str, Mapping[str, tuple[Any, Any]]] = ...,\n package_data: Mapping[str, list[str]] = ...,\n include_package_data: bool | Literal[0, 1] = ...,\n libraries: list[str] = ...,\n headers: list[str] = ...,\n ext_package: str = ...,\n include_dirs: list[str] = ...,\n password: str = ...,\n fullname: str = ...,\n **attrs: Any,\n) -> Distribution: ..."},{"fileName":"test_failures.py","filePath":"doc/en/example/assertion","id":52,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport py\n\nfailure_demo = py.path.local(__file__).dirpath(\"failure_demo.py\")\npytest_plugins = (\"pytester\",)\n\n\ndef test_failure_demo_fails_properly(testdir):\n target = testdir.tmpdir.join(failure_demo.basename)\n failure_demo.copy(target)\n failure_demo.copy(testdir.tmpdir.join(failure_demo.basename))\n result = testdir.runpytest(target, syspathinsert=True)\n result.stdout.fnmatch_lines([\"*44 failed*\"])\n assert result.ret != 0\n"},{"col":0,"comment":"null","endLoc":14,"header":"def test_failure_demo_fails_properly(testdir)","id":53,"name":"test_failure_demo_fails_properly","nodeType":"Function","startLoc":8,"text":"def test_failure_demo_fails_properly(testdir):\n target = testdir.tmpdir.join(failure_demo.basename)\n failure_demo.copy(target)\n failure_demo.copy(testdir.tmpdir.join(failure_demo.basename))\n result = testdir.runpytest(target, syspathinsert=True)\n result.stdout.fnmatch_lines([\"*44 failed*\"])\n assert result.ret != 0"},{"col":4,"comment":"null","endLoc":96,"header":"@property\n def __class__(self) -> type[Self]","id":54,"name":"__class__","nodeType":"Function","startLoc":95,"text":"@property\n def __class__(self) -> type[Self]: ..."},{"col":4,"comment":"null","endLoc":99,"header":"@__class__.setter\n def __class__(self, __type: type[object]) -> None","id":55,"name":"__class__","nodeType":"Function","startLoc":98,"text":"@__class__.setter\n def __class__(self, __type: type[object]) -> None: ... # noqa: F811"},{"col":4,"comment":"null","endLoc":100,"header":"def __init__(self) -> None","id":56,"name":"__init__","nodeType":"Function","startLoc":100,"text":"def __init__(self) -> None: ..."},{"col":4,"comment":"null","endLoc":101,"header":"def __new__(cls) -> Self","id":57,"name":"__new__","nodeType":"Function","startLoc":101,"text":"def __new__(cls) -> Self: ..."},{"col":4,"comment":"null","endLoc":104,"header":"def __setattr__(self, __name: str, __value: Any) -> None","id":58,"name":"__setattr__","nodeType":"Function","startLoc":104,"text":"def __setattr__(self, __name: str, __value: Any) -> None: ..."},{"col":4,"comment":"null","endLoc":105,"header":"def __delattr__(self, __name: str) -> None","id":59,"name":"__delattr__","nodeType":"Function","startLoc":105,"text":"def __delattr__(self, __name: str) -> None: ..."},{"col":4,"comment":"null","endLoc":106,"header":"def __eq__(self, __value: object) -> bool","id":60,"name":"__eq__","nodeType":"Function","startLoc":106,"text":"def __eq__(self, __value: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":107,"header":"def __ne__(self, __value: object) -> bool","id":61,"name":"__ne__","nodeType":"Function","startLoc":107,"text":"def __ne__(self, __value: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":108,"header":"def __str__(self) -> str","id":62,"name":"__str__","nodeType":"Function","startLoc":108,"text":"def __str__(self) -> str: ... # noqa: Y029"},{"col":4,"comment":"null","endLoc":109,"header":"def __repr__(self) -> str","id":63,"name":"__repr__","nodeType":"Function","startLoc":109,"text":"def __repr__(self) -> str: ... # noqa: Y029"},{"col":4,"comment":"null","endLoc":110,"header":"def __hash__(self) -> int","id":64,"name":"__hash__","nodeType":"Function","startLoc":110,"text":"def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":111,"header":"def __format__(self, __format_spec: str) -> str","id":65,"name":"__format__","nodeType":"Function","startLoc":111,"text":"def __format__(self, __format_spec: str) -> str: ..."},{"col":4,"comment":"null","endLoc":112,"header":"def __getattribute__(self, __name: str) -> Any","id":66,"name":"__getattribute__","nodeType":"Function","startLoc":112,"text":"def __getattribute__(self, __name: str) -> Any: ..."},{"col":4,"comment":"null","endLoc":113,"header":"def __sizeof__(self) -> int","id":67,"name":"__sizeof__","nodeType":"Function","startLoc":113,"text":"def __sizeof__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":116,"header":"def __reduce__(self) -> str | tuple[Any, ...]","id":68,"name":"__reduce__","nodeType":"Function","startLoc":116,"text":"def __reduce__(self) -> str | tuple[Any, ...]: ..."},{"col":8,"comment":"null","endLoc":118,"header":"def __reduce_ex__(self, __protocol: SupportsIndex) -> str | tuple[Any, ...]","id":69,"name":"__reduce_ex__","nodeType":"Function","startLoc":118,"text":"def __reduce_ex__(self, __protocol: SupportsIndex) -> str | tuple[Any, ...]: ..."},{"col":4,"comment":"null","endLoc":124,"header":"def __dir__(self) -> Iterable[str]","id":70,"name":"__dir__","nodeType":"Function","startLoc":124,"text":"def __dir__(self) -> Iterable[str]: ..."},{"col":4,"comment":"null","endLoc":125,"header":"def __init_subclass__(cls) -> None","id":71,"name":"__init_subclass__","nodeType":"Function","startLoc":125,"text":"def __init_subclass__(cls) -> None: ..."},{"col":4,"comment":"null","endLoc":127,"header":"@classmethod\n def __subclasshook__(cls, __subclass: type) -> bool","id":72,"name":"__subclasshook__","nodeType":"Function","startLoc":126,"text":"@classmethod\n def __subclasshook__(cls, __subclass: type) -> bool: ..."},{"attributeType":"str | None","col":4,"comment":"null","endLoc":91,"id":73,"name":"__doc__","nodeType":"Attribute","startLoc":91,"text":"__doc__"},{"attributeType":"dict","col":4,"comment":"null","endLoc":92,"id":74,"name":"__dict__","nodeType":"Attribute","startLoc":92,"text":"__dict__"},{"attributeType":"str","col":4,"comment":"null","endLoc":93,"id":75,"name":"__module__","nodeType":"Attribute","startLoc":93,"text":"__module__"},{"attributeType":"dict","col":4,"comment":"null","endLoc":94,"id":76,"name":"__annotations__","nodeType":"Attribute","startLoc":94,"text":"__annotations__"},{"col":0,"comment":"","endLoc":2,"header":"setup.py#","id":77,"name":"","nodeType":"Function","startLoc":2,"text":"if __name__ == \"__main__\":\n if \"sdist\" not in sys.argv[1:]:\n raise ValueError(\"please use 'pytest' pypi package instead of 'py.test'\")\n setup(\n name=\"py.test\",\n version=\"0.0\",\n description=\"please use 'pytest' for installation\",\n )"},{"attributeType":"_Feature","col":0,"comment":"null","endLoc":12,"id":78,"name":"division","nodeType":"Attribute","startLoc":12,"text":"division"},{"attributeType":"_Feature","col":0,"comment":"null","endLoc":15,"id":79,"name":"print_function","nodeType":"Attribute","startLoc":15,"text":"print_function"},{"col":0,"comment":"null","endLoc":335,"header":"def getimfunc(func)","id":80,"name":"getimfunc","nodeType":"Function","startLoc":331,"text":"def getimfunc(func):\n try:\n return func.__func__\n except AttributeError:\n return func"},{"className":"File","col":4,"comment":" base class for collecting tests from a file. ","endLoc":32,"id":81,"nodeType":"Class","startLoc":31,"text":"class File:\n \"\"\" base class for collecting tests from a file. \"\"\""},{"col":4,"comment":"null","endLoc":11,"header":"def collect(self)","id":82,"name":"collect","nodeType":"Function","startLoc":10,"text":"def collect(self):\n return []"},{"col":0,"comment":"null","endLoc":17,"header":"def pytest_pycollect_makemodule(path, parent)","id":83,"name":"pytest_pycollect_makemodule","nodeType":"Function","startLoc":14,"text":"def pytest_pycollect_makemodule(path, parent):\n bn = path.basename\n if \"py3\" in bn and not py3 or (\"py2\" in bn and py3):\n return DummyCollector(path, parent=parent)"},{"col":4,"comment":"null","endLoc":1933,"header":"def __init__(self, *args: object) -> None","id":84,"name":"__init__","nodeType":"Function","startLoc":1933,"text":"def __init__(self, *args: object) -> None: ..."},{"attributeType":"bool","col":0,"comment":"null","endLoc":6,"id":85,"name":"py3","nodeType":"Attribute","startLoc":6,"text":"py3"},{"col":0,"comment":"null","endLoc":36,"header":"def test_fixtures_in_module(testdir)","id":86,"name":"test_fixtures_in_module","nodeType":"Function","startLoc":10,"text":"def test_fixtures_in_module(testdir):\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture\n def _arg0():\n \"\"\"hidden arg0 fixture\"\"\"\n @pytest.fixture\n def arg1():\n \"\"\"arg1 docstring\"\"\"\n def test_arg1(arg1):\n pass\n '''\n )\n\n result = testdir.runpytest(\"--fixtures-per-test\", p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\n \"*fixtures used by test_arg1*\",\n \"*(test_fixtures_in_module.py:9)*\",\n \"arg1\",\n \" arg1 docstring\",\n ]\n )\n assert \"_arg0\" not in result.stdout.str()"},{"attributeType":"null","col":0,"comment":"null","endLoc":4,"id":87,"name":"failure_demo","nodeType":"Attribute","startLoc":4,"text":"failure_demo"},{"attributeType":"(str)","col":0,"comment":"null","endLoc":5,"id":88,"name":"pytest_plugins","nodeType":"Attribute","startLoc":5,"text":"pytest_plugins"},{"id":89,"name":"deprecations.rst","nodeType":"TextFile","path":"doc/en","text":".. _deprecations:\n\nDeprecations and Removals\n=========================\n\nThis page lists all pytest features that are currently deprecated or have been removed in past major releases.\nThe objective is to give users a clear rationale why a certain feature has been removed, and what alternatives\nshould be used instead.\n\n.. contents::\n :depth: 3\n :local:\n\n\nDeprecated Features\n-------------------\n\nBelow is a complete list of all pytest features which are considered deprecated. Using those features will issue\n:class:`_pytest.warning_types.PytestWarning` or subclasses, which can be filtered using\n:ref:`standard warning filters `.\n\n.. _`raises message deprecated`:\n\n``\"message\"`` parameter of ``pytest.raises``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 4.1\n\nIt is a common mistake to think this parameter will match the exception message, while in fact\nit only serves to provide a custom message in case the ``pytest.raises`` check fails. To prevent\nusers from making this mistake, and because it is believed to be little used, pytest is\ndeprecating it without providing an alternative for the moment.\n\nIf you have a valid use case for this parameter, consider that to obtain the same results\nyou can just call ``pytest.fail`` manually at the end of the ``with`` statement.\n\nFor example:\n\n.. code-block:: python\n\n with pytest.raises(TimeoutError, message=\"Client got unexpected message\"):\n wait_for(websocket.recv(), 0.5)\n\n\nBecomes:\n\n.. code-block:: python\n\n with pytest.raises(TimeoutError):\n wait_for(websocket.recv(), 0.5)\n pytest.fail(\"Client got unexpected message\")\n\n\nIf you still have concerns about this deprecation and future removal, please comment on\n`issue #3974 `__.\n\n\n``pytest.config`` global\n~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 4.1\n\nThe ``pytest.config`` global object is deprecated. Instead use\n``request.config`` (via the ``request`` fixture) or if you are a plugin author\nuse the ``pytest_configure(config)`` hook. Note that many hooks can also access\nthe ``config`` object indirectly, through ``session.config`` or ``item.config`` for example.\n\n.. _raises-warns-exec:\n\n``raises`` / ``warns`` with a string as the second argument\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 4.1\n\nUse the context manager form of these instead. When necessary, invoke ``exec``\ndirectly.\n\nExample:\n\n.. code-block:: python\n\n pytest.raises(ZeroDivisionError, \"1 / 0\")\n pytest.raises(SyntaxError, \"a $ b\")\n\n pytest.warns(DeprecationWarning, \"my_function()\")\n pytest.warns(SyntaxWarning, \"assert(1, 2)\")\n\nBecomes:\n\n.. code-block:: python\n\n with pytest.raises(ZeroDivisionError):\n 1 / 0\n with pytest.raises(SyntaxError):\n exec(\"a $ b\") # exec is required for invalid syntax\n\n with pytest.warns(DeprecationWarning):\n my_function()\n with pytest.warns(SyntaxWarning):\n exec(\"assert(1, 2)\") # exec is used to avoid a top-level warning\n\n\n\n\n\n\nResult log (``--result-log``)\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\n\nThe ``--resultlog`` command line option has been deprecated: it is little used\nand there are more modern and better alternatives, for example `pytest-tap `_.\n\nThis feature will be effectively removed in pytest 4.0 as the team intends to include a better alternative in the core.\n\nIf you have any concerns, please don't hesitate to `open an issue `__.\n\nRemoved Features\n----------------\n\nAs stated in our :ref:`backwards-compatibility` policy, deprecated features are removed only in major releases after\nan appropriate period of deprecation has passed.\n\nUsing ``Class`` in custom Collectors\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nUsing objects named ``\"Class\"`` as a way to customize the type of nodes that are collected in ``Collector``\nsubclasses has been deprecated. Users instead should use ``pytest_pycollect_makeitem`` to customize node types during\ncollection.\n\nThis issue should affect only advanced plugins who create new collection types, so if you see this warning\nmessage please contact the authors so they can change the code.\n\n\nmarks in ``pytest.mark.parametrize``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nApplying marks to values of a ``pytest.mark.parametrize`` call is now deprecated. For example:\n\n.. code-block:: python\n\n @pytest.mark.parametrize(\n \"a, b\",\n [\n (3, 9),\n pytest.mark.xfail(reason=\"flaky\")(6, 36),\n (10, 100),\n (20, 200),\n (40, 400),\n (50, 500),\n ],\n )\n def test_foo(a, b):\n ...\n\nThis code applies the ``pytest.mark.xfail(reason=\"flaky\")`` mark to the ``(6, 36)`` value of the above parametrization\ncall.\n\nThis was considered hard to read and understand, and also its implementation presented problems to the code preventing\nfurther internal improvements in the marks architecture.\n\nTo update the code, use ``pytest.param``:\n\n.. code-block:: python\n\n @pytest.mark.parametrize(\n \"a, b\",\n [\n (3, 9),\n pytest.param(6, 36, marks=pytest.mark.xfail(reason=\"flaky\")),\n (10, 100),\n (20, 200),\n (40, 400),\n (50, 500),\n ],\n )\n def test_foo(a, b):\n ...\n\n\n``pytest_funcarg__`` prefix\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nIn very early pytest versions fixtures could be defined using the ``pytest_funcarg__`` prefix:\n\n.. code-block:: python\n\n def pytest_funcarg__data():\n return SomeData()\n\nSwitch over to the ``@pytest.fixture`` decorator:\n\n.. code-block:: python\n\n @pytest.fixture\n def data():\n return SomeData()\n\n\n\n[pytest] section in setup.cfg files\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\n``[pytest]`` sections in ``setup.cfg`` files should now be named ``[tool:pytest]``\nto avoid conflicts with other distutils commands.\n\n\nMetafunc.addcall\n~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\n:meth:`_pytest.python.Metafunc.addcall` was a precursor to the current parametrized mechanism. Users should use\n:meth:`_pytest.python.Metafunc.parametrize` instead.\n\nExample:\n\n.. code-block:: python\n\n def pytest_generate_tests(metafunc):\n metafunc.addcall({\"i\": 1}, id=\"1\")\n metafunc.addcall({\"i\": 2}, id=\"2\")\n\nBecomes:\n\n.. code-block:: python\n\n def pytest_generate_tests(metafunc):\n metafunc.parametrize(\"i\", [1, 2], ids=[\"1\", \"2\"])\n\n\n``cached_setup``\n~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\n``request.cached_setup`` was the precursor of the setup/teardown mechanism available to fixtures.\n\nExample:\n\n.. code-block:: python\n\n @pytest.fixture\n def db_session():\n return request.cached_setup(\n setup=Session.create, teardown=lambda session: session.close(), scope=\"module\"\n )\n\nThis should be updated to make use of standard fixture mechanisms:\n\n.. code-block:: python\n\n @pytest.fixture(scope=\"module\")\n def db_session():\n session = Session.create()\n yield session\n session.close()\n\n\nYou can consult `funcarg comparison section in the docs `_ for\nmore information.\n\n\npytest_plugins in non-top-level conftest files\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nDefining ``pytest_plugins`` is now deprecated in non-top-level conftest.py\nfiles because they will activate referenced plugins *globally*, which is surprising because for all other pytest\nfeatures ``conftest.py`` files are only *active* for tests at or below it.\n\n\n``Config.warn`` and ``Node.warn``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nThose methods were part of the internal pytest warnings system, but since ``3.8`` pytest is using the builtin warning\nsystem for its own warnings, so those two functions are now deprecated.\n\n``Config.warn`` should be replaced by calls to the standard ``warnings.warn``, example:\n\n.. code-block:: python\n\n config.warn(\"C1\", \"some warning\")\n\nBecomes:\n\n.. code-block:: python\n\n warnings.warn(pytest.PytestWarning(\"some warning\"))\n\n``Node.warn`` now supports two signatures:\n\n* ``node.warn(PytestWarning(\"some message\"))``: is now the **recommended** way to call this function.\n The warning instance must be a PytestWarning or subclass.\n\n* ``node.warn(\"CI\", \"some message\")``: this code/message form has been **removed** and should be converted to the warning instance form above.\n\nrecord_xml_property\n~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nThe ``record_xml_property`` fixture is now deprecated in favor of the more generic ``record_property``, which\ncan be used by other consumers (for example ``pytest-html``) to obtain custom information about the test run.\n\nThis is just a matter of renaming the fixture as the API is the same:\n\n.. code-block:: python\n\n def test_foo(record_xml_property):\n ...\n\nChange to:\n\n.. code-block:: python\n\n def test_foo(record_property):\n ...\n\n\nPassing command-line string to ``pytest.main()``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nPassing a command-line string to ``pytest.main()`` is deprecated:\n\n.. code-block:: python\n\n pytest.main(\"-v -s\")\n\nPass a list instead:\n\n.. code-block:: python\n\n pytest.main([\"-v\", \"-s\"])\n\n\nBy passing a string, users expect that pytest will interpret that command-line using the shell rules they are working\non (for example ``bash`` or ``Powershell``), but this is very hard/impossible to do in a portable way.\n\n\nCalling fixtures directly\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nCalling a fixture function directly, as opposed to request them in a test function, is deprecated.\n\nFor example:\n\n.. code-block:: python\n\n @pytest.fixture\n def cell():\n return ...\n\n\n @pytest.fixture\n def full_cell():\n cell = cell()\n cell.make_full()\n return cell\n\nThis is a great source of confusion to new users, which will often call the fixture functions and request them from test functions interchangeably, which breaks the fixture resolution model.\n\nIn those cases just request the function directly in the dependent fixture:\n\n.. code-block:: python\n\n @pytest.fixture\n def cell():\n return ...\n\n\n @pytest.fixture\n def full_cell(cell):\n cell.make_full()\n return cell\n\nAlternatively if the fixture function is called multiple times inside a test (making it hard to apply the above pattern) or\nif you would like to make minimal changes to the code, you can create a fixture which calls the original function together\nwith the ``name`` parameter:\n\n.. code-block:: python\n\n def cell():\n return ...\n\n\n @pytest.fixture(name=\"cell\")\n def cell_fixture():\n return cell()\n\n\n``yield`` tests\n~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\npytest supported ``yield``-style tests, where a test function actually ``yield`` functions and values\nthat are then turned into proper test methods. Example:\n\n.. code-block:: python\n\n def check(x, y):\n assert x ** x == y\n\n\n def test_squared():\n yield check, 2, 4\n yield check, 3, 9\n\nThis would result into two actual test functions being generated.\n\nThis form of test function doesn't support fixtures properly, and users should switch to ``pytest.mark.parametrize``:\n\n.. code-block:: python\n\n @pytest.mark.parametrize(\"x, y\", [(2, 4), (3, 9)])\n def test_squared(x, y):\n assert x ** x == y\n\nInternal classes accessed through ``Node``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nAccess of ``Module``, ``Function``, ``Class``, ``Instance``, ``File`` and ``Item`` through ``Node`` instances now issue\nthis warning::\n\n usage of Function.Module is deprecated, please use pytest.Module instead\n\nUsers should just ``import pytest`` and access those objects using the ``pytest`` module.\n\nThis has been documented as deprecated for years, but only now we are actually emitting deprecation warnings.\n\n``Node.get_marker``\n~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nAs part of a large :ref:`marker-revamp`, :meth:`_pytest.nodes.Node.get_marker` is deprecated. See\n:ref:`the documentation ` on tips on how to update your code.\n\n\n``somefunction.markname``\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nAs part of a large :ref:`marker-revamp` we already deprecated using ``MarkInfo``\nthe only correct way to get markers of an element is via ``node.iter_markers(name)``.\n\n\n``pytest_namespace``\n~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nThis hook is deprecated because it greatly complicates the pytest internals regarding configuration and initialization, making some\nbug fixes and refactorings impossible.\n\nExample of usage:\n\n.. code-block:: python\n\n class MySymbol:\n ...\n\n\n def pytest_namespace():\n return {\"my_symbol\": MySymbol()}\n\n\nPlugin authors relying on this hook should instead require that users now import the plugin modules directly (with an appropriate public API).\n\nAs a stopgap measure, plugin authors may still inject their names into pytest's namespace, usually during ``pytest_configure``:\n\n.. code-block:: python\n\n import pytest\n\n\n def pytest_configure():\n pytest.my_symbol = MySymbol()\n\n\n\n\nReinterpretation mode (``--assert=reinterp``)\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 3.0\n\nReinterpretation mode has now been removed and only plain and rewrite\nmode are available, consequently the ``--assert=reinterp`` option is\nno longer available. This also means files imported from plugins or\n``conftest.py`` will not benefit from improved assertions by\ndefault, you should use ``pytest.register_assert_rewrite()`` to\nexplicitly turn on assertion rewriting for those files.\n\nRemoved command-line options\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 3.0\n\nThe following deprecated commandline options were removed:\n\n* ``--genscript``: no longer supported;\n* ``--no-assert``: use ``--assert=plain`` instead;\n* ``--nomagic``: use ``--assert=plain`` instead;\n* ``--report``: use ``-r`` instead;\n\npy.test-X* entry points\n~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 3.0\n\nRemoved all ``py.test-X*`` entry points. The versioned, suffixed entry points\nwere never documented and a leftover from a pre-virtualenv era. These entry\npoints also created broken entry points in wheels, so removing them also\nremoves a source of confusion for users.\n"},{"id":90,"name":"skipping.rst","nodeType":"TextFile","path":"doc/en","text":".. _`skip and xfail`:\n\n.. _skipping:\n\nSkip and xfail: dealing with tests that cannot succeed\n======================================================\n\nYou can mark test functions that cannot be run on certain platforms\nor that you expect to fail so pytest can deal with them accordingly and\npresent a summary of the test session, while keeping the test suite *green*.\n\nA **skip** means that you expect your test to pass only if some conditions are met,\notherwise pytest should skip running the test altogether. Common examples are skipping\nwindows-only tests on non-windows platforms, or skipping tests that depend on an external\nresource which is not available at the moment (for example a database).\n\nA **xfail** means that you expect a test to fail for some reason.\nA common example is a test for a feature not yet implemented, or a bug not yet fixed.\nWhen a test passes despite being expected to fail (marked with ``pytest.mark.xfail``),\nit's an **xpass** and will be reported in the test summary.\n\n``pytest`` counts and lists *skip* and *xfail* tests separately. Detailed\ninformation about skipped/xfailed tests is not shown by default to avoid\ncluttering the output. You can use the ``-r`` option to see details\ncorresponding to the \"short\" letters shown in the test progress:\n\n.. code-block:: bash\n\n pytest -rxXs # show extra info on xfailed, xpassed, and skipped tests\n\nMore details on the ``-r`` option can be found by running ``pytest -h``.\n\n(See :ref:`how to change command line options defaults`)\n\n.. _skipif:\n.. _skip:\n.. _`condition booleans`:\n\nSkipping test functions\n-----------------------\n\n\n\nThe simplest way to skip a test function is to mark it with the ``skip`` decorator\nwhich may be passed an optional ``reason``:\n\n.. code-block:: python\n\n @pytest.mark.skip(reason=\"no way of currently testing this\")\n def test_the_unknown():\n ...\n\n\nAlternatively, it is also possible to skip imperatively during test execution or setup\nby calling the ``pytest.skip(reason)`` function:\n\n.. code-block:: python\n\n def test_function():\n if not valid_config():\n pytest.skip(\"unsupported configuration\")\n\nThe imperative method is useful when it is not possible to evaluate the skip condition\nduring import time.\n\nIt is also possible to skip the whole module using\n``pytest.skip(reason, allow_module_level=True)`` at the module level:\n\n.. code-block:: python\n\n import sys\n import pytest\n\n if not sys.platform.startswith(\"win\"):\n pytest.skip(\"skipping windows-only tests\", allow_module_level=True)\n\n\n**Reference**: :ref:`pytest.mark.skip ref`\n\n``skipif``\n~~~~~~~~~~\n\n\n\nIf you wish to skip something conditionally then you can use ``skipif`` instead.\nHere is an example of marking a test function to be skipped\nwhen run on an interpreter earlier than Python3.6:\n\n.. code-block:: python\n\n import sys\n\n\n @pytest.mark.skipif(sys.version_info < (3, 6), reason=\"requires python3.6 or higher\")\n def test_function():\n ...\n\nIf the condition evaluates to ``True`` during collection, the test function will be skipped,\nwith the specified reason appearing in the summary when using ``-rs``.\n\nYou can share ``skipif`` markers between modules. Consider this test module:\n\n.. code-block:: python\n\n # content of test_mymodule.py\n import mymodule\n\n minversion = pytest.mark.skipif(\n mymodule.__versioninfo__ < (1, 1), reason=\"at least mymodule-1.1 required\"\n )\n\n\n @minversion\n def test_function():\n ...\n\nYou can import the marker and reuse it in another test module:\n\n.. code-block:: python\n\n # test_myothermodule.py\n from test_mymodule import minversion\n\n\n @minversion\n def test_anotherfunction():\n ...\n\nFor larger test suites it's usually a good idea to have one file\nwhere you define the markers which you then consistently apply\nthroughout your test suite.\n\nAlternatively, you can use :ref:`condition strings\n` instead of booleans, but they can't be shared between modules easily\nso they are supported mainly for backward compatibility reasons.\n\n**Reference**: :ref:`pytest.mark.skipif ref`\n\n\nSkip all test functions of a class or module\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can use the ``skipif`` marker (as any other marker) on classes:\n\n.. code-block:: python\n\n @pytest.mark.skipif(sys.platform == \"win32\", reason=\"does not run on windows\")\n class TestPosixCalls(object):\n def test_function(self):\n \"will not be setup or run under 'win32' platform\"\n\nIf the condition is ``True``, this marker will produce a skip result for\neach of the test methods of that class.\n\nIf you want to skip all test functions of a module, you may use\nthe ``pytestmark`` name on the global level:\n\n.. code-block:: python\n\n # test_module.py\n pytestmark = pytest.mark.skipif(...)\n\nIf multiple ``skipif`` decorators are applied to a test function, it\nwill be skipped if any of the skip conditions is true.\n\n.. _`whole class- or module level`: mark.html#scoped-marking\n\n\nSkipping files or directories\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nSometimes you may need to skip an entire file or directory, for example if the\ntests rely on Python version-specific features or contain code that you do not\nwish pytest to run. In this case, you must exclude the files and directories\nfrom collection. Refer to :ref:`customizing-test-collection` for more\ninformation.\n\n\nSkipping on a missing import dependency\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can use the following helper at module level\nor within a test or test setup function::\n\n docutils = pytest.importorskip(\"docutils\")\n\nIf ``docutils`` cannot be imported here, this will lead to a\nskip outcome of the test. You can also skip based on the\nversion number of a library::\n\n docutils = pytest.importorskip(\"docutils\", minversion=\"0.3\")\n\nThe version will be read from the specified\nmodule's ``__version__`` attribute.\n\nSummary\n~~~~~~~\n\nHere's a quick guide on how to skip tests in a module in different situations:\n\n1. Skip all tests in a module unconditionally:\n\n .. code-block:: python\n\n pytestmark = pytest.mark.skip(\"all tests still WIP\")\n\n2. Skip all tests in a module based on some condition:\n\n .. code-block:: python\n\n pytestmark = pytest.mark.skipif(sys.platform == \"win32\", reason=\"tests for linux only\")\n\n3. Skip all tests in a module if some import is missing:\n\n .. code-block:: python\n\n pexpect = pytest.importorskip(\"pexpect\")\n\n\n.. _xfail:\n\nXFail: mark test functions as expected to fail\n----------------------------------------------\n\nYou can use the ``xfail`` marker to indicate that you\nexpect a test to fail::\n\n @pytest.mark.xfail\n def test_function():\n ...\n\nThis test will be run but no traceback will be reported\nwhen it fails. Instead terminal reporting will list it in the\n\"expected to fail\" (``XFAIL``) or \"unexpectedly passing\" (``XPASS``) sections.\n\nAlternatively, you can also mark a test as ``XFAIL`` from within a test or setup function\nimperatively:\n\n.. code-block:: python\n\n def test_function():\n if not valid_config():\n pytest.xfail(\"failing configuration (but should work)\")\n\nThis will unconditionally make ``test_function`` ``XFAIL``. Note that no other code is executed\nafter ``pytest.xfail`` call, differently from the marker. That's because it is implemented\ninternally by raising a known exception.\n\n**Reference**: :ref:`pytest.mark.xfail ref`\n\n\n.. _`xfail strict tutorial`:\n\n``strict`` parameter\n~~~~~~~~~~~~~~~~~~~~\n\n\n\nBoth ``XFAIL`` and ``XPASS`` don't fail the test suite, unless the ``strict`` keyword-only\nparameter is passed as ``True``:\n\n.. code-block:: python\n\n @pytest.mark.xfail(strict=True)\n def test_function():\n ...\n\n\nThis will make ``XPASS`` (\"unexpectedly passing\") results from this test to fail the test suite.\n\nYou can change the default value of the ``strict`` parameter using the\n``xfail_strict`` ini option:\n\n.. code-block:: ini\n\n [pytest]\n xfail_strict=true\n\n\n``reason`` parameter\n~~~~~~~~~~~~~~~~~~~~\n\nAs with skipif_ you can also mark your expectation of a failure\non a particular platform:\n\n.. code-block:: python\n\n @pytest.mark.xfail(sys.version_info >= (3, 6), reason=\"python3.6 api changes\")\n def test_function():\n ...\n\n\n``raises`` parameter\n~~~~~~~~~~~~~~~~~~~~\n\nIf you want to be more specific as to why the test is failing, you can specify\na single exception, or a tuple of exceptions, in the ``raises`` argument.\n\n.. code-block:: python\n\n @pytest.mark.xfail(raises=RuntimeError)\n def test_function():\n ...\n\nThen the test will be reported as a regular failure if it fails with an\nexception not mentioned in ``raises``.\n\n``run`` parameter\n~~~~~~~~~~~~~~~~~\n\nIf a test should be marked as xfail and reported as such but should not be\neven executed, use the ``run`` parameter as ``False``:\n\n.. code-block:: python\n\n @pytest.mark.xfail(run=False)\n def test_function():\n ...\n\nThis is specially useful for xfailing tests that are crashing the interpreter and should be\ninvestigated later.\n\n\nIgnoring xfail\n~~~~~~~~~~~~~~\n\nBy specifying on the commandline:\n\n.. code-block:: bash\n\n pytest --runxfail\n\nyou can force the running and reporting of an ``xfail`` marked test\nas if it weren't marked at all. This also causes ``pytest.xfail`` to produce no effect.\n\nExamples\n~~~~~~~~\n\nHere is a simple test file with the several usages:\n\n.. literalinclude:: example/xfail_demo.py\n\nRunning it with the report-on-xfail option gives this output:\n\n.. code-block:: pytest\n\n example $ pytest -rx xfail_demo.py\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR/example\n collected 7 items\n\n xfail_demo.py xxxxxxx [100%]\n\n ========================= short test summary info ==========================\n XFAIL xfail_demo.py::test_hello\n XFAIL xfail_demo.py::test_hello2\n reason: [NOTRUN]\n XFAIL xfail_demo.py::test_hello3\n condition: hasattr(os, 'sep')\n XFAIL xfail_demo.py::test_hello4\n bug 110\n XFAIL xfail_demo.py::test_hello5\n condition: pytest.__version__[0] != \"17\"\n XFAIL xfail_demo.py::test_hello6\n reason: reason\n XFAIL xfail_demo.py::test_hello7\n ======================== 7 xfailed in 0.12 seconds =========================\n\n.. _`skip/xfail with parametrize`:\n\nSkip/xfail with parametrize\n---------------------------\n\nIt is possible to apply markers like skip and xfail to individual\ntest instances when using parametrize:\n\n.. code-block:: python\n\n import pytest\n\n\n @pytest.mark.parametrize(\n (\"n\", \"expected\"),\n [\n (1, 2),\n pytest.param(1, 0, marks=pytest.mark.xfail),\n pytest.param(1, 3, marks=pytest.mark.xfail(reason=\"some bug\")),\n (2, 3),\n (3, 4),\n (4, 5),\n pytest.param(\n 10, 11, marks=pytest.mark.skipif(sys.version_info >= (3, 0), reason=\"py2k\")\n ),\n ],\n )\n def test_increment(n, expected):\n assert n + 1 == expected\n"},{"col":0,"comment":"null","endLoc":83,"header":"def test_fixtures_in_conftest(testdir)","id":91,"name":"test_fixtures_in_conftest","nodeType":"Function","startLoc":39,"text":"def test_fixtures_in_conftest(testdir):\n testdir.makeconftest(\n '''\n import pytest\n @pytest.fixture\n def arg1():\n \"\"\"arg1 docstring\"\"\"\n @pytest.fixture\n def arg2():\n \"\"\"arg2 docstring\"\"\"\n @pytest.fixture\n def arg3(arg1, arg2):\n \"\"\"arg3\n docstring\n \"\"\"\n '''\n )\n p = testdir.makepyfile(\n \"\"\"\n def test_arg2(arg2):\n pass\n def test_arg3(arg3):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--fixtures-per-test\", p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\n \"*fixtures used by test_arg2*\",\n \"*(test_fixtures_in_conftest.py:2)*\",\n \"arg2\",\n \" arg2 docstring\",\n \"*fixtures used by test_arg3*\",\n \"*(test_fixtures_in_conftest.py:4)*\",\n \"arg1\",\n \" arg1 docstring\",\n \"arg2\",\n \" arg2 docstring\",\n \"arg3\",\n \" arg3\",\n \" docstring\",\n ]\n )"},{"fileName":"setup_plan.py","filePath":"testing/python","id":92,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ndef test_show_fixtures_and_test(testdir):\n \"\"\" Verifies that fixtures are not executed. \"\"\"\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def arg():\n assert False\n def test_arg(arg):\n assert False\n \"\"\"\n )\n\n result = testdir.runpytest(\"--setup-plan\", p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\"*SETUP F arg*\", \"*test_arg (fixtures used: arg)\", \"*TEARDOWN F arg*\"]\n )\n"},{"col":0,"comment":" Verifies that fixtures are not executed. ","endLoc":20,"header":"def test_show_fixtures_and_test(testdir)","id":93,"name":"test_show_fixtures_and_test","nodeType":"Function","startLoc":2,"text":"def test_show_fixtures_and_test(testdir):\n \"\"\" Verifies that fixtures are not executed. \"\"\"\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def arg():\n assert False\n def test_arg(arg):\n assert False\n \"\"\"\n )\n\n result = testdir.runpytest(\"--setup-plan\", p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\"*SETUP F arg*\", \"*test_arg (fixtures used: arg)\", \"*TEARDOWN F arg*\"]\n )"},{"col":0,"comment":"null","endLoc":120,"header":"def test_should_show_fixtures_used_by_test(testdir)","id":94,"name":"test_should_show_fixtures_used_by_test","nodeType":"Function","startLoc":86,"text":"def test_should_show_fixtures_used_by_test(testdir):\n testdir.makeconftest(\n '''\n import pytest\n @pytest.fixture\n def arg1():\n \"\"\"arg1 from conftest\"\"\"\n @pytest.fixture\n def arg2():\n \"\"\"arg2 from conftest\"\"\"\n '''\n )\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture\n def arg1():\n \"\"\"arg1 from testmodule\"\"\"\n def test_args(arg1, arg2):\n pass\n '''\n )\n result = testdir.runpytest(\"--fixtures-per-test\", p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\n \"*fixtures used by test_args*\",\n \"*(test_should_show_fixtures_used_by_test.py:6)*\",\n \"arg1\",\n \" arg1 from testmodule\",\n \"arg2\",\n \" arg2 from conftest\",\n ]\n )"},{"col":0,"comment":"","endLoc":2,"header":"test_failures.py#","id":95,"name":"","nodeType":"Function","startLoc":2,"text":"failure_demo = py.path.local(__file__).dirpath(\"failure_demo.py\")\n\npytest_plugins = (\"pytester\",)"},{"col":4,"comment":"null","endLoc":8,"header":"@pytest.fixture\n def something(self, request)","id":96,"name":"something","nodeType":"Function","startLoc":6,"text":"@pytest.fixture\n def something(self, request):\n return request.instance"},{"col":4,"comment":"null","endLoc":11,"header":"def test_method(self, something)","id":97,"name":"test_method","nodeType":"Function","startLoc":10,"text":"def test_method(self, something):\n assert something is self"},{"id":98,"name":"capture.rst","nodeType":"TextFile","path":"doc/en","text":"\n.. _`captures`:\n\nCapturing of the stdout/stderr output\n=========================================================\n\nDefault stdout/stderr/stdin capturing behaviour\n---------------------------------------------------------\n\nDuring test execution any output sent to ``stdout`` and ``stderr`` is\ncaptured. If a test or a setup method fails its according captured\noutput will usually be shown along with the failure traceback. (this\nbehavior can be configured by the ``--show-capture`` command-line option).\n\nIn addition, ``stdin`` is set to a \"null\" object which will\nfail on attempts to read from it because it is rarely desired\nto wait for interactive input when running automated tests.\n\nBy default capturing is done by intercepting writes to low level\nfile descriptors. This allows to capture output from simple\nprint statements as well as output from a subprocess started by\na test.\n\nSetting capturing methods or disabling capturing\n-------------------------------------------------\n\nThere are two ways in which ``pytest`` can perform capturing:\n\n* file descriptor (FD) level capturing (default): All writes going to the\n operating system file descriptors 1 and 2 will be captured.\n\n* ``sys`` level capturing: Only writes to Python files ``sys.stdout``\n and ``sys.stderr`` will be captured. No capturing of writes to\n filedescriptors is performed.\n\n.. _`disable capturing`:\n\nYou can influence output capturing mechanisms from the command line:\n\n.. code-block:: bash\n\n pytest -s # disable all capturing\n pytest --capture=sys # replace sys.stdout/stderr with in-mem files\n pytest --capture=fd # also point filedescriptors 1 and 2 to temp file\n\n.. _printdebugging:\n\nUsing print statements for debugging\n---------------------------------------------------\n\nOne primary benefit of the default capturing of stdout/stderr output\nis that you can use print statements for debugging::\n\n # content of test_module.py\n\n def setup_function(function):\n print(\"setting up %s\" % function)\n\n def test_func1():\n assert True\n\n def test_func2():\n assert False\n\nand running this module will show you precisely the output\nof the failing function and hide the other one:\n\n.. code-block:: pytest\n\n $ pytest\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 2 items\n\n test_module.py .F [100%]\n\n ================================= FAILURES =================================\n ________________________________ test_func2 ________________________________\n\n def test_func2():\n > assert False\n E assert False\n\n test_module.py:9: AssertionError\n -------------------------- Captured stdout setup ---------------------------\n setting up \n ==================== 1 failed, 1 passed in 0.12 seconds ====================\n\nAccessing captured output from a test function\n---------------------------------------------------\n\nThe ``capsys``, ``capsysbinary``, ``capfd``, and ``capfdbinary`` fixtures\nallow access to stdout/stderr output created during test execution. Here is\nan example test function that performs some output related checks:\n\n.. code-block:: python\n\n def test_myoutput(capsys): # or use \"capfd\" for fd-level\n print(\"hello\")\n sys.stderr.write(\"world\\n\")\n captured = capsys.readouterr()\n assert captured.out == \"hello\\n\"\n assert captured.err == \"world\\n\"\n print(\"next\")\n captured = capsys.readouterr()\n assert captured.out == \"next\\n\"\n\nThe ``readouterr()`` call snapshots the output so far -\nand capturing will be continued. After the test\nfunction finishes the original streams will\nbe restored. Using ``capsys`` this way frees your\ntest from having to care about setting/resetting\noutput streams and also interacts well with pytest's\nown per-test capturing.\n\nIf you want to capture on filedescriptor level you can use\nthe ``capfd`` fixture which offers the exact\nsame interface but allows to also capture output from\nlibraries or subprocesses that directly write to operating\nsystem level output streams (FD1 and FD2).\n\n\n\nThe return value from ``readouterr`` changed to a ``namedtuple`` with two attributes, ``out`` and ``err``.\n\n\n\nIf the code under test writes non-textual data, you can capture this using\nthe ``capsysbinary`` fixture which instead returns ``bytes`` from\nthe ``readouterr`` method. The ``capfsysbinary`` fixture is currently only\navailable in python 3.\n\n\n\n\nIf the code under test writes non-textual data, you can capture this using\nthe ``capfdbinary`` fixture which instead returns ``bytes`` from\nthe ``readouterr`` method. The ``capfdbinary`` fixture operates on the\nfiledescriptor level.\n\n\n\n\nTo temporarily disable capture within a test, both ``capsys``\nand ``capfd`` have a ``disabled()`` method that can be used\nas a context manager, disabling capture inside the ``with`` block:\n\n.. code-block:: python\n\n def test_disabling_capturing(capsys):\n print(\"this output is captured\")\n with capsys.disabled():\n print(\"output not captured, going directly to sys.stdout\")\n print(\"this output is also captured\")\n\n.. include:: links.inc\n"},{"col":0,"comment":"null","endLoc":159,"header":"def test_verbose_include_private_fixtures_and_loc(testdir)","id":99,"name":"test_verbose_include_private_fixtures_and_loc","nodeType":"Function","startLoc":123,"text":"def test_verbose_include_private_fixtures_and_loc(testdir):\n testdir.makeconftest(\n '''\n import pytest\n @pytest.fixture\n def _arg1():\n \"\"\"_arg1 from conftest\"\"\"\n @pytest.fixture\n def arg2(_arg1):\n \"\"\"arg2 from conftest\"\"\"\n '''\n )\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture\n def arg3():\n \"\"\"arg3 from testmodule\"\"\"\n def test_args(arg2, arg3):\n pass\n '''\n )\n result = testdir.runpytest(\"--fixtures-per-test\", \"-v\", p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\n \"*fixtures used by test_args*\",\n \"*(test_verbose_include_private_fixtures_and_loc.py:6)*\",\n \"_arg1 -- conftest.py:3\",\n \" _arg1 from conftest\",\n \"arg2 -- conftest.py:6\",\n \" arg2 from conftest\",\n \"arg3 -- test_verbose_include_private_fixtures_and_loc.py:3\",\n \" arg3 from testmodule\",\n ]\n )"},{"id":100,"name":"testing/freeze","nodeType":"Package"},{"id":101,"name":".gitignore","nodeType":"TextFile","path":"testing/freeze","text":"build/\ndist/\n*.spec\n"},{"fileName":"tox_run.py","filePath":"testing/freeze","id":102,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCalled by tox.ini: uses the generated executable to run the tests in ./tests/\ndirectory.\n\"\"\"\nif __name__ == \"__main__\":\n import os\n import sys\n\n executable = os.path.join(os.getcwd(), \"dist\", \"runtests_script\", \"runtests_script\")\n if sys.platform.startswith(\"win\"):\n executable += \".exe\"\n sys.exit(os.system(\"%s tests\" % executable))\n"},{"id":103,"name":"testing/freeze/tests","nodeType":"Package"},{"id":104,"name":"test_doctest.txt","nodeType":"TextFile","path":"testing/freeze/tests","text":"\n\nTesting doctest::\n\n >>> 1 + 1\n 2\n"},{"col":0,"comment":"null","endLoc":183,"header":"def test_doctest_items(testdir)","id":105,"name":"test_doctest_items","nodeType":"Function","startLoc":162,"text":"def test_doctest_items(testdir):\n testdir.makepyfile(\n '''\n def foo():\n \"\"\"\n >>> 1 + 1\n 2\n \"\"\"\n '''\n )\n testdir.maketxtfile(\n \"\"\"\n >>> 1 + 1\n 2\n \"\"\"\n )\n result = testdir.runpytest(\n \"--fixtures-per-test\", \"--doctest-modules\", \"--doctest-glob=*.txt\", \"-v\"\n )\n assert result.ret == 0\n\n result.stdout.fnmatch_lines([\"*collected 2 items*\"])"},{"fileName":"test_trivial.py","filePath":"testing/freeze/tests","id":106,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ndef test_upper():\n assert \"foo\".upper() == \"FOO\"\n\n\ndef test_lower():\n assert \"FOO\".lower() == \"foo\"\n"},{"col":0,"comment":"null","endLoc":3,"header":"def test_upper()","id":107,"name":"test_upper","nodeType":"Function","startLoc":2,"text":"def test_upper():\n assert \"foo\".upper() == \"FOO\""},{"fileName":"runtests_script.py","filePath":"testing/freeze","id":108,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis is the script that is actually frozen into an executable: simply executes\npy.test main().\n\"\"\"\n\nif __name__ == \"__main__\":\n import sys\n import pytest\n\n sys.exit(pytest.main())\n"},{"col":0,"comment":"","endLoc":5,"header":"runtests_script.py#","id":109,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"\nThis is the script that is actually frozen into an executable: simply executes\npy.test main().\n\"\"\"\n\nif __name__ == \"__main__\":\n import sys\n import pytest\n\n sys.exit(pytest.main())"},{"col":4,"comment":"null","endLoc":8,"header":"def setup_class(cls)","id":110,"name":"setup_class","nodeType":"Function","startLoc":7,"text":"def setup_class(cls):\n cls.classcount += 1"},{"col":4,"comment":"null","endLoc":11,"header":"def teardown_class(cls)","id":111,"name":"teardown_class","nodeType":"Function","startLoc":10,"text":"def teardown_class(cls):\n cls.classcount -= 1"},{"col":4,"comment":"null","endLoc":14,"header":"def setup_method(self, method)","id":112,"name":"setup_method","nodeType":"Function","startLoc":13,"text":"def setup_method(self, method):\n self.id = eval(method.__name__[5:])"},{"id":113,"name":"release-3.0.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.0.1\n============\n\npytest 3.0.1 has just been released to PyPI.\n\nThis release fixes some regressions reported in version 3.0.0, being a\ndrop-in replacement. To upgrade:\n\n pip install --upgrade pytest\n\nThe changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n Adam Chainz\n Andrew Svetlov\n Bruno Oliveira\n Daniel Hahler\n Dmitry Dygalo\n Florian Bruhin\n Marcin Bachry\n Ronny Pfannschmidt\n matthiasha\n\nHappy testing,\nThe py.test Development Team\n"},{"col":4,"comment":"null","endLoc":18,"header":"def test_42(self)","id":115,"name":"test_42","nodeType":"Function","startLoc":16,"text":"def test_42(self):\n assert self.classcount == 1\n assert self.id == 42"},{"attributeType":"str","col":4,"comment":"null","endLoc":10,"id":116,"name":"executable","nodeType":"Attribute","startLoc":10,"text":"executable"},{"col":4,"comment":"null","endLoc":22,"header":"def test_23(self)","id":117,"name":"test_23","nodeType":"Function","startLoc":20,"text":"def test_23(self):\n assert self.classcount == 1\n assert self.id == 23"},{"attributeType":"null","col":8,"comment":"null","endLoc":14,"id":118,"name":"id","nodeType":"Attribute","startLoc":14,"text":"self.id"},{"col":4,"comment":"null","endLoc":12,"header":"def test_method(self, something)","id":119,"name":"test_method","nodeType":"Function","startLoc":11,"text":"def test_method(self, something):\n assert something == \"test_method\""},{"col":0,"comment":"null","endLoc":7,"header":"@pytest.fixture\ndef something(request)","id":120,"name":"something","nodeType":"Function","startLoc":5,"text":"@pytest.fixture\ndef something(request):\n return request.function.__name__"},{"col":0,"comment":"null","endLoc":16,"header":"def test_func(something)","id":121,"name":"test_func","nodeType":"Function","startLoc":15,"text":"def test_func(something):\n assert something == \"test_func\""},{"col":4,"comment":"null","endLoc":13,"header":"@pytest.fixture\n def spam(self, spam)","id":122,"name":"spam","nodeType":"Function","startLoc":11,"text":"@pytest.fixture\n def spam(self, spam):\n return spam * 2"},{"col":4,"comment":"null","endLoc":16,"header":"def test_spam(self, spam)","id":123,"name":"test_spam","nodeType":"Function","startLoc":15,"text":"def test_spam(self, spam):\n assert spam == \"spamspam\""},{"col":0,"comment":"null","endLoc":7,"header":"@pytest.fixture\ndef spam()","id":124,"name":"spam","nodeType":"Function","startLoc":5,"text":"@pytest.fixture\ndef spam():\n return \"spam\""},{"col":0,"comment":"null","endLoc":7,"header":"def test_lower()","id":127,"name":"test_lower","nodeType":"Function","startLoc":6,"text":"def test_lower():\n assert \"FOO\".lower() == \"foo\""},{"attributeType":"null","col":0,"comment":"null","endLoc":40,"id":128,"name":"hookimpl","nodeType":"Attribute","startLoc":40,"text":"hookimpl"},{"id":129,"name":"src","nodeType":"Package"},{"fileName":"pytest.py","filePath":"src","id":130,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n# PYTHON_ARGCOMPLETE_OK\n\"\"\"\npytest: unit and functional testing with Python.\n\"\"\"\n# else we are imported\nfrom _pytest import __version__\nfrom _pytest.assertion import register_assert_rewrite\nfrom _pytest.config import cmdline\nfrom _pytest.config import hookimpl\nfrom _pytest.config import hookspec\nfrom _pytest.config import main\nfrom _pytest.config import UsageError\nfrom _pytest.debugging import pytestPDB as __pytestPDB\nfrom _pytest.fixtures import fillfixtures as _fillfuncargs\nfrom _pytest.fixtures import fixture\nfrom _pytest.fixtures import yield_fixture\nfrom _pytest.freeze_support import freeze_includes\nfrom _pytest.main import Session\nfrom _pytest.mark import MARK_GEN as mark\nfrom _pytest.mark import param\nfrom _pytest.nodes import Collector\nfrom _pytest.nodes import File\nfrom _pytest.nodes import Item\nfrom _pytest.outcomes import exit\nfrom _pytest.outcomes import fail\nfrom _pytest.outcomes import importorskip\nfrom _pytest.outcomes import skip\nfrom _pytest.outcomes import xfail\nfrom _pytest.python import Class\nfrom _pytest.python import Function\nfrom _pytest.python import Instance\nfrom _pytest.python import Module\nfrom _pytest.python import Package\nfrom _pytest.python_api import approx\nfrom _pytest.python_api import raises\nfrom _pytest.recwarn import deprecated_call\nfrom _pytest.recwarn import warns\nfrom _pytest.warning_types import PytestAssertRewriteWarning\nfrom _pytest.warning_types import PytestCacheWarning\nfrom _pytest.warning_types import PytestCollectionWarning\nfrom _pytest.warning_types import PytestConfigWarning\nfrom _pytest.warning_types import PytestDeprecationWarning\nfrom _pytest.warning_types import PytestExperimentalApiWarning\nfrom _pytest.warning_types import PytestUnhandledCoroutineWarning\nfrom _pytest.warning_types import PytestUnknownMarkWarning\nfrom _pytest.warning_types import PytestWarning\nfrom _pytest.warning_types import RemovedInPytest4Warning\n\nset_trace = __pytestPDB.set_trace\n\n__all__ = [\n \"__version__\",\n \"_fillfuncargs\",\n \"approx\",\n \"Class\",\n \"cmdline\",\n \"Collector\",\n \"deprecated_call\",\n \"exit\",\n \"fail\",\n \"File\",\n \"fixture\",\n \"freeze_includes\",\n \"Function\",\n \"hookimpl\",\n \"hookspec\",\n \"importorskip\",\n \"Instance\",\n \"Item\",\n \"main\",\n \"mark\",\n \"Module\",\n \"Package\",\n \"param\",\n \"PytestAssertRewriteWarning\",\n \"PytestCacheWarning\",\n \"PytestCollectionWarning\",\n \"PytestConfigWarning\",\n \"PytestDeprecationWarning\",\n \"PytestExperimentalApiWarning\",\n \"PytestUnhandledCoroutineWarning\",\n \"PytestUnknownMarkWarning\",\n \"PytestWarning\",\n \"raises\",\n \"register_assert_rewrite\",\n \"RemovedInPytest4Warning\",\n \"Session\",\n \"set_trace\",\n \"skip\",\n \"UsageError\",\n \"warns\",\n \"xfail\",\n \"yield_fixture\",\n]\n\nif __name__ == \"__main__\":\n # if run as a script or by 'python -m pytest'\n # we trigger the below \"else\" condition by the following import\n import pytest\n\n raise SystemExit(pytest.main())\nelse:\n\n from _pytest.compat import _setup_collect_fakemodule\n\n _setup_collect_fakemodule()\n"},{"attributeType":"null","col":4,"comment":"null","endLoc":9,"id":131,"name":"__version__","nodeType":"Attribute","startLoc":9,"text":"__version__"},{"fileName":"failure_demo.py","filePath":"doc/en/example/assertion","id":132,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport _pytest._code\nimport pytest\nfrom pytest import raises\n\n\ndef otherfunc(a, b):\n assert a == b\n\n\ndef somefunc(x, y):\n otherfunc(x, y)\n\n\ndef otherfunc_multi(a, b):\n assert a == b\n\n\n@pytest.mark.parametrize(\"param1, param2\", [(3, 6)])\ndef test_generative(param1, param2):\n assert param1 * 2 < param2\n\n\nclass TestFailing(object):\n def test_simple(self):\n def f():\n return 42\n\n def g():\n return 43\n\n assert f() == g()\n\n def test_simple_multiline(self):\n otherfunc_multi(42, 6 * 9)\n\n def test_not(self):\n def f():\n return 42\n\n assert not f()\n\n\nclass TestSpecialisedExplanations(object):\n def test_eq_text(self):\n assert \"spam\" == \"eggs\"\n\n def test_eq_similar_text(self):\n assert \"foo 1 bar\" == \"foo 2 bar\"\n\n def test_eq_multiline_text(self):\n assert \"foo\\nspam\\nbar\" == \"foo\\neggs\\nbar\"\n\n def test_eq_long_text(self):\n a = \"1\" * 100 + \"a\" + \"2\" * 100\n b = \"1\" * 100 + \"b\" + \"2\" * 100\n assert a == b\n\n def test_eq_long_text_multiline(self):\n a = \"1\\n\" * 100 + \"a\" + \"2\\n\" * 100\n b = \"1\\n\" * 100 + \"b\" + \"2\\n\" * 100\n assert a == b\n\n def test_eq_list(self):\n assert [0, 1, 2] == [0, 1, 3]\n\n def test_eq_list_long(self):\n a = [0] * 100 + [1] + [3] * 100\n b = [0] * 100 + [2] + [3] * 100\n assert a == b\n\n def test_eq_dict(self):\n assert {\"a\": 0, \"b\": 1, \"c\": 0} == {\"a\": 0, \"b\": 2, \"d\": 0}\n\n def test_eq_set(self):\n assert {0, 10, 11, 12} == {0, 20, 21}\n\n def test_eq_longer_list(self):\n assert [1, 2] == [1, 2, 3]\n\n def test_in_list(self):\n assert 1 in [0, 2, 3, 4, 5]\n\n def test_not_in_text_multiline(self):\n text = \"some multiline\\ntext\\nwhich\\nincludes foo\\nand a\\ntail\"\n assert \"foo\" not in text\n\n def test_not_in_text_single(self):\n text = \"single foo line\"\n assert \"foo\" not in text\n\n def test_not_in_text_single_long(self):\n text = \"head \" * 50 + \"foo \" + \"tail \" * 20\n assert \"foo\" not in text\n\n def test_not_in_text_single_long_term(self):\n text = \"head \" * 50 + \"f\" * 70 + \"tail \" * 20\n assert \"f\" * 70 not in text\n\n def test_eq_dataclass(self):\n from dataclasses import dataclass\n\n @dataclass\n class Foo(object):\n a: int\n b: str\n\n left = Foo(1, \"b\")\n right = Foo(1, \"c\")\n assert left == right\n\n def test_eq_attrs(self):\n import attr\n\n @attr.s\n class Foo(object):\n a = attr.ib()\n b = attr.ib()\n\n left = Foo(1, \"b\")\n right = Foo(1, \"c\")\n assert left == right\n\n\ndef test_attribute():\n class Foo(object):\n b = 1\n\n i = Foo()\n assert i.b == 2\n\n\ndef test_attribute_instance():\n class Foo(object):\n b = 1\n\n assert Foo().b == 2\n\n\ndef test_attribute_failure():\n class Foo(object):\n def _get_b(self):\n raise Exception(\"Failed to get attrib\")\n\n b = property(_get_b)\n\n i = Foo()\n assert i.b == 2\n\n\ndef test_attribute_multiple():\n class Foo(object):\n b = 1\n\n class Bar(object):\n b = 2\n\n assert Foo().b == Bar().b\n\n\ndef globf(x):\n return x + 1\n\n\nclass TestRaises(object):\n def test_raises(self):\n s = \"qwe\"\n raises(TypeError, int, s)\n\n def test_raises_doesnt(self):\n raises(IOError, int, \"3\")\n\n def test_raise(self):\n raise ValueError(\"demo error\")\n\n def test_tupleerror(self):\n a, b = [1] # NOQA\n\n def test_reinterpret_fails_with_print_for_the_fun_of_it(self):\n items = [1, 2, 3]\n print(\"items is %r\" % items)\n a, b = items.pop()\n\n def test_some_error(self):\n if namenotexi: # NOQA\n pass\n\n def func1(self):\n assert 41 == 42\n\n\n# thanks to Matthew Scott for this test\ndef test_dynamic_compile_shows_nicely():\n import imp\n import sys\n\n src = \"def foo():\\n assert 1 == 0\\n\"\n name = \"abc-123\"\n module = imp.new_module(name)\n code = _pytest._code.compile(src, name, \"exec\")\n exec(code, module.__dict__)\n sys.modules[name] = module\n module.foo()\n\n\nclass TestMoreErrors(object):\n def test_complex_error(self):\n def f():\n return 44\n\n def g():\n return 43\n\n somefunc(f(), g())\n\n def test_z1_unpack_error(self):\n items = []\n a, b = items\n\n def test_z2_type_error(self):\n items = 3\n a, b = items\n\n def test_startswith(self):\n s = \"123\"\n g = \"456\"\n assert s.startswith(g)\n\n def test_startswith_nested(self):\n def f():\n return \"123\"\n\n def g():\n return \"456\"\n\n assert f().startswith(g())\n\n def test_global_func(self):\n assert isinstance(globf(42), float)\n\n def test_instance(self):\n self.x = 6 * 7\n assert self.x != 42\n\n def test_compare(self):\n assert globf(10) < 5\n\n def test_try_finally(self):\n x = 1\n try:\n assert x == 0\n finally:\n x = 0\n\n\nclass TestCustomAssertMsg(object):\n def test_single_line(self):\n class A(object):\n a = 1\n\n b = 2\n assert A.a == b, \"A.a appears not to be b\"\n\n def test_multiline(self):\n class A(object):\n a = 1\n\n b = 2\n assert (\n A.a == b\n ), \"A.a appears not to be b\\nor does not appear to be b\\none of those\"\n\n def test_custom_repr(self):\n class JSON(object):\n a = 1\n\n def __repr__(self):\n return \"This is JSON\\n{\\n 'foo': 'bar'\\n}\"\n\n a = JSON()\n b = 2\n assert a.a == b, a\n"},{"id":135,"name":"release-2.0.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"py.test 2.0.0: asserts++, unittest++, reporting++, config++, docs++\n===========================================================================\n\nWelcome to pytest-2.0.0, a major new release of \"py.test\", the rapid\neasy Python testing tool. There are many new features and enhancements,\nsee below for summary and detailed lists. A lot of long-deprecated code\nhas been removed, resulting in a much smaller and cleaner\nimplementation. See the new docs with examples here:\n\n http://pytest.org/2.0.0/index.html\n\nA note on packaging: pytest used to part of the \"py\" distribution up\nuntil version py-1.3.4 but this has changed now: pytest-2.0.0 only\ncontains py.test related code and is expected to be backward-compatible\nto existing test code. If you want to install pytest, just type one of::\n\n pip install -U pytest\n easy_install -U pytest\n\nMany thanks to all issue reporters and people asking questions or\ncomplaining. Particular thanks to Floris Bruynooghe and Ronny Pfannschmidt\nfor their great coding contributions and many others for feedback and help.\n\nbest,\nholger krekel\n\n\nNew Features\n-----------------------\n\n- new invocations through Python interpreter and from Python::\n\n python -m pytest # on all pythons >= 2.5\n\n or from a python program::\n\n import pytest ; pytest.main(arglist, pluginlist)\n\n see http://pytest.org/2.0.0/usage.html for details.\n\n- new and better reporting information in assert expressions\n if comparing lists, sequences or strings.\n\n see http://pytest.org/2.0.0/assert.html#newreport\n\n- new configuration through ini-files (setup.cfg or tox.ini recognized),\n for example::\n\n [pytest]\n norecursedirs = .hg data* # don't ever recurse in such dirs\n addopts = -x --pyargs # add these command line options by default\n\n see http://pytest.org/2.0.0/customize.html\n\n- improved standard unittest support. In general py.test should now\n better be able to run custom unittest.TestCases like twisted trial\n or Django based TestCases. Also you can now run the tests of an\n installed 'unittest' package with py.test::\n\n py.test --pyargs unittest\n\n- new \"-q\" option which decreases verbosity and prints a more\n nose/unittest-style \"dot\" output.\n\n- many many more detailed improvements details\n\nFixes\n-----------------------\n\n- fix issue126 - introduce py.test.set_trace() to trace execution via\n PDB during the running of tests even if capturing is ongoing.\n- fix issue124 - make reporting more resilient against tests opening\n files on filedescriptor 1 (stdout).\n- fix issue109 - sibling conftest.py files will not be loaded.\n (and Directory collectors cannot be customized anymore from a Directory's\n conftest.py - this needs to happen at least one level up).\n- fix issue88 (finding custom test nodes from command line arg)\n- fix issue93 stdout/stderr is captured while importing conftest.py\n- fix bug: unittest collected functions now also can have \"pytestmark\"\n applied at class/module level\n\nImportant Notes\n--------------------\n\n* The usual way in pre-2.0 times to use py.test in python code was\n to import \"py\" and then e.g. use \"py.test.raises\" for the helper.\n This remains valid and is not planned to be deprecated. However,\n in most examples and internal code you'll find \"import pytest\"\n and \"pytest.raises\" used as the recommended default way.\n\n* pytest now first performs collection of the complete test suite\n before running any test. This changes for example the semantics of when\n pytest_collectstart/pytest_collectreport are called. Some plugins may\n need upgrading.\n\n* The pytest package consists of a 400 LOC core.py and about 20 builtin plugins,\n summing up to roughly 5000 LOCs, including docstrings. To be fair, it also\n uses generic code from the \"pylib\", and the new \"py\" package to help\n with filesystem and introspection/code manipulation.\n\n(Incompatible) Removals\n-----------------------------\n\n- py.test.config is now only available if you are in a test run.\n\n- the following (mostly already deprecated) functionality was removed:\n\n - removed support for Module/Class/... collection node definitions\n in conftest.py files. They will cause nothing special.\n - removed support for calling the pre-1.0 collection API of \"run()\" and \"join\"\n - removed reading option values from conftest.py files or env variables.\n This can now be done much much better and easier through the ini-file\n mechanism and the \"addopts\" entry in particular.\n - removed the \"disabled\" attribute in test classes. Use the skipping\n and pytestmark mechanism to skip or xfail a test class.\n\n- py.test.collect.Directory does not exist anymore and it\n is not possible to provide an own \"Directory\" object.\n If you have used this and don't know what to do, get\n in contact. We'll figure something out.\n\n Note that pytest_collect_directory() is still called but\n any return value will be ignored. This allows to keep\n old code working that performed for example \"py.test.skip()\"\n in collect() to prevent recursion into directory trees\n if a certain dependency or command line option is missing.\n\n\nsee :ref:`changelog` for more detailed changes.\n"},{"id":136,"name":"faq.rst","nodeType":"TextFile","path":"doc/en","text":"Some Issues and Questions\n==================================\n\n.. note::\n\n This FAQ is here only mostly for historic reasons. Checkout\n `pytest Q&A at Stackoverflow `_\n for many questions and answers related to pytest and/or use\n :ref:`contact channels` to get help.\n\nOn naming, nosetests, licensing and magic\n------------------------------------------------\n\nHow does pytest relate to nose and unittest?\n+++++++++++++++++++++++++++++++++++++++++++++++++\n\n``pytest`` and nose_ share basic philosophy when it comes\nto running and writing Python tests. In fact, you can run many tests\nwritten for nose with ``pytest``. nose_ was originally created\nas a clone of ``pytest`` when ``pytest`` was in the ``0.8`` release\ncycle. Note that starting with pytest-2.0 support for running unittest\ntest suites is majorly improved.\n\nhow does pytest relate to twisted's trial?\n++++++++++++++++++++++++++++++++++++++++++++++\n\nSince some time ``pytest`` has builtin support for supporting tests\nwritten using trial. It does not itself start a reactor, however,\nand does not handle Deferreds returned from a test in pytest style.\nIf you are using trial's unittest.TestCase chances are that you can\njust run your tests even if you return Deferreds. In addition,\nthere also is a dedicated `pytest-twisted\n`_ plugin which allows you to\nreturn deferreds from pytest-style tests, allowing the use of\n:ref:`fixtures` and other features.\n\nhow does pytest work with Django?\n++++++++++++++++++++++++++++++++++++++++++++++\n\nIn 2012, some work is going into the `pytest-django plugin `_. It substitutes the usage of Django's\n``manage.py test`` and allows the use of all pytest features_ most of which\nare not available from Django directly.\n\n.. _features: features.html\n\n\nWhat's this \"magic\" with pytest? (historic notes)\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\nAround 2007 (version ``0.8``) some people thought that ``pytest``\nwas using too much \"magic\". It had been part of the `pylib`_ which\ncontains a lot of unrelated python library code. Around 2010 there\nwas a major cleanup refactoring, which removed unused or deprecated code\nand resulted in the new ``pytest`` PyPI package which strictly contains\nonly test-related code. This release also brought a complete pluginification\nsuch that the core is around 300 lines of code and everything else is\nimplemented in plugins. Thus ``pytest`` today is a small, universally runnable\nand customizable testing framework for Python. Note, however, that\n``pytest`` uses metaprogramming techniques and reading its source is\nthus likely not something for Python beginners.\n\nA second \"magic\" issue was the assert statement debugging feature.\nNowadays, ``pytest`` explicitly rewrites assert statements in test modules\nin order to provide more useful :ref:`assert feedback `.\nThis completely avoids previous issues of confusing assertion-reporting.\nIt also means, that you can use Python's ``-O`` optimization without losing\nassertions in test modules.\n\nYou can also turn off all assertion interaction using the\n``--assert=plain`` option.\n\n.. _`py namespaces`: index.html\n.. _`py/__init__.py`: http://bitbucket.org/hpk42/py-trunk/src/trunk/py/__init__.py\n\n\nWhy can I use both ``pytest`` and ``py.test`` commands?\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\npytest used to be part of the py package, which provided several developer\nutilities, all starting with ``py.``, thus providing nice TAB-completion.\nIf you install ``pip install pycmd`` you get these tools from a separate\npackage. Once ``pytest`` became a separate package, the ``py.test`` name was\nretained due to avoid a naming conflict with another tool. This conflict was\neventually resolved, and the ``pytest`` command was therefore introduced. In\nfuture versions of pytest, we may deprecate and later remove the ``py.test``\ncommand to avoid perpetuating the confusion.\n\npytest fixtures, parametrized tests\n-------------------------------------------------------\n\n.. _funcargs: funcargs.html\n\nIs using pytest fixtures versus xUnit setup a style question?\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\nFor simple applications and for people experienced with nose_ or\nunittest-style test setup using `xUnit style setup`_ probably\nfeels natural. For larger test suites, parametrized testing\nor setup of complex test resources using fixtures_ may feel more natural.\nMoreover, fixtures are ideal for writing advanced test support\ncode (like e.g. the monkeypatch_, the tmpdir_ or capture_ fixtures)\nbecause the support code can register setup/teardown functions\nin a managed class/module/function scope.\n\n.. _monkeypatch: monkeypatch.html\n.. _tmpdir: tmpdir.html\n.. _capture: capture.html\n.. _fixtures: fixture.html\n\n.. _`why pytest_pyfuncarg__ methods?`:\n\n.. _`Convention over Configuration`: http://en.wikipedia.org/wiki/Convention_over_Configuration\n\nCan I yield multiple values from a fixture function?\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\nThere are two conceptual reasons why yielding from a factory function\nis not possible:\n\n* If multiple factories yielded values there would\n be no natural place to determine the combination\n policy - in real-world examples some combinations\n often should not run.\n\n* Calling factories for obtaining test function arguments\n is part of setting up and running a test. At that\n point it is not possible to add new test calls to\n the test collection anymore.\n\nHowever, with pytest-2.3 you can use the :ref:`@pytest.fixture` decorator\nand specify ``params`` so that all tests depending on the factory-created\nresource will run multiple times with different parameters.\n\nYou can also use the ``pytest_generate_tests`` hook to\nimplement the `parametrization scheme of your choice`_. See also\n:ref:`paramexamples` for more examples.\n\n.. _`parametrization scheme of your choice`: http://tetamap.wordpress.com/2009/05/13/parametrizing-python-tests-generalized/\n\npytest interaction with other packages\n---------------------------------------------------\n\nIssues with pytest, multiprocess and setuptools?\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\nOn Windows the multiprocess package will instantiate sub processes\nby pickling and thus implicitly re-import a lot of local modules.\nUnfortunately, setuptools-0.6.11 does not ``if __name__=='__main__'``\nprotect its generated command line script. This leads to infinite\nrecursion when running a test that instantiates Processes.\n\nAs of mid-2013, there shouldn't be a problem anymore when you\nuse the standard setuptools (note that distribute has been merged\nback into setuptools which is now shipped directly with virtualenv).\n\n.. include:: links.inc\n"},{"id":137,"name":"config.yml","nodeType":"TextFile","path":".github","text":"rtd:\n project: pytest\n"},{"id":138,"name":"release-3.0.5.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.0.5\n============\n\npytest 3.0.5 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Ana Vojnovic\n* Bruno Oliveira\n* Daniel Hahler\n* Duncan Betts\n* Igor Starikov\n* Ismail\n* Luke Murphy\n* Ned Batchelder\n* Ronny Pfannschmidt\n* Sebastian Ramacher\n* nmundar\n\nHappy testing,\nThe pytest Development Team\n"},{"id":139,"name":"scripts","nodeType":"Package"},{"id":140,"name":"upload-coverage.bat","nodeType":"TextFile","path":"scripts","text":"REM script called by Azure to combine and upload coverage information to codecov\nif \"%PYTEST_COVERAGE%\" == \"1\" (\n echo Prepare to upload coverage information\n if defined CODECOV_TOKEN (\n echo CODECOV_TOKEN defined\n ) else (\n echo CODECOV_TOKEN NOT defined\n )\n python -m pip install codecov\n python -m coverage combine\n python -m coverage xml\n python -m coverage report -m\n scripts\\retry python -m codecov --required -X gcov pycov search -f coverage.xml --name %PYTEST_CODECOV_NAME%\n) else (\n echo Skipping coverage upload, PYTEST_COVERAGE=%PYTEST_COVERAGE%\n)\n"},{"id":141,"name":"release-3.4.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.4.0\n=======================================\n\nThe pytest team is proud to announce the 3.4.0 release!\n\npytest is a mature Python testing tool with more than a 1600 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n http://doc.pytest.org/en/latest/changelog.html\n\nFor complete documentation, please visit:\n\n http://docs.pytest.org\n\nAs usual, you can upgrade from pypi via:\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Aaron\n* Alan Velasco\n* Anders Hovmöller\n* Andrew Toolan\n* Anthony Sottile\n* Aron Coyle\n* Brian Maissy\n* Bruno Oliveira\n* Cyrus Maden\n* Florian Bruhin\n* Henk-Jaap Wagenaar\n* Ian Lesperance\n* Jon Dufresne\n* Jurko Gospodnetić\n* Kate\n* Kimberly\n* Per A. Brodtkorb\n* Pierre-Alexandre Fonta\n* Raphael Castaneda\n* Ronny Pfannschmidt\n* ST John\n* Segev Finer\n* Thomas Hisch\n* Tzu-ping Chung\n* feuillemorte\n\n\nHappy testing,\nThe Pytest Development Team\n"},{"col":0,"comment":" return exit code, after performing an in-process test run.\n\n :arg args: list of command line arguments.\n\n :arg plugins: list of plugin objects to be auto-registered during\n initialization.\n ","endLoc":89,"header":"def main(args=None, plugins=None)","id":142,"name":"main","nodeType":"Function","startLoc":51,"text":"def main(args=None, plugins=None):\n \"\"\" return exit code, after performing an in-process test run.\n\n :arg args: list of command line arguments.\n\n :arg plugins: list of plugin objects to be auto-registered during\n initialization.\n \"\"\"\n from _pytest.main import EXIT_USAGEERROR\n\n try:\n try:\n config = _prepareconfig(args, plugins)\n except ConftestImportFailure as e:\n exc_info = ExceptionInfo(e.excinfo)\n tw = py.io.TerminalWriter(sys.stderr)\n tw.line(\n \"ImportError while loading conftest '{e.path}'.\".format(e=e), red=True\n )\n exc_info.traceback = exc_info.traceback.filter(filter_traceback)\n exc_repr = (\n exc_info.getrepr(style=\"short\", chain=False)\n if exc_info.traceback\n else exc_info.exconly()\n )\n formatted_tb = safe_str(exc_repr)\n for line in formatted_tb.splitlines():\n tw.line(line.rstrip(), red=True)\n return 4\n else:\n try:\n return config.hook.pytest_cmdline_main(config=config)\n finally:\n config._ensure_unconfigure()\n except UsageError as e:\n tw = py.io.TerminalWriter(sys.stderr)\n for msg in e.args:\n tw.line(\"ERROR: {}\\n\".format(msg), red=True)\n return EXIT_USAGEERROR"},{"col":0,"comment":"null","endLoc":211,"header":"def _prepareconfig(args=None, plugins=None)","id":143,"name":"_prepareconfig","nodeType":"Function","startLoc":183,"text":"def _prepareconfig(args=None, plugins=None):\n warning = None\n if args is None:\n args = sys.argv[1:]\n elif isinstance(args, py.path.local):\n args = [str(args)]\n elif not isinstance(args, (tuple, list)):\n msg = \"`args` parameter expected to be a list or tuple of strings, got: {!r} (type: {})\"\n raise TypeError(msg.format(args, type(args)))\n\n config = get_config(args)\n pluginmanager = config.pluginmanager\n try:\n if plugins:\n for plugin in plugins:\n if isinstance(plugin, six.string_types):\n pluginmanager.consider_pluginarg(plugin)\n else:\n pluginmanager.register(plugin)\n if warning:\n from _pytest.warnings import _issue_warning_captured\n\n _issue_warning_captured(warning, hook=config.hook, stacklevel=4)\n return pluginmanager.hook.pytest_cmdline_parse(\n pluginmanager=pluginmanager, args=args\n )\n except BaseException:\n config._ensure_unconfigure()\n raise"},{"col":0,"comment":"\n Assert that a code block/function call raises ``expected_exception``\n or raise a failure exception otherwise.\n\n :kwparam match: if specified, a string containing a regular expression,\n or a regular expression object, that is tested against the string\n representation of the exception using ``re.search``. To match a literal\n string that may contain `special characters`__, the pattern can\n first be escaped with ``re.escape``.\n\n __ https://docs.python.org/3/library/re.html#regular-expression-syntax\n\n :kwparam message: **(deprecated since 4.1)** if specified, provides a custom failure message\n if the exception is not raised. See :ref:`the deprecation docs ` for a workaround.\n\n .. currentmodule:: _pytest._code\n\n Use ``pytest.raises`` as a context manager, which will capture the exception of the given\n type::\n\n >>> with raises(ZeroDivisionError):\n ... 1/0\n\n If the code block does not raise the expected exception (``ZeroDivisionError`` in the example\n above), or no exception at all, the check will fail instead.\n\n You can also use the keyword argument ``match`` to assert that the\n exception matches a text or regex::\n\n >>> with raises(ValueError, match='must be 0 or None'):\n ... raise ValueError(\"value must be 0 or None\")\n\n >>> with raises(ValueError, match=r'must be \\d+$'):\n ... raise ValueError(\"value must be 42\")\n\n The context manager produces an :class:`ExceptionInfo` object which can be used to inspect the\n details of the captured exception::\n\n >>> with raises(ValueError) as exc_info:\n ... raise ValueError(\"value must be 42\")\n >>> assert exc_info.type is ValueError\n >>> assert exc_info.value.args[0] == \"value must be 42\"\n\n .. deprecated:: 4.1\n\n In the context manager form you may use the keyword argument\n ``message`` to specify a custom failure message that will be displayed\n in case the ``pytest.raises`` check fails. This has been deprecated as it\n is considered error prone as users often mean to use ``match`` instead.\n See :ref:`the deprecation docs ` for a workaround.\n\n .. note::\n\n When using ``pytest.raises`` as a context manager, it's worthwhile to\n note that normal context manager rules apply and that the exception\n raised *must* be the final line in the scope of the context manager.\n Lines of code after that, within the scope of the context manager will\n not be executed. For example::\n\n >>> value = 15\n >>> with raises(ValueError) as exc_info:\n ... if value > 10:\n ... raise ValueError(\"value must be <= 10\")\n ... assert exc_info.type is ValueError # this will not execute\n\n Instead, the following approach must be taken (note the difference in\n scope)::\n\n >>> with raises(ValueError) as exc_info:\n ... if value > 10:\n ... raise ValueError(\"value must be <= 10\")\n ...\n >>> assert exc_info.type is ValueError\n\n **Using with** ``pytest.mark.parametrize``\n\n When using :ref:`pytest.mark.parametrize ref`\n it is possible to parametrize tests such that\n some runs raise an exception and others do not.\n\n See :ref:`parametrizing_conditional_raising` for an example.\n\n **Legacy form**\n\n It is possible to specify a callable by passing a to-be-called lambda::\n\n >>> raises(ZeroDivisionError, lambda: 1/0)\n \n\n or you can specify an arbitrary callable with arguments::\n\n >>> def f(x): return 1/x\n ...\n >>> raises(ZeroDivisionError, f, 0)\n \n >>> raises(ZeroDivisionError, f, x=0)\n \n\n The form above is fully supported but discouraged for new code because the\n context manager form is regarded as more readable and less error-prone.\n\n .. note::\n Similar to caught exception objects in Python, explicitly clearing\n local references to returned ``ExceptionInfo`` objects can\n help the Python interpreter speed up its garbage collection.\n\n Clearing those references breaks a reference cycle\n (``ExceptionInfo`` --> caught exception --> frame stack raising\n the exception --> current frame stack --> local variables -->\n ``ExceptionInfo``) which makes Python keep all objects referenced\n from that cycle (including all local variables in the current\n frame) alive until the next cyclic garbage collection run. See the\n official Python ``try`` statement documentation for more detailed\n information.\n\n ","endLoc":716,"header":"def raises(expected_exception, *args, **kwargs)","id":144,"name":"raises","nodeType":"Function","startLoc":556,"text":"def raises(expected_exception, *args, **kwargs):\n r\"\"\"\n Assert that a code block/function call raises ``expected_exception``\n or raise a failure exception otherwise.\n\n :kwparam match: if specified, a string containing a regular expression,\n or a regular expression object, that is tested against the string\n representation of the exception using ``re.search``. To match a literal\n string that may contain `special characters`__, the pattern can\n first be escaped with ``re.escape``.\n\n __ https://docs.python.org/3/library/re.html#regular-expression-syntax\n\n :kwparam message: **(deprecated since 4.1)** if specified, provides a custom failure message\n if the exception is not raised. See :ref:`the deprecation docs ` for a workaround.\n\n .. currentmodule:: _pytest._code\n\n Use ``pytest.raises`` as a context manager, which will capture the exception of the given\n type::\n\n >>> with raises(ZeroDivisionError):\n ... 1/0\n\n If the code block does not raise the expected exception (``ZeroDivisionError`` in the example\n above), or no exception at all, the check will fail instead.\n\n You can also use the keyword argument ``match`` to assert that the\n exception matches a text or regex::\n\n >>> with raises(ValueError, match='must be 0 or None'):\n ... raise ValueError(\"value must be 0 or None\")\n\n >>> with raises(ValueError, match=r'must be \\d+$'):\n ... raise ValueError(\"value must be 42\")\n\n The context manager produces an :class:`ExceptionInfo` object which can be used to inspect the\n details of the captured exception::\n\n >>> with raises(ValueError) as exc_info:\n ... raise ValueError(\"value must be 42\")\n >>> assert exc_info.type is ValueError\n >>> assert exc_info.value.args[0] == \"value must be 42\"\n\n .. deprecated:: 4.1\n\n In the context manager form you may use the keyword argument\n ``message`` to specify a custom failure message that will be displayed\n in case the ``pytest.raises`` check fails. This has been deprecated as it\n is considered error prone as users often mean to use ``match`` instead.\n See :ref:`the deprecation docs ` for a workaround.\n\n .. note::\n\n When using ``pytest.raises`` as a context manager, it's worthwhile to\n note that normal context manager rules apply and that the exception\n raised *must* be the final line in the scope of the context manager.\n Lines of code after that, within the scope of the context manager will\n not be executed. For example::\n\n >>> value = 15\n >>> with raises(ValueError) as exc_info:\n ... if value > 10:\n ... raise ValueError(\"value must be <= 10\")\n ... assert exc_info.type is ValueError # this will not execute\n\n Instead, the following approach must be taken (note the difference in\n scope)::\n\n >>> with raises(ValueError) as exc_info:\n ... if value > 10:\n ... raise ValueError(\"value must be <= 10\")\n ...\n >>> assert exc_info.type is ValueError\n\n **Using with** ``pytest.mark.parametrize``\n\n When using :ref:`pytest.mark.parametrize ref`\n it is possible to parametrize tests such that\n some runs raise an exception and others do not.\n\n See :ref:`parametrizing_conditional_raising` for an example.\n\n **Legacy form**\n\n It is possible to specify a callable by passing a to-be-called lambda::\n\n >>> raises(ZeroDivisionError, lambda: 1/0)\n \n\n or you can specify an arbitrary callable with arguments::\n\n >>> def f(x): return 1/x\n ...\n >>> raises(ZeroDivisionError, f, 0)\n \n >>> raises(ZeroDivisionError, f, x=0)\n \n\n The form above is fully supported but discouraged for new code because the\n context manager form is regarded as more readable and less error-prone.\n\n .. note::\n Similar to caught exception objects in Python, explicitly clearing\n local references to returned ``ExceptionInfo`` objects can\n help the Python interpreter speed up its garbage collection.\n\n Clearing those references breaks a reference cycle\n (``ExceptionInfo`` --> caught exception --> frame stack raising\n the exception --> current frame stack --> local variables -->\n ``ExceptionInfo``) which makes Python keep all objects referenced\n from that cycle (including all local variables in the current\n frame) alive until the next cyclic garbage collection run. See the\n official Python ``try`` statement documentation for more detailed\n information.\n\n \"\"\"\n __tracebackhide__ = True\n for exc in filterfalse(isclass, always_iterable(expected_exception, BASE_TYPE)):\n msg = (\n \"exceptions must be old-style classes or\"\n \" derived from BaseException, not %s\"\n )\n raise TypeError(msg % type(exc))\n\n message = \"DID NOT RAISE {}\".format(expected_exception)\n match_expr = None\n\n if not args:\n if \"message\" in kwargs:\n message = kwargs.pop(\"message\")\n warnings.warn(deprecated.RAISES_MESSAGE_PARAMETER, stacklevel=2)\n if \"match\" in kwargs:\n match_expr = kwargs.pop(\"match\")\n if kwargs:\n msg = \"Unexpected keyword arguments passed to pytest.raises: \"\n msg += \", \".join(sorted(kwargs))\n raise TypeError(msg)\n return RaisesContext(expected_exception, message, match_expr)\n elif isinstance(args[0], str):\n warnings.warn(deprecated.RAISES_EXEC, stacklevel=2)\n code, = args\n assert isinstance(code, str)\n frame = sys._getframe(1)\n loc = frame.f_locals.copy()\n loc.update(kwargs)\n # print \"raises frame scope: %r\" % frame.f_locals\n try:\n code = _pytest._code.Source(code).compile(_genframe=frame)\n exec(code, frame.f_globals, loc)\n # XXX didn't mean f_globals == f_locals something special?\n # this is destroyed here ...\n except expected_exception:\n return _pytest._code.ExceptionInfo.from_current()\n else:\n func = args[0]\n try:\n func(*args[1:], **kwargs)\n except expected_exception:\n return _pytest._code.ExceptionInfo.from_current()\n fail(message)"},{"col":0,"comment":"Register one or more module names to be rewritten on import.\n\n This function will make sure that this module or all modules inside\n the package will get their assert statements rewritten.\n Thus you should make sure to call this before the module is\n actually imported, usually in your __init__.py if you are a plugin\n using a package.\n\n :raise TypeError: if the given module names are not strings.\n ","endLoc":56,"header":"def register_assert_rewrite(*names)","id":145,"name":"register_assert_rewrite","nodeType":"Function","startLoc":35,"text":"def register_assert_rewrite(*names):\n \"\"\"Register one or more module names to be rewritten on import.\n\n This function will make sure that this module or all modules inside\n the package will get their assert statements rewritten.\n Thus you should make sure to call this before the module is\n actually imported, usually in your __init__.py if you are a plugin\n using a package.\n\n :raise TypeError: if the given module names are not strings.\n \"\"\"\n for name in names:\n if not isinstance(name, str):\n msg = \"expected module names as *args, got {0} instead\"\n raise TypeError(msg.format(repr(names)))\n for hook in sys.meta_path:\n if isinstance(hook, rewrite.AssertionRewritingHook):\n importhook = hook\n break\n else:\n importhook = DummyRewriteHook()\n importhook.mark_rewrite(*names)"},{"col":0,"comment":"\n Explicitly fail an executing test with the given message.\n\n :param str msg: the message to show the user as reason for the failure.\n :param bool pytrace: if false the msg represents the full failure information and no\n python traceback will be reported.\n ","endLoc":119,"header":"def fail(msg=\"\", pytrace=True)","id":147,"name":"fail","nodeType":"Function","startLoc":110,"text":"def fail(msg=\"\", pytrace=True):\n \"\"\"\n Explicitly fail an executing test with the given message.\n\n :param str msg: the message to show the user as reason for the failure.\n :param bool pytrace: if false the msg represents the full failure information and no\n python traceback will be reported.\n \"\"\"\n __tracebackhide__ = True\n raise Failed(msg=msg, pytrace=pytrace)"},{"col":0,"comment":"null","endLoc":3,"header":"def setup_module(module)","id":149,"name":"setup_module","nodeType":"Function","startLoc":2,"text":"def setup_module(module):\n module.TestStateFullThing.classcount = 0"},{"col":0,"comment":"null","endLoc":26,"header":"def teardown_module(module)","id":150,"name":"teardown_module","nodeType":"Function","startLoc":25,"text":"def teardown_module(module):\n assert module.TestStateFullThing.classcount == 0"},{"col":0,"comment":"","endLoc":3,"header":"test_setup_flow_example.py#","id":151,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" For this example the control flow happens as follows::\n import test_setup_flow_example\n setup_module(test_setup_flow_example)\n setup_class(TestStateFullThing)\n instance = TestStateFullThing()\n setup_method(instance, instance.test_42)\n instance.test_42()\n setup_method(instance, instance.test_23)\n instance.test_23()\n teardown_class(TestStateFullThing)\n teardown_module(test_setup_flow_example)\n\nNote that ``setup_class(TestStateFullThing)`` is called and not\n``TestStateFullThing.setup_class()`` which would require you\nto insert ``setup_class = classmethod(setup_class)`` to make\nyour setup function callable.\n\"\"\""},{"col":4,"comment":"null","endLoc":23,"header":"def __init__(self, msg=None, pytrace=True)","id":152,"name":"__init__","nodeType":"Function","startLoc":20,"text":"def __init__(self, msg=None, pytrace=True):\n BaseException.__init__(self, msg)\n self.msg = msg\n self.pytrace = pytrace"},{"fileName":"deprecated.py","filePath":"src/_pytest","id":153,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis module contains deprecation messages and bits of code used elsewhere in the codebase\nthat is planned to be removed in the next pytest release.\n\nKeeping it in a central location makes it easy to track what is deprecated and should\nbe removed when the time comes.\n\nAll constants defined in this module should be either PytestWarning instances or UnformattedWarning\nin case of warnings which need to format their messages.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom _pytest.warning_types import PytestDeprecationWarning\nfrom _pytest.warning_types import RemovedInPytest4Warning\nfrom _pytest.warning_types import UnformattedWarning\n\nYIELD_TESTS = \"yield tests were removed in pytest 4.0 - {name} will be ignored\"\n\n\nFIXTURE_FUNCTION_CALL = (\n 'Fixture \"{name}\" called directly. Fixtures are not meant to be called directly,\\n'\n \"but are created automatically when test functions request them as parameters.\\n\"\n \"See https://docs.pytest.org/en/latest/fixture.html for more information about fixtures, and\\n\"\n \"https://docs.pytest.org/en/latest/deprecations.html#calling-fixtures-directly about how to update your code.\"\n)\n\nFIXTURE_NAMED_REQUEST = PytestDeprecationWarning(\n \"'request' is a reserved name for fixtures and will raise an error in future versions\"\n)\n\nCFG_PYTEST_SECTION = \"[pytest] section in {filename} files is no longer supported, change to [tool:pytest] instead.\"\n\nGETFUNCARGVALUE = RemovedInPytest4Warning(\n \"getfuncargvalue is deprecated, use getfixturevalue\"\n)\n\nRAISES_MESSAGE_PARAMETER = PytestDeprecationWarning(\n \"The 'message' parameter is deprecated.\\n\"\n \"(did you mean to use `match='some regex'` to check the exception message?)\\n\"\n \"Please see:\\n\"\n \" https://docs.pytest.org/en/4.6-maintenance/deprecations.html#message-parameter-of-pytest-raises\"\n)\n\nRESULT_LOG = PytestDeprecationWarning(\n \"--result-log is deprecated and scheduled for removal in pytest 5.0.\\n\"\n \"See https://docs.pytest.org/en/latest/deprecations.html#result-log-result-log for more information.\"\n)\n\nRAISES_EXEC = PytestDeprecationWarning(\n \"raises(..., 'code(as_a_string)') is deprecated, use the context manager form or use `exec()` directly\\n\\n\"\n \"See https://docs.pytest.org/en/latest/deprecations.html#raises-warns-exec\"\n)\nWARNS_EXEC = PytestDeprecationWarning(\n \"warns(..., 'code(as_a_string)') is deprecated, use the context manager form or use `exec()` directly.\\n\\n\"\n \"See https://docs.pytest.org/en/latest/deprecations.html#raises-warns-exec\"\n)\n\nPYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST = (\n \"Defining 'pytest_plugins' in a non-top-level conftest is no longer supported \"\n \"because it affects the entire directory tree in a non-explicit way.\\n\"\n \" {}\\n\"\n \"Please move it to a top level conftest file at the rootdir:\\n\"\n \" {}\\n\"\n \"For more information, visit:\\n\"\n \" https://docs.pytest.org/en/latest/deprecations.html#pytest-plugins-in-non-top-level-conftest-files\"\n)\n\nPYTEST_CONFIG_GLOBAL = PytestDeprecationWarning(\n \"the `pytest.config` global is deprecated. Please use `request.config` \"\n \"or `pytest_configure` (if you're a pytest plugin) instead.\"\n)\n\nPYTEST_ENSURETEMP = RemovedInPytest4Warning(\n \"pytest/tmpdir_factory.ensuretemp is deprecated, \\n\"\n \"please use the tmp_path fixture or tmp_path_factory.mktemp\"\n)\n\nPYTEST_LOGWARNING = PytestDeprecationWarning(\n \"pytest_logwarning is deprecated, no longer being called, and will be removed soon\\n\"\n \"please use pytest_warning_captured instead\"\n)\n\nPYTEST_WARNS_UNKNOWN_KWARGS = UnformattedWarning(\n PytestDeprecationWarning,\n \"pytest.warns() got unexpected keyword arguments: {args!r}.\\n\"\n \"This will be an error in future versions.\",\n)\n\nPYTEST_PARAM_UNKNOWN_KWARGS = UnformattedWarning(\n PytestDeprecationWarning,\n \"pytest.param() got unexpected keyword arguments: {args!r}.\\n\"\n \"This will be an error in future versions.\",\n)\n"},{"id":154,"name":"doc/en/_templates","nodeType":"Package"},{"id":155,"name":"layout.html","nodeType":"TextFile","path":"doc/en/_templates","text":"{% extends \"!layout.html\" %}\n{% block header %}\n {{super()}}\n{% endblock %}\n{% block footer %}\n{{ super() }}\n\n{% endblock %}\n"},{"id":156,"name":"release-4.3.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-4.3.0\n=======================================\n\nThe pytest team is proud to announce the 4.3.0 release!\n\npytest is a mature Python testing tool with more than a 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n https://docs.pytest.org/en/latest/changelog.html\n\nFor complete documentation, please visit:\n\n https://docs.pytest.org/en/latest/\n\nAs usual, you can upgrade from pypi via:\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Andras Mitzki\n* Anthony Sottile\n* Bruno Oliveira\n* Christian Fetzer\n* Daniel Hahler\n* Grygorii Iermolenko\n* R. Alex Matevish\n* Ronny Pfannschmidt\n* cclauss\n\n\nHappy testing,\nThe Pytest Development Team\n"},{"col":0,"comment":"\n Skip an executing test with the given message.\n\n This function should be called only during testing (setup, call or teardown) or\n during collection by using the ``allow_module_level`` flag. This function can\n be called in doctests as well.\n\n :kwarg bool allow_module_level: allows this function to be called at\n module level, skipping the rest of the module. Default to False.\n\n .. note::\n It is better to use the :ref:`pytest.mark.skipif ref` marker when possible to declare a test to be\n skipped under certain conditions like mismatching platforms or\n dependencies.\n Similarly, use the ``# doctest: +SKIP`` directive (see `doctest.SKIP\n `_)\n to skip a doctest statically.\n ","endLoc":104,"header":"def skip(msg=\"\", **kwargs)","id":157,"name":"skip","nodeType":"Function","startLoc":81,"text":"def skip(msg=\"\", **kwargs):\n \"\"\"\n Skip an executing test with the given message.\n\n This function should be called only during testing (setup, call or teardown) or\n during collection by using the ``allow_module_level`` flag. This function can\n be called in doctests as well.\n\n :kwarg bool allow_module_level: allows this function to be called at\n module level, skipping the rest of the module. Default to False.\n\n .. note::\n It is better to use the :ref:`pytest.mark.skipif ref` marker when possible to declare a test to be\n skipped under certain conditions like mismatching platforms or\n dependencies.\n Similarly, use the ``# doctest: +SKIP`` directive (see `doctest.SKIP\n `_)\n to skip a doctest statically.\n \"\"\"\n __tracebackhide__ = True\n allow_module_level = kwargs.pop(\"allow_module_level\", False)\n if kwargs:\n raise TypeError(\"unexpected keyword arguments: {}\".format(sorted(kwargs)))\n raise Skipped(msg=msg, allow_module_level=allow_module_level)"},{"id":158,"name":"release-2.8.5.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.8.5\n============\n\npytest is a mature Python testing tool with more than a 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is supposed to be drop-in compatible to 2.8.4.\n\nSee below for the changes and see docs at:\n\n http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n Alex Gaynor\n aselus-hub\n Bruno Oliveira\n Ronny Pfannschmidt\n\n\nHappy testing,\nThe py.test Development Team\n\n\n2.8.5 (compared to 2.8.4)\n-------------------------\n\n- fix #1243: fixed issue where class attributes injected during collection could break pytest.\n PR by Alexei Kozlenok, thanks Ronny Pfannschmidt and Bruno Oliveira for the review and help.\n\n- fix #1074: precompute junitxml chunks instead of storing the whole tree in objects\n Thanks Bruno Oliveira for the report and Ronny Pfannschmidt for the PR\n\n- fix #1238: fix ``pytest.deprecated_call()`` receiving multiple arguments\n (Regression introduced in 2.8.4). Thanks Alex Gaynor for the report and\n Bruno Oliveira for the PR.\n"},{"col":4,"comment":"null","endLoc":1106,"header":"@overload\n def pop(self, __key: _KT) -> _VT","id":159,"name":"pop","nodeType":"Function","startLoc":1105,"text":"@overload\n def pop(self, __key: _KT) -> _VT: ..."},{"col":4,"comment":"null","endLoc":1108,"header":"@overload\n def pop(self, __key: _KT, __default: _VT) -> _VT","id":160,"name":"pop","nodeType":"Function","startLoc":1107,"text":"@overload\n def pop(self, __key: _KT, __default: _VT) -> _VT: ..."},{"col":4,"comment":"null","endLoc":1110,"header":"@overload\n def pop(self, __key: _KT, __default: _T) -> _VT | _T","id":161,"name":"pop","nodeType":"Function","startLoc":1109,"text":"@overload\n def pop(self, __key: _KT, __default: _T) -> _VT | _T: ..."},{"id":162,"name":"","nodeType":"Package"},{"fileName":"setup.py","filePath":"","id":163,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom setuptools import setup\n\n# TODO: if py gets upgrade to >=1.6,\n# remove _width_of_current_line in terminal.py\nINSTALL_REQUIRES = [\n \"py>=1.5.0\",\n \"six>=1.10.0\",\n \"packaging\",\n \"attrs>=17.4.0\",\n 'more-itertools>=4.0.0,<6.0.0;python_version<=\"2.7\"',\n 'more-itertools>=4.0.0;python_version>\"2.7\"',\n \"atomicwrites>=1.0\",\n 'funcsigs>=1.0;python_version<\"3.0\"',\n 'pathlib2>=2.2.0;python_version<\"3.6\"',\n 'colorama;sys_platform==\"win32\"',\n \"pluggy>=0.12,<1.0\",\n \"importlib-metadata>=0.12\",\n \"wcwidth\",\n]\n\n\ndef main():\n setup(\n use_scm_version={\"write_to\": \"src/_pytest/_version.py\"},\n setup_requires=[\"setuptools-scm\", \"setuptools>=40.0\"],\n package_dir={\"\": \"src\"},\n # fmt: off\n extras_require={\n \"testing\": [\n \"argcomplete\",\n \"hypothesis>=3.56\",\n \"nose\",\n \"requests\",\n \"mock;python_version=='2.7'\",\n ],\n },\n # fmt: on\n install_requires=INSTALL_REQUIRES,\n )\n\n\nif __name__ == \"__main__\":\n main()\n"},{"className":"PytestDeprecationWarning","col":0,"comment":"\n Bases: :class:`pytest.PytestWarning`, :class:`DeprecationWarning`.\n\n Warning class for features that will be removed in a future version.\n ","endLoc":50,"id":166,"nodeType":"Class","startLoc":45,"text":"class PytestDeprecationWarning(PytestWarning, DeprecationWarning):\n \"\"\"\n Bases: :class:`pytest.PytestWarning`, :class:`DeprecationWarning`.\n\n Warning class for features that will be removed in a future version.\n \"\"\""},{"className":"PytestWarning","col":0,"comment":"\n Bases: :class:`UserWarning`.\n\n Base class for all warnings emitted by pytest.\n ","endLoc":10,"id":167,"nodeType":"Class","startLoc":5,"text":"class PytestWarning(UserWarning):\n \"\"\"\n Bases: :class:`UserWarning`.\n\n Base class for all warnings emitted by pytest.\n \"\"\""},{"className":"UserWarning","col":0,"comment":"null","endLoc":2068,"id":168,"nodeType":"Class","startLoc":2068,"text":"class UserWarning(Warning): ..."},{"col":0,"comment":"null","endLoc":74,"header":"def setup(\n *,\n name: str = ...,\n version: str = ...,\n description: str = ...,\n long_description: str = ...,\n long_description_content_type: str = ...,\n author: str = ...,\n author_email: str = ...,\n maintainer: str = ...,\n maintainer_email: str = ...,\n url: str = ...,\n download_url: str = ...,\n packages: list[str] = ...,\n py_modules: list[str] = ...,\n scripts: list[str] = ...,\n ext_modules: Sequence[Extension] = ...,\n classifiers: list[str] = ...,\n distclass: type[Distribution] = ...,\n script_name: str = ...,\n script_args: list[str] = ...,\n options: Mapping[str, Incomplete] = ...,\n license: str = ...,\n keywords: list[str] | str = ...,\n platforms: list[str] | str = ...,\n cmdclass: Mapping[str, type[_Command]] = ...,\n data_files: list[tuple[str, list[str]]] = ...,\n package_dir: Mapping[str, str] = ...,\n obsoletes: list[str] = ...,\n provides: list[str] = ...,\n requires: list[str] = ...,\n command_packages: list[str] = ...,\n command_options: Mapping[str, Mapping[str, tuple[Incomplete, Incomplete]]] = ...,\n package_data: Mapping[str, list[str]] = ...,\n include_package_data: bool = ...,\n libraries: list[str] = ...,\n headers: list[str] = ...,\n ext_package: str = ...,\n include_dirs: list[str] = ...,\n password: str = ...,\n fullname: str = ...,\n **attrs,\n) -> Distribution","id":169,"name":"setup","nodeType":"Function","startLoc":32,"text":"def setup(\n *,\n name: str = ...,\n version: str = ...,\n description: str = ...,\n long_description: str = ...,\n long_description_content_type: str = ...,\n author: str = ...,\n author_email: str = ...,\n maintainer: str = ...,\n maintainer_email: str = ...,\n url: str = ...,\n download_url: str = ...,\n packages: list[str] = ...,\n py_modules: list[str] = ...,\n scripts: list[str] = ...,\n ext_modules: Sequence[Extension] = ...,\n classifiers: list[str] = ...,\n distclass: type[Distribution] = ...,\n script_name: str = ...,\n script_args: list[str] = ...,\n options: Mapping[str, Incomplete] = ...,\n license: str = ...,\n keywords: list[str] | str = ...,\n platforms: list[str] | str = ...,\n cmdclass: Mapping[str, type[_Command]] = ...,\n data_files: list[tuple[str, list[str]]] = ...,\n package_dir: Mapping[str, str] = ...,\n obsoletes: list[str] = ...,\n provides: list[str] = ...,\n requires: list[str] = ...,\n command_packages: list[str] = ...,\n command_options: Mapping[str, Mapping[str, tuple[Incomplete, Incomplete]]] = ...,\n package_data: Mapping[str, list[str]] = ...,\n include_package_data: bool = ...,\n libraries: list[str] = ...,\n headers: list[str] = ...,\n ext_package: str = ...,\n include_dirs: list[str] = ...,\n password: str = ...,\n fullname: str = ...,\n **attrs,\n) -> Distribution: ..."},{"className":"cmdline","col":0,"comment":"null","endLoc":93,"id":172,"nodeType":"Class","startLoc":92,"text":"class cmdline(object): # compatibility namespace\n main = staticmethod(main)"},{"attributeType":"null","col":4,"comment":"null","endLoc":93,"id":173,"name":"main","nodeType":"Attribute","startLoc":93,"text":"main"},{"col":0,"comment":"null","endLoc":40,"header":"def main()","id":174,"name":"main","nodeType":"Function","startLoc":23,"text":"def main():\n setup(\n use_scm_version={\"write_to\": \"src/_pytest/_version.py\"},\n setup_requires=[\"setuptools-scm\", \"setuptools>=40.0\"],\n package_dir={\"\": \"src\"},\n # fmt: off\n extras_require={\n \"testing\": [\n \"argcomplete\",\n \"hypothesis>=3.56\",\n \"nose\",\n \"requests\",\n \"mock;python_version=='2.7'\",\n ],\n },\n # fmt: on\n install_requires=INSTALL_REQUIRES,\n )"},{"attributeType":"null","col":0,"comment":"null","endLoc":41,"id":175,"name":"hookspec","nodeType":"Attribute","startLoc":41,"text":"hookspec"},{"attributeType":"list","col":0,"comment":"null","endLoc":6,"id":176,"name":"INSTALL_REQUIRES","nodeType":"Attribute","startLoc":6,"text":"INSTALL_REQUIRES"},{"col":4,"comment":"null","endLoc":46,"header":"def __init__(self, msg=None, pytrace=True, allow_module_level=False)","id":177,"name":"__init__","nodeType":"Function","startLoc":44,"text":"def __init__(self, msg=None, pytrace=True, allow_module_level=False):\n OutcomeException.__init__(self, msg=msg, pytrace=pytrace)\n self.allow_module_level = allow_module_level"},{"col":0,"comment":"","endLoc":2,"header":"setup.py#","id":178,"name":"","nodeType":"Function","startLoc":2,"text":"INSTALL_REQUIRES = [\n \"py>=1.5.0\",\n \"six>=1.10.0\",\n \"packaging\",\n \"attrs>=17.4.0\",\n 'more-itertools>=4.0.0,<6.0.0;python_version<=\"2.7\"',\n 'more-itertools>=4.0.0;python_version>\"2.7\"',\n \"atomicwrites>=1.0\",\n 'funcsigs>=1.0;python_version<\"3.0\"',\n 'pathlib2>=2.2.0;python_version<\"3.6\"',\n 'colorama;sys_platform==\"win32\"',\n \"pluggy>=0.12,<1.0\",\n \"importlib-metadata>=0.12\",\n \"wcwidth\",\n]\n\nif __name__ == \"__main__\":\n main()"},{"className":"UsageError","col":0,"comment":" error in pytest usage or invocation","endLoc":3,"id":179,"nodeType":"Class","startLoc":2,"text":"class UsageError(Exception):\n \"\"\" error in pytest usage or invocation\"\"\""},{"className":"Exception","col":0,"comment":"null","endLoc":1947,"id":180,"nodeType":"Class","startLoc":1947,"text":"class Exception(BaseException): ..."},{"fileName":"publish_gh_release_notes.py","filePath":"scripts","id":181,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"\nScript used to publish GitHub release notes extracted from CHANGELOG.rst.\n\nThis script is meant to be executed after a successful deployment in Travis.\n\nUses the following environment variables:\n\n* GIT_TAG: the name of the tag of the current commit.\n* GH_RELEASE_NOTES_TOKEN: a personal access token with 'repo' permissions. It should be encrypted using:\n\n $travis encrypt GH_RELEASE_NOTES_TOKEN= -r pytest-dev/pytest\n\n And the contents pasted in the ``deploy.env.secure`` section in the ``travis.yml`` file.\n\nThe script also requires ``pandoc`` to be previously installed in the system.\n\nRequires Python3.6+.\n\"\"\"\nimport os\nimport re\nimport sys\nfrom pathlib import Path\n\nimport github3\nimport pypandoc\n\n\ndef publish_github_release(slug, token, tag_name, body):\n github = github3.login(token=token)\n owner, repo = slug.split(\"/\")\n repo = github.repository(owner, repo)\n return repo.create_release(tag_name=tag_name, body=body)\n\n\ndef parse_changelog(tag_name):\n p = Path(__file__).parent.parent / \"CHANGELOG.rst\"\n changelog_lines = p.read_text(encoding=\"UTF-8\").splitlines()\n\n title_regex = re.compile(r\"pytest (\\d\\.\\d+\\.\\d+) \\(\\d{4}-\\d{2}-\\d{2}\\)\")\n consuming_version = False\n version_lines = []\n for line in changelog_lines:\n m = title_regex.match(line)\n if m:\n # found the version we want: start to consume lines until we find the next version title\n if m.group(1) == tag_name:\n consuming_version = True\n # found a new version title while parsing the version we want: break out\n elif consuming_version:\n break\n if consuming_version:\n version_lines.append(line)\n\n return \"\\n\".join(version_lines)\n\n\ndef convert_rst_to_md(text):\n return pypandoc.convert_text(text, \"md\", format=\"rst\")\n\n\ndef main(argv):\n if len(argv) > 1:\n tag_name = argv[1]\n else:\n tag_name = os.environ.get(\"TRAVIS_TAG\")\n if not tag_name:\n print(\"tag_name not given and $TRAVIS_TAG not set\", file=sys.stderr)\n return 1\n\n token = os.environ.get(\"GH_RELEASE_NOTES_TOKEN\")\n if not token:\n print(\"GH_RELEASE_NOTES_TOKEN not set\", file=sys.stderr)\n return 1\n\n slug = os.environ.get(\"TRAVIS_REPO_SLUG\")\n if not slug:\n print(\"TRAVIS_REPO_SLUG not set\", file=sys.stderr)\n return 1\n\n rst_body = parse_changelog(tag_name)\n md_body = convert_rst_to_md(rst_body)\n if not publish_github_release(slug, token, tag_name, md_body):\n print(\"Could not publish release notes:\", file=sys.stderr)\n print(md_body, file=sys.stderr)\n return 5\n\n print()\n print(f\"Release notes for {tag_name} published successfully:\")\n print(f\"https://github.com/{slug}/releases/tag/{tag_name}\")\n print()\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv))\n"},{"fileName":"outcomes.py","filePath":"src/_pytest","id":182,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"\nexception classes and constants handling test outcomes\nas well as functions creating them\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\n\nfrom packaging.version import Version\n\n\nclass OutcomeException(BaseException):\n \"\"\" OutcomeException and its subclass instances indicate and\n contain info about test and collection outcomes.\n \"\"\"\n\n def __init__(self, msg=None, pytrace=True):\n BaseException.__init__(self, msg)\n self.msg = msg\n self.pytrace = pytrace\n\n def __repr__(self):\n if self.msg:\n val = self.msg\n if isinstance(val, bytes):\n val = val.decode(\"UTF-8\", errors=\"replace\")\n return val\n return \"<%s instance>\" % (self.__class__.__name__,)\n\n __str__ = __repr__\n\n\nTEST_OUTCOME = (OutcomeException, Exception)\n\n\nclass Skipped(OutcomeException):\n # XXX hackish: on 3k we fake to live in the builtins\n # in order to have Skipped exception printing shorter/nicer\n __module__ = \"builtins\"\n\n def __init__(self, msg=None, pytrace=True, allow_module_level=False):\n OutcomeException.__init__(self, msg=msg, pytrace=pytrace)\n self.allow_module_level = allow_module_level\n\n\nclass Failed(OutcomeException):\n \"\"\" raised from an explicit call to pytest.fail() \"\"\"\n\n __module__ = \"builtins\"\n\n\nclass Exit(Exception):\n \"\"\" raised for immediate program exits (no tracebacks/summaries)\"\"\"\n\n def __init__(self, msg=\"unknown reason\", returncode=None):\n self.msg = msg\n self.returncode = returncode\n super(Exit, self).__init__(msg)\n\n\n# exposed helper methods\n\n\ndef exit(msg, returncode=None):\n \"\"\"\n Exit testing process.\n\n :param str msg: message to display upon exit.\n :param int returncode: return code to be used when exiting pytest.\n \"\"\"\n __tracebackhide__ = True\n raise Exit(msg, returncode)\n\n\nexit.Exception = Exit\n\n\ndef skip(msg=\"\", **kwargs):\n \"\"\"\n Skip an executing test with the given message.\n\n This function should be called only during testing (setup, call or teardown) or\n during collection by using the ``allow_module_level`` flag. This function can\n be called in doctests as well.\n\n :kwarg bool allow_module_level: allows this function to be called at\n module level, skipping the rest of the module. Default to False.\n\n .. note::\n It is better to use the :ref:`pytest.mark.skipif ref` marker when possible to declare a test to be\n skipped under certain conditions like mismatching platforms or\n dependencies.\n Similarly, use the ``# doctest: +SKIP`` directive (see `doctest.SKIP\n `_)\n to skip a doctest statically.\n \"\"\"\n __tracebackhide__ = True\n allow_module_level = kwargs.pop(\"allow_module_level\", False)\n if kwargs:\n raise TypeError(\"unexpected keyword arguments: {}\".format(sorted(kwargs)))\n raise Skipped(msg=msg, allow_module_level=allow_module_level)\n\n\nskip.Exception = Skipped\n\n\ndef fail(msg=\"\", pytrace=True):\n \"\"\"\n Explicitly fail an executing test with the given message.\n\n :param str msg: the message to show the user as reason for the failure.\n :param bool pytrace: if false the msg represents the full failure information and no\n python traceback will be reported.\n \"\"\"\n __tracebackhide__ = True\n raise Failed(msg=msg, pytrace=pytrace)\n\n\nfail.Exception = Failed\n\n\nclass XFailed(fail.Exception):\n \"\"\" raised from an explicit call to pytest.xfail() \"\"\"\n\n\ndef xfail(reason=\"\"):\n \"\"\"\n Imperatively xfail an executing test or setup functions with the given reason.\n\n This function should be called only during testing (setup, call or teardown).\n\n .. note::\n It is better to use the :ref:`pytest.mark.xfail ref` marker when possible to declare a test to be\n xfailed under certain conditions like known bugs or missing features.\n \"\"\"\n __tracebackhide__ = True\n raise XFailed(reason)\n\n\nxfail.Exception = XFailed\n\n\ndef importorskip(modname, minversion=None, reason=None):\n \"\"\"Imports and returns the requested module ``modname``, or skip the current test\n if the module cannot be imported.\n\n :param str modname: the name of the module to import\n :param str minversion: if given, the imported module ``__version__`` attribute must be\n at least this minimal version, otherwise the test is still skipped.\n :param str reason: if given, this reason is shown as the message when the module\n cannot be imported.\n \"\"\"\n import warnings\n\n __tracebackhide__ = True\n compile(modname, \"\", \"eval\") # to catch syntaxerrors\n import_exc = None\n\n with warnings.catch_warnings():\n # make sure to ignore ImportWarnings that might happen because\n # of existing directories with the same name we're trying to\n # import but without a __init__.py file\n warnings.simplefilter(\"ignore\")\n try:\n __import__(modname)\n except ImportError as exc:\n # Do not raise chained exception here(#1485)\n import_exc = exc\n if import_exc:\n if reason is None:\n reason = \"could not import %r: %s\" % (modname, import_exc)\n raise Skipped(reason, allow_module_level=True)\n mod = sys.modules[modname]\n if minversion is None:\n return mod\n verattr = getattr(mod, \"__version__\", None)\n if minversion is not None:\n if verattr is None or Version(verattr) < Version(minversion):\n raise Skipped(\n \"module %r has __version__ %r, required is: %r\"\n % (modname, verattr, minversion),\n allow_module_level=True,\n )\n return mod\n"},{"col":0,"comment":"\n Imperatively xfail an executing test or setup functions with the given reason.\n\n This function should be called only during testing (setup, call or teardown).\n\n .. note::\n It is better to use the :ref:`pytest.mark.xfail ref` marker when possible to declare a test to be\n xfailed under certain conditions like known bugs or missing features.\n ","endLoc":140,"header":"def xfail(reason=\"\")","id":183,"name":"xfail","nodeType":"Function","startLoc":129,"text":"def xfail(reason=\"\"):\n \"\"\"\n Imperatively xfail an executing test or setup functions with the given reason.\n\n This function should be called only during testing (setup, call or teardown).\n\n .. note::\n It is better to use the :ref:`pytest.mark.xfail ref` marker when possible to declare a test to be\n xfailed under certain conditions like known bugs or missing features.\n \"\"\"\n __tracebackhide__ = True\n raise XFailed(reason)"},{"className":"OutcomeException","col":0,"comment":" OutcomeException and its subclass instances indicate and\n contain info about test and collection outcomes.\n ","endLoc":33,"id":184,"nodeType":"Class","startLoc":15,"text":"class OutcomeException(BaseException):\n \"\"\" OutcomeException and its subclass instances indicate and\n contain info about test and collection outcomes.\n \"\"\"\n\n def __init__(self, msg=None, pytrace=True):\n BaseException.__init__(self, msg)\n self.msg = msg\n self.pytrace = pytrace\n\n def __repr__(self):\n if self.msg:\n val = self.msg\n if isinstance(val, bytes):\n val = val.decode(\"UTF-8\", errors=\"replace\")\n return val\n return \"<%s instance>\" % (self.__class__.__name__,)\n\n __str__ = __repr__"},{"className":"BaseException","col":0,"comment":"null","endLoc":1939,"id":185,"nodeType":"Class","startLoc":1927,"text":"class BaseException:\n args: tuple[Any, ...]\n __cause__: BaseException | None\n __context__: BaseException | None\n __suppress_context__: bool\n __traceback__: TracebackType | None\n def __init__(self, *args: object) -> None: ...\n def __setstate__(self, __state: dict[str, Any] | None) -> None: ...\n def with_traceback(self, __tb: TracebackType | None) -> Self: ...\n if sys.version_info >= (3, 11):\n # only present after add_note() is called\n __notes__: list[str]\n def add_note(self, __note: str) -> None: ..."},{"col":4,"comment":"null","endLoc":1934,"header":"def __setstate__(self, __state: dict[str, Any] | None) -> None","id":186,"name":"__setstate__","nodeType":"Function","startLoc":1934,"text":"def __setstate__(self, __state: dict[str, Any] | None) -> None: ..."},{"col":4,"comment":"null","endLoc":1935,"header":"def with_traceback(self, __tb: TracebackType | None) -> Self","id":187,"name":"with_traceback","nodeType":"Function","startLoc":1935,"text":"def with_traceback(self, __tb: TracebackType | None) -> Self: ..."},{"attributeType":"(Any, ...)","col":4,"comment":"null","endLoc":1928,"id":188,"name":"args","nodeType":"Attribute","startLoc":1928,"text":"args"},{"className":"Warning","col":0,"comment":"null","endLoc":2067,"id":189,"nodeType":"Class","startLoc":2067,"text":"class Warning(Exception): ..."},{"className":"Path","col":0,"comment":"null","endLoc":267,"id":190,"nodeType":"Class","startLoc":103,"text":"class Path(PurePath):\n if sys.version_info >= (3, 12):\n def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ... # pyright: ignore[reportInconsistentConstructor]\n else:\n def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ...\n\n @classmethod\n def cwd(cls) -> Self: ...\n if sys.version_info >= (3, 10):\n def stat(self, *, follow_symlinks: bool = True) -> stat_result: ...\n def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None: ...\n else:\n def stat(self) -> stat_result: ...\n def chmod(self, mode: int) -> None: ...\n\n if sys.version_info >= (3, 13):\n @classmethod\n def from_uri(cls, uri: str) -> Self: ...\n def is_dir(self, *, follow_symlinks: bool = True) -> bool: ...\n def is_file(self, *, follow_symlinks: bool = True) -> bool: ...\n def read_text(self, encoding: str | None = None, errors: str | None = None, newline: str | None = None) -> str: ...\n else:\n def __enter__(self) -> Self: ...\n def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ...\n def is_dir(self) -> bool: ...\n def is_file(self) -> bool: ...\n def read_text(self, encoding: str | None = None, errors: str | None = None) -> str: ...\n\n if sys.version_info >= (3, 13):\n def glob(\n self, pattern: str, *, case_sensitive: bool | None = None, recurse_symlinks: bool = False\n ) -> Generator[Self, None, None]: ...\n def rglob(\n self, pattern: str, *, case_sensitive: bool | None = None, recurse_symlinks: bool = False\n ) -> Generator[Self, None, None]: ...\n elif sys.version_info >= (3, 12):\n def glob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self, None, None]: ...\n def rglob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self, None, None]: ...\n else:\n def glob(self, pattern: str) -> Generator[Self, None, None]: ...\n def rglob(self, pattern: str) -> Generator[Self, None, None]: ...\n\n if sys.version_info >= (3, 12):\n def exists(self, *, follow_symlinks: bool = True) -> bool: ...\n else:\n def exists(self) -> bool: ...\n\n def is_symlink(self) -> bool: ...\n def is_socket(self) -> bool: ...\n def is_fifo(self) -> bool: ...\n def is_block_device(self) -> bool: ...\n def is_char_device(self) -> bool: ...\n if sys.version_info >= (3, 12):\n def is_junction(self) -> bool: ...\n\n def iterdir(self) -> Generator[Self, None, None]: ...\n def lchmod(self, mode: int) -> None: ...\n def lstat(self) -> stat_result: ...\n def mkdir(self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None: ...\n # Adapted from builtins.open\n # Text mode: always returns a TextIOWrapper\n # The Traversable .open in stdlib/importlib/abc.pyi should be kept in sync with this.\n @overload\n def open(\n self,\n mode: OpenTextMode = \"r\",\n buffering: int = -1,\n encoding: str | None = None,\n errors: str | None = None,\n newline: str | None = None,\n ) -> TextIOWrapper: ...\n # Unbuffered binary mode: returns a FileIO\n @overload\n def open(\n self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = None, errors: None = None, newline: None = None\n ) -> FileIO: ...\n # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter\n @overload\n def open(\n self,\n mode: OpenBinaryModeUpdating,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedRandom: ...\n @overload\n def open(\n self,\n mode: OpenBinaryModeWriting,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedWriter: ...\n @overload\n def open(\n self,\n mode: OpenBinaryModeReading,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedReader: ...\n # Buffering cannot be determined: fall back to BinaryIO\n @overload\n def open(\n self, mode: OpenBinaryMode, buffering: int = -1, encoding: None = None, errors: None = None, newline: None = None\n ) -> BinaryIO: ...\n # Fallback if mode is not specified\n @overload\n def open(\n self, mode: str, buffering: int = -1, encoding: str | None = None, errors: str | None = None, newline: str | None = None\n ) -> IO[Any]: ...\n if sys.platform != \"win32\":\n # These methods do \"exist\" on Windows, but they always raise NotImplementedError,\n # so it's safer to pretend they don't exist\n if sys.version_info >= (3, 13):\n def owner(self, *, follow_symlinks: bool = True) -> str: ...\n def group(self, *, follow_symlinks: bool = True) -> str: ...\n else:\n def owner(self) -> str: ...\n def group(self) -> str: ...\n\n # This method does \"exist\" on Windows on <3.12, but always raises NotImplementedError\n # On py312+, it works properly on Windows, as with all other platforms\n if sys.platform != \"win32\" or sys.version_info >= (3, 12):\n def is_mount(self) -> bool: ...\n\n if sys.version_info >= (3, 9):\n def readlink(self) -> Self: ...\n\n def rename(self, target: str | PurePath) -> Self: ...\n def replace(self, target: str | PurePath) -> Self: ...\n def resolve(self, strict: bool = False) -> Self: ...\n def rmdir(self) -> None: ...\n def symlink_to(self, target: StrOrBytesPath, target_is_directory: bool = False) -> None: ...\n if sys.version_info >= (3, 10):\n def hardlink_to(self, target: StrOrBytesPath) -> None: ...\n\n def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None: ...\n def unlink(self, missing_ok: bool = False) -> None: ...\n @classmethod\n def home(cls) -> Self: ...\n def absolute(self) -> Self: ...\n def expanduser(self) -> Self: ...\n def read_bytes(self) -> bytes: ...\n def samefile(self, other_path: StrPath) -> bool: ...\n def write_bytes(self, data: ReadableBuffer) -> int: ...\n if sys.version_info >= (3, 10):\n def write_text(\n self, data: str, encoding: str | None = None, errors: str | None = None, newline: str | None = None\n ) -> int: ...\n else:\n def write_text(self, data: str, encoding: str | None = None, errors: str | None = None) -> int: ...\n if sys.version_info < (3, 12):\n if sys.version_info >= (3, 10):\n @deprecated(\"Deprecated as of Python 3.10 and removed in Python 3.12. Use hardlink_to() instead.\")\n def link_to(self, target: StrOrBytesPath) -> None: ...\n else:\n def link_to(self, target: StrOrBytesPath) -> None: ...\n if sys.version_info >= (3, 12):\n def walk(\n self, top_down: bool = ..., on_error: Callable[[OSError], object] | None = ..., follow_symlinks: bool = ...\n ) -> Iterator[tuple[Self, list[str], list[str]]]: ..."},{"className":"DeprecationWarning","col":0,"comment":"null","endLoc":2069,"id":191,"nodeType":"Class","startLoc":2069,"text":"class DeprecationWarning(Warning): ..."},{"className":"RemovedInPytest4Warning","col":0,"comment":"\n Bases: :class:`pytest.PytestDeprecationWarning`.\n\n Warning class for features scheduled to be removed in pytest 4.0.\n ","endLoc":94,"id":192,"nodeType":"Class","startLoc":89,"text":"class RemovedInPytest4Warning(PytestDeprecationWarning):\n \"\"\"\n Bases: :class:`pytest.PytestDeprecationWarning`.\n\n Warning class for features scheduled to be removed in pytest 4.0.\n \"\"\""},{"className":"UnformattedWarning","col":0,"comment":"Used to hold warnings that need to format their message at runtime, as opposed to a direct message.\n\n Using this class avoids to keep all the warning types and messages in this module, avoiding misuse.\n ","endLoc":109,"id":193,"nodeType":"Class","startLoc":97,"text":"@attr.s\nclass UnformattedWarning(object):\n \"\"\"Used to hold warnings that need to format their message at runtime, as opposed to a direct message.\n\n Using this class avoids to keep all the warning types and messages in this module, avoiding misuse.\n \"\"\"\n\n category = attr.ib()\n template = attr.ib()\n\n def format(self, **kwargs):\n \"\"\"Returns an instance of the warning category, formatted with given kwargs\"\"\"\n return self.category(self.template.format(**kwargs))"},{"col":4,"comment":"Returns an instance of the warning category, formatted with given kwargs","endLoc":109,"header":"def format(self, **kwargs)","id":194,"name":"format","nodeType":"Function","startLoc":107,"text":"def format(self, **kwargs):\n \"\"\"Returns an instance of the warning category, formatted with given kwargs\"\"\"\n return self.category(self.template.format(**kwargs))"},{"attributeType":"BaseException | None","col":4,"comment":"null","endLoc":1929,"id":195,"name":"__cause__","nodeType":"Attribute","startLoc":1929,"text":"__cause__"},{"attributeType":"null","col":4,"comment":"null","endLoc":104,"id":196,"name":"category","nodeType":"Attribute","startLoc":104,"text":"category"},{"attributeType":"null","col":4,"comment":"null","endLoc":105,"id":197,"name":"template","nodeType":"Attribute","startLoc":105,"text":"template"},{"attributeType":"str","col":0,"comment":"null","endLoc":20,"id":198,"name":"YIELD_TESTS","nodeType":"Attribute","startLoc":20,"text":"YIELD_TESTS"},{"id":199,"name":"extra","nodeType":"Package"},{"fileName":"get_issues.py","filePath":"extra","id":200,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport json\n\nimport py\nimport requests\n\nissues_url = \"https://api.github.com/repos/pytest-dev/pytest/issues\"\n\n\ndef get_issues():\n issues = []\n url = issues_url\n while 1:\n get_data = {\"state\": \"all\"}\n r = requests.get(url, params=get_data)\n data = r.json()\n if r.status_code == 403:\n # API request limit exceeded\n print(data[\"message\"])\n exit(1)\n issues.extend(data)\n\n # Look for next page\n links = requests.utils.parse_header_links(r.headers[\"Link\"])\n another_page = False\n for link in links:\n if link[\"rel\"] == \"next\":\n url = link[\"url\"]\n another_page = True\n if not another_page:\n return issues\n\n\ndef main(args):\n cachefile = py.path.local(args.cache)\n if not cachefile.exists() or args.refresh:\n issues = get_issues()\n cachefile.write(json.dumps(issues))\n else:\n issues = json.loads(cachefile.read())\n\n open_issues = [x for x in issues if x[\"state\"] == \"open\"]\n\n open_issues.sort(key=lambda x: x[\"number\"])\n report(open_issues)\n\n\ndef _get_kind(issue):\n labels = [l[\"name\"] for l in issue[\"labels\"]]\n for key in (\"bug\", \"enhancement\", \"proposal\"):\n if key in labels:\n return key\n return \"issue\"\n\n\ndef report(issues):\n for issue in issues:\n title = issue[\"title\"]\n # body = issue[\"body\"]\n kind = _get_kind(issue)\n status = issue[\"state\"]\n number = issue[\"number\"]\n link = \"https://github.com/pytest-dev/pytest/issues/%s/\" % number\n print(\"----\")\n print(status, kind, link)\n print(title)\n # print()\n # lines = body.split(\"\\n\")\n # print(\"\\n\".join(lines[:3]))\n # if len(lines) > 3 or len(body) > 240:\n # print(\"...\")\n print(\"\\n\\nFound %s open issues\" % len(issues))\n\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser(\"process bitbucket issues\")\n parser.add_argument(\n \"--refresh\", action=\"store_true\", help=\"invalidate cache, refresh issues\"\n )\n parser.add_argument(\n \"--cache\", action=\"store\", default=\"issues.json\", help=\"cache file\"\n )\n args = parser.parse_args()\n main(args)\n"},{"attributeType":"BaseException | None","col":4,"comment":"null","endLoc":1930,"id":201,"name":"__context__","nodeType":"Attribute","startLoc":1930,"text":"__context__"},{"attributeType":"str","col":0,"comment":"null","endLoc":23,"id":202,"name":"FIXTURE_FUNCTION_CALL","nodeType":"Attribute","startLoc":23,"text":"FIXTURE_FUNCTION_CALL"},{"attributeType":"PytestDeprecationWarning","col":0,"comment":"null","endLoc":30,"id":203,"name":"FIXTURE_NAMED_REQUEST","nodeType":"Attribute","startLoc":30,"text":"FIXTURE_NAMED_REQUEST"},{"attributeType":"bool","col":4,"comment":"null","endLoc":1931,"id":204,"name":"__suppress_context__","nodeType":"Attribute","startLoc":1931,"text":"__suppress_context__"},{"className":"PurePath","col":0,"comment":"null","endLoc":98,"id":205,"nodeType":"Class","startLoc":29,"text":"class PurePath(PathLike[str]):\n if sys.version_info >= (3, 13):\n parser: ClassVar[types.ModuleType]\n def full_match(self, pattern: StrPath, *, case_sensitive: bool | None = None) -> bool: ...\n\n @property\n def parts(self) -> tuple[str, ...]: ...\n @property\n def drive(self) -> str: ...\n @property\n def root(self) -> str: ...\n @property\n def anchor(self) -> str: ...\n @property\n def name(self) -> str: ...\n @property\n def suffix(self) -> str: ...\n @property\n def suffixes(self) -> list[str]: ...\n @property\n def stem(self) -> str: ...\n if sys.version_info >= (3, 12):\n def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ...\n def __init__(self, *args: StrPath) -> None: ... # pyright: ignore[reportInconsistentConstructor]\n else:\n def __new__(cls, *args: StrPath) -> Self: ...\n\n def __hash__(self) -> int: ...\n def __fspath__(self) -> str: ...\n def __lt__(self, other: PurePath) -> bool: ...\n def __le__(self, other: PurePath) -> bool: ...\n def __gt__(self, other: PurePath) -> bool: ...\n def __ge__(self, other: PurePath) -> bool: ...\n def __truediv__(self, key: StrPath) -> Self: ...\n def __rtruediv__(self, key: StrPath) -> Self: ...\n def __bytes__(self) -> bytes: ...\n def as_posix(self) -> str: ...\n def as_uri(self) -> str: ...\n def is_absolute(self) -> bool: ...\n def is_reserved(self) -> bool: ...\n if sys.version_info >= (3, 12):\n def is_relative_to(self, other: StrPath, /, *_deprecated: StrPath) -> bool: ...\n elif sys.version_info >= (3, 9):\n def is_relative_to(self, *other: StrPath) -> bool: ...\n\n if sys.version_info >= (3, 12):\n def match(self, path_pattern: str, *, case_sensitive: bool | None = None) -> bool: ...\n else:\n def match(self, path_pattern: str) -> bool: ...\n\n if sys.version_info >= (3, 12):\n def relative_to(self, other: StrPath, /, *_deprecated: StrPath, walk_up: bool = False) -> Self: ...\n else:\n def relative_to(self, *other: StrPath) -> Self: ...\n\n def with_name(self, name: str) -> Self: ...\n if sys.version_info >= (3, 9):\n def with_stem(self, stem: str) -> Self: ...\n\n def with_suffix(self, suffix: str) -> Self: ...\n def joinpath(self, *other: StrPath) -> Self: ...\n @property\n def parents(self) -> Sequence[Self]: ...\n @property\n def parent(self) -> Self: ...\n if sys.version_info >= (3, 9) and sys.version_info < (3, 11):\n def __class_getitem__(cls, type: Any) -> GenericAlias: ...\n\n if sys.version_info >= (3, 12):\n def with_segments(self, *args: StrPath) -> Self: ..."},{"attributeType":"TracebackType | None","col":4,"comment":"null","endLoc":1932,"id":206,"name":"__traceback__","nodeType":"Attribute","startLoc":1932,"text":"__traceback__"},{"col":0,"comment":"null","endLoc":31,"header":"def get_issues()","id":207,"name":"get_issues","nodeType":"Function","startLoc":10,"text":"def get_issues():\n issues = []\n url = issues_url\n while 1:\n get_data = {\"state\": \"all\"}\n r = requests.get(url, params=get_data)\n data = r.json()\n if r.status_code == 403:\n # API request limit exceeded\n print(data[\"message\"])\n exit(1)\n issues.extend(data)\n\n # Look for next page\n links = requests.utils.parse_header_links(r.headers[\"Link\"])\n another_page = False\n for link in links:\n if link[\"rel\"] == \"next\":\n url = link[\"url\"]\n another_page = True\n if not another_page:\n return issues"},{"col":4,"comment":"null","endLoc":31,"header":"def __repr__(self)","id":208,"name":"__repr__","nodeType":"Function","startLoc":25,"text":"def __repr__(self):\n if self.msg:\n val = self.msg\n if isinstance(val, bytes):\n val = val.decode(\"UTF-8\", errors=\"replace\")\n return val\n return \"<%s instance>\" % (self.__class__.__name__,)"},{"col":4,"comment":"null","endLoc":1015,"header":"def extend(self, __iterable: Iterable[_T]) -> None","id":212,"name":"extend","nodeType":"Function","startLoc":1015,"text":"def extend(self, __iterable: Iterable[_T]) -> None: ..."},{"col":0,"comment":"null","endLoc":45,"header":"def main(args)","id":213,"name":"main","nodeType":"Function","startLoc":34,"text":"def main(args):\n cachefile = py.path.local(args.cache)\n if not cachefile.exists() or args.refresh:\n issues = get_issues()\n cachefile.write(json.dumps(issues))\n else:\n issues = json.loads(cachefile.read())\n\n open_issues = [x for x in issues if x[\"state\"] == \"open\"]\n\n open_issues.sort(key=lambda x: x[\"number\"])\n report(open_issues)"},{"col":0,"comment":"","endLoc":5,"header":"tox_run.py#","id":214,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"\nCalled by tox.ini: uses the generated executable to run the tests in ./tests/\ndirectory.\n\"\"\"\n\nif __name__ == \"__main__\":\n import os\n import sys\n\n executable = os.path.join(os.getcwd(), \"dist\", \"runtests_script\", \"runtests_script\")\n if sys.platform.startswith(\"win\"):\n executable += \".exe\"\n sys.exit(os.system(\"%s tests\" % executable))"},{"col":4,"comment":"null","endLoc":35,"header":"@property\n def parts(self) -> tuple[str, ...]","id":216,"name":"parts","nodeType":"Function","startLoc":34,"text":"@property\n def parts(self) -> tuple[str, ...]: ..."},{"col":4,"comment":"null","endLoc":37,"header":"@property\n def drive(self) -> str","id":217,"name":"drive","nodeType":"Function","startLoc":36,"text":"@property\n def drive(self) -> str: ..."},{"col":4,"comment":"null","endLoc":39,"header":"@property\n def root(self) -> str","id":218,"name":"root","nodeType":"Function","startLoc":38,"text":"@property\n def root(self) -> str: ..."},{"col":4,"comment":"null","endLoc":41,"header":"@property\n def anchor(self) -> str","id":219,"name":"anchor","nodeType":"Function","startLoc":40,"text":"@property\n def anchor(self) -> str: ..."},{"col":4,"comment":"null","endLoc":43,"header":"@property\n def name(self) -> str","id":220,"name":"name","nodeType":"Function","startLoc":42,"text":"@property\n def name(self) -> str: ..."},{"col":4,"comment":"null","endLoc":45,"header":"@property\n def suffix(self) -> str","id":221,"name":"suffix","nodeType":"Function","startLoc":44,"text":"@property\n def suffix(self) -> str: ..."},{"col":4,"comment":"null","endLoc":47,"header":"@property\n def suffixes(self) -> list[str]","id":222,"name":"suffixes","nodeType":"Function","startLoc":46,"text":"@property\n def suffixes(self) -> list[str]: ..."},{"col":4,"comment":"null","endLoc":49,"header":"@property\n def stem(self) -> str","id":223,"name":"stem","nodeType":"Function","startLoc":48,"text":"@property\n def stem(self) -> str: ..."},{"col":8,"comment":"null","endLoc":54,"header":"def __new__(cls, *args: StrPath) -> Self","id":224,"name":"__new__","nodeType":"Function","startLoc":54,"text":"def __new__(cls, *args: StrPath) -> Self: ..."},{"col":4,"comment":"null","endLoc":56,"header":"def __hash__(self) -> int","id":225,"name":"__hash__","nodeType":"Function","startLoc":56,"text":"def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":57,"header":"def __fspath__(self) -> str","id":226,"name":"__fspath__","nodeType":"Function","startLoc":57,"text":"def __fspath__(self) -> str: ..."},{"col":4,"comment":"null","endLoc":58,"header":"def __lt__(self, other: PurePath) -> bool","id":227,"name":"__lt__","nodeType":"Function","startLoc":58,"text":"def __lt__(self, other: PurePath) -> bool: ..."},{"col":4,"comment":"null","endLoc":59,"header":"def __le__(self, other: PurePath) -> bool","id":228,"name":"__le__","nodeType":"Function","startLoc":59,"text":"def __le__(self, other: PurePath) -> bool: ..."},{"col":4,"comment":"null","endLoc":60,"header":"def __gt__(self, other: PurePath) -> bool","id":229,"name":"__gt__","nodeType":"Function","startLoc":60,"text":"def __gt__(self, other: PurePath) -> bool: ..."},{"col":4,"comment":"null","endLoc":61,"header":"def __ge__(self, other: PurePath) -> bool","id":230,"name":"__ge__","nodeType":"Function","startLoc":61,"text":"def __ge__(self, other: PurePath) -> bool: ..."},{"col":4,"comment":"null","endLoc":62,"header":"def __truediv__(self, key: StrPath) -> Self","id":231,"name":"__truediv__","nodeType":"Function","startLoc":62,"text":"def __truediv__(self, key: StrPath) -> Self: ..."},{"col":4,"comment":"null","endLoc":63,"header":"def __rtruediv__(self, key: StrPath) -> Self","id":232,"name":"__rtruediv__","nodeType":"Function","startLoc":63,"text":"def __rtruediv__(self, key: StrPath) -> Self: ..."},{"col":4,"comment":"null","endLoc":64,"header":"def __bytes__(self) -> bytes","id":233,"name":"__bytes__","nodeType":"Function","startLoc":64,"text":"def __bytes__(self) -> bytes: ..."},{"col":4,"comment":"null","endLoc":65,"header":"def as_posix(self) -> str","id":234,"name":"as_posix","nodeType":"Function","startLoc":65,"text":"def as_posix(self) -> str: ..."},{"col":4,"comment":"null","endLoc":66,"header":"def as_uri(self) -> str","id":235,"name":"as_uri","nodeType":"Function","startLoc":66,"text":"def as_uri(self) -> str: ..."},{"col":4,"comment":"null","endLoc":67,"header":"def is_absolute(self) -> bool","id":236,"name":"is_absolute","nodeType":"Function","startLoc":67,"text":"def is_absolute(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":68,"header":"def is_reserved(self) -> bool","id":237,"name":"is_reserved","nodeType":"Function","startLoc":68,"text":"def is_reserved(self) -> bool: ..."},{"col":8,"comment":"null","endLoc":72,"header":"def is_relative_to(self, *other: StrPath) -> bool","id":238,"name":"is_relative_to","nodeType":"Function","startLoc":72,"text":"def is_relative_to(self, *other: StrPath) -> bool: ..."},{"col":8,"comment":"null","endLoc":77,"header":"def match(self, path_pattern: str) -> bool","id":239,"name":"match","nodeType":"Function","startLoc":77,"text":"def match(self, path_pattern: str) -> bool: ..."},{"col":8,"comment":"null","endLoc":82,"header":"def relative_to(self, *other: StrPath) -> Self","id":240,"name":"relative_to","nodeType":"Function","startLoc":82,"text":"def relative_to(self, *other: StrPath) -> Self: ..."},{"col":4,"comment":"null","endLoc":84,"header":"def with_name(self, name: str) -> Self","id":241,"name":"with_name","nodeType":"Function","startLoc":84,"text":"def with_name(self, name: str) -> Self: ..."},{"col":8,"comment":"null","endLoc":86,"header":"def with_stem(self, stem: str) -> Self","id":242,"name":"with_stem","nodeType":"Function","startLoc":86,"text":"def with_stem(self, stem: str) -> Self: ..."},{"col":4,"comment":"null","endLoc":88,"header":"def with_suffix(self, suffix: str) -> Self","id":243,"name":"with_suffix","nodeType":"Function","startLoc":88,"text":"def with_suffix(self, suffix: str) -> Self: ..."},{"col":4,"comment":"null","endLoc":89,"header":"def joinpath(self, *other: StrPath) -> Self","id":244,"name":"joinpath","nodeType":"Function","startLoc":89,"text":"def joinpath(self, *other: StrPath) -> Self: ..."},{"col":4,"comment":"null","endLoc":91,"header":"@property\n def parents(self) -> Sequence[Self]","id":245,"name":"parents","nodeType":"Function","startLoc":90,"text":"@property\n def parents(self) -> Sequence[Self]: ..."},{"col":4,"comment":"null","endLoc":93,"header":"@property\n def parent(self) -> Self","id":246,"name":"parent","nodeType":"Function","startLoc":92,"text":"@property\n def parent(self) -> Self: ..."},{"col":8,"comment":"null","endLoc":95,"header":"def __class_getitem__(cls, type: Any) -> GenericAlias","id":247,"name":"__class_getitem__","nodeType":"Function","startLoc":95,"text":"def __class_getitem__(cls, type: Any) -> GenericAlias: ..."},{"col":8,"comment":"null","endLoc":107,"header":"def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self","id":248,"name":"__new__","nodeType":"Function","startLoc":107,"text":"def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ..."},{"col":4,"comment":"null","endLoc":110,"header":"@classmethod\n def cwd(cls) -> Self","id":249,"name":"cwd","nodeType":"Function","startLoc":109,"text":"@classmethod\n def cwd(cls) -> Self: ..."},{"col":8,"comment":"null","endLoc":115,"header":"def stat(self) -> stat_result","id":250,"name":"stat","nodeType":"Function","startLoc":115,"text":"def stat(self) -> stat_result: ..."},{"col":8,"comment":"null","endLoc":116,"header":"def chmod(self, mode: int) -> None","id":251,"name":"chmod","nodeType":"Function","startLoc":116,"text":"def chmod(self, mode: int) -> None: ..."},{"col":8,"comment":"null","endLoc":125,"header":"def __enter__(self) -> Self","id":252,"name":"__enter__","nodeType":"Function","startLoc":125,"text":"def __enter__(self) -> Self: ..."},{"col":8,"comment":"null","endLoc":126,"header":"def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None","id":253,"name":"__exit__","nodeType":"Function","startLoc":126,"text":"def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ..."},{"col":8,"comment":"null","endLoc":127,"header":"def is_dir(self) -> bool","id":254,"name":"is_dir","nodeType":"Function","startLoc":127,"text":"def is_dir(self) -> bool: ..."},{"col":8,"comment":"null","endLoc":128,"header":"def is_file(self) -> bool","id":255,"name":"is_file","nodeType":"Function","startLoc":128,"text":"def is_file(self) -> bool: ..."},{"col":8,"comment":"null","endLoc":129,"header":"def read_text(self, encoding: str | None = None, errors: str | None = None) -> str","id":256,"name":"read_text","nodeType":"Function","startLoc":129,"text":"def read_text(self, encoding: str | None = None, errors: str | None = None) -> str: ..."},{"col":8,"comment":"null","endLoc":142,"header":"def glob(self, pattern: str) -> Generator[Self, None, None]","id":257,"name":"glob","nodeType":"Function","startLoc":142,"text":"def glob(self, pattern: str) -> Generator[Self, None, None]: ..."},{"col":8,"comment":"null","endLoc":143,"header":"def rglob(self, pattern: str) -> Generator[Self, None, None]","id":258,"name":"rglob","nodeType":"Function","startLoc":143,"text":"def rglob(self, pattern: str) -> Generator[Self, None, None]: ..."},{"col":8,"comment":"null","endLoc":148,"header":"def exists(self) -> bool","id":259,"name":"exists","nodeType":"Function","startLoc":148,"text":"def exists(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":150,"header":"def is_symlink(self) -> bool","id":260,"name":"is_symlink","nodeType":"Function","startLoc":150,"text":"def is_symlink(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":151,"header":"def is_socket(self) -> bool","id":261,"name":"is_socket","nodeType":"Function","startLoc":151,"text":"def is_socket(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":152,"header":"def is_fifo(self) -> bool","id":262,"name":"is_fifo","nodeType":"Function","startLoc":152,"text":"def is_fifo(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":153,"header":"def is_block_device(self) -> bool","id":263,"name":"is_block_device","nodeType":"Function","startLoc":153,"text":"def is_block_device(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":154,"header":"def is_char_device(self) -> bool","id":264,"name":"is_char_device","nodeType":"Function","startLoc":154,"text":"def is_char_device(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":158,"header":"def iterdir(self) -> Generator[Self, None, None]","id":265,"name":"iterdir","nodeType":"Function","startLoc":158,"text":"def iterdir(self) -> Generator[Self, None, None]: ..."},{"col":4,"comment":"null","endLoc":159,"header":"def lchmod(self, mode: int) -> None","id":266,"name":"lchmod","nodeType":"Function","startLoc":159,"text":"def lchmod(self, mode: int) -> None: ..."},{"col":4,"comment":"null","endLoc":160,"header":"def lstat(self) -> stat_result","id":267,"name":"lstat","nodeType":"Function","startLoc":160,"text":"def lstat(self) -> stat_result: ..."},{"col":4,"comment":"null","endLoc":161,"header":"def mkdir(self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None","id":268,"name":"mkdir","nodeType":"Function","startLoc":161,"text":"def mkdir(self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None: ..."},{"col":4,"comment":"null","endLoc":173,"header":"@overload\n def open(\n self,\n mode: OpenTextMode = \"r\",\n buffering: int = -1,\n encoding: str | None = None,\n errors: str | None = None,\n newline: str | None = None,\n ) -> TextIOWrapper","id":269,"name":"open","nodeType":"Function","startLoc":165,"text":"@overload\n def open(\n self,\n mode: OpenTextMode = \"r\",\n buffering: int = -1,\n encoding: str | None = None,\n errors: str | None = None,\n newline: str | None = None,\n ) -> TextIOWrapper: ..."},{"col":4,"comment":"null","endLoc":178,"header":"@overload\n def open(\n self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = None, errors: None = None, newline: None = None\n ) -> FileIO","id":270,"name":"open","nodeType":"Function","startLoc":175,"text":"@overload\n def open(\n self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = None, errors: None = None, newline: None = None\n ) -> FileIO: ..."},{"col":4,"comment":"null","endLoc":188,"header":"@overload\n def open(\n self,\n mode: OpenBinaryModeUpdating,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedRandom","id":271,"name":"open","nodeType":"Function","startLoc":180,"text":"@overload\n def open(\n self,\n mode: OpenBinaryModeUpdating,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedRandom: ..."},{"col":4,"comment":"null","endLoc":197,"header":"@overload\n def open(\n self,\n mode: OpenBinaryModeWriting,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedWriter","id":272,"name":"open","nodeType":"Function","startLoc":189,"text":"@overload\n def open(\n self,\n mode: OpenBinaryModeWriting,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedWriter: ..."},{"col":4,"comment":"null","endLoc":206,"header":"@overload\n def open(\n self,\n mode: OpenBinaryModeReading,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedReader","id":273,"name":"open","nodeType":"Function","startLoc":198,"text":"@overload\n def open(\n self,\n mode: OpenBinaryModeReading,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedReader: ..."},{"col":4,"comment":"null","endLoc":211,"header":"@overload\n def open(\n self, mode: OpenBinaryMode, buffering: int = -1, encoding: None = None, errors: None = None, newline: None = None\n ) -> BinaryIO","id":274,"name":"open","nodeType":"Function","startLoc":208,"text":"@overload\n def open(\n self, mode: OpenBinaryMode, buffering: int = -1, encoding: None = None, errors: None = None, newline: None = None\n ) -> BinaryIO: ..."},{"col":4,"comment":"null","endLoc":216,"header":"@overload\n def open(\n self, mode: str, buffering: int = -1, encoding: str | None = None, errors: str | None = None, newline: str | None = None\n ) -> IO[Any]","id":275,"name":"open","nodeType":"Function","startLoc":213,"text":"@overload\n def open(\n self, mode: str, buffering: int = -1, encoding: str | None = None, errors: str | None = None, newline: str | None = None\n ) -> IO[Any]: ..."},{"col":12,"comment":"null","endLoc":224,"header":"def owner(self) -> str","id":276,"name":"owner","nodeType":"Function","startLoc":224,"text":"def owner(self) -> str: ..."},{"col":12,"comment":"null","endLoc":225,"header":"def group(self) -> str","id":277,"name":"group","nodeType":"Function","startLoc":225,"text":"def group(self) -> str: ..."},{"col":8,"comment":"null","endLoc":230,"header":"def is_mount(self) -> bool","id":278,"name":"is_mount","nodeType":"Function","startLoc":230,"text":"def is_mount(self) -> bool: ..."},{"col":8,"comment":"null","endLoc":233,"header":"def readlink(self) -> Self","id":279,"name":"readlink","nodeType":"Function","startLoc":233,"text":"def readlink(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":235,"header":"def rename(self, target: str | PurePath) -> Self","id":280,"name":"rename","nodeType":"Function","startLoc":235,"text":"def rename(self, target: str | PurePath) -> Self: ..."},{"col":4,"comment":"null","endLoc":236,"header":"def replace(self, target: str | PurePath) -> Self","id":281,"name":"replace","nodeType":"Function","startLoc":236,"text":"def replace(self, target: str | PurePath) -> Self: ..."},{"col":4,"comment":"null","endLoc":237,"header":"def resolve(self, strict: bool = False) -> Self","id":282,"name":"resolve","nodeType":"Function","startLoc":237,"text":"def resolve(self, strict: bool = False) -> Self: ..."},{"col":4,"comment":"null","endLoc":238,"header":"def rmdir(self) -> None","id":283,"name":"rmdir","nodeType":"Function","startLoc":238,"text":"def rmdir(self) -> None: ..."},{"col":4,"comment":"null","endLoc":239,"header":"def symlink_to(self, target: StrOrBytesPath, target_is_directory: bool = False) -> None","id":284,"name":"symlink_to","nodeType":"Function","startLoc":239,"text":"def symlink_to(self, target: StrOrBytesPath, target_is_directory: bool = False) -> None: ..."},{"col":4,"comment":"null","endLoc":243,"header":"def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None","id":285,"name":"touch","nodeType":"Function","startLoc":243,"text":"def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None: ..."},{"col":4,"comment":"null","endLoc":244,"header":"def unlink(self, missing_ok: bool = False) -> None","id":286,"name":"unlink","nodeType":"Function","startLoc":244,"text":"def unlink(self, missing_ok: bool = False) -> None: ..."},{"col":4,"comment":"null","endLoc":246,"header":"@classmethod\n def home(cls) -> Self","id":287,"name":"home","nodeType":"Function","startLoc":245,"text":"@classmethod\n def home(cls) -> Self: ..."},{"col":4,"comment":"null","endLoc":247,"header":"def absolute(self) -> Self","id":288,"name":"absolute","nodeType":"Function","startLoc":247,"text":"def absolute(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":248,"header":"def expanduser(self) -> Self","id":289,"name":"expanduser","nodeType":"Function","startLoc":248,"text":"def expanduser(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":249,"header":"def read_bytes(self) -> bytes","id":290,"name":"read_bytes","nodeType":"Function","startLoc":249,"text":"def read_bytes(self) -> bytes: ..."},{"col":4,"comment":"null","endLoc":250,"header":"def samefile(self, other_path: StrPath) -> bool","id":291,"name":"samefile","nodeType":"Function","startLoc":250,"text":"def samefile(self, other_path: StrPath) -> bool: ..."},{"col":4,"comment":"null","endLoc":251,"header":"def write_bytes(self, data: ReadableBuffer) -> int","id":292,"name":"write_bytes","nodeType":"Function","startLoc":251,"text":"def write_bytes(self, data: ReadableBuffer) -> int: ..."},{"col":8,"comment":"null","endLoc":257,"header":"def write_text(self, data: str, encoding: str | None = None, errors: str | None = None) -> int","id":293,"name":"write_text","nodeType":"Function","startLoc":257,"text":"def write_text(self, data: str, encoding: str | None = None, errors: str | None = None) -> int: ..."},{"col":12,"comment":"null","endLoc":263,"header":"def link_to(self, target: StrOrBytesPath) -> None","id":294,"name":"link_to","nodeType":"Function","startLoc":263,"text":"def link_to(self, target: StrOrBytesPath) -> None: ..."},{"col":0,"comment":"null","endLoc":33,"header":"def publish_github_release(slug, token, tag_name, body)","id":295,"name":"publish_github_release","nodeType":"Function","startLoc":29,"text":"def publish_github_release(slug, token, tag_name, body):\n github = github3.login(token=token)\n owner, repo = slug.split(\"/\")\n repo = github.repository(owner, repo)\n return repo.create_release(tag_name=tag_name, body=body)"},{"attributeType":"str","col":0,"comment":"null","endLoc":34,"id":296,"name":"CFG_PYTEST_SECTION","nodeType":"Attribute","startLoc":34,"text":"CFG_PYTEST_SECTION"},{"attributeType":"RemovedInPytest4Warning","col":0,"comment":"null","endLoc":36,"id":297,"name":"GETFUNCARGVALUE","nodeType":"Attribute","startLoc":36,"text":"GETFUNCARGVALUE"},{"col":0,"comment":"null","endLoc":55,"header":"def parse_changelog(tag_name)","id":298,"name":"parse_changelog","nodeType":"Function","startLoc":36,"text":"def parse_changelog(tag_name):\n p = Path(__file__).parent.parent / \"CHANGELOG.rst\"\n changelog_lines = p.read_text(encoding=\"UTF-8\").splitlines()\n\n title_regex = re.compile(r\"pytest (\\d\\.\\d+\\.\\d+) \\(\\d{4}-\\d{2}-\\d{2}\\)\")\n consuming_version = False\n version_lines = []\n for line in changelog_lines:\n m = title_regex.match(line)\n if m:\n # found the version we want: start to consume lines until we find the next version title\n if m.group(1) == tag_name:\n consuming_version = True\n # found a new version title while parsing the version we want: break out\n elif consuming_version:\n break\n if consuming_version:\n version_lines.append(line)\n\n return \"\\n\".join(version_lines)"},{"attributeType":"PytestDeprecationWarning","col":0,"comment":"null","endLoc":40,"id":300,"name":"RAISES_MESSAGE_PARAMETER","nodeType":"Attribute","startLoc":40,"text":"RAISES_MESSAGE_PARAMETER"},{"col":25,"endLoc":44,"id":302,"nodeType":"Lambda","startLoc":44,"text":"lambda x: x[\"number\"]"},{"col":4,"comment":"null","endLoc":442,"header":"@overload\n def __new__(cls, object: object = ...) -> Self","id":303,"name":"__new__","nodeType":"Function","startLoc":441,"text":"@overload\n def __new__(cls, object: object = ...) -> Self: ..."},{"col":4,"comment":"null","endLoc":444,"header":"@overload\n def __new__(cls, object: ReadableBuffer, encoding: str = ..., errors: str = ...) -> Self","id":304,"name":"__new__","nodeType":"Function","startLoc":443,"text":"@overload\n def __new__(cls, object: ReadableBuffer, encoding: str = ..., errors: str = ...) -> Self: ..."},{"attributeType":"PytestDeprecationWarning","col":0,"comment":"null","endLoc":47,"id":305,"name":"RESULT_LOG","nodeType":"Attribute","startLoc":47,"text":"RESULT_LOG"},{"attributeType":"PytestDeprecationWarning","col":0,"comment":"null","endLoc":52,"id":306,"name":"RAISES_EXEC","nodeType":"Attribute","startLoc":52,"text":"RAISES_EXEC"},{"attributeType":"PytestDeprecationWarning","col":0,"comment":"null","endLoc":56,"id":308,"name":"WARNS_EXEC","nodeType":"Attribute","startLoc":56,"text":"WARNS_EXEC"},{"attributeType":"function","col":4,"comment":"null","endLoc":33,"id":310,"name":"__str__","nodeType":"Attribute","startLoc":33,"text":"__str__"},{"attributeType":"str","col":0,"comment":"null","endLoc":61,"id":314,"name":"PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST","nodeType":"Attribute","startLoc":61,"text":"PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST"},{"attributeType":"PytestDeprecationWarning","col":0,"comment":"null","endLoc":71,"id":315,"name":"PYTEST_CONFIG_GLOBAL","nodeType":"Attribute","startLoc":71,"text":"PYTEST_CONFIG_GLOBAL"},{"attributeType":"null","col":8,"comment":"null","endLoc":22,"id":316,"name":"msg","nodeType":"Attribute","startLoc":22,"text":"self.msg"},{"attributeType":"bool","col":8,"comment":"null","endLoc":23,"id":317,"name":"pytrace","nodeType":"Attribute","startLoc":23,"text":"self.pytrace"},{"attributeType":"RemovedInPytest4Warning","col":0,"comment":"null","endLoc":76,"id":320,"name":"PYTEST_ENSURETEMP","nodeType":"Attribute","startLoc":76,"text":"PYTEST_ENSURETEMP"},{"className":"Skipped","col":0,"comment":"null","endLoc":46,"id":321,"nodeType":"Class","startLoc":39,"text":"class Skipped(OutcomeException):\n # XXX hackish: on 3k we fake to live in the builtins\n # in order to have Skipped exception printing shorter/nicer\n __module__ = \"builtins\"\n\n def __init__(self, msg=None, pytrace=True, allow_module_level=False):\n OutcomeException.__init__(self, msg=msg, pytrace=pytrace)\n self.allow_module_level = allow_module_level"},{"attributeType":"str","col":4,"comment":"null","endLoc":42,"id":322,"name":"__module__","nodeType":"Attribute","startLoc":42,"text":"__module__"},{"attributeType":"bool","col":8,"comment":"null","endLoc":46,"id":323,"name":"allow_module_level","nodeType":"Attribute","startLoc":46,"text":"self.allow_module_level"},{"attributeType":"PytestDeprecationWarning","col":0,"comment":"null","endLoc":81,"id":324,"name":"PYTEST_LOGWARNING","nodeType":"Attribute","startLoc":81,"text":"PYTEST_LOGWARNING"},{"className":"Failed","col":0,"comment":" raised from an explicit call to pytest.fail() ","endLoc":52,"id":325,"nodeType":"Class","startLoc":49,"text":"class Failed(OutcomeException):\n \"\"\" raised from an explicit call to pytest.fail() \"\"\"\n\n __module__ = \"builtins\""},{"col":4,"comment":"null","endLoc":84,"header":"def __init__(self, predicate: _Predicate[_T] | None, iterable: Iterable[_T], /) -> None","id":326,"name":"__init__","nodeType":"Function","startLoc":84,"text":"def __init__(self, predicate: _Predicate[_T] | None, iterable: Iterable[_T], /) -> None: ..."},{"attributeType":"str","col":4,"comment":"null","endLoc":52,"id":327,"name":"__module__","nodeType":"Attribute","startLoc":52,"text":"__module__"},{"className":"Exit","col":0,"comment":" raised for immediate program exits (no tracebacks/summaries)","endLoc":61,"id":328,"nodeType":"Class","startLoc":55,"text":"class Exit(Exception):\n \"\"\" raised for immediate program exits (no tracebacks/summaries)\"\"\"\n\n def __init__(self, msg=\"unknown reason\", returncode=None):\n self.msg = msg\n self.returncode = returncode\n super(Exit, self).__init__(msg)"},{"attributeType":"UnformattedWarning","col":0,"comment":"null","endLoc":86,"id":329,"name":"PYTEST_WARNS_UNKNOWN_KWARGS","nodeType":"Attribute","startLoc":86,"text":"PYTEST_WARNS_UNKNOWN_KWARGS"},{"col":4,"comment":"null","endLoc":61,"header":"def __init__(self, msg=\"unknown reason\", returncode=None)","id":330,"name":"__init__","nodeType":"Function","startLoc":58,"text":"def __init__(self, msg=\"unknown reason\", returncode=None):\n self.msg = msg\n self.returncode = returncode\n super(Exit, self).__init__(msg)"},{"attributeType":"UnformattedWarning","col":0,"comment":"null","endLoc":92,"id":331,"name":"PYTEST_PARAM_UNKNOWN_KWARGS","nodeType":"Attribute","startLoc":92,"text":"PYTEST_PARAM_UNKNOWN_KWARGS"},{"col":0,"comment":"","endLoc":11,"header":"deprecated.py#","id":334,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"\nThis module contains deprecation messages and bits of code used elsewhere in the codebase\nthat is planned to be removed in the next pytest release.\n\nKeeping it in a central location makes it easy to track what is deprecated and should\nbe removed when the time comes.\n\nAll constants defined in this module should be either PytestWarning instances or UnformattedWarning\nin case of warnings which need to format their messages.\n\"\"\"\n\nYIELD_TESTS = \"yield tests were removed in pytest 4.0 - {name} will be ignored\"\n\nFIXTURE_FUNCTION_CALL = (\n 'Fixture \"{name}\" called directly. Fixtures are not meant to be called directly,\\n'\n \"but are created automatically when test functions request them as parameters.\\n\"\n \"See https://docs.pytest.org/en/latest/fixture.html for more information about fixtures, and\\n\"\n \"https://docs.pytest.org/en/latest/deprecations.html#calling-fixtures-directly about how to update your code.\"\n)\n\nFIXTURE_NAMED_REQUEST = PytestDeprecationWarning(\n \"'request' is a reserved name for fixtures and will raise an error in future versions\"\n)\n\nCFG_PYTEST_SECTION = \"[pytest] section in {filename} files is no longer supported, change to [tool:pytest] instead.\"\n\nGETFUNCARGVALUE = RemovedInPytest4Warning(\n \"getfuncargvalue is deprecated, use getfixturevalue\"\n)\n\nRAISES_MESSAGE_PARAMETER = PytestDeprecationWarning(\n \"The 'message' parameter is deprecated.\\n\"\n \"(did you mean to use `match='some regex'` to check the exception message?)\\n\"\n \"Please see:\\n\"\n \" https://docs.pytest.org/en/4.6-maintenance/deprecations.html#message-parameter-of-pytest-raises\"\n)\n\nRESULT_LOG = PytestDeprecationWarning(\n \"--result-log is deprecated and scheduled for removal in pytest 5.0.\\n\"\n \"See https://docs.pytest.org/en/latest/deprecations.html#result-log-result-log for more information.\"\n)\n\nRAISES_EXEC = PytestDeprecationWarning(\n \"raises(..., 'code(as_a_string)') is deprecated, use the context manager form or use `exec()` directly\\n\\n\"\n \"See https://docs.pytest.org/en/latest/deprecations.html#raises-warns-exec\"\n)\n\nWARNS_EXEC = PytestDeprecationWarning(\n \"warns(..., 'code(as_a_string)') is deprecated, use the context manager form or use `exec()` directly.\\n\\n\"\n \"See https://docs.pytest.org/en/latest/deprecations.html#raises-warns-exec\"\n)\n\nPYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST = (\n \"Defining 'pytest_plugins' in a non-top-level conftest is no longer supported \"\n \"because it affects the entire directory tree in a non-explicit way.\\n\"\n \" {}\\n\"\n \"Please move it to a top level conftest file at the rootdir:\\n\"\n \" {}\\n\"\n \"For more information, visit:\\n\"\n \" https://docs.pytest.org/en/latest/deprecations.html#pytest-plugins-in-non-top-level-conftest-files\"\n)\n\nPYTEST_CONFIG_GLOBAL = PytestDeprecationWarning(\n \"the `pytest.config` global is deprecated. Please use `request.config` \"\n \"or `pytest_configure` (if you're a pytest plugin) instead.\"\n)\n\nPYTEST_ENSURETEMP = RemovedInPytest4Warning(\n \"pytest/tmpdir_factory.ensuretemp is deprecated, \\n\"\n \"please use the tmp_path fixture or tmp_path_factory.mktemp\"\n)\n\nPYTEST_LOGWARNING = PytestDeprecationWarning(\n \"pytest_logwarning is deprecated, no longer being called, and will be removed soon\\n\"\n \"please use pytest_warning_captured instead\"\n)\n\nPYTEST_WARNS_UNKNOWN_KWARGS = UnformattedWarning(\n PytestDeprecationWarning,\n \"pytest.warns() got unexpected keyword arguments: {args!r}.\\n\"\n \"This will be an error in future versions.\",\n)\n\nPYTEST_PARAM_UNKNOWN_KWARGS = UnformattedWarning(\n PytestDeprecationWarning,\n \"pytest.param() got unexpected keyword arguments: {args!r}.\\n\"\n \"This will be an error in future versions.\",\n)"},{"col":0,"comment":"","endLoc":2,"header":"conftest.py#","id":335,"name":"","nodeType":"Function","startLoc":2,"text":"py3 = sys.version_info[0] >= 3"},{"className":"pytestPDB","col":0,"comment":" Pseudo PDB that defers to the real pdb. ","endLoc":254,"id":336,"nodeType":"Class","startLoc":77,"text":"class pytestPDB(object):\n \"\"\" Pseudo PDB that defers to the real pdb. \"\"\"\n\n _pluginmanager = None\n _config = None\n _saved = []\n _recursive_debug = 0\n _wrapped_pdb_cls = None\n\n @classmethod\n def _is_capturing(cls, capman):\n if capman:\n return capman.is_capturing()\n return False\n\n @classmethod\n def _import_pdb_cls(cls, capman):\n if not cls._config:\n # Happens when using pytest.set_trace outside of a test.\n return pdb.Pdb\n\n usepdb_cls = cls._config.getvalue(\"usepdb_cls\")\n\n if cls._wrapped_pdb_cls and cls._wrapped_pdb_cls[0] == usepdb_cls:\n return cls._wrapped_pdb_cls[1]\n\n if usepdb_cls:\n modname, classname = usepdb_cls\n\n try:\n __import__(modname)\n mod = sys.modules[modname]\n\n # Handle --pdbcls=pdb:pdb.Pdb (useful e.g. with pdbpp).\n parts = classname.split(\".\")\n pdb_cls = getattr(mod, parts[0])\n for part in parts[1:]:\n pdb_cls = getattr(pdb_cls, part)\n except Exception as exc:\n value = \":\".join((modname, classname))\n raise UsageError(\n \"--pdbcls: could not import {!r}: {}\".format(value, exc)\n )\n else:\n pdb_cls = pdb.Pdb\n\n wrapped_cls = cls._get_pdb_wrapper_class(pdb_cls, capman)\n cls._wrapped_pdb_cls = (usepdb_cls, wrapped_cls)\n return wrapped_cls\n\n @classmethod\n def _get_pdb_wrapper_class(cls, pdb_cls, capman):\n import _pytest.config\n\n class PytestPdbWrapper(pdb_cls, object):\n _pytest_capman = capman\n _continued = False\n\n def do_debug(self, arg):\n cls._recursive_debug += 1\n ret = super(PytestPdbWrapper, self).do_debug(arg)\n cls._recursive_debug -= 1\n return ret\n\n def do_continue(self, arg):\n ret = super(PytestPdbWrapper, self).do_continue(arg)\n if cls._recursive_debug == 0:\n tw = _pytest.config.create_terminal_writer(cls._config)\n tw.line()\n\n capman = self._pytest_capman\n capturing = pytestPDB._is_capturing(capman)\n if capturing:\n if capturing == \"global\":\n tw.sep(\">\", \"PDB continue (IO-capturing resumed)\")\n else:\n tw.sep(\n \">\",\n \"PDB continue (IO-capturing resumed for %s)\"\n % capturing,\n )\n capman.resume()\n else:\n tw.sep(\">\", \"PDB continue\")\n cls._pluginmanager.hook.pytest_leave_pdb(config=cls._config, pdb=self)\n self._continued = True\n return ret\n\n do_c = do_cont = do_continue\n\n def do_quit(self, arg):\n \"\"\"Raise Exit outcome when quit command is used in pdb.\n\n This is a bit of a hack - it would be better if BdbQuit\n could be handled, but this would require to wrap the\n whole pytest run, and adjust the report etc.\n \"\"\"\n ret = super(PytestPdbWrapper, self).do_quit(arg)\n\n if cls._recursive_debug == 0:\n outcomes.exit(\"Quitting debugger\")\n\n return ret\n\n do_q = do_quit\n do_exit = do_quit\n\n def setup(self, f, tb):\n \"\"\"Suspend on setup().\n\n Needed after do_continue resumed, and entering another\n breakpoint again.\n \"\"\"\n ret = super(PytestPdbWrapper, self).setup(f, tb)\n if not ret and self._continued:\n # pdb.setup() returns True if the command wants to exit\n # from the interaction: do not suspend capturing then.\n if self._pytest_capman:\n self._pytest_capman.suspend_global_capture(in_=True)\n return ret\n\n def get_stack(self, f, t):\n stack, i = super(PytestPdbWrapper, self).get_stack(f, t)\n if f is None:\n # Find last non-hidden frame.\n i = max(0, len(stack) - 1)\n while i and stack[i][0].f_locals.get(\"__tracebackhide__\", False):\n i -= 1\n return stack, i\n\n return PytestPdbWrapper\n\n @classmethod\n def _init_pdb(cls, method, *args, **kwargs):\n \"\"\" Initialize PDB debugging, dropping any IO capturing. \"\"\"\n import _pytest.config\n\n if cls._pluginmanager is not None:\n capman = cls._pluginmanager.getplugin(\"capturemanager\")\n else:\n capman = None\n if capman:\n capman.suspend(in_=True)\n\n if cls._config:\n tw = _pytest.config.create_terminal_writer(cls._config)\n tw.line()\n\n if cls._recursive_debug == 0:\n # Handle header similar to pdb.set_trace in py37+.\n header = kwargs.pop(\"header\", None)\n if header is not None:\n tw.sep(\">\", header)\n else:\n capturing = cls._is_capturing(capman)\n if capturing == \"global\":\n tw.sep(\">\", \"PDB %s (IO-capturing turned off)\" % (method,))\n elif capturing:\n tw.sep(\n \">\",\n \"PDB %s (IO-capturing turned off for %s)\"\n % (method, capturing),\n )\n else:\n tw.sep(\">\", \"PDB %s\" % (method,))\n\n _pdb = cls._import_pdb_cls(capman)(**kwargs)\n\n if cls._pluginmanager:\n cls._pluginmanager.hook.pytest_enter_pdb(config=cls._config, pdb=_pdb)\n return _pdb\n\n @classmethod\n def set_trace(cls, *args, **kwargs):\n \"\"\"Invoke debugging via ``Pdb.set_trace``, dropping any IO capturing.\"\"\"\n frame = sys._getframe().f_back\n _pdb = cls._init_pdb(\"set_trace\", *args, **kwargs)\n _pdb.set_trace(frame)"},{"className":"Class","col":0,"comment":" Collector for test methods. ","endLoc":789,"id":340,"nodeType":"Class","startLoc":712,"text":"class Class(PyCollector):\n \"\"\" Collector for test methods. \"\"\"\n\n def collect(self):\n if not safe_getattr(self.obj, \"__test__\", True):\n return []\n if hasinit(self.obj):\n self.warn(\n PytestCollectionWarning(\n \"cannot collect test class %r because it has a \"\n \"__init__ constructor (from: %s)\"\n % (self.obj.__name__, self.parent.nodeid)\n )\n )\n return []\n elif hasnew(self.obj):\n self.warn(\n PytestCollectionWarning(\n \"cannot collect test class %r because it has a \"\n \"__new__ constructor (from: %s)\"\n % (self.obj.__name__, self.parent.nodeid)\n )\n )\n return []\n\n self._inject_setup_class_fixture()\n self._inject_setup_method_fixture()\n\n return [Instance(name=\"()\", parent=self)]\n\n def _inject_setup_class_fixture(self):\n \"\"\"Injects a hidden autouse, class scoped fixture into the collected class object\n that invokes setup_class/teardown_class if either or both are available.\n\n Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with\n other fixtures (#517).\n \"\"\"\n setup_class = _get_non_fixture_func(self.obj, \"setup_class\")\n teardown_class = getattr(self.obj, \"teardown_class\", None)\n if setup_class is None and teardown_class is None:\n return\n\n @fixtures.fixture(autouse=True, scope=\"class\")\n def xunit_setup_class_fixture(cls):\n if setup_class is not None:\n func = getimfunc(setup_class)\n _call_with_optional_argument(func, self.obj)\n yield\n if teardown_class is not None:\n func = getimfunc(teardown_class)\n _call_with_optional_argument(func, self.obj)\n\n self.obj.__pytest_setup_class = xunit_setup_class_fixture\n\n def _inject_setup_method_fixture(self):\n \"\"\"Injects a hidden autouse, function scoped fixture into the collected class object\n that invokes setup_method/teardown_method if either or both are available.\n\n Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with\n other fixtures (#517).\n \"\"\"\n setup_method = _get_non_fixture_func(self.obj, \"setup_method\")\n teardown_method = getattr(self.obj, \"teardown_method\", None)\n if setup_method is None and teardown_method is None:\n return\n\n @fixtures.fixture(autouse=True, scope=\"function\")\n def xunit_setup_method_fixture(self, request):\n method = request.function\n if setup_method is not None:\n func = getattr(self, \"setup_method\")\n _call_with_optional_argument(func, method)\n yield\n if teardown_method is not None:\n func = getattr(self, \"teardown_method\")\n _call_with_optional_argument(func, method)\n\n self.obj.__pytest_setup_method = xunit_setup_method_fixture"},{"attributeType":"str","col":8,"comment":"null","endLoc":59,"id":341,"name":"msg","nodeType":"Attribute","startLoc":59,"text":"self.msg"},{"attributeType":"null","col":8,"comment":"null","endLoc":60,"id":345,"name":"returncode","nodeType":"Attribute","startLoc":60,"text":"self.returncode"},{"col":4,"comment":"null","endLoc":90,"header":"@classmethod\n def _is_capturing(cls, capman)","id":346,"name":"_is_capturing","nodeType":"Function","startLoc":86,"text":"@classmethod\n def _is_capturing(cls, capman):\n if capman:\n return capman.is_capturing()\n return False"},{"col":4,"comment":"null","endLoc":125,"header":"@classmethod\n def _import_pdb_cls(cls, capman)","id":347,"name":"_import_pdb_cls","nodeType":"Function","startLoc":92,"text":"@classmethod\n def _import_pdb_cls(cls, capman):\n if not cls._config:\n # Happens when using pytest.set_trace outside of a test.\n return pdb.Pdb\n\n usepdb_cls = cls._config.getvalue(\"usepdb_cls\")\n\n if cls._wrapped_pdb_cls and cls._wrapped_pdb_cls[0] == usepdb_cls:\n return cls._wrapped_pdb_cls[1]\n\n if usepdb_cls:\n modname, classname = usepdb_cls\n\n try:\n __import__(modname)\n mod = sys.modules[modname]\n\n # Handle --pdbcls=pdb:pdb.Pdb (useful e.g. with pdbpp).\n parts = classname.split(\".\")\n pdb_cls = getattr(mod, parts[0])\n for part in parts[1:]:\n pdb_cls = getattr(pdb_cls, part)\n except Exception as exc:\n value = \":\".join((modname, classname))\n raise UsageError(\n \"--pdbcls: could not import {!r}: {}\".format(value, exc)\n )\n else:\n pdb_cls = pdb.Pdb\n\n wrapped_cls = cls._get_pdb_wrapper_class(pdb_cls, capman)\n cls._wrapped_pdb_cls = (usepdb_cls, wrapped_cls)\n return wrapped_cls"},{"className":"XFailed","col":0,"comment":" raised from an explicit call to pytest.xfail() ","endLoc":126,"id":348,"nodeType":"Class","startLoc":125,"text":"class XFailed(fail.Exception):\n \"\"\" raised from an explicit call to pytest.xfail() \"\"\""},{"fileName":"hookspec.py","filePath":"src/_pytest","id":349,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\" hook specifications for pytest plugins, invoked from main.py and builtin plugins. \"\"\"\nfrom pluggy import HookspecMarker\n\nfrom _pytest.deprecated import PYTEST_LOGWARNING\n\nhookspec = HookspecMarker(\"pytest\")\n\n# -------------------------------------------------------------------------\n# Initialization hooks called for every plugin\n# -------------------------------------------------------------------------\n\n\n@hookspec(historic=True)\ndef pytest_addhooks(pluginmanager):\n \"\"\"called at plugin registration time to allow adding new hooks via a call to\n ``pluginmanager.add_hookspecs(module_or_class, prefix)``.\n\n\n :param _pytest.config.PytestPluginManager pluginmanager: pytest plugin manager\n\n .. note::\n This hook is incompatible with ``hookwrapper=True``.\n \"\"\"\n\n\n@hookspec(historic=True)\ndef pytest_plugin_registered(plugin, manager):\n \"\"\" a new pytest plugin got registered.\n\n :param plugin: the plugin module or instance\n :param _pytest.config.PytestPluginManager manager: pytest plugin manager\n\n .. note::\n This hook is incompatible with ``hookwrapper=True``.\n \"\"\"\n\n\n@hookspec(historic=True)\ndef pytest_addoption(parser):\n \"\"\"register argparse-style options and ini-style config values,\n called once at the beginning of a test run.\n\n .. note::\n\n This function should be implemented only in plugins or ``conftest.py``\n files situated at the tests root directory due to how pytest\n :ref:`discovers plugins during startup `.\n\n :arg _pytest.config.Parser parser: To add command line options, call\n :py:func:`parser.addoption(...) <_pytest.config.Parser.addoption>`.\n To add ini-file values call :py:func:`parser.addini(...)\n <_pytest.config.Parser.addini>`.\n\n Options can later be accessed through the\n :py:class:`config <_pytest.config.Config>` object, respectively:\n\n - :py:func:`config.getoption(name) <_pytest.config.Config.getoption>` to\n retrieve the value of a command line option.\n\n - :py:func:`config.getini(name) <_pytest.config.Config.getini>` to retrieve\n a value read from an ini-style file.\n\n The config object is passed around on many internal objects via the ``.config``\n attribute or can be retrieved as the ``pytestconfig`` fixture.\n\n .. note::\n This hook is incompatible with ``hookwrapper=True``.\n \"\"\"\n\n\n@hookspec(historic=True)\ndef pytest_configure(config):\n \"\"\"\n Allows plugins and conftest files to perform initial configuration.\n\n This hook is called for every plugin and initial conftest file\n after command line options have been parsed.\n\n After that, the hook is called for other conftest files as they are\n imported.\n\n .. note::\n This hook is incompatible with ``hookwrapper=True``.\n\n :arg _pytest.config.Config config: pytest config object\n \"\"\"\n\n\n# -------------------------------------------------------------------------\n# Bootstrapping hooks called for plugins registered early enough:\n# internal and 3rd party plugins.\n# -------------------------------------------------------------------------\n\n\n@hookspec(firstresult=True)\ndef pytest_cmdline_parse(pluginmanager, args):\n \"\"\"return initialized config object, parsing the specified args.\n\n Stops at first non-None result, see :ref:`firstresult`\n\n .. note::\n This hook will only be called for plugin classes passed to the ``plugins`` arg when using `pytest.main`_ to\n perform an in-process test run.\n\n :param _pytest.config.PytestPluginManager pluginmanager: pytest plugin manager\n :param list[str] args: list of arguments passed on the command line\n \"\"\"\n\n\ndef pytest_cmdline_preparse(config, args):\n \"\"\"(**Deprecated**) modify command line arguments before option parsing.\n\n This hook is considered deprecated and will be removed in a future pytest version. Consider\n using :func:`pytest_load_initial_conftests` instead.\n\n .. note::\n This hook will not be called for ``conftest.py`` files, only for setuptools plugins.\n\n :param _pytest.config.Config config: pytest config object\n :param list[str] args: list of arguments passed on the command line\n \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_cmdline_main(config):\n \"\"\" called for performing the main command line action. The default\n implementation will invoke the configure hooks and runtest_mainloop.\n\n .. note::\n This hook will not be called for ``conftest.py`` files, only for setuptools plugins.\n\n Stops at first non-None result, see :ref:`firstresult`\n\n :param _pytest.config.Config config: pytest config object\n \"\"\"\n\n\ndef pytest_load_initial_conftests(early_config, parser, args):\n \"\"\" implements the loading of initial conftest files ahead\n of command line option parsing.\n\n .. note::\n This hook will not be called for ``conftest.py`` files, only for setuptools plugins.\n\n :param _pytest.config.Config early_config: pytest config object\n :param list[str] args: list of arguments passed on the command line\n :param _pytest.config.Parser parser: to add command line options\n \"\"\"\n\n\n# -------------------------------------------------------------------------\n# collection hooks\n# -------------------------------------------------------------------------\n\n\n@hookspec(firstresult=True)\ndef pytest_collection(session):\n \"\"\"Perform the collection protocol for the given session.\n\n Stops at first non-None result, see :ref:`firstresult`.\n\n :param _pytest.main.Session session: the pytest session object\n \"\"\"\n\n\ndef pytest_collection_modifyitems(session, config, items):\n \"\"\" called after collection has been performed, may filter or re-order\n the items in-place.\n\n :param _pytest.main.Session session: the pytest session object\n :param _pytest.config.Config config: pytest config object\n :param List[_pytest.nodes.Item] items: list of item objects\n \"\"\"\n\n\ndef pytest_collection_finish(session):\n \"\"\" called after collection has been performed and modified.\n\n :param _pytest.main.Session session: the pytest session object\n \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_ignore_collect(path, config):\n \"\"\" return True to prevent considering this path for collection.\n This hook is consulted for all files and directories prior to calling\n more specific hooks.\n\n Stops at first non-None result, see :ref:`firstresult`\n\n :param path: a :py:class:`py.path.local` - the path to analyze\n :param _pytest.config.Config config: pytest config object\n \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_collect_directory(path, parent):\n \"\"\" called before traversing a directory for collection files.\n\n Stops at first non-None result, see :ref:`firstresult`\n\n :param path: a :py:class:`py.path.local` - the path to analyze\n \"\"\"\n\n\ndef pytest_collect_file(path, parent):\n \"\"\" return collection Node or None for the given path. Any new node\n needs to have the specified ``parent`` as a parent.\n\n :param path: a :py:class:`py.path.local` - the path to collect\n \"\"\"\n\n\n# logging hooks for collection\n\n\ndef pytest_collectstart(collector):\n \"\"\" collector starts collecting. \"\"\"\n\n\ndef pytest_itemcollected(item):\n \"\"\" we just collected a test item. \"\"\"\n\n\ndef pytest_collectreport(report):\n \"\"\" collector finished collecting. \"\"\"\n\n\ndef pytest_deselected(items):\n \"\"\" called for test items deselected, e.g. by keyword. \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_make_collect_report(collector):\n \"\"\" perform ``collector.collect()`` and return a CollectReport.\n\n Stops at first non-None result, see :ref:`firstresult` \"\"\"\n\n\n# -------------------------------------------------------------------------\n# Python test function related hooks\n# -------------------------------------------------------------------------\n\n\n@hookspec(firstresult=True)\ndef pytest_pycollect_makemodule(path, parent):\n \"\"\" return a Module collector or None for the given path.\n This hook will be called for each matching test module path.\n The pytest_collect_file hook needs to be used if you want to\n create test modules for files that do not match as a test module.\n\n Stops at first non-None result, see :ref:`firstresult`\n\n :param path: a :py:class:`py.path.local` - the path of module to collect\n \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_pycollect_makeitem(collector, name, obj):\n \"\"\" return custom item/collector for a python object in a module, or None.\n\n Stops at first non-None result, see :ref:`firstresult` \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_pyfunc_call(pyfuncitem):\n \"\"\" call underlying test function.\n\n Stops at first non-None result, see :ref:`firstresult` \"\"\"\n\n\ndef pytest_generate_tests(metafunc):\n \"\"\" generate (multiple) parametrized calls to a test function.\"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_make_parametrize_id(config, val, argname):\n \"\"\"Return a user-friendly string representation of the given ``val`` that will be used\n by @pytest.mark.parametrize calls. Return None if the hook doesn't know about ``val``.\n The parameter name is available as ``argname``, if required.\n\n Stops at first non-None result, see :ref:`firstresult`\n\n :param _pytest.config.Config config: pytest config object\n :param val: the parametrized value\n :param str argname: the automatic parameter name produced by pytest\n \"\"\"\n\n\n# -------------------------------------------------------------------------\n# generic runtest related hooks\n# -------------------------------------------------------------------------\n\n\n@hookspec(firstresult=True)\ndef pytest_runtestloop(session):\n \"\"\" called for performing the main runtest loop\n (after collection finished).\n\n Stops at first non-None result, see :ref:`firstresult`\n\n :param _pytest.main.Session session: the pytest session object\n \"\"\"\n\n\ndef pytest_itemstart(item, node):\n \"\"\"(**Deprecated**) use pytest_runtest_logstart. \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_runtest_protocol(item, nextitem):\n \"\"\" implements the runtest_setup/call/teardown protocol for\n the given test item, including capturing exceptions and calling\n reporting hooks.\n\n :arg item: test item for which the runtest protocol is performed.\n\n :arg nextitem: the scheduled-to-be-next test item (or None if this\n is the end my friend). This argument is passed on to\n :py:func:`pytest_runtest_teardown`.\n\n :return boolean: True if no further hook implementations should be invoked.\n\n\n Stops at first non-None result, see :ref:`firstresult` \"\"\"\n\n\ndef pytest_runtest_logstart(nodeid, location):\n \"\"\" signal the start of running a single test item.\n\n This hook will be called **before** :func:`pytest_runtest_setup`, :func:`pytest_runtest_call` and\n :func:`pytest_runtest_teardown` hooks.\n\n :param str nodeid: full id of the item\n :param location: a triple of ``(filename, linenum, testname)``\n \"\"\"\n\n\ndef pytest_runtest_logfinish(nodeid, location):\n \"\"\" signal the complete finish of running a single test item.\n\n This hook will be called **after** :func:`pytest_runtest_setup`, :func:`pytest_runtest_call` and\n :func:`pytest_runtest_teardown` hooks.\n\n :param str nodeid: full id of the item\n :param location: a triple of ``(filename, linenum, testname)``\n \"\"\"\n\n\ndef pytest_runtest_setup(item):\n \"\"\" called before ``pytest_runtest_call(item)``. \"\"\"\n\n\ndef pytest_runtest_call(item):\n \"\"\" called to execute the test ``item``. \"\"\"\n\n\ndef pytest_runtest_teardown(item, nextitem):\n \"\"\" called after ``pytest_runtest_call``.\n\n :arg nextitem: the scheduled-to-be-next test item (None if no further\n test item is scheduled). This argument can be used to\n perform exact teardowns, i.e. calling just enough finalizers\n so that nextitem only needs to call setup-functions.\n \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_runtest_makereport(item, call):\n \"\"\" return a :py:class:`_pytest.runner.TestReport` object\n for the given :py:class:`pytest.Item <_pytest.main.Item>` and\n :py:class:`_pytest.runner.CallInfo`.\n\n Stops at first non-None result, see :ref:`firstresult` \"\"\"\n\n\ndef pytest_runtest_logreport(report):\n \"\"\" process a test setup/call/teardown report relating to\n the respective phase of executing a test. \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_report_to_serializable(config, report):\n \"\"\"\n .. warning::\n This hook is experimental and subject to change between pytest releases, even\n bug fixes.\n\n The intent is for this to be used by plugins maintained by the core-devs, such\n as ``pytest-xdist``, ``pytest-subtests``, and as a replacement for the internal\n 'resultlog' plugin.\n\n In the future it might become part of the public hook API.\n\n Serializes the given report object into a data structure suitable for sending\n over the wire, e.g. converted to JSON.\n \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_report_from_serializable(config, data):\n \"\"\"\n .. warning::\n This hook is experimental and subject to change between pytest releases, even\n bug fixes.\n\n The intent is for this to be used by plugins maintained by the core-devs, such\n as ``pytest-xdist``, ``pytest-subtests``, and as a replacement for the internal\n 'resultlog' plugin.\n\n In the future it might become part of the public hook API.\n\n Restores a report object previously serialized with pytest_report_to_serializable().\n \"\"\"\n\n\n# -------------------------------------------------------------------------\n# Fixture related hooks\n# -------------------------------------------------------------------------\n\n\n@hookspec(firstresult=True)\ndef pytest_fixture_setup(fixturedef, request):\n \"\"\" performs fixture setup execution.\n\n :return: The return value of the call to the fixture function\n\n Stops at first non-None result, see :ref:`firstresult`\n\n .. note::\n If the fixture function returns None, other implementations of\n this hook function will continue to be called, according to the\n behavior of the :ref:`firstresult` option.\n \"\"\"\n\n\ndef pytest_fixture_post_finalizer(fixturedef, request):\n \"\"\" called after fixture teardown, but before the cache is cleared so\n the fixture result cache ``fixturedef.cached_result`` can\n still be accessed.\"\"\"\n\n\n# -------------------------------------------------------------------------\n# test session related hooks\n# -------------------------------------------------------------------------\n\n\ndef pytest_sessionstart(session):\n \"\"\" called after the ``Session`` object has been created and before performing collection\n and entering the run test loop.\n\n :param _pytest.main.Session session: the pytest session object\n \"\"\"\n\n\ndef pytest_sessionfinish(session, exitstatus):\n \"\"\" called after whole test run finished, right before returning the exit status to the system.\n\n :param _pytest.main.Session session: the pytest session object\n :param int exitstatus: the status which pytest will return to the system\n \"\"\"\n\n\ndef pytest_unconfigure(config):\n \"\"\" called before test process is exited.\n\n :param _pytest.config.Config config: pytest config object\n \"\"\"\n\n\n# -------------------------------------------------------------------------\n# hooks for customizing the assert methods\n# -------------------------------------------------------------------------\n\n\ndef pytest_assertrepr_compare(config, op, left, right):\n \"\"\"return explanation for comparisons in failing assert expressions.\n\n Return None for no custom explanation, otherwise return a list\n of strings. The strings will be joined by newlines but any newlines\n *in* a string will be escaped. Note that all but the first line will\n be indented slightly, the intention is for the first line to be a summary.\n\n :param _pytest.config.Config config: pytest config object\n \"\"\"\n\n\n# -------------------------------------------------------------------------\n# hooks for influencing reporting (invoked from _pytest_terminal)\n# -------------------------------------------------------------------------\n\n\ndef pytest_report_header(config, startdir):\n \"\"\" return a string or list of strings to be displayed as header info for terminal reporting.\n\n :param _pytest.config.Config config: pytest config object\n :param startdir: py.path object with the starting dir\n\n .. note::\n\n This function should be implemented only in plugins or ``conftest.py``\n files situated at the tests root directory due to how pytest\n :ref:`discovers plugins during startup `.\n \"\"\"\n\n\ndef pytest_report_collectionfinish(config, startdir, items):\n \"\"\"\n .. versionadded:: 3.2\n\n return a string or list of strings to be displayed after collection has finished successfully.\n\n This strings will be displayed after the standard \"collected X items\" message.\n\n :param _pytest.config.Config config: pytest config object\n :param startdir: py.path object with the starting dir\n :param items: list of pytest items that are going to be executed; this list should not be modified.\n \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_report_teststatus(report, config):\n \"\"\" return result-category, shortletter and verbose word for reporting.\n\n :param _pytest.config.Config config: pytest config object\n\n Stops at first non-None result, see :ref:`firstresult` \"\"\"\n\n\ndef pytest_terminal_summary(terminalreporter, exitstatus, config):\n \"\"\"Add a section to terminal summary reporting.\n\n :param _pytest.terminal.TerminalReporter terminalreporter: the internal terminal reporter object\n :param int exitstatus: the exit status that will be reported back to the OS\n :param _pytest.config.Config config: pytest config object\n\n .. versionadded:: 4.2\n The ``config`` parameter.\n \"\"\"\n\n\n@hookspec(historic=True, warn_on_impl=PYTEST_LOGWARNING)\ndef pytest_logwarning(message, code, nodeid, fslocation):\n \"\"\"\n .. deprecated:: 3.8\n\n This hook is will stop working in a future release.\n\n pytest no longer triggers this hook, but the\n terminal writer still implements it to display warnings issued by\n :meth:`_pytest.config.Config.warn` and :meth:`_pytest.nodes.Node.warn`. Calling those functions will be\n an error in future releases.\n\n process a warning specified by a message, a code string,\n a nodeid and fslocation (both of which may be None\n if the warning is not tied to a particular node/location).\n\n .. note::\n This hook is incompatible with ``hookwrapper=True``.\n \"\"\"\n\n\n@hookspec(historic=True)\ndef pytest_warning_captured(warning_message, when, item):\n \"\"\"\n Process a warning captured by the internal pytest warnings plugin.\n\n :param warnings.WarningMessage warning_message:\n The captured warning. This is the same object produced by :py:func:`warnings.catch_warnings`, and contains\n the same attributes as the parameters of :py:func:`warnings.showwarning`.\n\n :param str when:\n Indicates when the warning was captured. Possible values:\n\n * ``\"config\"``: during pytest configuration/initialization stage.\n * ``\"collect\"``: during test collection.\n * ``\"runtest\"``: during test execution.\n\n :param pytest.Item|None item:\n **DEPRECATED**: This parameter is incompatible with ``pytest-xdist``, and will always receive ``None``\n in a future release.\n\n The item being executed if ``when`` is ``\"runtest\"``, otherwise ``None``.\n \"\"\"\n\n\n# -------------------------------------------------------------------------\n# doctest hooks\n# -------------------------------------------------------------------------\n\n\n@hookspec(firstresult=True)\ndef pytest_doctest_prepare_content(content):\n \"\"\" return processed content for a given doctest\n\n Stops at first non-None result, see :ref:`firstresult` \"\"\"\n\n\n# -------------------------------------------------------------------------\n# error handling and internal debugging hooks\n# -------------------------------------------------------------------------\n\n\ndef pytest_internalerror(excrepr, excinfo):\n \"\"\" called for internal errors. \"\"\"\n\n\ndef pytest_keyboard_interrupt(excinfo):\n \"\"\" called for keyboard interrupt. \"\"\"\n\n\ndef pytest_exception_interact(node, call, report):\n \"\"\"called when an exception was raised which can potentially be\n interactively handled.\n\n This hook is only called if an exception was raised\n that is not an internal exception like ``skip.Exception``.\n \"\"\"\n\n\ndef pytest_enter_pdb(config, pdb):\n \"\"\" called upon pdb.set_trace(), can be used by plugins to take special\n action just before the python debugger enters in interactive mode.\n\n :param _pytest.config.Config config: pytest config object\n :param pdb.Pdb pdb: Pdb instance\n \"\"\"\n\n\ndef pytest_leave_pdb(config, pdb):\n \"\"\" called when leaving pdb (e.g. with continue after pdb.set_trace()).\n\n Can be used by plugins to take special action just after the python\n debugger leaves interactive mode.\n\n :param _pytest.config.Config config: pytest config object\n :param pdb.Pdb pdb: Pdb instance\n \"\"\"\n"},{"col":0,"comment":"null","endLoc":168,"header":"def get_config(args=None)","id":350,"name":"get_config","nodeType":"Function","startLoc":157,"text":"def get_config(args=None):\n # subsequent calls to main will create a fresh instance\n pluginmanager = PytestPluginManager()\n config = Config(pluginmanager)\n\n if args is not None:\n # Handle any \"-p no:plugin\" args.\n pluginmanager.consider_preparse(args)\n\n for spec in default_plugins:\n pluginmanager.import_plugin(spec)\n return config"},{"col":0,"comment":"\n Exit testing process.\n\n :param str msg: message to display upon exit.\n :param int returncode: return code to be used when exiting pytest.\n ","endLoc":75,"header":"def exit(msg, returncode=None)","id":351,"name":"exit","nodeType":"Function","startLoc":67,"text":"def exit(msg, returncode=None):\n \"\"\"\n Exit testing process.\n\n :param str msg: message to display upon exit.\n :param int returncode: return code to be used when exiting pytest.\n \"\"\"\n __tracebackhide__ = True\n raise Exit(msg, returncode)"},{"col":0,"comment":"called at plugin registration time to allow adding new hooks via a call to\n ``pluginmanager.add_hookspecs(module_or_class, prefix)``.\n\n\n :param _pytest.config.PytestPluginManager pluginmanager: pytest plugin manager\n\n .. note::\n This hook is incompatible with ``hookwrapper=True``.\n ","endLoc":24,"header":"@hookspec(historic=True)\ndef pytest_addhooks(pluginmanager)","id":352,"name":"pytest_addhooks","nodeType":"Function","startLoc":14,"text":"@hookspec(historic=True)\ndef pytest_addhooks(pluginmanager):\n \"\"\"called at plugin registration time to allow adding new hooks via a call to\n ``pluginmanager.add_hookspecs(module_or_class, prefix)``.\n\n\n :param _pytest.config.PytestPluginManager pluginmanager: pytest plugin manager\n\n .. note::\n This hook is incompatible with ``hookwrapper=True``.\n \"\"\""},{"col":0,"comment":"Imports and returns the requested module ``modname``, or skip the current test\n if the module cannot be imported.\n\n :param str modname: the name of the module to import\n :param str minversion: if given, the imported module ``__version__`` attribute must be\n at least this minimal version, otherwise the test is still skipped.\n :param str reason: if given, this reason is shown as the message when the module\n cannot be imported.\n ","endLoc":187,"header":"def importorskip(modname, minversion=None, reason=None)","id":354,"name":"importorskip","nodeType":"Function","startLoc":146,"text":"def importorskip(modname, minversion=None, reason=None):\n \"\"\"Imports and returns the requested module ``modname``, or skip the current test\n if the module cannot be imported.\n\n :param str modname: the name of the module to import\n :param str minversion: if given, the imported module ``__version__`` attribute must be\n at least this minimal version, otherwise the test is still skipped.\n :param str reason: if given, this reason is shown as the message when the module\n cannot be imported.\n \"\"\"\n import warnings\n\n __tracebackhide__ = True\n compile(modname, \"\", \"eval\") # to catch syntaxerrors\n import_exc = None\n\n with warnings.catch_warnings():\n # make sure to ignore ImportWarnings that might happen because\n # of existing directories with the same name we're trying to\n # import but without a __init__.py file\n warnings.simplefilter(\"ignore\")\n try:\n __import__(modname)\n except ImportError as exc:\n # Do not raise chained exception here(#1485)\n import_exc = exc\n if import_exc:\n if reason is None:\n reason = \"could not import %r: %s\" % (modname, import_exc)\n raise Skipped(reason, allow_module_level=True)\n mod = sys.modules[modname]\n if minversion is None:\n return mod\n verattr = getattr(mod, \"__version__\", None)\n if minversion is not None:\n if verattr is None or Version(verattr) < Version(minversion):\n raise Skipped(\n \"module %r has __version__ %r, required is: %r\"\n % (modname, verattr, minversion),\n allow_module_level=True,\n )\n return mod"},{"col":0,"comment":" a new pytest plugin got registered.\n\n :param plugin: the plugin module or instance\n :param _pytest.config.PytestPluginManager manager: pytest plugin manager\n\n .. note::\n This hook is incompatible with ``hookwrapper=True``.\n ","endLoc":36,"header":"@hookspec(historic=True)\ndef pytest_plugin_registered(plugin, manager)","id":355,"name":"pytest_plugin_registered","nodeType":"Function","startLoc":27,"text":"@hookspec(historic=True)\ndef pytest_plugin_registered(plugin, manager):\n \"\"\" a new pytest plugin got registered.\n\n :param plugin: the plugin module or instance\n :param _pytest.config.PytestPluginManager manager: pytest plugin manager\n\n .. note::\n This hook is incompatible with ``hookwrapper=True``.\n \"\"\""},{"col":0,"comment":"register argparse-style options and ini-style config values,\n called once at the beginning of a test run.\n\n .. note::\n\n This function should be implemented only in plugins or ``conftest.py``\n files situated at the tests root directory due to how pytest\n :ref:`discovers plugins during startup `.\n\n :arg _pytest.config.Parser parser: To add command line options, call\n :py:func:`parser.addoption(...) <_pytest.config.Parser.addoption>`.\n To add ini-file values call :py:func:`parser.addini(...)\n <_pytest.config.Parser.addini>`.\n\n Options can later be accessed through the\n :py:class:`config <_pytest.config.Config>` object, respectively:\n\n - :py:func:`config.getoption(name) <_pytest.config.Config.getoption>` to\n retrieve the value of a command line option.\n\n - :py:func:`config.getini(name) <_pytest.config.Config.getini>` to retrieve\n a value read from an ini-style file.\n\n The config object is passed around on many internal objects via the ``.config``\n attribute or can be retrieved as the ``pytestconfig`` fixture.\n\n .. note::\n This hook is incompatible with ``hookwrapper=True``.\n ","endLoc":69,"header":"@hookspec(historic=True)\ndef pytest_addoption(parser)","id":356,"name":"pytest_addoption","nodeType":"Function","startLoc":39,"text":"@hookspec(historic=True)\ndef pytest_addoption(parser):\n \"\"\"register argparse-style options and ini-style config values,\n called once at the beginning of a test run.\n\n .. note::\n\n This function should be implemented only in plugins or ``conftest.py``\n files situated at the tests root directory due to how pytest\n :ref:`discovers plugins during startup `.\n\n :arg _pytest.config.Parser parser: To add command line options, call\n :py:func:`parser.addoption(...) <_pytest.config.Parser.addoption>`.\n To add ini-file values call :py:func:`parser.addini(...)\n <_pytest.config.Parser.addini>`.\n\n Options can later be accessed through the\n :py:class:`config <_pytest.config.Config>` object, respectively:\n\n - :py:func:`config.getoption(name) <_pytest.config.Config.getoption>` to\n retrieve the value of a command line option.\n\n - :py:func:`config.getini(name) <_pytest.config.Config.getini>` to retrieve\n a value read from an ini-style file.\n\n The config object is passed around on many internal objects via the ``.config``\n attribute or can be retrieved as the ``pytestconfig`` fixture.\n\n .. note::\n This hook is incompatible with ``hookwrapper=True``.\n \"\"\""},{"col":0,"comment":"\n Allows plugins and conftest files to perform initial configuration.\n\n This hook is called for every plugin and initial conftest file\n after command line options have been parsed.\n\n After that, the hook is called for other conftest files as they are\n imported.\n\n .. note::\n This hook is incompatible with ``hookwrapper=True``.\n\n :arg _pytest.config.Config config: pytest config object\n ","endLoc":87,"header":"@hookspec(historic=True)\ndef pytest_configure(config)","id":357,"name":"pytest_configure","nodeType":"Function","startLoc":72,"text":"@hookspec(historic=True)\ndef pytest_configure(config):\n \"\"\"\n Allows plugins and conftest files to perform initial configuration.\n\n This hook is called for every plugin and initial conftest file\n after command line options have been parsed.\n\n After that, the hook is called for other conftest files as they are\n imported.\n\n .. note::\n This hook is incompatible with ``hookwrapper=True``.\n\n :arg _pytest.config.Config config: pytest config object\n \"\"\""},{"col":0,"comment":"return initialized config object, parsing the specified args.\n\n Stops at first non-None result, see :ref:`firstresult`\n\n .. note::\n This hook will only be called for plugin classes passed to the ``plugins`` arg when using `pytest.main`_ to\n perform an in-process test run.\n\n :param _pytest.config.PytestPluginManager pluginmanager: pytest plugin manager\n :param list[str] args: list of arguments passed on the command line\n ","endLoc":108,"header":"@hookspec(firstresult=True)\ndef pytest_cmdline_parse(pluginmanager, args)","id":358,"name":"pytest_cmdline_parse","nodeType":"Function","startLoc":96,"text":"@hookspec(firstresult=True)\ndef pytest_cmdline_parse(pluginmanager, args):\n \"\"\"return initialized config object, parsing the specified args.\n\n Stops at first non-None result, see :ref:`firstresult`\n\n .. note::\n This hook will only be called for plugin classes passed to the ``plugins`` arg when using `pytest.main`_ to\n perform an in-process test run.\n\n :param _pytest.config.PytestPluginManager pluginmanager: pytest plugin manager\n :param list[str] args: list of arguments passed on the command line\n \"\"\""},{"col":0,"comment":"(**Deprecated**) modify command line arguments before option parsing.\n\n This hook is considered deprecated and will be removed in a future pytest version. Consider\n using :func:`pytest_load_initial_conftests` instead.\n\n .. note::\n This hook will not be called for ``conftest.py`` files, only for setuptools plugins.\n\n :param _pytest.config.Config config: pytest config object\n :param list[str] args: list of arguments passed on the command line\n ","endLoc":122,"header":"def pytest_cmdline_preparse(config, args)","id":359,"name":"pytest_cmdline_preparse","nodeType":"Function","startLoc":111,"text":"def pytest_cmdline_preparse(config, args):\n \"\"\"(**Deprecated**) modify command line arguments before option parsing.\n\n This hook is considered deprecated and will be removed in a future pytest version. Consider\n using :func:`pytest_load_initial_conftests` instead.\n\n .. note::\n This hook will not be called for ``conftest.py`` files, only for setuptools plugins.\n\n :param _pytest.config.Config config: pytest config object\n :param list[str] args: list of arguments passed on the command line\n \"\"\""},{"col":0,"comment":" called for performing the main command line action. The default\n implementation will invoke the configure hooks and runtest_mainloop.\n\n .. note::\n This hook will not be called for ``conftest.py`` files, only for setuptools plugins.\n\n Stops at first non-None result, see :ref:`firstresult`\n\n :param _pytest.config.Config config: pytest config object\n ","endLoc":136,"header":"@hookspec(firstresult=True)\ndef pytest_cmdline_main(config)","id":360,"name":"pytest_cmdline_main","nodeType":"Function","startLoc":125,"text":"@hookspec(firstresult=True)\ndef pytest_cmdline_main(config):\n \"\"\" called for performing the main command line action. The default\n implementation will invoke the configure hooks and runtest_mainloop.\n\n .. note::\n This hook will not be called for ``conftest.py`` files, only for setuptools plugins.\n\n Stops at first non-None result, see :ref:`firstresult`\n\n :param _pytest.config.Config config: pytest config object\n \"\"\""},{"col":0,"comment":" implements the loading of initial conftest files ahead\n of command line option parsing.\n\n .. note::\n This hook will not be called for ``conftest.py`` files, only for setuptools plugins.\n\n :param _pytest.config.Config early_config: pytest config object\n :param list[str] args: list of arguments passed on the command line\n :param _pytest.config.Parser parser: to add command line options\n ","endLoc":149,"header":"def pytest_load_initial_conftests(early_config, parser, args)","id":361,"name":"pytest_load_initial_conftests","nodeType":"Function","startLoc":139,"text":"def pytest_load_initial_conftests(early_config, parser, args):\n \"\"\" implements the loading of initial conftest files ahead\n of command line option parsing.\n\n .. note::\n This hook will not be called for ``conftest.py`` files, only for setuptools plugins.\n\n :param _pytest.config.Config early_config: pytest config object\n :param list[str] args: list of arguments passed on the command line\n :param _pytest.config.Parser parser: to add command line options\n \"\"\""},{"col":0,"comment":"Perform the collection protocol for the given session.\n\n Stops at first non-None result, see :ref:`firstresult`.\n\n :param _pytest.main.Session session: the pytest session object\n ","endLoc":164,"header":"@hookspec(firstresult=True)\ndef pytest_collection(session)","id":362,"name":"pytest_collection","nodeType":"Function","startLoc":157,"text":"@hookspec(firstresult=True)\ndef pytest_collection(session):\n \"\"\"Perform the collection protocol for the given session.\n\n Stops at first non-None result, see :ref:`firstresult`.\n\n :param _pytest.main.Session session: the pytest session object\n \"\"\""},{"col":0,"comment":" called after collection has been performed, may filter or re-order\n the items in-place.\n\n :param _pytest.main.Session session: the pytest session object\n :param _pytest.config.Config config: pytest config object\n :param List[_pytest.nodes.Item] items: list of item objects\n ","endLoc":174,"header":"def pytest_collection_modifyitems(session, config, items)","id":363,"name":"pytest_collection_modifyitems","nodeType":"Function","startLoc":167,"text":"def pytest_collection_modifyitems(session, config, items):\n \"\"\" called after collection has been performed, may filter or re-order\n the items in-place.\n\n :param _pytest.main.Session session: the pytest session object\n :param _pytest.config.Config config: pytest config object\n :param List[_pytest.nodes.Item] items: list of item objects\n \"\"\""},{"col":0,"comment":" called after collection has been performed and modified.\n\n :param _pytest.main.Session session: the pytest session object\n ","endLoc":181,"header":"def pytest_collection_finish(session)","id":365,"name":"pytest_collection_finish","nodeType":"Function","startLoc":177,"text":"def pytest_collection_finish(session):\n \"\"\" called after collection has been performed and modified.\n\n :param _pytest.main.Session session: the pytest session object\n \"\"\""},{"col":0,"comment":" return True to prevent considering this path for collection.\n This hook is consulted for all files and directories prior to calling\n more specific hooks.\n\n Stops at first non-None result, see :ref:`firstresult`\n\n :param path: a :py:class:`py.path.local` - the path to analyze\n :param _pytest.config.Config config: pytest config object\n ","endLoc":194,"header":"@hookspec(firstresult=True)\ndef pytest_ignore_collect(path, config)","id":367,"name":"pytest_ignore_collect","nodeType":"Function","startLoc":184,"text":"@hookspec(firstresult=True)\ndef pytest_ignore_collect(path, config):\n \"\"\" return True to prevent considering this path for collection.\n This hook is consulted for all files and directories prior to calling\n more specific hooks.\n\n Stops at first non-None result, see :ref:`firstresult`\n\n :param path: a :py:class:`py.path.local` - the path to analyze\n :param _pytest.config.Config config: pytest config object\n \"\"\""},{"col":4,"comment":"null","endLoc":250,"header":"def __init__(self)","id":372,"name":"__init__","nodeType":"Function","startLoc":224,"text":"def __init__(self):\n super(PytestPluginManager, self).__init__(\"pytest\")\n self._conftest_plugins = set()\n\n # state related to local conftest plugins\n self._dirpath2confmods = {}\n self._conftestpath2mod = {}\n self._confcutdir = None\n self._noconftest = False\n self._duplicatepaths = set()\n\n self.add_hookspecs(_pytest.hookspec)\n self.register(self)\n if os.environ.get(\"PYTEST_DEBUG\"):\n err = sys.stderr\n encoding = getattr(err, \"encoding\", \"utf8\")\n try:\n err = py.io.dupfile(err, encoding=encoding)\n except Exception:\n pass\n self.trace.root.setwriter(err.write)\n self.enable_tracing()\n\n # Config._consider_importhook will set a real object if required.\n self.rewrite_hook = _pytest.assertion.DummyRewriteHook()\n # Used to know when we are importing conftests after the pytest_configure stage\n self._configured = False"},{"col":0,"comment":" called before traversing a directory for collection files.\n\n Stops at first non-None result, see :ref:`firstresult`\n\n :param path: a :py:class:`py.path.local` - the path to analyze\n ","endLoc":204,"header":"@hookspec(firstresult=True)\ndef pytest_collect_directory(path, parent)","id":373,"name":"pytest_collect_directory","nodeType":"Function","startLoc":197,"text":"@hookspec(firstresult=True)\ndef pytest_collect_directory(path, parent):\n \"\"\" called before traversing a directory for collection files.\n\n Stops at first non-None result, see :ref:`firstresult`\n\n :param path: a :py:class:`py.path.local` - the path to analyze\n \"\"\""},{"col":0,"comment":" return collection Node or None for the given path. Any new node\n needs to have the specified ``parent`` as a parent.\n\n :param path: a :py:class:`py.path.local` - the path to collect\n ","endLoc":212,"header":"def pytest_collect_file(path, parent)","id":374,"name":"pytest_collect_file","nodeType":"Function","startLoc":207,"text":"def pytest_collect_file(path, parent):\n \"\"\" return collection Node or None for the given path. Any new node\n needs to have the specified ``parent`` as a parent.\n\n :param path: a :py:class:`py.path.local` - the path to collect\n \"\"\""},{"col":0,"comment":" collector starts collecting. ","endLoc":219,"header":"def pytest_collectstart(collector)","id":375,"name":"pytest_collectstart","nodeType":"Function","startLoc":218,"text":"def pytest_collectstart(collector):\n \"\"\" collector starts collecting. \"\"\""},{"col":0,"comment":" we just collected a test item. ","endLoc":223,"header":"def pytest_itemcollected(item)","id":376,"name":"pytest_itemcollected","nodeType":"Function","startLoc":222,"text":"def pytest_itemcollected(item):\n \"\"\" we just collected a test item. \"\"\""},{"col":0,"comment":" collector finished collecting. ","endLoc":227,"header":"def pytest_collectreport(report)","id":377,"name":"pytest_collectreport","nodeType":"Function","startLoc":226,"text":"def pytest_collectreport(report):\n \"\"\" collector finished collecting. \"\"\""},{"col":0,"comment":" called for test items deselected, e.g. by keyword. ","endLoc":231,"header":"def pytest_deselected(items)","id":378,"name":"pytest_deselected","nodeType":"Function","startLoc":230,"text":"def pytest_deselected(items):\n \"\"\" called for test items deselected, e.g. by keyword. \"\"\""},{"col":0,"comment":" perform ``collector.collect()`` and return a CollectReport.\n\n Stops at first non-None result, see :ref:`firstresult` ","endLoc":238,"header":"@hookspec(firstresult=True)\ndef pytest_make_collect_report(collector)","id":379,"name":"pytest_make_collect_report","nodeType":"Function","startLoc":234,"text":"@hookspec(firstresult=True)\ndef pytest_make_collect_report(collector):\n \"\"\" perform ``collector.collect()`` and return a CollectReport.\n\n Stops at first non-None result, see :ref:`firstresult` \"\"\""},{"col":0,"comment":" return a Module collector or None for the given path.\n This hook will be called for each matching test module path.\n The pytest_collect_file hook needs to be used if you want to\n create test modules for files that do not match as a test module.\n\n Stops at first non-None result, see :ref:`firstresult`\n\n :param path: a :py:class:`py.path.local` - the path of module to collect\n ","endLoc":256,"header":"@hookspec(firstresult=True)\ndef pytest_pycollect_makemodule(path, parent)","id":383,"name":"pytest_pycollect_makemodule","nodeType":"Function","startLoc":246,"text":"@hookspec(firstresult=True)\ndef pytest_pycollect_makemodule(path, parent):\n \"\"\" return a Module collector or None for the given path.\n This hook will be called for each matching test module path.\n The pytest_collect_file hook needs to be used if you want to\n create test modules for files that do not match as a test module.\n\n Stops at first non-None result, see :ref:`firstresult`\n\n :param path: a :py:class:`py.path.local` - the path of module to collect\n \"\"\""},{"col":0,"comment":" return custom item/collector for a python object in a module, or None.\n\n Stops at first non-None result, see :ref:`firstresult` ","endLoc":263,"header":"@hookspec(firstresult=True)\ndef pytest_pycollect_makeitem(collector, name, obj)","id":385,"name":"pytest_pycollect_makeitem","nodeType":"Function","startLoc":259,"text":"@hookspec(firstresult=True)\ndef pytest_pycollect_makeitem(collector, name, obj):\n \"\"\" return custom item/collector for a python object in a module, or None.\n\n Stops at first non-None result, see :ref:`firstresult` \"\"\""},{"col":0,"comment":" call underlying test function.\n\n Stops at first non-None result, see :ref:`firstresult` ","endLoc":270,"header":"@hookspec(firstresult=True)\ndef pytest_pyfunc_call(pyfuncitem)","id":386,"name":"pytest_pyfunc_call","nodeType":"Function","startLoc":266,"text":"@hookspec(firstresult=True)\ndef pytest_pyfunc_call(pyfuncitem):\n \"\"\" call underlying test function.\n\n Stops at first non-None result, see :ref:`firstresult` \"\"\""},{"col":0,"comment":" generate (multiple) parametrized calls to a test function.","endLoc":274,"header":"def pytest_generate_tests(metafunc)","id":387,"name":"pytest_generate_tests","nodeType":"Function","startLoc":273,"text":"def pytest_generate_tests(metafunc):\n \"\"\" generate (multiple) parametrized calls to a test function.\"\"\""},{"col":0,"comment":"Return a user-friendly string representation of the given ``val`` that will be used\n by @pytest.mark.parametrize calls. Return None if the hook doesn't know about ``val``.\n The parameter name is available as ``argname``, if required.\n\n Stops at first non-None result, see :ref:`firstresult`\n\n :param _pytest.config.Config config: pytest config object\n :param val: the parametrized value\n :param str argname: the automatic parameter name produced by pytest\n ","endLoc":288,"header":"@hookspec(firstresult=True)\ndef pytest_make_parametrize_id(config, val, argname)","id":388,"name":"pytest_make_parametrize_id","nodeType":"Function","startLoc":277,"text":"@hookspec(firstresult=True)\ndef pytest_make_parametrize_id(config, val, argname):\n \"\"\"Return a user-friendly string representation of the given ``val`` that will be used\n by @pytest.mark.parametrize calls. Return None if the hook doesn't know about ``val``.\n The parameter name is available as ``argname``, if required.\n\n Stops at first non-None result, see :ref:`firstresult`\n\n :param _pytest.config.Config config: pytest config object\n :param val: the parametrized value\n :param str argname: the automatic parameter name produced by pytest\n \"\"\""},{"col":0,"comment":" called for performing the main runtest loop\n (after collection finished).\n\n Stops at first non-None result, see :ref:`firstresult`\n\n :param _pytest.main.Session session: the pytest session object\n ","endLoc":304,"header":"@hookspec(firstresult=True)\ndef pytest_runtestloop(session)","id":389,"name":"pytest_runtestloop","nodeType":"Function","startLoc":296,"text":"@hookspec(firstresult=True)\ndef pytest_runtestloop(session):\n \"\"\" called for performing the main runtest loop\n (after collection finished).\n\n Stops at first non-None result, see :ref:`firstresult`\n\n :param _pytest.main.Session session: the pytest session object\n \"\"\""},{"col":0,"comment":"(**Deprecated**) use pytest_runtest_logstart. ","endLoc":308,"header":"def pytest_itemstart(item, node)","id":390,"name":"pytest_itemstart","nodeType":"Function","startLoc":307,"text":"def pytest_itemstart(item, node):\n \"\"\"(**Deprecated**) use pytest_runtest_logstart. \"\"\""},{"col":0,"comment":" implements the runtest_setup/call/teardown protocol for\n the given test item, including capturing exceptions and calling\n reporting hooks.\n\n :arg item: test item for which the runtest protocol is performed.\n\n :arg nextitem: the scheduled-to-be-next test item (or None if this\n is the end my friend). This argument is passed on to\n :py:func:`pytest_runtest_teardown`.\n\n :return boolean: True if no further hook implementations should be invoked.\n\n\n Stops at first non-None result, see :ref:`firstresult` ","endLoc":326,"header":"@hookspec(firstresult=True)\ndef pytest_runtest_protocol(item, nextitem)","id":391,"name":"pytest_runtest_protocol","nodeType":"Function","startLoc":311,"text":"@hookspec(firstresult=True)\ndef pytest_runtest_protocol(item, nextitem):\n \"\"\" implements the runtest_setup/call/teardown protocol for\n the given test item, including capturing exceptions and calling\n reporting hooks.\n\n :arg item: test item for which the runtest protocol is performed.\n\n :arg nextitem: the scheduled-to-be-next test item (or None if this\n is the end my friend). This argument is passed on to\n :py:func:`pytest_runtest_teardown`.\n\n :return boolean: True if no further hook implementations should be invoked.\n\n\n Stops at first non-None result, see :ref:`firstresult` \"\"\""},{"col":0,"comment":" signal the start of running a single test item.\n\n This hook will be called **before** :func:`pytest_runtest_setup`, :func:`pytest_runtest_call` and\n :func:`pytest_runtest_teardown` hooks.\n\n :param str nodeid: full id of the item\n :param location: a triple of ``(filename, linenum, testname)``\n ","endLoc":337,"header":"def pytest_runtest_logstart(nodeid, location)","id":392,"name":"pytest_runtest_logstart","nodeType":"Function","startLoc":329,"text":"def pytest_runtest_logstart(nodeid, location):\n \"\"\" signal the start of running a single test item.\n\n This hook will be called **before** :func:`pytest_runtest_setup`, :func:`pytest_runtest_call` and\n :func:`pytest_runtest_teardown` hooks.\n\n :param str nodeid: full id of the item\n :param location: a triple of ``(filename, linenum, testname)``\n \"\"\""},{"col":0,"comment":" signal the complete finish of running a single test item.\n\n This hook will be called **after** :func:`pytest_runtest_setup`, :func:`pytest_runtest_call` and\n :func:`pytest_runtest_teardown` hooks.\n\n :param str nodeid: full id of the item\n :param location: a triple of ``(filename, linenum, testname)``\n ","endLoc":348,"header":"def pytest_runtest_logfinish(nodeid, location)","id":393,"name":"pytest_runtest_logfinish","nodeType":"Function","startLoc":340,"text":"def pytest_runtest_logfinish(nodeid, location):\n \"\"\" signal the complete finish of running a single test item.\n\n This hook will be called **after** :func:`pytest_runtest_setup`, :func:`pytest_runtest_call` and\n :func:`pytest_runtest_teardown` hooks.\n\n :param str nodeid: full id of the item\n :param location: a triple of ``(filename, linenum, testname)``\n \"\"\""},{"col":0,"comment":" called before ``pytest_runtest_call(item)``. ","endLoc":352,"header":"def pytest_runtest_setup(item)","id":394,"name":"pytest_runtest_setup","nodeType":"Function","startLoc":351,"text":"def pytest_runtest_setup(item):\n \"\"\" called before ``pytest_runtest_call(item)``. \"\"\""},{"col":0,"comment":" called to execute the test ``item``. ","endLoc":356,"header":"def pytest_runtest_call(item)","id":395,"name":"pytest_runtest_call","nodeType":"Function","startLoc":355,"text":"def pytest_runtest_call(item):\n \"\"\" called to execute the test ``item``. \"\"\""},{"col":0,"comment":" called after ``pytest_runtest_call``.\n\n :arg nextitem: the scheduled-to-be-next test item (None if no further\n test item is scheduled). This argument can be used to\n perform exact teardowns, i.e. calling just enough finalizers\n so that nextitem only needs to call setup-functions.\n ","endLoc":366,"header":"def pytest_runtest_teardown(item, nextitem)","id":396,"name":"pytest_runtest_teardown","nodeType":"Function","startLoc":359,"text":"def pytest_runtest_teardown(item, nextitem):\n \"\"\" called after ``pytest_runtest_call``.\n\n :arg nextitem: the scheduled-to-be-next test item (None if no further\n test item is scheduled). This argument can be used to\n perform exact teardowns, i.e. calling just enough finalizers\n so that nextitem only needs to call setup-functions.\n \"\"\""},{"col":0,"comment":" return a :py:class:`_pytest.runner.TestReport` object\n for the given :py:class:`pytest.Item <_pytest.main.Item>` and\n :py:class:`_pytest.runner.CallInfo`.\n\n Stops at first non-None result, see :ref:`firstresult` ","endLoc":375,"header":"@hookspec(firstresult=True)\ndef pytest_runtest_makereport(item, call)","id":397,"name":"pytest_runtest_makereport","nodeType":"Function","startLoc":369,"text":"@hookspec(firstresult=True)\ndef pytest_runtest_makereport(item, call):\n \"\"\" return a :py:class:`_pytest.runner.TestReport` object\n for the given :py:class:`pytest.Item <_pytest.main.Item>` and\n :py:class:`_pytest.runner.CallInfo`.\n\n Stops at first non-None result, see :ref:`firstresult` \"\"\""},{"col":0,"comment":" process a test setup/call/teardown report relating to\n the respective phase of executing a test. ","endLoc":380,"header":"def pytest_runtest_logreport(report)","id":398,"name":"pytest_runtest_logreport","nodeType":"Function","startLoc":378,"text":"def pytest_runtest_logreport(report):\n \"\"\" process a test setup/call/teardown report relating to\n the respective phase of executing a test. \"\"\""},{"col":0,"comment":"\n .. warning::\n This hook is experimental and subject to change between pytest releases, even\n bug fixes.\n\n The intent is for this to be used by plugins maintained by the core-devs, such\n as ``pytest-xdist``, ``pytest-subtests``, and as a replacement for the internal\n 'resultlog' plugin.\n\n In the future it might become part of the public hook API.\n\n Serializes the given report object into a data structure suitable for sending\n over the wire, e.g. converted to JSON.\n ","endLoc":398,"header":"@hookspec(firstresult=True)\ndef pytest_report_to_serializable(config, report)","id":399,"name":"pytest_report_to_serializable","nodeType":"Function","startLoc":383,"text":"@hookspec(firstresult=True)\ndef pytest_report_to_serializable(config, report):\n \"\"\"\n .. warning::\n This hook is experimental and subject to change between pytest releases, even\n bug fixes.\n\n The intent is for this to be used by plugins maintained by the core-devs, such\n as ``pytest-xdist``, ``pytest-subtests``, and as a replacement for the internal\n 'resultlog' plugin.\n\n In the future it might become part of the public hook API.\n\n Serializes the given report object into a data structure suitable for sending\n over the wire, e.g. converted to JSON.\n \"\"\""},{"col":0,"comment":"\n .. warning::\n This hook is experimental and subject to change between pytest releases, even\n bug fixes.\n\n The intent is for this to be used by plugins maintained by the core-devs, such\n as ``pytest-xdist``, ``pytest-subtests``, and as a replacement for the internal\n 'resultlog' plugin.\n\n In the future it might become part of the public hook API.\n\n Restores a report object previously serialized with pytest_report_to_serializable().\n ","endLoc":415,"header":"@hookspec(firstresult=True)\ndef pytest_report_from_serializable(config, data)","id":400,"name":"pytest_report_from_serializable","nodeType":"Function","startLoc":401,"text":"@hookspec(firstresult=True)\ndef pytest_report_from_serializable(config, data):\n \"\"\"\n .. warning::\n This hook is experimental and subject to change between pytest releases, even\n bug fixes.\n\n The intent is for this to be used by plugins maintained by the core-devs, such\n as ``pytest-xdist``, ``pytest-subtests``, and as a replacement for the internal\n 'resultlog' plugin.\n\n In the future it might become part of the public hook API.\n\n Restores a report object previously serialized with pytest_report_to_serializable().\n \"\"\""},{"col":0,"comment":" performs fixture setup execution.\n\n :return: The return value of the call to the fixture function\n\n Stops at first non-None result, see :ref:`firstresult`\n\n .. note::\n If the fixture function returns None, other implementations of\n this hook function will continue to be called, according to the\n behavior of the :ref:`firstresult` option.\n ","endLoc":435,"header":"@hookspec(firstresult=True)\ndef pytest_fixture_setup(fixturedef, request)","id":401,"name":"pytest_fixture_setup","nodeType":"Function","startLoc":423,"text":"@hookspec(firstresult=True)\ndef pytest_fixture_setup(fixturedef, request):\n \"\"\" performs fixture setup execution.\n\n :return: The return value of the call to the fixture function\n\n Stops at first non-None result, see :ref:`firstresult`\n\n .. note::\n If the fixture function returns None, other implementations of\n this hook function will continue to be called, according to the\n behavior of the :ref:`firstresult` option.\n \"\"\""},{"col":0,"comment":" called after fixture teardown, but before the cache is cleared so\n the fixture result cache ``fixturedef.cached_result`` can\n still be accessed.","endLoc":441,"header":"def pytest_fixture_post_finalizer(fixturedef, request)","id":402,"name":"pytest_fixture_post_finalizer","nodeType":"Function","startLoc":438,"text":"def pytest_fixture_post_finalizer(fixturedef, request):\n \"\"\" called after fixture teardown, but before the cache is cleared so\n the fixture result cache ``fixturedef.cached_result`` can\n still be accessed.\"\"\""},{"col":0,"comment":" called after the ``Session`` object has been created and before performing collection\n and entering the run test loop.\n\n :param _pytest.main.Session session: the pytest session object\n ","endLoc":454,"header":"def pytest_sessionstart(session)","id":403,"name":"pytest_sessionstart","nodeType":"Function","startLoc":449,"text":"def pytest_sessionstart(session):\n \"\"\" called after the ``Session`` object has been created and before performing collection\n and entering the run test loop.\n\n :param _pytest.main.Session session: the pytest session object\n \"\"\""},{"col":0,"comment":" called after whole test run finished, right before returning the exit status to the system.\n\n :param _pytest.main.Session session: the pytest session object\n :param int exitstatus: the status which pytest will return to the system\n ","endLoc":462,"header":"def pytest_sessionfinish(session, exitstatus)","id":404,"name":"pytest_sessionfinish","nodeType":"Function","startLoc":457,"text":"def pytest_sessionfinish(session, exitstatus):\n \"\"\" called after whole test run finished, right before returning the exit status to the system.\n\n :param _pytest.main.Session session: the pytest session object\n :param int exitstatus: the status which pytest will return to the system\n \"\"\""},{"col":0,"comment":" called before test process is exited.\n\n :param _pytest.config.Config config: pytest config object\n ","endLoc":469,"header":"def pytest_unconfigure(config)","id":405,"name":"pytest_unconfigure","nodeType":"Function","startLoc":465,"text":"def pytest_unconfigure(config):\n \"\"\" called before test process is exited.\n\n :param _pytest.config.Config config: pytest config object\n \"\"\""},{"col":0,"comment":"return explanation for comparisons in failing assert expressions.\n\n Return None for no custom explanation, otherwise return a list\n of strings. The strings will be joined by newlines but any newlines\n *in* a string will be escaped. Note that all but the first line will\n be indented slightly, the intention is for the first line to be a summary.\n\n :param _pytest.config.Config config: pytest config object\n ","endLoc":486,"header":"def pytest_assertrepr_compare(config, op, left, right)","id":406,"name":"pytest_assertrepr_compare","nodeType":"Function","startLoc":477,"text":"def pytest_assertrepr_compare(config, op, left, right):\n \"\"\"return explanation for comparisons in failing assert expressions.\n\n Return None for no custom explanation, otherwise return a list\n of strings. The strings will be joined by newlines but any newlines\n *in* a string will be escaped. Note that all but the first line will\n be indented slightly, the intention is for the first line to be a summary.\n\n :param _pytest.config.Config config: pytest config object\n \"\"\""},{"col":0,"comment":" return a string or list of strings to be displayed as header info for terminal reporting.\n\n :param _pytest.config.Config config: pytest config object\n :param startdir: py.path object with the starting dir\n\n .. note::\n\n This function should be implemented only in plugins or ``conftest.py``\n files situated at the tests root directory due to how pytest\n :ref:`discovers plugins during startup `.\n ","endLoc":505,"header":"def pytest_report_header(config, startdir)","id":407,"name":"pytest_report_header","nodeType":"Function","startLoc":494,"text":"def pytest_report_header(config, startdir):\n \"\"\" return a string or list of strings to be displayed as header info for terminal reporting.\n\n :param _pytest.config.Config config: pytest config object\n :param startdir: py.path object with the starting dir\n\n .. note::\n\n This function should be implemented only in plugins or ``conftest.py``\n files situated at the tests root directory due to how pytest\n :ref:`discovers plugins during startup `.\n \"\"\""},{"col":0,"comment":"\n .. versionadded:: 3.2\n\n return a string or list of strings to be displayed after collection has finished successfully.\n\n This strings will be displayed after the standard \"collected X items\" message.\n\n :param _pytest.config.Config config: pytest config object\n :param startdir: py.path object with the starting dir\n :param items: list of pytest items that are going to be executed; this list should not be modified.\n ","endLoc":519,"header":"def pytest_report_collectionfinish(config, startdir, items)","id":408,"name":"pytest_report_collectionfinish","nodeType":"Function","startLoc":508,"text":"def pytest_report_collectionfinish(config, startdir, items):\n \"\"\"\n .. versionadded:: 3.2\n\n return a string or list of strings to be displayed after collection has finished successfully.\n\n This strings will be displayed after the standard \"collected X items\" message.\n\n :param _pytest.config.Config config: pytest config object\n :param startdir: py.path object with the starting dir\n :param items: list of pytest items that are going to be executed; this list should not be modified.\n \"\"\""},{"col":0,"comment":" return result-category, shortletter and verbose word for reporting.\n\n :param _pytest.config.Config config: pytest config object\n\n Stops at first non-None result, see :ref:`firstresult` ","endLoc":528,"header":"@hookspec(firstresult=True)\ndef pytest_report_teststatus(report, config)","id":409,"name":"pytest_report_teststatus","nodeType":"Function","startLoc":522,"text":"@hookspec(firstresult=True)\ndef pytest_report_teststatus(report, config):\n \"\"\" return result-category, shortletter and verbose word for reporting.\n\n :param _pytest.config.Config config: pytest config object\n\n Stops at first non-None result, see :ref:`firstresult` \"\"\""},{"col":0,"comment":"Add a section to terminal summary reporting.\n\n :param _pytest.terminal.TerminalReporter terminalreporter: the internal terminal reporter object\n :param int exitstatus: the exit status that will be reported back to the OS\n :param _pytest.config.Config config: pytest config object\n\n .. versionadded:: 4.2\n The ``config`` parameter.\n ","endLoc":540,"header":"def pytest_terminal_summary(terminalreporter, exitstatus, config)","id":410,"name":"pytest_terminal_summary","nodeType":"Function","startLoc":531,"text":"def pytest_terminal_summary(terminalreporter, exitstatus, config):\n \"\"\"Add a section to terminal summary reporting.\n\n :param _pytest.terminal.TerminalReporter terminalreporter: the internal terminal reporter object\n :param int exitstatus: the exit status that will be reported back to the OS\n :param _pytest.config.Config config: pytest config object\n\n .. versionadded:: 4.2\n The ``config`` parameter.\n \"\"\""},{"col":0,"comment":"\n .. deprecated:: 3.8\n\n This hook is will stop working in a future release.\n\n pytest no longer triggers this hook, but the\n terminal writer still implements it to display warnings issued by\n :meth:`_pytest.config.Config.warn` and :meth:`_pytest.nodes.Node.warn`. Calling those functions will be\n an error in future releases.\n\n process a warning specified by a message, a code string,\n a nodeid and fslocation (both of which may be None\n if the warning is not tied to a particular node/location).\n\n .. note::\n This hook is incompatible with ``hookwrapper=True``.\n ","endLoc":561,"header":"@hookspec(historic=True, warn_on_impl=PYTEST_LOGWARNING)\ndef pytest_logwarning(message, code, nodeid, fslocation)","id":411,"name":"pytest_logwarning","nodeType":"Function","startLoc":543,"text":"@hookspec(historic=True, warn_on_impl=PYTEST_LOGWARNING)\ndef pytest_logwarning(message, code, nodeid, fslocation):\n \"\"\"\n .. deprecated:: 3.8\n\n This hook is will stop working in a future release.\n\n pytest no longer triggers this hook, but the\n terminal writer still implements it to display warnings issued by\n :meth:`_pytest.config.Config.warn` and :meth:`_pytest.nodes.Node.warn`. Calling those functions will be\n an error in future releases.\n\n process a warning specified by a message, a code string,\n a nodeid and fslocation (both of which may be None\n if the warning is not tied to a particular node/location).\n\n .. note::\n This hook is incompatible with ``hookwrapper=True``.\n \"\"\""},{"col":0,"comment":"\n Process a warning captured by the internal pytest warnings plugin.\n\n :param warnings.WarningMessage warning_message:\n The captured warning. This is the same object produced by :py:func:`warnings.catch_warnings`, and contains\n the same attributes as the parameters of :py:func:`warnings.showwarning`.\n\n :param str when:\n Indicates when the warning was captured. Possible values:\n\n * ``\"config\"``: during pytest configuration/initialization stage.\n * ``\"collect\"``: during test collection.\n * ``\"runtest\"``: during test execution.\n\n :param pytest.Item|None item:\n **DEPRECATED**: This parameter is incompatible with ``pytest-xdist``, and will always receive ``None``\n in a future release.\n\n The item being executed if ``when`` is ``\"runtest\"``, otherwise ``None``.\n ","endLoc":585,"header":"@hookspec(historic=True)\ndef pytest_warning_captured(warning_message, when, item)","id":412,"name":"pytest_warning_captured","nodeType":"Function","startLoc":564,"text":"@hookspec(historic=True)\ndef pytest_warning_captured(warning_message, when, item):\n \"\"\"\n Process a warning captured by the internal pytest warnings plugin.\n\n :param warnings.WarningMessage warning_message:\n The captured warning. This is the same object produced by :py:func:`warnings.catch_warnings`, and contains\n the same attributes as the parameters of :py:func:`warnings.showwarning`.\n\n :param str when:\n Indicates when the warning was captured. Possible values:\n\n * ``\"config\"``: during pytest configuration/initialization stage.\n * ``\"collect\"``: during test collection.\n * ``\"runtest\"``: during test execution.\n\n :param pytest.Item|None item:\n **DEPRECATED**: This parameter is incompatible with ``pytest-xdist``, and will always receive ``None``\n in a future release.\n\n The item being executed if ``when`` is ``\"runtest\"``, otherwise ``None``.\n \"\"\""},{"col":0,"comment":" return processed content for a given doctest\n\n Stops at first non-None result, see :ref:`firstresult` ","endLoc":597,"header":"@hookspec(firstresult=True)\ndef pytest_doctest_prepare_content(content)","id":413,"name":"pytest_doctest_prepare_content","nodeType":"Function","startLoc":593,"text":"@hookspec(firstresult=True)\ndef pytest_doctest_prepare_content(content):\n \"\"\" return processed content for a given doctest\n\n Stops at first non-None result, see :ref:`firstresult` \"\"\""},{"col":0,"comment":" called for internal errors. ","endLoc":606,"header":"def pytest_internalerror(excrepr, excinfo)","id":414,"name":"pytest_internalerror","nodeType":"Function","startLoc":605,"text":"def pytest_internalerror(excrepr, excinfo):\n \"\"\" called for internal errors. \"\"\""},{"col":0,"comment":" called for keyboard interrupt. ","endLoc":610,"header":"def pytest_keyboard_interrupt(excinfo)","id":415,"name":"pytest_keyboard_interrupt","nodeType":"Function","startLoc":609,"text":"def pytest_keyboard_interrupt(excinfo):\n \"\"\" called for keyboard interrupt. \"\"\""},{"col":0,"comment":"called when an exception was raised which can potentially be\n interactively handled.\n\n This hook is only called if an exception was raised\n that is not an internal exception like ``skip.Exception``.\n ","endLoc":619,"header":"def pytest_exception_interact(node, call, report)","id":416,"name":"pytest_exception_interact","nodeType":"Function","startLoc":613,"text":"def pytest_exception_interact(node, call, report):\n \"\"\"called when an exception was raised which can potentially be\n interactively handled.\n\n This hook is only called if an exception was raised\n that is not an internal exception like ``skip.Exception``.\n \"\"\""},{"col":0,"comment":" called upon pdb.set_trace(), can be used by plugins to take special\n action just before the python debugger enters in interactive mode.\n\n :param _pytest.config.Config config: pytest config object\n :param pdb.Pdb pdb: Pdb instance\n ","endLoc":628,"header":"def pytest_enter_pdb(config, pdb)","id":417,"name":"pytest_enter_pdb","nodeType":"Function","startLoc":622,"text":"def pytest_enter_pdb(config, pdb):\n \"\"\" called upon pdb.set_trace(), can be used by plugins to take special\n action just before the python debugger enters in interactive mode.\n\n :param _pytest.config.Config config: pytest config object\n :param pdb.Pdb pdb: Pdb instance\n \"\"\""},{"col":0,"comment":" called when leaving pdb (e.g. with continue after pdb.set_trace()).\n\n Can be used by plugins to take special action just after the python\n debugger leaves interactive mode.\n\n :param _pytest.config.Config config: pytest config object\n :param pdb.Pdb pdb: Pdb instance\n ","endLoc":639,"header":"def pytest_leave_pdb(config, pdb)","id":418,"name":"pytest_leave_pdb","nodeType":"Function","startLoc":631,"text":"def pytest_leave_pdb(config, pdb):\n \"\"\" called when leaving pdb (e.g. with continue after pdb.set_trace()).\n\n Can be used by plugins to take special action just after the python\n debugger leaves interactive mode.\n\n :param _pytest.config.Config config: pytest config object\n :param pdb.Pdb pdb: Pdb instance\n \"\"\""},{"attributeType":"null","col":0,"comment":"null","endLoc":7,"id":419,"name":"hookspec","nodeType":"Attribute","startLoc":7,"text":"hookspec"},{"col":0,"comment":"","endLoc":2,"header":"hookspec.py#","id":420,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" hook specifications for pytest plugins, invoked from main.py and builtin plugins. \"\"\"\n\nhookspec = HookspecMarker(\"pytest\")"},{"id":423,"name":"release-3.9.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.9.1\n=======================================\n\npytest 3.9.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n* Ronny Pfannschmidt\n* Thomas Hisch\n\n\nHappy testing,\nThe pytest Development Team\n"},{"col":4,"comment":"null","endLoc":1029,"header":"@overload\n def sort(self: list[SupportsRichComparisonT], *, key: None = None, reverse: bool = False) -> None","id":424,"name":"sort","nodeType":"Function","startLoc":1028,"text":"@overload\n def sort(self: list[SupportsRichComparisonT], *, key: None = None, reverse: bool = False) -> None: ..."},{"col":4,"comment":"null","endLoc":1031,"header":"@overload\n def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> None","id":425,"name":"sort","nodeType":"Function","startLoc":1030,"text":"@overload\n def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> None: ..."},{"col":0,"comment":"null","endLoc":72,"header":"def report(issues)","id":426,"name":"report","nodeType":"Function","startLoc":56,"text":"def report(issues):\n for issue in issues:\n title = issue[\"title\"]\n # body = issue[\"body\"]\n kind = _get_kind(issue)\n status = issue[\"state\"]\n number = issue[\"number\"]\n link = \"https://github.com/pytest-dev/pytest/issues/%s/\" % number\n print(\"----\")\n print(status, kind, link)\n print(title)\n # print()\n # lines = body.split(\"\\n\")\n # print(\"\\n\".join(lines[:3]))\n # if len(lines) > 3 or len(body) > 240:\n # print(\"...\")\n print(\"\\n\\nFound %s open issues\" % len(issues))"},{"col":0,"comment":"null","endLoc":53,"header":"def _get_kind(issue)","id":427,"name":"_get_kind","nodeType":"Function","startLoc":48,"text":"def _get_kind(issue):\n labels = [l[\"name\"] for l in issue[\"labels\"]]\n for key in (\"bug\", \"enhancement\", \"proposal\"):\n if key in labels:\n return key\n return \"issue\""},{"id":428,"name":"doc/en/example/nonpython","nodeType":"Package"},{"fileName":"conftest.py","filePath":"doc/en/example/nonpython","id":429,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n# content of conftest.py\nimport pytest\n\n\ndef pytest_collect_file(parent, path):\n if path.ext == \".yml\" and path.basename.startswith(\"test\"):\n return YamlFile(path, parent)\n\n\nclass YamlFile(pytest.File):\n def collect(self):\n import yaml # we need a yaml parser, e.g. PyYAML\n\n raw = yaml.safe_load(self.fspath.open())\n for name, spec in sorted(raw.items()):\n yield YamlItem(name, self, spec)\n\n\nclass YamlItem(pytest.Item):\n def __init__(self, name, parent, spec):\n super(YamlItem, self).__init__(name, parent)\n self.spec = spec\n\n def runtest(self):\n for name, value in sorted(self.spec.items()):\n # some custom test execution (dumb example follows)\n if name != value:\n raise YamlException(self, name, value)\n\n def repr_failure(self, excinfo):\n \"\"\" called when self.runtest() raises an exception. \"\"\"\n if isinstance(excinfo.value, YamlException):\n return \"\\n\".join(\n [\n \"usecase execution failed\",\n \" spec failed: %r: %r\" % excinfo.value.args[1:3],\n \" no further details known at this point.\",\n ]\n )\n\n def reportinfo(self):\n return self.fspath, 0, \"usecase: %s\" % self.name\n\n\nclass YamlException(Exception):\n \"\"\" custom exception for error reporting. \"\"\"\n"},{"className":"YamlFile","col":0,"comment":"null","endLoc":17,"id":430,"nodeType":"Class","startLoc":11,"text":"class YamlFile(pytest.File):\n def collect(self):\n import yaml # we need a yaml parser, e.g. PyYAML\n\n raw = yaml.safe_load(self.fspath.open())\n for name, spec in sorted(raw.items()):\n yield YamlItem(name, self, spec)"},{"attributeType":"str","col":0,"comment":"null","endLoc":7,"id":432,"name":"issues_url","nodeType":"Attribute","startLoc":7,"text":"issues_url"},{"attributeType":"ArgumentParser","col":4,"comment":"null","endLoc":78,"id":433,"name":"parser","nodeType":"Attribute","startLoc":78,"text":"parser"},{"col":4,"comment":"null","endLoc":207,"header":"@classmethod\n def _get_pdb_wrapper_class(cls, pdb_cls, capman)","id":434,"name":"_get_pdb_wrapper_class","nodeType":"Function","startLoc":127,"text":"@classmethod\n def _get_pdb_wrapper_class(cls, pdb_cls, capman):\n import _pytest.config\n\n class PytestPdbWrapper(pdb_cls, object):\n _pytest_capman = capman\n _continued = False\n\n def do_debug(self, arg):\n cls._recursive_debug += 1\n ret = super(PytestPdbWrapper, self).do_debug(arg)\n cls._recursive_debug -= 1\n return ret\n\n def do_continue(self, arg):\n ret = super(PytestPdbWrapper, self).do_continue(arg)\n if cls._recursive_debug == 0:\n tw = _pytest.config.create_terminal_writer(cls._config)\n tw.line()\n\n capman = self._pytest_capman\n capturing = pytestPDB._is_capturing(capman)\n if capturing:\n if capturing == \"global\":\n tw.sep(\">\", \"PDB continue (IO-capturing resumed)\")\n else:\n tw.sep(\n \">\",\n \"PDB continue (IO-capturing resumed for %s)\"\n % capturing,\n )\n capman.resume()\n else:\n tw.sep(\">\", \"PDB continue\")\n cls._pluginmanager.hook.pytest_leave_pdb(config=cls._config, pdb=self)\n self._continued = True\n return ret\n\n do_c = do_cont = do_continue\n\n def do_quit(self, arg):\n \"\"\"Raise Exit outcome when quit command is used in pdb.\n\n This is a bit of a hack - it would be better if BdbQuit\n could be handled, but this would require to wrap the\n whole pytest run, and adjust the report etc.\n \"\"\"\n ret = super(PytestPdbWrapper, self).do_quit(arg)\n\n if cls._recursive_debug == 0:\n outcomes.exit(\"Quitting debugger\")\n\n return ret\n\n do_q = do_quit\n do_exit = do_quit\n\n def setup(self, f, tb):\n \"\"\"Suspend on setup().\n\n Needed after do_continue resumed, and entering another\n breakpoint again.\n \"\"\"\n ret = super(PytestPdbWrapper, self).setup(f, tb)\n if not ret and self._continued:\n # pdb.setup() returns True if the command wants to exit\n # from the interaction: do not suspend capturing then.\n if self._pytest_capman:\n self._pytest_capman.suspend_global_capture(in_=True)\n return ret\n\n def get_stack(self, f, t):\n stack, i = super(PytestPdbWrapper, self).get_stack(f, t)\n if f is None:\n # Find last non-hidden frame.\n i = max(0, len(stack) - 1)\n while i and stack[i][0].f_locals.get(\"__tracebackhide__\", False):\n i -= 1\n return stack, i\n\n return PytestPdbWrapper"},{"fileName":"release.py","filePath":"scripts","id":435,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"\nInvoke development tasks.\n\"\"\"\nimport argparse\nfrom pathlib import Path\nfrom subprocess import call\nfrom subprocess import check_call\nfrom subprocess import check_output\n\nfrom colorama import Fore\nfrom colorama import init\n\n\ndef announce(version):\n \"\"\"Generates a new release announcement entry in the docs.\"\"\"\n # Get our list of authors\n stdout = check_output([\"git\", \"describe\", \"--abbrev=0\", \"--tags\"])\n stdout = stdout.decode(\"utf-8\")\n last_version = stdout.strip()\n\n stdout = check_output(\n [\"git\", \"log\", \"{}..HEAD\".format(last_version), \"--format=%aN\"]\n )\n stdout = stdout.decode(\"utf-8\")\n\n contributors = set(stdout.splitlines())\n\n template_name = (\n \"release.minor.rst\" if version.endswith(\".0\") else \"release.patch.rst\"\n )\n template_text = (\n Path(__file__).parent.joinpath(template_name).read_text(encoding=\"UTF-8\")\n )\n\n contributors_text = (\n \"\\n\".join(\"* {}\".format(name) for name in sorted(contributors)) + \"\\n\"\n )\n text = template_text.format(version=version, contributors=contributors_text)\n\n target = Path(__file__).parent.joinpath(\n \"../doc/en/announce/release-{}.rst\".format(version)\n )\n target.write_text(text, encoding=\"UTF-8\")\n print(f\"{Fore.CYAN}[generate.announce] {Fore.RESET}Generated {target.name}\")\n\n # Update index with the new release entry\n index_path = Path(__file__).parent.joinpath(\"../doc/en/announce/index.rst\")\n lines = index_path.read_text(encoding=\"UTF-8\").splitlines()\n indent = \" \"\n for index, line in enumerate(lines):\n if line.startswith(\"{}release-\".format(indent)):\n new_line = indent + target.stem\n if line != new_line:\n lines.insert(index, new_line)\n index_path.write_text(\"\\n\".join(lines) + \"\\n\", encoding=\"UTF-8\")\n print(\n f\"{Fore.CYAN}[generate.announce] {Fore.RESET}Updated {index_path.name}\"\n )\n else:\n print(\n f\"{Fore.CYAN}[generate.announce] {Fore.RESET}Skip {index_path.name} (already contains release)\"\n )\n break\n\n check_call([\"git\", \"add\", str(target)])\n\n\ndef regen():\n \"\"\"Call regendoc tool to update examples and pytest output in the docs.\"\"\"\n print(f\"{Fore.CYAN}[generate.regen] {Fore.RESET}Updating docs\")\n check_call([\"tox\", \"-e\", \"regen\"])\n\n\ndef fix_formatting():\n \"\"\"Runs pre-commit in all files to ensure they are formatted correctly\"\"\"\n print(\n f\"{Fore.CYAN}[generate.fix linting] {Fore.RESET}Fixing formatting using pre-commit\"\n )\n call([\"pre-commit\", \"run\", \"--all-files\"])\n\n\ndef pre_release(version):\n \"\"\"Generates new docs, release announcements and creates a local tag.\"\"\"\n announce(version)\n regen()\n changelog(version, write_out=True)\n fix_formatting()\n\n msg = \"Preparing release version {}\".format(version)\n check_call([\"git\", \"commit\", \"-a\", \"-m\", msg])\n\n print()\n print(f\"{Fore.CYAN}[generate.pre_release] {Fore.GREEN}All done!\")\n print()\n print(f\"Please push your branch and open a PR.\")\n\n\ndef changelog(version, write_out=False):\n if write_out:\n addopts = []\n else:\n addopts = [\"--draft\"]\n check_call([\"towncrier\", \"--yes\", \"--version\", version] + addopts)\n\n\ndef main():\n init(autoreset=True)\n parser = argparse.ArgumentParser()\n parser.add_argument(\"version\", help=\"Release version\")\n options = parser.parse_args()\n pre_release(options.version)\n\n\nif __name__ == \"__main__\":\n main()\n"},{"col":4,"comment":"null","endLoc":962,"header":"def call(\n args: _CMD,\n bufsize: int = -1,\n executable: StrOrBytesPath | None = None,\n stdin: _FILE = None,\n stdout: _FILE = None,\n stderr: _FILE = None,\n preexec_fn: Callable[[], Any] | None = None,\n close_fds: bool = True,\n shell: bool = False,\n cwd: StrOrBytesPath | None = None,\n env: _ENV | None = None,\n universal_newlines: bool | None = None,\n startupinfo: Any = None,\n creationflags: int = 0,\n restore_signals: bool = True,\n start_new_session: bool = False,\n pass_fds: Collection[int] = ...,\n *,\n encoding: str | None = None,\n timeout: float | None = None,\n text: bool | None = None,\n user: str | int | None = None,\n group: str | int | None = None,\n extra_groups: Iterable[str | int] | None = None,\n umask: int = -1,\n ) -> int","id":436,"name":"call","nodeType":"Function","startLoc":936,"text":"def call(\n args: _CMD,\n bufsize: int = -1,\n executable: StrOrBytesPath | None = None,\n stdin: _FILE = None,\n stdout: _FILE = None,\n stderr: _FILE = None,\n preexec_fn: Callable[[], Any] | None = None,\n close_fds: bool = True,\n shell: bool = False,\n cwd: StrOrBytesPath | None = None,\n env: _ENV | None = None,\n universal_newlines: bool | None = None,\n startupinfo: Any = None,\n creationflags: int = 0,\n restore_signals: bool = True,\n start_new_session: bool = False,\n pass_fds: Collection[int] = ...,\n *,\n encoding: str | None = None,\n timeout: float | None = None,\n text: bool | None = None,\n user: str | int | None = None,\n group: str | int | None = None,\n extra_groups: Iterable[str | int] | None = None,\n umask: int = -1,\n ) -> int: ..."},{"className":"PyCollector","col":0,"comment":"null","endLoc":433,"id":437,"nodeType":"Class","startLoc":311,"text":"class PyCollector(PyobjMixin, nodes.Collector):\n def funcnamefilter(self, name):\n return self._matches_prefix_or_glob_option(\"python_functions\", name)\n\n def isnosetest(self, obj):\n \"\"\" Look for the __test__ attribute, which is applied by the\n @nose.tools.istest decorator\n \"\"\"\n # We explicitly check for \"is True\" here to not mistakenly treat\n # classes with a custom __getattr__ returning something truthy (like a\n # function) as test classes.\n return safe_getattr(obj, \"__test__\", False) is True\n\n def classnamefilter(self, name):\n return self._matches_prefix_or_glob_option(\"python_classes\", name)\n\n def istestfunction(self, obj, name):\n if self.funcnamefilter(name) or self.isnosetest(obj):\n if isinstance(obj, staticmethod):\n # static methods need to be unwrapped\n obj = safe_getattr(obj, \"__func__\", False)\n return (\n safe_getattr(obj, \"__call__\", False)\n and fixtures.getfixturemarker(obj) is None\n )\n else:\n return False\n\n def istestclass(self, obj, name):\n return self.classnamefilter(name) or self.isnosetest(obj)\n\n def _matches_prefix_or_glob_option(self, option_name, name):\n \"\"\"\n checks if the given name matches the prefix or glob-pattern defined\n in ini configuration.\n \"\"\"\n for option in self.config.getini(option_name):\n if name.startswith(option):\n return True\n # check that name looks like a glob-string before calling fnmatch\n # because this is called for every name in each collected module,\n # and fnmatch is somewhat expensive to call\n elif (\"*\" in option or \"?\" in option or \"[\" in option) and fnmatch.fnmatch(\n name, option\n ):\n return True\n return False\n\n def collect(self):\n if not getattr(self.obj, \"__test__\", True):\n return []\n\n # NB. we avoid random getattrs and peek in the __dict__ instead\n # (XXX originally introduced from a PyPy need, still true?)\n dicts = [getattr(self.obj, \"__dict__\", {})]\n for basecls in inspect.getmro(self.obj.__class__):\n dicts.append(basecls.__dict__)\n seen = {}\n values = []\n for dic in dicts:\n for name, obj in list(dic.items()):\n if name in seen:\n continue\n seen[name] = True\n res = self._makeitem(name, obj)\n if res is None:\n continue\n if not isinstance(res, list):\n res = [res]\n values.extend(res)\n values.sort(key=lambda item: item.reportinfo()[:2])\n return values\n\n def _makeitem(self, name, obj):\n # assert self.ihook.fspath == self.fspath, self\n return self.ihook.pytest_pycollect_makeitem(collector=self, name=name, obj=obj)\n\n def _genfunctions(self, name, funcobj):\n module = self.getparent(Module).obj\n clscol = self.getparent(Class)\n cls = clscol and clscol.obj or None\n fm = self.session._fixturemanager\n\n definition = FunctionDefinition(name=name, parent=self, callobj=funcobj)\n fixtureinfo = fm.getfixtureinfo(definition, funcobj, cls)\n\n metafunc = Metafunc(\n definition, fixtureinfo, self.config, cls=cls, module=module\n )\n methods = []\n if hasattr(module, \"pytest_generate_tests\"):\n methods.append(module.pytest_generate_tests)\n if hasattr(cls, \"pytest_generate_tests\"):\n methods.append(cls().pytest_generate_tests)\n if methods:\n self.ihook.pytest_generate_tests.call_extra(\n methods, dict(metafunc=metafunc)\n )\n else:\n self.ihook.pytest_generate_tests(metafunc=metafunc)\n\n if not metafunc._calls:\n yield Function(name, parent=self, fixtureinfo=fixtureinfo)\n else:\n # add funcargs() as fixturedefs to fixtureinfo.arg2fixturedefs\n fixtures.add_funcarg_pseudo_fixture_def(self, metafunc, fm)\n\n # add_funcarg_pseudo_fixture_def may have shadowed some fixtures\n # with direct parametrization, so make sure we update what the\n # function really needs.\n fixtureinfo.prune_dependency_tree()\n\n for callspec in metafunc._calls:\n subname = \"%s[%s]\" % (name, callspec.id)\n yield Function(\n name=subname,\n parent=self,\n callspec=callspec,\n callobj=funcobj,\n fixtureinfo=fixtureinfo,\n keywords={callspec.id: True},\n originalname=name,\n )"},{"className":"File","col":0,"comment":" base class for collecting tests from a file. ","endLoc":380,"id":438,"nodeType":"Class","startLoc":379,"text":"class File(FSCollector):\n \"\"\" base class for collecting tests from a file. \"\"\""},{"className":"PyobjMixin","col":0,"comment":"null","endLoc":308,"id":439,"nodeType":"Class","startLoc":248,"text":"class PyobjMixin(PyobjContext):\n _ALLOW_MARKERS = True\n\n def __init__(self, *k, **kw):\n super(PyobjMixin, self).__init__(*k, **kw)\n\n @property\n def obj(self):\n \"\"\"Underlying Python object.\"\"\"\n obj = getattr(self, \"_obj\", None)\n if obj is None:\n self._obj = obj = self._getobj()\n # XXX evil hack\n # used to avoid Instance collector marker duplication\n if self._ALLOW_MARKERS:\n self.own_markers.extend(get_unpacked_marks(self.obj))\n return obj\n\n @obj.setter\n def obj(self, value):\n self._obj = value\n\n def _getobj(self):\n \"\"\"Gets the underlying Python object. May be overwritten by subclasses.\"\"\"\n return getattr(self.parent.obj, self.name)\n\n def getmodpath(self, stopatmodule=True, includemodule=False):\n \"\"\" return python path relative to the containing module. \"\"\"\n chain = self.listchain()\n chain.reverse()\n parts = []\n for node in chain:\n if isinstance(node, Instance):\n continue\n name = node.name\n if isinstance(node, Module):\n name = os.path.splitext(name)[0]\n if stopatmodule:\n if includemodule:\n parts.append(name)\n break\n parts.append(name)\n parts.reverse()\n s = \".\".join(parts)\n return s.replace(\".[\", \"[\")\n\n def reportinfo(self):\n # XXX caching?\n obj = self.obj\n compat_co_firstlineno = getattr(obj, \"compat_co_firstlineno\", None)\n if isinstance(compat_co_firstlineno, int):\n # nose compatibility\n fspath = sys.modules[obj.__module__].__file__\n if fspath.endswith(\".pyc\"):\n fspath = fspath[:-1]\n lineno = compat_co_firstlineno\n else:\n fspath, lineno = getfslineno(obj)\n modpath = self.getmodpath()\n assert isinstance(lineno, int)\n return fspath, lineno, modpath"},{"className":"PyobjContext","col":0,"comment":"null","endLoc":245,"id":440,"nodeType":"Class","startLoc":242,"text":"class PyobjContext(object):\n module = pyobj_property(\"Module\")\n cls = pyobj_property(\"Class\")\n instance = pyobj_property(\"Instance\")"},{"attributeType":"null","col":4,"comment":"null","endLoc":243,"id":441,"name":"module","nodeType":"Attribute","startLoc":243,"text":"module"},{"col":0,"comment":"Create a TerminalWriter instance configured according to the options\n in the config object. Every code which requires a TerminalWriter object\n and has access to a config object should use this function.\n ","endLoc":1083,"header":"def create_terminal_writer(config, *args, **kwargs)","id":442,"name":"create_terminal_writer","nodeType":"Function","startLoc":1073,"text":"def create_terminal_writer(config, *args, **kwargs):\n \"\"\"Create a TerminalWriter instance configured according to the options\n in the config object. Every code which requires a TerminalWriter object\n and has access to a config object should use this function.\n \"\"\"\n tw = py.io.TerminalWriter(*args, **kwargs)\n if config.option.color == \"yes\":\n tw.hasmarkup = True\n if config.option.color == \"no\":\n tw.hasmarkup = False\n return tw"},{"col":4,"comment":"null","endLoc":30,"header":"@overload\n def warn(message: str, category: type[Warning] | None = None, stacklevel: int = 1, source: Any | None = None) -> None","id":443,"name":"warn","nodeType":"Function","startLoc":29,"text":"@overload\n def warn(message: str, category: type[Warning] | None = None, stacklevel: int = 1, source: Any | None = None) -> None: ..."},{"attributeType":"null","col":4,"comment":"null","endLoc":244,"id":444,"name":"cls","nodeType":"Attribute","startLoc":244,"text":"cls"},{"col":4,"comment":"null","endLoc":32,"header":"@overload\n def warn(message: Warning, category: Any = None, stacklevel: int = 1, source: Any | None = None) -> None","id":445,"name":"warn","nodeType":"Function","startLoc":31,"text":"@overload\n def warn(message: Warning, category: Any = None, stacklevel: int = 1, source: Any | None = None) -> None: ..."},{"attributeType":"null","col":4,"comment":"null","endLoc":245,"id":446,"name":"instance","nodeType":"Attribute","startLoc":245,"text":"instance"},{"col":4,"comment":"null","endLoc":252,"header":"def __init__(self, *k, **kw)","id":449,"name":"__init__","nodeType":"Function","startLoc":251,"text":"def __init__(self, *k, **kw):\n super(PyobjMixin, self).__init__(*k, **kw)"},{"className":"FSCollector","col":0,"comment":"null","endLoc":376,"id":451,"nodeType":"Class","startLoc":353,"text":"class FSCollector(Collector):\n def __init__(self, fspath, parent=None, config=None, session=None, nodeid=None):\n fspath = py.path.local(fspath) # xxx only for test_resultlog.py?\n name = fspath.basename\n if parent is not None:\n rel = fspath.relto(parent.fspath)\n if rel:\n name = rel\n name = name.replace(os.sep, SEP)\n self.fspath = fspath\n\n session = session or parent.session\n\n if nodeid is None:\n nodeid = self.fspath.relto(session.config.rootdir)\n\n if not nodeid:\n nodeid = _check_initialpaths_for_relpath(session, fspath)\n if nodeid and os.sep != SEP:\n nodeid = nodeid.replace(os.sep, SEP)\n\n super(FSCollector, self).__init__(\n name, parent, config, session, nodeid=nodeid, fspath=fspath\n )"},{"className":"Collector","col":0,"comment":" Collector instances create children through collect()\n and thus iteratively build a tree.\n ","endLoc":344,"id":452,"nodeType":"Class","startLoc":310,"text":"class Collector(Node):\n \"\"\" Collector instances create children through collect()\n and thus iteratively build a tree.\n \"\"\"\n\n class CollectError(Exception):\n \"\"\" an error during collection, contains a custom message. \"\"\"\n\n def collect(self):\n \"\"\" returns a list of children (items and collectors)\n for this collection node.\n \"\"\"\n raise NotImplementedError(\"abstract\")\n\n def repr_failure(self, excinfo):\n \"\"\" represent a collection failure. \"\"\"\n if excinfo.errisinstance(self.CollectError):\n exc = excinfo.value\n return str(exc.args[0])\n\n # Respect explicit tbstyle option, but default to \"short\"\n # (None._repr_failure_py defaults to \"long\" without \"fulltrace\" option).\n tbstyle = self.config.getoption(\"tbstyle\", \"auto\")\n if tbstyle == \"auto\":\n tbstyle = \"short\"\n\n return self._repr_failure_py(excinfo, style=tbstyle)\n\n def _prunetraceback(self, excinfo):\n if hasattr(self, \"fspath\"):\n traceback = excinfo.traceback\n ntraceback = traceback.cut(path=self.fspath)\n if ntraceback == traceback:\n ntraceback = ntraceback.cut(excludepath=tracebackcutdir)\n excinfo.traceback = ntraceback.filter()"},{"className":"Node","col":0,"comment":" base class for Collector and Item the test collection tree.\n Collector subclasses have children, Items are terminal nodes.","endLoc":289,"id":453,"nodeType":"Class","startLoc":58,"text":"class Node(object):\n \"\"\" base class for Collector and Item the test collection tree.\n Collector subclasses have children, Items are terminal nodes.\"\"\"\n\n def __init__(\n self, name, parent=None, config=None, session=None, fspath=None, nodeid=None\n ):\n #: a unique name within the scope of the parent node\n self.name = name\n\n #: the parent collector node.\n self.parent = parent\n\n #: the pytest config object\n self.config = config or parent.config\n\n #: the session this node is part of\n self.session = session or parent.session\n\n #: filesystem path where this node was collected from (can be None)\n self.fspath = fspath or getattr(parent, \"fspath\", None)\n\n #: keywords/markers collected from all scopes\n self.keywords = NodeKeywords(self)\n\n #: the marker objects belonging to this node\n self.own_markers = []\n\n #: allow adding of extra keywords to use for matching\n self.extra_keyword_matches = set()\n\n # used for storing artificial fixturedefs for direct parametrization\n self._name2pseudofixturedef = {}\n\n if nodeid is not None:\n assert \"::()\" not in nodeid\n self._nodeid = nodeid\n else:\n self._nodeid = self.parent.nodeid\n if self.name != \"()\":\n self._nodeid += \"::\" + self.name\n\n @property\n def ihook(self):\n \"\"\" fspath sensitive hook proxy used to call pytest hooks\"\"\"\n return self.session.gethookproxy(self.fspath)\n\n def __repr__(self):\n return \"<%s %s>\" % (self.__class__.__name__, getattr(self, \"name\", None))\n\n def warn(self, warning):\n \"\"\"Issue a warning for this item.\n\n Warnings will be displayed after the test session, unless explicitly suppressed\n\n :param Warning warning: the warning instance to issue. Must be a subclass of PytestWarning.\n\n :raise ValueError: if ``warning`` instance is not a subclass of PytestWarning.\n\n Example usage:\n\n .. code-block:: python\n\n node.warn(PytestWarning(\"some message\"))\n\n \"\"\"\n from _pytest.warning_types import PytestWarning\n\n if not isinstance(warning, PytestWarning):\n raise ValueError(\n \"warning must be an instance of PytestWarning or subclass, got {!r}\".format(\n warning\n )\n )\n path, lineno = get_fslocation_from_item(self)\n warnings.warn_explicit(\n warning,\n category=None,\n filename=str(path),\n lineno=lineno + 1 if lineno is not None else None,\n )\n\n # methods for ordering nodes\n @property\n def nodeid(self):\n \"\"\" a ::-separated string denoting its collection tree address. \"\"\"\n return self._nodeid\n\n def __hash__(self):\n return hash(self.nodeid)\n\n def setup(self):\n pass\n\n def teardown(self):\n pass\n\n def listchain(self):\n \"\"\" return list of all parent collectors up to self,\n starting from root of collection tree. \"\"\"\n chain = []\n item = self\n while item is not None:\n chain.append(item)\n item = item.parent\n chain.reverse()\n return chain\n\n def add_marker(self, marker, append=True):\n \"\"\"dynamically add a marker object to the node.\n\n :type marker: ``str`` or ``pytest.mark.*`` object\n :param marker:\n ``append=True`` whether to append the marker,\n if ``False`` insert at position ``0``.\n \"\"\"\n from _pytest.mark import MarkDecorator, MARK_GEN\n\n if isinstance(marker, six.string_types):\n marker = getattr(MARK_GEN, marker)\n elif not isinstance(marker, MarkDecorator):\n raise ValueError(\"is not a string or pytest.mark.* Marker\")\n self.keywords[marker.name] = marker\n if append:\n self.own_markers.append(marker.mark)\n else:\n self.own_markers.insert(0, marker.mark)\n\n def iter_markers(self, name=None):\n \"\"\"\n :param name: if given, filter the results by the name attribute\n\n iterate over all markers of the node\n \"\"\"\n return (x[1] for x in self.iter_markers_with_node(name=name))\n\n def iter_markers_with_node(self, name=None):\n \"\"\"\n :param name: if given, filter the results by the name attribute\n\n iterate over all markers of the node\n returns sequence of tuples (node, mark)\n \"\"\"\n for node in reversed(self.listchain()):\n for mark in node.own_markers:\n if name is None or getattr(mark, \"name\", None) == name:\n yield node, mark\n\n def get_closest_marker(self, name, default=None):\n \"\"\"return the first marker matching the name, from closest (for example function) to farther level (for example\n module level).\n\n :param default: fallback return value of no marker was found\n :param name: name to filter by\n \"\"\"\n return next(self.iter_markers(name=name), default)\n\n def listextrakeywords(self):\n \"\"\" Return a set of all extra keywords in self and any parents.\"\"\"\n extra_keywords = set()\n for item in self.listchain():\n extra_keywords.update(item.extra_keyword_matches)\n return extra_keywords\n\n def listnames(self):\n return [x.name for x in self.listchain()]\n\n def addfinalizer(self, fin):\n \"\"\" register a function to be called when this node is finalized.\n\n This method can only be called when this node is active\n in a setup chain, for example during self.setup().\n \"\"\"\n self.session._setupstate.addfinalizer(fin, self)\n\n def getparent(self, cls):\n \"\"\" get the next parent node (including ourself)\n which is an instance of the given class\"\"\"\n current = self\n while current and not isinstance(current, cls):\n current = current.parent\n return current\n\n def _prunetraceback(self, excinfo):\n pass\n\n def _repr_failure_py(self, excinfo, style=None):\n if excinfo.errisinstance(fail.Exception):\n if not excinfo.value.pytrace:\n return six.text_type(excinfo.value)\n fm = self.session._fixturemanager\n if excinfo.errisinstance(fm.FixtureLookupError):\n return excinfo.value.formatrepr()\n tbfilter = True\n if self.config.getoption(\"fulltrace\", False):\n style = \"long\"\n else:\n tb = _pytest._code.Traceback([excinfo.traceback[-1]])\n self._prunetraceback(excinfo)\n if len(excinfo.traceback) == 0:\n excinfo.traceback = tb\n tbfilter = False # prunetraceback already does it\n if style == \"auto\":\n style = \"long\"\n # XXX should excinfo.getrepr record all data and toterminal() process it?\n if style is None:\n if self.config.getoption(\"tbstyle\", \"auto\") == \"short\":\n style = \"short\"\n else:\n style = \"long\"\n\n if self.config.getoption(\"verbose\", 0) > 1:\n truncate_locals = False\n else:\n truncate_locals = True\n\n try:\n os.getcwd()\n abspath = False\n except OSError:\n abspath = True\n\n return excinfo.getrepr(\n funcargs=True,\n abspath=abspath,\n showlocals=self.config.getoption(\"showlocals\", False),\n style=style,\n tbfilter=tbfilter,\n truncate_locals=truncate_locals,\n )\n\n repr_failure = _repr_failure_py"},{"col":4,"comment":"null","endLoc":98,"header":"def __init__(\n self, name, parent=None, config=None, session=None, fspath=None, nodeid=None\n )","id":454,"name":"__init__","nodeType":"Function","startLoc":62,"text":"def __init__(\n self, name, parent=None, config=None, session=None, fspath=None, nodeid=None\n ):\n #: a unique name within the scope of the parent node\n self.name = name\n\n #: the parent collector node.\n self.parent = parent\n\n #: the pytest config object\n self.config = config or parent.config\n\n #: the session this node is part of\n self.session = session or parent.session\n\n #: filesystem path where this node was collected from (can be None)\n self.fspath = fspath or getattr(parent, \"fspath\", None)\n\n #: keywords/markers collected from all scopes\n self.keywords = NodeKeywords(self)\n\n #: the marker objects belonging to this node\n self.own_markers = []\n\n #: allow adding of extra keywords to use for matching\n self.extra_keyword_matches = set()\n\n # used for storing artificial fixturedefs for direct parametrization\n self._name2pseudofixturedef = {}\n\n if nodeid is not None:\n assert \"::()\" not in nodeid\n self._nodeid = nodeid\n else:\n self._nodeid = self.parent.nodeid\n if self.name != \"()\":\n self._nodeid += \"::\" + self.name"},{"col":4,"comment":"null","endLoc":727,"header":"def __init__(self, expected_exception, message, match_expr)","id":456,"name":"__init__","nodeType":"Function","startLoc":723,"text":"def __init__(self, expected_exception, message, match_expr):\n self.expected_exception = expected_exception\n self.message = message\n self.match_expr = match_expr\n self.excinfo = None"},{"attributeType":"Namespace","col":4,"comment":"null","endLoc":85,"id":459,"name":"args","nodeType":"Attribute","startLoc":85,"text":"args"},{"col":4,"comment":"Underlying Python object.","endLoc":264,"header":"@property\n def obj(self)","id":460,"name":"obj","nodeType":"Function","startLoc":254,"text":"@property\n def obj(self):\n \"\"\"Underlying Python object.\"\"\"\n obj = getattr(self, \"_obj\", None)\n if obj is None:\n self._obj = obj = self._getobj()\n # XXX evil hack\n # used to avoid Instance collector marker duplication\n if self._ALLOW_MARKERS:\n self.own_markers.extend(get_unpacked_marks(self.obj))\n return obj"},{"col":4,"comment":"null","endLoc":1081,"header":"def check_call(\n args: _CMD,\n bufsize: int = -1,\n executable: StrOrBytesPath | None = None,\n stdin: _FILE = None,\n stdout: _FILE = None,\n stderr: _FILE = None,\n preexec_fn: Callable[[], Any] | None = None,\n close_fds: bool = True,\n shell: bool = False,\n cwd: StrOrBytesPath | None = None,\n env: _ENV | None = None,\n universal_newlines: bool | None = None,\n startupinfo: Any = None,\n creationflags: int = 0,\n restore_signals: bool = True,\n start_new_session: bool = False,\n pass_fds: Collection[int] = ...,\n timeout: float | None = ...,\n *,\n encoding: str | None = None,\n text: bool | None = None,\n user: str | int | None = None,\n group: str | int | None = None,\n extra_groups: Iterable[str | int] | None = None,\n umask: int = -1,\n ) -> int","id":461,"name":"check_call","nodeType":"Function","startLoc":1055,"text":"def check_call(\n args: _CMD,\n bufsize: int = -1,\n executable: StrOrBytesPath | None = None,\n stdin: _FILE = None,\n stdout: _FILE = None,\n stderr: _FILE = None,\n preexec_fn: Callable[[], Any] | None = None,\n close_fds: bool = True,\n shell: bool = False,\n cwd: StrOrBytesPath | None = None,\n env: _ENV | None = None,\n universal_newlines: bool | None = None,\n startupinfo: Any = None,\n creationflags: int = 0,\n restore_signals: bool = True,\n start_new_session: bool = False,\n pass_fds: Collection[int] = ...,\n timeout: float | None = ...,\n *,\n encoding: str | None = None,\n text: bool | None = None,\n user: str | int | None = None,\n group: str | int | None = None,\n extra_groups: Iterable[str | int] | None = None,\n umask: int = -1,\n ) -> int: ..."},{"col":4,"comment":"null","endLoc":1512,"header":"@overload\n def check_output(\n args: _CMD,\n bufsize: int = -1,\n executable: StrOrBytesPath | None = None,\n stdin: _FILE = None,\n stderr: _FILE = None,\n preexec_fn: Callable[[], Any] | None = None,\n close_fds: bool = True,\n shell: bool = False,\n cwd: StrOrBytesPath | None = None,\n env: _ENV | None = None,\n universal_newlines: bool | None = None,\n startupinfo: Any = None,\n creationflags: int = 0,\n restore_signals: bool = True,\n start_new_session: bool = False,\n pass_fds: Collection[int] = ...,\n *,\n timeout: float | None = None,\n input: _InputString | None = ...,\n encoding: str | None = None,\n errors: str | None = None,\n text: Literal[True],\n user: str | int | None = None,\n group: str | int | None = None,\n extra_groups: Iterable[str | int] | None = None,\n umask: int = -1,\n ) -> str","id":462,"name":"check_output","nodeType":"Function","startLoc":1484,"text":"@overload\n def check_output(\n args: _CMD,\n bufsize: int = -1,\n executable: StrOrBytesPath | None = None,\n stdin: _FILE = None,\n stderr: _FILE = None,\n preexec_fn: Callable[[], Any] | None = None,\n close_fds: bool = True,\n shell: bool = False,\n cwd: StrOrBytesPath | None = None,\n env: _ENV | None = None,\n universal_newlines: bool | None = None,\n startupinfo: Any = None,\n creationflags: int = 0,\n restore_signals: bool = True,\n start_new_session: bool = False,\n pass_fds: Collection[int] = ...,\n *,\n timeout: float | None = None,\n input: _InputString | None = ...,\n encoding: str | None = None,\n errors: str | None = None,\n text: Literal[True],\n user: str | int | None = None,\n group: str | int | None = None,\n extra_groups: Iterable[str | int] | None = None,\n umask: int = -1,\n ) -> str: ..."},{"col":4,"comment":"null","endLoc":1541,"header":"@overload\n def check_output(\n args: _CMD,\n bufsize: int = -1,\n executable: StrOrBytesPath | None = None,\n stdin: _FILE = None,\n stderr: _FILE = None,\n preexec_fn: Callable[[], Any] | None = None,\n close_fds: bool = True,\n shell: bool = False,\n cwd: StrOrBytesPath | None = None,\n env: _ENV | None = None,\n universal_newlines: bool | None = None,\n startupinfo: Any = None,\n creationflags: int = 0,\n restore_signals: bool = True,\n start_new_session: bool = False,\n pass_fds: Collection[int] = ...,\n *,\n timeout: float | None = None,\n input: _InputString | None = ...,\n encoding: str,\n errors: str | None = None,\n text: bool | None = None,\n user: str | int | None = None,\n group: str | int | None = None,\n extra_groups: Iterable[str | int] | None = None,\n umask: int = -1,\n ) -> str","id":463,"name":"check_output","nodeType":"Function","startLoc":1513,"text":"@overload\n def check_output(\n args: _CMD,\n bufsize: int = -1,\n executable: StrOrBytesPath | None = None,\n stdin: _FILE = None,\n stderr: _FILE = None,\n preexec_fn: Callable[[], Any] | None = None,\n close_fds: bool = True,\n shell: bool = False,\n cwd: StrOrBytesPath | None = None,\n env: _ENV | None = None,\n universal_newlines: bool | None = None,\n startupinfo: Any = None,\n creationflags: int = 0,\n restore_signals: bool = True,\n start_new_session: bool = False,\n pass_fds: Collection[int] = ...,\n *,\n timeout: float | None = None,\n input: _InputString | None = ...,\n encoding: str,\n errors: str | None = None,\n text: bool | None = None,\n user: str | int | None = None,\n group: str | int | None = None,\n extra_groups: Iterable[str | int] | None = None,\n umask: int = -1,\n ) -> str: ..."},{"col":4,"comment":"null","endLoc":1570,"header":"@overload\n def check_output(\n args: _CMD,\n bufsize: int = -1,\n executable: StrOrBytesPath | None = None,\n stdin: _FILE = None,\n stderr: _FILE = None,\n preexec_fn: Callable[[], Any] | None = None,\n close_fds: bool = True,\n shell: bool = False,\n cwd: StrOrBytesPath | None = None,\n env: _ENV | None = None,\n universal_newlines: bool | None = None,\n startupinfo: Any = None,\n creationflags: int = 0,\n restore_signals: bool = True,\n start_new_session: bool = False,\n pass_fds: Collection[int] = ...,\n *,\n timeout: float | None = None,\n input: _InputString | None = ...,\n encoding: str | None = None,\n errors: str,\n text: bool | None = None,\n user: str | int | None = None,\n group: str | int | None = None,\n extra_groups: Iterable[str | int] | None = None,\n umask: int = -1,\n ) -> str","id":464,"name":"check_output","nodeType":"Function","startLoc":1542,"text":"@overload\n def check_output(\n args: _CMD,\n bufsize: int = -1,\n executable: StrOrBytesPath | None = None,\n stdin: _FILE = None,\n stderr: _FILE = None,\n preexec_fn: Callable[[], Any] | None = None,\n close_fds: bool = True,\n shell: bool = False,\n cwd: StrOrBytesPath | None = None,\n env: _ENV | None = None,\n universal_newlines: bool | None = None,\n startupinfo: Any = None,\n creationflags: int = 0,\n restore_signals: bool = True,\n start_new_session: bool = False,\n pass_fds: Collection[int] = ...,\n *,\n timeout: float | None = None,\n input: _InputString | None = ...,\n encoding: str | None = None,\n errors: str,\n text: bool | None = None,\n user: str | int | None = None,\n group: str | int | None = None,\n extra_groups: Iterable[str | int] | None = None,\n umask: int = -1,\n ) -> str: ..."},{"col":4,"comment":"null","endLoc":1600,"header":"@overload\n def check_output(\n args: _CMD,\n bufsize: int = -1,\n executable: StrOrBytesPath | None = None,\n stdin: _FILE = None,\n stderr: _FILE = None,\n preexec_fn: Callable[[], Any] | None = None,\n close_fds: bool = True,\n shell: bool = False,\n cwd: StrOrBytesPath | None = None,\n env: _ENV | None = None,\n *,\n universal_newlines: Literal[True],\n startupinfo: Any = None,\n creationflags: int = 0,\n restore_signals: bool = True,\n start_new_session: bool = False,\n pass_fds: Collection[int] = ...,\n # where the real keyword only ones start\n timeout: float | None = None,\n input: _InputString | None = ...,\n encoding: str | None = None,\n errors: str | None = None,\n text: bool | None = None,\n user: str | int | None = None,\n group: str | int | None = None,\n extra_groups: Iterable[str | int] | None = None,\n umask: int = -1,\n ) -> str","id":465,"name":"check_output","nodeType":"Function","startLoc":1571,"text":"@overload\n def check_output(\n args: _CMD,\n bufsize: int = -1,\n executable: StrOrBytesPath | None = None,\n stdin: _FILE = None,\n stderr: _FILE = None,\n preexec_fn: Callable[[], Any] | None = None,\n close_fds: bool = True,\n shell: bool = False,\n cwd: StrOrBytesPath | None = None,\n env: _ENV | None = None,\n *,\n universal_newlines: Literal[True],\n startupinfo: Any = None,\n creationflags: int = 0,\n restore_signals: bool = True,\n start_new_session: bool = False,\n pass_fds: Collection[int] = ...,\n # where the real keyword only ones start\n timeout: float | None = None,\n input: _InputString | None = ...,\n encoding: str | None = None,\n errors: str | None = None,\n text: bool | None = None,\n user: str | int | None = None,\n group: str | int | None = None,\n extra_groups: Iterable[str | int] | None = None,\n umask: int = -1,\n ) -> str: ..."},{"col":4,"comment":"null","endLoc":1629,"header":"@overload\n def check_output(\n args: _CMD,\n bufsize: int = -1,\n executable: StrOrBytesPath | None = None,\n stdin: _FILE = None,\n stderr: _FILE = None,\n preexec_fn: Callable[[], Any] | None = None,\n close_fds: bool = True,\n shell: bool = False,\n cwd: StrOrBytesPath | None = None,\n env: _ENV | None = None,\n universal_newlines: Literal[False] | None = None,\n startupinfo: Any = None,\n creationflags: int = 0,\n restore_signals: bool = True,\n start_new_session: bool = False,\n pass_fds: Collection[int] = ...,\n *,\n timeout: float | None = None,\n input: _InputString | None = ...,\n encoding: None = None,\n errors: None = None,\n text: Literal[False] | None = None,\n user: str | int | None = None,\n group: str | int | None = None,\n extra_groups: Iterable[str | int] | None = None,\n umask: int = -1,\n ) -> bytes","id":466,"name":"check_output","nodeType":"Function","startLoc":1601,"text":"@overload\n def check_output(\n args: _CMD,\n bufsize: int = -1,\n executable: StrOrBytesPath | None = None,\n stdin: _FILE = None,\n stderr: _FILE = None,\n preexec_fn: Callable[[], Any] | None = None,\n close_fds: bool = True,\n shell: bool = False,\n cwd: StrOrBytesPath | None = None,\n env: _ENV | None = None,\n universal_newlines: Literal[False] | None = None,\n startupinfo: Any = None,\n creationflags: int = 0,\n restore_signals: bool = True,\n start_new_session: bool = False,\n pass_fds: Collection[int] = ...,\n *,\n timeout: float | None = None,\n input: _InputString | None = ...,\n encoding: None = None,\n errors: None = None,\n text: Literal[False] | None = None,\n user: str | int | None = None,\n group: str | int | None = None,\n extra_groups: Iterable[str | int] | None = None,\n umask: int = -1,\n ) -> bytes: ..."},{"col":4,"comment":"null","endLoc":1658,"header":"@overload\n def check_output(\n args: _CMD,\n bufsize: int = -1,\n executable: StrOrBytesPath | None = None,\n stdin: _FILE = None,\n stderr: _FILE = None,\n preexec_fn: Callable[[], Any] | None = None,\n close_fds: bool = True,\n shell: bool = False,\n cwd: StrOrBytesPath | None = None,\n env: _ENV | None = None,\n universal_newlines: bool | None = None,\n startupinfo: Any = None,\n creationflags: int = 0,\n restore_signals: bool = True,\n start_new_session: bool = False,\n pass_fds: Collection[int] = ...,\n *,\n timeout: float | None = None,\n input: _InputString | None = ...,\n encoding: str | None = None,\n errors: str | None = None,\n text: bool | None = None,\n user: str | int | None = None,\n group: str | int | None = None,\n extra_groups: Iterable[str | int] | None = None,\n umask: int = -1,\n ) -> Any","id":467,"name":"check_output","nodeType":"Function","startLoc":1630,"text":"@overload\n def check_output(\n args: _CMD,\n bufsize: int = -1,\n executable: StrOrBytesPath | None = None,\n stdin: _FILE = None,\n stderr: _FILE = None,\n preexec_fn: Callable[[], Any] | None = None,\n close_fds: bool = True,\n shell: bool = False,\n cwd: StrOrBytesPath | None = None,\n env: _ENV | None = None,\n universal_newlines: bool | None = None,\n startupinfo: Any = None,\n creationflags: int = 0,\n restore_signals: bool = True,\n start_new_session: bool = False,\n pass_fds: Collection[int] = ...,\n *,\n timeout: float | None = None,\n input: _InputString | None = ...,\n encoding: str | None = None,\n errors: str | None = None,\n text: bool | None = None,\n user: str | int | None = None,\n group: str | int | None = None,\n extra_groups: Iterable[str | int] | None = None,\n umask: int = -1,\n ) -> Any: ... # morally: -> str | bytes"},{"col":0,"comment":"Generates a new release announcement entry in the docs.","endLoc":66,"header":"def announce(version)","id":468,"name":"announce","nodeType":"Function","startLoc":15,"text":"def announce(version):\n \"\"\"Generates a new release announcement entry in the docs.\"\"\"\n # Get our list of authors\n stdout = check_output([\"git\", \"describe\", \"--abbrev=0\", \"--tags\"])\n stdout = stdout.decode(\"utf-8\")\n last_version = stdout.strip()\n\n stdout = check_output(\n [\"git\", \"log\", \"{}..HEAD\".format(last_version), \"--format=%aN\"]\n )\n stdout = stdout.decode(\"utf-8\")\n\n contributors = set(stdout.splitlines())\n\n template_name = (\n \"release.minor.rst\" if version.endswith(\".0\") else \"release.patch.rst\"\n )\n template_text = (\n Path(__file__).parent.joinpath(template_name).read_text(encoding=\"UTF-8\")\n )\n\n contributors_text = (\n \"\\n\".join(\"* {}\".format(name) for name in sorted(contributors)) + \"\\n\"\n )\n text = template_text.format(version=version, contributors=contributors_text)\n\n target = Path(__file__).parent.joinpath(\n \"../doc/en/announce/release-{}.rst\".format(version)\n )\n target.write_text(text, encoding=\"UTF-8\")\n print(f\"{Fore.CYAN}[generate.announce] {Fore.RESET}Generated {target.name}\")\n\n # Update index with the new release entry\n index_path = Path(__file__).parent.joinpath(\"../doc/en/announce/index.rst\")\n lines = index_path.read_text(encoding=\"UTF-8\").splitlines()\n indent = \" \"\n for index, line in enumerate(lines):\n if line.startswith(\"{}release-\".format(indent)):\n new_line = indent + target.stem\n if line != new_line:\n lines.insert(index, new_line)\n index_path.write_text(\"\\n\".join(lines) + \"\\n\", encoding=\"UTF-8\")\n print(\n f\"{Fore.CYAN}[generate.announce] {Fore.RESET}Updated {index_path.name}\"\n )\n else:\n print(\n f\"{Fore.CYAN}[generate.announce] {Fore.RESET}Skip {index_path.name} (already contains release)\"\n )\n break\n\n check_call([\"git\", \"add\", str(target)])"},{"col":4,"comment":"null","endLoc":43,"header":"def __init__(self, *parts, **kwargs)","id":469,"name":"__init__","nodeType":"Function","startLoc":27,"text":"def __init__(self, *parts, **kwargs):\n self.lines = lines = []\n de = kwargs.get(\"deindent\", True)\n for part in parts:\n if not part:\n partlines = []\n elif isinstance(part, Source):\n partlines = part.lines\n elif isinstance(part, (tuple, list)):\n partlines = [x.rstrip(\"\\n\") for x in part]\n elif isinstance(part, six.string_types):\n partlines = part.split(\"\\n\")\n else:\n partlines = getsource(part, deindent=de).lines\n if de:\n partlines = deindent(partlines)\n lines.extend(partlines)"},{"col":4,"comment":"Gets the underlying Python object. May be overwritten by subclasses.","endLoc":272,"header":"def _getobj(self)","id":470,"name":"_getobj","nodeType":"Function","startLoc":270,"text":"def _getobj(self):\n \"\"\"Gets the underlying Python object. May be overwritten by subclasses.\"\"\"\n return getattr(self.parent.obj, self.name)"},{"col":4,"comment":"null","endLoc":329,"header":"def register(self, plugin, name=None)","id":471,"name":"register","nodeType":"Function","startLoc":310,"text":"def register(self, plugin, name=None):\n if name in [\"pytest_catchlog\", \"pytest_capturelog\"]:\n warnings.warn(\n PytestConfigWarning(\n \"{} plugin has been merged into the core, \"\n \"please remove it from your requirements.\".format(\n name.replace(\"_\", \"-\")\n )\n )\n )\n return\n ret = super(PytestPluginManager, self).register(plugin, name)\n if ret:\n self.hook.pytest_plugin_registered.call_historic(\n kwargs=dict(plugin=plugin, manager=self)\n )\n\n if isinstance(plugin, types.ModuleType):\n self.consider_module(plugin)\n return ret"},{"col":0,"comment":"\n obtain the unpacked marks that are stored on an object\n ","endLoc":261,"header":"def get_unpacked_marks(obj)","id":472,"name":"get_unpacked_marks","nodeType":"Function","startLoc":254,"text":"def get_unpacked_marks(obj):\n \"\"\"\n obtain the unpacked marks that are stored on an object\n \"\"\"\n mark_list = getattr(obj, \"pytestmark\", [])\n if not isinstance(mark_list, list):\n mark_list = [mark_list]\n return normalize_mark_list(mark_list)"},{"col":4,"comment":"null","endLoc":1100,"header":"@overload # type: ignore[override]\n def get(self, __key: _KT) -> _VT | None","id":473,"name":"get","nodeType":"Function","startLoc":1099,"text":"@overload # type: ignore[override]\n def get(self, __key: _KT) -> _VT | None: ..."},{"col":4,"comment":"null","endLoc":1102,"header":"@overload\n def get(self, __key: _KT, __default: _VT) -> _VT","id":474,"name":"get","nodeType":"Function","startLoc":1101,"text":"@overload\n def get(self, __key: _KT, __default: _VT) -> _VT: ..."},{"col":4,"comment":"null","endLoc":1104,"header":"@overload\n def get(self, __key: _KT, __default: _T) -> _VT | _T","id":475,"name":"get","nodeType":"Function","startLoc":1103,"text":"@overload\n def get(self, __key: _KT, __default: _T) -> _VT | _T: ..."},{"col":4,"comment":"null","endLoc":347,"header":"def __init__(self, node)","id":482,"name":"__init__","nodeType":"Function","startLoc":344,"text":"def __init__(self, node):\n self.node = node\n self.parent = node.parent\n self._markers = {node.name: True}"},{"col":0,"comment":"null","endLoc":259,"header":"def getsource(obj, **kwargs)","id":483,"name":"getsource","nodeType":"Function","startLoc":250,"text":"def getsource(obj, **kwargs):\n from .code import getrawcode\n\n obj = getrawcode(obj)\n try:\n strsrc = inspect.getsource(obj)\n except IndentationError:\n strsrc = '\"Buggy python version consider upgrading, cannot get source\"'\n assert isinstance(strsrc, str)\n return Source(strsrc, **kwargs)"},{"col":4,"comment":" Initialize PDB debugging, dropping any IO capturing. ","endLoc":247,"header":"@classmethod\n def _init_pdb(cls, method, *args, **kwargs)","id":484,"name":"_init_pdb","nodeType":"Function","startLoc":209,"text":"@classmethod\n def _init_pdb(cls, method, *args, **kwargs):\n \"\"\" Initialize PDB debugging, dropping any IO capturing. \"\"\"\n import _pytest.config\n\n if cls._pluginmanager is not None:\n capman = cls._pluginmanager.getplugin(\"capturemanager\")\n else:\n capman = None\n if capman:\n capman.suspend(in_=True)\n\n if cls._config:\n tw = _pytest.config.create_terminal_writer(cls._config)\n tw.line()\n\n if cls._recursive_debug == 0:\n # Handle header similar to pdb.set_trace in py37+.\n header = kwargs.pop(\"header\", None)\n if header is not None:\n tw.sep(\">\", header)\n else:\n capturing = cls._is_capturing(capman)\n if capturing == \"global\":\n tw.sep(\">\", \"PDB %s (IO-capturing turned off)\" % (method,))\n elif capturing:\n tw.sep(\n \">\",\n \"PDB %s (IO-capturing turned off for %s)\"\n % (method, capturing),\n )\n else:\n tw.sep(\">\", \"PDB %s\" % (method,))\n\n _pdb = cls._import_pdb_cls(capman)(**kwargs)\n\n if cls._pluginmanager:\n cls._pluginmanager.hook.pytest_enter_pdb(config=cls._config, pdb=_pdb)\n return _pdb"},{"col":0,"comment":"\n normalizes marker decorating helpers to mark objects\n\n :type mark_list: List[Union[Mark, Markdecorator]]\n :rtype: List[Mark]\n ","endLoc":277,"header":"def normalize_mark_list(mark_list)","id":485,"name":"normalize_mark_list","nodeType":"Function","startLoc":264,"text":"def normalize_mark_list(mark_list):\n \"\"\"\n normalizes marker decorating helpers to mark objects\n\n :type mark_list: List[Union[Mark, Markdecorator]]\n :rtype: List[Mark]\n \"\"\"\n extracted = [\n getattr(mark, \"mark\", mark) for mark in mark_list\n ] # unpack MarkDecorator\n for mark in extracted:\n if not isinstance(mark, Mark):\n raise TypeError(\"got {!r} instead of Mark\".format(mark))\n return [x for x in extracted if isinstance(x, Mark)]"},{"col":4,"comment":"null","endLoc":268,"header":"@obj.setter\n def obj(self, value)","id":486,"name":"obj","nodeType":"Function","startLoc":266,"text":"@obj.setter\n def obj(self, value):\n self._obj = value"},{"col":4,"comment":" return python path relative to the containing module. ","endLoc":292,"header":"def getmodpath(self, stopatmodule=True, includemodule=False)","id":487,"name":"getmodpath","nodeType":"Function","startLoc":274,"text":"def getmodpath(self, stopatmodule=True, includemodule=False):\n \"\"\" return python path relative to the containing module. \"\"\"\n chain = self.listchain()\n chain.reverse()\n parts = []\n for node in chain:\n if isinstance(node, Instance):\n continue\n name = node.name\n if isinstance(node, Module):\n name = os.path.splitext(name)[0]\n if stopatmodule:\n if includemodule:\n parts.append(name)\n break\n parts.append(name)\n parts.reverse()\n s = \".\".join(parts)\n return s.replace(\".[\", \"[\")"},{"col":4,"comment":"Invoke debugging via ``Pdb.set_trace``, dropping any IO capturing.","endLoc":254,"header":"@classmethod\n def set_trace(cls, *args, **kwargs)","id":490,"name":"set_trace","nodeType":"Function","startLoc":249,"text":"@classmethod\n def set_trace(cls, *args, **kwargs):\n \"\"\"Invoke debugging via ``Pdb.set_trace``, dropping any IO capturing.\"\"\"\n frame = sys._getframe().f_back\n _pdb = cls._init_pdb(\"set_trace\", *args, **kwargs)\n _pdb.set_trace(frame)"},{"attributeType":"null","col":4,"comment":"null","endLoc":80,"id":494,"name":"_pluginmanager","nodeType":"Attribute","startLoc":80,"text":"_pluginmanager"},{"attributeType":"null","col":4,"comment":"null","endLoc":81,"id":495,"name":"_config","nodeType":"Attribute","startLoc":81,"text":"_config"},{"attributeType":"null","col":4,"comment":"null","endLoc":82,"id":496,"name":"_saved","nodeType":"Attribute","startLoc":82,"text":"_saved"},{"attributeType":"null","col":4,"comment":"null","endLoc":83,"id":497,"name":"_recursive_debug","nodeType":"Attribute","startLoc":83,"text":"_recursive_debug"},{"attributeType":"null","col":4,"comment":"null","endLoc":84,"id":498,"name":"_wrapped_pdb_cls","nodeType":"Attribute","startLoc":84,"text":"_wrapped_pdb_cls"},{"attributeType":"null","col":8,"comment":"null","endLoc":124,"id":499,"name":"_wrapped_pdb_cls","nodeType":"Attribute","startLoc":124,"text":"cls._wrapped_pdb_cls"},{"col":0,"comment":"","endLoc":2,"header":"get_issues.py#","id":500,"name":"","nodeType":"Function","startLoc":2,"text":"issues_url = \"https://api.github.com/repos/pytest-dev/pytest/issues\"\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser(\"process bitbucket issues\")\n parser.add_argument(\n \"--refresh\", action=\"store_true\", help=\"invalidate cache, refresh issues\"\n )\n parser.add_argument(\n \"--cache\", action=\"store\", default=\"issues.json\", help=\"cache file\"\n )\n args = parser.parse_args()\n main(args)"},{"col":8,"comment":"null","endLoc":157,"header":"def __init__(\n self,\n prog: str | None = None,\n usage: str | None = None,\n description: str | None = None,\n epilog: str | None = None,\n parents: Sequence[ArgumentParser] = [],\n formatter_class: _FormatterClass = ...,\n prefix_chars: str = \"-\",\n fromfile_prefix_chars: str | None = None,\n argument_default: Any = None,\n conflict_handler: str = \"error\",\n add_help: bool = True,\n allow_abbrev: bool = True,\n exit_on_error: bool = True,\n ) -> None","id":501,"name":"__init__","nodeType":"Function","startLoc":142,"text":"def __init__(\n self,\n prog: str | None = None,\n usage: str | None = None,\n description: str | None = None,\n epilog: str | None = None,\n parents: Sequence[ArgumentParser] = [],\n formatter_class: _FormatterClass = ...,\n prefix_chars: str = \"-\",\n fromfile_prefix_chars: str | None = None,\n argument_default: Any = None,\n conflict_handler: str = \"error\",\n add_help: bool = True,\n allow_abbrev: bool = True,\n exit_on_error: bool = True,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":1067,"header":"@overload\n def __init__(self) -> None","id":502,"name":"__init__","nodeType":"Function","startLoc":1066,"text":"@overload\n def __init__(self) -> None: ..."},{"col":4,"comment":"null","endLoc":1069,"header":"@overload\n def __init__(self: dict[str, _VT], **kwargs: _VT) -> None","id":503,"name":"__init__","nodeType":"Function","startLoc":1068,"text":"@overload\n def __init__(self: dict[str, _VT], **kwargs: _VT) -> None: ..."},{"col":4,"comment":"null","endLoc":1071,"header":"@overload\n def __init__(self, __map: SupportsKeysAndGetItem[_KT, _VT]) -> None","id":504,"name":"__init__","nodeType":"Function","startLoc":1070,"text":"@overload\n def __init__(self, __map: SupportsKeysAndGetItem[_KT, _VT]) -> None: ..."},{"col":4,"comment":"null","endLoc":1073,"header":"@overload\n def __init__(self: dict[str, _VT], __map: SupportsKeysAndGetItem[str, _VT], **kwargs: _VT) -> None","id":505,"name":"__init__","nodeType":"Function","startLoc":1072,"text":"@overload\n def __init__(self: dict[str, _VT], __map: SupportsKeysAndGetItem[str, _VT], **kwargs: _VT) -> None: ..."},{"col":4,"comment":"null","endLoc":1075,"header":"@overload\n def __init__(self, __iterable: Iterable[tuple[_KT, _VT]]) -> None","id":506,"name":"__init__","nodeType":"Function","startLoc":1074,"text":"@overload\n def __init__(self, __iterable: Iterable[tuple[_KT, _VT]]) -> None: ..."},{"col":4,"comment":"null","endLoc":1077,"header":"@overload\n def __init__(self: dict[str, _VT], __iterable: Iterable[tuple[str, _VT]], **kwargs: _VT) -> None","id":507,"name":"__init__","nodeType":"Function","startLoc":1076,"text":"@overload\n def __init__(self: dict[str, _VT], __iterable: Iterable[tuple[str, _VT]], **kwargs: _VT) -> None: ..."},{"col":4,"comment":"null","endLoc":1081,"header":"@overload\n def __init__(self: dict[str, str], __iterable: Iterable[list[str]]) -> None","id":508,"name":"__init__","nodeType":"Function","startLoc":1080,"text":"@overload\n def __init__(self: dict[str, str], __iterable: Iterable[list[str]]) -> None: ..."},{"col":4,"comment":"null","endLoc":1083,"header":"@overload\n def __init__(self: dict[bytes, bytes], __iterable: Iterable[list[bytes]]) -> None","id":509,"name":"__init__","nodeType":"Function","startLoc":1082,"text":"@overload\n def __init__(self: dict[bytes, bytes], __iterable: Iterable[list[bytes]]) -> None: ..."},{"col":4,"comment":"null","endLoc":533,"header":"def consider_module(self, mod)","id":510,"name":"consider_module","nodeType":"Function","startLoc":532,"text":"def consider_module(self, mod):\n self._import_plugin_specs(getattr(mod, \"pytest_plugins\", []))"},{"col":4,"comment":"null","endLoc":538,"header":"def _import_plugin_specs(self, spec)","id":511,"name":"_import_plugin_specs","nodeType":"Function","startLoc":535,"text":"def _import_plugin_specs(self, spec):\n plugins = _get_plugin_specs_as_list(spec)\n for import_spec in plugins:\n self.import_plugin(import_spec)"},{"col":0,"comment":"\n Parses a list of \"plugin specs\" and returns a list of plugin names.\n\n Plugin specs can be given as a list of strings separated by \",\" or already as a list/tuple in\n which case it is returned as a list. Specs can also be `None` in which case an\n empty list is returned.\n ","endLoc":606,"header":"def _get_plugin_specs_as_list(specs)","id":512,"name":"_get_plugin_specs_as_list","nodeType":"Function","startLoc":589,"text":"def _get_plugin_specs_as_list(specs):\n \"\"\"\n Parses a list of \"plugin specs\" and returns a list of plugin names.\n\n Plugin specs can be given as a list of strings separated by \",\" or already as a list/tuple in\n which case it is returned as a list. Specs can also be `None` in which case an\n empty list is returned.\n \"\"\"\n if specs is not None and not isinstance(specs, types.ModuleType):\n if isinstance(specs, six.string_types):\n specs = specs.split(\",\") if specs else []\n if not isinstance(specs, (list, tuple)):\n raise UsageError(\n \"Plugin specs must be a ','-separated string or a \"\n \"list/tuple of strings for plugin names. Given: %r\" % specs\n )\n return list(specs)\n return []"},{"col":4,"comment":"null","endLoc":101,"header":"def add_argument(\n self,\n *name_or_flags: str,\n action: _ActionStr | type[Action] = ...,\n nargs: int | _NArgsStr | _SUPPRESS_T | None = None,\n const: Any = ...,\n default: Any = ...,\n type: _ActionType = ...,\n choices: Iterable[_T] | None = ...,\n required: bool = ...,\n help: str | None = ...,\n metavar: str | tuple[str, ...] | None = ...,\n dest: str | None = ...,\n version: str = ...,\n **kwargs: Any,\n ) -> Action","id":513,"name":"add_argument","nodeType":"Function","startLoc":86,"text":"def add_argument(\n self,\n *name_or_flags: str,\n action: _ActionStr | type[Action] = ...,\n nargs: int | _NArgsStr | _SUPPRESS_T | None = None,\n const: Any = ...,\n default: Any = ...,\n type: _ActionType = ...,\n choices: Iterable[_T] | None = ...,\n required: bool = ...,\n help: str | None = ...,\n metavar: str | tuple[str, ...] | None = ...,\n dest: str | None = ...,\n version: str = ...,\n **kwargs: Any,\n ) -> Action: ..."},{"col":4,"comment":"null","endLoc":176,"header":"@overload\n def parse_args(self, args: Sequence[str] | None = None, namespace: None = None) -> Namespace","id":514,"name":"parse_args","nodeType":"Function","startLoc":175,"text":"@overload\n def parse_args(self, args: Sequence[str] | None = None, namespace: None = None) -> Namespace: ..."},{"col":4,"comment":"null","endLoc":178,"header":"@overload\n def parse_args(self, args: Sequence[str] | None, namespace: _N) -> _N","id":515,"name":"parse_args","nodeType":"Function","startLoc":177,"text":"@overload\n def parse_args(self, args: Sequence[str] | None, namespace: _N) -> _N: ..."},{"col":4,"comment":"null","endLoc":180,"header":"@overload\n def parse_args(self, *, namespace: _N) -> _N","id":516,"name":"parse_args","nodeType":"Function","startLoc":179,"text":"@overload\n def parse_args(self, *, namespace: _N) -> _N: ..."},{"id":517,"name":"testing/example_scripts/fixtures/custom_item/foo","nodeType":"Package"},{"fileName":"__init__.py","filePath":"testing/example_scripts/fixtures/custom_item/foo","id":518,"nodeType":"File","text":""},{"id":519,"name":"release-4.0.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-4.0.0\n=======================================\n\nThe pytest team is proud to announce the 4.0.0 release!\n\npytest is a mature Python testing tool with more than a 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n https://docs.pytest.org/en/latest/changelog.html\n\nFor complete documentation, please visit:\n\n https://docs.pytest.org/en/latest/\n\nAs usual, you can upgrade from pypi via:\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n* Daniel Hahler\n* Ronny Pfannschmidt\n\n\nHappy testing,\nThe Pytest Development Team\n"},{"id":520,"name":"bench","nodeType":"Package"},{"fileName":"bench.py","filePath":"bench","id":521,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport sys\n\nif __name__ == \"__main__\":\n import cProfile\n import pytest # NOQA\n import pstats\n\n script = sys.argv[1:] if len(sys.argv) > 1 else [\"empty.py\"]\n stats = cProfile.run(\"pytest.cmdline.main(%r)\" % script, \"prof\")\n p = pstats.Stats(\"prof\")\n p.strip_dirs()\n p.sort_stats(\"cumulative\")\n print(p.print_stats(500))\n"},{"col":4,"comment":" fspath sensitive hook proxy used to call pytest hooks","endLoc":103,"header":"@property\n def ihook(self)","id":522,"name":"ihook","nodeType":"Function","startLoc":100,"text":"@property\n def ihook(self):\n \"\"\" fspath sensitive hook proxy used to call pytest hooks\"\"\"\n return self.session.gethookproxy(self.fspath)"},{"attributeType":"list","col":4,"comment":"null","endLoc":9,"id":523,"name":"script","nodeType":"Attribute","startLoc":9,"text":"script"},{"col":4,"comment":"null","endLoc":106,"header":"def __repr__(self)","id":524,"name":"__repr__","nodeType":"Function","startLoc":105,"text":"def __repr__(self):\n return \"<%s %s>\" % (self.__class__.__name__, getattr(self, \"name\", None))"},{"col":4,"comment":"Issue a warning for this item.\n\n Warnings will be displayed after the test session, unless explicitly suppressed\n\n :param Warning warning: the warning instance to issue. Must be a subclass of PytestWarning.\n\n :raise ValueError: if ``warning`` instance is not a subclass of PytestWarning.\n\n Example usage:\n\n .. code-block:: python\n\n node.warn(PytestWarning(\"some message\"))\n\n ","endLoc":138,"header":"def warn(self, warning)","id":525,"name":"warn","nodeType":"Function","startLoc":108,"text":"def warn(self, warning):\n \"\"\"Issue a warning for this item.\n\n Warnings will be displayed after the test session, unless explicitly suppressed\n\n :param Warning warning: the warning instance to issue. Must be a subclass of PytestWarning.\n\n :raise ValueError: if ``warning`` instance is not a subclass of PytestWarning.\n\n Example usage:\n\n .. code-block:: python\n\n node.warn(PytestWarning(\"some message\"))\n\n \"\"\"\n from _pytest.warning_types import PytestWarning\n\n if not isinstance(warning, PytestWarning):\n raise ValueError(\n \"warning must be an instance of PytestWarning or subclass, got {!r}\".format(\n warning\n )\n )\n path, lineno = get_fslocation_from_item(self)\n warnings.warn_explicit(\n warning,\n category=None,\n filename=str(path),\n lineno=lineno + 1 if lineno is not None else None,\n )"},{"attributeType":"None","col":4,"comment":"null","endLoc":10,"id":526,"name":"stats","nodeType":"Attribute","startLoc":10,"text":"stats"},{"col":4,"comment":"null","endLoc":1010,"header":"@overload\n def __init__(self) -> None","id":527,"name":"__init__","nodeType":"Function","startLoc":1009,"text":"@overload\n def __init__(self) -> None: ..."},{"col":4,"comment":"null","endLoc":1012,"header":"@overload\n def __init__(self, __iterable: Iterable[_T]) -> None","id":528,"name":"__init__","nodeType":"Function","startLoc":1011,"text":"@overload\n def __init__(self, __iterable: Iterable[_T]) -> None: ..."},{"col":0,"comment":"Tries to extract the actual location from an item, depending on available attributes:\n\n * \"fslocation\": a pair (path, lineno)\n * \"obj\": a Python object that the item wraps.\n * \"fspath\": just a path\n\n :rtype: a tuple of (str|LocalPath, int) with filename and line number.\n ","endLoc":307,"header":"def get_fslocation_from_item(item)","id":529,"name":"get_fslocation_from_item","nodeType":"Function","startLoc":292,"text":"def get_fslocation_from_item(item):\n \"\"\"Tries to extract the actual location from an item, depending on available attributes:\n\n * \"fslocation\": a pair (path, lineno)\n * \"obj\": a Python object that the item wraps.\n * \"fspath\": just a path\n\n :rtype: a tuple of (str|LocalPath, int) with filename and line number.\n \"\"\"\n result = getattr(item, \"location\", None)\n if result is not None:\n return result[:2]\n obj = getattr(item, \"obj\", None)\n if obj is not None:\n return getfslineno(obj)\n return getattr(item, \"fspath\", \"unknown location\"), -1"},{"col":4,"comment":"\n Imports a plugin with ``modname``. If ``consider_entry_points`` is True, entry point\n names are also considered to find a plugin.\n ","endLoc":586,"header":"def import_plugin(self, modname, consider_entry_points=False)","id":530,"name":"import_plugin","nodeType":"Function","startLoc":540,"text":"def import_plugin(self, modname, consider_entry_points=False):\n \"\"\"\n Imports a plugin with ``modname``. If ``consider_entry_points`` is True, entry point\n names are also considered to find a plugin.\n \"\"\"\n # most often modname refers to builtin modules, e.g. \"pytester\",\n # \"terminal\" or \"capture\". Those plugins are registered under their\n # basename for historic purposes but must be imported with the\n # _pytest prefix.\n assert isinstance(modname, six.string_types), (\n \"module name as text required, got %r\" % modname\n )\n modname = str(modname)\n if self.is_blocked(modname) or self.get_plugin(modname) is not None:\n return\n\n importspec = \"_pytest.\" + modname if modname in builtin_plugins else modname\n self.rewrite_hook.mark_rewrite(importspec)\n\n if consider_entry_points:\n loaded = self.load_setuptools_entrypoints(\"pytest11\", name=modname)\n if loaded:\n return\n\n try:\n __import__(importspec)\n except ImportError as e:\n new_exc_message = 'Error importing plugin \"%s\": %s' % (\n modname,\n safe_str(e.args[0]),\n )\n new_exc = ImportError(new_exc_message)\n tb = sys.exc_info()[2]\n\n six.reraise(ImportError, new_exc, tb)\n\n except Skipped as e:\n from _pytest.warnings import _issue_warning_captured\n\n _issue_warning_captured(\n PytestConfigWarning(\"skipped plugin %r: %s\" % (modname, e.msg)),\n self.hook,\n stacklevel=1,\n )\n else:\n mod = sys.modules[importspec]\n self.register(mod, modname)"},{"attributeType":"Stats","col":4,"comment":"null","endLoc":11,"id":531,"name":"p","nodeType":"Attribute","startLoc":11,"text":"p"},{"col":0,"comment":" fill missing funcargs for a test function. ","endLoc":296,"header":"def fillfixtures(function)","id":532,"name":"fillfixtures","nodeType":"Function","startLoc":277,"text":"def fillfixtures(function):\n \"\"\" fill missing funcargs for a test function. \"\"\"\n try:\n request = function._request\n except AttributeError:\n # XXX this special code path is only expected to execute\n # with the oejskit plugin. It uses classes with funcargs\n # and we thus have to work a bit to allow this.\n fm = function.session._fixturemanager\n fi = fm.getfixtureinfo(function.parent, function.obj, None)\n function._fixtureinfo = fi\n request = function._request = FixtureRequest(function)\n request._fillfixtures()\n # prune out funcargs for jstests\n newfuncargs = {}\n for name in fi.argnames:\n newfuncargs[name] = function.funcargs[name]\n function.funcargs = newfuncargs\n else:\n request._fillfixtures()"},{"col":0,"comment":"null","endLoc":328,"header":"def getfslineno(obj)","id":533,"name":"getfslineno","nodeType":"Function","startLoc":321,"text":"def getfslineno(obj):\n # xxx let decorators etc specify a sane ordering\n obj = get_real_func(obj)\n if hasattr(obj, \"place_as\"):\n obj = obj.place_as\n fslineno = _pytest._code.getfslineno(obj)\n assert isinstance(fslineno[1], int), obj\n return fslineno"},{"col":0,"comment":" return code object for given function. ","endLoc":1043,"header":"def getrawcode(obj, trycall=True)","id":534,"name":"getrawcode","nodeType":"Function","startLoc":1029,"text":"def getrawcode(obj, trycall=True):\n \"\"\" return code object for given function. \"\"\"\n try:\n return obj.__code__\n except AttributeError:\n obj = getattr(obj, \"im_func\", obj)\n obj = getattr(obj, \"func_code\", obj)\n obj = getattr(obj, \"f_code\", obj)\n obj = getattr(obj, \"__code__\", obj)\n if trycall and not hasattr(obj, \"co_firstlineno\"):\n if hasattr(obj, \"__call__\") and not inspect.isclass(obj):\n x = getrawcode(obj.__call__, trycall=False)\n if hasattr(x, \"co_firstlineno\"):\n return x\n return obj"},{"col":0,"comment":" gets the real function object of the (possibly) wrapped object by\n functools.wraps or functools.partial.\n ","endLoc":303,"header":"def get_real_func(obj)","id":535,"name":"get_real_func","nodeType":"Function","startLoc":278,"text":"def get_real_func(obj):\n \"\"\" gets the real function object of the (possibly) wrapped object by\n functools.wraps or functools.partial.\n \"\"\"\n start_obj = obj\n for i in range(100):\n # __pytest_wrapped__ is set by @pytest.fixture when wrapping the fixture function\n # to trigger a warning if it gets called directly instead of by pytest: we don't\n # want to unwrap further than this otherwise we lose useful wrappings like @mock.patch (#3774)\n new_obj = getattr(obj, \"__pytest_wrapped__\", None)\n if isinstance(new_obj, _PytestWrapper):\n obj = new_obj.obj\n break\n new_obj = getattr(obj, \"__wrapped__\", None)\n if new_obj is None:\n break\n obj = new_obj\n else:\n raise ValueError(\n (\"could not find real function of {start}\\nstopped at {current}\").format(\n start=saferepr(start_obj), current=saferepr(obj)\n )\n )\n if isinstance(obj, functools.partial):\n obj = obj.func\n return obj"},{"col":4,"comment":"null","endLoc":308,"header":"def reportinfo(self)","id":536,"name":"reportinfo","nodeType":"Function","startLoc":294,"text":"def reportinfo(self):\n # XXX caching?\n obj = self.obj\n compat_co_firstlineno = getattr(obj, \"compat_co_firstlineno\", None)\n if isinstance(compat_co_firstlineno, int):\n # nose compatibility\n fspath = sys.modules[obj.__module__].__file__\n if fspath.endswith(\".pyc\"):\n fspath = fspath[:-1]\n lineno = compat_co_firstlineno\n else:\n fspath, lineno = getfslineno(obj)\n modpath = self.getmodpath()\n assert isinstance(lineno, int)\n return fspath, lineno, modpath"},{"col":4,"comment":"returns v as string, converting to utf-8 if necessary","endLoc":387,"header":"def safe_str(v)","id":537,"name":"safe_str","nodeType":"Function","startLoc":379,"text":"def safe_str(v):\n \"\"\"returns v as string, converting to utf-8 if necessary\"\"\"\n try:\n return str(v)\n except UnicodeError:\n if not isinstance(v, text_type):\n v = text_type(v)\n errors = \"replace\"\n return v.encode(\"utf-8\", errors)"},{"attributeType":"null","col":4,"comment":"null","endLoc":249,"id":538,"name":"_ALLOW_MARKERS","nodeType":"Attribute","startLoc":249,"text":"_ALLOW_MARKERS"},{"attributeType":"null","col":12,"comment":"null","endLoc":259,"id":539,"name":"_obj","nodeType":"Attribute","startLoc":259,"text":"self._obj"},{"col":4,"comment":"null","endLoc":313,"header":"def funcnamefilter(self, name)","id":540,"name":"funcnamefilter","nodeType":"Function","startLoc":312,"text":"def funcnamefilter(self, name):\n return self._matches_prefix_or_glob_option(\"python_functions\", name)"},{"col":4,"comment":"\n checks if the given name matches the prefix or glob-pattern defined\n in ini configuration.\n ","endLoc":357,"header":"def _matches_prefix_or_glob_option(self, option_name, name)","id":541,"name":"_matches_prefix_or_glob_option","nodeType":"Function","startLoc":342,"text":"def _matches_prefix_or_glob_option(self, option_name, name):\n \"\"\"\n checks if the given name matches the prefix or glob-pattern defined\n in ini configuration.\n \"\"\"\n for option in self.config.getini(option_name):\n if name.startswith(option):\n return True\n # check that name looks like a glob-string before calling fnmatch\n # because this is called for every name in each collected module,\n # and fnmatch is somewhat expensive to call\n elif (\"*\" in option or \"?\" in option or \"[\" in option) and fnmatch.fnmatch(\n name, option\n ):\n return True\n return False"},{"col":0,"comment":"","endLoc":2,"header":"bench.py#","id":542,"name":"","nodeType":"Function","startLoc":2,"text":"if __name__ == \"__main__\":\n import cProfile\n import pytest # NOQA\n import pstats\n\n script = sys.argv[1:] if len(sys.argv) > 1 else [\"empty.py\"]\n stats = cProfile.run(\"pytest.cmdline.main(%r)\" % script, \"prof\")\n p = pstats.Stats(\"prof\")\n p.strip_dirs()\n p.sort_stats(\"cumulative\")\n print(p.print_stats(500))"},{"col":0,"comment":"null","endLoc":6,"header":"def fnmatch(name: AnyStr, pat: AnyStr) -> bool","id":545,"name":"fnmatch","nodeType":"Function","startLoc":6,"text":"def fnmatch(name: AnyStr, pat: AnyStr) -> bool: ..."},{"col":4,"comment":" Look for the __test__ attribute, which is applied by the\n @nose.tools.istest decorator\n ","endLoc":322,"header":"def isnosetest(self, obj)","id":546,"name":"isnosetest","nodeType":"Function","startLoc":315,"text":"def isnosetest(self, obj):\n \"\"\" Look for the __test__ attribute, which is applied by the\n @nose.tools.istest decorator\n \"\"\"\n # We explicitly check for \"is True\" here to not mistakenly treat\n # classes with a custom __getattr__ returning something truthy (like a\n # function) as test classes.\n return safe_getattr(obj, \"__test__\", False) is True"},{"col":0,"comment":" Like getattr but return default upon any Exception or any OutcomeException.\n\n Attribute access can potentially fail for 'evil' Python objects.\n See issue #214.\n It catches OutcomeException because of #2490 (issue #580), new outcomes are derived from BaseException\n instead of Exception (for more details check #2707)\n ","endLoc":349,"header":"def safe_getattr(object, name, default)","id":547,"name":"safe_getattr","nodeType":"Function","startLoc":338,"text":"def safe_getattr(object, name, default):\n \"\"\" Like getattr but return default upon any Exception or any OutcomeException.\n\n Attribute access can potentially fail for 'evil' Python objects.\n See issue #214.\n It catches OutcomeException because of #2490 (issue #580), new outcomes are derived from BaseException\n instead of Exception (for more details check #2707)\n \"\"\"\n try:\n return getattr(object, name, default)\n except TEST_OUTCOME:\n return default"},{"col":4,"comment":"null","endLoc":325,"header":"def classnamefilter(self, name)","id":549,"name":"classnamefilter","nodeType":"Function","startLoc":324,"text":"def classnamefilter(self, name):\n return self._matches_prefix_or_glob_option(\"python_classes\", name)"},{"col":4,"comment":"null","endLoc":337,"header":"def istestfunction(self, obj, name)","id":550,"name":"istestfunction","nodeType":"Function","startLoc":327,"text":"def istestfunction(self, obj, name):\n if self.funcnamefilter(name) or self.isnosetest(obj):\n if isinstance(obj, staticmethod):\n # static methods need to be unwrapped\n obj = safe_getattr(obj, \"__func__\", False)\n return (\n safe_getattr(obj, \"__call__\", False)\n and fixtures.getfixturemarker(obj) is None\n )\n else:\n return False"},{"col":8,"comment":"null","endLoc":105,"header":"@overload\n def __init__(self: catch_warnings[None], *, record: Literal[False] = False, module: ModuleType | None = None) -> None","id":553,"name":"__init__","nodeType":"Function","startLoc":104,"text":"@overload\n def __init__(self: catch_warnings[None], *, record: Literal[False] = False, module: ModuleType | None = None) -> None: ..."},{"col":0,"comment":" return fixturemarker or None if it doesn't exist or raised\n exceptions.","endLoc":180,"header":"def getfixturemarker(obj)","id":554,"name":"getfixturemarker","nodeType":"Function","startLoc":172,"text":"def getfixturemarker(obj):\n \"\"\" return fixturemarker or None if it doesn't exist or raised\n exceptions.\"\"\"\n try:\n return getattr(obj, \"_pytestfixturefunction\", None)\n except TEST_OUTCOME:\n # some objects raise errors like request (from flask import request)\n # we don't expect them to be fixture functions\n return None"},{"col":4,"comment":"null","endLoc":360,"header":"def __init__(self, pyfuncitem)","id":555,"name":"__init__","nodeType":"Function","startLoc":350,"text":"def __init__(self, pyfuncitem):\n self._pyfuncitem = pyfuncitem\n #: fixture for which this request is being performed\n self.fixturename = None\n #: Scope string, one of \"function\", \"class\", \"module\", \"session\"\n self.scope = \"function\"\n self._fixture_defs = {} # argname -> FixtureDef\n fixtureinfo = pyfuncitem._fixtureinfo\n self._arg2fixturedefs = fixtureinfo.name2fixturedefs.copy()\n self._arg2index = {}\n self._fixturemanager = pyfuncitem.session._fixturemanager"},{"col":8,"comment":"null","endLoc":109,"header":"@overload\n def __init__(\n self: catch_warnings[list[WarningMessage]], *, record: Literal[True], module: ModuleType | None = None\n ) -> None","id":556,"name":"__init__","nodeType":"Function","startLoc":106,"text":"@overload\n def __init__(\n self: catch_warnings[list[WarningMessage]], *, record: Literal[True], module: ModuleType | None = None\n ) -> None: ..."},{"col":8,"comment":"null","endLoc":113,"header":"@overload\n def __init__(\n self: catch_warnings[list[WarningMessage] | None], *, record: bool, module: ModuleType | None = None\n ) -> None","id":557,"name":"__init__","nodeType":"Function","startLoc":110,"text":"@overload\n def __init__(\n self: catch_warnings[list[WarningMessage] | None], *, record: bool, module: ModuleType | None = None\n ) -> None: ..."},{"col":4,"comment":"returns v as string","endLoc":374,"header":"def safe_str(v)","id":565,"name":"safe_str","nodeType":"Function","startLoc":372,"text":"def safe_str(v):\n \"\"\"returns v as string\"\"\"\n return str(v)"},{"col":4,"comment":"null","endLoc":340,"header":"def istestclass(self, obj, name)","id":566,"name":"istestclass","nodeType":"Function","startLoc":339,"text":"def istestclass(self, obj, name):\n return self.classnamefilter(name) or self.isnosetest(obj)"},{"col":0,"comment":"null","endLoc":263,"header":"def deindent(lines)","id":567,"name":"deindent","nodeType":"Function","startLoc":262,"text":"def deindent(lines):\n return textwrap.dedent(\"\\n\".join(lines)).splitlines()"},{"col":0,"comment":"Decorator to mark a fixture factory function.\n\n This decorator can be used, with or without parameters, to define a\n fixture function.\n\n The name of the fixture function can later be referenced to cause its\n invocation ahead of running tests: test\n modules or classes can use the ``pytest.mark.usefixtures(fixturename)``\n marker.\n\n Test functions can directly use fixture names as input\n arguments in which case the fixture instance returned from the fixture\n function will be injected.\n\n Fixtures can provide their values to test functions using ``return`` or ``yield``\n statements. When using ``yield`` the code block after the ``yield`` statement is executed\n as teardown code regardless of the test outcome, and must yield exactly once.\n\n :arg scope: the scope for which this fixture is shared, one of\n ``\"function\"`` (default), ``\"class\"``, ``\"module\"``,\n ``\"package\"`` or ``\"session\"``.\n\n ``\"package\"`` is considered **experimental** at this time.\n\n :arg params: an optional list of parameters which will cause multiple\n invocations of the fixture function and all of the tests\n using it.\n The current parameter is available in ``request.param``.\n\n :arg autouse: if True, the fixture func is activated for all tests that\n can see it. If False (the default) then an explicit\n reference is needed to activate the fixture.\n\n :arg ids: list of string ids each corresponding to the params\n so that they are part of the test id. If no ids are provided\n they will be generated automatically from the params.\n\n :arg name: the name of the fixture. This defaults to the name of the\n decorated function. If a fixture is used in the same module in\n which it is defined, the function name of the fixture will be\n shadowed by the function arg that requests the fixture; one way\n to resolve this is to name the decorated function\n ``fixture_`` and then use\n ``@pytest.fixture(name='')``.\n ","endLoc":1048,"header":"def fixture(scope=\"function\", params=None, autouse=False, ids=None, name=None)","id":568,"name":"fixture","nodeType":"Function","startLoc":997,"text":"def fixture(scope=\"function\", params=None, autouse=False, ids=None, name=None):\n \"\"\"Decorator to mark a fixture factory function.\n\n This decorator can be used, with or without parameters, to define a\n fixture function.\n\n The name of the fixture function can later be referenced to cause its\n invocation ahead of running tests: test\n modules or classes can use the ``pytest.mark.usefixtures(fixturename)``\n marker.\n\n Test functions can directly use fixture names as input\n arguments in which case the fixture instance returned from the fixture\n function will be injected.\n\n Fixtures can provide their values to test functions using ``return`` or ``yield``\n statements. When using ``yield`` the code block after the ``yield`` statement is executed\n as teardown code regardless of the test outcome, and must yield exactly once.\n\n :arg scope: the scope for which this fixture is shared, one of\n ``\"function\"`` (default), ``\"class\"``, ``\"module\"``,\n ``\"package\"`` or ``\"session\"``.\n\n ``\"package\"`` is considered **experimental** at this time.\n\n :arg params: an optional list of parameters which will cause multiple\n invocations of the fixture function and all of the tests\n using it.\n The current parameter is available in ``request.param``.\n\n :arg autouse: if True, the fixture func is activated for all tests that\n can see it. If False (the default) then an explicit\n reference is needed to activate the fixture.\n\n :arg ids: list of string ids each corresponding to the params\n so that they are part of the test id. If no ids are provided\n they will be generated automatically from the params.\n\n :arg name: the name of the fixture. This defaults to the name of the\n decorated function. If a fixture is used in the same module in\n which it is defined, the function name of the fixture will be\n shadowed by the function arg that requests the fixture; one way\n to resolve this is to name the decorated function\n ``fixture_`` and then use\n ``@pytest.fixture(name='')``.\n \"\"\"\n if callable(scope) and params is None and autouse is False:\n # direct decoration\n return FixtureFunctionMarker(\"function\", params, autouse, name=name)(scope)\n if params is not None and not isinstance(params, (list, tuple)):\n params = list(params)\n return FixtureFunctionMarker(scope, params, autouse, ids=ids, name=name)"},{"col":4,"comment":"null","endLoc":382,"header":"def collect(self)","id":569,"name":"collect","nodeType":"Function","startLoc":359,"text":"def collect(self):\n if not getattr(self.obj, \"__test__\", True):\n return []\n\n # NB. we avoid random getattrs and peek in the __dict__ instead\n # (XXX originally introduced from a PyPy need, still true?)\n dicts = [getattr(self.obj, \"__dict__\", {})]\n for basecls in inspect.getmro(self.obj.__class__):\n dicts.append(basecls.__dict__)\n seen = {}\n values = []\n for dic in dicts:\n for name, obj in list(dic.items()):\n if name in seen:\n continue\n seen[name] = True\n res = self._makeitem(name, obj)\n if res is None:\n continue\n if not isinstance(res, list):\n res = [res]\n values.extend(res)\n values.sort(key=lambda item: item.reportinfo()[:2])\n return values"},{"col":0,"comment":"null","endLoc":102,"header":"def dedent(text: str) -> str","id":571,"name":"dedent","nodeType":"Function","startLoc":102,"text":"def dedent(text: str) -> str: ..."},{"col":4,"comment":"null","endLoc":1222,"header":"@overload\n def __new__(cls, __stop: SupportsIndex) -> Self","id":572,"name":"__new__","nodeType":"Function","startLoc":1221,"text":"@overload\n def __new__(cls, __stop: SupportsIndex) -> Self: ..."},{"col":4,"comment":"null","endLoc":1224,"header":"@overload\n def __new__(cls, __start: SupportsIndex, __stop: SupportsIndex, __step: SupportsIndex = ...) -> Self","id":573,"name":"__new__","nodeType":"Function","startLoc":1223,"text":"@overload\n def __new__(cls, __start: SupportsIndex, __stop: SupportsIndex, __step: SupportsIndex = ...) -> Self: ..."},{"attributeType":"(OutcomeException, Exception)","col":0,"comment":"null","endLoc":36,"id":575,"name":"TEST_OUTCOME","nodeType":"Attribute","startLoc":36,"text":"TEST_OUTCOME"},{"col":4,"comment":" return compiled code object. if filename is None\n invent an artificial filename which displays\n the source/line position of the caller frame.\n ","endLoc":182,"header":"def compile(\n self, filename=None, mode=\"exec\", flag=0, dont_inherit=0, _genframe=None\n )","id":576,"name":"compile","nodeType":"Function","startLoc":145,"text":"def compile(\n self, filename=None, mode=\"exec\", flag=0, dont_inherit=0, _genframe=None\n ):\n \"\"\" return compiled code object. if filename is None\n invent an artificial filename which displays\n the source/line position of the caller frame.\n \"\"\"\n if not filename or py.path.local(filename).check(file=0):\n if _genframe is None:\n _genframe = sys._getframe(1) # the caller\n fn, lineno = _genframe.f_code.co_filename, _genframe.f_lineno\n base = \"<%d-codegen \" % self._compilecounter\n self.__class__._compilecounter += 1\n if not filename:\n filename = base + \"%s:%d>\" % (fn, lineno)\n else:\n filename = base + \"%r %s:%d>\" % (filename, fn, lineno)\n source = \"\\n\".join(self.lines) + \"\\n\"\n try:\n co = compile(source, filename, mode, flag)\n except SyntaxError:\n ex = sys.exc_info()[1]\n # re-represent syntax errors from parsing python strings\n msglines = self.lines[: ex.lineno]\n if ex.offset:\n msglines.append(\" \" * ex.offset + \"^\")\n msglines.append(\"(code was compiled probably from here: %s)\" % filename)\n newex = SyntaxError(\"\\n\".join(msglines))\n newex.offset = ex.offset\n newex.lineno = ex.lineno\n newex.text = ex.text\n raise newex\n else:\n if flag & _AST_FLAG:\n return co\n lines = [(x + \"\\n\") for x in self.lines]\n linecache.cache[filename] = (1, None, lines, filename)\n return co"},{"id":578,"name":"testing/io","nodeType":"Package"},{"fileName":"test_saferepr.py","filePath":"testing/io","id":579,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom _pytest._io.saferepr import saferepr\n\n\ndef test_simple_repr():\n assert saferepr(1) == \"1\"\n assert saferepr(None) == \"None\"\n\n\ndef test_maxsize():\n s = saferepr(\"x\" * 50, maxsize=25)\n assert len(s) == 25\n expected = repr(\"x\" * 10 + \"...\" + \"x\" * 10)\n assert s == expected\n\n\ndef test_maxsize_error_on_instance():\n class A:\n def __repr__():\n raise ValueError(\"...\")\n\n s = saferepr((\"*\" * 50, A()), maxsize=25)\n assert len(s) == 25\n assert s[0] == \"(\" and s[-1] == \")\"\n\n\ndef test_exceptions():\n class BrokenRepr:\n def __init__(self, ex):\n self.ex = ex\n\n def __repr__(self):\n raise self.ex\n\n class BrokenReprException(Exception):\n __str__ = None\n __repr__ = None\n\n assert \"Exception\" in saferepr(BrokenRepr(Exception(\"broken\")))\n s = saferepr(BrokenReprException(\"really broken\"))\n assert \"TypeError\" in s\n assert \"TypeError\" in saferepr(BrokenRepr(\"string\"))\n\n s2 = saferepr(BrokenRepr(BrokenReprException(\"omg even worse\")))\n assert \"NameError\" not in s2\n assert \"unknown\" in s2\n\n\ndef test_big_repr():\n from _pytest._io.saferepr import SafeRepr\n\n assert len(saferepr(range(1000))) <= len(\"[\" + SafeRepr().maxlist * \"1000\" + \"]\")\n\n\ndef test_repr_on_newstyle():\n class Function(object):\n def __repr__(self):\n return \"<%s>\" % (self.name)\n\n assert saferepr(Function())\n\n\ndef test_unicode():\n val = u\"£€\"\n reprval = u\"'£€'\"\n assert saferepr(val) == reprval\n"},{"col":4,"comment":"null","endLoc":994,"header":"def __call__(self, function)","id":580,"name":"__call__","nodeType":"Function","startLoc":979,"text":"def __call__(self, function):\n if isclass(function):\n raise ValueError(\"class fixtures not supported (maybe in the future)\")\n\n if getattr(function, \"_pytestfixturefunction\", False):\n raise ValueError(\n \"fixture is being applied more than once to the same function\"\n )\n\n function = wrap_function_to_error_out_if_called_directly(function, self)\n\n name = self.name or function.__name__\n if name == \"request\":\n warnings.warn(FIXTURE_NAMED_REQUEST)\n function._pytestfixturefunction = self\n return function"},{"col":0,"comment":"","endLoc":5,"header":"outcomes.py#","id":581,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"\nexception classes and constants handling test outcomes\nas well as functions creating them\n\"\"\"\n\nTEST_OUTCOME = (OutcomeException, Exception)\n\nexit.Exception = Exit\n\nskip.Exception = Skipped\n\nfail.Exception = Failed\n\nxfail.Exception = XFailed"},{"col":0,"comment":"return a size-limited safe repr-string for the given object.\n Failing __repr__ functions of user instances will be represented\n with a short exception info and 'saferepr' generally takes\n care to never raise exceptions itself. This function is a wrapper\n around the Repr/reprlib functionality of the standard 2.6 lib.\n ","endLoc":83,"header":"def saferepr(obj, maxsize=240)","id":582,"name":"saferepr","nodeType":"Function","startLoc":71,"text":"def saferepr(obj, maxsize=240):\n \"\"\"return a size-limited safe repr-string for the given object.\n Failing __repr__ functions of user instances will be represented\n with a short exception info and 'saferepr' generally takes\n care to never raise exceptions itself. This function is a wrapper\n around the Repr/reprlib functionality of the standard 2.6 lib.\n \"\"\"\n # review exception handling\n srepr = SafeRepr()\n srepr.maxstring = maxsize\n srepr.maxsize = maxsize\n srepr.maxother = 160\n return srepr.repr(obj)"},{"id":585,"name":"testing/example_scripts/fixtures/fill_fixtures/test_extend_fixture_conftest_conftest/pkg","nodeType":"Package"},{"fileName":"conftest.py","filePath":"testing/example_scripts/fixtures/fill_fixtures/test_extend_fixture_conftest_conftest/pkg","id":586,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\n@pytest.fixture\ndef spam(spam):\n return spam * 2\n"},{"col":0,"comment":"null","endLoc":7,"header":"@pytest.fixture\ndef spam(spam)","id":587,"name":"spam","nodeType":"Function","startLoc":5,"text":"@pytest.fixture\ndef spam(spam):\n return spam * 2"},{"col":4,"comment":"null","endLoc":1014,"header":"def append(self, __object: _T) -> None","id":588,"name":"append","nodeType":"Function","startLoc":1014,"text":"def append(self, __object: _T) -> None: ..."},{"col":0,"comment":"Wrap the given fixture function so we can raise an error about it being called directly,\n instead of used as an argument in a test function.\n ","endLoc":968,"header":"def wrap_function_to_error_out_if_called_directly(function, fixture_marker)","id":592,"name":"wrap_function_to_error_out_if_called_directly","nodeType":"Function","startLoc":952,"text":"def wrap_function_to_error_out_if_called_directly(function, fixture_marker):\n \"\"\"Wrap the given fixture function so we can raise an error about it being called directly,\n instead of used as an argument in a test function.\n \"\"\"\n message = FIXTURE_FUNCTION_CALL.format(\n name=fixture_marker.name or function.__name__\n )\n\n @six.wraps(function)\n def result(*args, **kwargs):\n fail(message, pytrace=False)\n\n # keep reference to the original function in our own custom attribute so we don't unwrap\n # further than this point and lose useful wrappings like @mock.patch (#3774)\n result.__pytest_wrapped__ = _PytestWrapper(function)\n\n return result"},{"col":0,"comment":"null","endLoc":59,"header":"def convert_rst_to_md(text)","id":593,"name":"convert_rst_to_md","nodeType":"Function","startLoc":58,"text":"def convert_rst_to_md(text):\n return pypandoc.convert_text(text, \"md\", format=\"rst\")"},{"col":0,"comment":"null","endLoc":92,"header":"def main(argv)","id":594,"name":"main","nodeType":"Function","startLoc":62,"text":"def main(argv):\n if len(argv) > 1:\n tag_name = argv[1]\n else:\n tag_name = os.environ.get(\"TRAVIS_TAG\")\n if not tag_name:\n print(\"tag_name not given and $TRAVIS_TAG not set\", file=sys.stderr)\n return 1\n\n token = os.environ.get(\"GH_RELEASE_NOTES_TOKEN\")\n if not token:\n print(\"GH_RELEASE_NOTES_TOKEN not set\", file=sys.stderr)\n return 1\n\n slug = os.environ.get(\"TRAVIS_REPO_SLUG\")\n if not slug:\n print(\"TRAVIS_REPO_SLUG not set\", file=sys.stderr)\n return 1\n\n rst_body = parse_changelog(tag_name)\n md_body = convert_rst_to_md(rst_body)\n if not publish_github_release(slug, token, tag_name, md_body):\n print(\"Could not publish release notes:\", file=sys.stderr)\n print(md_body, file=sys.stderr)\n return 5\n\n print()\n print(f\"Release notes for {tag_name} published successfully:\")\n print(f\"https://github.com/{slug}/releases/tag/{tag_name}\")\n print()\n return 0"},{"col":0,"comment":"null","endLoc":7,"header":"def test_simple_repr()","id":595,"name":"test_simple_repr","nodeType":"Function","startLoc":5,"text":"def test_simple_repr():\n assert saferepr(1) == \"1\"\n assert saferepr(None) == \"None\""},{"col":4,"comment":"returns an ExceptionInfo matching the current traceback\n\n .. warning::\n\n Experimental API\n\n\n :param exprinfo: a text string helping to determine if we should\n strip ``AssertionError`` from the output, defaults\n to the exception message/``__str__()``\n ","endLoc":425,"header":"@classmethod\n def from_current(cls, exprinfo=None)","id":596,"name":"from_current","nodeType":"Function","startLoc":402,"text":"@classmethod\n def from_current(cls, exprinfo=None):\n \"\"\"returns an ExceptionInfo matching the current traceback\n\n .. warning::\n\n Experimental API\n\n\n :param exprinfo: a text string helping to determine if we should\n strip ``AssertionError`` from the output, defaults\n to the exception message/``__str__()``\n \"\"\"\n tup = sys.exc_info()\n assert tup[0] is not None, \"no current exception\"\n _striptext = \"\"\n if exprinfo is None and isinstance(tup[1], AssertionError):\n exprinfo = getattr(tup[1], \"msg\", None)\n if exprinfo is None:\n exprinfo = saferepr(tup[1])\n if exprinfo and exprinfo.startswith(cls._assert_start_repr):\n _striptext = \"AssertionError: \"\n\n return cls(tup, _striptext)"},{"col":0,"comment":"null","endLoc":14,"header":"def test_maxsize()","id":597,"name":"test_maxsize","nodeType":"Function","startLoc":10,"text":"def test_maxsize():\n s = saferepr(\"x\" * 50, maxsize=25)\n assert len(s) == 25\n expected = repr(\"x\" * 10 + \"...\" + \"x\" * 10)\n assert s == expected"},{"col":4,"comment":"null","endLoc":120,"header":"def wraps(\n wrapped: Callable[_PWrapped, _RWrapped],\n assigned: Sequence[str] = (\"__module__\", \"__name__\", \"__qualname__\", \"__doc__\", \"__annotations__\"),\n updated","id":598,"name":"wraps","nodeType":"Function","startLoc":116,"text":"def wraps(\n wrapped: Callable[_PWrapped, _RWrapped],\n assigned: Sequence[str] = (\"__module__\", \"__name__\", \"__qualname__\", \"__doc__\", \"__annotations__\"),\n updated: Sequence[str] = (\"__dict__\",),\n ) -> _Wrapper[_PWrapped, _RWrapped]: ..."},{"fileName":"approx.py","filePath":"testing/python","id":599,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport doctest\nimport operator\nimport sys\nfrom decimal import Decimal\nfrom fractions import Fraction\nfrom operator import eq\nfrom operator import ne\n\nimport pytest\nfrom pytest import approx\n\ninf, nan = float(\"inf\"), float(\"nan\")\n\n\nclass MyDocTestRunner(doctest.DocTestRunner):\n def __init__(self):\n doctest.DocTestRunner.__init__(self)\n\n def report_failure(self, out, test, example, got):\n raise AssertionError(\n \"'{}' evaluates to '{}', not '{}'\".format(\n example.source.strip(), got.strip(), example.want.strip()\n )\n )\n\n\nclass TestApprox(object):\n @pytest.fixture\n def plus_minus(self):\n return u\"\\u00b1\" if sys.version_info[0] > 2 else u\"+-\"\n\n def test_repr_string(self, plus_minus):\n tol1, tol2, infr = \"1.0e-06\", \"2.0e-06\", \"inf\"\n assert repr(approx(1.0)) == \"1.0 {pm} {tol1}\".format(pm=plus_minus, tol1=tol1)\n assert repr(\n approx([1.0, 2.0])\n ) == \"approx([1.0 {pm} {tol1}, 2.0 {pm} {tol2}])\".format(\n pm=plus_minus, tol1=tol1, tol2=tol2\n )\n assert repr(\n approx((1.0, 2.0))\n ) == \"approx((1.0 {pm} {tol1}, 2.0 {pm} {tol2}))\".format(\n pm=plus_minus, tol1=tol1, tol2=tol2\n )\n assert repr(approx(inf)) == \"inf\"\n assert repr(approx(1.0, rel=nan)) == \"1.0 {pm} ???\".format(pm=plus_minus)\n assert repr(approx(1.0, rel=inf)) == \"1.0 {pm} {infr}\".format(\n pm=plus_minus, infr=infr\n )\n assert repr(approx(1.0j, rel=inf)) == \"1j\"\n\n # Dictionaries aren't ordered, so we need to check both orders.\n assert repr(approx({\"a\": 1.0, \"b\": 2.0})) in (\n \"approx({{'a': 1.0 {pm} {tol1}, 'b': 2.0 {pm} {tol2}}})\".format(\n pm=plus_minus, tol1=tol1, tol2=tol2\n ),\n \"approx({{'b': 2.0 {pm} {tol2}, 'a': 1.0 {pm} {tol1}}})\".format(\n pm=plus_minus, tol1=tol1, tol2=tol2\n ),\n )\n\n @pytest.mark.parametrize(\n \"value, repr_string\",\n [\n (5.0, \"approx(5.0 {pm} 5.0e-06)\"),\n ([5.0], \"approx([5.0 {pm} 5.0e-06])\"),\n ([[5.0]], \"approx([[5.0 {pm} 5.0e-06]])\"),\n ([[5.0, 6.0]], \"approx([[5.0 {pm} 5.0e-06, 6.0 {pm} 6.0e-06]])\"),\n ([[5.0], [6.0]], \"approx([[5.0 {pm} 5.0e-06], [6.0 {pm} 6.0e-06]])\"),\n ],\n )\n def test_repr_nd_array(self, plus_minus, value, repr_string):\n \"\"\"Make sure that arrays of all different dimensions are repr'd correctly.\"\"\"\n np = pytest.importorskip(\"numpy\")\n np_array = np.array(value)\n assert repr(approx(np_array)) == repr_string.format(pm=plus_minus)\n\n def test_operator_overloading(self):\n assert 1 == approx(1, rel=1e-6, abs=1e-12)\n assert not (1 != approx(1, rel=1e-6, abs=1e-12))\n assert 10 != approx(1, rel=1e-6, abs=1e-12)\n assert not (10 == approx(1, rel=1e-6, abs=1e-12))\n\n def test_exactly_equal(self):\n examples = [\n (2.0, 2.0),\n (0.1e200, 0.1e200),\n (1.123e-300, 1.123e-300),\n (12345, 12345.0),\n (0.0, -0.0),\n (345678, 345678),\n (Decimal(\"1.0001\"), Decimal(\"1.0001\")),\n (Fraction(1, 3), Fraction(-1, -3)),\n ]\n for a, x in examples:\n assert a == approx(x)\n\n def test_opposite_sign(self):\n examples = [(eq, 1e-100, -1e-100), (ne, 1e100, -1e100)]\n for op, a, x in examples:\n assert op(a, approx(x))\n\n def test_zero_tolerance(self):\n within_1e10 = [(1.1e-100, 1e-100), (-1.1e-100, -1e-100)]\n for a, x in within_1e10:\n assert x == approx(x, rel=0.0, abs=0.0)\n assert a != approx(x, rel=0.0, abs=0.0)\n assert a == approx(x, rel=0.0, abs=5e-101)\n assert a != approx(x, rel=0.0, abs=5e-102)\n assert a == approx(x, rel=5e-1, abs=0.0)\n assert a != approx(x, rel=5e-2, abs=0.0)\n\n def test_negative_tolerance(self):\n # Negative tolerances are not allowed.\n illegal_kwargs = [\n dict(rel=-1e100),\n dict(abs=-1e100),\n dict(rel=1e100, abs=-1e100),\n dict(rel=-1e100, abs=1e100),\n dict(rel=-1e100, abs=-1e100),\n ]\n for kwargs in illegal_kwargs:\n with pytest.raises(ValueError):\n 1.1 == approx(1, **kwargs)\n\n def test_inf_tolerance(self):\n # Everything should be equal if the tolerance is infinite.\n large_diffs = [(1, 1000), (1e-50, 1e50), (-1.0, -1e300), (0.0, 10)]\n for a, x in large_diffs:\n assert a != approx(x, rel=0.0, abs=0.0)\n assert a == approx(x, rel=inf, abs=0.0)\n assert a == approx(x, rel=0.0, abs=inf)\n assert a == approx(x, rel=inf, abs=inf)\n\n def test_inf_tolerance_expecting_zero(self):\n # If the relative tolerance is zero but the expected value is infinite,\n # the actual tolerance is a NaN, which should be an error.\n illegal_kwargs = [dict(rel=inf, abs=0.0), dict(rel=inf, abs=inf)]\n for kwargs in illegal_kwargs:\n with pytest.raises(ValueError):\n 1 == approx(0, **kwargs)\n\n def test_nan_tolerance(self):\n illegal_kwargs = [dict(rel=nan), dict(abs=nan), dict(rel=nan, abs=nan)]\n for kwargs in illegal_kwargs:\n with pytest.raises(ValueError):\n 1.1 == approx(1, **kwargs)\n\n def test_reasonable_defaults(self):\n # Whatever the defaults are, they should work for numbers close to 1\n # than have a small amount of floating-point error.\n assert 0.1 + 0.2 == approx(0.3)\n\n def test_default_tolerances(self):\n # This tests the defaults as they are currently set. If you change the\n # defaults, this test will fail but you should feel free to change it.\n # None of the other tests (except the doctests) should be affected by\n # the choice of defaults.\n examples = [\n # Relative tolerance used.\n (eq, 1e100 + 1e94, 1e100),\n (ne, 1e100 + 2e94, 1e100),\n (eq, 1e0 + 1e-6, 1e0),\n (ne, 1e0 + 2e-6, 1e0),\n # Absolute tolerance used.\n (eq, 1e-100, +1e-106),\n (eq, 1e-100, +2e-106),\n (eq, 1e-100, 0),\n ]\n for op, a, x in examples:\n assert op(a, approx(x))\n\n def test_custom_tolerances(self):\n assert 1e8 + 1e0 == approx(1e8, rel=5e-8, abs=5e0)\n assert 1e8 + 1e0 == approx(1e8, rel=5e-9, abs=5e0)\n assert 1e8 + 1e0 == approx(1e8, rel=5e-8, abs=5e-1)\n assert 1e8 + 1e0 != approx(1e8, rel=5e-9, abs=5e-1)\n\n assert 1e0 + 1e-8 == approx(1e0, rel=5e-8, abs=5e-8)\n assert 1e0 + 1e-8 == approx(1e0, rel=5e-9, abs=5e-8)\n assert 1e0 + 1e-8 == approx(1e0, rel=5e-8, abs=5e-9)\n assert 1e0 + 1e-8 != approx(1e0, rel=5e-9, abs=5e-9)\n\n assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-8, abs=5e-16)\n assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-9, abs=5e-16)\n assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-8, abs=5e-17)\n assert 1e-8 + 1e-16 != approx(1e-8, rel=5e-9, abs=5e-17)\n\n def test_relative_tolerance(self):\n within_1e8_rel = [(1e8 + 1e0, 1e8), (1e0 + 1e-8, 1e0), (1e-8 + 1e-16, 1e-8)]\n for a, x in within_1e8_rel:\n assert a == approx(x, rel=5e-8, abs=0.0)\n assert a != approx(x, rel=5e-9, abs=0.0)\n\n def test_absolute_tolerance(self):\n within_1e8_abs = [(1e8 + 9e-9, 1e8), (1e0 + 9e-9, 1e0), (1e-8 + 9e-9, 1e-8)]\n for a, x in within_1e8_abs:\n assert a == approx(x, rel=0, abs=5e-8)\n assert a != approx(x, rel=0, abs=5e-9)\n\n def test_expecting_zero(self):\n examples = [\n (ne, 1e-6, 0.0),\n (ne, -1e-6, 0.0),\n (eq, 1e-12, 0.0),\n (eq, -1e-12, 0.0),\n (ne, 2e-12, 0.0),\n (ne, -2e-12, 0.0),\n (ne, inf, 0.0),\n (ne, nan, 0.0),\n ]\n for op, a, x in examples:\n assert op(a, approx(x, rel=0.0, abs=1e-12))\n assert op(a, approx(x, rel=1e-6, abs=1e-12))\n\n def test_expecting_inf(self):\n examples = [\n (eq, inf, inf),\n (eq, -inf, -inf),\n (ne, inf, -inf),\n (ne, 0.0, inf),\n (ne, nan, inf),\n ]\n for op, a, x in examples:\n assert op(a, approx(x))\n\n def test_expecting_nan(self):\n examples = [\n (eq, nan, nan),\n (eq, -nan, -nan),\n (eq, nan, -nan),\n (ne, 0.0, nan),\n (ne, inf, nan),\n ]\n for op, a, x in examples:\n # Nothing is equal to NaN by default.\n assert a != approx(x)\n\n # If ``nan_ok=True``, then NaN is equal to NaN.\n assert op(a, approx(x, nan_ok=True))\n\n def test_int(self):\n within_1e6 = [(1000001, 1000000), (-1000001, -1000000)]\n for a, x in within_1e6:\n assert a == approx(x, rel=5e-6, abs=0)\n assert a != approx(x, rel=5e-7, abs=0)\n assert approx(x, rel=5e-6, abs=0) == a\n assert approx(x, rel=5e-7, abs=0) != a\n\n def test_decimal(self):\n within_1e6 = [\n (Decimal(\"1.000001\"), Decimal(\"1.0\")),\n (Decimal(\"-1.000001\"), Decimal(\"-1.0\")),\n ]\n for a, x in within_1e6:\n assert a == approx(x)\n assert a == approx(x, rel=Decimal(\"5e-6\"), abs=0)\n assert a != approx(x, rel=Decimal(\"5e-7\"), abs=0)\n assert approx(x, rel=Decimal(\"5e-6\"), abs=0) == a\n assert approx(x, rel=Decimal(\"5e-7\"), abs=0) != a\n\n def test_fraction(self):\n within_1e6 = [\n (1 + Fraction(1, 1000000), Fraction(1)),\n (-1 - Fraction(-1, 1000000), Fraction(-1)),\n ]\n for a, x in within_1e6:\n assert a == approx(x, rel=5e-6, abs=0)\n assert a != approx(x, rel=5e-7, abs=0)\n assert approx(x, rel=5e-6, abs=0) == a\n assert approx(x, rel=5e-7, abs=0) != a\n\n def test_complex(self):\n within_1e6 = [\n (1.000001 + 1.0j, 1.0 + 1.0j),\n (1.0 + 1.000001j, 1.0 + 1.0j),\n (-1.000001 + 1.0j, -1.0 + 1.0j),\n (1.0 - 1.000001j, 1.0 - 1.0j),\n ]\n for a, x in within_1e6:\n assert a == approx(x, rel=5e-6, abs=0)\n assert a != approx(x, rel=5e-7, abs=0)\n assert approx(x, rel=5e-6, abs=0) == a\n assert approx(x, rel=5e-7, abs=0) != a\n\n def test_list(self):\n actual = [1 + 1e-7, 2 + 1e-8]\n expected = [1, 2]\n\n # Return false if any element is outside the tolerance.\n assert actual == approx(expected, rel=5e-7, abs=0)\n assert actual != approx(expected, rel=5e-8, abs=0)\n assert approx(expected, rel=5e-7, abs=0) == actual\n assert approx(expected, rel=5e-8, abs=0) != actual\n\n def test_list_wrong_len(self):\n assert [1, 2] != approx([1])\n assert [1, 2] != approx([1, 2, 3])\n\n def test_tuple(self):\n actual = (1 + 1e-7, 2 + 1e-8)\n expected = (1, 2)\n\n # Return false if any element is outside the tolerance.\n assert actual == approx(expected, rel=5e-7, abs=0)\n assert actual != approx(expected, rel=5e-8, abs=0)\n assert approx(expected, rel=5e-7, abs=0) == actual\n assert approx(expected, rel=5e-8, abs=0) != actual\n\n def test_tuple_wrong_len(self):\n assert (1, 2) != approx((1,))\n assert (1, 2) != approx((1, 2, 3))\n\n def test_dict(self):\n actual = {\"a\": 1 + 1e-7, \"b\": 2 + 1e-8}\n # Dictionaries became ordered in python3.6, so switch up the order here\n # to make sure it doesn't matter.\n expected = {\"b\": 2, \"a\": 1}\n\n # Return false if any element is outside the tolerance.\n assert actual == approx(expected, rel=5e-7, abs=0)\n assert actual != approx(expected, rel=5e-8, abs=0)\n assert approx(expected, rel=5e-7, abs=0) == actual\n assert approx(expected, rel=5e-8, abs=0) != actual\n\n def test_dict_wrong_len(self):\n assert {\"a\": 1, \"b\": 2} != approx({\"a\": 1})\n assert {\"a\": 1, \"b\": 2} != approx({\"a\": 1, \"c\": 2})\n assert {\"a\": 1, \"b\": 2} != approx({\"a\": 1, \"b\": 2, \"c\": 3})\n\n def test_numpy_array(self):\n np = pytest.importorskip(\"numpy\")\n\n actual = np.array([1 + 1e-7, 2 + 1e-8])\n expected = np.array([1, 2])\n\n # Return false if any element is outside the tolerance.\n assert actual == approx(expected, rel=5e-7, abs=0)\n assert actual != approx(expected, rel=5e-8, abs=0)\n assert approx(expected, rel=5e-7, abs=0) == expected\n assert approx(expected, rel=5e-8, abs=0) != actual\n\n # Should be able to compare lists with numpy arrays.\n assert list(actual) == approx(expected, rel=5e-7, abs=0)\n assert list(actual) != approx(expected, rel=5e-8, abs=0)\n assert actual == approx(list(expected), rel=5e-7, abs=0)\n assert actual != approx(list(expected), rel=5e-8, abs=0)\n\n def test_numpy_tolerance_args(self):\n \"\"\"\n Check that numpy rel/abs args are handled correctly\n for comparison against an np.array\n Check both sides of the operator, hopefully it doesn't impact things.\n Test all permutations of where the approx and np.array() can show up\n \"\"\"\n np = pytest.importorskip(\"numpy\")\n expected = 100.0\n actual = 99.0\n abs_diff = expected - actual\n rel_diff = (expected - actual) / expected\n\n tests = [\n (eq, abs_diff, 0),\n (eq, 0, rel_diff),\n (ne, 0, rel_diff / 2.0), # rel diff fail\n (ne, abs_diff / 2.0, 0), # abs diff fail\n ]\n\n for op, _abs, _rel in tests:\n assert op(np.array(actual), approx(expected, abs=_abs, rel=_rel)) # a, b\n assert op(approx(expected, abs=_abs, rel=_rel), np.array(actual)) # b, a\n\n assert op(actual, approx(np.array(expected), abs=_abs, rel=_rel)) # a, b\n assert op(approx(np.array(expected), abs=_abs, rel=_rel), actual) # b, a\n\n assert op(np.array(actual), approx(np.array(expected), abs=_abs, rel=_rel))\n assert op(approx(np.array(expected), abs=_abs, rel=_rel), np.array(actual))\n\n def test_numpy_expecting_nan(self):\n np = pytest.importorskip(\"numpy\")\n examples = [\n (eq, nan, nan),\n (eq, -nan, -nan),\n (eq, nan, -nan),\n (ne, 0.0, nan),\n (ne, inf, nan),\n ]\n for op, a, x in examples:\n # Nothing is equal to NaN by default.\n assert np.array(a) != approx(x)\n assert a != approx(np.array(x))\n\n # If ``nan_ok=True``, then NaN is equal to NaN.\n assert op(np.array(a), approx(x, nan_ok=True))\n assert op(a, approx(np.array(x), nan_ok=True))\n\n def test_numpy_expecting_inf(self):\n np = pytest.importorskip(\"numpy\")\n examples = [\n (eq, inf, inf),\n (eq, -inf, -inf),\n (ne, inf, -inf),\n (ne, 0.0, inf),\n (ne, nan, inf),\n ]\n for op, a, x in examples:\n assert op(np.array(a), approx(x))\n assert op(a, approx(np.array(x)))\n assert op(np.array(a), approx(np.array(x)))\n\n def test_numpy_array_wrong_shape(self):\n np = pytest.importorskip(\"numpy\")\n\n a12 = np.array([[1, 2]])\n a21 = np.array([[1], [2]])\n\n assert a12 != approx(a21)\n assert a21 != approx(a12)\n\n def test_doctests(self):\n parser = doctest.DocTestParser()\n test = parser.get_doctest(\n approx.__doc__, {\"approx\": approx}, approx.__name__, None, None\n )\n runner = MyDocTestRunner()\n runner.run(test)\n\n def test_unicode_plus_minus(self, testdir):\n \"\"\"\n Comparing approx instances inside lists should not produce an error in the detailed diff.\n Integration test for issue #2111.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_foo():\n assert [3] == [pytest.approx(4)]\n \"\"\"\n )\n expected = \"4.0e-06\"\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"*At index 0 diff: 3 != 4 * {}\".format(expected), \"=* 1 failed in *=\"]\n )\n\n @pytest.mark.parametrize(\n \"x\",\n [\n pytest.param(None),\n pytest.param(\"string\"),\n pytest.param([\"string\"], id=\"nested-str\"),\n pytest.param([[1]], id=\"nested-list\"),\n pytest.param({\"key\": \"string\"}, id=\"dict-with-string\"),\n pytest.param({\"key\": {\"key\": 1}}, id=\"nested-dict\"),\n ],\n )\n def test_expected_value_type_error(self, x):\n with pytest.raises(TypeError):\n approx(x)\n\n @pytest.mark.parametrize(\n \"op\",\n [\n pytest.param(operator.le, id=\"<=\"),\n pytest.param(operator.lt, id=\"<\"),\n pytest.param(operator.ge, id=\">=\"),\n pytest.param(operator.gt, id=\">\"),\n ],\n )\n def test_comparison_operator_type_error(self, op):\n \"\"\"\n pytest.approx should raise TypeError for operators other than == and != (#2003).\n \"\"\"\n with pytest.raises(TypeError):\n op(1, approx(1, rel=1e-6, abs=1e-12))\n\n def test_numpy_array_with_scalar(self):\n np = pytest.importorskip(\"numpy\")\n\n actual = np.array([1 + 1e-7, 1 - 1e-8])\n expected = 1.0\n\n assert actual == approx(expected, rel=5e-7, abs=0)\n assert actual != approx(expected, rel=5e-8, abs=0)\n assert approx(expected, rel=5e-7, abs=0) == actual\n assert approx(expected, rel=5e-8, abs=0) != actual\n\n def test_numpy_scalar_with_array(self):\n np = pytest.importorskip(\"numpy\")\n\n actual = 1.0\n expected = np.array([1 + 1e-7, 1 - 1e-8])\n\n assert actual == approx(expected, rel=5e-7, abs=0)\n assert actual != approx(expected, rel=5e-8, abs=0)\n assert approx(expected, rel=5e-7, abs=0) == actual\n assert approx(expected, rel=5e-8, abs=0) != actual\n\n def test_generic_sized_iterable_object(self):\n class MySizedIterable(object):\n def __iter__(self):\n return iter([1, 2, 3, 4])\n\n def __len__(self):\n return 4\n\n expected = MySizedIterable()\n assert [1, 2, 3, 4] == approx(expected)\n"},{"col":0,"comment":"null","endLoc":24,"header":"def test_maxsize_error_on_instance()","id":600,"name":"test_maxsize_error_on_instance","nodeType":"Function","startLoc":17,"text":"def test_maxsize_error_on_instance():\n class A:\n def __repr__():\n raise ValueError(\"...\")\n\n s = saferepr((\"*\" * 50, A()), maxsize=25)\n assert len(s) == 25\n assert s[0] == \"(\" and s[-1] == \")\""},{"col":0,"comment":"\n This function should be used instead of calling ``warnings.warn`` directly when we are in the \"configure\" stage:\n at this point the actual options might not have been set, so we manually trigger the pytest_warning_captured\n hook so we can display this warnings in the terminal. This is a hack until we can sort out #2891.\n\n :param warning: the warning instance.\n :param hook: the hook caller\n :param stacklevel: stacklevel forwarded to warnings.warn\n ","endLoc":180,"header":"def _issue_warning_captured(warning, hook, stacklevel)","id":601,"name":"_issue_warning_captured","nodeType":"Function","startLoc":165,"text":"def _issue_warning_captured(warning, hook, stacklevel):\n \"\"\"\n This function should be used instead of calling ``warnings.warn`` directly when we are in the \"configure\" stage:\n at this point the actual options might not have been set, so we manually trigger the pytest_warning_captured\n hook so we can display this warnings in the terminal. This is a hack until we can sort out #2891.\n\n :param warning: the warning instance.\n :param hook: the hook caller\n :param stacklevel: stacklevel forwarded to warnings.warn\n \"\"\"\n with warnings.catch_warnings(record=True) as records:\n warnings.simplefilter(\"always\", type(warning))\n warnings.warn(warning, stacklevel=stacklevel)\n hook.pytest_warning_captured.call_historic(\n kwargs=dict(warning_message=records[0], when=\"config\", item=None)\n )"},{"className":"Decimal","col":0,"comment":"\n Construct a new Decimal object. 'value' can be an integer, string, tuple,\n or another Decimal object. If no value is given, return Decimal('0'). The\n context does not affect the conversion and is only passed to determine if\n the InvalidOperation trap is active.\n ","endLoc":1091,"id":602,"nodeType":"Class","startLoc":456,"text":"class Decimal(object):\n \"\"\"\n Construct a new Decimal object. 'value' can be an integer, string, tuple,\n or another Decimal object. If no value is given, return Decimal('0'). The\n context does not affect the conversion and is only passed to determine if\n the InvalidOperation trap is active.\n \"\"\"\n def adjusted(self, *args, **kwargs): # real signature unknown\n \"\"\" Return the adjusted exponent of the number. Defined as exp + digits - 1. \"\"\"\n pass\n\n def as_integer_ratio(self): # real signature unknown; restored from __doc__\n \"\"\"\n Decimal.as_integer_ratio() -> (int, int)\n \n Return a pair of integers, whose ratio is exactly equal to the original\n Decimal and with a positive denominator. The ratio is in lowest terms.\n Raise OverflowError on infinities and a ValueError on NaNs.\n \"\"\"\n pass\n\n def as_tuple(self, *args, **kwargs): # real signature unknown\n \"\"\" Return a tuple representation of the number. \"\"\"\n pass\n\n def canonical(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the canonical encoding of the argument. Currently, the encoding\n of a Decimal instance is always canonical, so this operation returns its\n argument unchanged.\n \"\"\"\n pass\n\n def compare(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Compare self to other. Return a decimal value:\n \n a or b is a NaN ==> Decimal('NaN')\n a < b ==> Decimal('-1')\n a == b ==> Decimal('0')\n a > b ==> Decimal('1')\n \"\"\"\n pass\n\n def compare_signal(self, *args, **kwargs): # real signature unknown\n \"\"\" Identical to compare, except that all NaNs signal. \"\"\"\n pass\n\n def compare_total(self, Decimal, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ \n \"\"\"\n Compare two operands using their abstract representation rather than\n their numerical value. Similar to the compare() method, but the result\n gives a total ordering on Decimal instances. Two Decimal instances with\n the same numeric value but different representations compare unequal\n in this ordering:\n \n >>> Decimal('12.0').compare_total(Decimal('12'))\n Decimal('-1')\n \n Quiet and signaling NaNs are also included in the total ordering. The result\n of this function is Decimal('0') if both operands have the same representation,\n Decimal('-1') if the first operand is lower in the total order than the second,\n and Decimal('1') if the first operand is higher in the total order than the\n second operand. See the specification for details of the total order.\n \n This operation is unaffected by context and is quiet: no flags are changed\n and no rounding is performed. As an exception, the C version may raise\n InvalidOperation if the second operand cannot be converted exactly.\n \"\"\"\n pass\n\n def compare_total_mag(self, y): # real signature unknown; restored from __doc__\n \"\"\"\n Compare two operands using their abstract representation rather than their\n value as in compare_total(), but ignoring the sign of each operand.\n \n x.compare_total_mag(y) is equivalent to x.copy_abs().compare_total(y.copy_abs()).\n \n This operation is unaffected by context and is quiet: no flags are changed\n and no rounding is performed. As an exception, the C version may raise\n InvalidOperation if the second operand cannot be converted exactly.\n \"\"\"\n pass\n\n def conjugate(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self. \"\"\"\n pass\n\n def copy_abs(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the absolute value of the argument. This operation is unaffected by\n context and is quiet: no flags are changed and no rounding is performed.\n \"\"\"\n pass\n\n def copy_negate(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the negation of the argument. This operation is unaffected by context\n and is quiet: no flags are changed and no rounding is performed.\n \"\"\"\n pass\n\n def copy_sign(self, Decimal, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ \n \"\"\"\n Return a copy of the first operand with the sign set to be the same as the\n sign of the second operand. For example:\n \n >>> Decimal('2.3').copy_sign(Decimal('-1.5'))\n Decimal('-2.3')\n \n This operation is unaffected by context and is quiet: no flags are changed\n and no rounding is performed. As an exception, the C version may raise\n InvalidOperation if the second operand cannot be converted exactly.\n \"\"\"\n pass\n\n def exp(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the value of the (natural) exponential function e**x at the given\n number. The function always uses the ROUND_HALF_EVEN mode and the result\n is correctly rounded.\n \"\"\"\n pass\n\n def fma(self, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ \n \"\"\"\n Fused multiply-add. Return self*other+third with no rounding of the\n intermediate product self*other.\n \n >>> Decimal(2).fma(3, 5)\n Decimal('11')\n \"\"\"\n pass\n\n @classmethod\n def from_float(cls, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ \n \"\"\"\n Class method that converts a float to a decimal number, exactly.\n Since 0.1 is not exactly representable in binary floating point,\n Decimal.from_float(0.1) is not the same as Decimal('0.1').\n \n >>> Decimal.from_float(0.1)\n Decimal('0.1000000000000000055511151231257827021181583404541015625')\n >>> Decimal.from_float(float('nan'))\n Decimal('NaN')\n >>> Decimal.from_float(float('inf'))\n Decimal('Infinity')\n >>> Decimal.from_float(float('-inf'))\n Decimal('-Infinity')\n \"\"\"\n pass\n\n def is_canonical(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return True if the argument is canonical and False otherwise. Currently,\n a Decimal instance is always canonical, so this operation always returns\n True.\n \"\"\"\n pass\n\n def is_finite(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return True if the argument is a finite number, and False if the argument\n is infinite or a NaN.\n \"\"\"\n pass\n\n def is_infinite(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return True if the argument is either positive or negative infinity and\n False otherwise.\n \"\"\"\n pass\n\n def is_nan(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return True if the argument is a (quiet or signaling) NaN and False\n otherwise.\n \"\"\"\n pass\n\n def is_normal(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return True if the argument is a normal finite non-zero number with an\n adjusted exponent greater than or equal to Emin. Return False if the\n argument is zero, subnormal, infinite or a NaN.\n \"\"\"\n pass\n\n def is_qnan(self, *args, **kwargs): # real signature unknown\n \"\"\" Return True if the argument is a quiet NaN, and False otherwise. \"\"\"\n pass\n\n def is_signed(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return True if the argument has a negative sign and False otherwise.\n Note that both zeros and NaNs can carry signs.\n \"\"\"\n pass\n\n def is_snan(self, *args, **kwargs): # real signature unknown\n \"\"\" Return True if the argument is a signaling NaN and False otherwise. \"\"\"\n pass\n\n def is_subnormal(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return True if the argument is subnormal, and False otherwise. A number is\n subnormal if it is non-zero, finite, and has an adjusted exponent less\n than Emin.\n \"\"\"\n pass\n\n def is_zero(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return True if the argument is a (positive or negative) zero and False\n otherwise.\n \"\"\"\n pass\n\n def ln(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the natural (base e) logarithm of the operand. The function always\n uses the ROUND_HALF_EVEN mode and the result is correctly rounded.\n \"\"\"\n pass\n\n def log10(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the base ten logarithm of the operand. The function always uses the\n ROUND_HALF_EVEN mode and the result is correctly rounded.\n \"\"\"\n pass\n\n def logb(self, *args, **kwargs): # real signature unknown\n \"\"\"\n For a non-zero number, return the adjusted exponent of the operand as a\n Decimal instance. If the operand is a zero, then Decimal('-Infinity') is\n returned and the DivisionByZero condition is raised. If the operand is\n an infinity then Decimal('Infinity') is returned.\n \"\"\"\n pass\n\n def logical_and(self, *args, **kwargs): # real signature unknown\n \"\"\" Return the digit-wise 'and' of the two (logical) operands. \"\"\"\n pass\n\n def logical_invert(self, *args, **kwargs): # real signature unknown\n \"\"\" Return the digit-wise inversion of the (logical) operand. \"\"\"\n pass\n\n def logical_or(self, *args, **kwargs): # real signature unknown\n \"\"\" Return the digit-wise 'or' of the two (logical) operands. \"\"\"\n pass\n\n def logical_xor(self, *args, **kwargs): # real signature unknown\n \"\"\" Return the digit-wise 'exclusive or' of the two (logical) operands. \"\"\"\n pass\n\n def max(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Maximum of self and other. If one operand is a quiet NaN and the other is\n numeric, the numeric operand is returned.\n \"\"\"\n pass\n\n def max_mag(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Similar to the max() method, but the comparison is done using the absolute\n values of the operands.\n \"\"\"\n pass\n\n def min(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Minimum of self and other. If one operand is a quiet NaN and the other is\n numeric, the numeric operand is returned.\n \"\"\"\n pass\n\n def min_mag(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Similar to the min() method, but the comparison is done using the absolute\n values of the operands.\n \"\"\"\n pass\n\n def next_minus(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the largest number representable in the given context (or in the\n current default context if no context is given) that is smaller than the\n given operand.\n \"\"\"\n pass\n\n def next_plus(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the smallest number representable in the given context (or in the\n current default context if no context is given) that is larger than the\n given operand.\n \"\"\"\n pass\n\n def next_toward(self, *args, **kwargs): # real signature unknown\n \"\"\"\n If the two operands are unequal, return the number closest to the first\n operand in the direction of the second operand. If both operands are\n numerically equal, return a copy of the first operand with the sign set\n to be the same as the sign of the second operand.\n \"\"\"\n pass\n\n def normalize(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Normalize the number by stripping the rightmost trailing zeros and\n converting any result equal to Decimal('0') to Decimal('0e0'). Used\n for producing canonical values for members of an equivalence class.\n For example, Decimal('32.100') and Decimal('0.321000e+2') both normalize\n to the equivalent value Decimal('32.1').\n \"\"\"\n pass\n\n def number_class(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return a string describing the class of the operand. The returned value\n is one of the following ten strings:\n \n * '-Infinity', indicating that the operand is negative infinity.\n * '-Normal', indicating that the operand is a negative normal number.\n * '-Subnormal', indicating that the operand is negative and subnormal.\n * '-Zero', indicating that the operand is a negative zero.\n * '+Zero', indicating that the operand is a positive zero.\n * '+Subnormal', indicating that the operand is positive and subnormal.\n * '+Normal', indicating that the operand is a positive normal number.\n * '+Infinity', indicating that the operand is positive infinity.\n * 'NaN', indicating that the operand is a quiet NaN (Not a Number).\n * 'sNaN', indicating that the operand is a signaling NaN.\n \"\"\"\n pass\n\n def quantize(self, Decimal, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ \n \"\"\"\n Return a value equal to the first operand after rounding and having the\n exponent of the second operand.\n \n >>> Decimal('1.41421356').quantize(Decimal('1.000'))\n Decimal('1.414')\n \n Unlike other operations, if the length of the coefficient after the quantize\n operation would be greater than precision, then an InvalidOperation is signaled.\n This guarantees that, unless there is an error condition, the quantized exponent\n is always equal to that of the right-hand operand.\n \n Also unlike other operations, quantize never signals Underflow, even if the\n result is subnormal and inexact.\n \n If the exponent of the second operand is larger than that of the first, then\n rounding may be necessary. In this case, the rounding mode is determined by the\n rounding argument if given, else by the given context argument; if neither\n argument is given, the rounding mode of the current thread's context is used.\n \"\"\"\n pass\n\n def radix(self, base): # real signature unknown; restored from __doc__\n \"\"\"\n Return Decimal(10), the radix (base) in which the Decimal class does\n all its arithmetic. Included for compatibility with the specification.\n \"\"\"\n pass\n\n def remainder_near(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the remainder from dividing self by other. This differs from\n self % other in that the sign of the remainder is chosen so as to minimize\n its absolute value. More precisely, the return value is self - n * other\n where n is the integer nearest to the exact value of self / other, and\n if two integers are equally near then the even one is chosen.\n \n If the result is zero then its sign will be the sign of self.\n \"\"\"\n pass\n\n def rotate(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the result of rotating the digits of the first operand by an amount\n specified by the second operand. The second operand must be an integer in\n the range -precision through precision. The absolute value of the second\n operand gives the number of places to rotate. If the second operand is\n positive then rotation is to the left; otherwise rotation is to the right.\n The coefficient of the first operand is padded on the left with zeros to\n length precision if necessary. The sign and exponent of the first operand are\n unchanged.\n \"\"\"\n pass\n\n def same_quantum(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Test whether self and other have the same exponent or whether both are NaN.\n \n This operation is unaffected by context and is quiet: no flags are changed\n and no rounding is performed. As an exception, the C version may raise\n InvalidOperation if the second operand cannot be converted exactly.\n \"\"\"\n pass\n\n def scaleb(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the first operand with the exponent adjusted the second. Equivalently,\n return the first operand multiplied by 10**other. The second operand must be\n an integer.\n \"\"\"\n pass\n\n def shift(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the result of shifting the digits of the first operand by an amount\n specified by the second operand. The second operand must be an integer in\n the range -precision through precision. The absolute value of the second\n operand gives the number of places to shift. If the second operand is\n positive, then the shift is to the left; otherwise the shift is to the\n right. Digits shifted into the coefficient are zeros. The sign and exponent\n of the first operand are unchanged.\n \"\"\"\n pass\n\n def sqrt(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the square root of the argument to full precision. The result is\n correctly rounded using the ROUND_HALF_EVEN rounding mode.\n \"\"\"\n pass\n\n def to_eng_string(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Convert to an engineering-type string. Engineering notation has an exponent\n which is a multiple of 3, so there are up to 3 digits left of the decimal\n place. For example, Decimal('123E+1') is converted to Decimal('1.23E+3').\n \n The value of context.capitals determines whether the exponent sign is lower\n or upper case. Otherwise, the context does not affect the operation.\n \"\"\"\n pass\n\n def to_integral(self): # real signature unknown; restored from __doc__\n \"\"\"\n Identical to the to_integral_value() method. The to_integral() name has been\n kept for compatibility with older versions.\n \"\"\"\n pass\n\n def to_integral_exact(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Round to the nearest integer, signaling Inexact or Rounded as appropriate if\n rounding occurs. The rounding mode is determined by the rounding parameter\n if given, else by the given context. If neither parameter is given, then the\n rounding mode of the current default context is used.\n \"\"\"\n pass\n\n def to_integral_value(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Round to the nearest integer without signaling Inexact or Rounded. The\n rounding mode is determined by the rounding parameter if given, else by\n the given context. If neither parameter is given, then the rounding mode\n of the current default context is used.\n \"\"\"\n pass\n\n def __abs__(self, *args, **kwargs): # real signature unknown\n \"\"\" abs(self) \"\"\"\n pass\n\n def __add__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self+value. \"\"\"\n pass\n\n def __bool__(self, *args, **kwargs): # real signature unknown\n \"\"\" self != 0 \"\"\"\n pass\n\n def __ceil__(self, *args, **kwargs): # real signature unknown\n pass\n\n def __complex__(self, *args, **kwargs): # real signature unknown\n pass\n\n def __copy__(self, *args, **kwargs): # real signature unknown\n pass\n\n def __deepcopy__(self, *args, **kwargs): # real signature unknown\n pass\n\n def __divmod__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return divmod(self, value). \"\"\"\n pass\n\n def __eq__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self==value. \"\"\"\n pass\n\n def __float__(self, *args, **kwargs): # real signature unknown\n \"\"\" float(self) \"\"\"\n pass\n\n def __floordiv__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self//value. \"\"\"\n pass\n\n def __floor__(self, *args, **kwargs): # real signature unknown\n pass\n\n def __format__(self, *args, **kwargs): # real signature unknown\n pass\n\n def __getattribute__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return getattr(self, name). \"\"\"\n pass\n\n def __ge__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self>=value. \"\"\"\n pass\n\n def __gt__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self>value. \"\"\"\n pass\n\n def __hash__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return hash(self). \"\"\"\n pass\n\n def __init__(self, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ \n pass\n\n def __int__(self, *args, **kwargs): # real signature unknown\n \"\"\" int(self) \"\"\"\n pass\n\n def __le__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self<=value. \"\"\"\n pass\n\n def __lt__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self (int, int)\n \n Return a pair of integers, whose ratio is exactly equal to the original\n Decimal and with a positive denominator. The ratio is in lowest terms.\n Raise OverflowError on infinities and a ValueError on NaNs.\n ","endLoc":475,"header":"def as_integer_ratio(self)","id":609,"name":"as_integer_ratio","nodeType":"Function","startLoc":467,"text":"def as_integer_ratio(self): # real signature unknown; restored from __doc__\n \"\"\"\n Decimal.as_integer_ratio() -> (int, int)\n \n Return a pair of integers, whose ratio is exactly equal to the original\n Decimal and with a positive denominator. The ratio is in lowest terms.\n Raise OverflowError on infinities and a ValueError on NaNs.\n \"\"\"\n pass"},{"col":4,"comment":" Return a tuple representation of the number. ","endLoc":479,"header":"def as_tuple(self, *args, **kwargs)","id":610,"name":"as_tuple","nodeType":"Function","startLoc":477,"text":"def as_tuple(self, *args, **kwargs): # real signature unknown\n \"\"\" Return a tuple representation of the number. \"\"\"\n pass"},{"col":4,"comment":"\n Return the canonical encoding of the argument. Currently, the encoding\n of a Decimal instance is always canonical, so this operation returns its\n argument unchanged.\n ","endLoc":487,"header":"def canonical(self, *args, **kwargs)","id":611,"name":"canonical","nodeType":"Function","startLoc":481,"text":"def canonical(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the canonical encoding of the argument. Currently, the encoding\n of a Decimal instance is always canonical, so this operation returns its\n argument unchanged.\n \"\"\"\n pass"},{"col":4,"comment":"\n Compare self to other. Return a decimal value:\n \n a or b is a NaN ==> Decimal('NaN')\n a < b ==> Decimal('-1')\n a == b ==> Decimal('0')\n a > b ==> Decimal('1')\n ","endLoc":498,"header":"def compare(self, *args, **kwargs)","id":612,"name":"compare","nodeType":"Function","startLoc":489,"text":"def compare(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Compare self to other. Return a decimal value:\n \n a or b is a NaN ==> Decimal('NaN')\n a < b ==> Decimal('-1')\n a == b ==> Decimal('0')\n a > b ==> Decimal('1')\n \"\"\"\n pass"},{"col":4,"comment":" Identical to compare, except that all NaNs signal. ","endLoc":502,"header":"def compare_signal(self, *args, **kwargs)","id":613,"name":"compare_signal","nodeType":"Function","startLoc":500,"text":"def compare_signal(self, *args, **kwargs): # real signature unknown\n \"\"\" Identical to compare, except that all NaNs signal. \"\"\"\n pass"},{"col":4,"comment":"\n Compare two operands using their abstract representation rather than\n their numerical value. Similar to the compare() method, but the result\n gives a total ordering on Decimal instances. Two Decimal instances with\n the same numeric value but different representations compare unequal\n in this ordering:\n \n >>> Decimal('12.0').compare_total(Decimal('12'))\n Decimal('-1')\n \n Quiet and signaling NaNs are also included in the total ordering. The result\n of this function is Decimal('0') if both operands have the same representation,\n Decimal('-1') if the first operand is lower in the total order than the second,\n and Decimal('1') if the first operand is higher in the total order than the\n second operand. See the specification for details of the total order.\n \n This operation is unaffected by context and is quiet: no flags are changed\n and no rounding is performed. As an exception, the C version may raise\n InvalidOperation if the second operand cannot be converted exactly.\n ","endLoc":525,"header":"def compare_total(self, Decimal, *args, **kwargs)","id":614,"name":"compare_total","nodeType":"Function","startLoc":504,"text":"def compare_total(self, Decimal, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ \n \"\"\"\n Compare two operands using their abstract representation rather than\n their numerical value. Similar to the compare() method, but the result\n gives a total ordering on Decimal instances. Two Decimal instances with\n the same numeric value but different representations compare unequal\n in this ordering:\n \n >>> Decimal('12.0').compare_total(Decimal('12'))\n Decimal('-1')\n \n Quiet and signaling NaNs are also included in the total ordering. The result\n of this function is Decimal('0') if both operands have the same representation,\n Decimal('-1') if the first operand is lower in the total order than the second,\n and Decimal('1') if the first operand is higher in the total order than the\n second operand. See the specification for details of the total order.\n \n This operation is unaffected by context and is quiet: no flags are changed\n and no rounding is performed. As an exception, the C version may raise\n InvalidOperation if the second operand cannot be converted exactly.\n \"\"\"\n pass"},{"col":4,"comment":"\n Compare two operands using their abstract representation rather than their\n value as in compare_total(), but ignoring the sign of each operand.\n \n x.compare_total_mag(y) is equivalent to x.copy_abs().compare_total(y.copy_abs()).\n \n This operation is unaffected by context and is quiet: no flags are changed\n and no rounding is performed. As an exception, the C version may raise\n InvalidOperation if the second operand cannot be converted exactly.\n ","endLoc":538,"header":"def compare_total_mag(self, y)","id":615,"name":"compare_total_mag","nodeType":"Function","startLoc":527,"text":"def compare_total_mag(self, y): # real signature unknown; restored from __doc__\n \"\"\"\n Compare two operands using their abstract representation rather than their\n value as in compare_total(), but ignoring the sign of each operand.\n \n x.compare_total_mag(y) is equivalent to x.copy_abs().compare_total(y.copy_abs()).\n \n This operation is unaffected by context and is quiet: no flags are changed\n and no rounding is performed. As an exception, the C version may raise\n InvalidOperation if the second operand cannot be converted exactly.\n \"\"\"\n pass"},{"col":4,"comment":" Return self. ","endLoc":542,"header":"def conjugate(self, *args, **kwargs)","id":616,"name":"conjugate","nodeType":"Function","startLoc":540,"text":"def conjugate(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self. \"\"\"\n pass"},{"col":4,"comment":"\n Return the absolute value of the argument. This operation is unaffected by\n context and is quiet: no flags are changed and no rounding is performed.\n ","endLoc":549,"header":"def copy_abs(self, *args, **kwargs)","id":617,"name":"copy_abs","nodeType":"Function","startLoc":544,"text":"def copy_abs(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the absolute value of the argument. This operation is unaffected by\n context and is quiet: no flags are changed and no rounding is performed.\n \"\"\"\n pass"},{"col":4,"comment":"\n Return the negation of the argument. This operation is unaffected by context\n and is quiet: no flags are changed and no rounding is performed.\n ","endLoc":556,"header":"def copy_negate(self, *args, **kwargs)","id":618,"name":"copy_negate","nodeType":"Function","startLoc":551,"text":"def copy_negate(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the negation of the argument. This operation is unaffected by context\n and is quiet: no flags are changed and no rounding is performed.\n \"\"\"\n pass"},{"col":4,"comment":"\n Return a copy of the first operand with the sign set to be the same as the\n sign of the second operand. For example:\n \n >>> Decimal('2.3').copy_sign(Decimal('-1.5'))\n Decimal('-2.3')\n \n This operation is unaffected by context and is quiet: no flags are changed\n and no rounding is performed. As an exception, the C version may raise\n InvalidOperation if the second operand cannot be converted exactly.\n ","endLoc":570,"header":"def copy_sign(self, Decimal, *args, **kwargs)","id":619,"name":"copy_sign","nodeType":"Function","startLoc":558,"text":"def copy_sign(self, Decimal, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ \n \"\"\"\n Return a copy of the first operand with the sign set to be the same as the\n sign of the second operand. For example:\n \n >>> Decimal('2.3').copy_sign(Decimal('-1.5'))\n Decimal('-2.3')\n \n This operation is unaffected by context and is quiet: no flags are changed\n and no rounding is performed. As an exception, the C version may raise\n InvalidOperation if the second operand cannot be converted exactly.\n \"\"\"\n pass"},{"col":4,"comment":"\n Return the value of the (natural) exponential function e**x at the given\n number. The function always uses the ROUND_HALF_EVEN mode and the result\n is correctly rounded.\n ","endLoc":578,"header":"def exp(self, *args, **kwargs)","id":620,"name":"exp","nodeType":"Function","startLoc":572,"text":"def exp(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the value of the (natural) exponential function e**x at the given\n number. The function always uses the ROUND_HALF_EVEN mode and the result\n is correctly rounded.\n \"\"\"\n pass"},{"col":4,"comment":"\n Fused multiply-add. Return self*other+third with no rounding of the\n intermediate product self*other.\n \n >>> Decimal(2).fma(3, 5)\n Decimal('11')\n ","endLoc":588,"header":"def fma(self, *args, **kwargs)","id":621,"name":"fma","nodeType":"Function","startLoc":580,"text":"def fma(self, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ \n \"\"\"\n Fused multiply-add. Return self*other+third with no rounding of the\n intermediate product self*other.\n \n >>> Decimal(2).fma(3, 5)\n Decimal('11')\n \"\"\"\n pass"},{"col":4,"comment":"\n Class method that converts a float to a decimal number, exactly.\n Since 0.1 is not exactly representable in binary floating point,\n Decimal.from_float(0.1) is not the same as Decimal('0.1').\n \n >>> Decimal.from_float(0.1)\n Decimal('0.1000000000000000055511151231257827021181583404541015625')\n >>> Decimal.from_float(float('nan'))\n Decimal('NaN')\n >>> Decimal.from_float(float('inf'))\n Decimal('Infinity')\n >>> Decimal.from_float(float('-inf'))\n Decimal('-Infinity')\n ","endLoc":606,"header":"@classmethod\n def from_float(cls, *args, **kwargs)","id":622,"name":"from_float","nodeType":"Function","startLoc":590,"text":"@classmethod\n def from_float(cls, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ \n \"\"\"\n Class method that converts a float to a decimal number, exactly.\n Since 0.1 is not exactly representable in binary floating point,\n Decimal.from_float(0.1) is not the same as Decimal('0.1').\n \n >>> Decimal.from_float(0.1)\n Decimal('0.1000000000000000055511151231257827021181583404541015625')\n >>> Decimal.from_float(float('nan'))\n Decimal('NaN')\n >>> Decimal.from_float(float('inf'))\n Decimal('Infinity')\n >>> Decimal.from_float(float('-inf'))\n Decimal('-Infinity')\n \"\"\"\n pass"},{"col":4,"comment":"\n Return True if the argument is canonical and False otherwise. Currently,\n a Decimal instance is always canonical, so this operation always returns\n True.\n ","endLoc":614,"header":"def is_canonical(self, *args, **kwargs)","id":623,"name":"is_canonical","nodeType":"Function","startLoc":608,"text":"def is_canonical(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return True if the argument is canonical and False otherwise. Currently,\n a Decimal instance is always canonical, so this operation always returns\n True.\n \"\"\"\n pass"},{"col":4,"comment":"\n Return True if the argument is a finite number, and False if the argument\n is infinite or a NaN.\n ","endLoc":621,"header":"def is_finite(self, *args, **kwargs)","id":624,"name":"is_finite","nodeType":"Function","startLoc":616,"text":"def is_finite(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return True if the argument is a finite number, and False if the argument\n is infinite or a NaN.\n \"\"\"\n pass"},{"col":4,"comment":"\n Return True if the argument is either positive or negative infinity and\n False otherwise.\n ","endLoc":628,"header":"def is_infinite(self, *args, **kwargs)","id":625,"name":"is_infinite","nodeType":"Function","startLoc":623,"text":"def is_infinite(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return True if the argument is either positive or negative infinity and\n False otherwise.\n \"\"\"\n pass"},{"col":4,"comment":"\n Return True if the argument is a (quiet or signaling) NaN and False\n otherwise.\n ","endLoc":635,"header":"def is_nan(self, *args, **kwargs)","id":626,"name":"is_nan","nodeType":"Function","startLoc":630,"text":"def is_nan(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return True if the argument is a (quiet or signaling) NaN and False\n otherwise.\n \"\"\"\n pass"},{"col":4,"comment":"\n Return True if the argument is a normal finite non-zero number with an\n adjusted exponent greater than or equal to Emin. Return False if the\n argument is zero, subnormal, infinite or a NaN.\n ","endLoc":643,"header":"def is_normal(self, *args, **kwargs)","id":627,"name":"is_normal","nodeType":"Function","startLoc":637,"text":"def is_normal(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return True if the argument is a normal finite non-zero number with an\n adjusted exponent greater than or equal to Emin. Return False if the\n argument is zero, subnormal, infinite or a NaN.\n \"\"\"\n pass"},{"col":4,"comment":" Return True if the argument is a quiet NaN, and False otherwise. ","endLoc":647,"header":"def is_qnan(self, *args, **kwargs)","id":628,"name":"is_qnan","nodeType":"Function","startLoc":645,"text":"def is_qnan(self, *args, **kwargs): # real signature unknown\n \"\"\" Return True if the argument is a quiet NaN, and False otherwise. \"\"\"\n pass"},{"col":4,"comment":"\n Return True if the argument has a negative sign and False otherwise.\n Note that both zeros and NaNs can carry signs.\n ","endLoc":654,"header":"def is_signed(self, *args, **kwargs)","id":629,"name":"is_signed","nodeType":"Function","startLoc":649,"text":"def is_signed(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return True if the argument has a negative sign and False otherwise.\n Note that both zeros and NaNs can carry signs.\n \"\"\"\n pass"},{"col":4,"comment":" Return True if the argument is a signaling NaN and False otherwise. ","endLoc":658,"header":"def is_snan(self, *args, **kwargs)","id":630,"name":"is_snan","nodeType":"Function","startLoc":656,"text":"def is_snan(self, *args, **kwargs): # real signature unknown\n \"\"\" Return True if the argument is a signaling NaN and False otherwise. \"\"\"\n pass"},{"col":4,"comment":"\n Return True if the argument is subnormal, and False otherwise. A number is\n subnormal if it is non-zero, finite, and has an adjusted exponent less\n than Emin.\n ","endLoc":666,"header":"def is_subnormal(self, *args, **kwargs)","id":631,"name":"is_subnormal","nodeType":"Function","startLoc":660,"text":"def is_subnormal(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return True if the argument is subnormal, and False otherwise. A number is\n subnormal if it is non-zero, finite, and has an adjusted exponent less\n than Emin.\n \"\"\"\n pass"},{"col":4,"comment":"\n Return True if the argument is a (positive or negative) zero and False\n otherwise.\n ","endLoc":673,"header":"def is_zero(self, *args, **kwargs)","id":632,"name":"is_zero","nodeType":"Function","startLoc":668,"text":"def is_zero(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return True if the argument is a (positive or negative) zero and False\n otherwise.\n \"\"\"\n pass"},{"col":4,"comment":"\n Return the natural (base e) logarithm of the operand. The function always\n uses the ROUND_HALF_EVEN mode and the result is correctly rounded.\n ","endLoc":680,"header":"def ln(self, *args, **kwargs)","id":633,"name":"ln","nodeType":"Function","startLoc":675,"text":"def ln(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the natural (base e) logarithm of the operand. The function always\n uses the ROUND_HALF_EVEN mode and the result is correctly rounded.\n \"\"\"\n pass"},{"col":4,"comment":"\n Return the base ten logarithm of the operand. The function always uses the\n ROUND_HALF_EVEN mode and the result is correctly rounded.\n ","endLoc":687,"header":"def log10(self, *args, **kwargs)","id":634,"name":"log10","nodeType":"Function","startLoc":682,"text":"def log10(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the base ten logarithm of the operand. The function always uses the\n ROUND_HALF_EVEN mode and the result is correctly rounded.\n \"\"\"\n pass"},{"col":4,"comment":"\n For a non-zero number, return the adjusted exponent of the operand as a\n Decimal instance. If the operand is a zero, then Decimal('-Infinity') is\n returned and the DivisionByZero condition is raised. If the operand is\n an infinity then Decimal('Infinity') is returned.\n ","endLoc":696,"header":"def logb(self, *args, **kwargs)","id":635,"name":"logb","nodeType":"Function","startLoc":689,"text":"def logb(self, *args, **kwargs): # real signature unknown\n \"\"\"\n For a non-zero number, return the adjusted exponent of the operand as a\n Decimal instance. If the operand is a zero, then Decimal('-Infinity') is\n returned and the DivisionByZero condition is raised. If the operand is\n an infinity then Decimal('Infinity') is returned.\n \"\"\"\n pass"},{"col":4,"comment":" Return the digit-wise 'and' of the two (logical) operands. ","endLoc":700,"header":"def logical_and(self, *args, **kwargs)","id":636,"name":"logical_and","nodeType":"Function","startLoc":698,"text":"def logical_and(self, *args, **kwargs): # real signature unknown\n \"\"\" Return the digit-wise 'and' of the two (logical) operands. \"\"\"\n pass"},{"col":4,"comment":" Return the digit-wise inversion of the (logical) operand. ","endLoc":704,"header":"def logical_invert(self, *args, **kwargs)","id":637,"name":"logical_invert","nodeType":"Function","startLoc":702,"text":"def logical_invert(self, *args, **kwargs): # real signature unknown\n \"\"\" Return the digit-wise inversion of the (logical) operand. \"\"\"\n pass"},{"col":4,"comment":" Return the digit-wise 'or' of the two (logical) operands. ","endLoc":708,"header":"def logical_or(self, *args, **kwargs)","id":638,"name":"logical_or","nodeType":"Function","startLoc":706,"text":"def logical_or(self, *args, **kwargs): # real signature unknown\n \"\"\" Return the digit-wise 'or' of the two (logical) operands. \"\"\"\n pass"},{"col":4,"comment":" Return the digit-wise 'exclusive or' of the two (logical) operands. ","endLoc":712,"header":"def logical_xor(self, *args, **kwargs)","id":639,"name":"logical_xor","nodeType":"Function","startLoc":710,"text":"def logical_xor(self, *args, **kwargs): # real signature unknown\n \"\"\" Return the digit-wise 'exclusive or' of the two (logical) operands. \"\"\"\n pass"},{"col":4,"comment":"\n Maximum of self and other. If one operand is a quiet NaN and the other is\n numeric, the numeric operand is returned.\n ","endLoc":719,"header":"def max(self, *args, **kwargs)","id":640,"name":"max","nodeType":"Function","startLoc":714,"text":"def max(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Maximum of self and other. If one operand is a quiet NaN and the other is\n numeric, the numeric operand is returned.\n \"\"\"\n pass"},{"col":4,"comment":"\n Similar to the max() method, but the comparison is done using the absolute\n values of the operands.\n ","endLoc":726,"header":"def max_mag(self, *args, **kwargs)","id":641,"name":"max_mag","nodeType":"Function","startLoc":721,"text":"def max_mag(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Similar to the max() method, but the comparison is done using the absolute\n values of the operands.\n \"\"\"\n pass"},{"col":4,"comment":"\n Minimum of self and other. If one operand is a quiet NaN and the other is\n numeric, the numeric operand is returned.\n ","endLoc":733,"header":"def min(self, *args, **kwargs)","id":642,"name":"min","nodeType":"Function","startLoc":728,"text":"def min(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Minimum of self and other. If one operand is a quiet NaN and the other is\n numeric, the numeric operand is returned.\n \"\"\"\n pass"},{"col":4,"comment":"\n Similar to the min() method, but the comparison is done using the absolute\n values of the operands.\n ","endLoc":740,"header":"def min_mag(self, *args, **kwargs)","id":643,"name":"min_mag","nodeType":"Function","startLoc":735,"text":"def min_mag(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Similar to the min() method, but the comparison is done using the absolute\n values of the operands.\n \"\"\"\n pass"},{"col":4,"comment":"\n Return the largest number representable in the given context (or in the\n current default context if no context is given) that is smaller than the\n given operand.\n ","endLoc":748,"header":"def next_minus(self, *args, **kwargs)","id":644,"name":"next_minus","nodeType":"Function","startLoc":742,"text":"def next_minus(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the largest number representable in the given context (or in the\n current default context if no context is given) that is smaller than the\n given operand.\n \"\"\"\n pass"},{"col":4,"comment":"\n Return the smallest number representable in the given context (or in the\n current default context if no context is given) that is larger than the\n given operand.\n ","endLoc":756,"header":"def next_plus(self, *args, **kwargs)","id":645,"name":"next_plus","nodeType":"Function","startLoc":750,"text":"def next_plus(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the smallest number representable in the given context (or in the\n current default context if no context is given) that is larger than the\n given operand.\n \"\"\"\n pass"},{"col":4,"comment":"\n If the two operands are unequal, return the number closest to the first\n operand in the direction of the second operand. If both operands are\n numerically equal, return a copy of the first operand with the sign set\n to be the same as the sign of the second operand.\n ","endLoc":765,"header":"def next_toward(self, *args, **kwargs)","id":646,"name":"next_toward","nodeType":"Function","startLoc":758,"text":"def next_toward(self, *args, **kwargs): # real signature unknown\n \"\"\"\n If the two operands are unequal, return the number closest to the first\n operand in the direction of the second operand. If both operands are\n numerically equal, return a copy of the first operand with the sign set\n to be the same as the sign of the second operand.\n \"\"\"\n pass"},{"col":4,"comment":"\n Normalize the number by stripping the rightmost trailing zeros and\n converting any result equal to Decimal('0') to Decimal('0e0'). Used\n for producing canonical values for members of an equivalence class.\n For example, Decimal('32.100') and Decimal('0.321000e+2') both normalize\n to the equivalent value Decimal('32.1').\n ","endLoc":775,"header":"def normalize(self, *args, **kwargs)","id":647,"name":"normalize","nodeType":"Function","startLoc":767,"text":"def normalize(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Normalize the number by stripping the rightmost trailing zeros and\n converting any result equal to Decimal('0') to Decimal('0e0'). Used\n for producing canonical values for members of an equivalence class.\n For example, Decimal('32.100') and Decimal('0.321000e+2') both normalize\n to the equivalent value Decimal('32.1').\n \"\"\"\n pass"},{"col":4,"comment":"\n Return a string describing the class of the operand. The returned value\n is one of the following ten strings:\n \n * '-Infinity', indicating that the operand is negative infinity.\n * '-Normal', indicating that the operand is a negative normal number.\n * '-Subnormal', indicating that the operand is negative and subnormal.\n * '-Zero', indicating that the operand is a negative zero.\n * '+Zero', indicating that the operand is a positive zero.\n * '+Subnormal', indicating that the operand is positive and subnormal.\n * '+Normal', indicating that the operand is a positive normal number.\n * '+Infinity', indicating that the operand is positive infinity.\n * 'NaN', indicating that the operand is a quiet NaN (Not a Number).\n * 'sNaN', indicating that the operand is a signaling NaN.\n ","endLoc":793,"header":"def number_class(self, *args, **kwargs)","id":648,"name":"number_class","nodeType":"Function","startLoc":777,"text":"def number_class(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return a string describing the class of the operand. The returned value\n is one of the following ten strings:\n \n * '-Infinity', indicating that the operand is negative infinity.\n * '-Normal', indicating that the operand is a negative normal number.\n * '-Subnormal', indicating that the operand is negative and subnormal.\n * '-Zero', indicating that the operand is a negative zero.\n * '+Zero', indicating that the operand is a positive zero.\n * '+Subnormal', indicating that the operand is positive and subnormal.\n * '+Normal', indicating that the operand is a positive normal number.\n * '+Infinity', indicating that the operand is positive infinity.\n * 'NaN', indicating that the operand is a quiet NaN (Not a Number).\n * 'sNaN', indicating that the operand is a signaling NaN.\n \"\"\"\n pass"},{"col":4,"comment":"\n Return a value equal to the first operand after rounding and having the\n exponent of the second operand.\n \n >>> Decimal('1.41421356').quantize(Decimal('1.000'))\n Decimal('1.414')\n \n Unlike other operations, if the length of the coefficient after the quantize\n operation would be greater than precision, then an InvalidOperation is signaled.\n This guarantees that, unless there is an error condition, the quantized exponent\n is always equal to that of the right-hand operand.\n \n Also unlike other operations, quantize never signals Underflow, even if the\n result is subnormal and inexact.\n \n If the exponent of the second operand is larger than that of the first, then\n rounding may be necessary. In this case, the rounding mode is determined by the\n rounding argument if given, else by the given context argument; if neither\n argument is given, the rounding mode of the current thread's context is used.\n ","endLoc":816,"header":"def quantize(self, Decimal, *args, **kwargs)","id":649,"name":"quantize","nodeType":"Function","startLoc":795,"text":"def quantize(self, Decimal, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ \n \"\"\"\n Return a value equal to the first operand after rounding and having the\n exponent of the second operand.\n \n >>> Decimal('1.41421356').quantize(Decimal('1.000'))\n Decimal('1.414')\n \n Unlike other operations, if the length of the coefficient after the quantize\n operation would be greater than precision, then an InvalidOperation is signaled.\n This guarantees that, unless there is an error condition, the quantized exponent\n is always equal to that of the right-hand operand.\n \n Also unlike other operations, quantize never signals Underflow, even if the\n result is subnormal and inexact.\n \n If the exponent of the second operand is larger than that of the first, then\n rounding may be necessary. In this case, the rounding mode is determined by the\n rounding argument if given, else by the given context argument; if neither\n argument is given, the rounding mode of the current thread's context is used.\n \"\"\"\n pass"},{"col":4,"comment":"\n Return Decimal(10), the radix (base) in which the Decimal class does\n all its arithmetic. Included for compatibility with the specification.\n ","endLoc":823,"header":"def radix(self, base)","id":650,"name":"radix","nodeType":"Function","startLoc":818,"text":"def radix(self, base): # real signature unknown; restored from __doc__\n \"\"\"\n Return Decimal(10), the radix (base) in which the Decimal class does\n all its arithmetic. Included for compatibility with the specification.\n \"\"\"\n pass"},{"col":4,"comment":"\n Return the remainder from dividing self by other. This differs from\n self % other in that the sign of the remainder is chosen so as to minimize\n its absolute value. More precisely, the return value is self - n * other\n where n is the integer nearest to the exact value of self / other, and\n if two integers are equally near then the even one is chosen.\n \n If the result is zero then its sign will be the sign of self.\n ","endLoc":835,"header":"def remainder_near(self, *args, **kwargs)","id":651,"name":"remainder_near","nodeType":"Function","startLoc":825,"text":"def remainder_near(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the remainder from dividing self by other. This differs from\n self % other in that the sign of the remainder is chosen so as to minimize\n its absolute value. More precisely, the return value is self - n * other\n where n is the integer nearest to the exact value of self / other, and\n if two integers are equally near then the even one is chosen.\n \n If the result is zero then its sign will be the sign of self.\n \"\"\"\n pass"},{"col":4,"comment":"\n Return the result of rotating the digits of the first operand by an amount\n specified by the second operand. The second operand must be an integer in\n the range -precision through precision. The absolute value of the second\n operand gives the number of places to rotate. If the second operand is\n positive then rotation is to the left; otherwise rotation is to the right.\n The coefficient of the first operand is padded on the left with zeros to\n length precision if necessary. The sign and exponent of the first operand are\n unchanged.\n ","endLoc":848,"header":"def rotate(self, *args, **kwargs)","id":652,"name":"rotate","nodeType":"Function","startLoc":837,"text":"def rotate(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the result of rotating the digits of the first operand by an amount\n specified by the second operand. The second operand must be an integer in\n the range -precision through precision. The absolute value of the second\n operand gives the number of places to rotate. If the second operand is\n positive then rotation is to the left; otherwise rotation is to the right.\n The coefficient of the first operand is padded on the left with zeros to\n length precision if necessary. The sign and exponent of the first operand are\n unchanged.\n \"\"\"\n pass"},{"col":4,"comment":"\n Test whether self and other have the same exponent or whether both are NaN.\n \n This operation is unaffected by context and is quiet: no flags are changed\n and no rounding is performed. As an exception, the C version may raise\n InvalidOperation if the second operand cannot be converted exactly.\n ","endLoc":858,"header":"def same_quantum(self, *args, **kwargs)","id":653,"name":"same_quantum","nodeType":"Function","startLoc":850,"text":"def same_quantum(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Test whether self and other have the same exponent or whether both are NaN.\n \n This operation is unaffected by context and is quiet: no flags are changed\n and no rounding is performed. As an exception, the C version may raise\n InvalidOperation if the second operand cannot be converted exactly.\n \"\"\"\n pass"},{"col":4,"comment":"\n Return the first operand with the exponent adjusted the second. Equivalently,\n return the first operand multiplied by 10**other. The second operand must be\n an integer.\n ","endLoc":866,"header":"def scaleb(self, *args, **kwargs)","id":654,"name":"scaleb","nodeType":"Function","startLoc":860,"text":"def scaleb(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the first operand with the exponent adjusted the second. Equivalently,\n return the first operand multiplied by 10**other. The second operand must be\n an integer.\n \"\"\"\n pass"},{"col":4,"comment":"\n Return the result of shifting the digits of the first operand by an amount\n specified by the second operand. The second operand must be an integer in\n the range -precision through precision. The absolute value of the second\n operand gives the number of places to shift. If the second operand is\n positive, then the shift is to the left; otherwise the shift is to the\n right. Digits shifted into the coefficient are zeros. The sign and exponent\n of the first operand are unchanged.\n ","endLoc":878,"header":"def shift(self, *args, **kwargs)","id":655,"name":"shift","nodeType":"Function","startLoc":868,"text":"def shift(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the result of shifting the digits of the first operand by an amount\n specified by the second operand. The second operand must be an integer in\n the range -precision through precision. The absolute value of the second\n operand gives the number of places to shift. If the second operand is\n positive, then the shift is to the left; otherwise the shift is to the\n right. Digits shifted into the coefficient are zeros. The sign and exponent\n of the first operand are unchanged.\n \"\"\"\n pass"},{"col":4,"comment":"\n Return the square root of the argument to full precision. The result is\n correctly rounded using the ROUND_HALF_EVEN rounding mode.\n ","endLoc":885,"header":"def sqrt(self, *args, **kwargs)","id":656,"name":"sqrt","nodeType":"Function","startLoc":880,"text":"def sqrt(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Return the square root of the argument to full precision. The result is\n correctly rounded using the ROUND_HALF_EVEN rounding mode.\n \"\"\"\n pass"},{"col":4,"comment":"\n Convert to an engineering-type string. Engineering notation has an exponent\n which is a multiple of 3, so there are up to 3 digits left of the decimal\n place. For example, Decimal('123E+1') is converted to Decimal('1.23E+3').\n \n The value of context.capitals determines whether the exponent sign is lower\n or upper case. Otherwise, the context does not affect the operation.\n ","endLoc":896,"header":"def to_eng_string(self, *args, **kwargs)","id":657,"name":"to_eng_string","nodeType":"Function","startLoc":887,"text":"def to_eng_string(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Convert to an engineering-type string. Engineering notation has an exponent\n which is a multiple of 3, so there are up to 3 digits left of the decimal\n place. For example, Decimal('123E+1') is converted to Decimal('1.23E+3').\n \n The value of context.capitals determines whether the exponent sign is lower\n or upper case. Otherwise, the context does not affect the operation.\n \"\"\"\n pass"},{"col":4,"comment":"\n Identical to the to_integral_value() method. The to_integral() name has been\n kept for compatibility with older versions.\n ","endLoc":903,"header":"def to_integral(self)","id":658,"name":"to_integral","nodeType":"Function","startLoc":898,"text":"def to_integral(self): # real signature unknown; restored from __doc__\n \"\"\"\n Identical to the to_integral_value() method. The to_integral() name has been\n kept for compatibility with older versions.\n \"\"\"\n pass"},{"col":4,"comment":"\n Round to the nearest integer, signaling Inexact or Rounded as appropriate if\n rounding occurs. The rounding mode is determined by the rounding parameter\n if given, else by the given context. If neither parameter is given, then the\n rounding mode of the current default context is used.\n ","endLoc":912,"header":"def to_integral_exact(self, *args, **kwargs)","id":659,"name":"to_integral_exact","nodeType":"Function","startLoc":905,"text":"def to_integral_exact(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Round to the nearest integer, signaling Inexact or Rounded as appropriate if\n rounding occurs. The rounding mode is determined by the rounding parameter\n if given, else by the given context. If neither parameter is given, then the\n rounding mode of the current default context is used.\n \"\"\"\n pass"},{"col":4,"comment":"\n Round to the nearest integer without signaling Inexact or Rounded. The\n rounding mode is determined by the rounding parameter if given, else by\n the given context. If neither parameter is given, then the rounding mode\n of the current default context is used.\n ","endLoc":921,"header":"def to_integral_value(self, *args, **kwargs)","id":660,"name":"to_integral_value","nodeType":"Function","startLoc":914,"text":"def to_integral_value(self, *args, **kwargs): # real signature unknown\n \"\"\"\n Round to the nearest integer without signaling Inexact or Rounded. The\n rounding mode is determined by the rounding parameter if given, else by\n the given context. If neither parameter is given, then the rounding mode\n of the current default context is used.\n \"\"\"\n pass"},{"col":4,"comment":" abs(self) ","endLoc":925,"header":"def __abs__(self, *args, **kwargs)","id":661,"name":"__abs__","nodeType":"Function","startLoc":923,"text":"def __abs__(self, *args, **kwargs): # real signature unknown\n \"\"\" abs(self) \"\"\"\n pass"},{"col":4,"comment":" Return self+value. ","endLoc":929,"header":"def __add__(self, *args, **kwargs)","id":662,"name":"__add__","nodeType":"Function","startLoc":927,"text":"def __add__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self+value. \"\"\"\n pass"},{"col":4,"comment":" self != 0 ","endLoc":933,"header":"def __bool__(self, *args, **kwargs)","id":663,"name":"__bool__","nodeType":"Function","startLoc":931,"text":"def __bool__(self, *args, **kwargs): # real signature unknown\n \"\"\" self != 0 \"\"\"\n pass"},{"col":4,"comment":"null","endLoc":936,"header":"def __ceil__(self, *args, **kwargs)","id":664,"name":"__ceil__","nodeType":"Function","startLoc":935,"text":"def __ceil__(self, *args, **kwargs): # real signature unknown\n pass"},{"col":4,"comment":"null","endLoc":939,"header":"def __complex__(self, *args, **kwargs)","id":665,"name":"__complex__","nodeType":"Function","startLoc":938,"text":"def __complex__(self, *args, **kwargs): # real signature unknown\n pass"},{"col":4,"comment":"null","endLoc":942,"header":"def __copy__(self, *args, **kwargs)","id":666,"name":"__copy__","nodeType":"Function","startLoc":941,"text":"def __copy__(self, *args, **kwargs): # real signature unknown\n pass"},{"col":4,"comment":"null","endLoc":945,"header":"def __deepcopy__(self, *args, **kwargs)","id":667,"name":"__deepcopy__","nodeType":"Function","startLoc":944,"text":"def __deepcopy__(self, *args, **kwargs): # real signature unknown\n pass"},{"col":4,"comment":" Return divmod(self, value). ","endLoc":949,"header":"def __divmod__(self, *args, **kwargs)","id":668,"name":"__divmod__","nodeType":"Function","startLoc":947,"text":"def __divmod__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return divmod(self, value). \"\"\"\n pass"},{"col":4,"comment":" Return self==value. ","endLoc":953,"header":"def __eq__(self, *args, **kwargs)","id":669,"name":"__eq__","nodeType":"Function","startLoc":951,"text":"def __eq__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self==value. \"\"\"\n pass"},{"col":4,"comment":" float(self) ","endLoc":957,"header":"def __float__(self, *args, **kwargs)","id":670,"name":"__float__","nodeType":"Function","startLoc":955,"text":"def __float__(self, *args, **kwargs): # real signature unknown\n \"\"\" float(self) \"\"\"\n pass"},{"col":4,"comment":" Return self//value. ","endLoc":961,"header":"def __floordiv__(self, *args, **kwargs)","id":671,"name":"__floordiv__","nodeType":"Function","startLoc":959,"text":"def __floordiv__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self//value. \"\"\"\n pass"},{"col":4,"comment":"null","endLoc":964,"header":"def __floor__(self, *args, **kwargs)","id":672,"name":"__floor__","nodeType":"Function","startLoc":963,"text":"def __floor__(self, *args, **kwargs): # real signature unknown\n pass"},{"col":4,"comment":"null","endLoc":967,"header":"def __format__(self, *args, **kwargs)","id":673,"name":"__format__","nodeType":"Function","startLoc":966,"text":"def __format__(self, *args, **kwargs): # real signature unknown\n pass"},{"col":4,"comment":" Return getattr(self, name). ","endLoc":971,"header":"def __getattribute__(self, *args, **kwargs)","id":674,"name":"__getattribute__","nodeType":"Function","startLoc":969,"text":"def __getattribute__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return getattr(self, name). \"\"\"\n pass"},{"col":4,"comment":" Return self>=value. ","endLoc":975,"header":"def __ge__(self, *args, **kwargs)","id":675,"name":"__ge__","nodeType":"Function","startLoc":973,"text":"def __ge__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self>=value. \"\"\"\n pass"},{"col":4,"comment":" Return self>value. ","endLoc":979,"header":"def __gt__(self, *args, **kwargs)","id":676,"name":"__gt__","nodeType":"Function","startLoc":977,"text":"def __gt__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self>value. \"\"\"\n pass"},{"col":4,"comment":" Return hash(self). ","endLoc":983,"header":"def __hash__(self, *args, **kwargs)","id":677,"name":"__hash__","nodeType":"Function","startLoc":981,"text":"def __hash__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return hash(self). \"\"\"\n pass"},{"col":4,"comment":"null","endLoc":986,"header":"def __init__(self, *args, **kwargs)","id":678,"name":"__init__","nodeType":"Function","startLoc":985,"text":"def __init__(self, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ \n pass"},{"col":4,"comment":" int(self) ","endLoc":990,"header":"def __int__(self, *args, **kwargs)","id":679,"name":"__int__","nodeType":"Function","startLoc":988,"text":"def __int__(self, *args, **kwargs): # real signature unknown\n \"\"\" int(self) \"\"\"\n pass"},{"col":4,"comment":" Return self<=value. ","endLoc":994,"header":"def __le__(self, *args, **kwargs)","id":680,"name":"__le__","nodeType":"Function","startLoc":992,"text":"def __le__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self<=value. \"\"\"\n pass"},{"col":4,"comment":" Return self Self: ...\n @overload\n def __new__(cls, value: float | Decimal | str, /) -> Self: ...\n @classmethod\n def from_float(cls, f: float) -> Self: ...\n @classmethod\n def from_decimal(cls, dec: Decimal) -> Self: ...\n def limit_denominator(self, max_denominator: int = 1000000) -> Fraction: ...\n def as_integer_ratio(self) -> tuple[int, int]: ...\n if sys.version_info >= (3, 12):\n def is_integer(self) -> bool: ...\n\n @property\n def numerator(a) -> int: ...\n @property\n def denominator(a) -> int: ...\n @overload\n def __add__(a, b: int | Fraction) -> Fraction: ...\n @overload\n def __add__(a, b: float) -> float: ...\n @overload\n def __add__(a, b: complex) -> complex: ...\n @overload\n def __radd__(b, a: int | Fraction) -> Fraction: ...\n @overload\n def __radd__(b, a: float) -> float: ...\n @overload\n def __radd__(b, a: complex) -> complex: ...\n @overload\n def __sub__(a, b: int | Fraction) -> Fraction: ...\n @overload\n def __sub__(a, b: float) -> float: ...\n @overload\n def __sub__(a, b: complex) -> complex: ...\n @overload\n def __rsub__(b, a: int | Fraction) -> Fraction: ...\n @overload\n def __rsub__(b, a: float) -> float: ...\n @overload\n def __rsub__(b, a: complex) -> complex: ...\n @overload\n def __mul__(a, b: int | Fraction) -> Fraction: ...\n @overload\n def __mul__(a, b: float) -> float: ...\n @overload\n def __mul__(a, b: complex) -> complex: ...\n @overload\n def __rmul__(b, a: int | Fraction) -> Fraction: ...\n @overload\n def __rmul__(b, a: float) -> float: ...\n @overload\n def __rmul__(b, a: complex) -> complex: ...\n @overload\n def __truediv__(a, b: int | Fraction) -> Fraction: ...\n @overload\n def __truediv__(a, b: float) -> float: ...\n @overload\n def __truediv__(a, b: complex) -> complex: ...\n @overload\n def __rtruediv__(b, a: int | Fraction) -> Fraction: ...\n @overload\n def __rtruediv__(b, a: float) -> float: ...\n @overload\n def __rtruediv__(b, a: complex) -> complex: ...\n @overload\n def __floordiv__(a, b: int | Fraction) -> int: ...\n @overload\n def __floordiv__(a, b: float) -> float: ...\n @overload\n def __rfloordiv__(b, a: int | Fraction) -> int: ...\n @overload\n def __rfloordiv__(b, a: float) -> float: ...\n @overload\n def __mod__(a, b: int | Fraction) -> Fraction: ...\n @overload\n def __mod__(a, b: float) -> float: ...\n @overload\n def __rmod__(b, a: int | Fraction) -> Fraction: ...\n @overload\n def __rmod__(b, a: float) -> float: ...\n @overload\n def __divmod__(a, b: int | Fraction) -> tuple[int, Fraction]: ...\n @overload\n def __divmod__(a, b: float) -> tuple[float, Fraction]: ...\n @overload\n def __rdivmod__(a, b: int | Fraction) -> tuple[int, Fraction]: ...\n @overload\n def __rdivmod__(a, b: float) -> tuple[float, Fraction]: ...\n @overload\n def __pow__(a, b: int) -> Fraction: ...\n @overload\n def __pow__(a, b: float | Fraction) -> float: ...\n @overload\n def __pow__(a, b: complex) -> complex: ...\n @overload\n def __rpow__(b, a: float | Fraction) -> float: ...\n @overload\n def __rpow__(b, a: complex) -> complex: ...\n def __pos__(a) -> Fraction: ...\n def __neg__(a) -> Fraction: ...\n def __abs__(a) -> Fraction: ...\n def __trunc__(a) -> int: ...\n def __floor__(a) -> int: ...\n def __ceil__(a) -> int: ...\n @overload\n def __round__(self, ndigits: None = None) -> int: ...\n @overload\n def __round__(self, ndigits: int) -> Fraction: ...\n def __hash__(self) -> int: ...\n def __eq__(a, b: object) -> bool: ...\n def __lt__(a, b: _ComparableNum) -> bool: ...\n def __gt__(a, b: _ComparableNum) -> bool: ...\n def __le__(a, b: _ComparableNum) -> bool: ...\n def __ge__(a, b: _ComparableNum) -> bool: ...\n def __bool__(a) -> bool: ...\n def __copy__(self) -> Self: ...\n def __deepcopy__(self, memo: Any) -> Self: ...\n if sys.version_info >= (3, 11):\n def __int__(a, _index: Callable[[SupportsIndex], int] = ...) -> int: ...\n # Not actually defined within fractions.py, but provides more useful\n # overrides\n @property\n def real(self) -> Fraction: ...\n @property\n def imag(self) -> Literal[0]: ...\n def conjugate(self) -> Fraction: ..."},{"col":4,"comment":"null","endLoc":150,"header":"def setup(self)","id":738,"name":"setup","nodeType":"Function","startLoc":149,"text":"def setup(self):\n pass"},{"col":4,"comment":"null","endLoc":153,"header":"def teardown(self)","id":739,"name":"teardown","nodeType":"Function","startLoc":152,"text":"def teardown(self):\n pass"},{"col":4,"comment":" return list of all parent collectors up to self,\n starting from root of collection tree. ","endLoc":164,"header":"def listchain(self)","id":740,"name":"listchain","nodeType":"Function","startLoc":155,"text":"def listchain(self):\n \"\"\" return list of all parent collectors up to self,\n starting from root of collection tree. \"\"\"\n chain = []\n item = self\n while item is not None:\n chain.append(item)\n item = item.parent\n chain.reverse()\n return chain"},{"col":4,"comment":"dynamically add a marker object to the node.\n\n :type marker: ``str`` or ``pytest.mark.*`` object\n :param marker:\n ``append=True`` whether to append the marker,\n if ``False`` insert at position ``0``.\n ","endLoc":184,"header":"def add_marker(self, marker, append=True)","id":741,"name":"add_marker","nodeType":"Function","startLoc":166,"text":"def add_marker(self, marker, append=True):\n \"\"\"dynamically add a marker object to the node.\n\n :type marker: ``str`` or ``pytest.mark.*`` object\n :param marker:\n ``append=True`` whether to append the marker,\n if ``False`` insert at position ``0``.\n \"\"\"\n from _pytest.mark import MarkDecorator, MARK_GEN\n\n if isinstance(marker, six.string_types):\n marker = getattr(MARK_GEN, marker)\n elif not isinstance(marker, MarkDecorator):\n raise ValueError(\"is not a string or pytest.mark.* Marker\")\n self.keywords[marker.name] = marker\n if append:\n self.own_markers.append(marker.mark)\n else:\n self.own_markers.insert(0, marker.mark)"},{"className":"Rational","col":0,"comment":"null","endLoc":159,"id":742,"nodeType":"Class","startLoc":152,"text":"class Rational(Real):\n @property\n @abstractmethod\n def numerator(self) -> _IntegralLike: ...\n @property\n @abstractmethod\n def denominator(self) -> _IntegralLike: ...\n def __float__(self) -> float: ..."},{"col":4,"comment":"null","endLoc":122,"header":"def test_eq_attrs(self)","id":743,"name":"test_eq_attrs","nodeType":"Function","startLoc":112,"text":"def test_eq_attrs(self):\n import attr\n\n @attr.s\n class Foo(object):\n a = attr.ib()\n b = attr.ib()\n\n left = Foo(1, \"b\")\n right = Foo(1, \"c\")\n assert left == right"},{"col":4,"comment":"\n :param name: if given, filter the results by the name attribute\n\n iterate over all markers of the node\n ","endLoc":192,"header":"def iter_markers(self, name=None)","id":744,"name":"iter_markers","nodeType":"Function","startLoc":186,"text":"def iter_markers(self, name=None):\n \"\"\"\n :param name: if given, filter the results by the name attribute\n\n iterate over all markers of the node\n \"\"\"\n return (x[1] for x in self.iter_markers_with_node(name=name))"},{"className":"Real","col":0,"comment":"null","endLoc":148,"id":745,"nodeType":"Class","startLoc":108,"text":"class Real(Complex, _RealLike):\n @abstractmethod\n def __float__(self) -> float: ...\n @abstractmethod\n def __trunc__(self) -> _IntegralLike: ...\n @abstractmethod\n def __floor__(self) -> _IntegralLike: ...\n @abstractmethod\n def __ceil__(self) -> _IntegralLike: ...\n @abstractmethod\n @overload\n def __round__(self, ndigits: None = None) -> _IntegralLike: ...\n @abstractmethod\n @overload\n def __round__(self, ndigits: int) -> _RealLike: ...\n def __divmod__(self, other) -> tuple[_RealLike, _RealLike]: ...\n def __rdivmod__(self, other) -> tuple[_RealLike, _RealLike]: ...\n @abstractmethod\n def __floordiv__(self, other) -> _RealLike: ...\n @abstractmethod\n def __rfloordiv__(self, other) -> _RealLike: ...\n @abstractmethod\n def __mod__(self, other) -> _RealLike: ...\n @abstractmethod\n def __rmod__(self, other) -> _RealLike: ...\n @abstractmethod\n def __lt__(self, other) -> bool: ...\n @abstractmethod\n def __le__(self, other) -> bool: ...\n def __complex__(self) -> complex: ...\n @property\n def real(self) -> _RealLike: ...\n @property\n def imag(self) -> Literal[0]: ...\n def conjugate(self) -> _RealLike: ...\n # Not actually overridden at runtime,\n # but we override these in the stub to give them more precise return types:\n @abstractmethod\n def __pos__(self) -> _RealLike: ...\n @abstractmethod\n def __neg__(self) -> _RealLike: ..."},{"col":4,"comment":"\n :param name: if given, filter the results by the name attribute\n\n iterate over all markers of the node\n returns sequence of tuples (node, mark)\n ","endLoc":204,"header":"def iter_markers_with_node(self, name=None)","id":746,"name":"iter_markers_with_node","nodeType":"Function","startLoc":194,"text":"def iter_markers_with_node(self, name=None):\n \"\"\"\n :param name: if given, filter the results by the name attribute\n\n iterate over all markers of the node\n returns sequence of tuples (node, mark)\n \"\"\"\n for node in reversed(self.listchain()):\n for mark in node.own_markers:\n if name is None or getattr(mark, \"name\", None) == name:\n yield node, mark"},{"col":24,"endLoc":381,"id":747,"nodeType":"Lambda","startLoc":381,"text":"lambda item: item.reportinfo()[:2]"},{"className":"Complex","col":0,"comment":"null","endLoc":104,"id":748,"nodeType":"Class","startLoc":67,"text":"class Complex(Number, _ComplexLike):\n @abstractmethod\n def __complex__(self) -> complex: ...\n def __bool__(self) -> bool: ...\n @property\n @abstractmethod\n def real(self) -> _RealLike: ...\n @property\n @abstractmethod\n def imag(self) -> _RealLike: ...\n @abstractmethod\n def __add__(self, other) -> _ComplexLike: ...\n @abstractmethod\n def __radd__(self, other) -> _ComplexLike: ...\n @abstractmethod\n def __neg__(self) -> _ComplexLike: ...\n @abstractmethod\n def __pos__(self) -> _ComplexLike: ...\n def __sub__(self, other) -> _ComplexLike: ...\n def __rsub__(self, other) -> _ComplexLike: ...\n @abstractmethod\n def __mul__(self, other) -> _ComplexLike: ...\n @abstractmethod\n def __rmul__(self, other) -> _ComplexLike: ...\n @abstractmethod\n def __truediv__(self, other) -> _ComplexLike: ...\n @abstractmethod\n def __rtruediv__(self, other) -> _ComplexLike: ...\n @abstractmethod\n def __pow__(self, exponent) -> _ComplexLike: ...\n @abstractmethod\n def __rpow__(self, base) -> _ComplexLike: ...\n @abstractmethod\n def __abs__(self) -> _RealLike: ...\n @abstractmethod\n def conjugate(self) -> _ComplexLike: ...\n @abstractmethod\n def __eq__(self, other: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":433,"header":"def _genfunctions(self, name, funcobj)","id":749,"name":"_genfunctions","nodeType":"Function","startLoc":388,"text":"def _genfunctions(self, name, funcobj):\n module = self.getparent(Module).obj\n clscol = self.getparent(Class)\n cls = clscol and clscol.obj or None\n fm = self.session._fixturemanager\n\n definition = FunctionDefinition(name=name, parent=self, callobj=funcobj)\n fixtureinfo = fm.getfixtureinfo(definition, funcobj, cls)\n\n metafunc = Metafunc(\n definition, fixtureinfo, self.config, cls=cls, module=module\n )\n methods = []\n if hasattr(module, \"pytest_generate_tests\"):\n methods.append(module.pytest_generate_tests)\n if hasattr(cls, \"pytest_generate_tests\"):\n methods.append(cls().pytest_generate_tests)\n if methods:\n self.ihook.pytest_generate_tests.call_extra(\n methods, dict(metafunc=metafunc)\n )\n else:\n self.ihook.pytest_generate_tests(metafunc=metafunc)\n\n if not metafunc._calls:\n yield Function(name, parent=self, fixtureinfo=fixtureinfo)\n else:\n # add funcargs() as fixturedefs to fixtureinfo.arg2fixturedefs\n fixtures.add_funcarg_pseudo_fixture_def(self, metafunc, fm)\n\n # add_funcarg_pseudo_fixture_def may have shadowed some fixtures\n # with direct parametrization, so make sure we update what the\n # function really needs.\n fixtureinfo.prune_dependency_tree()\n\n for callspec in metafunc._calls:\n subname = \"%s[%s]\" % (name, callspec.id)\n yield Function(\n name=subname,\n parent=self,\n callspec=callspec,\n callobj=funcobj,\n fixtureinfo=fixtureinfo,\n keywords={callspec.id: True},\n originalname=name,\n )"},{"className":"Number","col":0,"comment":"null","endLoc":63,"id":750,"nodeType":"Class","startLoc":61,"text":"class Number(metaclass=ABCMeta):\n @abstractmethod\n def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":63,"header":"@abstractmethod\n def __hash__(self) -> int","id":751,"name":"__hash__","nodeType":"Function","startLoc":62,"text":"@abstractmethod\n def __hash__(self) -> int: ..."},{"className":"_ComplexLike","col":0,"comment":"null","endLoc":29,"id":752,"nodeType":"Class","startLoc":26,"text":"class _ComplexLike(Protocol):\n def __neg__(self) -> _ComplexLike: ...\n def __pos__(self) -> _ComplexLike: ...\n def __abs__(self) -> _RealLike: ..."},{"col":4,"comment":"null","endLoc":27,"header":"def __neg__(self) -> _ComplexLike","id":753,"name":"__neg__","nodeType":"Function","startLoc":27,"text":"def __neg__(self) -> _ComplexLike: ..."},{"col":4,"comment":"null","endLoc":28,"header":"def __pos__(self) -> _ComplexLike","id":754,"name":"__pos__","nodeType":"Function","startLoc":28,"text":"def __pos__(self) -> _ComplexLike: ..."},{"col":4,"comment":"null","endLoc":29,"header":"def __abs__(self) -> _RealLike","id":755,"name":"__abs__","nodeType":"Function","startLoc":29,"text":"def __abs__(self) -> _RealLike: ..."},{"col":4,"comment":"null","endLoc":69,"header":"@abstractmethod\n def __complex__(self) -> complex","id":756,"name":"__complex__","nodeType":"Function","startLoc":68,"text":"@abstractmethod\n def __complex__(self) -> complex: ..."},{"col":4,"comment":"null","endLoc":70,"header":"def __bool__(self) -> bool","id":757,"name":"__bool__","nodeType":"Function","startLoc":70,"text":"def __bool__(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":73,"header":"@property\n @abstractmethod\n def real(self) -> _RealLike","id":758,"name":"real","nodeType":"Function","startLoc":71,"text":"@property\n @abstractmethod\n def real(self) -> _RealLike: ..."},{"col":4,"comment":"null","endLoc":76,"header":"@property\n @abstractmethod\n def imag(self) -> _RealLike","id":759,"name":"imag","nodeType":"Function","startLoc":74,"text":"@property\n @abstractmethod\n def imag(self) -> _RealLike: ..."},{"col":4,"comment":"null","endLoc":78,"header":"@abstractmethod\n def __add__(self, other) -> _ComplexLike","id":760,"name":"__add__","nodeType":"Function","startLoc":77,"text":"@abstractmethod\n def __add__(self, other) -> _ComplexLike: ..."},{"col":4,"comment":"null","endLoc":80,"header":"@abstractmethod\n def __radd__(self, other) -> _ComplexLike","id":761,"name":"__radd__","nodeType":"Function","startLoc":79,"text":"@abstractmethod\n def __radd__(self, other) -> _ComplexLike: ..."},{"col":4,"comment":"null","endLoc":82,"header":"@abstractmethod\n def __neg__(self) -> _ComplexLike","id":762,"name":"__neg__","nodeType":"Function","startLoc":81,"text":"@abstractmethod\n def __neg__(self) -> _ComplexLike: ..."},{"col":4,"comment":"null","endLoc":84,"header":"@abstractmethod\n def __pos__(self) -> _ComplexLike","id":763,"name":"__pos__","nodeType":"Function","startLoc":83,"text":"@abstractmethod\n def __pos__(self) -> _ComplexLike: ..."},{"col":4,"comment":"null","endLoc":85,"header":"def __sub__(self, other) -> _ComplexLike","id":764,"name":"__sub__","nodeType":"Function","startLoc":85,"text":"def __sub__(self, other) -> _ComplexLike: ..."},{"col":4,"comment":"null","endLoc":86,"header":"def __rsub__(self, other) -> _ComplexLike","id":765,"name":"__rsub__","nodeType":"Function","startLoc":86,"text":"def __rsub__(self, other) -> _ComplexLike: ..."},{"col":4,"comment":"null","endLoc":88,"header":"@abstractmethod\n def __mul__(self, other) -> _ComplexLike","id":766,"name":"__mul__","nodeType":"Function","startLoc":87,"text":"@abstractmethod\n def __mul__(self, other) -> _ComplexLike: ..."},{"col":4,"comment":"null","endLoc":90,"header":"@abstractmethod\n def __rmul__(self, other) -> _ComplexLike","id":767,"name":"__rmul__","nodeType":"Function","startLoc":89,"text":"@abstractmethod\n def __rmul__(self, other) -> _ComplexLike: ..."},{"col":4,"comment":"null","endLoc":92,"header":"@abstractmethod\n def __truediv__(self, other) -> _ComplexLike","id":768,"name":"__truediv__","nodeType":"Function","startLoc":91,"text":"@abstractmethod\n def __truediv__(self, other) -> _ComplexLike: ..."},{"col":4,"comment":"null","endLoc":94,"header":"@abstractmethod\n def __rtruediv__(self, other) -> _ComplexLike","id":769,"name":"__rtruediv__","nodeType":"Function","startLoc":93,"text":"@abstractmethod\n def __rtruediv__(self, other) -> _ComplexLike: ..."},{"col":4,"comment":"null","endLoc":96,"header":"@abstractmethod\n def __pow__(self, exponent) -> _ComplexLike","id":770,"name":"__pow__","nodeType":"Function","startLoc":95,"text":"@abstractmethod\n def __pow__(self, exponent) -> _ComplexLike: ..."},{"col":4,"comment":"null","endLoc":98,"header":"@abstractmethod\n def __rpow__(self, base) -> _ComplexLike","id":771,"name":"__rpow__","nodeType":"Function","startLoc":97,"text":"@abstractmethod\n def __rpow__(self, base) -> _ComplexLike: ..."},{"col":4,"comment":"null","endLoc":100,"header":"@abstractmethod\n def __abs__(self) -> _RealLike","id":772,"name":"__abs__","nodeType":"Function","startLoc":99,"text":"@abstractmethod\n def __abs__(self) -> _RealLike: ..."},{"col":4,"comment":"null","endLoc":102,"header":"@abstractmethod\n def conjugate(self) -> _ComplexLike","id":773,"name":"conjugate","nodeType":"Function","startLoc":101,"text":"@abstractmethod\n def conjugate(self) -> _ComplexLike: ..."},{"col":4,"comment":"null","endLoc":104,"header":"@abstractmethod\n def __eq__(self, other: object) -> bool","id":774,"name":"__eq__","nodeType":"Function","startLoc":103,"text":"@abstractmethod\n def __eq__(self, other: object) -> bool: ..."},{"className":"_RealLike","col":0,"comment":"null","endLoc":41,"id":775,"nodeType":"Class","startLoc":33,"text":"class _RealLike(_ComplexLike, Protocol):\n def __trunc__(self) -> _IntegralLike: ...\n def __floor__(self) -> _IntegralLike: ...\n def __ceil__(self) -> _IntegralLike: ...\n def __float__(self) -> float: ...\n # Overridden from `_ComplexLike`\n # for a more precise return type:\n def __neg__(self) -> _RealLike: ...\n def __pos__(self) -> _RealLike: ..."},{"col":4,"comment":"null","endLoc":34,"header":"def __trunc__(self) -> _IntegralLike","id":776,"name":"__trunc__","nodeType":"Function","startLoc":34,"text":"def __trunc__(self) -> _IntegralLike: ..."},{"col":4,"comment":" get the next parent node (including ourself)\n which is an instance of the given class","endLoc":239,"header":"def getparent(self, cls)","id":777,"name":"getparent","nodeType":"Function","startLoc":233,"text":"def getparent(self, cls):\n \"\"\" get the next parent node (including ourself)\n which is an instance of the given class\"\"\"\n current = self\n while current and not isinstance(current, cls):\n current = current.parent\n return current"},{"col":4,"comment":"null","endLoc":35,"header":"def __floor__(self) -> _IntegralLike","id":778,"name":"__floor__","nodeType":"Function","startLoc":35,"text":"def __floor__(self) -> _IntegralLike: ..."},{"col":4,"comment":"null","endLoc":36,"header":"def __ceil__(self) -> _IntegralLike","id":779,"name":"__ceil__","nodeType":"Function","startLoc":36,"text":"def __ceil__(self) -> _IntegralLike: ..."},{"col":4,"comment":"null","endLoc":37,"header":"def __float__(self) -> float","id":780,"name":"__float__","nodeType":"Function","startLoc":37,"text":"def __float__(self) -> float: ..."},{"col":4,"comment":"null","endLoc":40,"header":"def __neg__(self) -> _RealLike","id":781,"name":"__neg__","nodeType":"Function","startLoc":40,"text":"def __neg__(self) -> _RealLike: ..."},{"col":4,"comment":"null","endLoc":41,"header":"def __pos__(self) -> _RealLike","id":782,"name":"__pos__","nodeType":"Function","startLoc":41,"text":"def __pos__(self) -> _RealLike: ..."},{"col":4,"comment":"null","endLoc":110,"header":"@abstractmethod\n def __float__(self) -> float","id":783,"name":"__float__","nodeType":"Function","startLoc":109,"text":"@abstractmethod\n def __float__(self) -> float: ..."},{"col":4,"comment":"null","endLoc":112,"header":"@abstractmethod\n def __trunc__(self) -> _IntegralLike","id":784,"name":"__trunc__","nodeType":"Function","startLoc":111,"text":"@abstractmethod\n def __trunc__(self) -> _IntegralLike: ..."},{"col":4,"comment":"null","endLoc":114,"header":"@abstractmethod\n def __floor__(self) -> _IntegralLike","id":785,"name":"__floor__","nodeType":"Function","startLoc":113,"text":"@abstractmethod\n def __floor__(self) -> _IntegralLike: ..."},{"col":4,"comment":"null","endLoc":116,"header":"@abstractmethod\n def __ceil__(self) -> _IntegralLike","id":786,"name":"__ceil__","nodeType":"Function","startLoc":115,"text":"@abstractmethod\n def __ceil__(self) -> _IntegralLike: ..."},{"col":4,"comment":"null","endLoc":119,"header":"@abstractmethod\n @overload\n def __round__(self, ndigits: None = None) -> _IntegralLike","id":787,"name":"__round__","nodeType":"Function","startLoc":117,"text":"@abstractmethod\n @overload\n def __round__(self, ndigits: None = None) -> _IntegralLike: ..."},{"col":4,"comment":"null","endLoc":122,"header":"@abstractmethod\n @overload\n def __round__(self, ndigits: int) -> _RealLike","id":788,"name":"__round__","nodeType":"Function","startLoc":120,"text":"@abstractmethod\n @overload\n def __round__(self, ndigits: int) -> _RealLike: ..."},{"col":4,"comment":"null","endLoc":123,"header":"def __divmod__(self, other) -> tuple[_RealLike, _RealLike]","id":789,"name":"__divmod__","nodeType":"Function","startLoc":123,"text":"def __divmod__(self, other) -> tuple[_RealLike, _RealLike]: ..."},{"col":4,"comment":"null","endLoc":124,"header":"def __rdivmod__(self, other) -> tuple[_RealLike, _RealLike]","id":790,"name":"__rdivmod__","nodeType":"Function","startLoc":124,"text":"def __rdivmod__(self, other) -> tuple[_RealLike, _RealLike]: ..."},{"col":4,"comment":"null","endLoc":126,"header":"@abstractmethod\n def __floordiv__(self, other) -> _RealLike","id":791,"name":"__floordiv__","nodeType":"Function","startLoc":125,"text":"@abstractmethod\n def __floordiv__(self, other) -> _RealLike: ..."},{"col":4,"comment":"null","endLoc":128,"header":"@abstractmethod\n def __rfloordiv__(self, other) -> _RealLike","id":792,"name":"__rfloordiv__","nodeType":"Function","startLoc":127,"text":"@abstractmethod\n def __rfloordiv__(self, other) -> _RealLike: ..."},{"col":4,"comment":"null","endLoc":130,"header":"@abstractmethod\n def __mod__(self, other) -> _RealLike","id":793,"name":"__mod__","nodeType":"Function","startLoc":129,"text":"@abstractmethod\n def __mod__(self, other) -> _RealLike: ..."},{"col":4,"comment":"null","endLoc":132,"header":"@abstractmethod\n def __rmod__(self, other) -> _RealLike","id":794,"name":"__rmod__","nodeType":"Function","startLoc":131,"text":"@abstractmethod\n def __rmod__(self, other) -> _RealLike: ..."},{"col":4,"comment":"null","endLoc":134,"header":"@abstractmethod\n def __lt__(self, other) -> bool","id":795,"name":"__lt__","nodeType":"Function","startLoc":133,"text":"@abstractmethod\n def __lt__(self, other) -> bool: ..."},{"col":4,"comment":"null","endLoc":136,"header":"@abstractmethod\n def __le__(self, other) -> bool","id":796,"name":"__le__","nodeType":"Function","startLoc":135,"text":"@abstractmethod\n def __le__(self, other) -> bool: ..."},{"col":4,"comment":"null","endLoc":137,"header":"def __complex__(self) -> complex","id":797,"name":"__complex__","nodeType":"Function","startLoc":137,"text":"def __complex__(self) -> complex: ..."},{"col":4,"comment":"null","endLoc":139,"header":"@property\n def real(self) -> _RealLike","id":798,"name":"real","nodeType":"Function","startLoc":138,"text":"@property\n def real(self) -> _RealLike: ..."},{"col":4,"comment":"null","endLoc":141,"header":"@property\n def imag(self) -> Literal[0]","id":799,"name":"imag","nodeType":"Function","startLoc":140,"text":"@property\n def imag(self) -> Literal[0]: ..."},{"col":4,"comment":"null","endLoc":142,"header":"def conjugate(self) -> _RealLike","id":800,"name":"conjugate","nodeType":"Function","startLoc":142,"text":"def conjugate(self) -> _RealLike: ..."},{"col":4,"comment":"null","endLoc":146,"header":"@abstractmethod\n def __pos__(self) -> _RealLike","id":801,"name":"__pos__","nodeType":"Function","startLoc":145,"text":"@abstractmethod\n def __pos__(self) -> _RealLike: ..."},{"col":4,"comment":"null","endLoc":148,"header":"@abstractmethod\n def __neg__(self) -> _RealLike","id":802,"name":"__neg__","nodeType":"Function","startLoc":147,"text":"@abstractmethod\n def __neg__(self) -> _RealLike: ..."},{"col":4,"comment":"null","endLoc":155,"header":"@property\n @abstractmethod\n def numerator(self) -> _IntegralLike","id":803,"name":"numerator","nodeType":"Function","startLoc":153,"text":"@property\n @abstractmethod\n def numerator(self) -> _IntegralLike: ..."},{"col":4,"comment":"null","endLoc":158,"header":"@property\n @abstractmethod\n def denominator(self) -> _IntegralLike","id":804,"name":"denominator","nodeType":"Function","startLoc":156,"text":"@property\n @abstractmethod\n def denominator(self) -> _IntegralLike: ..."},{"col":4,"comment":"null","endLoc":159,"header":"def __float__(self) -> float","id":805,"name":"__float__","nodeType":"Function","startLoc":159,"text":"def __float__(self) -> float: ..."},{"col":4,"comment":"null","endLoc":25,"header":"@overload\n def __new__(cls, numerator: int | Rational = 0, denominator: int | Rational | None = None) -> Self","id":806,"name":"__new__","nodeType":"Function","startLoc":24,"text":"@overload\n def __new__(cls, numerator: int | Rational = 0, denominator: int | Rational | None = None) -> Self: ..."},{"col":4,"comment":"null","endLoc":27,"header":"@overload\n def __new__(cls, value: float | Decimal | str, /) -> Self","id":807,"name":"__new__","nodeType":"Function","startLoc":26,"text":"@overload\n def __new__(cls, value: float | Decimal | str, /) -> Self: ..."},{"col":4,"comment":"null","endLoc":29,"header":"@classmethod\n def from_float(cls, f: float) -> Self","id":808,"name":"from_float","nodeType":"Function","startLoc":28,"text":"@classmethod\n def from_float(cls, f: float) -> Self: ..."},{"col":4,"comment":"null","endLoc":31,"header":"@classmethod\n def from_decimal(cls, dec: Decimal) -> Self","id":809,"name":"from_decimal","nodeType":"Function","startLoc":30,"text":"@classmethod\n def from_decimal(cls, dec: Decimal) -> Self: ..."},{"col":4,"comment":"null","endLoc":32,"header":"def limit_denominator(self, max_denominator: int = 1000000) -> Fraction","id":810,"name":"limit_denominator","nodeType":"Function","startLoc":32,"text":"def limit_denominator(self, max_denominator: int = 1000000) -> Fraction: ..."},{"col":4,"comment":"null","endLoc":33,"header":"def as_integer_ratio(self) -> tuple[int, int]","id":811,"name":"as_integer_ratio","nodeType":"Function","startLoc":33,"text":"def as_integer_ratio(self) -> tuple[int, int]: ..."},{"col":4,"comment":"null","endLoc":38,"header":"@property\n def numerator(a) -> int","id":812,"name":"numerator","nodeType":"Function","startLoc":37,"text":"@property\n def numerator(a) -> int: ..."},{"col":4,"comment":"null","endLoc":40,"header":"@property\n def denominator(a) -> int","id":813,"name":"denominator","nodeType":"Function","startLoc":39,"text":"@property\n def denominator(a) -> int: ..."},{"col":4,"comment":"null","endLoc":42,"header":"@overload\n def __add__(a, b: int | Fraction) -> Fraction","id":814,"name":"__add__","nodeType":"Function","startLoc":41,"text":"@overload\n def __add__(a, b: int | Fraction) -> Fraction: ..."},{"col":4,"comment":"null","endLoc":44,"header":"@overload\n def __add__(a, b: float) -> float","id":815,"name":"__add__","nodeType":"Function","startLoc":43,"text":"@overload\n def __add__(a, b: float) -> float: ..."},{"col":4,"comment":"null","endLoc":46,"header":"@overload\n def __add__(a, b: complex) -> complex","id":816,"name":"__add__","nodeType":"Function","startLoc":45,"text":"@overload\n def __add__(a, b: complex) -> complex: ..."},{"col":4,"comment":"null","endLoc":48,"header":"@overload\n def __radd__(b, a: int | Fraction) -> Fraction","id":817,"name":"__radd__","nodeType":"Function","startLoc":47,"text":"@overload\n def __radd__(b, a: int | Fraction) -> Fraction: ..."},{"col":4,"comment":"null","endLoc":50,"header":"@overload\n def __radd__(b, a: float) -> float","id":818,"name":"__radd__","nodeType":"Function","startLoc":49,"text":"@overload\n def __radd__(b, a: float) -> float: ..."},{"col":4,"comment":"null","endLoc":52,"header":"@overload\n def __radd__(b, a: complex) -> complex","id":819,"name":"__radd__","nodeType":"Function","startLoc":51,"text":"@overload\n def __radd__(b, a: complex) -> complex: ..."},{"col":4,"comment":"null","endLoc":54,"header":"@overload\n def __sub__(a, b: int | Fraction) -> Fraction","id":820,"name":"__sub__","nodeType":"Function","startLoc":53,"text":"@overload\n def __sub__(a, b: int | Fraction) -> Fraction: ..."},{"col":4,"comment":"null","endLoc":56,"header":"@overload\n def __sub__(a, b: float) -> float","id":821,"name":"__sub__","nodeType":"Function","startLoc":55,"text":"@overload\n def __sub__(a, b: float) -> float: ..."},{"col":4,"comment":"null","endLoc":58,"header":"@overload\n def __sub__(a, b: complex) -> complex","id":822,"name":"__sub__","nodeType":"Function","startLoc":57,"text":"@overload\n def __sub__(a, b: complex) -> complex: ..."},{"col":4,"comment":"null","endLoc":60,"header":"@overload\n def __rsub__(b, a: int | Fraction) -> Fraction","id":823,"name":"__rsub__","nodeType":"Function","startLoc":59,"text":"@overload\n def __rsub__(b, a: int | Fraction) -> Fraction: ..."},{"col":4,"comment":"null","endLoc":62,"header":"@overload\n def __rsub__(b, a: float) -> float","id":824,"name":"__rsub__","nodeType":"Function","startLoc":61,"text":"@overload\n def __rsub__(b, a: float) -> float: ..."},{"col":4,"comment":"null","endLoc":64,"header":"@overload\n def __rsub__(b, a: complex) -> complex","id":825,"name":"__rsub__","nodeType":"Function","startLoc":63,"text":"@overload\n def __rsub__(b, a: complex) -> complex: ..."},{"col":4,"comment":"null","endLoc":66,"header":"@overload\n def __mul__(a, b: int | Fraction) -> Fraction","id":826,"name":"__mul__","nodeType":"Function","startLoc":65,"text":"@overload\n def __mul__(a, b: int | Fraction) -> Fraction: ..."},{"col":4,"comment":"null","endLoc":68,"header":"@overload\n def __mul__(a, b: float) -> float","id":827,"name":"__mul__","nodeType":"Function","startLoc":67,"text":"@overload\n def __mul__(a, b: float) -> float: ..."},{"col":4,"comment":"null","endLoc":70,"header":"@overload\n def __mul__(a, b: complex) -> complex","id":828,"name":"__mul__","nodeType":"Function","startLoc":69,"text":"@overload\n def __mul__(a, b: complex) -> complex: ..."},{"col":4,"comment":"null","endLoc":72,"header":"@overload\n def __rmul__(b, a: int | Fraction) -> Fraction","id":829,"name":"__rmul__","nodeType":"Function","startLoc":71,"text":"@overload\n def __rmul__(b, a: int | Fraction) -> Fraction: ..."},{"col":4,"comment":"null","endLoc":74,"header":"@overload\n def __rmul__(b, a: float) -> float","id":830,"name":"__rmul__","nodeType":"Function","startLoc":73,"text":"@overload\n def __rmul__(b, a: float) -> float: ..."},{"col":4,"comment":"null","endLoc":76,"header":"@overload\n def __rmul__(b, a: complex) -> complex","id":831,"name":"__rmul__","nodeType":"Function","startLoc":75,"text":"@overload\n def __rmul__(b, a: complex) -> complex: ..."},{"col":4,"comment":"null","endLoc":78,"header":"@overload\n def __truediv__(a, b: int | Fraction) -> Fraction","id":832,"name":"__truediv__","nodeType":"Function","startLoc":77,"text":"@overload\n def __truediv__(a, b: int | Fraction) -> Fraction: ..."},{"col":4,"comment":"null","endLoc":80,"header":"@overload\n def __truediv__(a, b: float) -> float","id":833,"name":"__truediv__","nodeType":"Function","startLoc":79,"text":"@overload\n def __truediv__(a, b: float) -> float: ..."},{"col":4,"comment":"null","endLoc":82,"header":"@overload\n def __truediv__(a, b: complex) -> complex","id":834,"name":"__truediv__","nodeType":"Function","startLoc":81,"text":"@overload\n def __truediv__(a, b: complex) -> complex: ..."},{"col":4,"comment":"null","endLoc":84,"header":"@overload\n def __rtruediv__(b, a: int | Fraction) -> Fraction","id":835,"name":"__rtruediv__","nodeType":"Function","startLoc":83,"text":"@overload\n def __rtruediv__(b, a: int | Fraction) -> Fraction: ..."},{"col":4,"comment":"null","endLoc":86,"header":"@overload\n def __rtruediv__(b, a: float) -> float","id":836,"name":"__rtruediv__","nodeType":"Function","startLoc":85,"text":"@overload\n def __rtruediv__(b, a: float) -> float: ..."},{"className":"TestRaises","col":0,"comment":"null","endLoc":189,"id":837,"nodeType":"Class","startLoc":165,"text":"class TestRaises(object):\n def test_raises(self):\n s = \"qwe\"\n raises(TypeError, int, s)\n\n def test_raises_doesnt(self):\n raises(IOError, int, \"3\")\n\n def test_raise(self):\n raise ValueError(\"demo error\")\n\n def test_tupleerror(self):\n a, b = [1] # NOQA\n\n def test_reinterpret_fails_with_print_for_the_fun_of_it(self):\n items = [1, 2, 3]\n print(\"items is %r\" % items)\n a, b = items.pop()\n\n def test_some_error(self):\n if namenotexi: # NOQA\n pass\n\n def func1(self):\n assert 41 == 42"},{"col":4,"comment":"null","endLoc":88,"header":"@overload\n def __rtruediv__(b, a: complex) -> complex","id":838,"name":"__rtruediv__","nodeType":"Function","startLoc":87,"text":"@overload\n def __rtruediv__(b, a: complex) -> complex: ..."},{"col":4,"comment":"null","endLoc":90,"header":"@overload\n def __floordiv__(a, b: int | Fraction) -> int","id":839,"name":"__floordiv__","nodeType":"Function","startLoc":89,"text":"@overload\n def __floordiv__(a, b: int | Fraction) -> int: ..."},{"col":4,"comment":"null","endLoc":92,"header":"@overload\n def __floordiv__(a, b: float) -> float","id":840,"name":"__floordiv__","nodeType":"Function","startLoc":91,"text":"@overload\n def __floordiv__(a, b: float) -> float: ..."},{"col":4,"comment":"null","endLoc":94,"header":"@overload\n def __rfloordiv__(b, a: int | Fraction) -> int","id":841,"name":"__rfloordiv__","nodeType":"Function","startLoc":93,"text":"@overload\n def __rfloordiv__(b, a: int | Fraction) -> int: ..."},{"col":4,"comment":"null","endLoc":96,"header":"@overload\n def __rfloordiv__(b, a: float) -> float","id":842,"name":"__rfloordiv__","nodeType":"Function","startLoc":95,"text":"@overload\n def __rfloordiv__(b, a: float) -> float: ..."},{"col":4,"comment":"null","endLoc":98,"header":"@overload\n def __mod__(a, b: int | Fraction) -> Fraction","id":843,"name":"__mod__","nodeType":"Function","startLoc":97,"text":"@overload\n def __mod__(a, b: int | Fraction) -> Fraction: ..."},{"col":4,"comment":"null","endLoc":100,"header":"@overload\n def __mod__(a, b: float) -> float","id":844,"name":"__mod__","nodeType":"Function","startLoc":99,"text":"@overload\n def __mod__(a, b: float) -> float: ..."},{"col":4,"comment":"null","endLoc":102,"header":"@overload\n def __rmod__(b, a: int | Fraction) -> Fraction","id":845,"name":"__rmod__","nodeType":"Function","startLoc":101,"text":"@overload\n def __rmod__(b, a: int | Fraction) -> Fraction: ..."},{"col":4,"comment":"null","endLoc":104,"header":"@overload\n def __rmod__(b, a: float) -> float","id":846,"name":"__rmod__","nodeType":"Function","startLoc":103,"text":"@overload\n def __rmod__(b, a: float) -> float: ..."},{"col":4,"comment":"null","endLoc":106,"header":"@overload\n def __divmod__(a, b: int | Fraction) -> tuple[int, Fraction]","id":847,"name":"__divmod__","nodeType":"Function","startLoc":105,"text":"@overload\n def __divmod__(a, b: int | Fraction) -> tuple[int, Fraction]: ..."},{"col":4,"comment":"null","endLoc":108,"header":"@overload\n def __divmod__(a, b: float) -> tuple[float, Fraction]","id":848,"name":"__divmod__","nodeType":"Function","startLoc":107,"text":"@overload\n def __divmod__(a, b: float) -> tuple[float, Fraction]: ..."},{"col":4,"comment":"null","endLoc":110,"header":"@overload\n def __rdivmod__(a, b: int | Fraction) -> tuple[int, Fraction]","id":849,"name":"__rdivmod__","nodeType":"Function","startLoc":109,"text":"@overload\n def __rdivmod__(a, b: int | Fraction) -> tuple[int, Fraction]: ..."},{"col":4,"comment":"null","endLoc":112,"header":"@overload\n def __rdivmod__(a, b: float) -> tuple[float, Fraction]","id":850,"name":"__rdivmod__","nodeType":"Function","startLoc":111,"text":"@overload\n def __rdivmod__(a, b: float) -> tuple[float, Fraction]: ..."},{"col":4,"comment":"null","endLoc":114,"header":"@overload\n def __pow__(a, b: int) -> Fraction","id":851,"name":"__pow__","nodeType":"Function","startLoc":113,"text":"@overload\n def __pow__(a, b: int) -> Fraction: ..."},{"col":4,"comment":"null","endLoc":116,"header":"@overload\n def __pow__(a, b: float | Fraction) -> float","id":852,"name":"__pow__","nodeType":"Function","startLoc":115,"text":"@overload\n def __pow__(a, b: float | Fraction) -> float: ..."},{"col":4,"comment":"null","endLoc":118,"header":"@overload\n def __pow__(a, b: complex) -> complex","id":853,"name":"__pow__","nodeType":"Function","startLoc":117,"text":"@overload\n def __pow__(a, b: complex) -> complex: ..."},{"col":4,"comment":"null","endLoc":120,"header":"@overload\n def __rpow__(b, a: float | Fraction) -> float","id":854,"name":"__rpow__","nodeType":"Function","startLoc":119,"text":"@overload\n def __rpow__(b, a: float | Fraction) -> float: ..."},{"col":4,"comment":"null","endLoc":122,"header":"@overload\n def __rpow__(b, a: complex) -> complex","id":855,"name":"__rpow__","nodeType":"Function","startLoc":121,"text":"@overload\n def __rpow__(b, a: complex) -> complex: ..."},{"col":4,"comment":"null","endLoc":123,"header":"def __pos__(a) -> Fraction","id":856,"name":"__pos__","nodeType":"Function","startLoc":123,"text":"def __pos__(a) -> Fraction: ..."},{"col":4,"comment":"null","endLoc":124,"header":"def __neg__(a) -> Fraction","id":857,"name":"__neg__","nodeType":"Function","startLoc":124,"text":"def __neg__(a) -> Fraction: ..."},{"col":4,"comment":"null","endLoc":125,"header":"def __abs__(a) -> Fraction","id":858,"name":"__abs__","nodeType":"Function","startLoc":125,"text":"def __abs__(a) -> Fraction: ..."},{"col":4,"comment":"null","endLoc":126,"header":"def __trunc__(a) -> int","id":859,"name":"__trunc__","nodeType":"Function","startLoc":126,"text":"def __trunc__(a) -> int: ..."},{"col":4,"comment":"null","endLoc":127,"header":"def __floor__(a) -> int","id":860,"name":"__floor__","nodeType":"Function","startLoc":127,"text":"def __floor__(a) -> int: ..."},{"col":4,"comment":"null","endLoc":128,"header":"def __ceil__(a) -> int","id":861,"name":"__ceil__","nodeType":"Function","startLoc":128,"text":"def __ceil__(a) -> int: ..."},{"col":4,"comment":"null","endLoc":130,"header":"@overload\n def __round__(self, ndigits: None = None) -> int","id":862,"name":"__round__","nodeType":"Function","startLoc":129,"text":"@overload\n def __round__(self, ndigits: None = None) -> int: ..."},{"col":4,"comment":"null","endLoc":132,"header":"@overload\n def __round__(self, ndigits: int) -> Fraction","id":863,"name":"__round__","nodeType":"Function","startLoc":131,"text":"@overload\n def __round__(self, ndigits: int) -> Fraction: ..."},{"col":4,"comment":"null","endLoc":133,"header":"def __hash__(self) -> int","id":864,"name":"__hash__","nodeType":"Function","startLoc":133,"text":"def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":134,"header":"def __eq__(a, b: object) -> bool","id":865,"name":"__eq__","nodeType":"Function","startLoc":134,"text":"def __eq__(a, b: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":135,"header":"def __lt__(a, b: _ComparableNum) -> bool","id":866,"name":"__lt__","nodeType":"Function","startLoc":135,"text":"def __lt__(a, b: _ComparableNum) -> bool: ..."},{"col":4,"comment":"null","endLoc":136,"header":"def __gt__(a, b: _ComparableNum) -> bool","id":867,"name":"__gt__","nodeType":"Function","startLoc":136,"text":"def __gt__(a, b: _ComparableNum) -> bool: ..."},{"col":4,"comment":"null","endLoc":137,"header":"def __le__(a, b: _ComparableNum) -> bool","id":868,"name":"__le__","nodeType":"Function","startLoc":137,"text":"def __le__(a, b: _ComparableNum) -> bool: ..."},{"col":4,"comment":"null","endLoc":138,"header":"def __ge__(a, b: _ComparableNum) -> bool","id":869,"name":"__ge__","nodeType":"Function","startLoc":138,"text":"def __ge__(a, b: _ComparableNum) -> bool: ..."},{"col":4,"comment":"null","endLoc":139,"header":"def __bool__(a) -> bool","id":870,"name":"__bool__","nodeType":"Function","startLoc":139,"text":"def __bool__(a) -> bool: ..."},{"col":4,"comment":"null","endLoc":140,"header":"def __copy__(self) -> Self","id":871,"name":"__copy__","nodeType":"Function","startLoc":140,"text":"def __copy__(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":141,"header":"def __deepcopy__(self, memo: Any) -> Self","id":872,"name":"__deepcopy__","nodeType":"Function","startLoc":141,"text":"def __deepcopy__(self, memo: Any) -> Self: ..."},{"col":4,"comment":"null","endLoc":147,"header":"@property\n def real(self) -> Fraction","id":873,"name":"real","nodeType":"Function","startLoc":146,"text":"@property\n def real(self) -> Fraction: ..."},{"col":4,"comment":"null","endLoc":149,"header":"@property\n def imag(self) -> Literal[0]","id":874,"name":"imag","nodeType":"Function","startLoc":148,"text":"@property\n def imag(self) -> Literal[0]: ..."},{"col":4,"comment":"null","endLoc":150,"header":"def conjugate(self) -> Fraction","id":875,"name":"conjugate","nodeType":"Function","startLoc":150,"text":"def conjugate(self) -> Fraction: ..."},{"col":4,"comment":"null","endLoc":168,"header":"def test_raises(self)","id":876,"name":"test_raises","nodeType":"Function","startLoc":166,"text":"def test_raises(self):\n s = \"qwe\"\n raises(TypeError, int, s)"},{"col":4,"comment":"null","endLoc":171,"header":"def test_raises_doesnt(self)","id":877,"name":"test_raises_doesnt","nodeType":"Function","startLoc":170,"text":"def test_raises_doesnt(self):\n raises(IOError, int, \"3\")"},{"col":4,"comment":"null","endLoc":174,"header":"def test_raise(self)","id":878,"name":"test_raise","nodeType":"Function","startLoc":173,"text":"def test_raise(self):\n raise ValueError(\"demo error\")"},{"col":4,"comment":"null","endLoc":684,"header":"@overload\n def get(self, key: _KT, /) -> _VT_co | None","id":879,"name":"get","nodeType":"Function","startLoc":683,"text":"@overload\n def get(self, key: _KT, /) -> _VT_co | None: ..."},{"col":4,"comment":"null","endLoc":177,"header":"def test_tupleerror(self)","id":880,"name":"test_tupleerror","nodeType":"Function","startLoc":176,"text":"def test_tupleerror(self):\n a, b = [1] # NOQA"},{"col":4,"comment":"null","endLoc":182,"header":"def test_reinterpret_fails_with_print_for_the_fun_of_it(self)","id":881,"name":"test_reinterpret_fails_with_print_for_the_fun_of_it","nodeType":"Function","startLoc":179,"text":"def test_reinterpret_fails_with_print_for_the_fun_of_it(self):\n items = [1, 2, 3]\n print(\"items is %r\" % items)\n a, b = items.pop()"},{"col":0,"comment":" Same as a == b. ","endLoc":48,"header":"def eq(*args, **kwargs)","id":882,"name":"eq","nodeType":"Function","startLoc":46,"text":"def eq(*args, **kwargs): # real signature unknown\n \"\"\" Same as a == b. \"\"\"\n pass"},{"col":4,"comment":"null","endLoc":1439,"header":"def __init__(\n self,\n name,\n parent,\n args=None,\n config=None,\n callspec=None,\n callobj=NOTSET,\n keywords=None,\n session=None,\n fixtureinfo=None,\n originalname=None,\n )","id":883,"name":"__init__","nodeType":"Function","startLoc":1380,"text":"def __init__(\n self,\n name,\n parent,\n args=None,\n config=None,\n callspec=None,\n callobj=NOTSET,\n keywords=None,\n session=None,\n fixtureinfo=None,\n originalname=None,\n ):\n super(Function, self).__init__(name, parent, config=config, session=session)\n self._args = args\n if callobj is not NOTSET:\n self.obj = callobj\n\n self.keywords.update(self.obj.__dict__)\n self.own_markers.extend(get_unpacked_marks(self.obj))\n if callspec:\n self.callspec = callspec\n # this is total hostile and a mess\n # keywords are broken by design by now\n # this will be redeemed later\n for mark in callspec.marks:\n # feel free to cry, this was broken for years before\n # and keywords cant fix it per design\n self.keywords[mark.name] = mark\n self.own_markers.extend(normalize_mark_list(callspec.marks))\n if keywords:\n self.keywords.update(keywords)\n\n # todo: this is a hell of a hack\n # https://github.com/pytest-dev/pytest/issues/4569\n\n self.keywords.update(\n dict.fromkeys(\n [\n mark.name\n for mark in self.iter_markers()\n if mark.name not in self.keywords\n ],\n True,\n )\n )\n\n if fixtureinfo is None:\n fixtureinfo = self.session._fixturemanager.getfixtureinfo(\n self, self.obj, self.cls, funcargs=True\n )\n self._fixtureinfo = fixtureinfo\n self.fixturenames = fixtureinfo.names_closure\n self._initrequest()\n\n #: original function name, without any decorations (for example\n #: parametrization adds a ``\"[...]\"`` suffix to function names).\n #:\n #: .. versionadded:: 3.0\n self.originalname = originalname"},{"col":0,"comment":" Same as a != b. ","endLoc":184,"header":"def ne(*args, **kwargs)","id":884,"name":"ne","nodeType":"Function","startLoc":182,"text":"def ne(*args, **kwargs): # real signature unknown\n \"\"\" Same as a != b. \"\"\"\n pass"},{"fileName":"junitxml.py","filePath":"src/_pytest","id":885,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"\n report test results in JUnit-XML format,\n for use with Jenkins and build integration servers.\n\n\nBased on initial code from Ross Lawley.\n\nOutput conforms to https://github.com/jenkinsci/xunit-plugin/blob/master/\nsrc/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\nimport os\nimport re\nimport sys\nimport time\n\nimport py\nimport six\n\nimport pytest\nfrom _pytest import nodes\nfrom _pytest.config import filename_arg\n\n# Python 2.X and 3.X compatibility\nif sys.version_info[0] < 3:\n from codecs import open\n\n\nclass Junit(py.xml.Namespace):\n pass\n\n\n# We need to get the subset of the invalid unicode ranges according to\n# XML 1.0 which are valid in this python build. Hence we calculate\n# this dynamically instead of hardcoding it. The spec range of valid\n# chars is: Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]\n# | [#x10000-#x10FFFF]\n_legal_chars = (0x09, 0x0A, 0x0D)\n_legal_ranges = ((0x20, 0x7E), (0x80, 0xD7FF), (0xE000, 0xFFFD), (0x10000, 0x10FFFF))\n_legal_xml_re = [\n u\"%s-%s\" % (six.unichr(low), six.unichr(high))\n for (low, high) in _legal_ranges\n if low < sys.maxunicode\n]\n_legal_xml_re = [six.unichr(x) for x in _legal_chars] + _legal_xml_re\nillegal_xml_re = re.compile(u\"[^%s]\" % u\"\".join(_legal_xml_re))\ndel _legal_chars\ndel _legal_ranges\ndel _legal_xml_re\n\n_py_ext_re = re.compile(r\"\\.py$\")\n\n\ndef bin_xml_escape(arg):\n def repl(matchobj):\n i = ord(matchobj.group())\n if i <= 0xFF:\n return u\"#x%02X\" % i\n else:\n return u\"#x%04X\" % i\n\n return py.xml.raw(illegal_xml_re.sub(repl, py.xml.escape(arg)))\n\n\ndef merge_family(left, right):\n result = {}\n for kl, vl in left.items():\n for kr, vr in right.items():\n if not isinstance(vl, list):\n raise TypeError(type(vl))\n result[kl] = vl + vr\n left.update(result)\n\n\nfamilies = {}\nfamilies[\"_base\"] = {\"testcase\": [\"classname\", \"name\"]}\nfamilies[\"_base_legacy\"] = {\"testcase\": [\"file\", \"line\", \"url\"]}\n\n# xUnit 1.x inherits legacy attributes\nfamilies[\"xunit1\"] = families[\"_base\"].copy()\nmerge_family(families[\"xunit1\"], families[\"_base_legacy\"])\n\n# xUnit 2.x uses strict base attributes\nfamilies[\"xunit2\"] = families[\"_base\"]\n\n\nclass _NodeReporter(object):\n def __init__(self, nodeid, xml):\n self.id = nodeid\n self.xml = xml\n self.add_stats = self.xml.add_stats\n self.family = self.xml.family\n self.duration = 0\n self.properties = []\n self.nodes = []\n self.testcase = None\n self.attrs = {}\n\n def append(self, node):\n self.xml.add_stats(type(node).__name__)\n self.nodes.append(node)\n\n def add_property(self, name, value):\n self.properties.append((str(name), bin_xml_escape(value)))\n\n def add_attribute(self, name, value):\n self.attrs[str(name)] = bin_xml_escape(value)\n\n def make_properties_node(self):\n \"\"\"Return a Junit node containing custom properties, if any.\n \"\"\"\n if self.properties:\n return Junit.properties(\n [\n Junit.property(name=name, value=value)\n for name, value in self.properties\n ]\n )\n return \"\"\n\n def record_testreport(self, testreport):\n assert not self.testcase\n names = mangle_test_address(testreport.nodeid)\n existing_attrs = self.attrs\n classnames = names[:-1]\n if self.xml.prefix:\n classnames.insert(0, self.xml.prefix)\n attrs = {\n \"classname\": \".\".join(classnames),\n \"name\": bin_xml_escape(names[-1]),\n \"file\": testreport.location[0],\n }\n if testreport.location[1] is not None:\n attrs[\"line\"] = testreport.location[1]\n if hasattr(testreport, \"url\"):\n attrs[\"url\"] = testreport.url\n self.attrs = attrs\n self.attrs.update(existing_attrs) # restore any user-defined attributes\n\n # Preserve legacy testcase behavior\n if self.family == \"xunit1\":\n return\n\n # Filter out attributes not permitted by this test family.\n # Including custom attributes because they are not valid here.\n temp_attrs = {}\n for key in self.attrs.keys():\n if key in families[self.family][\"testcase\"]:\n temp_attrs[key] = self.attrs[key]\n self.attrs = temp_attrs\n\n def to_xml(self):\n testcase = Junit.testcase(time=\"%.3f\" % self.duration, **self.attrs)\n testcase.append(self.make_properties_node())\n for node in self.nodes:\n testcase.append(node)\n return testcase\n\n def _add_simple(self, kind, message, data=None):\n data = bin_xml_escape(data)\n node = kind(data, message=message)\n self.append(node)\n\n def write_captured_output(self, report):\n if not self.xml.log_passing_tests and report.passed:\n return\n\n content_out = report.capstdout\n content_log = report.caplog\n content_err = report.capstderr\n\n if content_log or content_out:\n if content_log and self.xml.logging == \"system-out\":\n if content_out:\n # syncing stdout and the log-output is not done yet. It's\n # probably not worth the effort. Therefore, first the captured\n # stdout is shown and then the captured logs.\n content = \"\\n\".join(\n [\n \" Captured Stdout \".center(80, \"-\"),\n content_out,\n \"\",\n \" Captured Log \".center(80, \"-\"),\n content_log,\n ]\n )\n else:\n content = content_log\n else:\n content = content_out\n\n if content:\n tag = getattr(Junit, \"system-out\")\n self.append(tag(bin_xml_escape(content)))\n\n if content_log or content_err:\n if content_log and self.xml.logging == \"system-err\":\n if content_err:\n content = \"\\n\".join(\n [\n \" Captured Stderr \".center(80, \"-\"),\n content_err,\n \"\",\n \" Captured Log \".center(80, \"-\"),\n content_log,\n ]\n )\n else:\n content = content_log\n else:\n content = content_err\n\n if content:\n tag = getattr(Junit, \"system-err\")\n self.append(tag(bin_xml_escape(content)))\n\n def append_pass(self, report):\n self.add_stats(\"passed\")\n\n def append_failure(self, report):\n # msg = str(report.longrepr.reprtraceback.extraline)\n if hasattr(report, \"wasxfail\"):\n self._add_simple(Junit.skipped, \"xfail-marked test passes unexpectedly\")\n else:\n if hasattr(report.longrepr, \"reprcrash\"):\n message = report.longrepr.reprcrash.message\n elif isinstance(report.longrepr, six.string_types):\n message = report.longrepr\n else:\n message = str(report.longrepr)\n message = bin_xml_escape(message)\n fail = Junit.failure(message=message)\n fail.append(bin_xml_escape(report.longrepr))\n self.append(fail)\n\n def append_collect_error(self, report):\n # msg = str(report.longrepr.reprtraceback.extraline)\n self.append(\n Junit.error(bin_xml_escape(report.longrepr), message=\"collection failure\")\n )\n\n def append_collect_skipped(self, report):\n self._add_simple(Junit.skipped, \"collection skipped\", report.longrepr)\n\n def append_error(self, report):\n if report.when == \"teardown\":\n msg = \"test teardown failure\"\n else:\n msg = \"test setup failure\"\n self._add_simple(Junit.error, msg, report.longrepr)\n\n def append_skipped(self, report):\n if hasattr(report, \"wasxfail\"):\n xfailreason = report.wasxfail\n if xfailreason.startswith(\"reason: \"):\n xfailreason = xfailreason[8:]\n self.append(\n Junit.skipped(\n \"\", type=\"pytest.xfail\", message=bin_xml_escape(xfailreason)\n )\n )\n else:\n filename, lineno, skipreason = report.longrepr\n if skipreason.startswith(\"Skipped: \"):\n skipreason = skipreason[9:]\n details = \"%s:%s: %s\" % (filename, lineno, skipreason)\n\n self.append(\n Junit.skipped(\n bin_xml_escape(details),\n type=\"pytest.skip\",\n message=bin_xml_escape(skipreason),\n )\n )\n self.write_captured_output(report)\n\n def finalize(self):\n data = self.to_xml().unicode(indent=0)\n self.__dict__.clear()\n self.to_xml = lambda: py.xml.raw(data)\n\n\ndef _warn_incompatibility_with_xunit2(request, fixture_name):\n \"\"\"Emits a PytestWarning about the given fixture being incompatible with newer xunit revisions\"\"\"\n from _pytest.warning_types import PytestWarning\n\n xml = getattr(request.config, \"_xml\", None)\n if xml is not None and xml.family not in (\"xunit1\", \"legacy\"):\n request.node.warn(\n PytestWarning(\n \"{fixture_name} is incompatible with junit_family '{family}' (use 'legacy' or 'xunit1')\".format(\n fixture_name=fixture_name, family=xml.family\n )\n )\n )\n\n\n@pytest.fixture\ndef record_property(request):\n \"\"\"Add an extra properties the calling test.\n User properties become part of the test report and are available to the\n configured reporters, like JUnit XML.\n The fixture is callable with ``(name, value)``, with value being automatically\n xml-encoded.\n\n Example::\n\n def test_function(record_property):\n record_property(\"example_key\", 1)\n \"\"\"\n _warn_incompatibility_with_xunit2(request, \"record_property\")\n\n def append_property(name, value):\n request.node.user_properties.append((name, value))\n\n return append_property\n\n\n@pytest.fixture\ndef record_xml_attribute(request):\n \"\"\"Add extra xml attributes to the tag for the calling test.\n The fixture is callable with ``(name, value)``, with value being\n automatically xml-encoded\n \"\"\"\n from _pytest.warning_types import PytestExperimentalApiWarning\n\n request.node.warn(\n PytestExperimentalApiWarning(\"record_xml_attribute is an experimental feature\")\n )\n\n _warn_incompatibility_with_xunit2(request, \"record_xml_attribute\")\n\n # Declare noop\n def add_attr_noop(name, value):\n pass\n\n attr_func = add_attr_noop\n\n xml = getattr(request.config, \"_xml\", None)\n if xml is not None:\n node_reporter = xml.node_reporter(request.node.nodeid)\n attr_func = node_reporter.add_attribute\n\n return attr_func\n\n\ndef _check_record_param_type(param, v):\n \"\"\"Used by record_testsuite_property to check that the given parameter name is of the proper\n type\"\"\"\n __tracebackhide__ = True\n if not isinstance(v, six.string_types):\n msg = \"{param} parameter needs to be a string, but {g} given\"\n raise TypeError(msg.format(param=param, g=type(v).__name__))\n\n\n@pytest.fixture(scope=\"session\")\ndef record_testsuite_property(request):\n \"\"\"\n Records a new ```` tag as child of the root ````. This is suitable to\n writing global information regarding the entire test suite, and is compatible with ``xunit2`` JUnit family.\n\n This is a ``session``-scoped fixture which is called with ``(name, value)``. Example:\n\n .. code-block:: python\n\n def test_foo(record_testsuite_property):\n record_testsuite_property(\"ARCH\", \"PPC\")\n record_testsuite_property(\"STORAGE_TYPE\", \"CEPH\")\n\n ``name`` must be a string, ``value`` will be converted to a string and properly xml-escaped.\n \"\"\"\n\n __tracebackhide__ = True\n\n def record_func(name, value):\n \"\"\"noop function in case --junitxml was not passed in the command-line\"\"\"\n __tracebackhide__ = True\n _check_record_param_type(\"name\", name)\n\n xml = getattr(request.config, \"_xml\", None)\n if xml is not None:\n record_func = xml.add_global_property # noqa\n return record_func\n\n\ndef pytest_addoption(parser):\n group = parser.getgroup(\"terminal reporting\")\n group.addoption(\n \"--junitxml\",\n \"--junit-xml\",\n action=\"store\",\n dest=\"xmlpath\",\n metavar=\"path\",\n type=functools.partial(filename_arg, optname=\"--junitxml\"),\n default=None,\n help=\"create junit-xml style report file at given path.\",\n )\n group.addoption(\n \"--junitprefix\",\n \"--junit-prefix\",\n action=\"store\",\n metavar=\"str\",\n default=None,\n help=\"prepend prefix to classnames in junit-xml output\",\n )\n parser.addini(\n \"junit_suite_name\", \"Test suite name for JUnit report\", default=\"pytest\"\n )\n parser.addini(\n \"junit_logging\",\n \"Write captured log messages to JUnit report: \"\n \"one of no|system-out|system-err\",\n default=\"no\",\n ) # choices=['no', 'stdout', 'stderr'])\n parser.addini(\n \"junit_log_passing_tests\",\n \"Capture log information for passing tests to JUnit report: \",\n type=\"bool\",\n default=True,\n )\n parser.addini(\n \"junit_duration_report\",\n \"Duration time to report: one of total|call\",\n default=\"total\",\n ) # choices=['total', 'call'])\n parser.addini(\n \"junit_family\",\n \"Emit XML for schema: one of legacy|xunit1|xunit2\",\n default=\"xunit1\",\n )\n\n\ndef pytest_configure(config):\n xmlpath = config.option.xmlpath\n # prevent opening xmllog on slave nodes (xdist)\n if xmlpath and not hasattr(config, \"slaveinput\"):\n config._xml = LogXML(\n xmlpath,\n config.option.junitprefix,\n config.getini(\"junit_suite_name\"),\n config.getini(\"junit_logging\"),\n config.getini(\"junit_duration_report\"),\n config.getini(\"junit_family\"),\n config.getini(\"junit_log_passing_tests\"),\n )\n config.pluginmanager.register(config._xml)\n\n\ndef pytest_unconfigure(config):\n xml = getattr(config, \"_xml\", None)\n if xml:\n del config._xml\n config.pluginmanager.unregister(xml)\n\n\ndef mangle_test_address(address):\n path, possible_open_bracket, params = address.partition(\"[\")\n names = path.split(\"::\")\n try:\n names.remove(\"()\")\n except ValueError:\n pass\n # convert file path to dotted path\n names[0] = names[0].replace(nodes.SEP, \".\")\n names[0] = _py_ext_re.sub(\"\", names[0])\n # put any params back\n names[-1] += possible_open_bracket + params\n return names\n\n\nclass LogXML(object):\n def __init__(\n self,\n logfile,\n prefix,\n suite_name=\"pytest\",\n logging=\"no\",\n report_duration=\"total\",\n family=\"xunit1\",\n log_passing_tests=True,\n ):\n logfile = os.path.expanduser(os.path.expandvars(logfile))\n self.logfile = os.path.normpath(os.path.abspath(logfile))\n self.prefix = prefix\n self.suite_name = suite_name\n self.logging = logging\n self.log_passing_tests = log_passing_tests\n self.report_duration = report_duration\n self.family = family\n self.stats = dict.fromkeys([\"error\", \"passed\", \"failure\", \"skipped\"], 0)\n self.node_reporters = {} # nodeid -> _NodeReporter\n self.node_reporters_ordered = []\n self.global_properties = []\n\n # List of reports that failed on call but teardown is pending.\n self.open_reports = []\n self.cnt_double_fail_tests = 0\n\n # Replaces convenience family with real family\n if self.family == \"legacy\":\n self.family = \"xunit1\"\n\n def finalize(self, report):\n nodeid = getattr(report, \"nodeid\", report)\n # local hack to handle xdist report order\n slavenode = getattr(report, \"node\", None)\n reporter = self.node_reporters.pop((nodeid, slavenode))\n if reporter is not None:\n reporter.finalize()\n\n def node_reporter(self, report):\n nodeid = getattr(report, \"nodeid\", report)\n # local hack to handle xdist report order\n slavenode = getattr(report, \"node\", None)\n\n key = nodeid, slavenode\n\n if key in self.node_reporters:\n # TODO: breasks for --dist=each\n return self.node_reporters[key]\n\n reporter = _NodeReporter(nodeid, self)\n\n self.node_reporters[key] = reporter\n self.node_reporters_ordered.append(reporter)\n\n return reporter\n\n def add_stats(self, key):\n if key in self.stats:\n self.stats[key] += 1\n\n def _opentestcase(self, report):\n reporter = self.node_reporter(report)\n reporter.record_testreport(report)\n return reporter\n\n def pytest_runtest_logreport(self, report):\n \"\"\"handle a setup/call/teardown report, generating the appropriate\n xml tags as necessary.\n\n note: due to plugins like xdist, this hook may be called in interlaced\n order with reports from other nodes. for example:\n\n usual call order:\n -> setup node1\n -> call node1\n -> teardown node1\n -> setup node2\n -> call node2\n -> teardown node2\n\n possible call order in xdist:\n -> setup node1\n -> call node1\n -> setup node2\n -> call node2\n -> teardown node2\n -> teardown node1\n \"\"\"\n close_report = None\n if report.passed:\n if report.when == \"call\": # ignore setup/teardown\n reporter = self._opentestcase(report)\n reporter.append_pass(report)\n elif report.failed:\n if report.when == \"teardown\":\n # The following vars are needed when xdist plugin is used\n report_wid = getattr(report, \"worker_id\", None)\n report_ii = getattr(report, \"item_index\", None)\n close_report = next(\n (\n rep\n for rep in self.open_reports\n if (\n rep.nodeid == report.nodeid\n and getattr(rep, \"item_index\", None) == report_ii\n and getattr(rep, \"worker_id\", None) == report_wid\n )\n ),\n None,\n )\n if close_report:\n # We need to open new testcase in case we have failure in\n # call and error in teardown in order to follow junit\n # schema\n self.finalize(close_report)\n self.cnt_double_fail_tests += 1\n reporter = self._opentestcase(report)\n if report.when == \"call\":\n reporter.append_failure(report)\n self.open_reports.append(report)\n else:\n reporter.append_error(report)\n elif report.skipped:\n reporter = self._opentestcase(report)\n reporter.append_skipped(report)\n self.update_testcase_duration(report)\n if report.when == \"teardown\":\n reporter = self._opentestcase(report)\n reporter.write_captured_output(report)\n\n for propname, propvalue in report.user_properties:\n reporter.add_property(propname, propvalue)\n\n self.finalize(report)\n report_wid = getattr(report, \"worker_id\", None)\n report_ii = getattr(report, \"item_index\", None)\n close_report = next(\n (\n rep\n for rep in self.open_reports\n if (\n rep.nodeid == report.nodeid\n and getattr(rep, \"item_index\", None) == report_ii\n and getattr(rep, \"worker_id\", None) == report_wid\n )\n ),\n None,\n )\n if close_report:\n self.open_reports.remove(close_report)\n\n def update_testcase_duration(self, report):\n \"\"\"accumulates total duration for nodeid from given report and updates\n the Junit.testcase with the new total if already created.\n \"\"\"\n if self.report_duration == \"total\" or report.when == self.report_duration:\n reporter = self.node_reporter(report)\n reporter.duration += getattr(report, \"duration\", 0.0)\n\n def pytest_collectreport(self, report):\n if not report.passed:\n reporter = self._opentestcase(report)\n if report.failed:\n reporter.append_collect_error(report)\n else:\n reporter.append_collect_skipped(report)\n\n def pytest_internalerror(self, excrepr):\n reporter = self.node_reporter(\"internal\")\n reporter.attrs.update(classname=\"pytest\", name=\"internal\")\n reporter._add_simple(Junit.error, \"internal error\", excrepr)\n\n def pytest_sessionstart(self):\n self.suite_start_time = time.time()\n\n def pytest_sessionfinish(self):\n dirname = os.path.dirname(os.path.abspath(self.logfile))\n if not os.path.isdir(dirname):\n os.makedirs(dirname)\n logfile = open(self.logfile, \"w\", encoding=\"utf-8\")\n suite_stop_time = time.time()\n suite_time_delta = suite_stop_time - self.suite_start_time\n\n numtests = (\n self.stats[\"passed\"]\n + self.stats[\"failure\"]\n + self.stats[\"skipped\"]\n + self.stats[\"error\"]\n - self.cnt_double_fail_tests\n )\n logfile.write('')\n\n logfile.write(\n Junit.testsuite(\n self._get_global_properties_node(),\n [x.to_xml() for x in self.node_reporters_ordered],\n name=self.suite_name,\n errors=self.stats[\"error\"],\n failures=self.stats[\"failure\"],\n skipped=self.stats[\"skipped\"],\n tests=numtests,\n time=\"%.3f\" % suite_time_delta,\n ).unicode(indent=0)\n )\n logfile.close()\n\n def pytest_terminal_summary(self, terminalreporter):\n terminalreporter.write_sep(\"-\", \"generated xml file: %s\" % (self.logfile))\n\n def add_global_property(self, name, value):\n __tracebackhide__ = True\n _check_record_param_type(\"name\", name)\n self.global_properties.append((name, bin_xml_escape(value)))\n\n def _get_global_properties_node(self):\n \"\"\"Return a Junit node containing custom properties, if any.\n \"\"\"\n if self.global_properties:\n return Junit.properties(\n [\n Junit.property(name=name, value=value)\n for name, value in self.global_properties\n ]\n )\n return \"\"\n"},{"col":0,"comment":"\n Assert that two numbers (or two sets of numbers) are equal to each other\n within some tolerance.\n\n Due to the `intricacies of floating-point arithmetic`__, numbers that we\n would intuitively expect to be equal are not always so::\n\n >>> 0.1 + 0.2 == 0.3\n False\n\n __ https://docs.python.org/3/tutorial/floatingpoint.html\n\n This problem is commonly encountered when writing tests, e.g. when making\n sure that floating-point values are what you expect them to be. One way to\n deal with this problem is to assert that two floating-point numbers are\n equal to within some appropriate tolerance::\n\n >>> abs((0.1 + 0.2) - 0.3) < 1e-6\n True\n\n However, comparisons like this are tedious to write and difficult to\n understand. Furthermore, absolute comparisons like the one above are\n usually discouraged because there's no tolerance that works well for all\n situations. ``1e-6`` is good for numbers around ``1``, but too small for\n very big numbers and too big for very small ones. It's better to express\n the tolerance as a fraction of the expected value, but relative comparisons\n like that are even more difficult to write correctly and concisely.\n\n The ``approx`` class performs floating-point comparisons using a syntax\n that's as intuitive as possible::\n\n >>> from pytest import approx\n >>> 0.1 + 0.2 == approx(0.3)\n True\n\n The same syntax also works for sequences of numbers::\n\n >>> (0.1 + 0.2, 0.2 + 0.4) == approx((0.3, 0.6))\n True\n\n Dictionary *values*::\n\n >>> {'a': 0.1 + 0.2, 'b': 0.2 + 0.4} == approx({'a': 0.3, 'b': 0.6})\n True\n\n ``numpy`` arrays::\n\n >>> import numpy as np # doctest: +SKIP\n >>> np.array([0.1, 0.2]) + np.array([0.2, 0.4]) == approx(np.array([0.3, 0.6])) # doctest: +SKIP\n True\n\n And for a ``numpy`` array against a scalar::\n\n >>> import numpy as np # doctest: +SKIP\n >>> np.array([0.1, 0.2]) + np.array([0.2, 0.1]) == approx(0.3) # doctest: +SKIP\n True\n\n By default, ``approx`` considers numbers within a relative tolerance of\n ``1e-6`` (i.e. one part in a million) of its expected value to be equal.\n This treatment would lead to surprising results if the expected value was\n ``0.0``, because nothing but ``0.0`` itself is relatively close to ``0.0``.\n To handle this case less surprisingly, ``approx`` also considers numbers\n within an absolute tolerance of ``1e-12`` of its expected value to be\n equal. Infinity and NaN are special cases. Infinity is only considered\n equal to itself, regardless of the relative tolerance. NaN is not\n considered equal to anything by default, but you can make it be equal to\n itself by setting the ``nan_ok`` argument to True. (This is meant to\n facilitate comparing arrays that use NaN to mean \"no data\".)\n\n Both the relative and absolute tolerances can be changed by passing\n arguments to the ``approx`` constructor::\n\n >>> 1.0001 == approx(1)\n False\n >>> 1.0001 == approx(1, rel=1e-3)\n True\n >>> 1.0001 == approx(1, abs=1e-3)\n True\n\n If you specify ``abs`` but not ``rel``, the comparison will not consider\n the relative tolerance at all. In other words, two numbers that are within\n the default relative tolerance of ``1e-6`` will still be considered unequal\n if they exceed the specified absolute tolerance. If you specify both\n ``abs`` and ``rel``, the numbers will be considered equal if either\n tolerance is met::\n\n >>> 1 + 1e-8 == approx(1)\n True\n >>> 1 + 1e-8 == approx(1, abs=1e-12)\n False\n >>> 1 + 1e-8 == approx(1, rel=1e-6, abs=1e-12)\n True\n\n If you're thinking about using ``approx``, then you might want to know how\n it compares to other good ways of comparing floating-point numbers. All of\n these algorithms are based on relative and absolute tolerances and should\n agree for the most part, but they do have meaningful differences:\n\n - ``math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0)``: True if the relative\n tolerance is met w.r.t. either ``a`` or ``b`` or if the absolute\n tolerance is met. Because the relative tolerance is calculated w.r.t.\n both ``a`` and ``b``, this test is symmetric (i.e. neither ``a`` nor\n ``b`` is a \"reference value\"). You have to specify an absolute tolerance\n if you want to compare to ``0.0`` because there is no tolerance by\n default. Only available in python>=3.5. `More information...`__\n\n __ https://docs.python.org/3/library/math.html#math.isclose\n\n - ``numpy.isclose(a, b, rtol=1e-5, atol=1e-8)``: True if the difference\n between ``a`` and ``b`` is less that the sum of the relative tolerance\n w.r.t. ``b`` and the absolute tolerance. Because the relative tolerance\n is only calculated w.r.t. ``b``, this test is asymmetric and you can\n think of ``b`` as the reference value. Support for comparing sequences\n is provided by ``numpy.allclose``. `More information...`__\n\n __ http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.isclose.html\n\n - ``unittest.TestCase.assertAlmostEqual(a, b)``: True if ``a`` and ``b``\n are within an absolute tolerance of ``1e-7``. No relative tolerance is\n considered and the absolute tolerance cannot be changed, so this function\n is not appropriate for very large or very small numbers. Also, it's only\n available in subclasses of ``unittest.TestCase`` and it's ugly because it\n doesn't follow PEP8. `More information...`__\n\n __ https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertAlmostEqual\n\n - ``a == pytest.approx(b, rel=1e-6, abs=1e-12)``: True if the relative\n tolerance is met w.r.t. ``b`` or if the absolute tolerance is met.\n Because the relative tolerance is only calculated w.r.t. ``b``, this test\n is asymmetric and you can think of ``b`` as the reference value. In the\n special case that you explicitly specify an absolute tolerance but not a\n relative tolerance, only the absolute tolerance is considered.\n\n .. warning::\n\n .. versionchanged:: 3.2\n\n In order to avoid inconsistent behavior, ``TypeError`` is\n raised for ``>``, ``>=``, ``<`` and ``<=`` comparisons.\n The example below illustrates the problem::\n\n assert approx(0.1) > 0.1 + 1e-10 # calls approx(0.1).__gt__(0.1 + 1e-10)\n assert 0.1 + 1e-10 > approx(0.1) # calls approx(0.1).__lt__(0.1 + 1e-10)\n\n In the second example one expects ``approx(0.1).__le__(0.1 + 1e-10)``\n to be called. But instead, ``approx(0.1).__lt__(0.1 + 1e-10)`` is used to\n comparison. This is because the call hierarchy of rich comparisons\n follows a fixed behavior. `More information...`__\n\n __ https://docs.python.org/3/reference/datamodel.html#object.__ge__\n ","endLoc":537,"header":"def approx(expected, rel=None, abs=None, nan_ok=False)","id":886,"name":"approx","nodeType":"Function","startLoc":350,"text":"def approx(expected, rel=None, abs=None, nan_ok=False):\n \"\"\"\n Assert that two numbers (or two sets of numbers) are equal to each other\n within some tolerance.\n\n Due to the `intricacies of floating-point arithmetic`__, numbers that we\n would intuitively expect to be equal are not always so::\n\n >>> 0.1 + 0.2 == 0.3\n False\n\n __ https://docs.python.org/3/tutorial/floatingpoint.html\n\n This problem is commonly encountered when writing tests, e.g. when making\n sure that floating-point values are what you expect them to be. One way to\n deal with this problem is to assert that two floating-point numbers are\n equal to within some appropriate tolerance::\n\n >>> abs((0.1 + 0.2) - 0.3) < 1e-6\n True\n\n However, comparisons like this are tedious to write and difficult to\n understand. Furthermore, absolute comparisons like the one above are\n usually discouraged because there's no tolerance that works well for all\n situations. ``1e-6`` is good for numbers around ``1``, but too small for\n very big numbers and too big for very small ones. It's better to express\n the tolerance as a fraction of the expected value, but relative comparisons\n like that are even more difficult to write correctly and concisely.\n\n The ``approx`` class performs floating-point comparisons using a syntax\n that's as intuitive as possible::\n\n >>> from pytest import approx\n >>> 0.1 + 0.2 == approx(0.3)\n True\n\n The same syntax also works for sequences of numbers::\n\n >>> (0.1 + 0.2, 0.2 + 0.4) == approx((0.3, 0.6))\n True\n\n Dictionary *values*::\n\n >>> {'a': 0.1 + 0.2, 'b': 0.2 + 0.4} == approx({'a': 0.3, 'b': 0.6})\n True\n\n ``numpy`` arrays::\n\n >>> import numpy as np # doctest: +SKIP\n >>> np.array([0.1, 0.2]) + np.array([0.2, 0.4]) == approx(np.array([0.3, 0.6])) # doctest: +SKIP\n True\n\n And for a ``numpy`` array against a scalar::\n\n >>> import numpy as np # doctest: +SKIP\n >>> np.array([0.1, 0.2]) + np.array([0.2, 0.1]) == approx(0.3) # doctest: +SKIP\n True\n\n By default, ``approx`` considers numbers within a relative tolerance of\n ``1e-6`` (i.e. one part in a million) of its expected value to be equal.\n This treatment would lead to surprising results if the expected value was\n ``0.0``, because nothing but ``0.0`` itself is relatively close to ``0.0``.\n To handle this case less surprisingly, ``approx`` also considers numbers\n within an absolute tolerance of ``1e-12`` of its expected value to be\n equal. Infinity and NaN are special cases. Infinity is only considered\n equal to itself, regardless of the relative tolerance. NaN is not\n considered equal to anything by default, but you can make it be equal to\n itself by setting the ``nan_ok`` argument to True. (This is meant to\n facilitate comparing arrays that use NaN to mean \"no data\".)\n\n Both the relative and absolute tolerances can be changed by passing\n arguments to the ``approx`` constructor::\n\n >>> 1.0001 == approx(1)\n False\n >>> 1.0001 == approx(1, rel=1e-3)\n True\n >>> 1.0001 == approx(1, abs=1e-3)\n True\n\n If you specify ``abs`` but not ``rel``, the comparison will not consider\n the relative tolerance at all. In other words, two numbers that are within\n the default relative tolerance of ``1e-6`` will still be considered unequal\n if they exceed the specified absolute tolerance. If you specify both\n ``abs`` and ``rel``, the numbers will be considered equal if either\n tolerance is met::\n\n >>> 1 + 1e-8 == approx(1)\n True\n >>> 1 + 1e-8 == approx(1, abs=1e-12)\n False\n >>> 1 + 1e-8 == approx(1, rel=1e-6, abs=1e-12)\n True\n\n If you're thinking about using ``approx``, then you might want to know how\n it compares to other good ways of comparing floating-point numbers. All of\n these algorithms are based on relative and absolute tolerances and should\n agree for the most part, but they do have meaningful differences:\n\n - ``math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0)``: True if the relative\n tolerance is met w.r.t. either ``a`` or ``b`` or if the absolute\n tolerance is met. Because the relative tolerance is calculated w.r.t.\n both ``a`` and ``b``, this test is symmetric (i.e. neither ``a`` nor\n ``b`` is a \"reference value\"). You have to specify an absolute tolerance\n if you want to compare to ``0.0`` because there is no tolerance by\n default. Only available in python>=3.5. `More information...`__\n\n __ https://docs.python.org/3/library/math.html#math.isclose\n\n - ``numpy.isclose(a, b, rtol=1e-5, atol=1e-8)``: True if the difference\n between ``a`` and ``b`` is less that the sum of the relative tolerance\n w.r.t. ``b`` and the absolute tolerance. Because the relative tolerance\n is only calculated w.r.t. ``b``, this test is asymmetric and you can\n think of ``b`` as the reference value. Support for comparing sequences\n is provided by ``numpy.allclose``. `More information...`__\n\n __ http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.isclose.html\n\n - ``unittest.TestCase.assertAlmostEqual(a, b)``: True if ``a`` and ``b``\n are within an absolute tolerance of ``1e-7``. No relative tolerance is\n considered and the absolute tolerance cannot be changed, so this function\n is not appropriate for very large or very small numbers. Also, it's only\n available in subclasses of ``unittest.TestCase`` and it's ugly because it\n doesn't follow PEP8. `More information...`__\n\n __ https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertAlmostEqual\n\n - ``a == pytest.approx(b, rel=1e-6, abs=1e-12)``: True if the relative\n tolerance is met w.r.t. ``b`` or if the absolute tolerance is met.\n Because the relative tolerance is only calculated w.r.t. ``b``, this test\n is asymmetric and you can think of ``b`` as the reference value. In the\n special case that you explicitly specify an absolute tolerance but not a\n relative tolerance, only the absolute tolerance is considered.\n\n .. warning::\n\n .. versionchanged:: 3.2\n\n In order to avoid inconsistent behavior, ``TypeError`` is\n raised for ``>``, ``>=``, ``<`` and ``<=`` comparisons.\n The example below illustrates the problem::\n\n assert approx(0.1) > 0.1 + 1e-10 # calls approx(0.1).__gt__(0.1 + 1e-10)\n assert 0.1 + 1e-10 > approx(0.1) # calls approx(0.1).__lt__(0.1 + 1e-10)\n\n In the second example one expects ``approx(0.1).__le__(0.1 + 1e-10)``\n to be called. But instead, ``approx(0.1).__lt__(0.1 + 1e-10)`` is used to\n comparison. This is because the call hierarchy of rich comparisons\n follows a fixed behavior. `More information...`__\n\n __ https://docs.python.org/3/reference/datamodel.html#object.__ge__\n \"\"\"\n\n # Delegate the comparison to a class that knows how to deal with the type\n # of the expected value (e.g. int, float, list, dict, numpy.array, etc).\n #\n # The primary responsibility of these classes is to implement ``__eq__()``\n # and ``__repr__()``. The former is used to actually check if some\n # \"actual\" value is equivalent to the given expected value within the\n # allowed tolerance. The latter is used to show the user the expected\n # value and tolerance, in the case that a test failed.\n #\n # The actual logic for making approximate comparisons can be found in\n # ApproxScalar, which is used to compare individual numbers. All of the\n # other Approx classes eventually delegate to this class. The ApproxBase\n # class provides some convenient methods and overloads, but isn't really\n # essential.\n\n __tracebackhide__ = True\n\n if isinstance(expected, Decimal):\n cls = ApproxDecimal\n elif isinstance(expected, Number):\n cls = ApproxScalar\n elif isinstance(expected, Mapping):\n cls = ApproxMapping\n elif _is_numpy_array(expected):\n cls = ApproxNumpy\n elif (\n isinstance(expected, Iterable)\n and isinstance(expected, Sized)\n and not isinstance(expected, STRING_TYPES)\n ):\n cls = ApproxSequencelike\n else:\n raise _non_numeric_type_error(expected, at=None)\n\n return cls(expected, rel, abs, nan_ok)"},{"col":0,"comment":" Argparse type validator for filename arguments.\n\n :path: path of filename\n :optname: name of the option\n ","endLoc":104,"header":"def filename_arg(path, optname)","id":887,"name":"filename_arg","nodeType":"Function","startLoc":96,"text":"def filename_arg(path, optname):\n \"\"\" Argparse type validator for filename arguments.\n\n :path: path of filename\n :optname: name of the option\n \"\"\"\n if os.path.isdir(path):\n raise UsageError(\"{} must be a filename, given: {}\".format(optname, path))\n return path"},{"col":4,"comment":"null","endLoc":686,"header":"@overload\n def get(self, key: _KT, /, default: _VT_co | _T) -> _VT_co | _T","id":888,"name":"get","nodeType":"Function","startLoc":685,"text":"@overload\n def get(self, key: _KT, /, default: _VT_co | _T) -> _VT_co | _T: ..."},{"col":0,"comment":" (return a) decorator to mark a yield-fixture factory function.\n\n .. deprecated:: 3.0\n Use :py:func:`pytest.fixture` directly instead.\n ","endLoc":1057,"header":"def yield_fixture(scope=\"function\", params=None, autouse=False, ids=None, name=None)","id":889,"name":"yield_fixture","nodeType":"Function","startLoc":1051,"text":"def yield_fixture(scope=\"function\", params=None, autouse=False, ids=None, name=None):\n \"\"\" (return a) decorator to mark a yield-fixture factory function.\n\n .. deprecated:: 3.0\n Use :py:func:`pytest.fixture` directly instead.\n \"\"\"\n return fixture(scope=scope, params=params, autouse=autouse, ids=ids, name=name)"},{"col":0,"comment":"\n Return true if the given object is a numpy array. Make a special effort to\n avoid importing numpy unless it's really necessary.\n ","endLoc":550,"header":"def _is_numpy_array(obj)","id":890,"name":"_is_numpy_array","nodeType":"Function","startLoc":540,"text":"def _is_numpy_array(obj):\n \"\"\"\n Return true if the given object is a numpy array. Make a special effort to\n avoid importing numpy unless it's really necessary.\n \"\"\"\n import sys\n\n np = sys.modules.get(\"numpy\")\n if np is not None:\n return isinstance(obj, np.ndarray)\n return False"},{"col":0,"comment":"\n Returns a list of module names used by pytest that should be\n included by cx_freeze.\n ","endLoc":21,"header":"def freeze_includes()","id":894,"name":"freeze_includes","nodeType":"Function","startLoc":11,"text":"def freeze_includes():\n \"\"\"\n Returns a list of module names used by pytest that should be\n included by cx_freeze.\n \"\"\"\n import py\n import _pytest\n\n result = list(_iter_all_modules(py))\n result += list(_iter_all_modules(_pytest))\n return result"},{"col":0,"comment":"\n Iterates over the names of all modules that can be found in the given\n package, recursively.\n Example:\n _iter_all_modules(_pytest) ->\n ['_pytest.assertion.newinterpret',\n '_pytest.capture',\n '_pytest.core',\n ...\n ]\n ","endLoc":48,"header":"def _iter_all_modules(package, prefix=\"\")","id":895,"name":"_iter_all_modules","nodeType":"Function","startLoc":24,"text":"def _iter_all_modules(package, prefix=\"\"):\n \"\"\"\n Iterates over the names of all modules that can be found in the given\n package, recursively.\n Example:\n _iter_all_modules(_pytest) ->\n ['_pytest.assertion.newinterpret',\n '_pytest.capture',\n '_pytest.core',\n ...\n ]\n \"\"\"\n import os\n import pkgutil\n\n if type(package) is not str:\n path, prefix = package.__path__[0], package.__name__ + \".\"\n else:\n path = package\n for _, name, is_package in pkgutil.iter_modules([path]):\n if is_package:\n for m in _iter_all_modules(os.path.join(path, name), prefix=name + \".\"):\n yield prefix + m\n else:\n yield prefix + name"},{"col":4,"comment":"return the first marker matching the name, from closest (for example function) to farther level (for example\n module level).\n\n :param default: fallback return value of no marker was found\n :param name: name to filter by\n ","endLoc":213,"header":"def get_closest_marker(self, name, default=None)","id":896,"name":"get_closest_marker","nodeType":"Function","startLoc":206,"text":"def get_closest_marker(self, name, default=None):\n \"\"\"return the first marker matching the name, from closest (for example function) to farther level (for example\n module level).\n\n :param default: fallback return value of no marker was found\n :param name: name to filter by\n \"\"\"\n return next(self.iter_markers(name=name), default)"},{"col":4,"comment":"null","endLoc":396,"header":"def __init__(self, name, parent=None, config=None, session=None, nodeid=None)","id":897,"name":"__init__","nodeType":"Function","startLoc":390,"text":"def __init__(self, name, parent=None, config=None, session=None, nodeid=None):\n super(Item, self).__init__(name, parent, config, session, nodeid=nodeid)\n self._report_sections = []\n\n #: user properties is a list of tuples (name, value) that holds user\n #: defined properties for this test.\n self.user_properties = []"},{"col":4,"comment":"null","endLoc":1016,"header":"def pop(self, __index: SupportsIndex = -1) -> _T","id":898,"name":"pop","nodeType":"Function","startLoc":1016,"text":"def pop(self, __index: SupportsIndex = -1) -> _T: ..."},{"col":4,"comment":"null","endLoc":186,"header":"def test_some_error(self)","id":899,"name":"test_some_error","nodeType":"Function","startLoc":184,"text":"def test_some_error(self):\n if namenotexi: # NOQA\n pass"},{"col":4,"comment":"null","endLoc":189,"header":"def func1(self)","id":900,"name":"func1","nodeType":"Function","startLoc":188,"text":"def func1(self):\n assert 41 == 42"},{"className":"TestMoreErrors","col":0,"comment":"null","endLoc":253,"id":901,"nodeType":"Class","startLoc":206,"text":"class TestMoreErrors(object):\n def test_complex_error(self):\n def f():\n return 44\n\n def g():\n return 43\n\n somefunc(f(), g())\n\n def test_z1_unpack_error(self):\n items = []\n a, b = items\n\n def test_z2_type_error(self):\n items = 3\n a, b = items\n\n def test_startswith(self):\n s = \"123\"\n g = \"456\"\n assert s.startswith(g)\n\n def test_startswith_nested(self):\n def f():\n return \"123\"\n\n def g():\n return \"456\"\n\n assert f().startswith(g())\n\n def test_global_func(self):\n assert isinstance(globf(42), float)\n\n def test_instance(self):\n self.x = 6 * 7\n assert self.x != 42\n\n def test_compare(self):\n assert globf(10) < 5\n\n def test_try_finally(self):\n x = 1\n try:\n assert x == 0\n finally:\n x = 0"},{"col":4,"comment":"null","endLoc":214,"header":"def test_complex_error(self)","id":902,"name":"test_complex_error","nodeType":"Function","startLoc":207,"text":"def test_complex_error(self):\n def f():\n return 44\n\n def g():\n return 43\n\n somefunc(f(), g())"},{"col":0,"comment":"null","endLoc":12,"header":"def somefunc(x, y)","id":905,"name":"somefunc","nodeType":"Function","startLoc":11,"text":"def somefunc(x, y):\n otherfunc(x, y)"},{"col":0,"comment":"null","endLoc":8,"header":"def otherfunc(a, b)","id":906,"name":"otherfunc","nodeType":"Function","startLoc":7,"text":"def otherfunc(a, b):\n assert a == b"},{"col":4,"comment":"null","endLoc":218,"header":"def test_z1_unpack_error(self)","id":907,"name":"test_z1_unpack_error","nodeType":"Function","startLoc":216,"text":"def test_z1_unpack_error(self):\n items = []\n a, b = items"},{"col":4,"comment":"null","endLoc":222,"header":"def test_z2_type_error(self)","id":908,"name":"test_z2_type_error","nodeType":"Function","startLoc":220,"text":"def test_z2_type_error(self):\n items = 3\n a, b = items"},{"col":4,"comment":"null","endLoc":227,"header":"def test_startswith(self)","id":909,"name":"test_startswith","nodeType":"Function","startLoc":224,"text":"def test_startswith(self):\n s = \"123\"\n g = \"456\"\n assert s.startswith(g)"},{"col":0,"comment":"null","endLoc":1546,"header":"@overload\ndef next(__i: SupportsNext[_T]) -> _T","id":910,"name":"next","nodeType":"Function","startLoc":1545,"text":"@overload\ndef next(__i: SupportsNext[_T]) -> _T: ..."},{"col":0,"comment":"null","endLoc":1548,"header":"@overload\ndef next(__i: SupportsNext[_T], __default: _VT) -> _T | _VT","id":911,"name":"next","nodeType":"Function","startLoc":1547,"text":"@overload\ndef next(__i: SupportsNext[_T], __default: _VT) -> _T | _VT: ..."},{"col":4,"comment":" Return a set of all extra keywords in self and any parents.","endLoc":220,"header":"def listextrakeywords(self)","id":912,"name":"listextrakeywords","nodeType":"Function","startLoc":215,"text":"def listextrakeywords(self):\n \"\"\" Return a set of all extra keywords in self and any parents.\"\"\"\n extra_keywords = set()\n for item in self.listchain():\n extra_keywords.update(item.extra_keyword_matches)\n return extra_keywords"},{"col":0,"comment":"null","endLoc":133,"header":"def open(\n filename: str, mode: str = \"r\", encoding: str | None = None, errors: str = \"strict\", buffering: int = -1\n) -> StreamReaderWriter","id":913,"name":"open","nodeType":"Function","startLoc":131,"text":"def open(\n filename: str, mode: str = \"r\", encoding: str | None = None, errors: str = \"strict\", buffering: int = -1\n) -> StreamReaderWriter: ..."},{"col":4,"comment":"null","endLoc":223,"header":"def listnames(self)","id":914,"name":"listnames","nodeType":"Function","startLoc":222,"text":"def listnames(self):\n return [x.name for x in self.listchain()]"},{"col":4,"comment":" register a function to be called when this node is finalized.\n\n This method can only be called when this node is active\n in a setup chain, for example during self.setup().\n ","endLoc":231,"header":"def addfinalizer(self, fin)","id":915,"name":"addfinalizer","nodeType":"Function","startLoc":225,"text":"def addfinalizer(self, fin):\n \"\"\" register a function to be called when this node is finalized.\n\n This method can only be called when this node is active\n in a setup chain, for example during self.setup().\n \"\"\"\n self.session._setupstate.addfinalizer(fin, self)"},{"col":4,"comment":"null","endLoc":242,"header":"def _prunetraceback(self, excinfo)","id":916,"name":"_prunetraceback","nodeType":"Function","startLoc":241,"text":"def _prunetraceback(self, excinfo):\n pass"},{"col":4,"comment":"null","endLoc":287,"header":"def _repr_failure_py(self, excinfo, style=None)","id":917,"name":"_repr_failure_py","nodeType":"Function","startLoc":244,"text":"def _repr_failure_py(self, excinfo, style=None):\n if excinfo.errisinstance(fail.Exception):\n if not excinfo.value.pytrace:\n return six.text_type(excinfo.value)\n fm = self.session._fixturemanager\n if excinfo.errisinstance(fm.FixtureLookupError):\n return excinfo.value.formatrepr()\n tbfilter = True\n if self.config.getoption(\"fulltrace\", False):\n style = \"long\"\n else:\n tb = _pytest._code.Traceback([excinfo.traceback[-1]])\n self._prunetraceback(excinfo)\n if len(excinfo.traceback) == 0:\n excinfo.traceback = tb\n tbfilter = False # prunetraceback already does it\n if style == \"auto\":\n style = \"long\"\n # XXX should excinfo.getrepr record all data and toterminal() process it?\n if style is None:\n if self.config.getoption(\"tbstyle\", \"auto\") == \"short\":\n style = \"short\"\n else:\n style = \"long\"\n\n if self.config.getoption(\"verbose\", 0) > 1:\n truncate_locals = False\n else:\n truncate_locals = True\n\n try:\n os.getcwd()\n abspath = False\n except OSError:\n abspath = True\n\n return excinfo.getrepr(\n funcargs=True,\n abspath=abspath,\n showlocals=self.config.getoption(\"showlocals\", False),\n style=style,\n tbfilter=tbfilter,\n truncate_locals=truncate_locals,\n )"},{"col":0,"comment":"","endLoc":19,"header":"publish_gh_release_notes.py#","id":918,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"\nScript used to publish GitHub release notes extracted from CHANGELOG.rst.\n\nThis script is meant to be executed after a successful deployment in Travis.\n\nUses the following environment variables:\n\n* GIT_TAG: the name of the tag of the current commit.\n* GH_RELEASE_NOTES_TOKEN: a personal access token with 'repo' permissions. It should be encrypted using:\n\n $travis encrypt GH_RELEASE_NOTES_TOKEN= -r pytest-dev/pytest\n\n And the contents pasted in the ``deploy.env.secure`` section in the ``travis.yml`` file.\n\nThe script also requires ``pandoc`` to be previously installed in the system.\n\nRequires Python3.6+.\n\"\"\"\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv))"},{"className":"Junit","col":0,"comment":"null","endLoc":35,"id":919,"nodeType":"Class","startLoc":34,"text":"class Junit(py.xml.Namespace):\n pass"},{"className":"_NodeReporter","col":0,"comment":"null","endLoc":285,"id":920,"nodeType":"Class","startLoc":92,"text":"class _NodeReporter(object):\n def __init__(self, nodeid, xml):\n self.id = nodeid\n self.xml = xml\n self.add_stats = self.xml.add_stats\n self.family = self.xml.family\n self.duration = 0\n self.properties = []\n self.nodes = []\n self.testcase = None\n self.attrs = {}\n\n def append(self, node):\n self.xml.add_stats(type(node).__name__)\n self.nodes.append(node)\n\n def add_property(self, name, value):\n self.properties.append((str(name), bin_xml_escape(value)))\n\n def add_attribute(self, name, value):\n self.attrs[str(name)] = bin_xml_escape(value)\n\n def make_properties_node(self):\n \"\"\"Return a Junit node containing custom properties, if any.\n \"\"\"\n if self.properties:\n return Junit.properties(\n [\n Junit.property(name=name, value=value)\n for name, value in self.properties\n ]\n )\n return \"\"\n\n def record_testreport(self, testreport):\n assert not self.testcase\n names = mangle_test_address(testreport.nodeid)\n existing_attrs = self.attrs\n classnames = names[:-1]\n if self.xml.prefix:\n classnames.insert(0, self.xml.prefix)\n attrs = {\n \"classname\": \".\".join(classnames),\n \"name\": bin_xml_escape(names[-1]),\n \"file\": testreport.location[0],\n }\n if testreport.location[1] is not None:\n attrs[\"line\"] = testreport.location[1]\n if hasattr(testreport, \"url\"):\n attrs[\"url\"] = testreport.url\n self.attrs = attrs\n self.attrs.update(existing_attrs) # restore any user-defined attributes\n\n # Preserve legacy testcase behavior\n if self.family == \"xunit1\":\n return\n\n # Filter out attributes not permitted by this test family.\n # Including custom attributes because they are not valid here.\n temp_attrs = {}\n for key in self.attrs.keys():\n if key in families[self.family][\"testcase\"]:\n temp_attrs[key] = self.attrs[key]\n self.attrs = temp_attrs\n\n def to_xml(self):\n testcase = Junit.testcase(time=\"%.3f\" % self.duration, **self.attrs)\n testcase.append(self.make_properties_node())\n for node in self.nodes:\n testcase.append(node)\n return testcase\n\n def _add_simple(self, kind, message, data=None):\n data = bin_xml_escape(data)\n node = kind(data, message=message)\n self.append(node)\n\n def write_captured_output(self, report):\n if not self.xml.log_passing_tests and report.passed:\n return\n\n content_out = report.capstdout\n content_log = report.caplog\n content_err = report.capstderr\n\n if content_log or content_out:\n if content_log and self.xml.logging == \"system-out\":\n if content_out:\n # syncing stdout and the log-output is not done yet. It's\n # probably not worth the effort. Therefore, first the captured\n # stdout is shown and then the captured logs.\n content = \"\\n\".join(\n [\n \" Captured Stdout \".center(80, \"-\"),\n content_out,\n \"\",\n \" Captured Log \".center(80, \"-\"),\n content_log,\n ]\n )\n else:\n content = content_log\n else:\n content = content_out\n\n if content:\n tag = getattr(Junit, \"system-out\")\n self.append(tag(bin_xml_escape(content)))\n\n if content_log or content_err:\n if content_log and self.xml.logging == \"system-err\":\n if content_err:\n content = \"\\n\".join(\n [\n \" Captured Stderr \".center(80, \"-\"),\n content_err,\n \"\",\n \" Captured Log \".center(80, \"-\"),\n content_log,\n ]\n )\n else:\n content = content_log\n else:\n content = content_err\n\n if content:\n tag = getattr(Junit, \"system-err\")\n self.append(tag(bin_xml_escape(content)))\n\n def append_pass(self, report):\n self.add_stats(\"passed\")\n\n def append_failure(self, report):\n # msg = str(report.longrepr.reprtraceback.extraline)\n if hasattr(report, \"wasxfail\"):\n self._add_simple(Junit.skipped, \"xfail-marked test passes unexpectedly\")\n else:\n if hasattr(report.longrepr, \"reprcrash\"):\n message = report.longrepr.reprcrash.message\n elif isinstance(report.longrepr, six.string_types):\n message = report.longrepr\n else:\n message = str(report.longrepr)\n message = bin_xml_escape(message)\n fail = Junit.failure(message=message)\n fail.append(bin_xml_escape(report.longrepr))\n self.append(fail)\n\n def append_collect_error(self, report):\n # msg = str(report.longrepr.reprtraceback.extraline)\n self.append(\n Junit.error(bin_xml_escape(report.longrepr), message=\"collection failure\")\n )\n\n def append_collect_skipped(self, report):\n self._add_simple(Junit.skipped, \"collection skipped\", report.longrepr)\n\n def append_error(self, report):\n if report.when == \"teardown\":\n msg = \"test teardown failure\"\n else:\n msg = \"test setup failure\"\n self._add_simple(Junit.error, msg, report.longrepr)\n\n def append_skipped(self, report):\n if hasattr(report, \"wasxfail\"):\n xfailreason = report.wasxfail\n if xfailreason.startswith(\"reason: \"):\n xfailreason = xfailreason[8:]\n self.append(\n Junit.skipped(\n \"\", type=\"pytest.xfail\", message=bin_xml_escape(xfailreason)\n )\n )\n else:\n filename, lineno, skipreason = report.longrepr\n if skipreason.startswith(\"Skipped: \"):\n skipreason = skipreason[9:]\n details = \"%s:%s: %s\" % (filename, lineno, skipreason)\n\n self.append(\n Junit.skipped(\n bin_xml_escape(details),\n type=\"pytest.skip\",\n message=bin_xml_escape(skipreason),\n )\n )\n self.write_captured_output(report)\n\n def finalize(self):\n data = self.to_xml().unicode(indent=0)\n self.__dict__.clear()\n self.to_xml = lambda: py.xml.raw(data)"},{"col":4,"comment":"null","endLoc":102,"header":"def __init__(self, nodeid, xml)","id":921,"name":"__init__","nodeType":"Function","startLoc":93,"text":"def __init__(self, nodeid, xml):\n self.id = nodeid\n self.xml = xml\n self.add_stats = self.xml.add_stats\n self.family = self.xml.family\n self.duration = 0\n self.properties = []\n self.nodes = []\n self.testcase = None\n self.attrs = {}"},{"col":4,"comment":"null","endLoc":106,"header":"def append(self, node)","id":922,"name":"append","nodeType":"Function","startLoc":104,"text":"def append(self, node):\n self.xml.add_stats(type(node).__name__)\n self.nodes.append(node)"},{"id":923,"name":"release.minor.rst","nodeType":"TextFile","path":"scripts","text":"pytest-{version}\n=======================================\n\nThe pytest team is proud to announce the {version} release!\n\npytest is a mature Python testing tool with more than a 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n https://docs.pytest.org/en/latest/changelog.html\n\nFor complete documentation, please visit:\n\n https://docs.pytest.org/en/latest/\n\nAs usual, you can upgrade from pypi via:\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n{contributors}\n\nHappy testing,\nThe Pytest Development Team\n"},{"id":924,"name":"unittest.rst","nodeType":"TextFile","path":"doc/en","text":"\n.. _`unittest.TestCase`:\n.. _`unittest`:\n\nunittest.TestCase Support\n=========================\n\n``pytest`` supports running Python ``unittest``-based tests out of the box.\nIt's meant for leveraging existing ``unittest``-based test suites\nto use pytest as a test runner and also allow to incrementally adapt\nthe test suite to take full advantage of pytest's features.\n\nTo run an existing ``unittest``-style test suite using ``pytest``, type::\n\n pytest tests\n\n\npytest will automatically collect ``unittest.TestCase`` subclasses and\ntheir ``test`` methods in ``test_*.py`` or ``*_test.py`` files.\n\nAlmost all ``unittest`` features are supported:\n\n* ``@unittest.skip`` style decorators;\n* ``setUp/tearDown``;\n* ``setUpClass/tearDownClass``;\n* ``setUpModule/tearDownModule``;\n\n.. _`load_tests protocol`: https://docs.python.org/3/library/unittest.html#load-tests-protocol\n.. _`subtests`: https://docs.python.org/3/library/unittest.html#distinguishing-test-iterations-using-subtests\n\nUp to this point pytest does not have support for the following features:\n\n* `load_tests protocol`_;\n* `subtests`_;\n\nBenefits out of the box\n-----------------------\n\nBy running your test suite with pytest you can make use of several features,\nin most cases without having to modify existing code:\n\n* Obtain :ref:`more informative tracebacks `;\n* :ref:`stdout and stderr ` capturing;\n* :ref:`Test selection options ` using ``-k`` and ``-m`` flags;\n* :ref:`maxfail`;\n* :ref:`--pdb ` command-line option for debugging on test failures\n (see :ref:`note ` below);\n* Distribute tests to multiple CPUs using the `pytest-xdist `_ plugin;\n* Use :ref:`plain assert-statements ` instead of ``self.assert*`` functions (`unittest2pytest\n `__ is immensely helpful in this);\n\n\npytest features in ``unittest.TestCase`` subclasses\n---------------------------------------------------\n\nThe following pytest features work in ``unittest.TestCase`` subclasses:\n\n* :ref:`Marks `: :ref:`skip `, :ref:`skipif `, :ref:`xfail `;\n* :ref:`Auto-use fixtures `;\n\nThe following pytest features **do not** work, and probably\nnever will due to different design philosophies:\n\n* :ref:`Fixtures ` (except for ``autouse`` fixtures, see :ref:`below `);\n* :ref:`Parametrization `;\n* :ref:`Custom hooks `;\n\n\nThird party plugins may or may not work well, depending on the plugin and the test suite.\n\n.. _mixing-fixtures:\n\nMixing pytest fixtures into ``unittest.TestCase`` subclasses using marks\n------------------------------------------------------------------------\n\nRunning your unittest with ``pytest`` allows you to use its\n:ref:`fixture mechanism ` with ``unittest.TestCase`` style\ntests. Assuming you have at least skimmed the pytest fixture features,\nlet's jump-start into an example that integrates a pytest ``db_class``\nfixture, setting up a class-cached database object, and then reference\nit from a unittest-style test::\n\n # content of conftest.py\n\n # we define a fixture function below and it will be \"used\" by\n # referencing its name from tests\n\n import pytest\n\n @pytest.fixture(scope=\"class\")\n def db_class(request):\n class DummyDB(object):\n pass\n # set a class attribute on the invoking test context\n request.cls.db = DummyDB()\n\nThis defines a fixture function ``db_class`` which - if used - is\ncalled once for each test class and which sets the class-level\n``db`` attribute to a ``DummyDB`` instance. The fixture function\nachieves this by receiving a special ``request`` object which gives\naccess to :ref:`the requesting test context ` such\nas the ``cls`` attribute, denoting the class from which the fixture\nis used. This architecture de-couples fixture writing from actual test\ncode and allows re-use of the fixture by a minimal reference, the fixture\nname. So let's write an actual ``unittest.TestCase`` class using our\nfixture definition::\n\n # content of test_unittest_db.py\n\n import unittest\n import pytest\n\n @pytest.mark.usefixtures(\"db_class\")\n class MyTest(unittest.TestCase):\n def test_method1(self):\n assert hasattr(self, \"db\")\n assert 0, self.db # fail for demo purposes\n\n def test_method2(self):\n assert 0, self.db # fail for demo purposes\n\nThe ``@pytest.mark.usefixtures(\"db_class\")`` class-decorator makes sure that\nthe pytest fixture function ``db_class`` is called once per class.\nDue to the deliberately failing assert statements, we can take a look at\nthe ``self.db`` values in the traceback:\n\n.. code-block:: pytest\n\n $ pytest test_unittest_db.py\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 2 items\n\n test_unittest_db.py FF [100%]\n\n ================================= FAILURES =================================\n ___________________________ MyTest.test_method1 ____________________________\n\n self = \n\n def test_method1(self):\n assert hasattr(self, \"db\")\n > assert 0, self.db # fail for demo purposes\n E AssertionError: .DummyDB object at 0xdeadbeef>\n E assert 0\n\n test_unittest_db.py:9: AssertionError\n ___________________________ MyTest.test_method2 ____________________________\n\n self = \n\n def test_method2(self):\n > assert 0, self.db # fail for demo purposes\n E AssertionError: .DummyDB object at 0xdeadbeef>\n E assert 0\n\n test_unittest_db.py:12: AssertionError\n ========================= 2 failed in 0.12 seconds =========================\n\nThis default pytest traceback shows that the two test methods\nshare the same ``self.db`` instance which was our intention\nwhen writing the class-scoped fixture function above.\n\n\nUsing autouse fixtures and accessing other fixtures\n---------------------------------------------------\n\nAlthough it's usually better to explicitly declare use of fixtures you need\nfor a given test, you may sometimes want to have fixtures that are\nautomatically used in a given context. After all, the traditional\nstyle of unittest-setup mandates the use of this implicit fixture writing\nand chances are, you are used to it or like it.\n\nYou can flag fixture functions with ``@pytest.fixture(autouse=True)``\nand define the fixture function in the context where you want it used.\nLet's look at an ``initdir`` fixture which makes all test methods of a\n``TestCase`` class execute in a temporary directory with a\npre-initialized ``samplefile.ini``. Our ``initdir`` fixture itself uses\nthe pytest builtin :ref:`tmpdir ` fixture to delegate the\ncreation of a per-test temporary directory::\n\n # content of test_unittest_cleandir.py\n import pytest\n import unittest\n\n class MyTest(unittest.TestCase):\n\n @pytest.fixture(autouse=True)\n def initdir(self, tmpdir):\n tmpdir.chdir() # change to pytest-provided temporary directory\n tmpdir.join(\"samplefile.ini\").write(\"# testdata\")\n\n def test_method(self):\n with open(\"samplefile.ini\") as f:\n s = f.read()\n assert \"testdata\" in s\n\nDue to the ``autouse`` flag the ``initdir`` fixture function will be\nused for all methods of the class where it is defined. This is a\nshortcut for using a ``@pytest.mark.usefixtures(\"initdir\")`` marker\non the class like in the previous example.\n\nRunning this test module ...:\n\n.. code-block:: pytest\n\n $ pytest -q test_unittest_cleandir.py\n . [100%]\n 1 passed in 0.12 seconds\n\n... gives us one passed test because the ``initdir`` fixture function\nwas executed ahead of the ``test_method``.\n\n.. note::\n\n ``unittest.TestCase`` methods cannot directly receive fixture\n arguments as implementing that is likely to inflict\n on the ability to run general unittest.TestCase test suites.\n\n The above ``usefixtures`` and ``autouse`` examples should help to mix in\n pytest fixtures into unittest suites.\n\n You can also gradually move away from subclassing from ``unittest.TestCase`` to *plain asserts*\n and then start to benefit from the full pytest feature set step by step.\n\n.. _pdb-unittest-note:\n\n.. note::\n\n Running tests from ``unittest.TestCase`` subclasses with ``--pdb`` will\n disable tearDown and cleanup methods for the case that an Exception\n occurs. This allows proper post mortem debugging for all applications\n which have significant logic in their tearDown machinery. However,\n supporting this feature has the following side effect: If people\n overwrite ``unittest.TestCase`` ``__call__`` or ``run``, they need to\n to overwrite ``debug`` in the same way (this is also true for standard\n unittest).\n\n.. note::\n\n Due to architectural differences between the two frameworks, setup and\n teardown for ``unittest``-based tests is performed during the ``call`` phase\n of testing instead of in ``pytest``'s standard ``setup`` and ``teardown``\n stages. This can be important to understand in some situations, particularly\n when reasoning about errors. For example, if a ``unittest``-based suite\n exhibits errors during setup, ``pytest`` will report no errors during its\n ``setup`` phase and will instead raise the error during ``call``.\n"},{"fileName":"test_foo.py","filePath":"testing/example_scripts/fixtures/custom_item/foo","id":926,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ndef test():\n pass\n"},{"col":0,"comment":"null","endLoc":3,"header":"def test()","id":927,"name":"test","nodeType":"Function","startLoc":2,"text":"def test():\n pass"},{"id":928,"name":"doc/en/example","nodeType":"Package"},{"id":929,"name":"index.rst","nodeType":"TextFile","path":"doc/en/example","text":"\n.. _examples:\n\nExamples and customization tricks\n=================================\n\nHere is a (growing) list of examples. :ref:`Contact ` us if you\nneed more examples or have questions. Also take a look at the\n:ref:`comprehensive documentation ` which contains many example\nsnippets as well. Also, `pytest on stackoverflow.com\n`_ often comes with example\nanswers.\n\nFor basic examples, see\n\n- :doc:`../getting-started` for basic introductory examples\n- :ref:`assert` for basic assertion examples\n- :ref:`fixtures` for basic fixture/setup examples\n- :ref:`parametrize` for basic test function parametrization\n- :doc:`../unittest` for basic unittest integration\n- :doc:`../nose` for basic nosetests integration\n\nThe following examples aim at various use cases you might encounter.\n\n.. toctree::\n :maxdepth: 2\n\n reportingdemo\n simple\n parametrize\n markers\n special\n pythoncollection\n nonpython\n"},{"col":0,"comment":"null","endLoc":47,"header":"def _non_numeric_type_error(value, at)","id":930,"name":"_non_numeric_type_error","nodeType":"Function","startLoc":41,"text":"def _non_numeric_type_error(value, at):\n at_str = \" at {}\".format(at) if at else \"\"\n return TypeError(\n \"cannot make approximate comparisons to non-numeric values: {!r} {}\".format(\n value, at_str\n )\n )"},{"id":931,"name":"release-4.4.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-4.4.0\n=======================================\n\nThe pytest team is proud to announce the 4.4.0 release!\n\npytest is a mature Python testing tool with more than a 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n https://docs.pytest.org/en/latest/changelog.html\n\nFor complete documentation, please visit:\n\n https://docs.pytest.org/en/latest/\n\nAs usual, you can upgrade from pypi via:\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* ApaDoctor\n* Bernhard M. Wiedemann\n* Brian Skinn\n* Bruno Oliveira\n* Daniel Hahler\n* Gary Tyler\n* Jeong YunWon\n* Miro Hrončok\n* Takafumi Arakaki\n* henrykironde\n* smheidrich\n\n\nHappy testing,\nThe Pytest Development Team\n"},{"id":932,"name":"adopt.rst","nodeType":"TextFile","path":"doc/en","text":":orphan:\n\n.. warnings about this file not being included in any toctree will be suppressed by :orphan:\n\n\nApril 2015 is \"adopt pytest month\"\n=============================================\n\nAre you an enthusiastic pytest user, the local testing guru in your workplace? Or are you considering using pytest for your open source project, but not sure how to get started? Then you may be interested in \"adopt pytest month\"!\n\nWe will pair experienced pytest users with open source projects, for a month's effort of getting new development teams started with pytest.\n\nIn 2015 we are trying this for the first time. In February and March 2015 we will gather volunteers on both sides, in April we will do the work, and in May we will evaluate how it went. This effort is being coordinated by Brianna Laugher. If you have any questions or comments, you can raise them on the `@pytestdotorg twitter account `_ the `issue tracker`_ or the `pytest-dev mailing list`_.\n\n\n.. _`issue tracker`: https://github.com/pytest-dev/pytest/issues/676\n.. _`pytest-dev mailing list`: https://mail.python.org/mailman/listinfo/pytest-dev\n\n\nThe ideal pytest helper\n-----------------------------------------\n\n - will be able to commit 2-4 hours a week to working with their particular project (this might involve joining their mailing list, installing the software and exploring any existing tests, offering advice, writing some example tests)\n - feels confident in using pytest (e.g. has explored command line options, knows how to write parametrized tests, has an idea about conftest contents)\n - does not need to be an expert in every aspect!\n\n`Pytest helpers, sign up here`_! (preferably in February, hard deadline 22 March)\n\n\n.. _`Pytest helpers, sign up here`: http://goo.gl/forms/nxqAhqWt1P\n\n\nThe ideal partner project\n-----------------------------------------\n\n - is open source, and predominantly written in Python\n - has an automated/documented install process for developers\n - has more than one core developer\n - has at least one official release (e.g. is available on pypi)\n - has the support of the core development team, in trying out pytest adoption\n - has no tests... or 100% test coverage... or somewhere in between!\n\n`Partner projects, sign up here`_! (by 22 March)\n\n\n.. _`Partner projects, sign up here`: http://goo.gl/forms/ZGyqlHiwk3\n\n\nWhat does it mean to \"adopt pytest\"?\n-----------------------------------------\n\nThere can be many different definitions of \"success\". Pytest can run many `nose and unittest`_ tests by default, so using pytest as your testrunner may be possible from day 1. Job done, right?\n\nProgressive success might look like:\n\n - tests can be run (by pytest) without errors (there may be failures)\n - tests can be run (by pytest) without failures\n - test runner is integrated into CI server\n - existing tests are rewritten to take advantage of pytest features - this can happen in several iterations, for example:\n - changing to native assert_ statements (pycmd_ has a script to help with that, ``pyconvert_unittest.py``)\n - changing `setUp/tearDown methods`_ to fixtures_\n - adding markers_\n - other changes to reduce boilerplate\n - assess needs for future tests to be written, e.g. new fixtures, distributed_ testing tweaks\n\n\"Success\" should also include that the development team feels comfortable with their knowledge of how to use pytest. In fact this is probably more important than anything else. So spending a lot of time on communication, giving examples, etc will probably be important - both in running the tests, and in writing them.\n\nIt may be after the month is up, the partner project decides that pytest is not right for it. That's okay - hopefully the pytest team will also learn something about its weaknesses or deficiencies.\n\n.. _`nose and unittest`: faq.html#how-does-pytest-relate-to-nose-and-unittest\n.. _assert: asserts.html\n.. _pycmd: https://bitbucket.org/hpk42/pycmd/overview\n.. _`setUp/tearDown methods`: xunit_setup.html\n.. _fixtures: fixture.html\n.. _markers: markers.html\n.. _distributed: xdist.html\n\n\nOther ways to help\n-----------------------------------------\n\nPromote! Do your favourite open source Python projects use pytest? If not, why not tell them about this page?\n"},{"id":933,"name":"funcargs.rst","nodeType":"TextFile","path":"doc/en","text":"\n=======================================================\nfuncargs: resource injection and parametrization\n=======================================================\n\npytest-2.3 introduces major refinements to fixture management\nof which the funcarg mechanism introduced with pytest-2.0 remains\na core part. The documentation has been refactored as well\nand you can read on here:\n\n- :ref:`fixtures`\n- :ref:`parametrize`\n- :ref:`funcargcompare`\n"},{"col":4,"comment":"null","endLoc":1094,"header":"@classmethod\n @overload\n def fromkeys(cls, __iterable: Iterable[_T], __value: None = None) -> dict[_T, Any | None]","id":934,"name":"fromkeys","nodeType":"Function","startLoc":1092,"text":"@classmethod\n @overload\n def fromkeys(cls, __iterable: Iterable[_T], __value: None = None) -> dict[_T, Any | None]: ..."},{"col":4,"comment":"null","endLoc":1097,"header":"@classmethod\n @overload\n def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> dict[_T, _S]","id":935,"name":"fromkeys","nodeType":"Function","startLoc":1095,"text":"@classmethod\n @overload\n def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> dict[_T, _S]: ..."},{"id":936,"name":"testing/example_scripts/fixtures/fill_fixtures/test_conftest_funcargs_only_available_in_subdir/sub1","nodeType":"Package"},{"fileName":"test_in_sub1.py","filePath":"testing/example_scripts/fixtures/fill_fixtures/test_conftest_funcargs_only_available_in_subdir/sub1","id":937,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ndef test_1(arg1):\n pass\n"},{"col":0,"comment":"null","endLoc":3,"header":"def test_1(arg1)","id":938,"name":"test_1","nodeType":"Function","startLoc":2,"text":"def test_1(arg1):\n pass"},{"col":0,"comment":"null","endLoc":60,"header":"def test_repr_on_newstyle()","id":939,"name":"test_repr_on_newstyle","nodeType":"Function","startLoc":55,"text":"def test_repr_on_newstyle():\n class Function(object):\n def __repr__(self):\n return \"<%s>\" % (self.name)\n\n assert saferepr(Function())"},{"fileName":"manyparam.py","filePath":"bench","id":940,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\n@pytest.fixture(scope=\"module\", params=range(966))\ndef foo(request):\n return request.param\n\n\ndef test_it(foo):\n pass\n\n\ndef test_it2(foo):\n pass\n"},{"col":0,"comment":"null","endLoc":7,"header":"@pytest.fixture(scope=\"module\", params=range(966))\ndef foo(request)","id":941,"name":"foo","nodeType":"Function","startLoc":5,"text":"@pytest.fixture(scope=\"module\", params=range(966))\ndef foo(request):\n return request.param"},{"col":4,"comment":"null","endLoc":236,"header":"def test_startswith_nested(self)","id":942,"name":"test_startswith_nested","nodeType":"Function","startLoc":229,"text":"def test_startswith_nested(self):\n def f():\n return \"123\"\n\n def g():\n return \"456\"\n\n assert f().startswith(g())"},{"col":4,"comment":"null","endLoc":1443,"header":"def _initrequest(self)","id":945,"name":"_initrequest","nodeType":"Function","startLoc":1441,"text":"def _initrequest(self):\n self.funcargs = {}\n self._request = fixtures.FixtureRequest(self)"},{"col":0,"comment":"null","endLoc":66,"header":"def test_unicode()","id":946,"name":"test_unicode","nodeType":"Function","startLoc":63,"text":"def test_unicode():\n val = u\"£€\"\n reprval = u\"'£€'\"\n assert saferepr(val) == reprval"},{"col":4,"comment":"null","endLoc":239,"header":"def test_global_func(self)","id":947,"name":"test_global_func","nodeType":"Function","startLoc":238,"text":"def test_global_func(self):\n assert isinstance(globf(42), float)"},{"col":0,"comment":"null","endLoc":162,"header":"def globf(x)","id":948,"name":"globf","nodeType":"Function","startLoc":161,"text":"def globf(x):\n return x + 1"},{"col":4,"comment":"null","endLoc":243,"header":"def test_instance(self)","id":949,"name":"test_instance","nodeType":"Function","startLoc":241,"text":"def test_instance(self):\n self.x = 6 * 7\n assert self.x != 42"},{"col":4,"comment":"null","endLoc":246,"header":"def test_compare(self)","id":950,"name":"test_compare","nodeType":"Function","startLoc":245,"text":"def test_compare(self):\n assert globf(10) < 5"},{"id":951,"name":"src/_pytest/assertion","nodeType":"Package"},{"fileName":"__init__.py","filePath":"src/_pytest/assertion","id":952,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"\nsupport for presenting detailed information in failing assertions.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\n\nimport six\n\nfrom _pytest.assertion import rewrite\nfrom _pytest.assertion import truncate\nfrom _pytest.assertion import util\n\n\ndef pytest_addoption(parser):\n group = parser.getgroup(\"debugconfig\")\n group.addoption(\n \"--assert\",\n action=\"store\",\n dest=\"assertmode\",\n choices=(\"rewrite\", \"plain\"),\n default=\"rewrite\",\n metavar=\"MODE\",\n help=\"\"\"Control assertion debugging tools. 'plain'\n performs no assertion debugging. 'rewrite'\n (the default) rewrites assert statements in\n test modules on import to provide assert\n expression information.\"\"\",\n )\n\n\ndef register_assert_rewrite(*names):\n \"\"\"Register one or more module names to be rewritten on import.\n\n This function will make sure that this module or all modules inside\n the package will get their assert statements rewritten.\n Thus you should make sure to call this before the module is\n actually imported, usually in your __init__.py if you are a plugin\n using a package.\n\n :raise TypeError: if the given module names are not strings.\n \"\"\"\n for name in names:\n if not isinstance(name, str):\n msg = \"expected module names as *args, got {0} instead\"\n raise TypeError(msg.format(repr(names)))\n for hook in sys.meta_path:\n if isinstance(hook, rewrite.AssertionRewritingHook):\n importhook = hook\n break\n else:\n importhook = DummyRewriteHook()\n importhook.mark_rewrite(*names)\n\n\nclass DummyRewriteHook(object):\n \"\"\"A no-op import hook for when rewriting is disabled.\"\"\"\n\n def mark_rewrite(self, *names):\n pass\n\n\nclass AssertionState(object):\n \"\"\"State for the assertion plugin.\"\"\"\n\n def __init__(self, config, mode):\n self.mode = mode\n self.trace = config.trace.root.get(\"assertion\")\n self.hook = None\n\n\ndef install_importhook(config):\n \"\"\"Try to install the rewrite hook, raise SystemError if it fails.\"\"\"\n # Jython has an AST bug that make the assertion rewriting hook malfunction.\n if sys.platform.startswith(\"java\"):\n raise SystemError(\"rewrite not supported\")\n\n config._assertstate = AssertionState(config, \"rewrite\")\n config._assertstate.hook = hook = rewrite.AssertionRewritingHook(config)\n sys.meta_path.insert(0, hook)\n config._assertstate.trace(\"installed rewrite import hook\")\n\n def undo():\n hook = config._assertstate.hook\n if hook is not None and hook in sys.meta_path:\n sys.meta_path.remove(hook)\n\n config.add_cleanup(undo)\n return hook\n\n\ndef pytest_collection(session):\n # this hook is only called when test modules are collected\n # so for example not in the master process of pytest-xdist\n # (which does not collect test modules)\n assertstate = getattr(session.config, \"_assertstate\", None)\n if assertstate:\n if assertstate.hook is not None:\n assertstate.hook.set_session(session)\n\n\ndef pytest_runtest_setup(item):\n \"\"\"Setup the pytest_assertrepr_compare hook\n\n The newinterpret and rewrite modules will use util._reprcompare if\n it exists to use custom reporting via the\n pytest_assertrepr_compare hook. This sets up this custom\n comparison for the test.\n \"\"\"\n\n def callbinrepr(op, left, right):\n \"\"\"Call the pytest_assertrepr_compare hook and prepare the result\n\n This uses the first result from the hook and then ensures the\n following:\n * Overly verbose explanations are truncated unless configured otherwise\n (eg. if running in verbose mode).\n * Embedded newlines are escaped to help util.format_explanation()\n later.\n * If the rewrite mode is used embedded %-characters are replaced\n to protect later % formatting.\n\n The result can be formatted by util.format_explanation() for\n pretty printing.\n \"\"\"\n hook_result = item.ihook.pytest_assertrepr_compare(\n config=item.config, op=op, left=left, right=right\n )\n for new_expl in hook_result:\n if new_expl:\n new_expl = truncate.truncate_if_required(new_expl, item)\n new_expl = [line.replace(\"\\n\", \"\\\\n\") for line in new_expl]\n res = six.text_type(\"\\n~\").join(new_expl)\n if item.config.getvalue(\"assertmode\") == \"rewrite\":\n res = res.replace(\"%\", \"%%\")\n return res\n\n util._reprcompare = callbinrepr\n\n\ndef pytest_runtest_teardown(item):\n util._reprcompare = None\n\n\ndef pytest_sessionfinish(session):\n assertstate = getattr(session.config, \"_assertstate\", None)\n if assertstate:\n if assertstate.hook is not None:\n assertstate.hook.set_session(None)\n\n\n# Expose this plugin's implementation for the pytest_assertrepr_compare hook\npytest_assertrepr_compare = util.assertrepr_compare\n"},{"col":4,"comment":"null","endLoc":253,"header":"def test_try_finally(self)","id":953,"name":"test_try_finally","nodeType":"Function","startLoc":248,"text":"def test_try_finally(self):\n x = 1\n try:\n assert x == 0\n finally:\n x = 0"},{"attributeType":"int","col":8,"comment":"null","endLoc":242,"id":954,"name":"x","nodeType":"Attribute","startLoc":242,"text":"self.x"},{"className":"DummyRewriteHook","col":0,"comment":"A no-op import hook for when rewriting is disabled.","endLoc":63,"id":955,"nodeType":"Class","startLoc":59,"text":"class DummyRewriteHook(object):\n \"\"\"A no-op import hook for when rewriting is disabled.\"\"\"\n\n def mark_rewrite(self, *names):\n pass"},{"col":4,"comment":"null","endLoc":63,"header":"def mark_rewrite(self, *names)","id":956,"name":"mark_rewrite","nodeType":"Function","startLoc":62,"text":"def mark_rewrite(self, *names):\n pass"},{"className":"AssertionState","col":0,"comment":"State for the assertion plugin.","endLoc":72,"id":957,"nodeType":"Class","startLoc":66,"text":"class AssertionState(object):\n \"\"\"State for the assertion plugin.\"\"\"\n\n def __init__(self, config, mode):\n self.mode = mode\n self.trace = config.trace.root.get(\"assertion\")\n self.hook = None"},{"col":4,"comment":"null","endLoc":72,"header":"def __init__(self, config, mode)","id":958,"name":"__init__","nodeType":"Function","startLoc":69,"text":"def __init__(self, config, mode):\n self.mode = mode\n self.trace = config.trace.root.get(\"assertion\")\n self.hook = None"},{"attributeType":"null","col":8,"comment":"null","endLoc":70,"id":959,"name":"mode","nodeType":"Attribute","startLoc":70,"text":"self.mode"},{"attributeType":"null","col":8,"comment":"null","endLoc":71,"id":960,"name":"trace","nodeType":"Attribute","startLoc":71,"text":"self.trace"},{"col":4,"comment":"null","endLoc":956,"header":"def __init__(self, definition, fixtureinfo, config, cls=None, module=None)","id":961,"name":"__init__","nodeType":"Function","startLoc":932,"text":"def __init__(self, definition, fixtureinfo, config, cls=None, module=None):\n assert (\n isinstance(definition, FunctionDefinition)\n or type(definition).__name__ == \"DefinitionMock\"\n )\n self.definition = definition\n\n #: access to the :class:`_pytest.config.Config` object for the test session\n self.config = config\n\n #: the module object where the test function is defined in.\n self.module = module\n\n #: underlying python test function\n self.function = definition.obj\n\n #: set of fixture names required by the test function\n self.fixturenames = fixtureinfo.names_closure\n\n #: class object where the test function is defined in or ``None``.\n self.cls = cls\n\n self._calls = []\n self._ids = set()\n self._arg2fixturedefs = fixtureinfo.name2fixturedefs"},{"attributeType":"None","col":8,"comment":"null","endLoc":72,"id":964,"name":"hook","nodeType":"Attribute","startLoc":72,"text":"self.hook"},{"col":4,"comment":" initialize from given python traceback object and ExceptionInfo ","endLoc":298,"header":"def __init__(self, tb, excinfo=None)","id":965,"name":"__init__","nodeType":"Function","startLoc":286,"text":"def __init__(self, tb, excinfo=None):\n \"\"\" initialize from given python traceback object and ExceptionInfo \"\"\"\n self._excinfo = excinfo\n if hasattr(tb, \"tb_next\"):\n\n def f(cur):\n while cur is not None:\n yield self.Entry(cur, excinfo=excinfo)\n cur = cur.tb_next\n\n list.__init__(self, f(tb))\n else:\n list.__init__(self, tb)"},{"col":0,"comment":"null","endLoc":32,"header":"def pytest_addoption(parser)","id":966,"name":"pytest_addoption","nodeType":"Function","startLoc":18,"text":"def pytest_addoption(parser):\n group = parser.getgroup(\"debugconfig\")\n group.addoption(\n \"--assert\",\n action=\"store\",\n dest=\"assertmode\",\n choices=(\"rewrite\", \"plain\"),\n default=\"rewrite\",\n metavar=\"MODE\",\n help=\"\"\"Control assertion debugging tools. 'plain'\n performs no assertion debugging. 'rewrite'\n (the default) rewrites assert statements in\n test modules on import to provide assert\n expression information.\"\"\",\n )"},{"className":"TestCustomAssertMsg","col":0,"comment":"null","endLoc":282,"id":967,"nodeType":"Class","startLoc":256,"text":"class TestCustomAssertMsg(object):\n def test_single_line(self):\n class A(object):\n a = 1\n\n b = 2\n assert A.a == b, \"A.a appears not to be b\"\n\n def test_multiline(self):\n class A(object):\n a = 1\n\n b = 2\n assert (\n A.a == b\n ), \"A.a appears not to be b\\nor does not appear to be b\\none of those\"\n\n def test_custom_repr(self):\n class JSON(object):\n a = 1\n\n def __repr__(self):\n return \"This is JSON\\n{\\n 'foo': 'bar'\\n}\"\n\n a = JSON()\n b = 2\n assert a.a == b, a"},{"col":0,"comment":"Try to install the rewrite hook, raise SystemError if it fails.","endLoc":92,"header":"def install_importhook(config)","id":968,"name":"install_importhook","nodeType":"Function","startLoc":75,"text":"def install_importhook(config):\n \"\"\"Try to install the rewrite hook, raise SystemError if it fails.\"\"\"\n # Jython has an AST bug that make the assertion rewriting hook malfunction.\n if sys.platform.startswith(\"java\"):\n raise SystemError(\"rewrite not supported\")\n\n config._assertstate = AssertionState(config, \"rewrite\")\n config._assertstate.hook = hook = rewrite.AssertionRewritingHook(config)\n sys.meta_path.insert(0, hook)\n config._assertstate.trace(\"installed rewrite import hook\")\n\n def undo():\n hook = config._assertstate.hook\n if hook is not None and hook in sys.meta_path:\n sys.meta_path.remove(hook)\n\n config.add_cleanup(undo)\n return hook"},{"col":4,"comment":"null","endLoc":262,"header":"def test_single_line(self)","id":969,"name":"test_single_line","nodeType":"Function","startLoc":257,"text":"def test_single_line(self):\n class A(object):\n a = 1\n\n b = 2\n assert A.a == b, \"A.a appears not to be b\""},{"col":4,"comment":"null","endLoc":271,"header":"def test_multiline(self)","id":970,"name":"test_multiline","nodeType":"Function","startLoc":264,"text":"def test_multiline(self):\n class A(object):\n a = 1\n\n b = 2\n assert (\n A.a == b\n ), \"A.a appears not to be b\\nor does not appear to be b\\none of those\""},{"col":4,"comment":"null","endLoc":282,"header":"def test_custom_repr(self)","id":971,"name":"test_custom_repr","nodeType":"Function","startLoc":273,"text":"def test_custom_repr(self):\n class JSON(object):\n a = 1\n\n def __repr__(self):\n return \"This is JSON\\n{\\n 'foo': 'bar'\\n}\"\n\n a = JSON()\n b = 2\n assert a.a == b, a"},{"col":4,"comment":"null","endLoc":109,"header":"def add_property(self, name, value)","id":972,"name":"add_property","nodeType":"Function","startLoc":108,"text":"def add_property(self, name, value):\n self.properties.append((str(name), bin_xml_escape(value)))"},{"col":0,"comment":"null","endLoc":21,"header":"@pytest.mark.parametrize(\"param1, param2\", [(3, 6)])\ndef test_generative(param1, param2)","id":973,"name":"test_generative","nodeType":"Function","startLoc":19,"text":"@pytest.mark.parametrize(\"param1, param2\", [(3, 6)])\ndef test_generative(param1, param2):\n assert param1 * 2 < param2"},{"col":4,"comment":"null","endLoc":69,"header":"def __init__(self, expected, rel=None, abs=None, nan_ok=False)","id":974,"name":"__init__","nodeType":"Function","startLoc":63,"text":"def __init__(self, expected, rel=None, abs=None, nan_ok=False):\n __tracebackhide__ = True\n self.expected = expected\n self.abs = abs\n self.rel = rel\n self.nan_ok = nan_ok\n self._check_type()"},{"col":4,"comment":"\n Raise a TypeError if the expected value is not a valid type.\n ","endLoc":106,"header":"def _check_type(self)","id":975,"name":"_check_type","nodeType":"Function","startLoc":97,"text":"def _check_type(self):\n \"\"\"\n Raise a TypeError if the expected value is not a valid type.\n \"\"\"\n # This is only a concern if the expected value is a sequence. In every\n # other case, the approx() function ensures that the expected value has\n # a numeric type. For this reason, the default is to do nothing. The\n # classes that deal with sequences should reimplement this method to\n # raise if there are any non-numeric elements in the sequence.\n pass"},{"className":"MyDocTestRunner","col":0,"comment":"null","endLoc":25,"id":976,"nodeType":"Class","startLoc":16,"text":"class MyDocTestRunner(doctest.DocTestRunner):\n def __init__(self):\n doctest.DocTestRunner.__init__(self)\n\n def report_failure(self, out, test, example, got):\n raise AssertionError(\n \"'{}' evaluates to '{}', not '{}'\".format(\n example.source.strip(), got.strip(), example.want.strip()\n )\n )"},{"className":"DocTestRunner","col":0,"comment":"null","endLoc":147,"id":977,"nodeType":"Class","startLoc":131,"text":"class DocTestRunner:\n DIVIDER: str\n optionflags: int\n original_optionflags: int\n tries: int\n failures: int\n test: DocTest\n def __init__(self, checker: OutputChecker | None = None, verbose: bool | None = None, optionflags: int = 0) -> None: ...\n def report_start(self, out: _Out, test: DocTest, example: Example) -> None: ...\n def report_success(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ...\n def report_failure(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ...\n def report_unexpected_exception(self, out: _Out, test: DocTest, example: Example, exc_info: ExcInfo) -> None: ...\n def run(\n self, test: DocTest, compileflags: int | None = None, out: _Out | None = None, clear_globs: bool = True\n ) -> TestResults: ...\n def summarize(self, verbose: bool | None = None) -> TestResults: ...\n def merge(self, other: DocTestRunner) -> None: ..."},{"col":4,"comment":"null","endLoc":175,"header":"def __init__(self, rawentry, excinfo=None)","id":978,"name":"__init__","nodeType":"Function","startLoc":172,"text":"def __init__(self, rawentry, excinfo=None):\n self._excinfo = excinfo\n self._rawentry = rawentry\n self.lineno = rawentry.tb_lineno - 1"},{"col":4,"comment":"null","endLoc":138,"header":"def __init__(self, checker: OutputChecker | None = None, verbose: bool | None = None, optionflags: int = 0) -> None","id":980,"name":"__init__","nodeType":"Function","startLoc":138,"text":"def __init__(self, checker: OutputChecker | None = None, verbose: bool | None = None, optionflags: int = 0) -> None: ..."},{"col":4,"comment":"null","endLoc":139,"header":"def report_start(self, out: _Out, test: DocTest, example: Example) -> None","id":981,"name":"report_start","nodeType":"Function","startLoc":139,"text":"def report_start(self, out: _Out, test: DocTest, example: Example) -> None: ..."},{"col":4,"comment":"null","endLoc":140,"header":"def report_success(self, out: _Out, test: DocTest, example: Example, got: str) -> None","id":982,"name":"report_success","nodeType":"Function","startLoc":140,"text":"def report_success(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ..."},{"col":4,"comment":"null","endLoc":141,"header":"def report_failure(self, out: _Out, test: DocTest, example: Example, got: str) -> None","id":983,"name":"report_failure","nodeType":"Function","startLoc":141,"text":"def report_failure(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ..."},{"col":4,"comment":"null","endLoc":142,"header":"def report_unexpected_exception(self, out: _Out, test: DocTest, example: Example, exc_info: ExcInfo) -> None","id":984,"name":"report_unexpected_exception","nodeType":"Function","startLoc":142,"text":"def report_unexpected_exception(self, out: _Out, test: DocTest, example: Example, exc_info: ExcInfo) -> None: ..."},{"col":4,"comment":"null","endLoc":145,"header":"def run(\n self, test: DocTest, compileflags: int | None = None, out: _Out | None = None, clear_globs: bool = True\n ) -> TestResults","id":985,"name":"run","nodeType":"Function","startLoc":143,"text":"def run(\n self, test: DocTest, compileflags: int | None = None, out: _Out | None = None, clear_globs: bool = True\n ) -> TestResults: ..."},{"col":4,"comment":"null","endLoc":146,"header":"def summarize(self, verbose: bool | None = None) -> TestResults","id":986,"name":"summarize","nodeType":"Function","startLoc":146,"text":"def summarize(self, verbose: bool | None = None) -> TestResults: ..."},{"col":4,"comment":"null","endLoc":147,"header":"def merge(self, other: DocTestRunner) -> None","id":987,"name":"merge","nodeType":"Function","startLoc":147,"text":"def merge(self, other: DocTestRunner) -> None: ..."},{"attributeType":"str","col":4,"comment":"null","endLoc":132,"id":988,"name":"DIVIDER","nodeType":"Attribute","startLoc":132,"text":"DIVIDER"},{"attributeType":"int","col":4,"comment":"null","endLoc":133,"id":989,"name":"optionflags","nodeType":"Attribute","startLoc":133,"text":"optionflags"},{"attributeType":"int","col":4,"comment":"null","endLoc":134,"id":990,"name":"original_optionflags","nodeType":"Attribute","startLoc":134,"text":"original_optionflags"},{"attributeType":"int","col":4,"comment":"null","endLoc":135,"id":991,"name":"tries","nodeType":"Attribute","startLoc":135,"text":"tries"},{"attributeType":"int","col":4,"comment":"null","endLoc":136,"id":992,"name":"failures","nodeType":"Attribute","startLoc":136,"text":"failures"},{"attributeType":"DocTest","col":4,"comment":"null","endLoc":137,"id":993,"name":"test","nodeType":"Attribute","startLoc":137,"text":"test"},{"col":4,"comment":"null","endLoc":18,"header":"def __init__(self)","id":994,"name":"__init__","nodeType":"Function","startLoc":17,"text":"def __init__(self):\n doctest.DocTestRunner.__init__(self)"},{"col":0,"comment":"null","endLoc":130,"header":"def test_attribute()","id":995,"name":"test_attribute","nodeType":"Function","startLoc":125,"text":"def test_attribute():\n class Foo(object):\n b = 1\n\n i = Foo()\n assert i.b == 2"},{"className":"Session","col":0,"comment":"null","endLoc":780,"id":996,"nodeType":"Class","startLoc":421,"text":"class Session(nodes.FSCollector):\n Interrupted = Interrupted\n Failed = Failed\n\n def __init__(self, config):\n nodes.FSCollector.__init__(\n self, config.rootdir, parent=None, config=config, session=self, nodeid=\"\"\n )\n self.testsfailed = 0\n self.testscollected = 0\n self.shouldstop = False\n self.shouldfail = False\n self.trace = config.trace.root.get(\"collection\")\n self._norecursepatterns = config.getini(\"norecursedirs\")\n self.startdir = config.invocation_dir\n self._initialpaths = frozenset()\n # Keep track of any collected nodes in here, so we don't duplicate fixtures\n self._node_cache = {}\n self._bestrelpathcache = _bestrelpath_cache(config.rootdir)\n # Dirnames of pkgs with dunder-init files.\n self._pkg_roots = {}\n\n self.config.pluginmanager.register(self, name=\"session\")\n\n def __repr__(self):\n return \"<%s %s exitstatus=%r testsfailed=%d testscollected=%d>\" % (\n self.__class__.__name__,\n self.name,\n getattr(self, \"exitstatus\", \"\"),\n self.testsfailed,\n self.testscollected,\n )\n\n def _node_location_to_relpath(self, node_path):\n # bestrelpath is a quite slow function\n return self._bestrelpathcache[node_path]\n\n @hookimpl(tryfirst=True)\n def pytest_collectstart(self):\n if self.shouldfail:\n raise self.Failed(self.shouldfail)\n if self.shouldstop:\n raise self.Interrupted(self.shouldstop)\n\n @hookimpl(tryfirst=True)\n def pytest_runtest_logreport(self, report):\n if report.failed and not hasattr(report, \"wasxfail\"):\n self.testsfailed += 1\n maxfail = self.config.getvalue(\"maxfail\")\n if maxfail and self.testsfailed >= maxfail:\n self.shouldfail = \"stopping after %d failures\" % (self.testsfailed)\n\n pytest_collectreport = pytest_runtest_logreport\n\n def isinitpath(self, path):\n return path in self._initialpaths\n\n def gethookproxy(self, fspath):\n # check if we have the common case of running\n # hooks with all conftest.py files\n pm = self.config.pluginmanager\n my_conftestmodules = pm._getconftestmodules(fspath)\n remove_mods = pm._conftest_plugins.difference(my_conftestmodules)\n if remove_mods:\n # one or more conftests are not in use at this fspath\n proxy = FSHookProxy(fspath, pm, remove_mods)\n else:\n # all plugis are active for this fspath\n proxy = self.config.hook\n return proxy\n\n def perform_collect(self, args=None, genitems=True):\n hook = self.config.hook\n try:\n items = self._perform_collect(args, genitems)\n self.config.pluginmanager.check_pending()\n hook.pytest_collection_modifyitems(\n session=self, config=self.config, items=items\n )\n finally:\n hook.pytest_collection_finish(session=self)\n self.testscollected = len(items)\n return items\n\n def _perform_collect(self, args, genitems):\n if args is None:\n args = self.config.args\n self.trace(\"perform_collect\", self, args)\n self.trace.root.indent += 1\n self._notfound = []\n initialpaths = []\n self._initialparts = []\n self.items = items = []\n for arg in args:\n parts = self._parsearg(arg)\n self._initialparts.append(parts)\n initialpaths.append(parts[0])\n self._initialpaths = frozenset(initialpaths)\n rep = collect_one_node(self)\n self.ihook.pytest_collectreport(report=rep)\n self.trace.root.indent -= 1\n if self._notfound:\n errors = []\n for arg, exc in self._notfound:\n line = \"(no name %r in any of %r)\" % (arg, exc.args[0])\n errors.append(\"not found: %s\\n%s\" % (arg, line))\n # XXX: test this\n raise UsageError(*errors)\n if not genitems:\n return rep.result\n else:\n if rep.passed:\n for node in rep.result:\n self.items.extend(self.genitems(node))\n return items\n\n def collect(self):\n for initialpart in self._initialparts:\n arg = \"::\".join(map(str, initialpart))\n self.trace(\"processing argument\", arg)\n self.trace.root.indent += 1\n try:\n for x in self._collect(arg):\n yield x\n except NoMatch:\n # we are inside a make_report hook so\n # we cannot directly pass through the exception\n self._notfound.append((arg, sys.exc_info()[1]))\n\n self.trace.root.indent -= 1\n\n def _collect(self, arg):\n from _pytest.python import Package\n\n names = self._parsearg(arg)\n argpath = names.pop(0)\n\n # Start with a Session root, and delve to argpath item (dir or file)\n # and stack all Packages found on the way.\n # No point in finding packages when collecting doctests\n if not self.config.getoption(\"doctestmodules\", False):\n pm = self.config.pluginmanager\n for parent in reversed(argpath.parts()):\n if pm._confcutdir and pm._confcutdir.relto(parent):\n break\n\n if parent.isdir():\n pkginit = parent.join(\"__init__.py\")\n if pkginit.isfile():\n if pkginit not in self._node_cache:\n col = self._collectfile(pkginit, handle_dupes=False)\n if col:\n if isinstance(col[0], Package):\n self._pkg_roots[parent] = col[0]\n # always store a list in the cache, matchnodes expects it\n self._node_cache[col[0].fspath] = [col[0]]\n\n # If it's a directory argument, recurse and look for any Subpackages.\n # Let the Package collector deal with subnodes, don't collect here.\n if argpath.check(dir=1):\n assert not names, \"invalid arg %r\" % (arg,)\n\n seen_dirs = set()\n for path in argpath.visit(\n fil=self._visit_filter, rec=self._recurse, bf=True, sort=True\n ):\n dirpath = path.dirpath()\n if dirpath not in seen_dirs:\n # Collect packages first.\n seen_dirs.add(dirpath)\n pkginit = dirpath.join(\"__init__.py\")\n if pkginit.exists():\n for x in self._collectfile(pkginit):\n yield x\n if isinstance(x, Package):\n self._pkg_roots[dirpath] = x\n if dirpath in self._pkg_roots:\n # Do not collect packages here.\n continue\n\n for x in self._collectfile(path):\n key = (type(x), x.fspath)\n if key in self._node_cache:\n yield self._node_cache[key]\n else:\n self._node_cache[key] = x\n yield x\n else:\n assert argpath.check(file=1)\n\n if argpath in self._node_cache:\n col = self._node_cache[argpath]\n else:\n collect_root = self._pkg_roots.get(argpath.dirname, self)\n col = collect_root._collectfile(argpath, handle_dupes=False)\n if col:\n self._node_cache[argpath] = col\n m = self.matchnodes(col, names)\n # If __init__.py was the only file requested, then the matched node will be\n # the corresponding Package, and the first yielded item will be the __init__\n # Module itself, so just use that. If this special case isn't taken, then all\n # the files in the package will be yielded.\n if argpath.basename == \"__init__.py\":\n try:\n yield next(m[0].collect())\n except StopIteration:\n # The package collects nothing with only an __init__.py\n # file in it, which gets ignored by the default\n # \"python_files\" option.\n pass\n return\n for y in m:\n yield y\n\n def _collectfile(self, path, handle_dupes=True):\n assert path.isfile(), \"%r is not a file (isdir=%r, exists=%r, islink=%r)\" % (\n path,\n path.isdir(),\n path.exists(),\n path.islink(),\n )\n ihook = self.gethookproxy(path)\n if not self.isinitpath(path):\n if ihook.pytest_ignore_collect(path=path, config=self.config):\n return ()\n\n if handle_dupes:\n keepduplicates = self.config.getoption(\"keepduplicates\")\n if not keepduplicates:\n duplicate_paths = self.config.pluginmanager._duplicatepaths\n if path in duplicate_paths:\n return ()\n else:\n duplicate_paths.add(path)\n\n return ihook.pytest_collect_file(path=path, parent=self)\n\n def _recurse(self, dirpath):\n if dirpath.basename == \"__pycache__\":\n return False\n ihook = self.gethookproxy(dirpath.dirpath())\n if ihook.pytest_ignore_collect(path=dirpath, config=self.config):\n return False\n for pat in self._norecursepatterns:\n if dirpath.check(fnmatch=pat):\n return False\n ihook = self.gethookproxy(dirpath)\n ihook.pytest_collect_directory(path=dirpath, parent=self)\n return True\n\n if six.PY2:\n\n @staticmethod\n def _visit_filter(f):\n return f.check(file=1) and not f.strpath.endswith(\"*.pyc\")\n\n else:\n\n @staticmethod\n def _visit_filter(f):\n return f.check(file=1)\n\n def _tryconvertpyarg(self, x):\n \"\"\"Convert a dotted module name to path.\"\"\"\n try:\n with _patched_find_module():\n loader = pkgutil.find_loader(x)\n except ImportError:\n return x\n if loader is None:\n return x\n # This method is sometimes invoked when AssertionRewritingHook, which\n # does not define a get_filename method, is already in place:\n try:\n with _patched_find_module():\n path = loader.get_filename(x)\n except AttributeError:\n # Retrieve path from AssertionRewritingHook:\n path = loader.modules[x][0].co_filename\n if loader.is_package(x):\n path = os.path.dirname(path)\n return path\n\n def _parsearg(self, arg):\n \"\"\" return (fspath, names) tuple after checking the file exists. \"\"\"\n parts = str(arg).split(\"::\")\n if self.config.option.pyargs:\n parts[0] = self._tryconvertpyarg(parts[0])\n relpath = parts[0].replace(\"/\", os.sep)\n path = self.config.invocation_dir.join(relpath, abs=True)\n if not path.check():\n if self.config.option.pyargs:\n raise UsageError(\n \"file or package not found: \" + arg + \" (missing __init__.py?)\"\n )\n raise UsageError(\"file not found: \" + arg)\n parts[0] = path.realpath()\n return parts\n\n def matchnodes(self, matching, names):\n self.trace(\"matchnodes\", matching, names)\n self.trace.root.indent += 1\n nodes = self._matchnodes(matching, names)\n num = len(nodes)\n self.trace(\"matchnodes finished -> \", num, \"nodes\")\n self.trace.root.indent -= 1\n if num == 0:\n raise NoMatch(matching, names[:1])\n return nodes\n\n def _matchnodes(self, matching, names):\n if not matching or not names:\n return matching\n name = names[0]\n assert name\n nextnames = names[1:]\n resultnodes = []\n for node in matching:\n if isinstance(node, nodes.Item):\n if not names:\n resultnodes.append(node)\n continue\n assert isinstance(node, nodes.Collector)\n key = (type(node), node.nodeid)\n if key in self._node_cache:\n rep = self._node_cache[key]\n else:\n rep = collect_one_node(node)\n self._node_cache[key] = rep\n if rep.passed:\n has_matched = False\n for x in rep.result:\n # TODO: remove parametrized workaround once collection structure contains parametrization\n if x.name == name or x.name.split(\"[\")[0] == name:\n resultnodes.extend(self.matchnodes([x], nextnames))\n has_matched = True\n # XXX accept IDs that don't have \"()\" for class instances\n if not has_matched and len(rep.result) == 1 and x.name == \"()\":\n nextnames.insert(0, name)\n resultnodes.extend(self.matchnodes([x], nextnames))\n else:\n # report collection failures here to avoid failing to run some test\n # specified in the command line because the module could not be\n # imported (#134)\n node.ihook.pytest_collectreport(report=rep)\n return resultnodes\n\n def genitems(self, node):\n self.trace(\"genitems\", node)\n if isinstance(node, nodes.Item):\n node.ihook.pytest_itemcollected(item=node)\n yield node\n else:\n assert isinstance(node, nodes.Collector)\n rep = collect_one_node(node)\n if rep.passed:\n for subnode in rep.result:\n for x in self.genitems(subnode):\n yield x\n node.ihook.pytest_collectreport(report=rep)"},{"col":0,"comment":"null","endLoc":137,"header":"def test_attribute_instance()","id":997,"name":"test_attribute_instance","nodeType":"Function","startLoc":133,"text":"def test_attribute_instance():\n class Foo(object):\n b = 1\n\n assert Foo().b == 2"},{"col":0,"comment":"null","endLoc":148,"header":"def test_attribute_failure()","id":998,"name":"test_attribute_failure","nodeType":"Function","startLoc":140,"text":"def test_attribute_failure():\n class Foo(object):\n def _get_b(self):\n raise Exception(\"Failed to get attrib\")\n\n b = property(_get_b)\n\n i = Foo()\n assert i.b == 2"},{"col":0,"comment":"null","endLoc":11,"header":"def test_it(foo)","id":999,"name":"test_it","nodeType":"Function","startLoc":10,"text":"def test_it(foo):\n pass"},{"col":0,"comment":"null","endLoc":15,"header":"def test_it2(foo)","id":1000,"name":"test_it2","nodeType":"Function","startLoc":14,"text":"def test_it2(foo):\n pass"},{"fileName":"__init__.py","filePath":"testing/example_scripts/fixtures/fill_fixtures/test_extend_fixture_conftest_conftest/pkg","id":1001,"nodeType":"File","text":""},{"col":0,"comment":"null","endLoc":67,"header":"def bin_xml_escape(arg)","id":1002,"name":"bin_xml_escape","nodeType":"Function","startLoc":59,"text":"def bin_xml_escape(arg):\n def repl(matchobj):\n i = ord(matchobj.group())\n if i <= 0xFF:\n return u\"#x%02X\" % i\n else:\n return u\"#x%04X\" % i\n\n return py.xml.raw(illegal_xml_re.sub(repl, py.xml.escape(arg)))"},{"col":4,"comment":"null","endLoc":25,"header":"def report_failure(self, out, test, example, got)","id":1003,"name":"report_failure","nodeType":"Function","startLoc":20,"text":"def report_failure(self, out, test, example, got):\n raise AssertionError(\n \"'{}' evaluates to '{}', not '{}'\".format(\n example.source.strip(), got.strip(), example.want.strip()\n )\n )"},{"col":4,"comment":"null","endLoc":443,"header":"def __init__(self, config)","id":1006,"name":"__init__","nodeType":"Function","startLoc":425,"text":"def __init__(self, config):\n nodes.FSCollector.__init__(\n self, config.rootdir, parent=None, config=config, session=self, nodeid=\"\"\n )\n self.testsfailed = 0\n self.testscollected = 0\n self.shouldstop = False\n self.shouldfail = False\n self.trace = config.trace.root.get(\"collection\")\n self._norecursepatterns = config.getini(\"norecursedirs\")\n self.startdir = config.invocation_dir\n self._initialpaths = frozenset()\n # Keep track of any collected nodes in here, so we don't duplicate fixtures\n self._node_cache = {}\n self._bestrelpathcache = _bestrelpath_cache(config.rootdir)\n # Dirnames of pkgs with dunder-init files.\n self._pkg_roots = {}\n\n self.config.pluginmanager.register(self, name=\"session\")"},{"col":0,"comment":"null","endLoc":158,"header":"def test_attribute_multiple()","id":1007,"name":"test_attribute_multiple","nodeType":"Function","startLoc":151,"text":"def test_attribute_multiple():\n class Foo(object):\n b = 1\n\n class Bar(object):\n b = 2\n\n assert Foo().b == Bar().b"},{"col":4,"comment":"null","endLoc":376,"header":"def __init__(self, fspath, parent=None, config=None, session=None, nodeid=None)","id":1008,"name":"__init__","nodeType":"Function","startLoc":354,"text":"def __init__(self, fspath, parent=None, config=None, session=None, nodeid=None):\n fspath = py.path.local(fspath) # xxx only for test_resultlog.py?\n name = fspath.basename\n if parent is not None:\n rel = fspath.relto(parent.fspath)\n if rel:\n name = rel\n name = name.replace(os.sep, SEP)\n self.fspath = fspath\n\n session = session or parent.session\n\n if nodeid is None:\n nodeid = self.fspath.relto(session.config.rootdir)\n\n if not nodeid:\n nodeid = _check_initialpaths_for_relpath(session, fspath)\n if nodeid and os.sep != SEP:\n nodeid = nodeid.replace(os.sep, SEP)\n\n super(FSCollector, self).__init__(\n name, parent, config, session, nodeid=nodeid, fspath=fspath\n )"},{"col":0,"comment":"null","endLoc":203,"header":"def test_dynamic_compile_shows_nicely()","id":1009,"name":"test_dynamic_compile_shows_nicely","nodeType":"Function","startLoc":193,"text":"def test_dynamic_compile_shows_nicely():\n import imp\n import sys\n\n src = \"def foo():\\n assert 1 == 0\\n\"\n name = \"abc-123\"\n module = imp.new_module(name)\n code = _pytest._code.compile(src, name, \"exec\")\n exec(code, module.__dict__)\n sys.modules[name] = module\n module.foo()"},{"col":0,"comment":" compile the given source to a raw code object,\n and maintain an internal cache which allows later\n retrieval of the source code for the code object\n and any recursively created code objects.\n ","endLoc":202,"header":"def compile_(source, filename=None, mode=\"exec\", flags=0, dont_inherit=0)","id":1011,"name":"compile_","nodeType":"Function","startLoc":190,"text":"def compile_(source, filename=None, mode=\"exec\", flags=0, dont_inherit=0):\n \"\"\" compile the given source to a raw code object,\n and maintain an internal cache which allows later\n retrieval of the source code for the code object\n and any recursively created code objects.\n \"\"\"\n if isinstance(source, ast.AST):\n # XXX should Source support having AST?\n return compile(source, filename, mode, flags, dont_inherit)\n _genframe = sys._getframe(1) # the caller\n s = Source(source)\n co = s.compile(filename, mode, flags, _genframe=_genframe)\n return co"},{"fileName":"__init__.py","filePath":"testing/example_scripts/fixtures/fill_fixtures/test_conftest_funcargs_only_available_in_subdir/sub1","id":1012,"nodeType":"File","text":""},{"id":1013,"name":"Makefile","nodeType":"TextFile","path":"doc/en","text":"# Makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line.\nSPHINXOPTS =\nSPHINXBUILD = sphinx-build\nPAPER =\nBUILDDIR = _build\n\n# Internal variables.\nPAPEROPT_a4 = -D latex_paper_size=a4\nPAPEROPT_letter = -D latex_paper_size=letter\nALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .\n\nREGENDOC_ARGS := \\\n\t--normalize \"/[ \\t]+\\n/\\n/\" \\\n\t--normalize \"~\\$$REGENDOC_TMPDIR~/home/sweet/project~\" \\\n\t--normalize \"~/path/to/example~/home/sweet/project~\" \\\n\t--normalize \"/in \\d+.\\d+ seconds/in 0.12 seconds/\" \\\n\t--normalize \"@/tmp/pytest-of-.*/pytest-\\d+@PYTEST_TMPDIR@\" \\\n\t--normalize \"@pytest-(\\d+)\\\\.[^ ,]+@pytest-\\1.x.y@\" \\\n\t--normalize \"@(This is pytest version )(\\d+)\\\\.[^ ,]+@\\1\\2.x.y@\" \\\n\t--normalize \"@py-(\\d+)\\\\.[^ ,]+@py-\\1.x.y@\" \\\n\t--normalize \"@pluggy-(\\d+)\\\\.[.\\d,]+@pluggy-\\1.x.y@\" \\\n\t--normalize \"@hypothesis-(\\d+)\\\\.[.\\d,]+@hypothesis-\\1.x.y@\" \\\n\t--normalize \"@Python (\\d+)\\\\.[^ ,]+@Python \\1.x.y@\"\n\n.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest\n\n\nhelp:\n\t@echo \"Please use \\`make ' where is one of\"\n\t@echo \" html to make standalone HTML files\"\n\t@echo \" latexpdf to make LaTeX files and run them through pdflatex\"\n\t@echo \" showtarget to show the pytest.org target directory\"\n\t@echo \" install to install docs to pytest.org/SITETARGET\"\n\t@echo \" install-ldf to install the doc pdf to pytest.org/SITETARGET\"\n\t@echo \" regen to regenerate pytest examples using the installed pytest\"\n\t@echo \" linkcheck to check all external links for integrity\"\n\nclean:\n\t-rm -rf $(BUILDDIR)/*\n\nregen: REGENDOC_FILES:=*.rst */*.rst\nregen:\n\tPYTHONDONTWRITEBYTECODE=1 PYTEST_ADDOPTS=\"-pno:hypothesis -Wignore::pytest.PytestUnknownMarkWarning\" COLUMNS=76 regendoc --update ${REGENDOC_FILES} ${REGENDOC_ARGS}\n\nhtml:\n\t$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html\n\t@echo\n\t@echo \"Build finished. The HTML pages are in $(BUILDDIR)/html.\"\n\ndirhtml:\n\t$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml\n\t@echo\n\t@echo \"Build finished. The HTML pages are in $(BUILDDIR)/dirhtml.\"\n\nsinglehtml:\n\t$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml\n\t@echo\n\t@echo \"Build finished. The HTML page is in $(BUILDDIR)/singlehtml.\"\n\npickle:\n\t$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle\n\t@echo\n\t@echo \"Build finished; now you can process the pickle files.\"\n\njson:\n\t$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json\n\t@echo\n\t@echo \"Build finished; now you can process the JSON files.\"\n\nhtmlhelp:\n\t$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp\n\t@echo\n\t@echo \"Build finished; now you can run HTML Help Workshop with the\" \\\n\t \".hhp project file in $(BUILDDIR)/htmlhelp.\"\n\nqthelp:\n\t$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp\n\t@echo\n\t@echo \"Build finished; now you can run \"qcollectiongenerator\" with the\" \\\n\t \".qhcp project file in $(BUILDDIR)/qthelp, like this:\"\n\t@echo \"# qcollectiongenerator $(BUILDDIR)/qthelp/pytest.qhcp\"\n\t@echo \"To view the help file:\"\n\t@echo \"# assistant -collectionFile $(BUILDDIR)/qthelp/pytest.qhc\"\n\ndevhelp:\n\t$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp\n\t@echo\n\t@echo \"Build finished.\"\n\t@echo \"To view the help file:\"\n\t@echo \"# mkdir -p $$HOME/.local/share/devhelp/pytest\"\n\t@echo \"# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pytest\"\n\t@echo \"# devhelp\"\n\nepub:\n\t$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub\n\t@echo\n\t@echo \"Build finished. The epub file is in $(BUILDDIR)/epub.\"\n\nlatex:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo\n\t@echo \"Build finished; the LaTeX files are in $(BUILDDIR)/latex.\"\n\t@echo \"Run \\`make' in that directory to run these through (pdf)latex\" \\\n\t \"(use \\`make latexpdf' here to do that automatically).\"\n\nlatexpdf:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo \"Running LaTeX files through pdflatex...\"\n\tmake -C $(BUILDDIR)/latex all-pdf\n\t@echo \"pdflatex finished; the PDF files are in $(BUILDDIR)/latex.\"\n\ntext:\n\t$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text\n\t@echo\n\t@echo \"Build finished. The text files are in $(BUILDDIR)/text.\"\n\nman:\n\t$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man\n\t@echo\n\t@echo \"Build finished. The manual pages are in $(BUILDDIR)/man.\"\n\nchanges:\n\t$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes\n\t@echo\n\t@echo \"The overview file is in $(BUILDDIR)/changes.\"\n\nlinkcheck:\n\t$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck\n\t@echo\n\t@echo \"Link check complete; look for any errors in the above output \" \\\n\t \"or in $(BUILDDIR)/linkcheck/output.txt.\"\n\ndoctest:\n\t$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest\n\t@echo \"Testing of doctests in the sources finished, look at the \" \\\n\t \"results in $(BUILDDIR)/doctest/output.txt.\"\n\ntexinfo:\n\tmkdir -p $(BUILDDIR)/texinfo\n\t$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo\n\t@echo\n\t@echo \"Build finished. The Texinfo files are in $(BUILDDIR)/texinfo.\"\n\t@echo \"Run \\`make' in that directory to run these through makeinfo\" \\\n\t \"(use \\`make info' here to do that automatically).\"\n\ninfo:\n\tmkdir -p $(BUILDDIR)/texinfo\n\t$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo\n\t@echo \"Running Texinfo files through makeinfo...\"\n\tmake -C $(BUILDDIR)/texinfo info\n\t@echo \"makeinfo finished; the Info files are in $(BUILDDIR)/texinfo.\"\n"},{"attributeType":"function","col":4,"comment":"null","endLoc":289,"id":1014,"name":"repr_failure","nodeType":"Attribute","startLoc":289,"text":"repr_failure"},{"attributeType":"null","col":8,"comment":"null","endLoc":87,"id":1015,"name":"extra_keyword_matches","nodeType":"Attribute","startLoc":87,"text":"self.extra_keyword_matches"},{"attributeType":"null","col":8,"comment":"null","endLoc":69,"id":1016,"name":"parent","nodeType":"Attribute","startLoc":69,"text":"self.parent"},{"col":0,"comment":"null","endLoc":350,"header":"def _check_initialpaths_for_relpath(session, fspath)","id":1017,"name":"_check_initialpaths_for_relpath","nodeType":"Function","startLoc":347,"text":"def _check_initialpaths_for_relpath(session, fspath):\n for initial_path in session._initialpaths:\n if fspath.common(initial_path) == initial_path:\n return fspath.relto(initial_path)"},{"attributeType":"null","col":8,"comment":"null","endLoc":81,"id":1018,"name":"keywords","nodeType":"Attribute","startLoc":81,"text":"self.keywords"},{"attributeType":"null","col":8,"comment":"null","endLoc":90,"id":1019,"name":"_name2pseudofixturedef","nodeType":"Attribute","startLoc":90,"text":"self._name2pseudofixturedef"},{"attributeType":"null","col":8,"comment":"null","endLoc":78,"id":1020,"name":"fspath","nodeType":"Attribute","startLoc":78,"text":"self.fspath"},{"attributeType":"null","col":8,"comment":"null","endLoc":75,"id":1021,"name":"session","nodeType":"Attribute","startLoc":75,"text":"self.session"},{"attributeType":"null","col":8,"comment":"null","endLoc":66,"id":1022,"name":"name","nodeType":"Attribute","startLoc":66,"text":"self.name"},{"attributeType":"null","col":8,"comment":"null","endLoc":84,"id":1023,"name":"own_markers","nodeType":"Attribute","startLoc":84,"text":"self.own_markers"},{"attributeType":"null","col":12,"comment":"null","endLoc":96,"id":1024,"name":"_nodeid","nodeType":"Attribute","startLoc":96,"text":"self._nodeid"},{"attributeType":"null","col":8,"comment":"null","endLoc":72,"id":1025,"name":"config","nodeType":"Attribute","startLoc":72,"text":"self.config"},{"col":4,"comment":" returns a list of children (items and collectors)\n for this collection node.\n ","endLoc":322,"header":"def collect(self)","id":1026,"name":"collect","nodeType":"Function","startLoc":318,"text":"def collect(self):\n \"\"\" returns a list of children (items and collectors)\n for this collection node.\n \"\"\"\n raise NotImplementedError(\"abstract\")"},{"id":1027,"name":"testing/code","nodeType":"Package"},{"fileName":"test_code.py","filePath":"testing/code","id":1028,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\n\nfrom six import text_type\nfrom test_excinfo import TWMock\n\nimport _pytest._code\nimport pytest\n\ntry:\n import mock\nexcept ImportError:\n import unittest.mock as mock\n\n\ndef test_ne():\n code1 = _pytest._code.Code(compile('foo = \"bar\"', \"\", \"exec\"))\n assert code1 == code1\n code2 = _pytest._code.Code(compile('foo = \"baz\"', \"\", \"exec\"))\n assert code2 != code1\n\n\ndef test_code_gives_back_name_for_not_existing_file():\n name = \"abc-123\"\n co_code = compile(\"pass\\n\", name, \"exec\")\n assert co_code.co_filename == name\n code = _pytest._code.Code(co_code)\n assert str(code.path) == name\n assert code.fullsource is None\n\n\ndef test_code_with_class():\n class A(object):\n pass\n\n pytest.raises(TypeError, _pytest._code.Code, A)\n\n\ndef x():\n raise NotImplementedError()\n\n\ndef test_code_fullsource():\n code = _pytest._code.Code(x)\n full = code.fullsource\n assert \"test_code_fullsource()\" in str(full)\n\n\ndef test_code_source():\n code = _pytest._code.Code(x)\n src = code.source()\n expected = \"\"\"def x():\n raise NotImplementedError()\"\"\"\n assert str(src) == expected\n\n\ndef test_frame_getsourcelineno_myself():\n def func():\n return sys._getframe(0)\n\n f = func()\n f = _pytest._code.Frame(f)\n source, lineno = f.code.fullsource, f.lineno\n assert source[lineno].startswith(\" return sys._getframe(0)\")\n\n\ndef test_getstatement_empty_fullsource():\n def func():\n return sys._getframe(0)\n\n f = func()\n f = _pytest._code.Frame(f)\n with mock.patch.object(f.code.__class__, \"fullsource\", None):\n assert f.statement == \"\"\n\n\ndef test_code_from_func():\n co = _pytest._code.Code(test_frame_getsourcelineno_myself)\n assert co.firstlineno\n assert co.path\n\n\ndef test_unicode_handling():\n value = u\"ąć\".encode(\"UTF-8\")\n\n def f():\n raise Exception(value)\n\n excinfo = pytest.raises(Exception, f)\n text_type(excinfo)\n if sys.version_info < (3,):\n bytes(excinfo)\n\n\n@pytest.mark.skipif(sys.version_info[0] >= 3, reason=\"python 2 only issue\")\ndef test_unicode_handling_syntax_error():\n value = u\"ąć\".encode(\"UTF-8\")\n\n def f():\n raise SyntaxError(\"invalid syntax\", (None, 1, 3, value))\n\n excinfo = pytest.raises(Exception, f)\n str(excinfo)\n if sys.version_info[0] < 3:\n text_type(excinfo)\n\n\ndef test_code_getargs():\n def f1(x):\n raise NotImplementedError()\n\n c1 = _pytest._code.Code(f1)\n assert c1.getargs(var=True) == (\"x\",)\n\n def f2(x, *y):\n raise NotImplementedError()\n\n c2 = _pytest._code.Code(f2)\n assert c2.getargs(var=True) == (\"x\", \"y\")\n\n def f3(x, **z):\n raise NotImplementedError()\n\n c3 = _pytest._code.Code(f3)\n assert c3.getargs(var=True) == (\"x\", \"z\")\n\n def f4(x, *y, **z):\n raise NotImplementedError()\n\n c4 = _pytest._code.Code(f4)\n assert c4.getargs(var=True) == (\"x\", \"y\", \"z\")\n\n\ndef test_frame_getargs():\n def f1(x):\n return sys._getframe(0)\n\n fr1 = _pytest._code.Frame(f1(\"a\"))\n assert fr1.getargs(var=True) == [(\"x\", \"a\")]\n\n def f2(x, *y):\n return sys._getframe(0)\n\n fr2 = _pytest._code.Frame(f2(\"a\", \"b\", \"c\"))\n assert fr2.getargs(var=True) == [(\"x\", \"a\"), (\"y\", (\"b\", \"c\"))]\n\n def f3(x, **z):\n return sys._getframe(0)\n\n fr3 = _pytest._code.Frame(f3(\"a\", b=\"c\"))\n assert fr3.getargs(var=True) == [(\"x\", \"a\"), (\"z\", {\"b\": \"c\"})]\n\n def f4(x, *y, **z):\n return sys._getframe(0)\n\n fr4 = _pytest._code.Frame(f4(\"a\", \"b\", c=\"d\"))\n assert fr4.getargs(var=True) == [(\"x\", \"a\"), (\"y\", (\"b\",)), (\"z\", {\"c\": \"d\"})]\n\n\nclass TestExceptionInfo(object):\n def test_bad_getsource(self):\n try:\n if False:\n pass\n else:\n assert False\n except AssertionError:\n exci = _pytest._code.ExceptionInfo.from_current()\n assert exci.getrepr()\n\n def test_from_current_with_missing(self):\n with pytest.raises(AssertionError, match=\"no current exception\"):\n _pytest._code.ExceptionInfo.from_current()\n\n\nclass TestTracebackEntry(object):\n def test_getsource(self):\n try:\n if False:\n pass\n else:\n assert False\n except AssertionError:\n exci = _pytest._code.ExceptionInfo.from_current()\n entry = exci.traceback[0]\n source = entry.getsource()\n assert len(source) == 6\n assert \"assert False\" in source[5]\n\n\nclass TestReprFuncArgs(object):\n def test_not_raise_exception_with_mixed_encoding(self):\n from _pytest._code.code import ReprFuncArgs\n\n tw = TWMock()\n\n args = [(\"unicode_string\", u\"São Paulo\"), (\"utf8_string\", b\"S\\xc3\\xa3o Paulo\")]\n\n r = ReprFuncArgs(args)\n r.toterminal(tw)\n if sys.version_info[0] >= 3:\n assert (\n tw.lines[0]\n == r\"unicode_string = São Paulo, utf8_string = b'S\\xc3\\xa3o Paulo'\"\n )\n else:\n assert tw.lines[0] == \"unicode_string = São Paulo, utf8_string = São Paulo\"\n"},{"col":4,"comment":" represent a collection failure. ","endLoc":336,"header":"def repr_failure(self, excinfo)","id":1029,"name":"repr_failure","nodeType":"Function","startLoc":324,"text":"def repr_failure(self, excinfo):\n \"\"\" represent a collection failure. \"\"\"\n if excinfo.errisinstance(self.CollectError):\n exc = excinfo.value\n return str(exc.args[0])\n\n # Respect explicit tbstyle option, but default to \"short\"\n # (None._repr_failure_py defaults to \"long\" without \"fulltrace\" option).\n tbstyle = self.config.getoption(\"tbstyle\", \"auto\")\n if tbstyle == \"auto\":\n tbstyle = \"short\"\n\n return self._repr_failure_py(excinfo, style=tbstyle)"},{"attributeType":"str","col":0,"comment":"null","endLoc":30,"id":1030,"name":"text_type","nodeType":"Attribute","startLoc":30,"text":"text_type"},{"className":"TestApprox","col":0,"comment":"null","endLoc":509,"id":1031,"nodeType":"Class","startLoc":28,"text":"class TestApprox(object):\n @pytest.fixture\n def plus_minus(self):\n return u\"\\u00b1\" if sys.version_info[0] > 2 else u\"+-\"\n\n def test_repr_string(self, plus_minus):\n tol1, tol2, infr = \"1.0e-06\", \"2.0e-06\", \"inf\"\n assert repr(approx(1.0)) == \"1.0 {pm} {tol1}\".format(pm=plus_minus, tol1=tol1)\n assert repr(\n approx([1.0, 2.0])\n ) == \"approx([1.0 {pm} {tol1}, 2.0 {pm} {tol2}])\".format(\n pm=plus_minus, tol1=tol1, tol2=tol2\n )\n assert repr(\n approx((1.0, 2.0))\n ) == \"approx((1.0 {pm} {tol1}, 2.0 {pm} {tol2}))\".format(\n pm=plus_minus, tol1=tol1, tol2=tol2\n )\n assert repr(approx(inf)) == \"inf\"\n assert repr(approx(1.0, rel=nan)) == \"1.0 {pm} ???\".format(pm=plus_minus)\n assert repr(approx(1.0, rel=inf)) == \"1.0 {pm} {infr}\".format(\n pm=plus_minus, infr=infr\n )\n assert repr(approx(1.0j, rel=inf)) == \"1j\"\n\n # Dictionaries aren't ordered, so we need to check both orders.\n assert repr(approx({\"a\": 1.0, \"b\": 2.0})) in (\n \"approx({{'a': 1.0 {pm} {tol1}, 'b': 2.0 {pm} {tol2}}})\".format(\n pm=plus_minus, tol1=tol1, tol2=tol2\n ),\n \"approx({{'b': 2.0 {pm} {tol2}, 'a': 1.0 {pm} {tol1}}})\".format(\n pm=plus_minus, tol1=tol1, tol2=tol2\n ),\n )\n\n @pytest.mark.parametrize(\n \"value, repr_string\",\n [\n (5.0, \"approx(5.0 {pm} 5.0e-06)\"),\n ([5.0], \"approx([5.0 {pm} 5.0e-06])\"),\n ([[5.0]], \"approx([[5.0 {pm} 5.0e-06]])\"),\n ([[5.0, 6.0]], \"approx([[5.0 {pm} 5.0e-06, 6.0 {pm} 6.0e-06]])\"),\n ([[5.0], [6.0]], \"approx([[5.0 {pm} 5.0e-06], [6.0 {pm} 6.0e-06]])\"),\n ],\n )\n def test_repr_nd_array(self, plus_minus, value, repr_string):\n \"\"\"Make sure that arrays of all different dimensions are repr'd correctly.\"\"\"\n np = pytest.importorskip(\"numpy\")\n np_array = np.array(value)\n assert repr(approx(np_array)) == repr_string.format(pm=plus_minus)\n\n def test_operator_overloading(self):\n assert 1 == approx(1, rel=1e-6, abs=1e-12)\n assert not (1 != approx(1, rel=1e-6, abs=1e-12))\n assert 10 != approx(1, rel=1e-6, abs=1e-12)\n assert not (10 == approx(1, rel=1e-6, abs=1e-12))\n\n def test_exactly_equal(self):\n examples = [\n (2.0, 2.0),\n (0.1e200, 0.1e200),\n (1.123e-300, 1.123e-300),\n (12345, 12345.0),\n (0.0, -0.0),\n (345678, 345678),\n (Decimal(\"1.0001\"), Decimal(\"1.0001\")),\n (Fraction(1, 3), Fraction(-1, -3)),\n ]\n for a, x in examples:\n assert a == approx(x)\n\n def test_opposite_sign(self):\n examples = [(eq, 1e-100, -1e-100), (ne, 1e100, -1e100)]\n for op, a, x in examples:\n assert op(a, approx(x))\n\n def test_zero_tolerance(self):\n within_1e10 = [(1.1e-100, 1e-100), (-1.1e-100, -1e-100)]\n for a, x in within_1e10:\n assert x == approx(x, rel=0.0, abs=0.0)\n assert a != approx(x, rel=0.0, abs=0.0)\n assert a == approx(x, rel=0.0, abs=5e-101)\n assert a != approx(x, rel=0.0, abs=5e-102)\n assert a == approx(x, rel=5e-1, abs=0.0)\n assert a != approx(x, rel=5e-2, abs=0.0)\n\n def test_negative_tolerance(self):\n # Negative tolerances are not allowed.\n illegal_kwargs = [\n dict(rel=-1e100),\n dict(abs=-1e100),\n dict(rel=1e100, abs=-1e100),\n dict(rel=-1e100, abs=1e100),\n dict(rel=-1e100, abs=-1e100),\n ]\n for kwargs in illegal_kwargs:\n with pytest.raises(ValueError):\n 1.1 == approx(1, **kwargs)\n\n def test_inf_tolerance(self):\n # Everything should be equal if the tolerance is infinite.\n large_diffs = [(1, 1000), (1e-50, 1e50), (-1.0, -1e300), (0.0, 10)]\n for a, x in large_diffs:\n assert a != approx(x, rel=0.0, abs=0.0)\n assert a == approx(x, rel=inf, abs=0.0)\n assert a == approx(x, rel=0.0, abs=inf)\n assert a == approx(x, rel=inf, abs=inf)\n\n def test_inf_tolerance_expecting_zero(self):\n # If the relative tolerance is zero but the expected value is infinite,\n # the actual tolerance is a NaN, which should be an error.\n illegal_kwargs = [dict(rel=inf, abs=0.0), dict(rel=inf, abs=inf)]\n for kwargs in illegal_kwargs:\n with pytest.raises(ValueError):\n 1 == approx(0, **kwargs)\n\n def test_nan_tolerance(self):\n illegal_kwargs = [dict(rel=nan), dict(abs=nan), dict(rel=nan, abs=nan)]\n for kwargs in illegal_kwargs:\n with pytest.raises(ValueError):\n 1.1 == approx(1, **kwargs)\n\n def test_reasonable_defaults(self):\n # Whatever the defaults are, they should work for numbers close to 1\n # than have a small amount of floating-point error.\n assert 0.1 + 0.2 == approx(0.3)\n\n def test_default_tolerances(self):\n # This tests the defaults as they are currently set. If you change the\n # defaults, this test will fail but you should feel free to change it.\n # None of the other tests (except the doctests) should be affected by\n # the choice of defaults.\n examples = [\n # Relative tolerance used.\n (eq, 1e100 + 1e94, 1e100),\n (ne, 1e100 + 2e94, 1e100),\n (eq, 1e0 + 1e-6, 1e0),\n (ne, 1e0 + 2e-6, 1e0),\n # Absolute tolerance used.\n (eq, 1e-100, +1e-106),\n (eq, 1e-100, +2e-106),\n (eq, 1e-100, 0),\n ]\n for op, a, x in examples:\n assert op(a, approx(x))\n\n def test_custom_tolerances(self):\n assert 1e8 + 1e0 == approx(1e8, rel=5e-8, abs=5e0)\n assert 1e8 + 1e0 == approx(1e8, rel=5e-9, abs=5e0)\n assert 1e8 + 1e0 == approx(1e8, rel=5e-8, abs=5e-1)\n assert 1e8 + 1e0 != approx(1e8, rel=5e-9, abs=5e-1)\n\n assert 1e0 + 1e-8 == approx(1e0, rel=5e-8, abs=5e-8)\n assert 1e0 + 1e-8 == approx(1e0, rel=5e-9, abs=5e-8)\n assert 1e0 + 1e-8 == approx(1e0, rel=5e-8, abs=5e-9)\n assert 1e0 + 1e-8 != approx(1e0, rel=5e-9, abs=5e-9)\n\n assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-8, abs=5e-16)\n assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-9, abs=5e-16)\n assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-8, abs=5e-17)\n assert 1e-8 + 1e-16 != approx(1e-8, rel=5e-9, abs=5e-17)\n\n def test_relative_tolerance(self):\n within_1e8_rel = [(1e8 + 1e0, 1e8), (1e0 + 1e-8, 1e0), (1e-8 + 1e-16, 1e-8)]\n for a, x in within_1e8_rel:\n assert a == approx(x, rel=5e-8, abs=0.0)\n assert a != approx(x, rel=5e-9, abs=0.0)\n\n def test_absolute_tolerance(self):\n within_1e8_abs = [(1e8 + 9e-9, 1e8), (1e0 + 9e-9, 1e0), (1e-8 + 9e-9, 1e-8)]\n for a, x in within_1e8_abs:\n assert a == approx(x, rel=0, abs=5e-8)\n assert a != approx(x, rel=0, abs=5e-9)\n\n def test_expecting_zero(self):\n examples = [\n (ne, 1e-6, 0.0),\n (ne, -1e-6, 0.0),\n (eq, 1e-12, 0.0),\n (eq, -1e-12, 0.0),\n (ne, 2e-12, 0.0),\n (ne, -2e-12, 0.0),\n (ne, inf, 0.0),\n (ne, nan, 0.0),\n ]\n for op, a, x in examples:\n assert op(a, approx(x, rel=0.0, abs=1e-12))\n assert op(a, approx(x, rel=1e-6, abs=1e-12))\n\n def test_expecting_inf(self):\n examples = [\n (eq, inf, inf),\n (eq, -inf, -inf),\n (ne, inf, -inf),\n (ne, 0.0, inf),\n (ne, nan, inf),\n ]\n for op, a, x in examples:\n assert op(a, approx(x))\n\n def test_expecting_nan(self):\n examples = [\n (eq, nan, nan),\n (eq, -nan, -nan),\n (eq, nan, -nan),\n (ne, 0.0, nan),\n (ne, inf, nan),\n ]\n for op, a, x in examples:\n # Nothing is equal to NaN by default.\n assert a != approx(x)\n\n # If ``nan_ok=True``, then NaN is equal to NaN.\n assert op(a, approx(x, nan_ok=True))\n\n def test_int(self):\n within_1e6 = [(1000001, 1000000), (-1000001, -1000000)]\n for a, x in within_1e6:\n assert a == approx(x, rel=5e-6, abs=0)\n assert a != approx(x, rel=5e-7, abs=0)\n assert approx(x, rel=5e-6, abs=0) == a\n assert approx(x, rel=5e-7, abs=0) != a\n\n def test_decimal(self):\n within_1e6 = [\n (Decimal(\"1.000001\"), Decimal(\"1.0\")),\n (Decimal(\"-1.000001\"), Decimal(\"-1.0\")),\n ]\n for a, x in within_1e6:\n assert a == approx(x)\n assert a == approx(x, rel=Decimal(\"5e-6\"), abs=0)\n assert a != approx(x, rel=Decimal(\"5e-7\"), abs=0)\n assert approx(x, rel=Decimal(\"5e-6\"), abs=0) == a\n assert approx(x, rel=Decimal(\"5e-7\"), abs=0) != a\n\n def test_fraction(self):\n within_1e6 = [\n (1 + Fraction(1, 1000000), Fraction(1)),\n (-1 - Fraction(-1, 1000000), Fraction(-1)),\n ]\n for a, x in within_1e6:\n assert a == approx(x, rel=5e-6, abs=0)\n assert a != approx(x, rel=5e-7, abs=0)\n assert approx(x, rel=5e-6, abs=0) == a\n assert approx(x, rel=5e-7, abs=0) != a\n\n def test_complex(self):\n within_1e6 = [\n (1.000001 + 1.0j, 1.0 + 1.0j),\n (1.0 + 1.000001j, 1.0 + 1.0j),\n (-1.000001 + 1.0j, -1.0 + 1.0j),\n (1.0 - 1.000001j, 1.0 - 1.0j),\n ]\n for a, x in within_1e6:\n assert a == approx(x, rel=5e-6, abs=0)\n assert a != approx(x, rel=5e-7, abs=0)\n assert approx(x, rel=5e-6, abs=0) == a\n assert approx(x, rel=5e-7, abs=0) != a\n\n def test_list(self):\n actual = [1 + 1e-7, 2 + 1e-8]\n expected = [1, 2]\n\n # Return false if any element is outside the tolerance.\n assert actual == approx(expected, rel=5e-7, abs=0)\n assert actual != approx(expected, rel=5e-8, abs=0)\n assert approx(expected, rel=5e-7, abs=0) == actual\n assert approx(expected, rel=5e-8, abs=0) != actual\n\n def test_list_wrong_len(self):\n assert [1, 2] != approx([1])\n assert [1, 2] != approx([1, 2, 3])\n\n def test_tuple(self):\n actual = (1 + 1e-7, 2 + 1e-8)\n expected = (1, 2)\n\n # Return false if any element is outside the tolerance.\n assert actual == approx(expected, rel=5e-7, abs=0)\n assert actual != approx(expected, rel=5e-8, abs=0)\n assert approx(expected, rel=5e-7, abs=0) == actual\n assert approx(expected, rel=5e-8, abs=0) != actual\n\n def test_tuple_wrong_len(self):\n assert (1, 2) != approx((1,))\n assert (1, 2) != approx((1, 2, 3))\n\n def test_dict(self):\n actual = {\"a\": 1 + 1e-7, \"b\": 2 + 1e-8}\n # Dictionaries became ordered in python3.6, so switch up the order here\n # to make sure it doesn't matter.\n expected = {\"b\": 2, \"a\": 1}\n\n # Return false if any element is outside the tolerance.\n assert actual == approx(expected, rel=5e-7, abs=0)\n assert actual != approx(expected, rel=5e-8, abs=0)\n assert approx(expected, rel=5e-7, abs=0) == actual\n assert approx(expected, rel=5e-8, abs=0) != actual\n\n def test_dict_wrong_len(self):\n assert {\"a\": 1, \"b\": 2} != approx({\"a\": 1})\n assert {\"a\": 1, \"b\": 2} != approx({\"a\": 1, \"c\": 2})\n assert {\"a\": 1, \"b\": 2} != approx({\"a\": 1, \"b\": 2, \"c\": 3})\n\n def test_numpy_array(self):\n np = pytest.importorskip(\"numpy\")\n\n actual = np.array([1 + 1e-7, 2 + 1e-8])\n expected = np.array([1, 2])\n\n # Return false if any element is outside the tolerance.\n assert actual == approx(expected, rel=5e-7, abs=0)\n assert actual != approx(expected, rel=5e-8, abs=0)\n assert approx(expected, rel=5e-7, abs=0) == expected\n assert approx(expected, rel=5e-8, abs=0) != actual\n\n # Should be able to compare lists with numpy arrays.\n assert list(actual) == approx(expected, rel=5e-7, abs=0)\n assert list(actual) != approx(expected, rel=5e-8, abs=0)\n assert actual == approx(list(expected), rel=5e-7, abs=0)\n assert actual != approx(list(expected), rel=5e-8, abs=0)\n\n def test_numpy_tolerance_args(self):\n \"\"\"\n Check that numpy rel/abs args are handled correctly\n for comparison against an np.array\n Check both sides of the operator, hopefully it doesn't impact things.\n Test all permutations of where the approx and np.array() can show up\n \"\"\"\n np = pytest.importorskip(\"numpy\")\n expected = 100.0\n actual = 99.0\n abs_diff = expected - actual\n rel_diff = (expected - actual) / expected\n\n tests = [\n (eq, abs_diff, 0),\n (eq, 0, rel_diff),\n (ne, 0, rel_diff / 2.0), # rel diff fail\n (ne, abs_diff / 2.0, 0), # abs diff fail\n ]\n\n for op, _abs, _rel in tests:\n assert op(np.array(actual), approx(expected, abs=_abs, rel=_rel)) # a, b\n assert op(approx(expected, abs=_abs, rel=_rel), np.array(actual)) # b, a\n\n assert op(actual, approx(np.array(expected), abs=_abs, rel=_rel)) # a, b\n assert op(approx(np.array(expected), abs=_abs, rel=_rel), actual) # b, a\n\n assert op(np.array(actual), approx(np.array(expected), abs=_abs, rel=_rel))\n assert op(approx(np.array(expected), abs=_abs, rel=_rel), np.array(actual))\n\n def test_numpy_expecting_nan(self):\n np = pytest.importorskip(\"numpy\")\n examples = [\n (eq, nan, nan),\n (eq, -nan, -nan),\n (eq, nan, -nan),\n (ne, 0.0, nan),\n (ne, inf, nan),\n ]\n for op, a, x in examples:\n # Nothing is equal to NaN by default.\n assert np.array(a) != approx(x)\n assert a != approx(np.array(x))\n\n # If ``nan_ok=True``, then NaN is equal to NaN.\n assert op(np.array(a), approx(x, nan_ok=True))\n assert op(a, approx(np.array(x), nan_ok=True))\n\n def test_numpy_expecting_inf(self):\n np = pytest.importorskip(\"numpy\")\n examples = [\n (eq, inf, inf),\n (eq, -inf, -inf),\n (ne, inf, -inf),\n (ne, 0.0, inf),\n (ne, nan, inf),\n ]\n for op, a, x in examples:\n assert op(np.array(a), approx(x))\n assert op(a, approx(np.array(x)))\n assert op(np.array(a), approx(np.array(x)))\n\n def test_numpy_array_wrong_shape(self):\n np = pytest.importorskip(\"numpy\")\n\n a12 = np.array([[1, 2]])\n a21 = np.array([[1], [2]])\n\n assert a12 != approx(a21)\n assert a21 != approx(a12)\n\n def test_doctests(self):\n parser = doctest.DocTestParser()\n test = parser.get_doctest(\n approx.__doc__, {\"approx\": approx}, approx.__name__, None, None\n )\n runner = MyDocTestRunner()\n runner.run(test)\n\n def test_unicode_plus_minus(self, testdir):\n \"\"\"\n Comparing approx instances inside lists should not produce an error in the detailed diff.\n Integration test for issue #2111.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_foo():\n assert [3] == [pytest.approx(4)]\n \"\"\"\n )\n expected = \"4.0e-06\"\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"*At index 0 diff: 3 != 4 * {}\".format(expected), \"=* 1 failed in *=\"]\n )\n\n @pytest.mark.parametrize(\n \"x\",\n [\n pytest.param(None),\n pytest.param(\"string\"),\n pytest.param([\"string\"], id=\"nested-str\"),\n pytest.param([[1]], id=\"nested-list\"),\n pytest.param({\"key\": \"string\"}, id=\"dict-with-string\"),\n pytest.param({\"key\": {\"key\": 1}}, id=\"nested-dict\"),\n ],\n )\n def test_expected_value_type_error(self, x):\n with pytest.raises(TypeError):\n approx(x)\n\n @pytest.mark.parametrize(\n \"op\",\n [\n pytest.param(operator.le, id=\"<=\"),\n pytest.param(operator.lt, id=\"<\"),\n pytest.param(operator.ge, id=\">=\"),\n pytest.param(operator.gt, id=\">\"),\n ],\n )\n def test_comparison_operator_type_error(self, op):\n \"\"\"\n pytest.approx should raise TypeError for operators other than == and != (#2003).\n \"\"\"\n with pytest.raises(TypeError):\n op(1, approx(1, rel=1e-6, abs=1e-12))\n\n def test_numpy_array_with_scalar(self):\n np = pytest.importorskip(\"numpy\")\n\n actual = np.array([1 + 1e-7, 1 - 1e-8])\n expected = 1.0\n\n assert actual == approx(expected, rel=5e-7, abs=0)\n assert actual != approx(expected, rel=5e-8, abs=0)\n assert approx(expected, rel=5e-7, abs=0) == actual\n assert approx(expected, rel=5e-8, abs=0) != actual\n\n def test_numpy_scalar_with_array(self):\n np = pytest.importorskip(\"numpy\")\n\n actual = 1.0\n expected = np.array([1 + 1e-7, 1 - 1e-8])\n\n assert actual == approx(expected, rel=5e-7, abs=0)\n assert actual != approx(expected, rel=5e-8, abs=0)\n assert approx(expected, rel=5e-7, abs=0) == actual\n assert approx(expected, rel=5e-8, abs=0) != actual\n\n def test_generic_sized_iterable_object(self):\n class MySizedIterable(object):\n def __iter__(self):\n return iter([1, 2, 3, 4])\n\n def __len__(self):\n return 4\n\n expected = MySizedIterable()\n assert [1, 2, 3, 4] == approx(expected)"},{"fileName":"metafunc.py","filePath":"testing/python","id":1032,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport re\nimport sys\nimport textwrap\n\nimport attr\nimport hypothesis\nimport six\nfrom hypothesis import strategies\n\nimport pytest\nfrom _pytest import fixtures\nfrom _pytest import python\nfrom _pytest.warnings import SHOW_PYTEST_WARNINGS_ARG\n\nPY3 = sys.version_info >= (3, 0)\n\n\nclass TestMetafunc(object):\n def Metafunc(self, func, config=None):\n # the unit tests of this class check if things work correctly\n # on the funcarg level, so we don't need a full blown\n # initiliazation\n class FixtureInfo(object):\n name2fixturedefs = None\n\n def __init__(self, names):\n self.names_closure = names\n\n @attr.s\n class DefinitionMock(object):\n obj = attr.ib()\n\n names = fixtures.getfuncargnames(func)\n fixtureinfo = FixtureInfo(names)\n definition = DefinitionMock(func)\n return python.Metafunc(definition, fixtureinfo, config)\n\n def test_no_funcargs(self, testdir):\n def function():\n pass\n\n metafunc = self.Metafunc(function)\n assert not metafunc.fixturenames\n repr(metafunc._calls)\n\n def test_function_basic(self):\n def func(arg1, arg2=\"qwe\"):\n pass\n\n metafunc = self.Metafunc(func)\n assert len(metafunc.fixturenames) == 1\n assert \"arg1\" in metafunc.fixturenames\n assert metafunc.function is func\n assert metafunc.cls is None\n\n def test_parametrize_error(self):\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n metafunc.parametrize(\"x\", [1, 2])\n pytest.raises(ValueError, lambda: metafunc.parametrize(\"x\", [5, 6]))\n pytest.raises(ValueError, lambda: metafunc.parametrize(\"x\", [5, 6]))\n metafunc.parametrize(\"y\", [1, 2])\n pytest.raises(ValueError, lambda: metafunc.parametrize(\"y\", [5, 6]))\n pytest.raises(ValueError, lambda: metafunc.parametrize(\"y\", [5, 6]))\n\n def test_parametrize_bad_scope(self, testdir):\n def func(x):\n pass\n\n metafunc = self.Metafunc(func)\n with pytest.raises(\n pytest.fail.Exception,\n match=r\"parametrize\\(\\) call in func got an unexpected scope value 'doggy'\",\n ):\n metafunc.parametrize(\"x\", [1], scope=\"doggy\")\n\n def test_find_parametrized_scope(self):\n \"\"\"unittest for _find_parametrized_scope (#3941)\"\"\"\n from _pytest.python import _find_parametrized_scope\n\n @attr.s\n class DummyFixtureDef(object):\n scope = attr.ib()\n\n fixtures_defs = dict(\n session_fix=[DummyFixtureDef(\"session\")],\n package_fix=[DummyFixtureDef(\"package\")],\n module_fix=[DummyFixtureDef(\"module\")],\n class_fix=[DummyFixtureDef(\"class\")],\n func_fix=[DummyFixtureDef(\"function\")],\n )\n\n # use arguments to determine narrow scope; the cause of the bug is that it would look on all\n # fixture defs given to the method\n def find_scope(argnames, indirect):\n return _find_parametrized_scope(argnames, fixtures_defs, indirect=indirect)\n\n assert find_scope([\"func_fix\"], indirect=True) == \"function\"\n assert find_scope([\"class_fix\"], indirect=True) == \"class\"\n assert find_scope([\"module_fix\"], indirect=True) == \"module\"\n assert find_scope([\"package_fix\"], indirect=True) == \"package\"\n assert find_scope([\"session_fix\"], indirect=True) == \"session\"\n\n assert find_scope([\"class_fix\", \"func_fix\"], indirect=True) == \"function\"\n assert find_scope([\"func_fix\", \"session_fix\"], indirect=True) == \"function\"\n assert find_scope([\"session_fix\", \"class_fix\"], indirect=True) == \"class\"\n assert find_scope([\"package_fix\", \"session_fix\"], indirect=True) == \"package\"\n assert find_scope([\"module_fix\", \"session_fix\"], indirect=True) == \"module\"\n\n # when indirect is False or is not for all scopes, always use function\n assert find_scope([\"session_fix\", \"module_fix\"], indirect=False) == \"function\"\n assert (\n find_scope([\"session_fix\", \"module_fix\"], indirect=[\"module_fix\"])\n == \"function\"\n )\n assert (\n find_scope(\n [\"session_fix\", \"module_fix\"], indirect=[\"session_fix\", \"module_fix\"]\n )\n == \"module\"\n )\n\n def test_parametrize_and_id(self):\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n\n metafunc.parametrize(\"x\", [1, 2], ids=[\"basic\", \"advanced\"])\n metafunc.parametrize(\"y\", [\"abc\", \"def\"])\n ids = [x.id for x in metafunc._calls]\n assert ids == [\"basic-abc\", \"basic-def\", \"advanced-abc\", \"advanced-def\"]\n\n def test_parametrize_and_id_unicode(self):\n \"\"\"Allow unicode strings for \"ids\" parameter in Python 2 (##1905)\"\"\"\n\n def func(x):\n pass\n\n metafunc = self.Metafunc(func)\n metafunc.parametrize(\"x\", [1, 2], ids=[u\"basic\", u\"advanced\"])\n ids = [x.id for x in metafunc._calls]\n assert ids == [u\"basic\", u\"advanced\"]\n\n def test_parametrize_with_wrong_number_of_ids(self, testdir):\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n\n with pytest.raises(pytest.fail.Exception):\n metafunc.parametrize(\"x\", [1, 2], ids=[\"basic\"])\n\n with pytest.raises(pytest.fail.Exception):\n metafunc.parametrize(\n (\"x\", \"y\"), [(\"abc\", \"def\"), (\"ghi\", \"jkl\")], ids=[\"one\"]\n )\n\n def test_parametrize_empty_list(self):\n \"\"\"#510\"\"\"\n\n def func(y):\n pass\n\n class MockConfig(object):\n def getini(self, name):\n return \"\"\n\n @property\n def hook(self):\n return self\n\n def pytest_make_parametrize_id(self, **kw):\n pass\n\n metafunc = self.Metafunc(func, MockConfig())\n metafunc.parametrize(\"y\", [])\n assert \"skip\" == metafunc._calls[0].marks[0].name\n\n def test_parametrize_with_userobjects(self):\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n\n class A(object):\n pass\n\n metafunc.parametrize(\"x\", [A(), A()])\n metafunc.parametrize(\"y\", list(\"ab\"))\n assert metafunc._calls[0].id == \"x0-a\"\n assert metafunc._calls[1].id == \"x0-b\"\n assert metafunc._calls[2].id == \"x1-a\"\n assert metafunc._calls[3].id == \"x1-b\"\n\n @hypothesis.given(strategies.text() | strategies.binary())\n @hypothesis.settings(\n deadline=400.0\n ) # very close to std deadline and CI boxes are not reliable in CPU power\n def test_idval_hypothesis(self, value):\n from _pytest.python import _idval\n\n escaped = _idval(value, \"a\", 6, None, item=None, config=None)\n assert isinstance(escaped, six.text_type)\n escaped.encode(\"ascii\")\n\n def test_unicode_idval(self):\n \"\"\"This tests that Unicode strings outside the ASCII character set get\n escaped, using byte escapes if they're in that range or unicode\n escapes if they're not.\n\n \"\"\"\n from _pytest.python import _idval\n\n values = [\n (u\"\", \"\"),\n (u\"ascii\", \"ascii\"),\n (u\"ação\", \"a\\\\xe7\\\\xe3o\"),\n (u\"josé@blah.com\", \"jos\\\\xe9@blah.com\"),\n (\n u\"δοκ.ιμή@παράδειγμα.δοκιμή\",\n \"\\\\u03b4\\\\u03bf\\\\u03ba.\\\\u03b9\\\\u03bc\\\\u03ae@\\\\u03c0\\\\u03b1\\\\u03c1\\\\u03ac\\\\u03b4\\\\u03b5\\\\u03b9\\\\u03b3\"\n \"\\\\u03bc\\\\u03b1.\\\\u03b4\\\\u03bf\\\\u03ba\\\\u03b9\\\\u03bc\\\\u03ae\",\n ),\n ]\n for val, expected in values:\n assert _idval(val, \"a\", 6, None, item=None, config=None) == expected\n\n def test_unicode_idval_with_config(self):\n \"\"\"unittest for expected behavior to obtain ids with\n disable_test_id_escaping_and_forfeit_all_rights_to_community_support\n option. (#5294)\n \"\"\"\n from _pytest.python import _idval\n\n class MockConfig(object):\n def __init__(self, config):\n self.config = config\n\n @property\n def hook(self):\n return self\n\n def pytest_make_parametrize_id(self, **kw):\n pass\n\n def getini(self, name):\n return self.config[name]\n\n option = \"disable_test_id_escaping_and_forfeit_all_rights_to_community_support\"\n\n values = [\n (u\"ação\", MockConfig({option: True}), u\"ação\"),\n (u\"ação\", MockConfig({option: False}), \"a\\\\xe7\\\\xe3o\"),\n ]\n for val, config, expected in values:\n assert _idval(val, \"a\", 6, None, item=None, config=config) == expected\n\n def test_bytes_idval(self):\n \"\"\"unittest for the expected behavior to obtain ids for parametrized\n bytes values:\n - python2: non-ascii strings are considered bytes and formatted using\n \"binary escape\", where any byte < 127 is escaped into its hex form.\n - python3: bytes objects are always escaped using \"binary escape\".\n \"\"\"\n from _pytest.python import _idval\n\n values = [\n (b\"\", \"\"),\n (b\"\\xc3\\xb4\\xff\\xe4\", \"\\\\xc3\\\\xb4\\\\xff\\\\xe4\"),\n (b\"ascii\", \"ascii\"),\n (u\"αρά\".encode(\"utf-8\"), \"\\\\xce\\\\xb1\\\\xcf\\\\x81\\\\xce\\\\xac\"),\n ]\n for val, expected in values:\n assert _idval(val, \"a\", 6, idfn=None, item=None, config=None) == expected\n\n def test_class_or_function_idval(self):\n \"\"\"unittest for the expected behavior to obtain ids for parametrized\n values that are classes or functions: their __name__.\n \"\"\"\n from _pytest.python import _idval\n\n class TestClass(object):\n pass\n\n def test_function():\n pass\n\n values = [(TestClass, \"TestClass\"), (test_function, \"test_function\")]\n for val, expected in values:\n assert _idval(val, \"a\", 6, None, item=None, config=None) == expected\n\n def test_idmaker_autoname(self):\n \"\"\"#250\"\"\"\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"a\", \"b\"), [pytest.param(\"string\", 1.0), pytest.param(\"st-ring\", 2.0)]\n )\n assert result == [\"string-1.0\", \"st-ring-2.0\"]\n\n result = idmaker(\n (\"a\", \"b\"), [pytest.param(object(), 1.0), pytest.param(object(), object())]\n )\n assert result == [\"a0-1.0\", \"a1-b1\"]\n # unicode mixing, issue250\n result = idmaker((u\"a\", \"b\"), [pytest.param({}, b\"\\xc3\\xb4\")])\n assert result == [\"a0-\\\\xc3\\\\xb4\"]\n\n def test_idmaker_with_bytes_regex(self):\n from _pytest.python import idmaker\n\n result = idmaker((\"a\"), [pytest.param(re.compile(b\"foo\"), 1.0)])\n assert result == [\"foo\"]\n\n def test_idmaker_native_strings(self):\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"a\", \"b\"),\n [\n pytest.param(1.0, -1.1),\n pytest.param(2, -202),\n pytest.param(\"three\", \"three hundred\"),\n pytest.param(True, False),\n pytest.param(None, None),\n pytest.param(re.compile(\"foo\"), re.compile(\"bar\")),\n pytest.param(str, int),\n pytest.param(list(\"six\"), [66, 66]),\n pytest.param({7}, set(\"seven\")),\n pytest.param(tuple(\"eight\"), (8, -8, 8)),\n pytest.param(b\"\\xc3\\xb4\", b\"name\"),\n pytest.param(b\"\\xc3\\xb4\", u\"other\"),\n ],\n )\n assert result == [\n \"1.0--1.1\",\n \"2--202\",\n \"three-three hundred\",\n \"True-False\",\n \"None-None\",\n \"foo-bar\",\n \"str-int\",\n \"a7-b7\",\n \"a8-b8\",\n \"a9-b9\",\n \"\\\\xc3\\\\xb4-name\",\n \"\\\\xc3\\\\xb4-other\",\n ]\n\n def test_idmaker_non_printable_characters(self):\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"s\", \"n\"),\n [\n pytest.param(\"\\x00\", 1),\n pytest.param(\"\\x05\", 2),\n pytest.param(b\"\\x00\", 3),\n pytest.param(b\"\\x05\", 4),\n pytest.param(\"\\t\", 5),\n pytest.param(b\"\\t\", 6),\n ],\n )\n assert result == [\"\\\\x00-1\", \"\\\\x05-2\", \"\\\\x00-3\", \"\\\\x05-4\", \"\\\\t-5\", \"\\\\t-6\"]\n\n def test_idmaker_manual_ids_must_be_printable(self):\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"s\",),\n [\n pytest.param(\"x00\", id=\"hello \\x00\"),\n pytest.param(\"x05\", id=\"hello \\x05\"),\n ],\n )\n assert result == [\"hello \\\\x00\", \"hello \\\\x05\"]\n\n def test_idmaker_enum(self):\n from _pytest.python import idmaker\n\n enum = pytest.importorskip(\"enum\")\n e = enum.Enum(\"Foo\", \"one, two\")\n result = idmaker((\"a\", \"b\"), [pytest.param(e.one, e.two)])\n assert result == [\"Foo.one-Foo.two\"]\n\n def test_idmaker_idfn(self):\n \"\"\"#351\"\"\"\n from _pytest.python import idmaker\n\n def ids(val):\n if isinstance(val, Exception):\n return repr(val)\n\n result = idmaker(\n (\"a\", \"b\"),\n [\n pytest.param(10.0, IndexError()),\n pytest.param(20, KeyError()),\n pytest.param(\"three\", [1, 2, 3]),\n ],\n idfn=ids,\n )\n assert result == [\"10.0-IndexError()\", \"20-KeyError()\", \"three-b2\"]\n\n def test_idmaker_idfn_unique_names(self):\n \"\"\"#351\"\"\"\n from _pytest.python import idmaker\n\n def ids(val):\n return \"a\"\n\n result = idmaker(\n (\"a\", \"b\"),\n [\n pytest.param(10.0, IndexError()),\n pytest.param(20, KeyError()),\n pytest.param(\"three\", [1, 2, 3]),\n ],\n idfn=ids,\n )\n assert result == [\"a-a0\", \"a-a1\", \"a-a2\"]\n\n def test_idmaker_with_idfn_and_config(self):\n \"\"\"unittest for expected behavior to create ids with idfn and\n disable_test_id_escaping_and_forfeit_all_rights_to_community_support\n option. (#5294)\n \"\"\"\n from _pytest.python import idmaker\n\n class MockConfig(object):\n def __init__(self, config):\n self.config = config\n\n @property\n def hook(self):\n return self\n\n def pytest_make_parametrize_id(self, **kw):\n pass\n\n def getini(self, name):\n return self.config[name]\n\n option = \"disable_test_id_escaping_and_forfeit_all_rights_to_community_support\"\n\n values = [\n (MockConfig({option: True}), u\"ação\"),\n (MockConfig({option: False}), \"a\\\\xe7\\\\xe3o\"),\n ]\n for config, expected in values:\n result = idmaker(\n (\"a\",), [pytest.param(\"string\")], idfn=lambda _: u\"ação\", config=config\n )\n assert result == [expected]\n\n def test_idmaker_with_ids_and_config(self):\n \"\"\"unittest for expected behavior to create ids with ids and\n disable_test_id_escaping_and_forfeit_all_rights_to_community_support\n option. (#5294)\n \"\"\"\n from _pytest.python import idmaker\n\n class MockConfig(object):\n def __init__(self, config):\n self.config = config\n\n @property\n def hook(self):\n return self\n\n def pytest_make_parametrize_id(self, **kw):\n pass\n\n def getini(self, name):\n return self.config[name]\n\n option = \"disable_test_id_escaping_and_forfeit_all_rights_to_community_support\"\n\n values = [\n (MockConfig({option: True}), u\"ação\"),\n (MockConfig({option: False}), \"a\\\\xe7\\\\xe3o\"),\n ]\n for config, expected in values:\n result = idmaker(\n (\"a\",), [pytest.param(\"string\")], ids=[u\"ação\"], config=config\n )\n assert result == [expected]\n\n def test_parametrize_ids_exception(self, testdir):\n \"\"\"\n :param testdir: the instance of Testdir class, a temporary\n test directory.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n def ids(arg):\n raise Exception(\"bad ids\")\n\n @pytest.mark.parametrize(\"arg\", [\"a\", \"b\"], ids=ids)\n def test_foo(arg):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*test_foo: error raised while trying to determine id of parameter 'arg' at position 0\",\n \"*Exception: bad ids\",\n ]\n )\n\n def test_parametrize_ids_returns_non_string(self, testdir):\n testdir.makepyfile(\n \"\"\"\\\n import pytest\n\n def ids(d):\n return d\n\n @pytest.mark.parametrize(\"arg\", ({1: 2}, {3, 4}), ids=ids)\n def test(arg):\n assert arg\n \"\"\"\n )\n assert testdir.runpytest().ret == 0\n\n def test_idmaker_with_ids(self):\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"a\", \"b\"), [pytest.param(1, 2), pytest.param(3, 4)], ids=[\"a\", None]\n )\n assert result == [\"a\", \"3-4\"]\n\n def test_idmaker_with_paramset_id(self):\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"a\", \"b\"),\n [pytest.param(1, 2, id=\"me\"), pytest.param(3, 4, id=\"you\")],\n ids=[\"a\", None],\n )\n assert result == [\"me\", \"you\"]\n\n def test_idmaker_with_ids_unique_names(self):\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"a\"), map(pytest.param, [1, 2, 3, 4, 5]), ids=[\"a\", \"a\", \"b\", \"c\", \"b\"]\n )\n assert result == [\"a0\", \"a1\", \"b0\", \"c\", \"b1\"]\n\n def test_parametrize_indirect(self):\n \"\"\"#714\"\"\"\n\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n metafunc.parametrize(\"x\", [1], indirect=True)\n metafunc.parametrize(\"y\", [2, 3], indirect=True)\n assert len(metafunc._calls) == 2\n assert metafunc._calls[0].funcargs == {}\n assert metafunc._calls[1].funcargs == {}\n assert metafunc._calls[0].params == dict(x=1, y=2)\n assert metafunc._calls[1].params == dict(x=1, y=3)\n\n def test_parametrize_indirect_list(self):\n \"\"\"#714\"\"\"\n\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n metafunc.parametrize(\"x, y\", [(\"a\", \"b\")], indirect=[\"x\"])\n assert metafunc._calls[0].funcargs == dict(y=\"b\")\n assert metafunc._calls[0].params == dict(x=\"a\")\n\n def test_parametrize_indirect_list_all(self):\n \"\"\"#714\"\"\"\n\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n metafunc.parametrize(\"x, y\", [(\"a\", \"b\")], indirect=[\"x\", \"y\"])\n assert metafunc._calls[0].funcargs == {}\n assert metafunc._calls[0].params == dict(x=\"a\", y=\"b\")\n\n def test_parametrize_indirect_list_empty(self):\n \"\"\"#714\"\"\"\n\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n metafunc.parametrize(\"x, y\", [(\"a\", \"b\")], indirect=[])\n assert metafunc._calls[0].funcargs == dict(x=\"a\", y=\"b\")\n assert metafunc._calls[0].params == {}\n\n def test_parametrize_indirect_list_functional(self, testdir):\n \"\"\"\n #714\n Test parametrization with 'indirect' parameter applied on\n particular arguments. As y is is direct, its value should\n be used directly rather than being passed to the fixture\n y.\n\n :param testdir: the instance of Testdir class, a temporary\n test directory.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope='function')\n def x(request):\n return request.param * 3\n @pytest.fixture(scope='function')\n def y(request):\n return request.param * 2\n @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x'])\n def test_simple(x,y):\n assert len(x) == 3\n assert len(y) == 1\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines([\"*test_simple*a-b*\", \"*1 passed*\"])\n\n def test_parametrize_indirect_list_error(self, testdir):\n \"\"\"#714\"\"\"\n\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n with pytest.raises(pytest.fail.Exception):\n metafunc.parametrize(\"x, y\", [(\"a\", \"b\")], indirect=[\"x\", \"z\"])\n\n def test_parametrize_uses_no_fixture_error_indirect_false(self, testdir):\n \"\"\"The 'uses no fixture' error tells the user at collection time\n that the parametrize data they've set up doesn't correspond to the\n fixtures in their test function, rather than silently ignoring this\n and letting the test potentially pass.\n\n #714\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=False)\n def test_simple(x):\n assert len(x) == 3\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*uses no argument 'y'*\"])\n\n def test_parametrize_uses_no_fixture_error_indirect_true(self, testdir):\n \"\"\"#714\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope='function')\n def x(request):\n return request.param * 3\n @pytest.fixture(scope='function')\n def y(request):\n return request.param * 2\n\n @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=True)\n def test_simple(x):\n assert len(x) == 3\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*uses no fixture 'y'*\"])\n\n def test_parametrize_indirect_uses_no_fixture_error_indirect_string(self, testdir):\n \"\"\"#714\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope='function')\n def x(request):\n return request.param * 3\n\n @pytest.mark.parametrize('x, y', [('a', 'b')], indirect='y')\n def test_simple(x):\n assert len(x) == 3\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*uses no fixture 'y'*\"])\n\n def test_parametrize_indirect_uses_no_fixture_error_indirect_list(self, testdir):\n \"\"\"#714\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope='function')\n def x(request):\n return request.param * 3\n\n @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['y'])\n def test_simple(x):\n assert len(x) == 3\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*uses no fixture 'y'*\"])\n\n def test_parametrize_argument_not_in_indirect_list(self, testdir):\n \"\"\"#714\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope='function')\n def x(request):\n return request.param * 3\n\n @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x'])\n def test_simple(x):\n assert len(x) == 3\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*uses no argument 'y'*\"])\n\n def test_parametrize_gives_indicative_error_on_function_with_default_argument(\n self, testdir\n ):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize('x, y', [('a', 'b')])\n def test_simple(x, y=1):\n assert len(x) == 1\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines(\n [\"*already takes an argument 'y' with a default value\"]\n )\n\n def test_parametrize_functional(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('x', [1,2], indirect=True)\n metafunc.parametrize('y', [2])\n @pytest.fixture\n def x(request):\n return request.param * 10\n\n def test_simple(x,y):\n assert x in (10,20)\n assert y == 2\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n [\"*test_simple*1-2*\", \"*test_simple*2-2*\", \"*2 passed*\"]\n )\n\n def test_parametrize_onearg(self):\n metafunc = self.Metafunc(lambda x: None)\n metafunc.parametrize(\"x\", [1, 2])\n assert len(metafunc._calls) == 2\n assert metafunc._calls[0].funcargs == dict(x=1)\n assert metafunc._calls[0].id == \"1\"\n assert metafunc._calls[1].funcargs == dict(x=2)\n assert metafunc._calls[1].id == \"2\"\n\n def test_parametrize_onearg_indirect(self):\n metafunc = self.Metafunc(lambda x: None)\n metafunc.parametrize(\"x\", [1, 2], indirect=True)\n assert metafunc._calls[0].params == dict(x=1)\n assert metafunc._calls[0].id == \"1\"\n assert metafunc._calls[1].params == dict(x=2)\n assert metafunc._calls[1].id == \"2\"\n\n def test_parametrize_twoargs(self):\n metafunc = self.Metafunc(lambda x, y: None)\n metafunc.parametrize((\"x\", \"y\"), [(1, 2), (3, 4)])\n assert len(metafunc._calls) == 2\n assert metafunc._calls[0].funcargs == dict(x=1, y=2)\n assert metafunc._calls[0].id == \"1-2\"\n assert metafunc._calls[1].funcargs == dict(x=3, y=4)\n assert metafunc._calls[1].id == \"3-4\"\n\n def test_parametrize_multiple_times(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n pytestmark = pytest.mark.parametrize(\"x\", [1,2])\n def test_func(x):\n assert 0, x\n class TestClass(object):\n pytestmark = pytest.mark.parametrize(\"y\", [3,4])\n def test_meth(self, x, y):\n assert 0, x\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.assert_outcomes(failed=6)\n\n def test_parametrize_CSV(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize(\"x, y,\", [(1,2), (2,3)])\n def test_func(x, y):\n assert x+1 == y\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_parametrize_class_scenarios(self, testdir):\n testdir.makepyfile(\n \"\"\"\n # same as doc/en/example/parametrize scenario example\n def pytest_generate_tests(metafunc):\n idlist = []\n argvalues = []\n for scenario in metafunc.cls.scenarios:\n idlist.append(scenario[0])\n items = scenario[1].items()\n argnames = [x[0] for x in items]\n argvalues.append(([x[1] for x in items]))\n metafunc.parametrize(argnames, argvalues, ids=idlist, scope=\"class\")\n\n class Test(object):\n scenarios = [['1', {'arg': {1: 2}, \"arg2\": \"value2\"}],\n ['2', {'arg':'value2', \"arg2\": \"value2\"}]]\n\n def test_1(self, arg, arg2):\n pass\n\n def test_2(self, arg2, arg):\n pass\n\n def test_3(self, arg, arg2):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n \"\"\"\n *test_1*1*\n *test_2*1*\n *test_3*1*\n *test_1*2*\n *test_2*2*\n *test_3*2*\n *6 passed*\n \"\"\"\n )\n\n def test_format_args(self):\n def function1():\n pass\n\n assert fixtures._format_args(function1) == \"()\"\n\n def function2(arg1):\n pass\n\n assert fixtures._format_args(function2) == \"(arg1)\"\n\n def function3(arg1, arg2=\"qwe\"):\n pass\n\n assert fixtures._format_args(function3) == \"(arg1, arg2='qwe')\"\n\n def function4(arg1, *args, **kwargs):\n pass\n\n assert fixtures._format_args(function4) == \"(arg1, *args, **kwargs)\"\n\n\nclass TestMetafuncFunctional(object):\n def test_attributes(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n # assumes that generate/provide runs in the same process\n import sys, pytest, six\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('metafunc', [metafunc])\n\n @pytest.fixture\n def metafunc(request):\n return request.param\n\n def test_function(metafunc, pytestconfig):\n assert metafunc.config == pytestconfig\n assert metafunc.module.__name__ == __name__\n assert metafunc.function == test_function\n assert metafunc.cls is None\n\n class TestClass(object):\n def test_method(self, metafunc, pytestconfig):\n assert metafunc.config == pytestconfig\n assert metafunc.module.__name__ == __name__\n unbound = six.get_unbound_function(TestClass.test_method)\n assert metafunc.function == unbound\n assert metafunc.cls == TestClass\n \"\"\"\n )\n result = testdir.runpytest(p, \"-v\", SHOW_PYTEST_WARNINGS_ARG)\n result.assert_outcomes(passed=2)\n\n def test_two_functions(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('arg1', [10, 20], ids=['0', '1'])\n\n def test_func1(arg1):\n assert arg1 == 10\n\n def test_func2(arg1):\n assert arg1 in (10, 20)\n \"\"\"\n )\n result = testdir.runpytest(\"-v\", p, SHOW_PYTEST_WARNINGS_ARG)\n result.stdout.fnmatch_lines(\n [\n \"*test_func1*0*PASS*\",\n \"*test_func1*1*FAIL*\",\n \"*test_func2*PASS*\",\n \"*test_func2*PASS*\",\n \"*1 failed, 3 passed*\",\n ]\n )\n\n def test_noself_in_method(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n assert 'xyz' not in metafunc.fixturenames\n\n class TestHello(object):\n def test_hello(xyz):\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.assert_outcomes(passed=1)\n\n def test_generate_tests_in_class(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n class TestClass(object):\n def pytest_generate_tests(self, metafunc):\n metafunc.parametrize('hello', ['world'], ids=['hellow'])\n\n def test_myfunc(self, hello):\n assert hello == \"world\"\n \"\"\"\n )\n result = testdir.runpytest(\"-v\", p, SHOW_PYTEST_WARNINGS_ARG)\n result.stdout.fnmatch_lines([\"*test_myfunc*hello*PASS*\", \"*1 passed*\"])\n\n def test_two_functions_not_same_instance(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('arg1', [10, 20], ids=[\"0\", \"1\"])\n\n class TestClass(object):\n def test_func(self, arg1):\n assert not hasattr(self, 'x')\n self.x = 1\n \"\"\"\n )\n result = testdir.runpytest(\"-v\", p, SHOW_PYTEST_WARNINGS_ARG)\n result.stdout.fnmatch_lines(\n [\"*test_func*0*PASS*\", \"*test_func*1*PASS*\", \"*2 pass*\"]\n )\n\n def test_issue28_setup_method_in_generate_tests(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('arg1', [1])\n\n class TestClass(object):\n def test_method(self, arg1):\n assert arg1 == self.val\n def setup_method(self, func):\n self.val = 1\n \"\"\"\n )\n result = testdir.runpytest(p, SHOW_PYTEST_WARNINGS_ARG)\n result.assert_outcomes(passed=1)\n\n def test_parametrize_functional2(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n metafunc.parametrize(\"arg1\", [1,2])\n metafunc.parametrize(\"arg2\", [4,5])\n def test_hello(arg1, arg2):\n assert 0, (arg1, arg2)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"*(1, 4)*\", \"*(1, 5)*\", \"*(2, 4)*\", \"*(2, 5)*\", \"*4 failed*\"]\n )\n\n def test_parametrize_and_inner_getfixturevalue(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n metafunc.parametrize(\"arg1\", [1], indirect=True)\n metafunc.parametrize(\"arg2\", [10], indirect=True)\n\n import pytest\n @pytest.fixture\n def arg1(request):\n x = request.getfixturevalue(\"arg2\")\n return x + request.param\n\n @pytest.fixture\n def arg2(request):\n return request.param\n\n def test_func1(arg1, arg2):\n assert arg1 == 11\n \"\"\"\n )\n result = testdir.runpytest(\"-v\", p)\n result.stdout.fnmatch_lines([\"*test_func1*1*PASS*\", \"*1 passed*\"])\n\n def test_parametrize_on_setup_arg(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n assert \"arg1\" in metafunc.fixturenames\n metafunc.parametrize(\"arg1\", [1], indirect=True)\n\n import pytest\n @pytest.fixture\n def arg1(request):\n return request.param\n\n @pytest.fixture\n def arg2(request, arg1):\n return 10 * arg1\n\n def test_func(arg2):\n assert arg2 == 10\n \"\"\"\n )\n result = testdir.runpytest(\"-v\", p)\n result.stdout.fnmatch_lines([\"*test_func*1*PASS*\", \"*1 passed*\"])\n\n def test_parametrize_with_ids(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style=classic\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n metafunc.parametrize((\"a\", \"b\"), [(1,1), (1,2)],\n ids=[\"basic\", \"advanced\"])\n\n def test_function(a, b):\n assert a == b\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n assert result.ret == 1\n result.stdout.fnmatch_lines_random(\n [\"*test_function*basic*PASSED\", \"*test_function*advanced*FAILED\"]\n )\n\n def test_parametrize_without_ids(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n metafunc.parametrize((\"a\", \"b\"),\n [(1,object()), (1.3,object())])\n\n def test_function(a, b):\n assert 1\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *test_function*1-b0*\n *test_function*1.3-b1*\n \"\"\"\n )\n\n def test_parametrize_with_None_in_ids(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n metafunc.parametrize((\"a\", \"b\"), [(1,1), (1,1), (1,2)],\n ids=[\"basic\", None, \"advanced\"])\n\n def test_function(a, b):\n assert a == b\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n assert result.ret == 1\n result.stdout.fnmatch_lines_random(\n [\n \"*test_function*basic*PASSED*\",\n \"*test_function*1-1*PASSED*\",\n \"*test_function*advanced*FAILED*\",\n ]\n )\n\n def test_fixture_parametrized_empty_ids(self, testdir):\n \"\"\"Fixtures parametrized with empty ids cause an internal error (#1849).\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"module\", ids=[], params=[])\n def temp(request):\n return request.param\n\n def test_temp(temp):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 skipped *\"])\n\n def test_parametrized_empty_ids(self, testdir):\n \"\"\"Tests parametrized with empty ids cause an internal error (#1849).\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize('temp', [], ids=list())\n def test_temp(temp):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 skipped *\"])\n\n def test_parametrized_ids_invalid_type(self, testdir):\n \"\"\"Tests parametrized with ids as non-strings (#1857).\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize(\"x, expected\", [(10, 20), (40, 80)], ids=(None, 2))\n def test_ids_numbers(x,expected):\n assert x * 2 == expected\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*In test_ids_numbers: ids must be list of strings, found: 2 (type: *'int'>)*\"\n ]\n )\n\n def test_parametrize_with_identical_ids_get_unique_names(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n metafunc.parametrize((\"a\", \"b\"), [(1,1), (1,2)],\n ids=[\"a\", \"a\"])\n\n def test_function(a, b):\n assert a == b\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n assert result.ret == 1\n result.stdout.fnmatch_lines_random(\n [\"*test_function*a0*PASSED*\", \"*test_function*a1*FAILED*\"]\n )\n\n @pytest.mark.parametrize((\"scope\", \"length\"), [(\"module\", 2), (\"function\", 4)])\n def test_parametrize_scope_overrides(self, testdir, scope, length):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n def pytest_generate_tests(metafunc):\n if \"arg\" in metafunc.funcargnames:\n metafunc.parametrize(\"arg\", [1,2], indirect=True,\n scope=%r)\n @pytest.fixture\n def arg(request):\n values.append(request.param)\n return request.param\n def test_hello(arg):\n assert arg in (1,2)\n def test_world(arg):\n assert arg in (1,2)\n def test_checklength():\n assert len(values) == %d\n \"\"\"\n % (scope, length)\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=5)\n\n def test_parametrize_issue323(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='module', params=range(966))\n def foo(request):\n return request.param\n\n def test_it(foo):\n pass\n def test_it2(foo):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(\"--collect-only\")\n assert not reprec.getcalls(\"pytest_internalerror\")\n\n def test_usefixtures_seen_in_generate_tests(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n assert \"abc\" in metafunc.fixturenames\n metafunc.parametrize(\"abc\", [1])\n\n @pytest.mark.usefixtures(\"abc\")\n def test_function():\n pass\n \"\"\"\n )\n reprec = testdir.runpytest()\n reprec.assert_outcomes(passed=1)\n\n def test_generate_tests_only_done_in_subdir(self, testdir):\n sub1 = testdir.mkpydir(\"sub1\")\n sub2 = testdir.mkpydir(\"sub2\")\n sub1.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def pytest_generate_tests(metafunc):\n assert metafunc.function.__name__ == \"test_1\"\n \"\"\"\n )\n )\n sub2.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def pytest_generate_tests(metafunc):\n assert metafunc.function.__name__ == \"test_2\"\n \"\"\"\n )\n )\n sub1.join(\"test_in_sub1.py\").write(\"def test_1(): pass\")\n sub2.join(\"test_in_sub2.py\").write(\"def test_2(): pass\")\n result = testdir.runpytest(\"--keep-duplicates\", \"-v\", \"-s\", sub1, sub2, sub1)\n result.assert_outcomes(passed=3)\n\n def test_generate_same_function_names_issue403(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n def make_tests():\n @pytest.mark.parametrize(\"x\", range(2))\n def test_foo(x):\n pass\n return test_foo\n\n test_x = make_tests()\n test_y = make_tests()\n \"\"\"\n )\n reprec = testdir.runpytest()\n reprec.assert_outcomes(passed=4)\n\n @pytest.mark.parametrize(\"attr\", [\"parametrise\", \"parameterize\", \"parameterise\"])\n def test_parametrize_misspelling(self, testdir, attr):\n \"\"\"#463\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.{}(\"x\", range(2))\n def test_foo(x):\n pass\n \"\"\".format(\n attr\n )\n )\n result = testdir.runpytest(\"--collectonly\")\n result.stdout.fnmatch_lines(\n [\n \"test_foo has '{}' mark, spelling should be 'parametrize'\".format(attr),\n \"*1 error in*\",\n ]\n )\n\n\nclass TestMetafuncFunctionalAuto(object):\n \"\"\"\n Tests related to automatically find out the correct scope for parametrized tests (#1832).\n \"\"\"\n\n def test_parametrize_auto_scope(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='session', autouse=True)\n def fixture():\n return 1\n\n @pytest.mark.parametrize('animal', [\"dog\", \"cat\"])\n def test_1(animal):\n assert animal in ('dog', 'cat')\n\n @pytest.mark.parametrize('animal', ['fish'])\n def test_2(animal):\n assert animal == 'fish'\n\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 3 passed *\"])\n\n def test_parametrize_auto_scope_indirect(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='session')\n def echo(request):\n return request.param\n\n @pytest.mark.parametrize('animal, echo', [(\"dog\", 1), (\"cat\", 2)], indirect=['echo'])\n def test_1(animal, echo):\n assert animal in ('dog', 'cat')\n assert echo in (1, 2, 3)\n\n @pytest.mark.parametrize('animal, echo', [('fish', 3)], indirect=['echo'])\n def test_2(animal, echo):\n assert animal == 'fish'\n assert echo in (1, 2, 3)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 3 passed *\"])\n\n def test_parametrize_auto_scope_override_fixture(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='session', autouse=True)\n def animal():\n return 'fox'\n\n @pytest.mark.parametrize('animal', [\"dog\", \"cat\"])\n def test_1(animal):\n assert animal in ('dog', 'cat')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed *\"])\n\n def test_parametrize_all_indirects(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture()\n def animal(request):\n return request.param\n\n @pytest.fixture(scope='session')\n def echo(request):\n return request.param\n\n @pytest.mark.parametrize('animal, echo', [(\"dog\", 1), (\"cat\", 2)], indirect=True)\n def test_1(animal, echo):\n assert animal in ('dog', 'cat')\n assert echo in (1, 2, 3)\n\n @pytest.mark.parametrize('animal, echo', [(\"fish\", 3)], indirect=True)\n def test_2(animal, echo):\n assert animal == 'fish'\n assert echo in (1, 2, 3)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 3 passed *\"])\n\n def test_parametrize_some_arguments_auto_scope(self, testdir, monkeypatch):\n \"\"\"Integration test for (#3941)\"\"\"\n class_fix_setup = []\n monkeypatch.setattr(sys, \"class_fix_setup\", class_fix_setup, raising=False)\n func_fix_setup = []\n monkeypatch.setattr(sys, \"func_fix_setup\", func_fix_setup, raising=False)\n\n testdir.makepyfile(\n \"\"\"\n import pytest\n import sys\n\n @pytest.fixture(scope='class', autouse=True)\n def class_fix(request):\n sys.class_fix_setup.append(request.param)\n\n @pytest.fixture(autouse=True)\n def func_fix():\n sys.func_fix_setup.append(True)\n\n @pytest.mark.parametrize('class_fix', [10, 20], indirect=True)\n class Test:\n def test_foo(self):\n pass\n def test_bar(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest_inprocess()\n result.stdout.fnmatch_lines([\"* 4 passed in *\"])\n assert func_fix_setup == [True] * 4\n assert class_fix_setup == [10, 20]\n\n def test_parametrize_issue634(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='module')\n def foo(request):\n print('preparing foo-%d' % request.param)\n return 'foo-%d' % request.param\n\n def test_one(foo):\n pass\n\n def test_two(foo):\n pass\n\n test_two.test_with = (2, 3)\n\n def pytest_generate_tests(metafunc):\n params = (1, 2, 3, 4)\n if not 'foo' in metafunc.fixturenames:\n return\n\n test_with = getattr(metafunc.function, 'test_with', None)\n if test_with:\n params = test_with\n metafunc.parametrize('foo', params, indirect=True)\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n output = result.stdout.str()\n assert output.count(\"preparing foo-2\") == 1\n assert output.count(\"preparing foo-3\") == 1\n\n\nclass TestMarkersWithParametrization(object):\n \"\"\"#308\"\"\"\n\n def test_simple_mark(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.foo\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(1, 3, marks=pytest.mark.bar),\n (2, 3),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n items = testdir.getitems(s)\n assert len(items) == 3\n for item in items:\n assert \"foo\" in item.keywords\n assert \"bar\" not in items[0].keywords\n assert \"bar\" in items[1].keywords\n assert \"bar\" not in items[2].keywords\n\n def test_select_based_on_mark(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(2, 3, marks=pytest.mark.foo),\n (3, 4),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n testdir.makepyfile(s)\n rec = testdir.inline_run(\"-m\", \"foo\", SHOW_PYTEST_WARNINGS_ARG)\n passed, skipped, fail = rec.listoutcomes()\n assert len(passed) == 1\n assert len(skipped) == 0\n assert len(fail) == 0\n\n @pytest.mark.xfail(reason=\"is this important to support??\")\n def test_nested_marks(self, testdir):\n s = \"\"\"\n import pytest\n mastermark = pytest.mark.foo(pytest.mark.bar)\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n mastermark((1, 3)),\n (2, 3),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n items = testdir.getitems(s)\n assert len(items) == 3\n for mark in [\"foo\", \"bar\"]:\n assert mark not in items[0].keywords\n assert mark in items[1].keywords\n assert mark not in items[2].keywords\n\n def test_simple_xfail(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(1, 3, marks=pytest.mark.xfail),\n (2, 3),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n # xfail is skip??\n reprec.assertoutcome(passed=2, skipped=1)\n\n def test_simple_xfail_single_argname(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize(\"n\", [\n 2,\n pytest.param(3, marks=pytest.mark.xfail),\n 4,\n ])\n def test_isEven(n):\n assert n % 2 == 0\n \"\"\"\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n reprec.assertoutcome(passed=2, skipped=1)\n\n def test_xfail_with_arg(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(1, 3, marks=pytest.mark.xfail(\"True\")),\n (2, 3),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n reprec.assertoutcome(passed=2, skipped=1)\n\n def test_xfail_with_kwarg(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(1, 3, marks=pytest.mark.xfail(reason=\"some bug\")),\n (2, 3),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n reprec.assertoutcome(passed=2, skipped=1)\n\n def test_xfail_with_arg_and_kwarg(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(1, 3, marks=pytest.mark.xfail(\"True\", reason=\"some bug\")),\n (2, 3),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n reprec.assertoutcome(passed=2, skipped=1)\n\n @pytest.mark.parametrize(\"strict\", [True, False])\n def test_xfail_passing_is_xpass(self, testdir, strict):\n s = \"\"\"\n import pytest\n\n m = pytest.mark.xfail(\"sys.version_info > (0, 0, 0)\", reason=\"some bug\", strict={strict})\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(2, 3, marks=m),\n (3, 4),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\".format(\n strict=strict\n )\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n passed, failed = (2, 1) if strict else (3, 0)\n reprec.assertoutcome(passed=passed, failed=failed)\n\n def test_parametrize_called_in_generate_tests(self, testdir):\n s = \"\"\"\n import pytest\n\n\n def pytest_generate_tests(metafunc):\n passingTestData = [(1, 2),\n (2, 3)]\n failingTestData = [(1, 3),\n (2, 2)]\n\n testData = passingTestData + [pytest.param(*d, marks=pytest.mark.xfail)\n for d in failingTestData]\n metafunc.parametrize((\"n\", \"expected\"), testData)\n\n\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n reprec.assertoutcome(passed=2, skipped=2)\n\n def test_parametrize_ID_generation_string_int_works(self, testdir):\n \"\"\"#290\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def myfixture():\n return 'example'\n @pytest.mark.parametrize(\n 'limit', (0, '0'))\n def test_limit(limit, myfixture):\n return\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n @pytest.mark.parametrize(\"strict\", [True, False])\n def test_parametrize_marked_value(self, testdir, strict):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n pytest.param(\n 2,3,\n marks=pytest.mark.xfail(\"sys.version_info > (0, 0, 0)\", reason=\"some bug\", strict={strict}),\n ),\n pytest.param(\n 2,3,\n marks=[pytest.mark.xfail(\"sys.version_info > (0, 0, 0)\", reason=\"some bug\", strict={strict})],\n ),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\".format(\n strict=strict\n )\n testdir.makepyfile(s)\n reprec = testdir.inline_run()\n passed, failed = (0, 2) if strict else (2, 0)\n reprec.assertoutcome(passed=passed, failed=failed)\n\n def test_pytest_make_parametrize_id(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_make_parametrize_id(config, val):\n return str(val * 2)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize(\"x\", range(2))\n def test_func(x):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines([\"*test_func*0*PASS*\", \"*test_func*2*PASS*\"])\n\n def test_pytest_make_parametrize_id_with_argname(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_make_parametrize_id(config, val, argname):\n return str(val * 2 if argname == 'x' else val * 10)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize(\"x\", range(2))\n def test_func_a(x):\n pass\n\n @pytest.mark.parametrize(\"y\", [1])\n def test_func_b(y):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n [\"*test_func_a*0*PASS*\", \"*test_func_a*2*PASS*\", \"*test_func_b*10*PASS*\"]\n )\n\n def test_parametrize_positional_args(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize(\"a\", [1], False)\n def test_foo(a):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.assert_outcomes(passed=1)\n"},{"col":4,"comment":"null","endLoc":344,"header":"def _prunetraceback(self, excinfo)","id":1033,"name":"_prunetraceback","nodeType":"Function","startLoc":338,"text":"def _prunetraceback(self, excinfo):\n if hasattr(self, \"fspath\"):\n traceback = excinfo.traceback\n ntraceback = traceback.cut(path=self.fspath)\n if ntraceback == traceback:\n ntraceback = ntraceback.cut(excludepath=tracebackcutdir)\n excinfo.traceback = ntraceback.filter()"},{"col":4,"comment":"null","endLoc":31,"header":"@pytest.fixture\n def plus_minus(self)","id":1034,"name":"plus_minus","nodeType":"Function","startLoc":29,"text":"@pytest.fixture\n def plus_minus(self):\n return u\"\\u00b1\" if sys.version_info[0] > 2 else u\"+-\""},{"col":4,"comment":"null","endLoc":61,"header":"def test_repr_string(self, plus_minus)","id":1035,"name":"test_repr_string","nodeType":"Function","startLoc":33,"text":"def test_repr_string(self, plus_minus):\n tol1, tol2, infr = \"1.0e-06\", \"2.0e-06\", \"inf\"\n assert repr(approx(1.0)) == \"1.0 {pm} {tol1}\".format(pm=plus_minus, tol1=tol1)\n assert repr(\n approx([1.0, 2.0])\n ) == \"approx([1.0 {pm} {tol1}, 2.0 {pm} {tol2}])\".format(\n pm=plus_minus, tol1=tol1, tol2=tol2\n )\n assert repr(\n approx((1.0, 2.0))\n ) == \"approx((1.0 {pm} {tol1}, 2.0 {pm} {tol2}))\".format(\n pm=plus_minus, tol1=tol1, tol2=tol2\n )\n assert repr(approx(inf)) == \"inf\"\n assert repr(approx(1.0, rel=nan)) == \"1.0 {pm} ???\".format(pm=plus_minus)\n assert repr(approx(1.0, rel=inf)) == \"1.0 {pm} {infr}\".format(\n pm=plus_minus, infr=infr\n )\n assert repr(approx(1.0j, rel=inf)) == \"1j\"\n\n # Dictionaries aren't ordered, so we need to check both orders.\n assert repr(approx({\"a\": 1.0, \"b\": 2.0})) in (\n \"approx({{'a': 1.0 {pm} {tol1}, 'b': 2.0 {pm} {tol2}}})\".format(\n pm=plus_minus, tol1=tol1, tol2=tol2\n ),\n \"approx({{'b': 2.0 {pm} {tol2}, 'a': 1.0 {pm} {tol1}}})\".format(\n pm=plus_minus, tol1=tol1, tol2=tol2\n ),\n )"},{"attributeType":"null","col":0,"comment":"null","endLoc":13,"id":1036,"name":"SHOW_PYTEST_WARNINGS_ARG","nodeType":"Attribute","startLoc":13,"text":"SHOW_PYTEST_WARNINGS_ARG"},{"className":"TestMetafunc","col":0,"comment":"null","endLoc":891,"id":1037,"nodeType":"Class","startLoc":19,"text":"class TestMetafunc(object):\n def Metafunc(self, func, config=None):\n # the unit tests of this class check if things work correctly\n # on the funcarg level, so we don't need a full blown\n # initiliazation\n class FixtureInfo(object):\n name2fixturedefs = None\n\n def __init__(self, names):\n self.names_closure = names\n\n @attr.s\n class DefinitionMock(object):\n obj = attr.ib()\n\n names = fixtures.getfuncargnames(func)\n fixtureinfo = FixtureInfo(names)\n definition = DefinitionMock(func)\n return python.Metafunc(definition, fixtureinfo, config)\n\n def test_no_funcargs(self, testdir):\n def function():\n pass\n\n metafunc = self.Metafunc(function)\n assert not metafunc.fixturenames\n repr(metafunc._calls)\n\n def test_function_basic(self):\n def func(arg1, arg2=\"qwe\"):\n pass\n\n metafunc = self.Metafunc(func)\n assert len(metafunc.fixturenames) == 1\n assert \"arg1\" in metafunc.fixturenames\n assert metafunc.function is func\n assert metafunc.cls is None\n\n def test_parametrize_error(self):\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n metafunc.parametrize(\"x\", [1, 2])\n pytest.raises(ValueError, lambda: metafunc.parametrize(\"x\", [5, 6]))\n pytest.raises(ValueError, lambda: metafunc.parametrize(\"x\", [5, 6]))\n metafunc.parametrize(\"y\", [1, 2])\n pytest.raises(ValueError, lambda: metafunc.parametrize(\"y\", [5, 6]))\n pytest.raises(ValueError, lambda: metafunc.parametrize(\"y\", [5, 6]))\n\n def test_parametrize_bad_scope(self, testdir):\n def func(x):\n pass\n\n metafunc = self.Metafunc(func)\n with pytest.raises(\n pytest.fail.Exception,\n match=r\"parametrize\\(\\) call in func got an unexpected scope value 'doggy'\",\n ):\n metafunc.parametrize(\"x\", [1], scope=\"doggy\")\n\n def test_find_parametrized_scope(self):\n \"\"\"unittest for _find_parametrized_scope (#3941)\"\"\"\n from _pytest.python import _find_parametrized_scope\n\n @attr.s\n class DummyFixtureDef(object):\n scope = attr.ib()\n\n fixtures_defs = dict(\n session_fix=[DummyFixtureDef(\"session\")],\n package_fix=[DummyFixtureDef(\"package\")],\n module_fix=[DummyFixtureDef(\"module\")],\n class_fix=[DummyFixtureDef(\"class\")],\n func_fix=[DummyFixtureDef(\"function\")],\n )\n\n # use arguments to determine narrow scope; the cause of the bug is that it would look on all\n # fixture defs given to the method\n def find_scope(argnames, indirect):\n return _find_parametrized_scope(argnames, fixtures_defs, indirect=indirect)\n\n assert find_scope([\"func_fix\"], indirect=True) == \"function\"\n assert find_scope([\"class_fix\"], indirect=True) == \"class\"\n assert find_scope([\"module_fix\"], indirect=True) == \"module\"\n assert find_scope([\"package_fix\"], indirect=True) == \"package\"\n assert find_scope([\"session_fix\"], indirect=True) == \"session\"\n\n assert find_scope([\"class_fix\", \"func_fix\"], indirect=True) == \"function\"\n assert find_scope([\"func_fix\", \"session_fix\"], indirect=True) == \"function\"\n assert find_scope([\"session_fix\", \"class_fix\"], indirect=True) == \"class\"\n assert find_scope([\"package_fix\", \"session_fix\"], indirect=True) == \"package\"\n assert find_scope([\"module_fix\", \"session_fix\"], indirect=True) == \"module\"\n\n # when indirect is False or is not for all scopes, always use function\n assert find_scope([\"session_fix\", \"module_fix\"], indirect=False) == \"function\"\n assert (\n find_scope([\"session_fix\", \"module_fix\"], indirect=[\"module_fix\"])\n == \"function\"\n )\n assert (\n find_scope(\n [\"session_fix\", \"module_fix\"], indirect=[\"session_fix\", \"module_fix\"]\n )\n == \"module\"\n )\n\n def test_parametrize_and_id(self):\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n\n metafunc.parametrize(\"x\", [1, 2], ids=[\"basic\", \"advanced\"])\n metafunc.parametrize(\"y\", [\"abc\", \"def\"])\n ids = [x.id for x in metafunc._calls]\n assert ids == [\"basic-abc\", \"basic-def\", \"advanced-abc\", \"advanced-def\"]\n\n def test_parametrize_and_id_unicode(self):\n \"\"\"Allow unicode strings for \"ids\" parameter in Python 2 (##1905)\"\"\"\n\n def func(x):\n pass\n\n metafunc = self.Metafunc(func)\n metafunc.parametrize(\"x\", [1, 2], ids=[u\"basic\", u\"advanced\"])\n ids = [x.id for x in metafunc._calls]\n assert ids == [u\"basic\", u\"advanced\"]\n\n def test_parametrize_with_wrong_number_of_ids(self, testdir):\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n\n with pytest.raises(pytest.fail.Exception):\n metafunc.parametrize(\"x\", [1, 2], ids=[\"basic\"])\n\n with pytest.raises(pytest.fail.Exception):\n metafunc.parametrize(\n (\"x\", \"y\"), [(\"abc\", \"def\"), (\"ghi\", \"jkl\")], ids=[\"one\"]\n )\n\n def test_parametrize_empty_list(self):\n \"\"\"#510\"\"\"\n\n def func(y):\n pass\n\n class MockConfig(object):\n def getini(self, name):\n return \"\"\n\n @property\n def hook(self):\n return self\n\n def pytest_make_parametrize_id(self, **kw):\n pass\n\n metafunc = self.Metafunc(func, MockConfig())\n metafunc.parametrize(\"y\", [])\n assert \"skip\" == metafunc._calls[0].marks[0].name\n\n def test_parametrize_with_userobjects(self):\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n\n class A(object):\n pass\n\n metafunc.parametrize(\"x\", [A(), A()])\n metafunc.parametrize(\"y\", list(\"ab\"))\n assert metafunc._calls[0].id == \"x0-a\"\n assert metafunc._calls[1].id == \"x0-b\"\n assert metafunc._calls[2].id == \"x1-a\"\n assert metafunc._calls[3].id == \"x1-b\"\n\n @hypothesis.given(strategies.text() | strategies.binary())\n @hypothesis.settings(\n deadline=400.0\n ) # very close to std deadline and CI boxes are not reliable in CPU power\n def test_idval_hypothesis(self, value):\n from _pytest.python import _idval\n\n escaped = _idval(value, \"a\", 6, None, item=None, config=None)\n assert isinstance(escaped, six.text_type)\n escaped.encode(\"ascii\")\n\n def test_unicode_idval(self):\n \"\"\"This tests that Unicode strings outside the ASCII character set get\n escaped, using byte escapes if they're in that range or unicode\n escapes if they're not.\n\n \"\"\"\n from _pytest.python import _idval\n\n values = [\n (u\"\", \"\"),\n (u\"ascii\", \"ascii\"),\n (u\"ação\", \"a\\\\xe7\\\\xe3o\"),\n (u\"josé@blah.com\", \"jos\\\\xe9@blah.com\"),\n (\n u\"δοκ.ιμή@παράδειγμα.δοκιμή\",\n \"\\\\u03b4\\\\u03bf\\\\u03ba.\\\\u03b9\\\\u03bc\\\\u03ae@\\\\u03c0\\\\u03b1\\\\u03c1\\\\u03ac\\\\u03b4\\\\u03b5\\\\u03b9\\\\u03b3\"\n \"\\\\u03bc\\\\u03b1.\\\\u03b4\\\\u03bf\\\\u03ba\\\\u03b9\\\\u03bc\\\\u03ae\",\n ),\n ]\n for val, expected in values:\n assert _idval(val, \"a\", 6, None, item=None, config=None) == expected\n\n def test_unicode_idval_with_config(self):\n \"\"\"unittest for expected behavior to obtain ids with\n disable_test_id_escaping_and_forfeit_all_rights_to_community_support\n option. (#5294)\n \"\"\"\n from _pytest.python import _idval\n\n class MockConfig(object):\n def __init__(self, config):\n self.config = config\n\n @property\n def hook(self):\n return self\n\n def pytest_make_parametrize_id(self, **kw):\n pass\n\n def getini(self, name):\n return self.config[name]\n\n option = \"disable_test_id_escaping_and_forfeit_all_rights_to_community_support\"\n\n values = [\n (u\"ação\", MockConfig({option: True}), u\"ação\"),\n (u\"ação\", MockConfig({option: False}), \"a\\\\xe7\\\\xe3o\"),\n ]\n for val, config, expected in values:\n assert _idval(val, \"a\", 6, None, item=None, config=config) == expected\n\n def test_bytes_idval(self):\n \"\"\"unittest for the expected behavior to obtain ids for parametrized\n bytes values:\n - python2: non-ascii strings are considered bytes and formatted using\n \"binary escape\", where any byte < 127 is escaped into its hex form.\n - python3: bytes objects are always escaped using \"binary escape\".\n \"\"\"\n from _pytest.python import _idval\n\n values = [\n (b\"\", \"\"),\n (b\"\\xc3\\xb4\\xff\\xe4\", \"\\\\xc3\\\\xb4\\\\xff\\\\xe4\"),\n (b\"ascii\", \"ascii\"),\n (u\"αρά\".encode(\"utf-8\"), \"\\\\xce\\\\xb1\\\\xcf\\\\x81\\\\xce\\\\xac\"),\n ]\n for val, expected in values:\n assert _idval(val, \"a\", 6, idfn=None, item=None, config=None) == expected\n\n def test_class_or_function_idval(self):\n \"\"\"unittest for the expected behavior to obtain ids for parametrized\n values that are classes or functions: their __name__.\n \"\"\"\n from _pytest.python import _idval\n\n class TestClass(object):\n pass\n\n def test_function():\n pass\n\n values = [(TestClass, \"TestClass\"), (test_function, \"test_function\")]\n for val, expected in values:\n assert _idval(val, \"a\", 6, None, item=None, config=None) == expected\n\n def test_idmaker_autoname(self):\n \"\"\"#250\"\"\"\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"a\", \"b\"), [pytest.param(\"string\", 1.0), pytest.param(\"st-ring\", 2.0)]\n )\n assert result == [\"string-1.0\", \"st-ring-2.0\"]\n\n result = idmaker(\n (\"a\", \"b\"), [pytest.param(object(), 1.0), pytest.param(object(), object())]\n )\n assert result == [\"a0-1.0\", \"a1-b1\"]\n # unicode mixing, issue250\n result = idmaker((u\"a\", \"b\"), [pytest.param({}, b\"\\xc3\\xb4\")])\n assert result == [\"a0-\\\\xc3\\\\xb4\"]\n\n def test_idmaker_with_bytes_regex(self):\n from _pytest.python import idmaker\n\n result = idmaker((\"a\"), [pytest.param(re.compile(b\"foo\"), 1.0)])\n assert result == [\"foo\"]\n\n def test_idmaker_native_strings(self):\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"a\", \"b\"),\n [\n pytest.param(1.0, -1.1),\n pytest.param(2, -202),\n pytest.param(\"three\", \"three hundred\"),\n pytest.param(True, False),\n pytest.param(None, None),\n pytest.param(re.compile(\"foo\"), re.compile(\"bar\")),\n pytest.param(str, int),\n pytest.param(list(\"six\"), [66, 66]),\n pytest.param({7}, set(\"seven\")),\n pytest.param(tuple(\"eight\"), (8, -8, 8)),\n pytest.param(b\"\\xc3\\xb4\", b\"name\"),\n pytest.param(b\"\\xc3\\xb4\", u\"other\"),\n ],\n )\n assert result == [\n \"1.0--1.1\",\n \"2--202\",\n \"three-three hundred\",\n \"True-False\",\n \"None-None\",\n \"foo-bar\",\n \"str-int\",\n \"a7-b7\",\n \"a8-b8\",\n \"a9-b9\",\n \"\\\\xc3\\\\xb4-name\",\n \"\\\\xc3\\\\xb4-other\",\n ]\n\n def test_idmaker_non_printable_characters(self):\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"s\", \"n\"),\n [\n pytest.param(\"\\x00\", 1),\n pytest.param(\"\\x05\", 2),\n pytest.param(b\"\\x00\", 3),\n pytest.param(b\"\\x05\", 4),\n pytest.param(\"\\t\", 5),\n pytest.param(b\"\\t\", 6),\n ],\n )\n assert result == [\"\\\\x00-1\", \"\\\\x05-2\", \"\\\\x00-3\", \"\\\\x05-4\", \"\\\\t-5\", \"\\\\t-6\"]\n\n def test_idmaker_manual_ids_must_be_printable(self):\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"s\",),\n [\n pytest.param(\"x00\", id=\"hello \\x00\"),\n pytest.param(\"x05\", id=\"hello \\x05\"),\n ],\n )\n assert result == [\"hello \\\\x00\", \"hello \\\\x05\"]\n\n def test_idmaker_enum(self):\n from _pytest.python import idmaker\n\n enum = pytest.importorskip(\"enum\")\n e = enum.Enum(\"Foo\", \"one, two\")\n result = idmaker((\"a\", \"b\"), [pytest.param(e.one, e.two)])\n assert result == [\"Foo.one-Foo.two\"]\n\n def test_idmaker_idfn(self):\n \"\"\"#351\"\"\"\n from _pytest.python import idmaker\n\n def ids(val):\n if isinstance(val, Exception):\n return repr(val)\n\n result = idmaker(\n (\"a\", \"b\"),\n [\n pytest.param(10.0, IndexError()),\n pytest.param(20, KeyError()),\n pytest.param(\"three\", [1, 2, 3]),\n ],\n idfn=ids,\n )\n assert result == [\"10.0-IndexError()\", \"20-KeyError()\", \"three-b2\"]\n\n def test_idmaker_idfn_unique_names(self):\n \"\"\"#351\"\"\"\n from _pytest.python import idmaker\n\n def ids(val):\n return \"a\"\n\n result = idmaker(\n (\"a\", \"b\"),\n [\n pytest.param(10.0, IndexError()),\n pytest.param(20, KeyError()),\n pytest.param(\"three\", [1, 2, 3]),\n ],\n idfn=ids,\n )\n assert result == [\"a-a0\", \"a-a1\", \"a-a2\"]\n\n def test_idmaker_with_idfn_and_config(self):\n \"\"\"unittest for expected behavior to create ids with idfn and\n disable_test_id_escaping_and_forfeit_all_rights_to_community_support\n option. (#5294)\n \"\"\"\n from _pytest.python import idmaker\n\n class MockConfig(object):\n def __init__(self, config):\n self.config = config\n\n @property\n def hook(self):\n return self\n\n def pytest_make_parametrize_id(self, **kw):\n pass\n\n def getini(self, name):\n return self.config[name]\n\n option = \"disable_test_id_escaping_and_forfeit_all_rights_to_community_support\"\n\n values = [\n (MockConfig({option: True}), u\"ação\"),\n (MockConfig({option: False}), \"a\\\\xe7\\\\xe3o\"),\n ]\n for config, expected in values:\n result = idmaker(\n (\"a\",), [pytest.param(\"string\")], idfn=lambda _: u\"ação\", config=config\n )\n assert result == [expected]\n\n def test_idmaker_with_ids_and_config(self):\n \"\"\"unittest for expected behavior to create ids with ids and\n disable_test_id_escaping_and_forfeit_all_rights_to_community_support\n option. (#5294)\n \"\"\"\n from _pytest.python import idmaker\n\n class MockConfig(object):\n def __init__(self, config):\n self.config = config\n\n @property\n def hook(self):\n return self\n\n def pytest_make_parametrize_id(self, **kw):\n pass\n\n def getini(self, name):\n return self.config[name]\n\n option = \"disable_test_id_escaping_and_forfeit_all_rights_to_community_support\"\n\n values = [\n (MockConfig({option: True}), u\"ação\"),\n (MockConfig({option: False}), \"a\\\\xe7\\\\xe3o\"),\n ]\n for config, expected in values:\n result = idmaker(\n (\"a\",), [pytest.param(\"string\")], ids=[u\"ação\"], config=config\n )\n assert result == [expected]\n\n def test_parametrize_ids_exception(self, testdir):\n \"\"\"\n :param testdir: the instance of Testdir class, a temporary\n test directory.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n def ids(arg):\n raise Exception(\"bad ids\")\n\n @pytest.mark.parametrize(\"arg\", [\"a\", \"b\"], ids=ids)\n def test_foo(arg):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*test_foo: error raised while trying to determine id of parameter 'arg' at position 0\",\n \"*Exception: bad ids\",\n ]\n )\n\n def test_parametrize_ids_returns_non_string(self, testdir):\n testdir.makepyfile(\n \"\"\"\\\n import pytest\n\n def ids(d):\n return d\n\n @pytest.mark.parametrize(\"arg\", ({1: 2}, {3, 4}), ids=ids)\n def test(arg):\n assert arg\n \"\"\"\n )\n assert testdir.runpytest().ret == 0\n\n def test_idmaker_with_ids(self):\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"a\", \"b\"), [pytest.param(1, 2), pytest.param(3, 4)], ids=[\"a\", None]\n )\n assert result == [\"a\", \"3-4\"]\n\n def test_idmaker_with_paramset_id(self):\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"a\", \"b\"),\n [pytest.param(1, 2, id=\"me\"), pytest.param(3, 4, id=\"you\")],\n ids=[\"a\", None],\n )\n assert result == [\"me\", \"you\"]\n\n def test_idmaker_with_ids_unique_names(self):\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"a\"), map(pytest.param, [1, 2, 3, 4, 5]), ids=[\"a\", \"a\", \"b\", \"c\", \"b\"]\n )\n assert result == [\"a0\", \"a1\", \"b0\", \"c\", \"b1\"]\n\n def test_parametrize_indirect(self):\n \"\"\"#714\"\"\"\n\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n metafunc.parametrize(\"x\", [1], indirect=True)\n metafunc.parametrize(\"y\", [2, 3], indirect=True)\n assert len(metafunc._calls) == 2\n assert metafunc._calls[0].funcargs == {}\n assert metafunc._calls[1].funcargs == {}\n assert metafunc._calls[0].params == dict(x=1, y=2)\n assert metafunc._calls[1].params == dict(x=1, y=3)\n\n def test_parametrize_indirect_list(self):\n \"\"\"#714\"\"\"\n\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n metafunc.parametrize(\"x, y\", [(\"a\", \"b\")], indirect=[\"x\"])\n assert metafunc._calls[0].funcargs == dict(y=\"b\")\n assert metafunc._calls[0].params == dict(x=\"a\")\n\n def test_parametrize_indirect_list_all(self):\n \"\"\"#714\"\"\"\n\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n metafunc.parametrize(\"x, y\", [(\"a\", \"b\")], indirect=[\"x\", \"y\"])\n assert metafunc._calls[0].funcargs == {}\n assert metafunc._calls[0].params == dict(x=\"a\", y=\"b\")\n\n def test_parametrize_indirect_list_empty(self):\n \"\"\"#714\"\"\"\n\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n metafunc.parametrize(\"x, y\", [(\"a\", \"b\")], indirect=[])\n assert metafunc._calls[0].funcargs == dict(x=\"a\", y=\"b\")\n assert metafunc._calls[0].params == {}\n\n def test_parametrize_indirect_list_functional(self, testdir):\n \"\"\"\n #714\n Test parametrization with 'indirect' parameter applied on\n particular arguments. As y is is direct, its value should\n be used directly rather than being passed to the fixture\n y.\n\n :param testdir: the instance of Testdir class, a temporary\n test directory.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope='function')\n def x(request):\n return request.param * 3\n @pytest.fixture(scope='function')\n def y(request):\n return request.param * 2\n @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x'])\n def test_simple(x,y):\n assert len(x) == 3\n assert len(y) == 1\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines([\"*test_simple*a-b*\", \"*1 passed*\"])\n\n def test_parametrize_indirect_list_error(self, testdir):\n \"\"\"#714\"\"\"\n\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n with pytest.raises(pytest.fail.Exception):\n metafunc.parametrize(\"x, y\", [(\"a\", \"b\")], indirect=[\"x\", \"z\"])\n\n def test_parametrize_uses_no_fixture_error_indirect_false(self, testdir):\n \"\"\"The 'uses no fixture' error tells the user at collection time\n that the parametrize data they've set up doesn't correspond to the\n fixtures in their test function, rather than silently ignoring this\n and letting the test potentially pass.\n\n #714\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=False)\n def test_simple(x):\n assert len(x) == 3\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*uses no argument 'y'*\"])\n\n def test_parametrize_uses_no_fixture_error_indirect_true(self, testdir):\n \"\"\"#714\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope='function')\n def x(request):\n return request.param * 3\n @pytest.fixture(scope='function')\n def y(request):\n return request.param * 2\n\n @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=True)\n def test_simple(x):\n assert len(x) == 3\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*uses no fixture 'y'*\"])\n\n def test_parametrize_indirect_uses_no_fixture_error_indirect_string(self, testdir):\n \"\"\"#714\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope='function')\n def x(request):\n return request.param * 3\n\n @pytest.mark.parametrize('x, y', [('a', 'b')], indirect='y')\n def test_simple(x):\n assert len(x) == 3\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*uses no fixture 'y'*\"])\n\n def test_parametrize_indirect_uses_no_fixture_error_indirect_list(self, testdir):\n \"\"\"#714\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope='function')\n def x(request):\n return request.param * 3\n\n @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['y'])\n def test_simple(x):\n assert len(x) == 3\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*uses no fixture 'y'*\"])\n\n def test_parametrize_argument_not_in_indirect_list(self, testdir):\n \"\"\"#714\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope='function')\n def x(request):\n return request.param * 3\n\n @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x'])\n def test_simple(x):\n assert len(x) == 3\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*uses no argument 'y'*\"])\n\n def test_parametrize_gives_indicative_error_on_function_with_default_argument(\n self, testdir\n ):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize('x, y', [('a', 'b')])\n def test_simple(x, y=1):\n assert len(x) == 1\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines(\n [\"*already takes an argument 'y' with a default value\"]\n )\n\n def test_parametrize_functional(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('x', [1,2], indirect=True)\n metafunc.parametrize('y', [2])\n @pytest.fixture\n def x(request):\n return request.param * 10\n\n def test_simple(x,y):\n assert x in (10,20)\n assert y == 2\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n [\"*test_simple*1-2*\", \"*test_simple*2-2*\", \"*2 passed*\"]\n )\n\n def test_parametrize_onearg(self):\n metafunc = self.Metafunc(lambda x: None)\n metafunc.parametrize(\"x\", [1, 2])\n assert len(metafunc._calls) == 2\n assert metafunc._calls[0].funcargs == dict(x=1)\n assert metafunc._calls[0].id == \"1\"\n assert metafunc._calls[1].funcargs == dict(x=2)\n assert metafunc._calls[1].id == \"2\"\n\n def test_parametrize_onearg_indirect(self):\n metafunc = self.Metafunc(lambda x: None)\n metafunc.parametrize(\"x\", [1, 2], indirect=True)\n assert metafunc._calls[0].params == dict(x=1)\n assert metafunc._calls[0].id == \"1\"\n assert metafunc._calls[1].params == dict(x=2)\n assert metafunc._calls[1].id == \"2\"\n\n def test_parametrize_twoargs(self):\n metafunc = self.Metafunc(lambda x, y: None)\n metafunc.parametrize((\"x\", \"y\"), [(1, 2), (3, 4)])\n assert len(metafunc._calls) == 2\n assert metafunc._calls[0].funcargs == dict(x=1, y=2)\n assert metafunc._calls[0].id == \"1-2\"\n assert metafunc._calls[1].funcargs == dict(x=3, y=4)\n assert metafunc._calls[1].id == \"3-4\"\n\n def test_parametrize_multiple_times(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n pytestmark = pytest.mark.parametrize(\"x\", [1,2])\n def test_func(x):\n assert 0, x\n class TestClass(object):\n pytestmark = pytest.mark.parametrize(\"y\", [3,4])\n def test_meth(self, x, y):\n assert 0, x\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.assert_outcomes(failed=6)\n\n def test_parametrize_CSV(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize(\"x, y,\", [(1,2), (2,3)])\n def test_func(x, y):\n assert x+1 == y\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_parametrize_class_scenarios(self, testdir):\n testdir.makepyfile(\n \"\"\"\n # same as doc/en/example/parametrize scenario example\n def pytest_generate_tests(metafunc):\n idlist = []\n argvalues = []\n for scenario in metafunc.cls.scenarios:\n idlist.append(scenario[0])\n items = scenario[1].items()\n argnames = [x[0] for x in items]\n argvalues.append(([x[1] for x in items]))\n metafunc.parametrize(argnames, argvalues, ids=idlist, scope=\"class\")\n\n class Test(object):\n scenarios = [['1', {'arg': {1: 2}, \"arg2\": \"value2\"}],\n ['2', {'arg':'value2', \"arg2\": \"value2\"}]]\n\n def test_1(self, arg, arg2):\n pass\n\n def test_2(self, arg2, arg):\n pass\n\n def test_3(self, arg, arg2):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n \"\"\"\n *test_1*1*\n *test_2*1*\n *test_3*1*\n *test_1*2*\n *test_2*2*\n *test_3*2*\n *6 passed*\n \"\"\"\n )\n\n def test_format_args(self):\n def function1():\n pass\n\n assert fixtures._format_args(function1) == \"()\"\n\n def function2(arg1):\n pass\n\n assert fixtures._format_args(function2) == \"(arg1)\"\n\n def function3(arg1, arg2=\"qwe\"):\n pass\n\n assert fixtures._format_args(function3) == \"(arg1, arg2='qwe')\"\n\n def function4(arg1, *args, **kwargs):\n pass\n\n assert fixtures._format_args(function4) == \"(arg1, *args, **kwargs)\""},{"attributeType":"null","col":8,"comment":"null","endLoc":362,"id":1038,"name":"fspath","nodeType":"Attribute","startLoc":362,"text":"self.fspath"},{"col":4,"comment":"null","endLoc":37,"header":"def Metafunc(self, func, config=None)","id":1039,"name":"Metafunc","nodeType":"Function","startLoc":20,"text":"def Metafunc(self, func, config=None):\n # the unit tests of this class check if things work correctly\n # on the funcarg level, so we don't need a full blown\n # initiliazation\n class FixtureInfo(object):\n name2fixturedefs = None\n\n def __init__(self, names):\n self.names_closure = names\n\n @attr.s\n class DefinitionMock(object):\n obj = attr.ib()\n\n names = fixtures.getfuncargnames(func)\n fixtureinfo = FixtureInfo(names)\n definition = DefinitionMock(func)\n return python.Metafunc(definition, fixtureinfo, config)"},{"col":0,"comment":"Returns the names of a function's mandatory arguments.\n\n This should return the names of all function arguments that:\n * Aren't bound to an instance or type as in instance or class methods.\n * Don't have default values.\n * Aren't bound with functools.partial.\n * Aren't replaced with mocks.\n\n The is_method and cls arguments indicate that the function should\n be treated as a bound method even though it's not unless, only in\n the case of cls, the function is a static method.\n\n @RonnyPfannschmidt: This function should be refactored when we\n revisit fixtures. The fixture mechanism should ask the node for\n the fixture names, and not try to obtain directly from the\n function object well after collection has occurred.\n\n ","endLoc":165,"header":"def getfuncargnames(function, is_method=False, cls=None)","id":1041,"name":"getfuncargnames","nodeType":"Function","startLoc":115,"text":"def getfuncargnames(function, is_method=False, cls=None):\n \"\"\"Returns the names of a function's mandatory arguments.\n\n This should return the names of all function arguments that:\n * Aren't bound to an instance or type as in instance or class methods.\n * Don't have default values.\n * Aren't bound with functools.partial.\n * Aren't replaced with mocks.\n\n The is_method and cls arguments indicate that the function should\n be treated as a bound method even though it's not unless, only in\n the case of cls, the function is a static method.\n\n @RonnyPfannschmidt: This function should be refactored when we\n revisit fixtures. The fixture mechanism should ask the node for\n the fixture names, and not try to obtain directly from the\n function object well after collection has occurred.\n\n \"\"\"\n # The parameters attribute of a Signature object contains an\n # ordered mapping of parameter names to Parameter instances. This\n # creates a tuple of the names of the parameters that don't have\n # defaults.\n try:\n parameters = signature(function).parameters\n except (ValueError, TypeError) as e:\n fail(\n \"Could not determine arguments of {!r}: {}\".format(function, e),\n pytrace=False,\n )\n\n arg_names = tuple(\n p.name\n for p in parameters.values()\n if (\n p.kind is Parameter.POSITIONAL_OR_KEYWORD\n or p.kind is Parameter.KEYWORD_ONLY\n )\n and p.default is Parameter.empty\n )\n # If this function should be treated as a bound method even though\n # it's passed as an unbound method or function, remove the first\n # parameter name.\n if is_method or (\n cls and not isinstance(cls.__dict__.get(function.__name__, None), staticmethod)\n ):\n arg_names = arg_names[1:]\n # Remove any names that will be replaced with mocks.\n if hasattr(function, \"__wrapped__\"):\n arg_names = arg_names[num_mock_patch_args(function) :]\n return arg_names"},{"col":4,"comment":"null","endLoc":17,"header":"def collect(self)","id":1042,"name":"collect","nodeType":"Function","startLoc":12,"text":"def collect(self):\n import yaml # we need a yaml parser, e.g. PyYAML\n\n raw = yaml.safe_load(self.fspath.open())\n for name, spec in sorted(raw.items()):\n yield YamlItem(name, self, spec)"},{"col":4,"comment":"null","endLoc":308,"header":"def signature(obj: _IntrospectableCallable, *, follow_wrapped: bool = True) -> Signature","id":1043,"name":"signature","nodeType":"Function","startLoc":308,"text":"def signature(obj: _IntrospectableCallable, *, follow_wrapped: bool = True) -> Signature: ..."},{"className":"TWMock","col":0,"comment":"null","endLoc":66,"id":1044,"nodeType":"Class","startLoc":42,"text":"class TWMock(object):\n WRITE = object()\n\n def __init__(self):\n self.lines = []\n self.is_writing = False\n\n def sep(self, sep, line=None):\n self.lines.append((sep, line))\n\n def write(self, msg, **kw):\n self.lines.append((TWMock.WRITE, msg))\n\n def line(self, line, **kw):\n self.lines.append(line)\n\n def markup(self, text, **kw):\n return text\n\n def get_write_msg(self, idx):\n flag, msg = self.lines[idx]\n assert flag == TWMock.WRITE\n return msg\n\n fullwidth = 80"},{"col":4,"comment":"Make sure that arrays of all different dimensions are repr'd correctly.","endLoc":77,"header":"@pytest.mark.parametrize(\n \"value, repr_string\",\n [\n (5.0, \"approx(5.0 {pm} 5.0e-06)\"),\n ([5.0], \"approx([5.0 {pm} 5.0e-06])\"),\n ([[5.0]], \"approx([[5.0 {pm} 5.0e-06]])\"),\n ([[5.0, 6.0]], \"approx([[5.0 {pm} 5.0e-06, 6.0 {pm} 6.0e-06]])\"),\n ([[5.0], [6.0]], \"approx([[5.0 {pm} 5.0e-06], [6.0 {pm} 6.0e-06]])\"),\n ],\n )\n def test_repr_nd_array(self, plus_minus, value, repr_string)","id":1045,"name":"test_repr_nd_array","nodeType":"Function","startLoc":63,"text":"@pytest.mark.parametrize(\n \"value, repr_string\",\n [\n (5.0, \"approx(5.0 {pm} 5.0e-06)\"),\n ([5.0], \"approx([5.0 {pm} 5.0e-06])\"),\n ([[5.0]], \"approx([[5.0 {pm} 5.0e-06]])\"),\n ([[5.0, 6.0]], \"approx([[5.0 {pm} 5.0e-06, 6.0 {pm} 6.0e-06]])\"),\n ([[5.0], [6.0]], \"approx([[5.0 {pm} 5.0e-06], [6.0 {pm} 6.0e-06]])\"),\n ],\n )\n def test_repr_nd_array(self, plus_minus, value, repr_string):\n \"\"\"Make sure that arrays of all different dimensions are repr'd correctly.\"\"\"\n np = pytest.importorskip(\"numpy\")\n np_array = np.array(value)\n assert repr(approx(np_array)) == repr_string.format(pm=plus_minus)"},{"col":4,"comment":"null","endLoc":77,"header":"def __init__(self, config)","id":1046,"name":"__init__","nodeType":"Function","startLoc":62,"text":"def __init__(self, config):\n self.config = config\n try:\n self.fnpats = config.getini(\"python_files\")\n except ValueError:\n self.fnpats = [\"test_*.py\", \"*_test.py\"]\n self.session = None\n self.modules = {}\n self._rewritten_names = set()\n self._must_rewrite = set()\n # flag to guard against trying to rewrite a pyc file while we are already writing another pyc file,\n # which might result in infinite recursion (#3506)\n self._writing_pyc = False\n self._basenames_to_check_rewrite = {\"conftest\"}\n self._marked_for_rewrite_cache = {}\n self._session_paths_checked = False"},{"col":4,"comment":"null","endLoc":452,"header":"def __repr__(self)","id":1047,"name":"__repr__","nodeType":"Function","startLoc":445,"text":"def __repr__(self):\n return \"<%s %s exitstatus=%r testsfailed=%d testscollected=%d>\" % (\n self.__class__.__name__,\n self.name,\n getattr(self, \"exitstatus\", \"\"),\n self.testsfailed,\n self.testscollected,\n )"},{"col":4,"comment":"null","endLoc":47,"header":"def __init__(self)","id":1048,"name":"__init__","nodeType":"Function","startLoc":45,"text":"def __init__(self):\n self.lines = []\n self.is_writing = False"},{"col":4,"comment":"null","endLoc":50,"header":"def sep(self, sep, line=None)","id":1049,"name":"sep","nodeType":"Function","startLoc":49,"text":"def sep(self, sep, line=None):\n self.lines.append((sep, line))"},{"col":4,"comment":"null","endLoc":456,"header":"def _node_location_to_relpath(self, node_path)","id":1050,"name":"_node_location_to_relpath","nodeType":"Function","startLoc":454,"text":"def _node_location_to_relpath(self, node_path):\n # bestrelpath is a quite slow function\n return self._bestrelpathcache[node_path]"},{"col":4,"comment":"null","endLoc":463,"header":"@hookimpl(tryfirst=True)\n def pytest_collectstart(self)","id":1051,"name":"pytest_collectstart","nodeType":"Function","startLoc":458,"text":"@hookimpl(tryfirst=True)\n def pytest_collectstart(self):\n if self.shouldfail:\n raise self.Failed(self.shouldfail)\n if self.shouldstop:\n raise self.Interrupted(self.shouldstop)"},{"col":4,"comment":"null","endLoc":23,"header":"def __init__(self, name, parent, spec)","id":1052,"name":"__init__","nodeType":"Function","startLoc":21,"text":"def __init__(self, name, parent, spec):\n super(YamlItem, self).__init__(name, parent)\n self.spec = spec"},{"col":4,"comment":"null","endLoc":83,"header":"def test_operator_overloading(self)","id":1053,"name":"test_operator_overloading","nodeType":"Function","startLoc":79,"text":"def test_operator_overloading(self):\n assert 1 == approx(1, rel=1e-6, abs=1e-12)\n assert not (1 != approx(1, rel=1e-6, abs=1e-12))\n assert 10 != approx(1, rel=1e-6, abs=1e-12)\n assert not (10 == approx(1, rel=1e-6, abs=1e-12))"},{"col":4,"comment":"null","endLoc":53,"header":"def write(self, msg, **kw)","id":1054,"name":"write","nodeType":"Function","startLoc":52,"text":"def write(self, msg, **kw):\n self.lines.append((TWMock.WRITE, msg))"},{"col":4,"comment":"null","endLoc":56,"header":"def line(self, line, **kw)","id":1055,"name":"line","nodeType":"Function","startLoc":55,"text":"def line(self, line, **kw):\n self.lines.append(line)"},{"col":4,"comment":"null","endLoc":59,"header":"def markup(self, text, **kw)","id":1056,"name":"markup","nodeType":"Function","startLoc":58,"text":"def markup(self, text, **kw):\n return text"},{"col":4,"comment":"null","endLoc":64,"header":"def get_write_msg(self, idx)","id":1057,"name":"get_write_msg","nodeType":"Function","startLoc":61,"text":"def get_write_msg(self, idx):\n flag, msg = self.lines[idx]\n assert flag == TWMock.WRITE\n return msg"},{"attributeType":"null","col":4,"comment":"null","endLoc":43,"id":1058,"name":"WRITE","nodeType":"Attribute","startLoc":43,"text":"WRITE"},{"attributeType":"null","col":4,"comment":"null","endLoc":66,"id":1059,"name":"fullwidth","nodeType":"Attribute","startLoc":66,"text":"fullwidth"},{"attributeType":"null","col":8,"comment":"null","endLoc":46,"id":1060,"name":"lines","nodeType":"Attribute","startLoc":46,"text":"self.lines"},{"attributeType":"null","col":8,"comment":"null","endLoc":47,"id":1061,"name":"is_writing","nodeType":"Attribute","startLoc":47,"text":"self.is_writing"},{"col":4,"comment":"null","endLoc":97,"header":"def test_exactly_equal(self)","id":1062,"name":"test_exactly_equal","nodeType":"Function","startLoc":85,"text":"def test_exactly_equal(self):\n examples = [\n (2.0, 2.0),\n (0.1e200, 0.1e200),\n (1.123e-300, 1.123e-300),\n (12345, 12345.0),\n (0.0, -0.0),\n (345678, 345678),\n (Decimal(\"1.0001\"), Decimal(\"1.0001\")),\n (Fraction(1, 3), Fraction(-1, -3)),\n ]\n for a, x in examples:\n assert a == approx(x)"},{"col":4,"comment":"null","endLoc":471,"header":"@hookimpl(tryfirst=True)\n def pytest_runtest_logreport(self, report)","id":1063,"name":"pytest_runtest_logreport","nodeType":"Function","startLoc":465,"text":"@hookimpl(tryfirst=True)\n def pytest_runtest_logreport(self, report):\n if report.failed and not hasattr(report, \"wasxfail\"):\n self.testsfailed += 1\n maxfail = self.config.getvalue(\"maxfail\")\n if maxfail and self.testsfailed >= maxfail:\n self.shouldfail = \"stopping after %d failures\" % (self.testsfailed)"},{"className":"TestExceptionInfo","col":0,"comment":"null","endLoc":177,"id":1064,"nodeType":"Class","startLoc":164,"text":"class TestExceptionInfo(object):\n def test_bad_getsource(self):\n try:\n if False:\n pass\n else:\n assert False\n except AssertionError:\n exci = _pytest._code.ExceptionInfo.from_current()\n assert exci.getrepr()\n\n def test_from_current_with_missing(self):\n with pytest.raises(AssertionError, match=\"no current exception\"):\n _pytest._code.ExceptionInfo.from_current()"},{"col":4,"comment":"null","endLoc":173,"header":"def test_bad_getsource(self)","id":1068,"name":"test_bad_getsource","nodeType":"Function","startLoc":165,"text":"def test_bad_getsource(self):\n try:\n if False:\n pass\n else:\n assert False\n except AssertionError:\n exci = _pytest._code.ExceptionInfo.from_current()\n assert exci.getrepr()"},{"col":4,"comment":"null","endLoc":476,"header":"def isinitpath(self, path)","id":1069,"name":"isinitpath","nodeType":"Function","startLoc":475,"text":"def isinitpath(self, path):\n return path in self._initialpaths"},{"col":4,"comment":"null","endLoc":490,"header":"def gethookproxy(self, fspath)","id":1070,"name":"gethookproxy","nodeType":"Function","startLoc":478,"text":"def gethookproxy(self, fspath):\n # check if we have the common case of running\n # hooks with all conftest.py files\n pm = self.config.pluginmanager\n my_conftestmodules = pm._getconftestmodules(fspath)\n remove_mods = pm._conftest_plugins.difference(my_conftestmodules)\n if remove_mods:\n # one or more conftests are not in use at this fspath\n proxy = FSHookProxy(fspath, pm, remove_mods)\n else:\n # all plugis are active for this fspath\n proxy = self.config.hook\n return proxy"},{"col":4,"comment":"null","endLoc":389,"header":"def __init__(self, fspath, pm, remove_mods)","id":1072,"name":"__init__","nodeType":"Function","startLoc":386,"text":"def __init__(self, fspath, pm, remove_mods):\n self.fspath = fspath\n self.pm = pm\n self.remove_mods = remove_mods"},{"col":4,"comment":"null","endLoc":503,"header":"def perform_collect(self, args=None, genitems=True)","id":1073,"name":"perform_collect","nodeType":"Function","startLoc":492,"text":"def perform_collect(self, args=None, genitems=True):\n hook = self.config.hook\n try:\n items = self._perform_collect(args, genitems)\n self.config.pluginmanager.check_pending()\n hook.pytest_collection_modifyitems(\n session=self, config=self.config, items=items\n )\n finally:\n hook.pytest_collection_finish(session=self)\n self.testscollected = len(items)\n return items"},{"col":4,"comment":"null","endLoc":112,"header":"def add_attribute(self, name, value)","id":1074,"name":"add_attribute","nodeType":"Function","startLoc":111,"text":"def add_attribute(self, name, value):\n self.attrs[str(name)] = bin_xml_escape(value)"},{"className":"YamlItem","col":0,"comment":"null","endLoc":43,"id":1075,"nodeType":"Class","startLoc":20,"text":"class YamlItem(pytest.Item):\n def __init__(self, name, parent, spec):\n super(YamlItem, self).__init__(name, parent)\n self.spec = spec\n\n def runtest(self):\n for name, value in sorted(self.spec.items()):\n # some custom test execution (dumb example follows)\n if name != value:\n raise YamlException(self, name, value)\n\n def repr_failure(self, excinfo):\n \"\"\" called when self.runtest() raises an exception. \"\"\"\n if isinstance(excinfo.value, YamlException):\n return \"\\n\".join(\n [\n \"usecase execution failed\",\n \" spec failed: %r: %r\" % excinfo.value.args[1:3],\n \" no further details known at this point.\",\n ]\n )\n\n def reportinfo(self):\n return self.fspath, 0, \"usecase: %s\" % self.name"},{"className":"Item","col":0,"comment":" a basic test invocation item. Note that for a single function\n there might be multiple test invocation items.\n ","endLoc":429,"id":1076,"nodeType":"Class","startLoc":383,"text":"class Item(Node):\n \"\"\" a basic test invocation item. Note that for a single function\n there might be multiple test invocation items.\n \"\"\"\n\n nextitem = None\n\n def __init__(self, name, parent=None, config=None, session=None, nodeid=None):\n super(Item, self).__init__(name, parent, config, session, nodeid=nodeid)\n self._report_sections = []\n\n #: user properties is a list of tuples (name, value) that holds user\n #: defined properties for this test.\n self.user_properties = []\n\n def add_report_section(self, when, key, content):\n \"\"\"\n Adds a new report section, similar to what's done internally to add stdout and\n stderr captured output::\n\n item.add_report_section(\"call\", \"stdout\", \"report section contents\")\n\n :param str when:\n One of the possible capture states, ``\"setup\"``, ``\"call\"``, ``\"teardown\"``.\n :param str key:\n Name of the section, can be customized at will. Pytest uses ``\"stdout\"`` and\n ``\"stderr\"`` internally.\n\n :param str content:\n The full contents as a string.\n \"\"\"\n if content:\n self._report_sections.append((when, key, content))\n\n def reportinfo(self):\n return self.fspath, None, \"\"\n\n @property\n def location(self):\n try:\n return self._location\n except AttributeError:\n location = self.reportinfo()\n fspath = self.session._node_location_to_relpath(location[0])\n location = (fspath, location[1], str(location[2]))\n self._location = location\n return location"},{"col":4,"comment":"\n Adds a new report section, similar to what's done internally to add stdout and\n stderr captured output::\n\n item.add_report_section(\"call\", \"stdout\", \"report section contents\")\n\n :param str when:\n One of the possible capture states, ``\"setup\"``, ``\"call\"``, ``\"teardown\"``.\n :param str key:\n Name of the section, can be customized at will. Pytest uses ``\"stdout\"`` and\n ``\"stderr\"`` internally.\n\n :param str content:\n The full contents as a string.\n ","endLoc":415,"header":"def add_report_section(self, when, key, content)","id":1077,"name":"add_report_section","nodeType":"Function","startLoc":398,"text":"def add_report_section(self, when, key, content):\n \"\"\"\n Adds a new report section, similar to what's done internally to add stdout and\n stderr captured output::\n\n item.add_report_section(\"call\", \"stdout\", \"report section contents\")\n\n :param str when:\n One of the possible capture states, ``\"setup\"``, ``\"call\"``, ``\"teardown\"``.\n :param str key:\n Name of the section, can be customized at will. Pytest uses ``\"stdout\"`` and\n ``\"stderr\"`` internally.\n\n :param str content:\n The full contents as a string.\n \"\"\"\n if content:\n self._report_sections.append((when, key, content))"},{"col":0,"comment":" return number of arguments used up by mock arguments (if any) ","endLoc":112,"header":"def num_mock_patch_args(function)","id":1078,"name":"num_mock_patch_args","nodeType":"Function","startLoc":101,"text":"def num_mock_patch_args(function):\n \"\"\" return number of arguments used up by mock arguments (if any) \"\"\"\n patchings = getattr(function, \"patchings\", None)\n if not patchings:\n return 0\n mock_modules = [sys.modules.get(\"mock\"), sys.modules.get(\"unittest.mock\")]\n if any(mock_modules):\n sentinels = [m.DEFAULT for m in mock_modules if m is not None]\n return len(\n [p for p in patchings if not p.attribute_name and p.new in sentinels]\n )\n return len(patchings)"},{"col":4,"comment":"null","endLoc":177,"header":"def test_from_current_with_missing(self)","id":1079,"name":"test_from_current_with_missing","nodeType":"Function","startLoc":175,"text":"def test_from_current_with_missing(self):\n with pytest.raises(AssertionError, match=\"no current exception\"):\n _pytest._code.ExceptionInfo.from_current()"},{"col":4,"comment":"null","endLoc":535,"header":"def _perform_collect(self, args, genitems)","id":1080,"name":"_perform_collect","nodeType":"Function","startLoc":505,"text":"def _perform_collect(self, args, genitems):\n if args is None:\n args = self.config.args\n self.trace(\"perform_collect\", self, args)\n self.trace.root.indent += 1\n self._notfound = []\n initialpaths = []\n self._initialparts = []\n self.items = items = []\n for arg in args:\n parts = self._parsearg(arg)\n self._initialparts.append(parts)\n initialpaths.append(parts[0])\n self._initialpaths = frozenset(initialpaths)\n rep = collect_one_node(self)\n self.ihook.pytest_collectreport(report=rep)\n self.trace.root.indent -= 1\n if self._notfound:\n errors = []\n for arg, exc in self._notfound:\n line = \"(no name %r in any of %r)\" % (arg, exc.args[0])\n errors.append(\"not found: %s\\n%s\" % (arg, line))\n # XXX: test this\n raise UsageError(*errors)\n if not genitems:\n return rep.result\n else:\n if rep.passed:\n for node in rep.result:\n self.items.extend(self.genitems(node))\n return items"},{"col":4,"comment":"null","endLoc":418,"header":"def reportinfo(self)","id":1081,"name":"reportinfo","nodeType":"Function","startLoc":417,"text":"def reportinfo(self):\n return self.fspath, None, \"\""},{"col":4,"comment":"null","endLoc":429,"header":"@property\n def location(self)","id":1082,"name":"location","nodeType":"Function","startLoc":420,"text":"@property\n def location(self):\n try:\n return self._location\n except AttributeError:\n location = self.reportinfo()\n fspath = self.session._node_location_to_relpath(location[0])\n location = (fspath, location[1], str(location[2]))\n self._location = location\n return location"},{"className":"TestTracebackEntry","col":0,"comment":"null","endLoc":192,"id":1083,"nodeType":"Class","startLoc":180,"text":"class TestTracebackEntry(object):\n def test_getsource(self):\n try:\n if False:\n pass\n else:\n assert False\n except AssertionError:\n exci = _pytest._code.ExceptionInfo.from_current()\n entry = exci.traceback[0]\n source = entry.getsource()\n assert len(source) == 6\n assert \"assert False\" in source[5]"},{"col":4,"comment":" return (fspath, names) tuple after checking the file exists. ","endLoc":718,"header":"def _parsearg(self, arg)","id":1084,"name":"_parsearg","nodeType":"Function","startLoc":704,"text":"def _parsearg(self, arg):\n \"\"\" return (fspath, names) tuple after checking the file exists. \"\"\"\n parts = str(arg).split(\"::\")\n if self.config.option.pyargs:\n parts[0] = self._tryconvertpyarg(parts[0])\n relpath = parts[0].replace(\"/\", os.sep)\n path = self.config.invocation_dir.join(relpath, abs=True)\n if not path.check():\n if self.config.option.pyargs:\n raise UsageError(\n \"file or package not found: \" + arg + \" (missing __init__.py?)\"\n )\n raise UsageError(\"file not found: \" + arg)\n parts[0] = path.realpath()\n return parts"},{"col":4,"comment":"null","endLoc":192,"header":"def test_getsource(self)","id":1085,"name":"test_getsource","nodeType":"Function","startLoc":181,"text":"def test_getsource(self):\n try:\n if False:\n pass\n else:\n assert False\n except AssertionError:\n exci = _pytest._code.ExceptionInfo.from_current()\n entry = exci.traceback[0]\n source = entry.getsource()\n assert len(source) == 6\n assert \"assert False\" in source[5]"},{"className":"TestReprFuncArgs","col":0,"comment":"null","endLoc":211,"id":1086,"nodeType":"Class","startLoc":195,"text":"class TestReprFuncArgs(object):\n def test_not_raise_exception_with_mixed_encoding(self):\n from _pytest._code.code import ReprFuncArgs\n\n tw = TWMock()\n\n args = [(\"unicode_string\", u\"São Paulo\"), (\"utf8_string\", b\"S\\xc3\\xa3o Paulo\")]\n\n r = ReprFuncArgs(args)\n r.toterminal(tw)\n if sys.version_info[0] >= 3:\n assert (\n tw.lines[0]\n == r\"unicode_string = São Paulo, utf8_string = b'S\\xc3\\xa3o Paulo'\"\n )\n else:\n assert tw.lines[0] == \"unicode_string = São Paulo, utf8_string = São Paulo\""},{"col":4,"comment":"null","endLoc":211,"header":"def test_not_raise_exception_with_mixed_encoding(self)","id":1087,"name":"test_not_raise_exception_with_mixed_encoding","nodeType":"Function","startLoc":196,"text":"def test_not_raise_exception_with_mixed_encoding(self):\n from _pytest._code.code import ReprFuncArgs\n\n tw = TWMock()\n\n args = [(\"unicode_string\", u\"São Paulo\"), (\"utf8_string\", b\"S\\xc3\\xa3o Paulo\")]\n\n r = ReprFuncArgs(args)\n r.toterminal(tw)\n if sys.version_info[0] >= 3:\n assert (\n tw.lines[0]\n == r\"unicode_string = São Paulo, utf8_string = b'S\\xc3\\xa3o Paulo'\"\n )\n else:\n assert tw.lines[0] == \"unicode_string = São Paulo, utf8_string = São Paulo\""},{"col":4,"comment":"null","endLoc":1008,"header":"def __init__(self, args)","id":1088,"name":"__init__","nodeType":"Function","startLoc":1007,"text":"def __init__(self, args):\n self.args = args"},{"attributeType":"null","col":4,"comment":"null","endLoc":388,"id":1089,"name":"nextitem","nodeType":"Attribute","startLoc":388,"text":"nextitem"},{"col":4,"comment":"Return a Junit node containing custom properties, if any.\n ","endLoc":124,"header":"def make_properties_node(self)","id":1090,"name":"make_properties_node","nodeType":"Function","startLoc":114,"text":"def make_properties_node(self):\n \"\"\"Return a Junit node containing custom properties, if any.\n \"\"\"\n if self.properties:\n return Junit.properties(\n [\n Junit.property(name=name, value=value)\n for name, value in self.properties\n ]\n )\n return \"\""},{"attributeType":"function","col":12,"comment":"null","endLoc":428,"id":1091,"name":"_location","nodeType":"Attribute","startLoc":428,"text":"self._location"},{"attributeType":"null","col":8,"comment":"null","endLoc":396,"id":1092,"name":"user_properties","nodeType":"Attribute","startLoc":396,"text":"self.user_properties"},{"col":4,"comment":"null","endLoc":155,"header":"def record_testreport(self, testreport)","id":1093,"name":"record_testreport","nodeType":"Function","startLoc":126,"text":"def record_testreport(self, testreport):\n assert not self.testcase\n names = mangle_test_address(testreport.nodeid)\n existing_attrs = self.attrs\n classnames = names[:-1]\n if self.xml.prefix:\n classnames.insert(0, self.xml.prefix)\n attrs = {\n \"classname\": \".\".join(classnames),\n \"name\": bin_xml_escape(names[-1]),\n \"file\": testreport.location[0],\n }\n if testreport.location[1] is not None:\n attrs[\"line\"] = testreport.location[1]\n if hasattr(testreport, \"url\"):\n attrs[\"url\"] = testreport.url\n self.attrs = attrs\n self.attrs.update(existing_attrs) # restore any user-defined attributes\n\n # Preserve legacy testcase behavior\n if self.family == \"xunit1\":\n return\n\n # Filter out attributes not permitted by this test family.\n # Including custom attributes because they are not valid here.\n temp_attrs = {}\n for key in self.attrs.keys():\n if key in families[self.family][\"testcase\"]:\n temp_attrs[key] = self.attrs[key]\n self.attrs = temp_attrs"},{"col":0,"comment":"null","endLoc":473,"header":"def mangle_test_address(address)","id":1094,"name":"mangle_test_address","nodeType":"Function","startLoc":461,"text":"def mangle_test_address(address):\n path, possible_open_bracket, params = address.partition(\"[\")\n names = path.split(\"::\")\n try:\n names.remove(\"()\")\n except ValueError:\n pass\n # convert file path to dotted path\n names[0] = names[0].replace(nodes.SEP, \".\")\n names[0] = _py_ext_re.sub(\"\", names[0])\n # put any params back\n names[-1] += possible_open_bracket + params\n return names"},{"attributeType":"null","col":8,"comment":"null","endLoc":392,"id":1095,"name":"_report_sections","nodeType":"Attribute","startLoc":392,"text":"self._report_sections"},{"col":4,"comment":"null","endLoc":29,"header":"def runtest(self)","id":1096,"name":"runtest","nodeType":"Function","startLoc":25,"text":"def runtest(self):\n for name, value in sorted(self.spec.items()):\n # some custom test execution (dumb example follows)\n if name != value:\n raise YamlException(self, name, value)"},{"col":0,"comment":"null","endLoc":169,"header":"def add_funcarg_pseudo_fixture_def(collector, metafunc, fixturemanager)","id":1097,"name":"add_funcarg_pseudo_fixture_def","nodeType":"Function","startLoc":114,"text":"def add_funcarg_pseudo_fixture_def(collector, metafunc, fixturemanager):\n # this function will transform all collected calls to a functions\n # if they use direct funcargs (i.e. direct parametrization)\n # because we want later test execution to be able to rely on\n # an existing FixtureDef structure for all arguments.\n # XXX we can probably avoid this algorithm if we modify CallSpec2\n # to directly care for creating the fixturedefs within its methods.\n if not metafunc._calls[0].funcargs:\n return # this function call does not have direct parametrization\n # collect funcargs of all callspecs into a list of values\n arg2params = {}\n arg2scope = {}\n for callspec in metafunc._calls:\n for argname, argvalue in callspec.funcargs.items():\n assert argname not in callspec.params\n callspec.params[argname] = argvalue\n arg2params_list = arg2params.setdefault(argname, [])\n callspec.indices[argname] = len(arg2params_list)\n arg2params_list.append(argvalue)\n if argname not in arg2scope:\n scopenum = callspec._arg2scopenum.get(argname, scopenum_function)\n arg2scope[argname] = scopes[scopenum]\n callspec.funcargs.clear()\n\n # register artificial FixtureDef's so that later at test execution\n # time we can rely on a proper FixtureDef to exist for fixture setup.\n arg2fixturedefs = metafunc._arg2fixturedefs\n for argname, valuelist in arg2params.items():\n # if we have a scope that is higher than function we need\n # to make sure we only ever create an according fixturedef on\n # a per-scope basis. We thus store and cache the fixturedef on the\n # node related to the scope.\n scope = arg2scope[argname]\n node = None\n if scope != \"function\":\n node = get_scope_node(collector, scope)\n if node is None:\n assert scope == \"class\" and isinstance(collector, _pytest.python.Module)\n # use module-level collector for class-scope (for now)\n node = collector\n if node and argname in node._name2pseudofixturedef:\n arg2fixturedefs[argname] = [node._name2pseudofixturedef[argname]]\n else:\n fixturedef = FixtureDef(\n fixturemanager,\n \"\",\n argname,\n get_direct_param_fixture_func,\n arg2scope[argname],\n valuelist,\n False,\n False,\n )\n arg2fixturedefs[argname] = [fixturedef]\n if node is not None:\n node._name2pseudofixturedef[argname] = fixturedef"},{"col":0,"comment":"null","endLoc":111,"header":"def get_scope_node(node, scope)","id":1098,"name":"get_scope_node","nodeType":"Function","startLoc":107,"text":"def get_scope_node(node, scope):\n cls = scopename2class.get(scope)\n if cls is None:\n raise ValueError(\"unknown scope\")\n return node.getparent(cls)"},{"col":4,"comment":" called when self.runtest() raises an exception. ","endLoc":40,"header":"def repr_failure(self, excinfo)","id":1100,"name":"repr_failure","nodeType":"Function","startLoc":31,"text":"def repr_failure(self, excinfo):\n \"\"\" called when self.runtest() raises an exception. \"\"\"\n if isinstance(excinfo.value, YamlException):\n return \"\\n\".join(\n [\n \"usecase execution failed\",\n \" spec failed: %r: %r\" % excinfo.value.args[1:3],\n \" no further details known at this point.\",\n ]\n )"},{"col":4,"comment":"null","endLoc":1021,"header":"def insert(self, __index: SupportsIndex, __object: _T) -> None","id":1101,"name":"insert","nodeType":"Function","startLoc":1021,"text":"def insert(self, __index: SupportsIndex, __object: _T) -> None: ..."},{"col":4,"comment":"null","endLoc":1026,"header":"def toterminal(self, tw)","id":1103,"name":"toterminal","nodeType":"Function","startLoc":1010,"text":"def toterminal(self, tw):\n if self.args:\n linesofar = \"\"\n for name, value in self.args:\n ns = \"%s = %s\" % (safe_str(name), safe_str(value))\n if len(ns) + len(linesofar) + 2 > tw.fullwidth:\n if linesofar:\n tw.line(linesofar)\n linesofar = ns\n else:\n if linesofar:\n linesofar += \", \" + ns\n else:\n linesofar = ns\n if linesofar:\n tw.line(linesofar)\n tw.line(\"\")"},{"col":4,"comment":"null","endLoc":43,"header":"def reportinfo(self)","id":1104,"name":"reportinfo","nodeType":"Function","startLoc":42,"text":"def reportinfo(self):\n return self.fspath, 0, \"usecase: %s\" % self.name"},{"attributeType":"null","col":8,"comment":"null","endLoc":23,"id":1105,"name":"spec","nodeType":"Attribute","startLoc":23,"text":"self.spec"},{"className":"YamlException","col":0,"comment":" custom exception for error reporting. ","endLoc":47,"id":1106,"nodeType":"Class","startLoc":46,"text":"class YamlException(Exception):\n \"\"\" custom exception for error reporting. \"\"\""},{"col":0,"comment":"null","endLoc":8,"header":"def pytest_collect_file(parent, path)","id":1107,"name":"pytest_collect_file","nodeType":"Function","startLoc":6,"text":"def pytest_collect_file(parent, path):\n if path.ext == \".yml\" and path.basename.startswith(\"test\"):\n return YamlFile(path, parent)"},{"col":0,"comment":"null","endLoc":24,"header":"def test_ne()","id":1108,"name":"test_ne","nodeType":"Function","startLoc":20,"text":"def test_ne():\n code1 = _pytest._code.Code(compile('foo = \"bar\"', \"\", \"exec\"))\n assert code1 == code1\n code2 = _pytest._code.Code(compile('foo = \"baz\"', \"\", \"exec\"))\n assert code2 != code1"},{"col":4,"comment":"null","endLoc":661,"header":"def __init__(self, pluginmanager)","id":1109,"name":"__init__","nodeType":"Function","startLoc":639,"text":"def __init__(self, pluginmanager):\n #: access to command line option as attributes.\n #: (deprecated), use :py:func:`getoption() <_pytest.config.Config.getoption>` instead\n self.option = argparse.Namespace()\n from .argparsing import Parser, FILE_OR_DIR\n\n _a = FILE_OR_DIR\n self._parser = Parser(\n usage=\"%%(prog)s [options] [%s] [%s] [...]\" % (_a, _a),\n processopt=self._processopt,\n )\n #: a pluginmanager instance\n self.pluginmanager = pluginmanager\n self.trace = self.pluginmanager.trace.root.get(\"config\")\n self.hook = self.pluginmanager.hook\n self._inicache = {}\n self._override_ini = ()\n self._opt2dest = {}\n self._cleanup = []\n self.pluginmanager.register(self, \"pytestconfig\")\n self._configured = False\n self.invocation_dir = py.path.local()\n self.hook.pytest_addoption.call_historic(kwargs=dict(parser=self._parser))"},{"col":4,"comment":"null","endLoc":45,"header":"def __init__(self, rawcode)","id":1111,"name":"__init__","nodeType":"Function","startLoc":36,"text":"def __init__(self, rawcode):\n if not hasattr(rawcode, \"co_filename\"):\n rawcode = getrawcode(rawcode)\n try:\n self.filename = rawcode.co_filename\n self.firstlineno = rawcode.co_firstlineno - 1\n self.name = rawcode.co_name\n except AttributeError:\n raise TypeError(\"not a code object: %r\" % (rawcode,))\n self.raw = rawcode"},{"col":4,"comment":"Convert a dotted module name to path.","endLoc":702,"header":"def _tryconvertpyarg(self, x)","id":1114,"name":"_tryconvertpyarg","nodeType":"Function","startLoc":683,"text":"def _tryconvertpyarg(self, x):\n \"\"\"Convert a dotted module name to path.\"\"\"\n try:\n with _patched_find_module():\n loader = pkgutil.find_loader(x)\n except ImportError:\n return x\n if loader is None:\n return x\n # This method is sometimes invoked when AssertionRewritingHook, which\n # does not define a get_filename method, is already in place:\n try:\n with _patched_find_module():\n path = loader.get_filename(x)\n except AttributeError:\n # Retrieve path from AssertionRewritingHook:\n path = loader.modules[x][0].co_filename\n if loader.is_package(x):\n path = os.path.dirname(path)\n return path"},{"col":4,"comment":"null","endLoc":45,"header":"def test_no_funcargs(self, testdir)","id":1115,"name":"test_no_funcargs","nodeType":"Function","startLoc":39,"text":"def test_no_funcargs(self, testdir):\n def function():\n pass\n\n metafunc = self.Metafunc(function)\n assert not metafunc.fixturenames\n repr(metafunc._calls)"},{"col":0,"comment":"Patch bug in pkgutil.ImpImporter.find_module\n\n When using pkgutil.find_loader on python<3.4 it removes symlinks\n from the path due to a call to os.path.realpath. This is not consistent\n with actually doing the import (in these versions, pkgutil and __import__\n did not share the same underlying code). This can break conftest\n discovery for pytest where symlinks are involved.\n\n The only supported python<3.4 by pytest is python 2.7.\n ","endLoc":382,"header":"@contextlib.contextmanager\ndef _patched_find_module()","id":1116,"name":"_patched_find_module","nodeType":"Function","startLoc":345,"text":"@contextlib.contextmanager\ndef _patched_find_module():\n \"\"\"Patch bug in pkgutil.ImpImporter.find_module\n\n When using pkgutil.find_loader on python<3.4 it removes symlinks\n from the path due to a call to os.path.realpath. This is not consistent\n with actually doing the import (in these versions, pkgutil and __import__\n did not share the same underlying code). This can break conftest\n discovery for pytest where symlinks are involved.\n\n The only supported python<3.4 by pytest is python 2.7.\n \"\"\"\n if six.PY2: # python 3.4+ uses importlib instead\n\n def find_module_patched(self, fullname, path=None):\n # Note: we ignore 'path' argument since it is only used via meta_path\n subname = fullname.split(\".\")[-1]\n if subname != fullname and self.path is None:\n return None\n if self.path is None:\n path = None\n else:\n # original: path = [os.path.realpath(self.path)]\n path = [self.path]\n try:\n file, filename, etc = pkgutil.imp.find_module(subname, path)\n except ImportError:\n return None\n return pkgutil.ImpLoader(fullname, file, filename, etc)\n\n old_find_module = pkgutil.ImpImporter.find_module\n pkgutil.ImpImporter.find_module = find_module_patched\n try:\n yield\n finally:\n pkgutil.ImpImporter.find_module = old_find_module\n else:\n yield"},{"col":4,"comment":"null","endLoc":1022,"header":"def remove(self, __value: _T) -> None","id":1117,"name":"remove","nodeType":"Function","startLoc":1022,"text":"def remove(self, __value: _T) -> None: ..."},{"col":0,"comment":"null","endLoc":102,"header":"def pytest_collection(session)","id":1118,"name":"pytest_collection","nodeType":"Function","startLoc":95,"text":"def pytest_collection(session):\n # this hook is only called when test modules are collected\n # so for example not in the master process of pytest-xdist\n # (which does not collect test modules)\n assertstate = getattr(session.config, \"_assertstate\", None)\n if assertstate:\n if assertstate.hook is not None:\n assertstate.hook.set_session(session)"},{"col":4,"comment":"null","endLoc":841,"header":"def __init__(\n self,\n fixturemanager,\n baseid,\n argname,\n func,\n scope,\n params,\n unittest=False,\n ids=None,\n )","id":1119,"name":"__init__","nodeType":"Function","startLoc":815,"text":"def __init__(\n self,\n fixturemanager,\n baseid,\n argname,\n func,\n scope,\n params,\n unittest=False,\n ids=None,\n ):\n self._fixturemanager = fixturemanager\n self.baseid = baseid or \"\"\n self.has_location = baseid is not None\n self.func = func\n self.argname = argname\n self.scope = scope\n self.scopenum = scope2index(\n scope or \"function\",\n descr=\"Fixture '{}'\".format(func.__name__),\n where=baseid,\n )\n self.params = params\n self.argnames = getfuncargnames(func, is_method=unittest)\n self.unittest = unittest\n self.ids = ids\n self._finalizers = []"},{"col":4,"comment":"null","endLoc":102,"header":"def test_opposite_sign(self)","id":1120,"name":"test_opposite_sign","nodeType":"Function","startLoc":99,"text":"def test_opposite_sign(self):\n examples = [(eq, 1e-100, -1e-100), (ne, 1e100, -1e100)]\n for op, a, x in examples:\n assert op(a, approx(x))"},{"col":0,"comment":"Look up the index of ``scope`` and raise a descriptive value error\n if not defined.\n ","endLoc":696,"header":"def scope2index(scope, descr, where=None)","id":1121,"name":"scope2index","nodeType":"Function","startLoc":684,"text":"def scope2index(scope, descr, where=None):\n \"\"\"Look up the index of ``scope`` and raise a descriptive value error\n if not defined.\n \"\"\"\n try:\n return scopes.index(scope)\n except ValueError:\n fail(\n \"{} {}got an unexpected scope value '{}'\".format(\n descr, \"from {} \".format(where) if where else \"\", scope\n ),\n pytrace=False,\n )"},{"id":1122,"name":"doc/en/example/assertion/global_testmodule_config","nodeType":"Package"},{"fileName":"conftest.py","filePath":"doc/en/example/assertion/global_testmodule_config","id":1123,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport py\n\nimport pytest\n\nmydir = py.path.local(__file__).dirpath()\n\n\ndef pytest_runtest_setup(item):\n if isinstance(item, pytest.Function):\n if not item.fspath.relto(mydir):\n return\n mod = item.getparent(pytest.Module).obj\n if hasattr(mod, \"hello\"):\n print(\"mod.hello {!r}\".format(mod.hello))\n"},{"col":0,"comment":"null","endLoc":33,"header":"def test_code_gives_back_name_for_not_existing_file()","id":1124,"name":"test_code_gives_back_name_for_not_existing_file","nodeType":"Function","startLoc":27,"text":"def test_code_gives_back_name_for_not_existing_file():\n name = \"abc-123\"\n co_code = compile(\"pass\\n\", name, \"exec\")\n assert co_code.co_filename == name\n code = _pytest._code.Code(co_code)\n assert str(code.path) == name\n assert code.fullsource is None"},{"col":0,"comment":"null","endLoc":15,"header":"def pytest_runtest_setup(item)","id":1125,"name":"pytest_runtest_setup","nodeType":"Function","startLoc":9,"text":"def pytest_runtest_setup(item):\n if isinstance(item, pytest.Function):\n if not item.fspath.relto(mydir):\n return\n mod = item.getparent(pytest.Module).obj\n if hasattr(mod, \"hello\"):\n print(\"mod.hello {!r}\".format(mod.hello))"},{"col":4,"comment":"null","endLoc":55,"header":"def test_function_basic(self)","id":1129,"name":"test_function_basic","nodeType":"Function","startLoc":47,"text":"def test_function_basic(self):\n def func(arg1, arg2=\"qwe\"):\n pass\n\n metafunc = self.Metafunc(func)\n assert len(metafunc.fixturenames) == 1\n assert \"arg1\" in metafunc.fixturenames\n assert metafunc.function is func\n assert metafunc.cls is None"},{"col":4,"comment":"null","endLoc":67,"header":"def test_parametrize_error(self)","id":1130,"name":"test_parametrize_error","nodeType":"Function","startLoc":57,"text":"def test_parametrize_error(self):\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n metafunc.parametrize(\"x\", [1, 2])\n pytest.raises(ValueError, lambda: metafunc.parametrize(\"x\", [5, 6]))\n pytest.raises(ValueError, lambda: metafunc.parametrize(\"x\", [5, 6]))\n metafunc.parametrize(\"y\", [1, 2])\n pytest.raises(ValueError, lambda: metafunc.parametrize(\"y\", [5, 6]))\n pytest.raises(ValueError, lambda: metafunc.parametrize(\"y\", [5, 6]))"},{"col":4,"comment":"null","endLoc":740,"header":"def collect(self)","id":1131,"name":"collect","nodeType":"Function","startLoc":715,"text":"def collect(self):\n if not safe_getattr(self.obj, \"__test__\", True):\n return []\n if hasinit(self.obj):\n self.warn(\n PytestCollectionWarning(\n \"cannot collect test class %r because it has a \"\n \"__init__ constructor (from: %s)\"\n % (self.obj.__name__, self.parent.nodeid)\n )\n )\n return []\n elif hasnew(self.obj):\n self.warn(\n PytestCollectionWarning(\n \"cannot collect test class %r because it has a \"\n \"__new__ constructor (from: %s)\"\n % (self.obj.__name__, self.parent.nodeid)\n )\n )\n return []\n\n self._inject_setup_class_fixture()\n self._inject_setup_method_fixture()\n\n return [Instance(name=\"()\", parent=self)]"},{"col":4,"comment":" Add new invocations to the underlying test function using the list\n of argvalues for the given argnames. Parametrization is performed\n during the collection phase. If you need to setup expensive resources\n see about setting indirect to do it rather at test setup time.\n\n :arg argnames: a comma-separated string denoting one or more argument\n names, or a list/tuple of argument strings.\n\n :arg argvalues: The list of argvalues determines how often a\n test is invoked with different argument values. If only one\n argname was specified argvalues is a list of values. If N\n argnames were specified, argvalues must be a list of N-tuples,\n where each tuple-element specifies a value for its respective\n argname.\n\n :arg indirect: The list of argnames or boolean. A list of arguments'\n names (subset of argnames). If True the list contains all names from\n the argnames. Each argvalue corresponding to an argname in this list will\n be passed as request.param to its respective argname fixture\n function so that it can perform more expensive setups during the\n setup phase of a test rather than at collection time.\n\n :arg ids: list of string ids, or a callable.\n If strings, each is corresponding to the argvalues so that they are\n part of the test id. If None is given as id of specific test, the\n automatically generated id for that argument will be used.\n If callable, it should take one argument (a single argvalue) and return\n a string or return None. If None, the automatically generated id for that\n argument will be used.\n If no ids are provided they will be generated automatically from\n the argvalues.\n\n :arg scope: if specified it denotes the scope of the parameters.\n The scope is used for grouping tests by parameter instances.\n It will also override any fixture-function defined scope, allowing\n to set a dynamic scope using test context or configuration.\n ","endLoc":1038,"header":"def parametrize(self, argnames, argvalues, indirect=False, ids=None, scope=None)","id":1132,"name":"parametrize","nodeType":"Function","startLoc":958,"text":"def parametrize(self, argnames, argvalues, indirect=False, ids=None, scope=None):\n \"\"\" Add new invocations to the underlying test function using the list\n of argvalues for the given argnames. Parametrization is performed\n during the collection phase. If you need to setup expensive resources\n see about setting indirect to do it rather at test setup time.\n\n :arg argnames: a comma-separated string denoting one or more argument\n names, or a list/tuple of argument strings.\n\n :arg argvalues: The list of argvalues determines how often a\n test is invoked with different argument values. If only one\n argname was specified argvalues is a list of values. If N\n argnames were specified, argvalues must be a list of N-tuples,\n where each tuple-element specifies a value for its respective\n argname.\n\n :arg indirect: The list of argnames or boolean. A list of arguments'\n names (subset of argnames). If True the list contains all names from\n the argnames. Each argvalue corresponding to an argname in this list will\n be passed as request.param to its respective argname fixture\n function so that it can perform more expensive setups during the\n setup phase of a test rather than at collection time.\n\n :arg ids: list of string ids, or a callable.\n If strings, each is corresponding to the argvalues so that they are\n part of the test id. If None is given as id of specific test, the\n automatically generated id for that argument will be used.\n If callable, it should take one argument (a single argvalue) and return\n a string or return None. If None, the automatically generated id for that\n argument will be used.\n If no ids are provided they will be generated automatically from\n the argvalues.\n\n :arg scope: if specified it denotes the scope of the parameters.\n The scope is used for grouping tests by parameter instances.\n It will also override any fixture-function defined scope, allowing\n to set a dynamic scope using test context or configuration.\n \"\"\"\n from _pytest.fixtures import scope2index\n from _pytest.mark import ParameterSet\n\n argnames, parameters = ParameterSet._for_parametrize(\n argnames,\n argvalues,\n self.function,\n self.config,\n function_definition=self.definition,\n )\n del argvalues\n\n if scope is None:\n scope = _find_parametrized_scope(argnames, self._arg2fixturedefs, indirect)\n\n self._validate_if_using_arg_names(argnames, indirect)\n\n arg_values_types = self._resolve_arg_value_types(argnames, indirect)\n\n ids = self._resolve_arg_ids(argnames, ids, parameters, item=self.definition)\n\n scopenum = scope2index(\n scope, descr=\"parametrize() call in {}\".format(self.function.__name__)\n )\n\n # create the new calls: if we are parametrize() multiple times (by applying the decorator\n # more than once) then we accumulate those calls generating the cartesian product\n # of all calls\n newcalls = []\n for callspec in self._calls or [CallSpec2(self)]:\n for param_index, (param_id, param_set) in enumerate(zip(ids, parameters)):\n newcallspec = callspec.copy()\n newcallspec.setmulti2(\n arg_values_types,\n argnames,\n param_set.values,\n param_id,\n param_set.marks,\n scopenum,\n param_index,\n )\n newcalls.append(newcallspec)\n self._calls = newcalls"},{"col":0,"comment":"null","endLoc":852,"header":"def hasinit(obj)","id":1134,"name":"hasinit","nodeType":"Function","startLoc":849,"text":"def hasinit(obj):\n init = getattr(obj, \"__init__\", None)\n if init:\n return init != object.__init__"},{"col":0,"comment":"Setup the pytest_assertrepr_compare hook\n\n The newinterpret and rewrite modules will use util._reprcompare if\n it exists to use custom reporting via the\n pytest_assertrepr_compare hook. This sets up this custom\n comparison for the test.\n ","endLoc":141,"header":"def pytest_runtest_setup(item)","id":1135,"name":"pytest_runtest_setup","nodeType":"Function","startLoc":105,"text":"def pytest_runtest_setup(item):\n \"\"\"Setup the pytest_assertrepr_compare hook\n\n The newinterpret and rewrite modules will use util._reprcompare if\n it exists to use custom reporting via the\n pytest_assertrepr_compare hook. This sets up this custom\n comparison for the test.\n \"\"\"\n\n def callbinrepr(op, left, right):\n \"\"\"Call the pytest_assertrepr_compare hook and prepare the result\n\n This uses the first result from the hook and then ensures the\n following:\n * Overly verbose explanations are truncated unless configured otherwise\n (eg. if running in verbose mode).\n * Embedded newlines are escaped to help util.format_explanation()\n later.\n * If the rewrite mode is used embedded %-characters are replaced\n to protect later % formatting.\n\n The result can be formatted by util.format_explanation() for\n pretty printing.\n \"\"\"\n hook_result = item.ihook.pytest_assertrepr_compare(\n config=item.config, op=op, left=left, right=right\n )\n for new_expl in hook_result:\n if new_expl:\n new_expl = truncate.truncate_if_required(new_expl, item)\n new_expl = [line.replace(\"\\n\", \"\\\\n\") for line in new_expl]\n res = six.text_type(\"\\n~\").join(new_expl)\n if item.config.getvalue(\"assertmode\") == \"rewrite\":\n res = res.replace(\"%\", \"%%\")\n return res\n\n util._reprcompare = callbinrepr"},{"col":4,"comment":"null","endLoc":154,"header":"@classmethod\n def _for_parametrize(cls, argnames, argvalues, func, config, function_definition)","id":1136,"name":"_for_parametrize","nodeType":"Function","startLoc":121,"text":"@classmethod\n def _for_parametrize(cls, argnames, argvalues, func, config, function_definition):\n argnames, force_tuple = cls._parse_parametrize_args(argnames, argvalues)\n parameters = cls._parse_parametrize_parameters(argvalues, force_tuple)\n del argvalues\n\n if parameters:\n # check all parameter sets have the correct number of values\n for param in parameters:\n if len(param.values) != len(argnames):\n msg = (\n '{nodeid}: in \"parametrize\" the number of names ({names_len}):\\n'\n \" {names}\\n\"\n \"must be equal to the number of values ({values_len}):\\n\"\n \" {values}\"\n )\n fail(\n msg.format(\n nodeid=function_definition.nodeid,\n values=param.values,\n names=argnames,\n names_len=len(argnames),\n values_len=len(param.values),\n ),\n pytrace=False,\n )\n else:\n # empty parameter set (likely computed at runtime): create a single\n # parameter set with NOTSET values, with the \"empty parameter set\" mark applied to it\n mark = get_empty_parameterset_mark(config, argnames, func)\n parameters.append(\n ParameterSet(values=(NOTSET,) * len(argnames), marks=[mark], id=None)\n )\n return argnames, parameters"},{"col":4,"comment":"null","endLoc":29,"header":"def __init__(self, usage=None, processopt=None)","id":1137,"name":"__init__","nodeType":"Function","startLoc":22,"text":"def __init__(self, usage=None, processopt=None):\n self._anonymous = OptionGroup(\"custom options\", parser=self)\n self._groups = []\n self._processopt = processopt\n self._usage = usage\n self._inidict = {}\n self._ininames = []\n self.extra_info = {}"},{"col":4,"comment":"null","endLoc":113,"header":"@staticmethod\n def _parse_parametrize_args(argnames, argvalues, *args, **kwargs)","id":1138,"name":"_parse_parametrize_args","nodeType":"Function","startLoc":106,"text":"@staticmethod\n def _parse_parametrize_args(argnames, argvalues, *args, **kwargs):\n if not isinstance(argnames, (tuple, list)):\n argnames = [x.strip() for x in argnames.split(\",\") if x.strip()]\n force_tuple = len(argnames) == 1\n else:\n force_tuple = False\n return argnames, force_tuple"},{"col":4,"comment":"null","endLoc":119,"header":"@staticmethod\n def _parse_parametrize_parameters(argvalues, force_tuple)","id":1139,"name":"_parse_parametrize_parameters","nodeType":"Function","startLoc":115,"text":"@staticmethod\n def _parse_parametrize_parameters(argvalues, force_tuple):\n return [\n ParameterSet.extract_from(x, force_tuple=force_tuple) for x in argvalues\n ]"},{"col":4,"comment":"\n :param parameterset:\n a legacy style parameterset that may or may not be a tuple,\n and may or may not be wrapped into a mess of mark objects\n\n :param force_tuple:\n enforce tuple wrapping so single argument tuple values\n don't get decomposed and break tests\n ","endLoc":104,"header":"@classmethod\n def extract_from(cls, parameterset, force_tuple=False)","id":1140,"name":"extract_from","nodeType":"Function","startLoc":87,"text":"@classmethod\n def extract_from(cls, parameterset, force_tuple=False):\n \"\"\"\n :param parameterset:\n a legacy style parameterset that may or may not be a tuple,\n and may or may not be wrapped into a mess of mark objects\n\n :param force_tuple:\n enforce tuple wrapping so single argument tuple values\n don't get decomposed and break tests\n \"\"\"\n\n if isinstance(parameterset, cls):\n return parameterset\n if force_tuple:\n return cls.param(parameterset)\n else:\n return cls(parameterset, marks=[], id=None)"},{"col":0,"comment":"null","endLoc":858,"header":"def hasnew(obj)","id":1141,"name":"hasnew","nodeType":"Function","startLoc":855,"text":"def hasnew(obj):\n new = getattr(obj, \"__new__\", None)\n if new:\n return new != object.__new__"},{"col":4,"comment":"null","endLoc":85,"header":"@classmethod\n def param(cls, *values, **kwargs)","id":1142,"name":"param","nodeType":"Function","startLoc":65,"text":"@classmethod\n def param(cls, *values, **kwargs):\n marks = kwargs.pop(\"marks\", ())\n if isinstance(marks, MarkDecorator):\n marks = (marks,)\n else:\n assert isinstance(marks, (tuple, list, set))\n\n id_ = kwargs.pop(\"id\", None)\n if id_ is not None:\n if not isinstance(id_, six.string_types):\n raise TypeError(\n \"Expected id to be a string, got {}: {!r}\".format(type(id_), id_)\n )\n id_ = ascii_escaped(id_)\n\n if kwargs:\n warnings.warn(\n PYTEST_PARAM_UNKNOWN_KWARGS.format(args=sorted(kwargs)), stacklevel=3\n )\n return cls(values, marks, id_)"},{"col":4,"comment":"Injects a hidden autouse, class scoped fixture into the collected class object\n that invokes setup_class/teardown_class if either or both are available.\n\n Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with\n other fixtures (#517).\n ","endLoc":764,"header":"def _inject_setup_class_fixture(self)","id":1143,"name":"_inject_setup_class_fixture","nodeType":"Function","startLoc":742,"text":"def _inject_setup_class_fixture(self):\n \"\"\"Injects a hidden autouse, class scoped fixture into the collected class object\n that invokes setup_class/teardown_class if either or both are available.\n\n Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with\n other fixtures (#517).\n \"\"\"\n setup_class = _get_non_fixture_func(self.obj, \"setup_class\")\n teardown_class = getattr(self.obj, \"teardown_class\", None)\n if setup_class is None and teardown_class is None:\n return\n\n @fixtures.fixture(autouse=True, scope=\"class\")\n def xunit_setup_class_fixture(cls):\n if setup_class is not None:\n func = getimfunc(setup_class)\n _call_with_optional_argument(func, self.obj)\n yield\n if teardown_class is not None:\n func = getimfunc(teardown_class)\n _call_with_optional_argument(func, self.obj)\n\n self.obj.__pytest_setup_class = xunit_setup_class_fixture"},{"col":4,"comment":"null","endLoc":290,"header":"def __init__(self, name, description=\"\", parser=None)","id":1144,"name":"__init__","nodeType":"Function","startLoc":286,"text":"def __init__(self, name, description=\"\", parser=None):\n self.name = name\n self.description = description\n self.options = []\n self.parser = parser"},{"col":0,"comment":"Return the attribute from the given object to be used as a setup/teardown\n xunit-style function, but only if not marked as a fixture to\n avoid calling it twice.\n ","endLoc":709,"header":"def _get_non_fixture_func(obj, name)","id":1145,"name":"_get_non_fixture_func","nodeType":"Function","startLoc":702,"text":"def _get_non_fixture_func(obj, name):\n \"\"\"Return the attribute from the given object to be used as a setup/teardown\n xunit-style function, but only if not marked as a fixture to\n avoid calling it twice.\n \"\"\"\n meth = getattr(obj, name, None)\n if fixtures.getfixturemarker(meth) is None:\n return meth"},{"col":4,"comment":"null","endLoc":737,"header":"@overload\n def update(self, m: SupportsKeysAndGetItem[_KT, _VT], /, **kwargs: _VT) -> None","id":1146,"name":"update","nodeType":"Function","startLoc":736,"text":"@overload\n def update(self, m: SupportsKeysAndGetItem[_KT, _VT], /, **kwargs: _VT) -> None: ..."},{"col":4,"comment":"null","endLoc":739,"header":"@overload\n def update(self, m: Iterable[tuple[_KT, _VT]], /, **kwargs: _VT) -> None","id":1147,"name":"update","nodeType":"Function","startLoc":738,"text":"@overload\n def update(self, m: Iterable[tuple[_KT, _VT]], /, **kwargs: _VT) -> None: ..."},{"col":4,"comment":"null","endLoc":741,"header":"@overload\n def update(self, **kwargs: _VT) -> None","id":1148,"name":"update","nodeType":"Function","startLoc":740,"text":"@overload\n def update(self, **kwargs: _VT) -> None: ..."},{"col":0,"comment":"\n Truncate this assertion explanation if the given test item is eligible.\n ","endLoc":27,"header":"def truncate_if_required(explanation, item, max_length=None)","id":1149,"name":"truncate_if_required","nodeType":"Function","startLoc":21,"text":"def truncate_if_required(explanation, item, max_length=None):\n \"\"\"\n Truncate this assertion explanation if the given test item is eligible.\n \"\"\"\n if _should_truncate_item(item):\n return _truncate_explanation(explanation)\n return explanation"},{"col":0,"comment":"\n Whether or not this test item is eligible for truncation.\n ","endLoc":35,"header":"def _should_truncate_item(item)","id":1150,"name":"_should_truncate_item","nodeType":"Function","startLoc":30,"text":"def _should_truncate_item(item):\n \"\"\"\n Whether or not this test item is eligible for truncation.\n \"\"\"\n verbose = item.config.option.verbose\n return verbose < 2 and not _running_on_ci()"},{"col":0,"comment":"Check if we're currently running on a CI system.","endLoc":41,"header":"def _running_on_ci()","id":1151,"name":"_running_on_ci","nodeType":"Function","startLoc":38,"text":"def _running_on_ci():\n \"\"\"Check if we're currently running on a CI system.\"\"\"\n env_vars = [\"CI\", \"BUILD_NUMBER\"]\n return any(var in os.environ for var in env_vars)"},{"col":0,"comment":"\n Truncate given list of strings that makes up the assertion explanation.\n\n Truncates to either 8 lines, or 640 characters - whichever the input reaches\n first. The remaining lines will be replaced by a usage message.\n ","endLoc":80,"header":"def _truncate_explanation(input_lines, max_lines=None, max_chars=None)","id":1152,"name":"_truncate_explanation","nodeType":"Function","startLoc":44,"text":"def _truncate_explanation(input_lines, max_lines=None, max_chars=None):\n \"\"\"\n Truncate given list of strings that makes up the assertion explanation.\n\n Truncates to either 8 lines, or 640 characters - whichever the input reaches\n first. The remaining lines will be replaced by a usage message.\n \"\"\"\n\n if max_lines is None:\n max_lines = DEFAULT_MAX_LINES\n if max_chars is None:\n max_chars = DEFAULT_MAX_CHARS\n\n # Check if truncation required\n input_char_count = len(\"\".join(input_lines))\n if len(input_lines) <= max_lines and input_char_count <= max_chars:\n return input_lines\n\n # Truncate first to max_lines, and then truncate to max_chars if max_chars\n # is exceeded.\n truncated_explanation = input_lines[:max_lines]\n truncated_explanation = _truncate_by_char_count(truncated_explanation, max_chars)\n\n # Add ellipsis to final line\n truncated_explanation[-1] = truncated_explanation[-1] + \"...\"\n\n # Append useful message to explanation\n truncated_line_count = len(input_lines) - len(truncated_explanation)\n truncated_line_count += 1 # Account for the part-truncated final line\n msg = \"...Full output truncated\"\n if truncated_line_count == 1:\n msg += \" ({} line hidden)\".format(truncated_line_count)\n else:\n msg += \" ({} lines hidden)\".format(truncated_line_count)\n msg += \", {}\".format(USAGE_MSG)\n truncated_explanation.extend([six.text_type(\"\"), six.text_type(msg)])\n return truncated_explanation"},{"col":0,"comment":"null","endLoc":102,"header":"def _truncate_by_char_count(input_lines, max_chars)","id":1154,"name":"_truncate_by_char_count","nodeType":"Function","startLoc":83,"text":"def _truncate_by_char_count(input_lines, max_chars):\n # Check if truncation required\n if len(\"\".join(input_lines)) <= max_chars:\n return input_lines\n\n # Find point at which input length exceeds total allowed length\n iterated_char_count = 0\n for iterated_index, input_line in enumerate(input_lines):\n if iterated_char_count + len(input_line) > max_chars:\n break\n iterated_char_count += len(input_line)\n\n # Create truncated explanation with modified final line\n truncated_result = input_lines[:iterated_index]\n final_line = input_lines[iterated_index]\n if final_line:\n final_line_truncate_point = max_chars - iterated_char_count\n final_line = final_line[:final_line_truncate_point]\n truncated_result.append(final_line)\n return truncated_result"},{"col":0,"comment":"Call the given function with the given argument if func accepts one argument, otherwise\n calls func without arguments","endLoc":699,"header":"def _call_with_optional_argument(func, arg)","id":1156,"name":"_call_with_optional_argument","nodeType":"Function","startLoc":690,"text":"def _call_with_optional_argument(func, arg):\n \"\"\"Call the given function with the given argument if func accepts one argument, otherwise\n calls func without arguments\"\"\"\n arg_count = func.__code__.co_argcount\n if inspect.ismethod(func):\n arg_count -= 1\n if arg_count:\n func(arg)\n else:\n func()"},{"col":0,"comment":"null","endLoc":40,"header":"def test_code_with_class()","id":1158,"name":"test_code_with_class","nodeType":"Function","startLoc":36,"text":"def test_code_with_class():\n class A(object):\n pass\n\n pytest.raises(TypeError, _pytest._code.Code, A)"},{"col":4,"comment":"null","endLoc":112,"header":"def test_zero_tolerance(self)","id":1159,"name":"test_zero_tolerance","nodeType":"Function","startLoc":104,"text":"def test_zero_tolerance(self):\n within_1e10 = [(1.1e-100, 1e-100), (-1.1e-100, -1e-100)]\n for a, x in within_1e10:\n assert x == approx(x, rel=0.0, abs=0.0)\n assert a != approx(x, rel=0.0, abs=0.0)\n assert a == approx(x, rel=0.0, abs=5e-101)\n assert a != approx(x, rel=0.0, abs=5e-102)\n assert a == approx(x, rel=5e-1, abs=0.0)\n assert a != approx(x, rel=5e-2, abs=0.0)"},{"col":0,"comment":"null","endLoc":44,"header":"def x()","id":1160,"name":"x","nodeType":"Function","startLoc":43,"text":"def x():\n raise NotImplementedError()"},{"col":0,"comment":"null","endLoc":50,"header":"def test_code_fullsource()","id":1161,"name":"test_code_fullsource","nodeType":"Function","startLoc":47,"text":"def test_code_fullsource():\n code = _pytest._code.Code(x)\n full = code.fullsource\n assert \"test_code_fullsource()\" in str(full)"},{"col":4,"comment":"null","endLoc":125,"header":"def test_negative_tolerance(self)","id":1162,"name":"test_negative_tolerance","nodeType":"Function","startLoc":114,"text":"def test_negative_tolerance(self):\n # Negative tolerances are not allowed.\n illegal_kwargs = [\n dict(rel=-1e100),\n dict(abs=-1e100),\n dict(rel=1e100, abs=-1e100),\n dict(rel=-1e100, abs=1e100),\n dict(rel=-1e100, abs=-1e100),\n ]\n for kwargs in illegal_kwargs:\n with pytest.raises(ValueError):\n 1.1 == approx(1, **kwargs)"},{"col":4,"comment":"Injects a hidden autouse, function scoped fixture into the collected class object\n that invokes setup_method/teardown_method if either or both are available.\n\n Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with\n other fixtures (#517).\n ","endLoc":789,"header":"def _inject_setup_method_fixture(self)","id":1163,"name":"_inject_setup_method_fixture","nodeType":"Function","startLoc":766,"text":"def _inject_setup_method_fixture(self):\n \"\"\"Injects a hidden autouse, function scoped fixture into the collected class object\n that invokes setup_method/teardown_method if either or both are available.\n\n Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with\n other fixtures (#517).\n \"\"\"\n setup_method = _get_non_fixture_func(self.obj, \"setup_method\")\n teardown_method = getattr(self.obj, \"teardown_method\", None)\n if setup_method is None and teardown_method is None:\n return\n\n @fixtures.fixture(autouse=True, scope=\"function\")\n def xunit_setup_method_fixture(self, request):\n method = request.function\n if setup_method is not None:\n func = getattr(self, \"setup_method\")\n _call_with_optional_argument(func, method)\n yield\n if teardown_method is not None:\n func = getattr(self, \"teardown_method\")\n _call_with_optional_argument(func, method)\n\n self.obj.__pytest_setup_method = xunit_setup_method_fixture"},{"col":4,"comment":"null","endLoc":1086,"header":"def keys(self) -> dict_keys[_KT, _VT]","id":1164,"name":"keys","nodeType":"Function","startLoc":1086,"text":"def keys(self) -> dict_keys[_KT, _VT]: ..."},{"col":4,"comment":"null","endLoc":162,"header":"def to_xml(self)","id":1165,"name":"to_xml","nodeType":"Function","startLoc":157,"text":"def to_xml(self):\n testcase = Junit.testcase(time=\"%.3f\" % self.duration, **self.attrs)\n testcase.append(self.make_properties_node())\n for node in self.nodes:\n testcase.append(node)\n return testcase"},{"attributeType":"null","col":0,"comment":"null","endLoc":6,"id":1166,"name":"mydir","nodeType":"Attribute","startLoc":6,"text":"mydir"},{"col":0,"comment":"","endLoc":2,"header":"conftest.py#","id":1167,"name":"","nodeType":"Function","startLoc":2,"text":"mydir = py.path.local(__file__).dirpath()"},{"col":0,"comment":"null","endLoc":58,"header":"def test_code_source()","id":1168,"name":"test_code_source","nodeType":"Function","startLoc":53,"text":"def test_code_source():\n code = _pytest._code.Code(x)\n src = code.source()\n expected = \"\"\"def x():\n raise NotImplementedError()\"\"\"\n assert str(src) == expected"},{"col":4,"comment":"null","endLoc":167,"header":"def _add_simple(self, kind, message, data=None)","id":1169,"name":"_add_simple","nodeType":"Function","startLoc":164,"text":"def _add_simple(self, kind, message, data=None):\n data = bin_xml_escape(data)\n node = kind(data, message=message)\n self.append(node)"},{"col":4,"comment":"In py2 bytes and str are the same type, so return if it's a bytes\n object, return it unchanged if it is a full ascii string,\n otherwise escape it into its binary form.\n\n If it's a unicode string, change the unicode characters into\n unicode escapes.\n\n ","endLoc":263,"header":"def ascii_escaped(val)","id":1170,"name":"ascii_escaped","nodeType":"Function","startLoc":247,"text":"def ascii_escaped(val):\n \"\"\"In py2 bytes and str are the same type, so return if it's a bytes\n object, return it unchanged if it is a full ascii string,\n otherwise escape it into its binary form.\n\n If it's a unicode string, change the unicode characters into\n unicode escapes.\n\n \"\"\"\n if isinstance(val, bytes):\n try:\n ret = val.decode(\"ascii\")\n except UnicodeDecodeError:\n ret = val.encode(\"string-escape\").decode(\"ascii\")\n else:\n ret = val.encode(\"unicode-escape\").decode(\"ascii\")\n return _translate_non_printable(ret)"},{"col":4,"comment":" return a _pytest._code.Source object for the code object's source only\n ","endLoc":86,"header":"def source(self)","id":1171,"name":"source","nodeType":"Function","startLoc":80,"text":"def source(self):\n \"\"\" return a _pytest._code.Source object for the code object's source only\n \"\"\"\n # return source only for that part of code\n import _pytest._code\n\n return _pytest._code.Source(self.raw)"},{"col":4,"comment":"null","endLoc":220,"header":"def write_captured_output(self, report)","id":1172,"name":"write_captured_output","nodeType":"Function","startLoc":169,"text":"def write_captured_output(self, report):\n if not self.xml.log_passing_tests and report.passed:\n return\n\n content_out = report.capstdout\n content_log = report.caplog\n content_err = report.capstderr\n\n if content_log or content_out:\n if content_log and self.xml.logging == \"system-out\":\n if content_out:\n # syncing stdout and the log-output is not done yet. It's\n # probably not worth the effort. Therefore, first the captured\n # stdout is shown and then the captured logs.\n content = \"\\n\".join(\n [\n \" Captured Stdout \".center(80, \"-\"),\n content_out,\n \"\",\n \" Captured Log \".center(80, \"-\"),\n content_log,\n ]\n )\n else:\n content = content_log\n else:\n content = content_out\n\n if content:\n tag = getattr(Junit, \"system-out\")\n self.append(tag(bin_xml_escape(content)))\n\n if content_log or content_err:\n if content_log and self.xml.logging == \"system-err\":\n if content_err:\n content = \"\\n\".join(\n [\n \" Captured Stderr \".center(80, \"-\"),\n content_err,\n \"\",\n \" Captured Log \".center(80, \"-\"),\n content_log,\n ]\n )\n else:\n content = content_log\n else:\n content = content_err\n\n if content:\n tag = getattr(Junit, \"system-err\")\n self.append(tag(bin_xml_escape(content)))"},{"col":0,"comment":"null","endLoc":195,"header":"def _translate_non_printable(s)","id":1173,"name":"_translate_non_printable","nodeType":"Function","startLoc":194,"text":"def _translate_non_printable(s):\n return s.translate(_non_printable_ascii_translate_table)"},{"fileName":"create_executable.py","filePath":"testing/freeze","id":1174,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"\nGenerates an executable with pytest runner embedded using PyInstaller.\n\"\"\"\nif __name__ == \"__main__\":\n import pytest\n import subprocess\n\n hidden = []\n for x in pytest.freeze_includes():\n hidden.extend([\"--hidden-import\", x])\n hidden.extend([\"--hidden-import\", \"distutils\"])\n args = [\"pyinstaller\", \"--noconfirm\"] + hidden + [\"runtests_script.py\"]\n subprocess.check_call(\" \".join(args), shell=True)\n"},{"col":4,"comment":"If val is pure ascii, returns it as a str(). Otherwise, escapes\n bytes objects into a sequence of escaped bytes:\n\n b'ôÅÖ' -> u'\\xc3\\xb4\\xc5\\xd6'\n\n and escapes unicode objects into a sequence of escaped unicode\n ids, e.g.:\n\n '4\\nV\\U00043efa\\x0eMXWB\\x1e\\u3028\\u15fd\\xcd\\U0007d944'\n\n note:\n the obvious \"v.decode('unicode-escape')\" will return\n valid utf-8 unicode if it finds them in bytes, but we\n want to return escaped bytes for any byte, even if they match\n a utf-8 string.\n\n ","endLoc":240,"header":"def ascii_escaped(val)","id":1175,"name":"ascii_escaped","nodeType":"Function","startLoc":218,"text":"def ascii_escaped(val):\n \"\"\"If val is pure ascii, returns it as a str(). Otherwise, escapes\n bytes objects into a sequence of escaped bytes:\n\n b'\\xc3\\xb4\\xc5\\xd6' -> u'\\\\xc3\\\\xb4\\\\xc5\\\\xd6'\n\n and escapes unicode objects into a sequence of escaped unicode\n ids, e.g.:\n\n '4\\\\nV\\\\U00043efa\\\\x0eMXWB\\\\x1e\\\\u3028\\\\u15fd\\\\xcd\\\\U0007d944'\n\n note:\n the obvious \"v.decode('unicode-escape')\" will return\n valid utf-8 unicode if it finds them in bytes, but we\n want to return escaped bytes for any byte, even if they match\n a utf-8 string.\n\n \"\"\"\n if isinstance(val, bytes):\n ret = _bytes_to_ascii(val)\n else:\n ret = val.encode(\"unicode_escape\").decode(\"ascii\")\n return _translate_non_printable(ret)"},{"attributeType":"list","col":4,"comment":"null","endLoc":9,"id":1176,"name":"hidden","nodeType":"Attribute","startLoc":9,"text":"hidden"},{"col":8,"comment":"null","endLoc":205,"header":"def _bytes_to_ascii(val)","id":1177,"name":"_bytes_to_ascii","nodeType":"Function","startLoc":204,"text":"def _bytes_to_ascii(val):\n return val.decode(\"ascii\", \"backslashreplace\")"},{"col":8,"comment":"null","endLoc":216,"header":"def _bytes_to_ascii(val)","id":1178,"name":"_bytes_to_ascii","nodeType":"Function","startLoc":209,"text":"def _bytes_to_ascii(val):\n if val:\n # source: http://goo.gl/bGsnwC\n encoded_bytes, _ = codecs.escape_encode(val)\n return encoded_bytes.decode(\"ascii\")\n else:\n # empty bytes crashes codecs.escape_encode (#1087)\n return \"\""},{"col":0,"comment":"null","endLoc":68,"header":"def test_frame_getsourcelineno_myself()","id":1180,"name":"test_frame_getsourcelineno_myself","nodeType":"Function","startLoc":61,"text":"def test_frame_getsourcelineno_myself():\n def func():\n return sys._getframe(0)\n\n f = func()\n f = _pytest._code.Frame(f)\n source, lineno = f.code.fullsource, f.lineno\n assert source[lineno].startswith(\" return sys._getframe(0)\")"},{"attributeType":"null","col":8,"comment":"null","endLoc":10,"id":1182,"name":"x","nodeType":"Attribute","startLoc":10,"text":"x"},{"attributeType":"list","col":4,"comment":"null","endLoc":13,"id":1183,"name":"args","nodeType":"Attribute","startLoc":13,"text":"args"},{"col":4,"comment":"null","endLoc":112,"header":"def __init__(self, frame)","id":1184,"name":"__init__","nodeType":"Function","startLoc":107,"text":"def __init__(self, frame):\n self.lineno = frame.f_lineno - 1\n self.f_globals = frame.f_globals\n self.f_locals = frame.f_locals\n self.raw = frame\n self.code = Code(frame.f_code)"},{"col":0,"comment":"null","endLoc":375,"header":"def collect_one_node(collector)","id":1185,"name":"collect_one_node","nodeType":"Function","startLoc":368,"text":"def collect_one_node(collector):\n ihook = collector.ihook\n ihook.pytest_collectstart(collector=collector)\n rep = ihook.pytest_make_collect_report(collector=collector)\n call = rep.__dict__.pop(\"call\", None)\n if call and check_interactive_exception(call, rep):\n ihook.pytest_exception_interact(node=collector, call=call, report=rep)\n return rep"},{"className":"Function","col":0,"comment":" a Function Item is responsible for setting up and executing a\n Python test function.\n ","endLoc":1468,"id":1186,"nodeType":"Class","startLoc":1372,"text":"class Function(FunctionMixin, nodes.Item, fixtures.FuncargnamesCompatAttr):\n \"\"\" a Function Item is responsible for setting up and executing a\n Python test function.\n \"\"\"\n\n # disable since functions handle it themselves\n _ALLOW_MARKERS = False\n\n def __init__(\n self,\n name,\n parent,\n args=None,\n config=None,\n callspec=None,\n callobj=NOTSET,\n keywords=None,\n session=None,\n fixtureinfo=None,\n originalname=None,\n ):\n super(Function, self).__init__(name, parent, config=config, session=session)\n self._args = args\n if callobj is not NOTSET:\n self.obj = callobj\n\n self.keywords.update(self.obj.__dict__)\n self.own_markers.extend(get_unpacked_marks(self.obj))\n if callspec:\n self.callspec = callspec\n # this is total hostile and a mess\n # keywords are broken by design by now\n # this will be redeemed later\n for mark in callspec.marks:\n # feel free to cry, this was broken for years before\n # and keywords cant fix it per design\n self.keywords[mark.name] = mark\n self.own_markers.extend(normalize_mark_list(callspec.marks))\n if keywords:\n self.keywords.update(keywords)\n\n # todo: this is a hell of a hack\n # https://github.com/pytest-dev/pytest/issues/4569\n\n self.keywords.update(\n dict.fromkeys(\n [\n mark.name\n for mark in self.iter_markers()\n if mark.name not in self.keywords\n ],\n True,\n )\n )\n\n if fixtureinfo is None:\n fixtureinfo = self.session._fixturemanager.getfixtureinfo(\n self, self.obj, self.cls, funcargs=True\n )\n self._fixtureinfo = fixtureinfo\n self.fixturenames = fixtureinfo.names_closure\n self._initrequest()\n\n #: original function name, without any decorations (for example\n #: parametrization adds a ``\"[...]\"`` suffix to function names).\n #:\n #: .. versionadded:: 3.0\n self.originalname = originalname\n\n def _initrequest(self):\n self.funcargs = {}\n self._request = fixtures.FixtureRequest(self)\n\n @property\n def function(self):\n \"underlying python 'function' object\"\n return getimfunc(self.obj)\n\n def _getobj(self):\n name = self.name\n i = name.find(\"[\") # parametrization\n if i != -1:\n name = name[:i]\n return getattr(self.parent.obj, name)\n\n @property\n def _pyfuncitem(self):\n \"(compatonly) for code expecting pytest-2.2 style request objects\"\n return self\n\n def runtest(self):\n \"\"\" execute the underlying test function. \"\"\"\n self.ihook.pytest_pyfunc_call(pyfuncitem=self)\n\n def setup(self):\n super(Function, self).setup()\n fixtures.fillfixtures(self)"},{"col":0,"comment":"null","endLoc":78,"header":"def test_getstatement_empty_fullsource()","id":1187,"name":"test_getstatement_empty_fullsource","nodeType":"Function","startLoc":71,"text":"def test_getstatement_empty_fullsource():\n def func():\n return sys._getframe(0)\n\n f = func()\n f = _pytest._code.Frame(f)\n with mock.patch.object(f.code.__class__, \"fullsource\", None):\n assert f.statement == \"\""},{"col":0,"comment":"null","endLoc":188,"header":"def check_interactive_exception(call, report)","id":1189,"name":"check_interactive_exception","nodeType":"Function","startLoc":183,"text":"def check_interactive_exception(call, report):\n return call.excinfo and not (\n hasattr(report, \"wasxfail\")\n or call.excinfo.errisinstance(Skipped)\n or call.excinfo.errisinstance(bdb.BdbQuit)\n )"},{"className":"FunctionMixin","col":0,"comment":" mixin for the code common to Function and Generator.\n ","endLoc":846,"id":1190,"nodeType":"Class","startLoc":810,"text":"class FunctionMixin(PyobjMixin):\n \"\"\" mixin for the code common to Function and Generator.\n \"\"\"\n\n def setup(self):\n \"\"\" perform setup for this test function. \"\"\"\n if isinstance(self.parent, Instance):\n self.parent.newinstance()\n self.obj = self._getobj()\n\n def _prunetraceback(self, excinfo):\n if hasattr(self, \"_obj\") and not self.config.getoption(\"fulltrace\", False):\n code = _pytest._code.Code(get_real_func(self.obj))\n path, firstlineno = code.path, code.firstlineno\n traceback = excinfo.traceback\n ntraceback = traceback.cut(path=path, firstlineno=firstlineno)\n if ntraceback == traceback:\n ntraceback = ntraceback.cut(path=path)\n if ntraceback == traceback:\n ntraceback = ntraceback.filter(filter_traceback)\n if not ntraceback:\n ntraceback = traceback\n\n excinfo.traceback = ntraceback.filter()\n # issue364: mark all but first and last frames to\n # only show a single-line message for each frame\n if self.config.getoption(\"tbstyle\", \"auto\") == \"auto\":\n if len(excinfo.traceback) > 2:\n for entry in excinfo.traceback[1:-1]:\n entry.set_repr_style(\"short\")\n\n def repr_failure(self, excinfo, outerr=None):\n assert outerr is None, \"XXX outerr usage is deprecated\"\n style = self.config.getoption(\"tbstyle\", \"auto\")\n if style == \"auto\":\n style = \"long\"\n return self._repr_failure_py(excinfo, style=style)"},{"col":4,"comment":" perform setup for this test function. ","endLoc":818,"header":"def setup(self)","id":1191,"name":"setup","nodeType":"Function","startLoc":814,"text":"def setup(self):\n \"\"\" perform setup for this test function. \"\"\"\n if isinstance(self.parent, Instance):\n self.parent.newinstance()\n self.obj = self._getobj()"},{"col":0,"comment":"null","endLoc":61,"header":"def get_empty_parameterset_mark(config, argnames, func)","id":1192,"name":"get_empty_parameterset_mark","nodeType":"Function","startLoc":38,"text":"def get_empty_parameterset_mark(config, argnames, func):\n from ..nodes import Collector\n\n requested_mark = config.getini(EMPTY_PARAMETERSET_OPTION)\n if requested_mark in (\"\", None, \"skip\"):\n mark = MARK_GEN.skip\n elif requested_mark == \"xfail\":\n mark = MARK_GEN.xfail(run=False)\n elif requested_mark == \"fail_at_collect\":\n f_name = func.__name__\n _, lineno = getfslineno(func)\n raise Collector.CollectError(\n \"Empty parameter set in '%s' at line %d\" % (f_name, lineno + 1)\n )\n else:\n raise LookupError(requested_mark)\n fs, lineno = getfslineno(func)\n reason = \"got empty parameter set %r, function %s at %s:%d\" % (\n argnames,\n func.__name__,\n fs,\n lineno,\n )\n return mark(reason=reason)"},{"col":4,"comment":"null","endLoc":839,"header":"def _prunetraceback(self, excinfo)","id":1195,"name":"_prunetraceback","nodeType":"Function","startLoc":820,"text":"def _prunetraceback(self, excinfo):\n if hasattr(self, \"_obj\") and not self.config.getoption(\"fulltrace\", False):\n code = _pytest._code.Code(get_real_func(self.obj))\n path, firstlineno = code.path, code.firstlineno\n traceback = excinfo.traceback\n ntraceback = traceback.cut(path=path, firstlineno=firstlineno)\n if ntraceback == traceback:\n ntraceback = ntraceback.cut(path=path)\n if ntraceback == traceback:\n ntraceback = ntraceback.filter(filter_traceback)\n if not ntraceback:\n ntraceback = traceback\n\n excinfo.traceback = ntraceback.filter()\n # issue364: mark all but first and last frames to\n # only show a single-line message for each frame\n if self.config.getoption(\"tbstyle\", \"auto\") == \"auto\":\n if len(excinfo.traceback) > 2:\n for entry in excinfo.traceback[1:-1]:\n entry.set_repr_style(\"short\")"},{"col":0,"comment":"Find the most appropriate scope for a parametrized call based on its arguments.\n\n When there's at least one direct argument, always use \"function\" scope.\n\n When a test function is parametrized and all its arguments are indirect\n (e.g. fixtures), return the most narrow scope based on the fixtures used.\n\n Related to issue #1832, based on code posted by @Kingdread.\n ","endLoc":1161,"header":"def _find_parametrized_scope(argnames, arg2fixturedefs, indirect)","id":1196,"name":"_find_parametrized_scope","nodeType":"Function","startLoc":1131,"text":"def _find_parametrized_scope(argnames, arg2fixturedefs, indirect):\n \"\"\"Find the most appropriate scope for a parametrized call based on its arguments.\n\n When there's at least one direct argument, always use \"function\" scope.\n\n When a test function is parametrized and all its arguments are indirect\n (e.g. fixtures), return the most narrow scope based on the fixtures used.\n\n Related to issue #1832, based on code posted by @Kingdread.\n \"\"\"\n from _pytest.fixtures import scopes\n\n if isinstance(indirect, (list, tuple)):\n all_arguments_are_fixtures = len(indirect) == len(argnames)\n else:\n all_arguments_are_fixtures = bool(indirect)\n\n if all_arguments_are_fixtures:\n fixturedefs = arg2fixturedefs or {}\n used_scopes = [\n fixturedef[0].scope\n for name, fixturedef in fixturedefs.items()\n if name in argnames\n ]\n if used_scopes:\n # Takes the most narrow scope from used fixtures\n for scope in reversed(scopes):\n if scope in used_scopes:\n return scope\n\n return \"function\""},{"col":4,"comment":"null","endLoc":780,"header":"def genitems(self, node)","id":1197,"name":"genitems","nodeType":"Function","startLoc":768,"text":"def genitems(self, node):\n self.trace(\"genitems\", node)\n if isinstance(node, nodes.Item):\n node.ihook.pytest_itemcollected(item=node)\n yield node\n else:\n assert isinstance(node, nodes.Collector)\n rep = collect_one_node(node)\n if rep.passed:\n for subnode in rep.result:\n for x in self.genitems(subnode):\n yield x\n node.ihook.pytest_collectreport(report=rep)"},{"col":4,"comment":"null","endLoc":846,"header":"def repr_failure(self, excinfo, outerr=None)","id":1199,"name":"repr_failure","nodeType":"Function","startLoc":841,"text":"def repr_failure(self, excinfo, outerr=None):\n assert outerr is None, \"XXX outerr usage is deprecated\"\n style = self.config.getoption(\"tbstyle\", \"auto\")\n if style == \"auto\":\n style = \"long\"\n return self._repr_failure_py(excinfo, style=style)"},{"attributeType":"null","col":12,"comment":"null","endLoc":818,"id":1201,"name":"obj","nodeType":"Attribute","startLoc":818,"text":"self.obj"},{"className":"FuncargnamesCompatAttr","col":0,"comment":" helper class so that Metafunc, Function and FixtureRequest\n don't need to each define the \"funcargnames\" compatibility attribute.\n ","endLoc":444,"id":1202,"nodeType":"Class","startLoc":436,"text":"class FuncargnamesCompatAttr(object):\n \"\"\" helper class so that Metafunc, Function and FixtureRequest\n don't need to each define the \"funcargnames\" compatibility attribute.\n \"\"\"\n\n @property\n def funcargnames(self):\n \"\"\" alias attribute for ``fixturenames`` for pre-2.3 compatibility\"\"\"\n return self.fixturenames"},{"col":4,"comment":" alias attribute for ``fixturenames`` for pre-2.3 compatibility","endLoc":444,"header":"@property\n def funcargnames(self)","id":1203,"name":"funcargnames","nodeType":"Function","startLoc":441,"text":"@property\n def funcargnames(self):\n \"\"\" alias attribute for ``fixturenames`` for pre-2.3 compatibility\"\"\"\n return self.fixturenames"},{"col":4,"comment":"underlying python 'function' object","endLoc":1448,"header":"@property\n def function(self)","id":1204,"name":"function","nodeType":"Function","startLoc":1445,"text":"@property\n def function(self):\n \"underlying python 'function' object\"\n return getimfunc(self.obj)"},{"col":4,"comment":"null","endLoc":1455,"header":"def _getobj(self)","id":1205,"name":"_getobj","nodeType":"Function","startLoc":1450,"text":"def _getobj(self):\n name = self.name\n i = name.find(\"[\") # parametrization\n if i != -1:\n name = name[:i]\n return getattr(self.parent.obj, name)"},{"col":0,"comment":"null","endLoc":84,"header":"def test_code_from_func()","id":1207,"name":"test_code_from_func","nodeType":"Function","startLoc":81,"text":"def test_code_from_func():\n co = _pytest._code.Code(test_frame_getsourcelineno_myself)\n assert co.firstlineno\n assert co.path"},{"col":0,"comment":"null","endLoc":96,"header":"def test_unicode_handling()","id":1208,"name":"test_unicode_handling","nodeType":"Function","startLoc":87,"text":"def test_unicode_handling():\n value = u\"ąć\".encode(\"UTF-8\")\n\n def f():\n raise Exception(value)\n\n excinfo = pytest.raises(Exception, f)\n text_type(excinfo)\n if sys.version_info < (3,):\n bytes(excinfo)"},{"col":4,"comment":"null","endLoc":550,"header":"def collect(self)","id":1209,"name":"collect","nodeType":"Function","startLoc":537,"text":"def collect(self):\n for initialpart in self._initialparts:\n arg = \"::\".join(map(str, initialpart))\n self.trace(\"processing argument\", arg)\n self.trace.root.indent += 1\n try:\n for x in self._collect(arg):\n yield x\n except NoMatch:\n # we are inside a make_report hook so\n # we cannot directly pass through the exception\n self._notfound.append((arg, sys.exc_info()[1]))\n\n self.trace.root.indent -= 1"},{"col":0,"comment":"","endLoc":4,"header":"create_executable.py#","id":1210,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"\nGenerates an executable with pytest runner embedded using PyInstaller.\n\"\"\"\n\nif __name__ == \"__main__\":\n import pytest\n import subprocess\n\n hidden = []\n for x in pytest.freeze_includes():\n hidden.extend([\"--hidden-import\", x])\n hidden.extend([\"--hidden-import\", \"distutils\"])\n args = [\"pyinstaller\", \"--noconfirm\"] + hidden + [\"runtests_script.py\"]\n subprocess.check_call(\" \".join(args), shell=True)"},{"col":4,"comment":"(compatonly) for code expecting pytest-2.2 style request objects","endLoc":1460,"header":"@property\n def _pyfuncitem(self)","id":1211,"name":"_pyfuncitem","nodeType":"Function","startLoc":1457,"text":"@property\n def _pyfuncitem(self):\n \"(compatonly) for code expecting pytest-2.2 style request objects\"\n return self"},{"col":4,"comment":" execute the underlying test function. ","endLoc":1464,"header":"def runtest(self)","id":1212,"name":"runtest","nodeType":"Function","startLoc":1462,"text":"def runtest(self):\n \"\"\" execute the underlying test function. \"\"\"\n self.ihook.pytest_pyfunc_call(pyfuncitem=self)"},{"col":4,"comment":"null","endLoc":1468,"header":"def setup(self)","id":1213,"name":"setup","nodeType":"Function","startLoc":1466,"text":"def setup(self):\n super(Function, self).setup()\n fixtures.fillfixtures(self)"},{"attributeType":"null","col":4,"comment":"null","endLoc":1378,"id":1214,"name":"_ALLOW_MARKERS","nodeType":"Attribute","startLoc":1378,"text":"_ALLOW_MARKERS"},{"attributeType":"null","col":8,"comment":"null","endLoc":1431,"id":1215,"name":"_fixtureinfo","nodeType":"Attribute","startLoc":1431,"text":"self._fixtureinfo"},{"attributeType":"null","col":8,"comment":"null","endLoc":1394,"id":1217,"name":"_args","nodeType":"Attribute","startLoc":1394,"text":"self._args"},{"col":4,"comment":"\n Check if all argnames are being used, by default values, or directly/indirectly.\n\n :param List[str] argnames: list of argument names passed to ``parametrize()``.\n :param indirect: same ``indirect`` parameter of ``parametrize()``.\n :raise ValueError: if validation fails.\n ","endLoc":1128,"header":"def _validate_if_using_arg_names(self, argnames, indirect)","id":1218,"name":"_validate_if_using_arg_names","nodeType":"Function","startLoc":1101,"text":"def _validate_if_using_arg_names(self, argnames, indirect):\n \"\"\"\n Check if all argnames are being used, by default values, or directly/indirectly.\n\n :param List[str] argnames: list of argument names passed to ``parametrize()``.\n :param indirect: same ``indirect`` parameter of ``parametrize()``.\n :raise ValueError: if validation fails.\n \"\"\"\n default_arg_names = set(get_default_arg_names(self.function))\n func_name = self.function.__name__\n for arg in argnames:\n if arg not in self.fixturenames:\n if arg in default_arg_names:\n fail(\n \"In {}: function already takes an argument '{}' with a default value\".format(\n func_name, arg\n ),\n pytrace=False,\n )\n else:\n if isinstance(indirect, (tuple, list)):\n name = \"fixture\" if arg in indirect else \"argument\"\n else:\n name = \"fixture\" if indirect else \"argument\"\n fail(\n \"In {}: function uses no {} '{}'\".format(func_name, name, arg),\n pytrace=False,\n )"},{"id":1219,"name":"existingtestsuite.rst","nodeType":"TextFile","path":"doc/en","text":".. _existingtestsuite:\n\nUsing pytest with an existing test suite\n===========================================\n\nPytest can be used with most existing test suites, but its\nbehavior differs from other test runners such as :ref:`nose ` or\nPython's default unittest framework.\n\nBefore using this section you will want to :ref:`install pytest `.\n\nRunning an existing test suite with pytest\n---------------------------------------------\n\nSay you want to contribute to an existing repository somewhere.\nAfter pulling the code into your development space using some\nflavor of version control and (optionally) setting up a virtualenv\nyou will want to run::\n\n cd \n pip install -e . # Environment dependent alternatives include\n # 'python setup.py develop' and 'conda develop'\n\nin your project root. This will set up a symlink to your code in\nsite-packages, allowing you to edit your code while your tests\nrun against it as if it were installed.\n\nSetting up your project in development mode lets you avoid having to\nreinstall every time you want to run your tests, and is less brittle than\nmucking about with sys.path to point your tests at local code.\n\nAlso consider using :ref:`tox `.\n\n.. include:: links.inc\n"},{"id":1220,"name":"reference.rst","nodeType":"TextFile","path":"doc/en","text":"Reference\n=========\n\nThis page contains the full reference to pytest's API.\n\n.. contents::\n :depth: 3\n :local:\n\nFunctions\n---------\n\npytest.approx\n~~~~~~~~~~~~~\n\n.. autofunction:: _pytest.python_api.approx\n\npytest.fail\n~~~~~~~~~~~\n\n**Tutorial**: :ref:`skipping`\n\n.. autofunction:: _pytest.outcomes.fail\n\npytest.skip\n~~~~~~~~~~~\n\n.. autofunction:: _pytest.outcomes.skip(msg, [allow_module_level=False])\n\npytest.importorskip\n~~~~~~~~~~~~~~~~~~~\n\n.. autofunction:: _pytest.outcomes.importorskip\n\npytest.xfail\n~~~~~~~~~~~~\n\n.. autofunction:: _pytest.outcomes.xfail\n\npytest.exit\n~~~~~~~~~~~\n\n.. autofunction:: _pytest.outcomes.exit\n\npytest.main\n~~~~~~~~~~~\n\n.. autofunction:: _pytest.config.main\n\npytest.param\n~~~~~~~~~~~~\n\n.. autofunction:: pytest.param(*values, [id], [marks])\n\npytest.raises\n~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`assertraises`.\n\n.. autofunction:: pytest.raises(expected_exception: Exception, [match], [message])\n :with: excinfo\n\npytest.deprecated_call\n~~~~~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`ensuring_function_triggers`.\n\n.. autofunction:: pytest.deprecated_call()\n :with:\n\npytest.register_assert_rewrite\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`assertion-rewriting`.\n\n.. autofunction:: pytest.register_assert_rewrite\n\npytest.warns\n~~~~~~~~~~~~\n\n**Tutorial**: :ref:`assertwarnings`\n\n.. autofunction:: pytest.warns(expected_warning: Exception, [match])\n :with:\n\npytest.freeze_includes\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`freezing-pytest`.\n\n.. autofunction:: pytest.freeze_includes\n\n.. _`marks ref`:\n\nMarks\n-----\n\nMarks can be used apply meta data to *test functions* (but not fixtures), which can then be accessed by\nfixtures or plugins.\n\n\n\n\n.. _`pytest.mark.filterwarnings ref`:\n\npytest.mark.filterwarnings\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`filterwarnings`.\n\nAdd warning filters to marked test items.\n\n.. py:function:: pytest.mark.filterwarnings(filter)\n\n :keyword str filter:\n A *warning specification string*, which is composed of contents of the tuple ``(action, message, category, module, lineno)``\n as specified in `The Warnings filter `_ section of\n the Python documentation, separated by ``\":\"``. Optional fields can be omitted.\n Module names passed for filtering are not regex-escaped.\n\n For example:\n\n .. code-block:: python\n\n @pytest.mark.warnings(\"ignore:.*usage will be deprecated.*:DeprecationWarning\")\n def test_foo():\n ...\n\n\n.. _`pytest.mark.parametrize ref`:\n\npytest.mark.parametrize\n~~~~~~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :doc:`parametrize`.\n\n.. automethod:: _pytest.python.Metafunc.parametrize\n\n\n.. _`pytest.mark.skip ref`:\n\npytest.mark.skip\n~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`skip`.\n\nUnconditionally skip a test function.\n\n.. py:function:: pytest.mark.skip(*, reason=None)\n\n :keyword str reason: Reason why the test function is being skipped.\n\n\n.. _`pytest.mark.skipif ref`:\n\npytest.mark.skipif\n~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`skipif`.\n\nSkip a test function if a condition is ``True``.\n\n.. py:function:: pytest.mark.skipif(condition, *, reason=None)\n\n :type condition: bool or str\n :param condition: ``True/False`` if the condition should be skipped or a :ref:`condition string `.\n :keyword str reason: Reason why the test function is being skipped.\n\n\n.. _`pytest.mark.usefixtures ref`:\n\npytest.mark.usefixtures\n~~~~~~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`usefixtures`.\n\nMark a test function as using the given fixture names.\n\n.. warning::\n\n This mark has no effect when applied\n to a **fixture** function.\n\n.. py:function:: pytest.mark.usefixtures(*names)\n\n :param args: the names of the fixture to use, as strings\n\n\n.. _`pytest.mark.xfail ref`:\n\npytest.mark.xfail\n~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`xfail`.\n\nMarks a test function as *expected to fail*.\n\n.. py:function:: pytest.mark.xfail(condition=None, *, reason=None, raises=None, run=True, strict=False)\n\n :type condition: bool or str\n :param condition:\n Condition for marking the test function as xfail (``True/False`` or a\n :ref:`condition string `).\n :keyword str reason: Reason why the test function is marked as xfail.\n :keyword Exception raises: Exception subclass expected to be raised by the test function; other exceptions will fail the test.\n :keyword bool run:\n If the test function should actually be executed. If ``False``, the function will always xfail and will\n not be executed (useful if a function is segfaulting).\n :keyword bool strict:\n * If ``False`` (the default) the function will be shown in the terminal output as ``xfailed`` if it fails\n and as ``xpass`` if it passes. In both cases this will not cause the test suite to fail as a whole. This\n is particularly useful to mark *flaky* tests (tests that fail at random) to be tackled later.\n * If ``True``, the function will be shown in the terminal output as ``xfailed`` if it fails, but if it\n unexpectedly passes then it will **fail** the test suite. This is particularly useful to mark functions\n that are always failing and there should be a clear indication if they unexpectedly start to pass (for example\n a new release of a library fixes a known bug).\n\n\ncustom marks\n~~~~~~~~~~~~\n\nMarks are created dynamically using the factory object ``pytest.mark`` and applied as a decorator.\n\nFor example:\n\n.. code-block:: python\n\n @pytest.mark.timeout(10, \"slow\", method=\"thread\")\n def test_function():\n ...\n\nWill create and attach a :class:`Mark <_pytest.mark.structures.Mark>` object to the collected\n:class:`Item <_pytest.nodes.Item>`, which can then be accessed by fixtures or hooks with\n:meth:`Node.iter_markers <_pytest.nodes.Node.iter_markers>`. The ``mark`` object will have the following attributes:\n\n.. code-block:: python\n\n mark.args == (10, \"slow\")\n mark.kwargs == {\"method\": \"thread\"}\n\n\nFixtures\n--------\n\n**Tutorial**: :ref:`fixture`.\n\nFixtures are requested by test functions or other fixtures by declaring them as argument names.\n\n\nExample of a test requiring a fixture:\n\n.. code-block:: python\n\n def test_output(capsys):\n print(\"hello\")\n out, err = capsys.readouterr()\n assert out == \"hello\\n\"\n\n\nExample of a fixture requiring another fixture:\n\n.. code-block:: python\n\n @pytest.fixture\n def db_session(tmpdir):\n fn = tmpdir / \"db.file\"\n return connect(str(fn))\n\nFor more details, consult the full :ref:`fixtures docs `.\n\n\n@pytest.fixture\n~~~~~~~~~~~~~~~\n\n.. autofunction:: pytest.fixture\n :decorator:\n\n\n.. _`cache-api`:\n\nconfig.cache\n~~~~~~~~~~~~\n\n**Tutorial**: :ref:`cache`.\n\nThe ``config.cache`` object allows other plugins and fixtures\nto store and retrieve values across test runs. To access it from fixtures\nrequest ``pytestconfig`` into your fixture and get it with ``pytestconfig.cache``.\n\nUnder the hood, the cache plugin uses the simple\n``dumps``/``loads`` API of the :py:mod:`json` stdlib module.\n\n.. currentmodule:: _pytest.cacheprovider\n\n.. automethod:: Cache.get\n.. automethod:: Cache.set\n.. automethod:: Cache.makedir\n\n\ncapsys\n~~~~~~\n\n**Tutorial**: :doc:`capture`.\n\n.. currentmodule:: _pytest.capture\n\n.. autofunction:: capsys()\n :no-auto-options:\n\n Returns an instance of :py:class:`CaptureFixture`.\n\n Example:\n\n .. code-block:: python\n\n def test_output(capsys):\n print(\"hello\")\n captured = capsys.readouterr()\n assert captured.out == \"hello\\n\"\n\n.. autoclass:: CaptureFixture()\n :members:\n\n\ncapsysbinary\n~~~~~~~~~~~~\n\n**Tutorial**: :doc:`capture`.\n\n.. autofunction:: capsysbinary()\n :no-auto-options:\n\n Returns an instance of :py:class:`CaptureFixture`.\n\n Example:\n\n .. code-block:: python\n\n def test_output(capsysbinary):\n print(\"hello\")\n captured = capsysbinary.readouterr()\n assert captured.out == b\"hello\\n\"\n\n\ncapfd\n~~~~~~\n\n**Tutorial**: :doc:`capture`.\n\n.. autofunction:: capfd()\n :no-auto-options:\n\n Returns an instance of :py:class:`CaptureFixture`.\n\n Example:\n\n .. code-block:: python\n\n def test_system_echo(capfd):\n os.system('echo \"hello\"')\n captured = capsys.readouterr()\n assert captured.out == \"hello\\n\"\n\n\ncapfdbinary\n~~~~~~~~~~~~\n\n**Tutorial**: :doc:`capture`.\n\n.. autofunction:: capfdbinary()\n :no-auto-options:\n\n Returns an instance of :py:class:`CaptureFixture`.\n\n Example:\n\n .. code-block:: python\n\n def test_system_echo(capfdbinary):\n os.system('echo \"hello\"')\n captured = capfdbinary.readouterr()\n assert captured.out == b\"hello\\n\"\n\n\ndoctest_namespace\n~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :doc:`doctest`.\n\n.. autofunction:: _pytest.doctest.doctest_namespace()\n\n Usually this fixture is used in conjunction with another ``autouse`` fixture:\n\n .. code-block:: python\n\n @pytest.fixture(autouse=True)\n def add_np(doctest_namespace):\n doctest_namespace[\"np\"] = numpy\n\n For more details: :ref:`doctest_namespace`.\n\n\nrequest\n~~~~~~~\n\n**Tutorial**: :ref:`request example`.\n\nThe ``request`` fixture is a special fixture providing information of the requesting test function.\n\n.. autoclass:: _pytest.fixtures.FixtureRequest()\n :members:\n\n\npytestconfig\n~~~~~~~~~~~~\n\n.. autofunction:: _pytest.fixtures.pytestconfig()\n\n\nrecord_property\n~~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`record_property example`.\n\n.. autofunction:: _pytest.junitxml.record_property()\n\n\nrecord_testsuite_property\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`record_testsuite_property example`.\n\n.. autofunction:: _pytest.junitxml.record_testsuite_property()\n\ncaplog\n~~~~~~\n\n**Tutorial**: :doc:`logging`.\n\n.. autofunction:: _pytest.logging.caplog()\n :no-auto-options:\n\n This returns a :class:`_pytest.logging.LogCaptureFixture` instance.\n\n.. autoclass:: _pytest.logging.LogCaptureFixture\n :members:\n\n\nmonkeypatch\n~~~~~~~~~~~\n\n.. currentmodule:: _pytest.monkeypatch\n\n**Tutorial**: :doc:`monkeypatch`.\n\n.. autofunction:: _pytest.monkeypatch.monkeypatch()\n :no-auto-options:\n\n This returns a :class:`MonkeyPatch` instance.\n\n.. autoclass:: _pytest.monkeypatch.MonkeyPatch\n :members:\n\ntestdir\n~~~~~~~\n\n.. currentmodule:: _pytest.pytester\n\nThis fixture provides a :class:`Testdir` instance useful for black-box testing of test files, making it ideal to\ntest plugins.\n\nTo use it, include in your top-most ``conftest.py`` file::\n\n pytest_plugins = 'pytester'\n\n\n\n.. autoclass:: Testdir()\n :members:\n\n.. autoclass:: RunResult()\n :members:\n\n.. autoclass:: LineMatcher()\n :members:\n\n\nrecwarn\n~~~~~~~\n\n**Tutorial**: :ref:`assertwarnings`\n\n.. currentmodule:: _pytest.recwarn\n\n.. autofunction:: recwarn()\n :no-auto-options:\n\n.. autoclass:: _pytest.recwarn.WarningsRecorder()\n :members:\n\nEach recorded warning is an instance of :class:`warnings.WarningMessage`.\n\n.. note::\n :class:`RecordedWarning` was changed from a plain class to a namedtuple in pytest 3.1\n\n.. note::\n ``DeprecationWarning`` and ``PendingDeprecationWarning`` are treated\n differently; see :ref:`ensuring_function_triggers`.\n\n\ntmp_path\n~~~~~~~~\n\n**Tutorial**: :doc:`tmpdir`\n\n.. currentmodule:: _pytest.tmpdir\n\n.. autofunction:: tmp_path()\n :no-auto-options:\n\n\ntmp_path_factory\n~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`tmp_path_factory example`\n\n.. _`tmp_path_factory factory api`:\n\n``tmp_path_factory`` instances have the following methods:\n\n.. currentmodule:: _pytest.tmpdir\n\n.. automethod:: TempPathFactory.mktemp\n.. automethod:: TempPathFactory.getbasetemp\n\n\ntmpdir\n~~~~~~\n\n**Tutorial**: :doc:`tmpdir`\n\n.. currentmodule:: _pytest.tmpdir\n\n.. autofunction:: tmpdir()\n :no-auto-options:\n\n\ntmpdir_factory\n~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`tmpdir factory example`\n\n.. _`tmpdir factory api`:\n\n``tmpdir_factory`` instances have the following methods:\n\n.. currentmodule:: _pytest.tmpdir\n\n.. automethod:: TempdirFactory.mktemp\n.. automethod:: TempdirFactory.getbasetemp\n\n\n.. _`hook-reference`:\n\nHooks\n-----\n\n**Tutorial**: :doc:`writing_plugins`.\n\n.. currentmodule:: _pytest.hookspec\n\nReference to all hooks which can be implemented by :ref:`conftest.py files ` and :ref:`plugins `.\n\nBootstrapping hooks\n~~~~~~~~~~~~~~~~~~~\n\nBootstrapping hooks called for plugins registered early enough (internal and setuptools plugins).\n\n.. autofunction:: pytest_load_initial_conftests\n.. autofunction:: pytest_cmdline_preparse\n.. autofunction:: pytest_cmdline_parse\n.. autofunction:: pytest_cmdline_main\n\n.. _`initialization-hooks`:\n\nInitialization hooks\n~~~~~~~~~~~~~~~~~~~~\n\nInitialization hooks called for plugins and ``conftest.py`` files.\n\n.. autofunction:: pytest_addoption\n.. autofunction:: pytest_addhooks\n.. autofunction:: pytest_configure\n.. autofunction:: pytest_unconfigure\n.. autofunction:: pytest_sessionstart\n.. autofunction:: pytest_sessionfinish\n\n.. autofunction:: pytest_plugin_registered\n\nTest running hooks\n~~~~~~~~~~~~~~~~~~\n\nAll runtest related hooks receive a :py:class:`pytest.Item <_pytest.main.Item>` object.\n\n.. autofunction:: pytest_runtestloop\n.. autofunction:: pytest_runtest_protocol\n.. autofunction:: pytest_runtest_logstart\n.. autofunction:: pytest_runtest_logfinish\n.. autofunction:: pytest_runtest_setup\n.. autofunction:: pytest_runtest_call\n.. autofunction:: pytest_runtest_teardown\n.. autofunction:: pytest_runtest_makereport\n\nFor deeper understanding you may look at the default implementation of\nthese hooks in :py:mod:`_pytest.runner` and maybe also\nin :py:mod:`_pytest.pdb` which interacts with :py:mod:`_pytest.capture`\nand its input/output capturing in order to immediately drop\ninto interactive debugging when a test failure occurs.\n\nThe :py:mod:`_pytest.terminal` reported specifically uses\nthe reporting hook to print information about a test run.\n\n.. autofunction:: pytest_pyfunc_call\n\nCollection hooks\n~~~~~~~~~~~~~~~~\n\n``pytest`` calls the following hooks for collecting files and directories:\n\n.. autofunction:: pytest_collection\n.. autofunction:: pytest_ignore_collect\n.. autofunction:: pytest_collect_directory\n.. autofunction:: pytest_collect_file\n.. autofunction:: pytest_pycollect_makemodule\n\nFor influencing the collection of objects in Python modules\nyou can use the following hook:\n\n.. autofunction:: pytest_pycollect_makeitem\n.. autofunction:: pytest_generate_tests\n.. autofunction:: pytest_make_parametrize_id\n\nAfter collection is complete, you can modify the order of\nitems, delete or otherwise amend the test items:\n\n.. autofunction:: pytest_collection_modifyitems\n\n.. autofunction:: pytest_collection_finish\n\nReporting hooks\n~~~~~~~~~~~~~~~\n\nSession related reporting hooks:\n\n.. autofunction:: pytest_collectstart\n.. autofunction:: pytest_make_collect_report\n.. autofunction:: pytest_itemcollected\n.. autofunction:: pytest_collectreport\n.. autofunction:: pytest_deselected\n.. autofunction:: pytest_report_header\n.. autofunction:: pytest_report_collectionfinish\n.. autofunction:: pytest_report_teststatus\n.. autofunction:: pytest_terminal_summary\n.. autofunction:: pytest_fixture_setup\n.. autofunction:: pytest_fixture_post_finalizer\n.. autofunction:: pytest_warning_captured\n\nAnd here is the central hook for reporting about\ntest execution:\n\n.. autofunction:: pytest_runtest_logreport\n\nYou can also use this hook to customize assertion representation for some\ntypes:\n\n.. autofunction:: pytest_assertrepr_compare\n\n\nDebugging/Interaction hooks\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThere are few hooks which can be used for special\nreporting or interaction with exceptions:\n\n.. autofunction:: pytest_internalerror\n.. autofunction:: pytest_keyboard_interrupt\n.. autofunction:: pytest_exception_interact\n.. autofunction:: pytest_enter_pdb\n\n\nObjects\n-------\n\nFull reference to objects accessible from :ref:`fixtures ` or :ref:`hooks `.\n\n\nCallInfo\n~~~~~~~~\n\n.. autoclass:: _pytest.runner.CallInfo()\n :members:\n\n\nClass\n~~~~~\n\n.. autoclass:: _pytest.python.Class()\n :members:\n :show-inheritance:\n\nCollector\n~~~~~~~~~\n\n.. autoclass:: _pytest.nodes.Collector()\n :members:\n :show-inheritance:\n\nConfig\n~~~~~~\n\n.. autoclass:: _pytest.config.Config()\n :members:\n\nExceptionInfo\n~~~~~~~~~~~~~\n\n.. autoclass:: _pytest._code.ExceptionInfo\n :members:\n\nFixtureDef\n~~~~~~~~~~\n\n.. autoclass:: _pytest.fixtures.FixtureDef()\n :members:\n :show-inheritance:\n\nFSCollector\n~~~~~~~~~~~\n\n.. autoclass:: _pytest.nodes.FSCollector()\n :members:\n :show-inheritance:\n\nFunction\n~~~~~~~~\n\n.. autoclass:: _pytest.python.Function()\n :members:\n :show-inheritance:\n\nItem\n~~~~\n\n.. autoclass:: _pytest.nodes.Item()\n :members:\n :show-inheritance:\n\nMarkDecorator\n~~~~~~~~~~~~~\n\n.. autoclass:: _pytest.mark.MarkDecorator\n :members:\n\n\nMarkGenerator\n~~~~~~~~~~~~~\n\n.. autoclass:: _pytest.mark.MarkGenerator\n :members:\n\n\nMark\n~~~~\n\n.. autoclass:: _pytest.mark.structures.Mark\n :members:\n\n\nMetafunc\n~~~~~~~~\n\n.. autoclass:: _pytest.python.Metafunc\n :members:\n\nModule\n~~~~~~\n\n.. autoclass:: _pytest.python.Module()\n :members:\n :show-inheritance:\n\nNode\n~~~~\n\n.. autoclass:: _pytest.nodes.Node()\n :members:\n\nParser\n~~~~~~\n\n.. autoclass:: _pytest.config.argparsing.Parser()\n :members:\n\nPluginManager\n~~~~~~~~~~~~~\n\n.. autoclass:: pluggy.PluginManager()\n :members:\n\n\nPytestPluginManager\n~~~~~~~~~~~~~~~~~~~\n\n.. autoclass:: _pytest.config.PytestPluginManager()\n :members:\n :undoc-members:\n :show-inheritance:\n\nSession\n~~~~~~~\n\n.. autoclass:: _pytest.main.Session()\n :members:\n :show-inheritance:\n\nTestReport\n~~~~~~~~~~\n\n.. autoclass:: _pytest.runner.TestReport()\n :members:\n :inherited-members:\n\n_Result\n~~~~~~~\n\n.. autoclass:: pluggy.callers._Result\n :members:\n\nSpecial Variables\n-----------------\n\npytest treats some global variables in a special manner when defined in a test module.\n\n\ncollect_ignore\n~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`customizing-test-collection`\n\nCan be declared in *conftest.py files* to exclude test directories or modules.\nNeeds to be ``list[str]``.\n\n.. code-block:: python\n\n collect_ignore = [\"setup.py\"]\n\n\ncollect_ignore_glob\n~~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`customizing-test-collection`\n\nCan be declared in *conftest.py files* to exclude test directories or modules\nwith Unix shell-style wildcards. Needs to be ``list[str]`` where ``str`` can\ncontain glob patterns.\n\n.. code-block:: python\n\n collect_ignore_glob = [\"*_ignore.py\"]\n\n\npytest_plugins\n~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`available installable plugins`\n\nCan be declared at the **global** level in *test modules* and *conftest.py files* to register additional plugins.\nCan be either a ``str`` or ``Sequence[str]``.\n\n.. code-block:: python\n\n pytest_plugins = \"myapp.testsupport.myplugin\"\n\n.. code-block:: python\n\n pytest_plugins = (\"myapp.testsupport.tools\", \"myapp.testsupport.regression\")\n\n\npytest_mark\n~~~~~~~~~~~\n\n**Tutorial**: :ref:`scoped-marking`\n\nCan be declared at the **global** level in *test modules* to apply one or more :ref:`marks ` to all\ntest functions and methods. Can be either a single mark or a list of marks.\n\n.. code-block:: python\n\n import pytest\n\n pytestmark = pytest.mark.webtest\n\n\n.. code-block:: python\n\n import pytest\n\n pytestmark = [pytest.mark.integration, pytest.mark.slow]\n\nPYTEST_DONT_REWRITE (module docstring)\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe text ``PYTEST_DONT_REWRITE`` can be add to any **module docstring** to disable\n:ref:`assertion rewriting ` for that module.\n\n\nEnvironment Variables\n---------------------\n\nEnvironment variables that can be used to change pytest's behavior.\n\nPYTEST_ADDOPTS\n~~~~~~~~~~~~~~\n\nThis contains a command-line (parsed by the py:mod:`shlex` module) that will be **prepended** to the command line given\nby the user, see :ref:`adding default options` for more information.\n\nPYTEST_DEBUG\n~~~~~~~~~~~~\n\nWhen set, pytest will print tracing and debug information.\n\nPYTEST_PLUGINS\n~~~~~~~~~~~~~~\n\nContains comma-separated list of modules that should be loaded as plugins:\n\n.. code-block:: bash\n\n export PYTEST_PLUGINS=mymodule.plugin,xdist\n\nPYTEST_DISABLE_PLUGIN_AUTOLOAD\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWhen set, disables plugin auto-loading through setuptools entrypoints. Only explicitly specified plugins will be\nloaded.\n\nPYTEST_CURRENT_TEST\n~~~~~~~~~~~~~~~~~~~\n\nThis is not meant to be set by users, but is set by pytest internally with the name of the current test so other\nprocesses can inspect it, see :ref:`pytest current test env` for more information.\n\n\n.. _`ini options ref`:\n\nConfiguration Options\n---------------------\n\nHere is a list of builtin configuration options that may be written in a ``pytest.ini``, ``tox.ini`` or ``setup.cfg``\nfile, usually located at the root of your repository. All options must be under a ``[pytest]`` section\n(``[tool:pytest]`` for ``setup.cfg`` files).\n\n.. warning::\n Usage of ``setup.cfg`` is not recommended unless for very simple use cases. ``.cfg``\n files use a different parser than ``pytest.ini`` and ``tox.ini`` which might cause hard to track\n down problems.\n When possible, it is recommended to use the latter files to hold your pytest configuration.\n\nConfiguration file options may be overwritten in the command-line by using ``-o/--override``, which can also be\npassed multiple times. The expected format is ``name=value``. For example::\n\n pytest -o console_output_style=classic -o cache_dir=/tmp/mycache\n\n\n.. confval:: addopts\n\n Add the specified ``OPTS`` to the set of command line arguments as if they\n had been specified by the user. Example: if you have this ini file content:\n\n .. code-block:: ini\n\n # content of pytest.ini\n [pytest]\n addopts = --maxfail=2 -rf # exit after 2 failures, report fail info\n\n issuing ``pytest test_hello.py`` actually means::\n\n pytest --maxfail=2 -rf test_hello.py\n\n Default is to add no options.\n\n\n.. confval:: cache_dir\n\n\n\n Sets a directory where stores content of cache plugin. Default directory is\n ``.pytest_cache`` which is created in :ref:`rootdir `. Directory may be\n relative or absolute path. If setting relative path, then directory is created\n relative to :ref:`rootdir `. Additionally path may contain environment\n variables, that will be expanded. For more information about cache plugin\n please refer to :ref:`cache_provider`.\n\n\n.. confval:: confcutdir\n\n Sets a directory where search upwards for ``conftest.py`` files stops.\n By default, pytest will stop searching for ``conftest.py`` files upwards\n from ``pytest.ini``/``tox.ini``/``setup.cfg`` of the project if any,\n or up to the file-system root.\n\n\n.. confval:: console_output_style\n\n\n\n Sets the console output style while running tests:\n\n * ``classic``: classic pytest output.\n * ``progress``: like classic pytest output, but with a progress indicator.\n * ``count``: like progress, but shows progress as the number of tests completed instead of a percent.\n\n The default is ``progress``, but you can fallback to ``classic`` if you prefer or\n the new mode is causing unexpected problems:\n\n .. code-block:: ini\n\n # content of pytest.ini\n [pytest]\n console_output_style = classic\n\n\n.. confval:: doctest_encoding\n\n\n\n Default encoding to use to decode text files with docstrings.\n :doc:`See how pytest handles doctests `.\n\n\n.. confval:: doctest_optionflags\n\n One or more doctest flag names from the standard ``doctest`` module.\n :doc:`See how pytest handles doctests `.\n\n\n.. confval:: empty_parameter_set_mark\n\n\n\n Allows to pick the action for empty parametersets in parameterization\n\n * ``skip`` skips tests with an empty parameterset (default)\n * ``xfail`` marks tests with an empty parameterset as xfail(run=False)\n * ``fail_at_collect`` raises an exception if parametrize collects an empty parameter set\n\n .. code-block:: ini\n\n # content of pytest.ini\n [pytest]\n empty_parameter_set_mark = xfail\n\n .. note::\n\n The default value of this option is planned to change to ``xfail`` in future releases\n as this is considered less error prone, see `#3155 `_\n for more details.\n\n\n.. confval:: filterwarnings\n\n\n\n Sets a list of filters and actions that should be taken for matched\n warnings. By default all warnings emitted during the test session\n will be displayed in a summary at the end of the test session.\n\n .. code-block:: ini\n\n # content of pytest.ini\n [pytest]\n filterwarnings =\n error\n ignore::DeprecationWarning\n\n This tells pytest to ignore deprecation warnings and turn all other warnings\n into errors. For more information please refer to :ref:`warnings`.\n\n\n.. confval:: junit_duration_report\n\n .. versionadded:: 4.1\n\n Configures how durations are recorded into the JUnit XML report:\n\n * ``total`` (the default): duration times reported include setup, call, and teardown times.\n * ``call``: duration times reported include only call times, excluding setup and teardown.\n\n .. code-block:: ini\n\n [pytest]\n junit_duration_report = call\n\n\n.. confval:: junit_family\n\n .. versionadded:: 4.2\n\n Configures the format of the generated JUnit XML file. The possible options are:\n\n * ``xunit1`` (or ``legacy``): produces old style output, compatible with the xunit 1.0 format. **This is the default**.\n * ``xunit2``: produces `xunit 2.0 style output `__,\n which should be more compatible with latest Jenkins versions.\n\n .. code-block:: ini\n\n [pytest]\n junit_family = xunit2\n\n\n.. confval:: junit_logging\n\n .. versionadded:: 3.5\n\n Configures if stdout/stderr should be written to the JUnit XML file. Valid values are\n ``system-out``, ``system-err``, and ``no`` (the default).\n\n .. code-block:: ini\n\n [pytest]\n junit_logging = system-out\n\n\n.. confval:: junit_log_passing_tests\n\n .. versionadded:: 4.6\n\n If ``junit_logging != \"no\"``, configures if the captured output should be written\n to the JUnit XML file for **passing** tests. Default is ``True``.\n\n .. code-block:: ini\n\n [pytest]\n junit_log_passing_tests = False\n\n\n.. confval:: junit_suite_name\n\n To set the name of the root test suite xml item, you can configure the ``junit_suite_name`` option in your config file:\n\n .. code-block:: ini\n\n [pytest]\n junit_suite_name = my_suite\n\n\n.. confval:: log_cli_date_format\n\n\n\n Sets a :py:func:`time.strftime`-compatible string that will be used when formatting dates for live logging.\n\n .. code-block:: ini\n\n [pytest]\n log_cli_date_format = %Y-%m-%d %H:%M:%S\n\n For more information, see :ref:`live_logs`.\n\n.. confval:: log_cli_format\n\n\n\n Sets a :py:mod:`logging`-compatible string used to format live logging messages.\n\n .. code-block:: ini\n\n [pytest]\n log_cli_format = %(asctime)s %(levelname)s %(message)s\n\n For more information, see :ref:`live_logs`.\n\n\n.. confval:: log_cli_level\n\n\n\n Sets the minimum log message level that should be captured for live logging. The integer value or\n the names of the levels can be used.\n\n .. code-block:: ini\n\n [pytest]\n log_cli_level = INFO\n\n For more information, see :ref:`live_logs`.\n\n\n.. confval:: log_date_format\n\n\n\n Sets a :py:func:`time.strftime`-compatible string that will be used when formatting dates for logging capture.\n\n .. code-block:: ini\n\n [pytest]\n log_date_format = %Y-%m-%d %H:%M:%S\n\n For more information, see :ref:`logging`.\n\n\n.. confval:: log_file\n\n\n\n Sets a file name relative to the ``pytest.ini`` file where log messages should be written to, in addition\n to the other logging facilities that are active.\n\n .. code-block:: ini\n\n [pytest]\n log_file = logs/pytest-logs.txt\n\n For more information, see :ref:`logging`.\n\n\n.. confval:: log_file_date_format\n\n\n\n Sets a :py:func:`time.strftime`-compatible string that will be used when formatting dates for the logging file.\n\n .. code-block:: ini\n\n [pytest]\n log_file_date_format = %Y-%m-%d %H:%M:%S\n\n For more information, see :ref:`logging`.\n\n.. confval:: log_file_format\n\n\n\n Sets a :py:mod:`logging`-compatible string used to format logging messages redirected to the logging file.\n\n .. code-block:: ini\n\n [pytest]\n log_file_format = %(asctime)s %(levelname)s %(message)s\n\n For more information, see :ref:`logging`.\n\n.. confval:: log_file_level\n\n\n\n Sets the minimum log message level that should be captured for the logging file. The integer value or\n the names of the levels can be used.\n\n .. code-block:: ini\n\n [pytest]\n log_file_level = INFO\n\n For more information, see :ref:`logging`.\n\n\n.. confval:: log_format\n\n\n\n Sets a :py:mod:`logging`-compatible string used to format captured logging messages.\n\n .. code-block:: ini\n\n [pytest]\n log_format = %(asctime)s %(levelname)s %(message)s\n\n For more information, see :ref:`logging`.\n\n\n.. confval:: log_level\n\n\n\n Sets the minimum log message level that should be captured for logging capture. The integer value or\n the names of the levels can be used.\n\n .. code-block:: ini\n\n [pytest]\n log_level = INFO\n\n For more information, see :ref:`logging`.\n\n\n.. confval:: log_print\n\n\n\n If set to ``False``, will disable displaying captured logging messages for failed tests.\n\n .. code-block:: ini\n\n [pytest]\n log_print = False\n\n For more information, see :ref:`logging`.\n\n\n.. confval:: markers\n\n When the ``--strict-markers`` or ``--strict`` command-line arguments are used,\n only known markers - defined in code by core pytest or some plugin - are allowed.\n\n You can list additional markers in this setting to add them to the whitelist,\n in which case you probably want to add ``--strict-markers`` to ``addopts``\n to avoid future regressions:\n\n .. code-block:: ini\n\n [pytest]\n addopts = --strict-markers\n markers =\n slow\n serial\n\n.. confval:: minversion\n\n Specifies a minimal pytest version required for running tests.\n\n .. code-block:: ini\n\n # content of pytest.ini\n [pytest]\n minversion = 3.0 # will fail if we run with pytest-2.8\n\n\n.. confval:: norecursedirs\n\n Set the directory basename patterns to avoid when recursing\n for test discovery. The individual (fnmatch-style) patterns are\n applied to the basename of a directory to decide if to recurse into it.\n Pattern matching characters::\n\n * matches everything\n ? matches any single character\n [seq] matches any character in seq\n [!seq] matches any char not in seq\n\n Default patterns are ``'.*', 'build', 'dist', 'CVS', '_darcs', '{arch}', '*.egg', 'venv'``.\n Setting a ``norecursedirs`` replaces the default. Here is an example of\n how to avoid certain directories:\n\n .. code-block:: ini\n\n [pytest]\n norecursedirs = .svn _build tmp*\n\n This would tell ``pytest`` to not look into typical subversion or\n sphinx-build directories or into any ``tmp`` prefixed directory.\n\n Additionally, ``pytest`` will attempt to intelligently identify and ignore a\n virtualenv by the presence of an activation script. Any directory deemed to\n be the root of a virtual environment will not be considered during test\n collection unless ``‑‑collect‑in‑virtualenv`` is given. Note also that\n ``norecursedirs`` takes precedence over ``‑‑collect‑in‑virtualenv``; e.g. if\n you intend to run tests in a virtualenv with a base directory that matches\n ``'.*'`` you *must* override ``norecursedirs`` in addition to using the\n ``‑‑collect‑in‑virtualenv`` flag.\n\n\n.. confval:: python_classes\n\n One or more name prefixes or glob-style patterns determining which classes\n are considered for test collection. Search for multiple glob patterns by\n adding a space between patterns. By default, pytest will consider any\n class prefixed with ``Test`` as a test collection. Here is an example of how\n to collect tests from classes that end in ``Suite``:\n\n .. code-block:: ini\n\n [pytest]\n python_classes = *Suite\n\n Note that ``unittest.TestCase`` derived classes are always collected\n regardless of this option, as ``unittest``'s own collection framework is used\n to collect those tests.\n\n\n.. confval:: python_files\n\n One or more Glob-style file patterns determining which python files\n are considered as test modules. Search for multiple glob patterns by\n adding a space between patterns:\n\n .. code-block:: ini\n\n [pytest]\n python_files = test_*.py check_*.py example_*.py\n\n Or one per line:\n\n .. code-block:: ini\n\n [pytest]\n python_files =\n test_*.py\n check_*.py\n example_*.py\n\n By default, files matching ``test_*.py`` and ``*_test.py`` will be considered\n test modules.\n\n\n.. confval:: python_functions\n\n One or more name prefixes or glob-patterns determining which test functions\n and methods are considered tests. Search for multiple glob patterns by\n adding a space between patterns. By default, pytest will consider any\n function prefixed with ``test`` as a test. Here is an example of how\n to collect test functions and methods that end in ``_test``:\n\n .. code-block:: ini\n\n [pytest]\n python_functions = *_test\n\n Note that this has no effect on methods that live on a ``unittest\n .TestCase`` derived class, as ``unittest``'s own collection framework is used\n to collect those tests.\n\n See :ref:`change naming conventions` for more detailed examples.\n\n\n.. confval:: testpaths\n\n\n\n Sets list of directories that should be searched for tests when\n no specific directories, files or test ids are given in the command line when\n executing pytest from the :ref:`rootdir ` directory.\n Useful when all project tests are in a known location to speed up\n test collection and to avoid picking up undesired tests by accident.\n\n .. code-block:: ini\n\n [pytest]\n testpaths = testing doc\n\n This tells pytest to only look for tests in ``testing`` and ``doc``\n directories when executing from the root directory.\n\n\n.. confval:: usefixtures\n\n List of fixtures that will be applied to all test functions; this is semantically the same to apply\n the ``@pytest.mark.usefixtures`` marker to all test functions.\n\n\n .. code-block:: ini\n\n [pytest]\n usefixtures =\n clean_db\n\n\n.. confval:: xfail_strict\n\n If set to ``True``, tests marked with ``@pytest.mark.xfail`` that actually succeed will by default fail the\n test suite.\n For more information, see :ref:`xfail strict tutorial`.\n\n\n .. code-block:: ini\n\n [pytest]\n xfail_strict = True\n"},{"col":0,"comment":"null","endLoc":183,"header":"def get_default_arg_names(function)","id":1221,"name":"get_default_arg_names","nodeType":"Function","startLoc":175,"text":"def get_default_arg_names(function):\n # Note: this code intentionally mirrors the code at the beginning of getfuncargnames,\n # to get the arguments which were excluded from its result because they had default values\n return tuple(\n p.name\n for p in signature(function).parameters.values()\n if p.kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY)\n and p.default is not Parameter.empty\n )"},{"col":0,"comment":"Call regendoc tool to update examples and pytest output in the docs.","endLoc":72,"header":"def regen()","id":1222,"name":"regen","nodeType":"Function","startLoc":69,"text":"def regen():\n \"\"\"Call regendoc tool to update examples and pytest output in the docs.\"\"\"\n print(f\"{Fore.CYAN}[generate.regen] {Fore.RESET}Updating docs\")\n check_call([\"tox\", \"-e\", \"regen\"])"},{"col":0,"comment":"Runs pre-commit in all files to ensure they are formatted correctly","endLoc":80,"header":"def fix_formatting()","id":1223,"name":"fix_formatting","nodeType":"Function","startLoc":75,"text":"def fix_formatting():\n \"\"\"Runs pre-commit in all files to ensure they are formatted correctly\"\"\"\n print(\n f\"{Fore.CYAN}[generate.fix linting] {Fore.RESET}Fixing formatting using pre-commit\"\n )\n call([\"pre-commit\", \"run\", \"--all-files\"])"},{"col":0,"comment":"Generates new docs, release announcements and creates a local tag.","endLoc":96,"header":"def pre_release(version)","id":1224,"name":"pre_release","nodeType":"Function","startLoc":83,"text":"def pre_release(version):\n \"\"\"Generates new docs, release announcements and creates a local tag.\"\"\"\n announce(version)\n regen()\n changelog(version, write_out=True)\n fix_formatting()\n\n msg = \"Preparing release version {}\".format(version)\n check_call([\"git\", \"commit\", \"-a\", \"-m\", msg])\n\n print()\n print(f\"{Fore.CYAN}[generate.pre_release] {Fore.GREEN}All done!\")\n print()\n print(f\"Please push your branch and open a PR.\")"},{"col":0,"comment":"null","endLoc":104,"header":"def changelog(version, write_out=False)","id":1225,"name":"changelog","nodeType":"Function","startLoc":99,"text":"def changelog(version, write_out=False):\n if write_out:\n addopts = []\n else:\n addopts = [\"--draft\"]\n check_call([\"towncrier\", \"--yes\", \"--version\", version] + addopts)"},{"col":0,"comment":"null","endLoc":112,"header":"def main()","id":1226,"name":"main","nodeType":"Function","startLoc":107,"text":"def main():\n init(autoreset=True)\n parser = argparse.ArgumentParser()\n parser.add_argument(\"version\", help=\"Release version\")\n options = parser.parse_args()\n pre_release(options.version)"},{"attributeType":"null","col":12,"comment":"null","endLoc":1396,"id":1227,"name":"obj","nodeType":"Attribute","startLoc":1396,"text":"self.obj"},{"id":1228,"name":"testing/logging","nodeType":"Package"},{"fileName":"test_fixture.py","filePath":"testing/logging","id":1229,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport logging\n\nimport pytest\n\nlogger = logging.getLogger(__name__)\nsublogger = logging.getLogger(__name__ + \".baz\")\n\n\ndef test_fixture_help(testdir):\n result = testdir.runpytest(\"--fixtures\")\n result.stdout.fnmatch_lines([\"*caplog*\"])\n\n\ndef test_change_level(caplog):\n caplog.set_level(logging.INFO)\n logger.debug(\"handler DEBUG level\")\n logger.info(\"handler INFO level\")\n\n caplog.set_level(logging.CRITICAL, logger=sublogger.name)\n sublogger.warning(\"logger WARNING level\")\n sublogger.critical(\"logger CRITICAL level\")\n\n assert \"DEBUG\" not in caplog.text\n assert \"INFO\" in caplog.text\n assert \"WARNING\" not in caplog.text\n assert \"CRITICAL\" in caplog.text\n\n\ndef test_change_level_undo(testdir):\n \"\"\"Ensure that 'set_level' is undone after the end of the test\"\"\"\n testdir.makepyfile(\n \"\"\"\n import logging\n\n def test1(caplog):\n caplog.set_level(logging.INFO)\n # using + operator here so fnmatch_lines doesn't match the code in the traceback\n logging.info('log from ' + 'test1')\n assert 0\n\n def test2(caplog):\n # using + operator here so fnmatch_lines doesn't match the code in the traceback\n logging.info('log from ' + 'test2')\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*log from test1*\", \"*2 failed in *\"])\n assert \"log from test2\" not in result.stdout.str()\n\n\ndef test_with_statement(caplog):\n with caplog.at_level(logging.INFO):\n logger.debug(\"handler DEBUG level\")\n logger.info(\"handler INFO level\")\n\n with caplog.at_level(logging.CRITICAL, logger=sublogger.name):\n sublogger.warning(\"logger WARNING level\")\n sublogger.critical(\"logger CRITICAL level\")\n\n assert \"DEBUG\" not in caplog.text\n assert \"INFO\" in caplog.text\n assert \"WARNING\" not in caplog.text\n assert \"CRITICAL\" in caplog.text\n\n\ndef test_log_access(caplog):\n caplog.set_level(logging.INFO)\n logger.info(\"boo %s\", \"arg\")\n assert caplog.records[0].levelname == \"INFO\"\n assert caplog.records[0].msg == \"boo %s\"\n assert \"boo arg\" in caplog.text\n\n\ndef test_messages(caplog):\n caplog.set_level(logging.INFO)\n logger.info(\"boo %s\", \"arg\")\n logger.info(\"bar %s\\nbaz %s\", \"arg1\", \"arg2\")\n assert \"boo arg\" == caplog.messages[0]\n assert \"bar arg1\\nbaz arg2\" == caplog.messages[1]\n assert caplog.text.count(\"\\n\") > len(caplog.messages)\n assert len(caplog.text.splitlines()) > len(caplog.messages)\n\n try:\n raise Exception(\"test\")\n except Exception:\n logger.exception(\"oops\")\n\n assert \"oops\" in caplog.text\n assert \"oops\" in caplog.messages[-1]\n # Tracebacks are stored in the record and not added until the formatter or handler.\n assert \"Exception\" in caplog.text\n assert \"Exception\" not in caplog.messages[-1]\n\n\ndef test_record_tuples(caplog):\n caplog.set_level(logging.INFO)\n logger.info(\"boo %s\", \"arg\")\n\n assert caplog.record_tuples == [(__name__, logging.INFO, \"boo arg\")]\n\n\ndef test_unicode(caplog):\n caplog.set_level(logging.INFO)\n logger.info(u\"bū\")\n assert caplog.records[0].levelname == \"INFO\"\n assert caplog.records[0].msg == u\"bū\"\n assert u\"bū\" in caplog.text\n\n\ndef test_clear(caplog):\n caplog.set_level(logging.INFO)\n logger.info(u\"bū\")\n assert len(caplog.records)\n assert caplog.text\n caplog.clear()\n assert not len(caplog.records)\n assert not caplog.text\n\n\n@pytest.fixture\ndef logging_during_setup_and_teardown(caplog):\n caplog.set_level(\"INFO\")\n logger.info(\"a_setup_log\")\n yield\n logger.info(\"a_teardown_log\")\n assert [x.message for x in caplog.get_records(\"teardown\")] == [\"a_teardown_log\"]\n\n\ndef test_caplog_captures_for_all_stages(caplog, logging_during_setup_and_teardown):\n assert not caplog.records\n assert not caplog.get_records(\"call\")\n logger.info(\"a_call_log\")\n assert [x.message for x in caplog.get_records(\"call\")] == [\"a_call_log\"]\n\n assert [x.message for x in caplog.get_records(\"setup\")] == [\"a_setup_log\"]\n\n # This reaches into private API, don't use this type of thing in real tests!\n assert set(caplog._item.catch_log_handlers.keys()) == {\"setup\", \"call\"}\n"},{"attributeType":"null","col":8,"comment":"null","endLoc":1432,"id":1230,"name":"fixturenames","nodeType":"Attribute","startLoc":1432,"text":"self.fixturenames"},{"attributeType":"null","col":8,"comment":"null","endLoc":1439,"id":1231,"name":"originalname","nodeType":"Attribute","startLoc":1439,"text":"self.originalname"},{"col":0,"comment":"null","endLoc":12,"header":"def test_fixture_help(testdir)","id":1232,"name":"test_fixture_help","nodeType":"Function","startLoc":10,"text":"def test_fixture_help(testdir):\n result = testdir.runpytest(\"--fixtures\")\n result.stdout.fnmatch_lines([\"*caplog*\"])"},{"attributeType":"null","col":8,"comment":"null","endLoc":1442,"id":1233,"name":"funcargs","nodeType":"Attribute","startLoc":1442,"text":"self.funcargs"},{"col":0,"comment":"null","endLoc":27,"header":"def test_change_level(caplog)","id":1234,"name":"test_change_level","nodeType":"Function","startLoc":15,"text":"def test_change_level(caplog):\n caplog.set_level(logging.INFO)\n logger.debug(\"handler DEBUG level\")\n logger.info(\"handler INFO level\")\n\n caplog.set_level(logging.CRITICAL, logger=sublogger.name)\n sublogger.warning(\"logger WARNING level\")\n sublogger.critical(\"logger CRITICAL level\")\n\n assert \"DEBUG\" not in caplog.text\n assert \"INFO\" in caplog.text\n assert \"WARNING\" not in caplog.text\n assert \"CRITICAL\" in caplog.text"},{"attributeType":"null","col":12,"comment":"null","endLoc":1401,"id":1235,"name":"callspec","nodeType":"Attribute","startLoc":1401,"text":"self.callspec"},{"col":4,"comment":"Resolves if each parametrized argument must be considered a parameter to a fixture or a \"funcarg\"\n to the function, based on the ``indirect`` parameter of the parametrized() call.\n\n :param List[str] argnames: list of argument names passed to ``parametrize()``.\n :param indirect: same ``indirect`` parameter of ``parametrize()``.\n :rtype: Dict[str, str]\n A dict mapping each arg name to either:\n * \"params\" if the argname should be the parameter of a fixture of the same name.\n * \"funcargs\" if the argname should be a parameter to the parametrized test function.\n ","endLoc":1099,"header":"def _resolve_arg_value_types(self, argnames, indirect)","id":1236,"name":"_resolve_arg_value_types","nodeType":"Function","startLoc":1072,"text":"def _resolve_arg_value_types(self, argnames, indirect):\n \"\"\"Resolves if each parametrized argument must be considered a parameter to a fixture or a \"funcarg\"\n to the function, based on the ``indirect`` parameter of the parametrized() call.\n\n :param List[str] argnames: list of argument names passed to ``parametrize()``.\n :param indirect: same ``indirect`` parameter of ``parametrize()``.\n :rtype: Dict[str, str]\n A dict mapping each arg name to either:\n * \"params\" if the argname should be the parameter of a fixture of the same name.\n * \"funcargs\" if the argname should be a parameter to the parametrized test function.\n \"\"\"\n valtypes = {}\n if indirect is True:\n valtypes = dict.fromkeys(argnames, \"params\")\n elif indirect is False:\n valtypes = dict.fromkeys(argnames, \"funcargs\")\n elif isinstance(indirect, (tuple, list)):\n valtypes = dict.fromkeys(argnames, \"funcargs\")\n for arg in indirect:\n if arg not in argnames:\n fail(\n \"In {}: indirect fixture '{}' doesn't exist\".format(\n self.function.__name__, arg\n ),\n pytrace=False,\n )\n valtypes[arg] = \"params\"\n return valtypes"},{"attributeType":"null","col":8,"comment":"null","endLoc":1443,"id":1237,"name":"_request","nodeType":"Attribute","startLoc":1443,"text":"self._request"},{"className":"UnitTestCase","col":0,"comment":"null","endLoc":80,"id":1238,"nodeType":"Class","startLoc":32,"text":"class UnitTestCase(Class):\n # marker for fixturemanger.getfixtureinfo()\n # to declare that our children do not support funcargs\n nofuncargs = True\n\n def collect(self):\n from unittest import TestLoader\n\n cls = self.obj\n if not getattr(cls, \"__test__\", True):\n return\n\n skipped = getattr(cls, \"__unittest_skip__\", False)\n if not skipped:\n self._inject_setup_teardown_fixtures(cls)\n self._inject_setup_class_fixture()\n\n self.session._fixturemanager.parsefactories(self, unittest=True)\n loader = TestLoader()\n foundsomething = False\n for name in loader.getTestCaseNames(self.obj):\n x = getattr(self.obj, name)\n if not getattr(x, \"__test__\", True):\n continue\n funcobj = getimfunc(x)\n yield TestCaseFunction(name, parent=self, callobj=funcobj)\n foundsomething = True\n\n if not foundsomething:\n runtest = getattr(self.obj, \"runTest\", None)\n if runtest is not None:\n ut = sys.modules.get(\"twisted.trial.unittest\", None)\n if ut is None or runtest != ut.TestCase.runTest:\n yield TestCaseFunction(\"runTest\", parent=self)\n\n def _inject_setup_teardown_fixtures(self, cls):\n \"\"\"Injects a hidden auto-use fixture to invoke setUpClass/setup_method and corresponding\n teardown functions (#517)\"\"\"\n class_fixture = _make_xunit_fixture(\n cls, \"setUpClass\", \"tearDownClass\", scope=\"class\", pass_self=False\n )\n if class_fixture:\n cls.__pytest_class_setup = class_fixture\n\n method_fixture = _make_xunit_fixture(\n cls, \"setup_method\", \"teardown_method\", scope=\"function\", pass_self=True\n )\n if method_fixture:\n cls.__pytest_method_setup = method_fixture"},{"col":4,"comment":"null","endLoc":65,"header":"def collect(self)","id":1239,"name":"collect","nodeType":"Function","startLoc":37,"text":"def collect(self):\n from unittest import TestLoader\n\n cls = self.obj\n if not getattr(cls, \"__test__\", True):\n return\n\n skipped = getattr(cls, \"__unittest_skip__\", False)\n if not skipped:\n self._inject_setup_teardown_fixtures(cls)\n self._inject_setup_class_fixture()\n\n self.session._fixturemanager.parsefactories(self, unittest=True)\n loader = TestLoader()\n foundsomething = False\n for name in loader.getTestCaseNames(self.obj):\n x = getattr(self.obj, name)\n if not getattr(x, \"__test__\", True):\n continue\n funcobj = getimfunc(x)\n yield TestCaseFunction(name, parent=self, callobj=funcobj)\n foundsomething = True\n\n if not foundsomething:\n runtest = getattr(self.obj, \"runTest\", None)\n if runtest is not None:\n ut = sys.modules.get(\"twisted.trial.unittest\", None)\n if ut is None or runtest != ut.TestCase.runTest:\n yield TestCaseFunction(\"runTest\", parent=self)"},{"col":4,"comment":"null","endLoc":223,"header":"def append_pass(self, report)","id":1240,"name":"append_pass","nodeType":"Function","startLoc":222,"text":"def append_pass(self, report):\n self.add_stats(\"passed\")"},{"col":4,"comment":"Resolves the actual ids for the given argnames, based on the ``ids`` parameter given\n to ``parametrize``.\n\n :param List[str] argnames: list of argument names passed to ``parametrize()``.\n :param ids: the ids parameter of the parametrized call (see docs).\n :param List[ParameterSet] parameters: the list of parameter values, same size as ``argnames``.\n :param Item item: the item that generated this parametrized call.\n :rtype: List[str]\n :return: the list of ids for each argname given\n ","endLoc":1070,"header":"def _resolve_arg_ids(self, argnames, ids, parameters, item)","id":1241,"name":"_resolve_arg_ids","nodeType":"Function","startLoc":1040,"text":"def _resolve_arg_ids(self, argnames, ids, parameters, item):\n \"\"\"Resolves the actual ids for the given argnames, based on the ``ids`` parameter given\n to ``parametrize``.\n\n :param List[str] argnames: list of argument names passed to ``parametrize()``.\n :param ids: the ids parameter of the parametrized call (see docs).\n :param List[ParameterSet] parameters: the list of parameter values, same size as ``argnames``.\n :param Item item: the item that generated this parametrized call.\n :rtype: List[str]\n :return: the list of ids for each argname given\n \"\"\"\n from _pytest._io.saferepr import saferepr\n\n idfn = None\n if callable(ids):\n idfn = ids\n ids = None\n if ids:\n func_name = self.function.__name__\n if len(ids) != len(parameters):\n msg = \"In {}: {} parameter sets specified, with different number of ids: {}\"\n fail(msg.format(func_name, len(parameters), len(ids)), pytrace=False)\n for id_value in ids:\n if id_value is not None and not isinstance(id_value, six.string_types):\n msg = \"In {}: ids must be list of strings, found: {} (type: {!r})\"\n fail(\n msg.format(func_name, saferepr(id_value), type(id_value)),\n pytrace=False,\n )\n ids = idmaker(argnames, parameters, idfn, ids, self.config, item=item)\n return ids"},{"col":4,"comment":"null","endLoc":239,"header":"def append_failure(self, report)","id":1242,"name":"append_failure","nodeType":"Function","startLoc":225,"text":"def append_failure(self, report):\n # msg = str(report.longrepr.reprtraceback.extraline)\n if hasattr(report, \"wasxfail\"):\n self._add_simple(Junit.skipped, \"xfail-marked test passes unexpectedly\")\n else:\n if hasattr(report.longrepr, \"reprcrash\"):\n message = report.longrepr.reprcrash.message\n elif isinstance(report.longrepr, six.string_types):\n message = report.longrepr\n else:\n message = str(report.longrepr)\n message = bin_xml_escape(message)\n fail = Junit.failure(message=message)\n fail.append(bin_xml_escape(report.longrepr))\n self.append(fail)"},{"col":0,"comment":"null","endLoc":1233,"header":"def idmaker(argnames, parametersets, idfn=None, ids=None, config=None, item=None)","id":1243,"name":"idmaker","nodeType":"Function","startLoc":1220,"text":"def idmaker(argnames, parametersets, idfn=None, ids=None, config=None, item=None):\n ids = [\n _idvalset(valindex, parameterset, argnames, idfn, ids, config=config, item=item)\n for valindex, parameterset in enumerate(parametersets)\n ]\n if len(set(ids)) != len(ids):\n # The ids are not unique\n duplicates = [testid for testid in ids if ids.count(testid) > 1]\n counters = collections.defaultdict(lambda: 0)\n for index, testid in enumerate(ids):\n if testid in duplicates:\n ids[index] = testid + str(counters[testid])\n counters[testid] += 1\n return ids"},{"col":0,"comment":"null","endLoc":1217,"header":"def _idvalset(idx, parameterset, argnames, idfn, ids, item, config)","id":1244,"name":"_idvalset","nodeType":"Function","startLoc":1207,"text":"def _idvalset(idx, parameterset, argnames, idfn, ids, item, config):\n if parameterset.id is not None:\n return parameterset.id\n if ids is None or (idx >= len(ids) or ids[idx] is None):\n this_id = [\n _idval(val, argname, idx, idfn, item=item, config=config)\n for val, argname in zip(parameterset.values, argnames)\n ]\n return \"-\".join(this_id)\n else:\n return _ascii_escaped_by_config(ids[idx], config)"},{"fileName":"test_hello_world.py","filePath":"doc/en/example/assertion/global_testmodule_config","id":1245,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nhello = \"world\"\n\n\ndef test_func():\n pass\n"},{"col":0,"comment":"null","endLoc":6,"header":"def test_func()","id":1246,"name":"test_func","nodeType":"Function","startLoc":5,"text":"def test_func():\n pass"},{"attributeType":"str","col":0,"comment":"null","endLoc":2,"id":1247,"name":"hello","nodeType":"Attribute","startLoc":2,"text":"hello"},{"col":0,"comment":"null","endLoc":1204,"header":"def _idval(val, argname, idx, idfn, item, config)","id":1248,"name":"_idval","nodeType":"Function","startLoc":1174,"text":"def _idval(val, argname, idx, idfn, item, config):\n if idfn:\n try:\n generated_id = idfn(val)\n if generated_id is not None:\n val = generated_id\n except Exception as e:\n # See issue https://github.com/pytest-dev/pytest/issues/2169\n msg = \"{}: error raised while trying to determine id of parameter '{}' at position {}\\n\"\n msg = msg.format(item.nodeid, argname, idx)\n # we only append the exception type and message because on Python 2 reraise does nothing\n msg += \" {}: {}\\n\".format(type(e).__name__, e)\n six.raise_from(ValueError(msg), e)\n elif config:\n hook_id = config.hook.pytest_make_parametrize_id(\n config=config, val=val, argname=argname\n )\n if hook_id:\n return hook_id\n\n if isinstance(val, STRING_TYPES):\n return _ascii_escaped_by_config(val, config)\n elif val is None or isinstance(val, (float, int, bool)):\n return str(val)\n elif isinstance(val, REGEX_TYPE):\n return ascii_escaped(val.pattern)\n elif enum is not None and isinstance(val, enum.Enum):\n return str(val)\n elif (isclass(val) or isfunction(val)) and hasattr(val, \"__name__\"):\n return val.__name__\n return str(argname) + str(idx)"},{"col":0,"comment":"null","endLoc":145,"header":"def pytest_runtest_teardown(item)","id":1251,"name":"pytest_runtest_teardown","nodeType":"Function","startLoc":144,"text":"def pytest_runtest_teardown(item):\n util._reprcompare = None"},{"col":0,"comment":"null","endLoc":152,"header":"def pytest_sessionfinish(session)","id":1252,"name":"pytest_sessionfinish","nodeType":"Function","startLoc":148,"text":"def pytest_sessionfinish(session):\n assertstate = getattr(session.config, \"_assertstate\", None)\n if assertstate:\n if assertstate.hook is not None:\n assertstate.hook.set_session(None)"},{"col":0,"comment":"","endLoc":2,"header":"test_hello_world.py#","id":1253,"name":"","nodeType":"Function","startLoc":2,"text":"hello = \"world\""},{"attributeType":"function","col":0,"comment":"null","endLoc":156,"id":1255,"name":"pytest_assertrepr_compare","nodeType":"Attribute","startLoc":156,"text":"pytest_assertrepr_compare"},{"col":4,"comment":"null","endLoc":245,"header":"def append_collect_error(self, report)","id":1256,"name":"append_collect_error","nodeType":"Function","startLoc":241,"text":"def append_collect_error(self, report):\n # msg = str(report.longrepr.reprtraceback.extraline)\n self.append(\n Junit.error(bin_xml_escape(report.longrepr), message=\"collection failure\")\n )"},{"col":4,"comment":"null","endLoc":248,"header":"def append_collect_skipped(self, report)","id":1257,"name":"append_collect_skipped","nodeType":"Function","startLoc":247,"text":"def append_collect_skipped(self, report):\n self._add_simple(Junit.skipped, \"collection skipped\", report.longrepr)"},{"col":4,"comment":"null","endLoc":255,"header":"def append_error(self, report)","id":1258,"name":"append_error","nodeType":"Function","startLoc":250,"text":"def append_error(self, report):\n if report.when == \"teardown\":\n msg = \"test teardown failure\"\n else:\n msg = \"test setup failure\"\n self._add_simple(Junit.error, msg, report.longrepr)"},{"col":0,"comment":"null","endLoc":1171,"header":"def _ascii_escaped_by_config(val, config)","id":1260,"name":"_ascii_escaped_by_config","nodeType":"Function","startLoc":1164,"text":"def _ascii_escaped_by_config(val, config):\n if config is None:\n escape_option = False\n else:\n escape_option = config.getini(\n \"disable_test_id_escaping_and_forfeit_all_rights_to_community_support\"\n )\n return val if escape_option else ascii_escaped(val)"},{"col":4,"comment":"null","endLoc":134,"header":"def test_inf_tolerance(self)","id":1261,"name":"test_inf_tolerance","nodeType":"Function","startLoc":127,"text":"def test_inf_tolerance(self):\n # Everything should be equal if the tolerance is infinite.\n large_diffs = [(1, 1000), (1e-50, 1e50), (-1.0, -1e300), (0.0, 10)]\n for a, x in large_diffs:\n assert a != approx(x, rel=0.0, abs=0.0)\n assert a == approx(x, rel=inf, abs=0.0)\n assert a == approx(x, rel=0.0, abs=inf)\n assert a == approx(x, rel=inf, abs=inf)"},{"col":4,"comment":"null","endLoc":280,"header":"def append_skipped(self, report)","id":1262,"name":"append_skipped","nodeType":"Function","startLoc":257,"text":"def append_skipped(self, report):\n if hasattr(report, \"wasxfail\"):\n xfailreason = report.wasxfail\n if xfailreason.startswith(\"reason: \"):\n xfailreason = xfailreason[8:]\n self.append(\n Junit.skipped(\n \"\", type=\"pytest.xfail\", message=bin_xml_escape(xfailreason)\n )\n )\n else:\n filename, lineno, skipreason = report.longrepr\n if skipreason.startswith(\"Skipped: \"):\n skipreason = skipreason[9:]\n details = \"%s:%s: %s\" % (filename, lineno, skipreason)\n\n self.append(\n Junit.skipped(\n bin_xml_escape(details),\n type=\"pytest.skip\",\n message=bin_xml_escape(skipreason),\n )\n )\n self.write_captured_output(report)"},{"col":4,"comment":"null","endLoc":142,"header":"def test_inf_tolerance_expecting_zero(self)","id":1263,"name":"test_inf_tolerance_expecting_zero","nodeType":"Function","startLoc":136,"text":"def test_inf_tolerance_expecting_zero(self):\n # If the relative tolerance is zero but the expected value is infinite,\n # the actual tolerance is a NaN, which should be an error.\n illegal_kwargs = [dict(rel=inf, abs=0.0), dict(rel=inf, abs=inf)]\n for kwargs in illegal_kwargs:\n with pytest.raises(ValueError):\n 1 == approx(0, **kwargs)"},{"col":0,"comment":"","endLoc":4,"header":"__init__.py#","id":1264,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"\nsupport for presenting detailed information in failing assertions.\n\"\"\"\n\npytest_assertrepr_compare = util.assertrepr_compare"},{"fileName":"conftest.py","filePath":"doc/en/example","id":1265,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ncollect_ignore = [\"nonpython\"]\n"},{"attributeType":"list","col":0,"comment":"null","endLoc":2,"id":1266,"name":"collect_ignore","nodeType":"Attribute","startLoc":2,"text":"collect_ignore"},{"col":0,"comment":"","endLoc":2,"header":"conftest.py#","id":1267,"name":"","nodeType":"Function","startLoc":2,"text":"collect_ignore = [\"nonpython\"]"},{"id":1268,"name":"release-3.0.7.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.0.7\n============\n\npytest 3.0.7 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Barney Gale\n* Bruno Oliveira\n* Florian Bruhin\n* Floris Bruynooghe\n* Ionel Cristian Mărieș\n* Katerina Koukiou\n* NODA, Kai\n* Omer Hadari\n* Patrick Hayes\n* Ran Benita\n* Ronny Pfannschmidt\n* Victor Uriarte\n* Vidar Tonaas Fauske\n* Ville Skyttä\n* fbjorn\n* mbyt\n\nHappy testing,\nThe pytest Development Team\n"},{"col":4,"comment":"null","endLoc":285,"header":"def finalize(self)","id":1269,"name":"finalize","nodeType":"Function","startLoc":282,"text":"def finalize(self):\n data = self.to_xml().unicode(indent=0)\n self.__dict__.clear()\n self.to_xml = lambda: py.xml.raw(data)"},{"col":4,"comment":"null","endLoc":148,"header":"def test_nan_tolerance(self)","id":1270,"name":"test_nan_tolerance","nodeType":"Function","startLoc":144,"text":"def test_nan_tolerance(self):\n illegal_kwargs = [dict(rel=nan), dict(abs=nan), dict(rel=nan, abs=nan)]\n for kwargs in illegal_kwargs:\n with pytest.raises(ValueError):\n 1.1 == approx(1, **kwargs)"},{"col":0,"comment":"null","endLoc":109,"header":"@pytest.mark.skipif(sys.version_info[0] >= 3, reason=\"python 2 only issue\")\ndef test_unicode_handling_syntax_error()","id":1274,"name":"test_unicode_handling_syntax_error","nodeType":"Function","startLoc":99,"text":"@pytest.mark.skipif(sys.version_info[0] >= 3, reason=\"python 2 only issue\")\ndef test_unicode_handling_syntax_error():\n value = u\"ąć\".encode(\"UTF-8\")\n\n def f():\n raise SyntaxError(\"invalid syntax\", (None, 1, 3, value))\n\n excinfo = pytest.raises(Exception, f)\n str(excinfo)\n if sys.version_info[0] < 3:\n text_type(excinfo)"},{"col":4,"comment":"null","endLoc":698,"header":"def clear(self) -> None","id":1275,"name":"clear","nodeType":"Function","startLoc":698,"text":"def clear(self) -> None: ..."},{"col":22,"endLoc":285,"id":1276,"nodeType":"Lambda","startLoc":285,"text":"lambda: py.xml.raw(data)"},{"attributeType":"int","col":8,"comment":"null","endLoc":98,"id":1277,"name":"duration","nodeType":"Attribute","startLoc":98,"text":"self.duration"},{"attributeType":"list","col":8,"comment":"null","endLoc":100,"id":1278,"name":"nodes","nodeType":"Attribute","startLoc":100,"text":"self.nodes"},{"attributeType":"null","col":8,"comment":"null","endLoc":95,"id":1279,"name":"xml","nodeType":"Attribute","startLoc":95,"text":"self.xml"},{"attributeType":"null","col":8,"comment":"null","endLoc":96,"id":1280,"name":"add_stats","nodeType":"Attribute","startLoc":96,"text":"self.add_stats"},{"attributeType":"function","col":8,"comment":"null","endLoc":285,"id":1281,"name":"to_xml","nodeType":"Attribute","startLoc":285,"text":"self.to_xml"},{"attributeType":"null","col":8,"comment":"null","endLoc":94,"id":1282,"name":"id","nodeType":"Attribute","startLoc":94,"text":"self.id"},{"attributeType":"null","col":8,"comment":"null","endLoc":97,"id":1283,"name":"family","nodeType":"Attribute","startLoc":97,"text":"self.family"},{"col":4,"comment":"null","endLoc":1476,"header":"@overload\n def __init__(self, __func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> None","id":1284,"name":"__init__","nodeType":"Function","startLoc":1475,"text":"@overload\n def __init__(self, __func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> None: ..."},{"col":4,"comment":"null","endLoc":1478,"header":"@overload\n def __init__(self, __func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> None","id":1285,"name":"__init__","nodeType":"Function","startLoc":1477,"text":"@overload\n def __init__(self, __func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> None: ..."},{"col":4,"comment":"null","endLoc":1482,"header":"@overload\n def __init__(\n self, __func: Callable[[_T1, _T2, _T3], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]\n ) -> None","id":1286,"name":"__init__","nodeType":"Function","startLoc":1479,"text":"@overload\n def __init__(\n self, __func: Callable[[_T1, _T2, _T3], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":1491,"header":"@overload\n def __init__(\n self,\n __func: Callable[[_T1, _T2, _T3, _T4], _S],\n __iter1: Iterable[_T1],\n __iter2: Iterable[_T2],\n __iter3: Iterable[_T3],\n __iter4: Iterable[_T4],\n ) -> None","id":1287,"name":"__init__","nodeType":"Function","startLoc":1483,"text":"@overload\n def __init__(\n self,\n __func: Callable[[_T1, _T2, _T3, _T4], _S],\n __iter1: Iterable[_T1],\n __iter2: Iterable[_T2],\n __iter3: Iterable[_T3],\n __iter4: Iterable[_T4],\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":1501,"header":"@overload\n def __init__(\n self,\n __func: Callable[[_T1, _T2, _T3, _T4, _T5], _S],\n __iter1: Iterable[_T1],\n __iter2: Iterable[_T2],\n __iter3: Iterable[_T3],\n __iter4: Iterable[_T4],\n __iter5: Iterable[_T5],\n ) -> None","id":1288,"name":"__init__","nodeType":"Function","startLoc":1492,"text":"@overload\n def __init__(\n self,\n __func: Callable[[_T1, _T2, _T3, _T4, _T5], _S],\n __iter1: Iterable[_T1],\n __iter2: Iterable[_T2],\n __iter3: Iterable[_T3],\n __iter4: Iterable[_T4],\n __iter5: Iterable[_T5],\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":1513,"header":"@overload\n def __init__(\n self,\n __func: Callable[..., _S],\n __iter1: Iterable[Any],\n __iter2: Iterable[Any],\n __iter3: Iterable[Any],\n __iter4: Iterable[Any],\n __iter5: Iterable[Any],\n __iter6: Iterable[Any],\n *iterables: Iterable[Any],\n ) -> None","id":1289,"name":"__init__","nodeType":"Function","startLoc":1502,"text":"@overload\n def __init__(\n self,\n __func: Callable[..., _S],\n __iter1: Iterable[Any],\n __iter2: Iterable[Any],\n __iter3: Iterable[Any],\n __iter4: Iterable[Any],\n __iter5: Iterable[Any],\n __iter6: Iterable[Any],\n *iterables: Iterable[Any],\n ) -> None: ..."},{"attributeType":"list","col":8,"comment":"null","endLoc":99,"id":1290,"name":"properties","nodeType":"Attribute","startLoc":99,"text":"self.properties"},{"attributeType":"None","col":8,"comment":"null","endLoc":101,"id":1291,"name":"testcase","nodeType":"Attribute","startLoc":101,"text":"self.testcase"},{"col":4,"comment":"null","endLoc":633,"header":"def _collect(self, arg)","id":1292,"name":"_collect","nodeType":"Function","startLoc":552,"text":"def _collect(self, arg):\n from _pytest.python import Package\n\n names = self._parsearg(arg)\n argpath = names.pop(0)\n\n # Start with a Session root, and delve to argpath item (dir or file)\n # and stack all Packages found on the way.\n # No point in finding packages when collecting doctests\n if not self.config.getoption(\"doctestmodules\", False):\n pm = self.config.pluginmanager\n for parent in reversed(argpath.parts()):\n if pm._confcutdir and pm._confcutdir.relto(parent):\n break\n\n if parent.isdir():\n pkginit = parent.join(\"__init__.py\")\n if pkginit.isfile():\n if pkginit not in self._node_cache:\n col = self._collectfile(pkginit, handle_dupes=False)\n if col:\n if isinstance(col[0], Package):\n self._pkg_roots[parent] = col[0]\n # always store a list in the cache, matchnodes expects it\n self._node_cache[col[0].fspath] = [col[0]]\n\n # If it's a directory argument, recurse and look for any Subpackages.\n # Let the Package collector deal with subnodes, don't collect here.\n if argpath.check(dir=1):\n assert not names, \"invalid arg %r\" % (arg,)\n\n seen_dirs = set()\n for path in argpath.visit(\n fil=self._visit_filter, rec=self._recurse, bf=True, sort=True\n ):\n dirpath = path.dirpath()\n if dirpath not in seen_dirs:\n # Collect packages first.\n seen_dirs.add(dirpath)\n pkginit = dirpath.join(\"__init__.py\")\n if pkginit.exists():\n for x in self._collectfile(pkginit):\n yield x\n if isinstance(x, Package):\n self._pkg_roots[dirpath] = x\n if dirpath in self._pkg_roots:\n # Do not collect packages here.\n continue\n\n for x in self._collectfile(path):\n key = (type(x), x.fspath)\n if key in self._node_cache:\n yield self._node_cache[key]\n else:\n self._node_cache[key] = x\n yield x\n else:\n assert argpath.check(file=1)\n\n if argpath in self._node_cache:\n col = self._node_cache[argpath]\n else:\n collect_root = self._pkg_roots.get(argpath.dirname, self)\n col = collect_root._collectfile(argpath, handle_dupes=False)\n if col:\n self._node_cache[argpath] = col\n m = self.matchnodes(col, names)\n # If __init__.py was the only file requested, then the matched node will be\n # the corresponding Package, and the first yielded item will be the __init__\n # Module itself, so just use that. If this special case isn't taken, then all\n # the files in the package will be yielded.\n if argpath.basename == \"__init__.py\":\n try:\n yield next(m[0].collect())\n except StopIteration:\n # The package collects nothing with only an __init__.py\n # file in it, which gets ignored by the default\n # \"python_files\" option.\n pass\n return\n for y in m:\n yield y"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":102,"id":1293,"name":"attrs","nodeType":"Attribute","startLoc":102,"text":"self.attrs"},{"col":4,"comment":"Injects a hidden auto-use fixture to invoke setUpClass/setup_method and corresponding\n teardown functions (#517)","endLoc":80,"header":"def _inject_setup_teardown_fixtures(self, cls)","id":1294,"name":"_inject_setup_teardown_fixtures","nodeType":"Function","startLoc":67,"text":"def _inject_setup_teardown_fixtures(self, cls):\n \"\"\"Injects a hidden auto-use fixture to invoke setUpClass/setup_method and corresponding\n teardown functions (#517)\"\"\"\n class_fixture = _make_xunit_fixture(\n cls, \"setUpClass\", \"tearDownClass\", scope=\"class\", pass_self=False\n )\n if class_fixture:\n cls.__pytest_class_setup = class_fixture\n\n method_fixture = _make_xunit_fixture(\n cls, \"setup_method\", \"teardown_method\", scope=\"function\", pass_self=True\n )\n if method_fixture:\n cls.__pytest_method_setup = method_fixture"},{"col":0,"comment":"null","endLoc":106,"header":"def _make_xunit_fixture(obj, setup_name, teardown_name, scope, pass_self)","id":1295,"name":"_make_xunit_fixture","nodeType":"Function","startLoc":83,"text":"def _make_xunit_fixture(obj, setup_name, teardown_name, scope, pass_self):\n setup = getattr(obj, setup_name, None)\n teardown = getattr(obj, teardown_name, None)\n if setup is None and teardown is None:\n return None\n\n @pytest.fixture(scope=scope, autouse=True)\n def fixture(self, request):\n if getattr(self, \"__unittest_skip__\", None):\n reason = self.__unittest_skip_why__\n pytest.skip(reason)\n if setup is not None:\n if pass_self:\n setup(self, request.function)\n else:\n setup()\n yield\n if teardown is not None:\n if pass_self:\n teardown(self, request.function)\n else:\n teardown()\n\n return fixture"},{"className":"LogXML","col":0,"comment":"null","endLoc":702,"id":1297,"nodeType":"Class","startLoc":476,"text":"class LogXML(object):\n def __init__(\n self,\n logfile,\n prefix,\n suite_name=\"pytest\",\n logging=\"no\",\n report_duration=\"total\",\n family=\"xunit1\",\n log_passing_tests=True,\n ):\n logfile = os.path.expanduser(os.path.expandvars(logfile))\n self.logfile = os.path.normpath(os.path.abspath(logfile))\n self.prefix = prefix\n self.suite_name = suite_name\n self.logging = logging\n self.log_passing_tests = log_passing_tests\n self.report_duration = report_duration\n self.family = family\n self.stats = dict.fromkeys([\"error\", \"passed\", \"failure\", \"skipped\"], 0)\n self.node_reporters = {} # nodeid -> _NodeReporter\n self.node_reporters_ordered = []\n self.global_properties = []\n\n # List of reports that failed on call but teardown is pending.\n self.open_reports = []\n self.cnt_double_fail_tests = 0\n\n # Replaces convenience family with real family\n if self.family == \"legacy\":\n self.family = \"xunit1\"\n\n def finalize(self, report):\n nodeid = getattr(report, \"nodeid\", report)\n # local hack to handle xdist report order\n slavenode = getattr(report, \"node\", None)\n reporter = self.node_reporters.pop((nodeid, slavenode))\n if reporter is not None:\n reporter.finalize()\n\n def node_reporter(self, report):\n nodeid = getattr(report, \"nodeid\", report)\n # local hack to handle xdist report order\n slavenode = getattr(report, \"node\", None)\n\n key = nodeid, slavenode\n\n if key in self.node_reporters:\n # TODO: breasks for --dist=each\n return self.node_reporters[key]\n\n reporter = _NodeReporter(nodeid, self)\n\n self.node_reporters[key] = reporter\n self.node_reporters_ordered.append(reporter)\n\n return reporter\n\n def add_stats(self, key):\n if key in self.stats:\n self.stats[key] += 1\n\n def _opentestcase(self, report):\n reporter = self.node_reporter(report)\n reporter.record_testreport(report)\n return reporter\n\n def pytest_runtest_logreport(self, report):\n \"\"\"handle a setup/call/teardown report, generating the appropriate\n xml tags as necessary.\n\n note: due to plugins like xdist, this hook may be called in interlaced\n order with reports from other nodes. for example:\n\n usual call order:\n -> setup node1\n -> call node1\n -> teardown node1\n -> setup node2\n -> call node2\n -> teardown node2\n\n possible call order in xdist:\n -> setup node1\n -> call node1\n -> setup node2\n -> call node2\n -> teardown node2\n -> teardown node1\n \"\"\"\n close_report = None\n if report.passed:\n if report.when == \"call\": # ignore setup/teardown\n reporter = self._opentestcase(report)\n reporter.append_pass(report)\n elif report.failed:\n if report.when == \"teardown\":\n # The following vars are needed when xdist plugin is used\n report_wid = getattr(report, \"worker_id\", None)\n report_ii = getattr(report, \"item_index\", None)\n close_report = next(\n (\n rep\n for rep in self.open_reports\n if (\n rep.nodeid == report.nodeid\n and getattr(rep, \"item_index\", None) == report_ii\n and getattr(rep, \"worker_id\", None) == report_wid\n )\n ),\n None,\n )\n if close_report:\n # We need to open new testcase in case we have failure in\n # call and error in teardown in order to follow junit\n # schema\n self.finalize(close_report)\n self.cnt_double_fail_tests += 1\n reporter = self._opentestcase(report)\n if report.when == \"call\":\n reporter.append_failure(report)\n self.open_reports.append(report)\n else:\n reporter.append_error(report)\n elif report.skipped:\n reporter = self._opentestcase(report)\n reporter.append_skipped(report)\n self.update_testcase_duration(report)\n if report.when == \"teardown\":\n reporter = self._opentestcase(report)\n reporter.write_captured_output(report)\n\n for propname, propvalue in report.user_properties:\n reporter.add_property(propname, propvalue)\n\n self.finalize(report)\n report_wid = getattr(report, \"worker_id\", None)\n report_ii = getattr(report, \"item_index\", None)\n close_report = next(\n (\n rep\n for rep in self.open_reports\n if (\n rep.nodeid == report.nodeid\n and getattr(rep, \"item_index\", None) == report_ii\n and getattr(rep, \"worker_id\", None) == report_wid\n )\n ),\n None,\n )\n if close_report:\n self.open_reports.remove(close_report)\n\n def update_testcase_duration(self, report):\n \"\"\"accumulates total duration for nodeid from given report and updates\n the Junit.testcase with the new total if already created.\n \"\"\"\n if self.report_duration == \"total\" or report.when == self.report_duration:\n reporter = self.node_reporter(report)\n reporter.duration += getattr(report, \"duration\", 0.0)\n\n def pytest_collectreport(self, report):\n if not report.passed:\n reporter = self._opentestcase(report)\n if report.failed:\n reporter.append_collect_error(report)\n else:\n reporter.append_collect_skipped(report)\n\n def pytest_internalerror(self, excrepr):\n reporter = self.node_reporter(\"internal\")\n reporter.attrs.update(classname=\"pytest\", name=\"internal\")\n reporter._add_simple(Junit.error, \"internal error\", excrepr)\n\n def pytest_sessionstart(self):\n self.suite_start_time = time.time()\n\n def pytest_sessionfinish(self):\n dirname = os.path.dirname(os.path.abspath(self.logfile))\n if not os.path.isdir(dirname):\n os.makedirs(dirname)\n logfile = open(self.logfile, \"w\", encoding=\"utf-8\")\n suite_stop_time = time.time()\n suite_time_delta = suite_stop_time - self.suite_start_time\n\n numtests = (\n self.stats[\"passed\"]\n + self.stats[\"failure\"]\n + self.stats[\"skipped\"]\n + self.stats[\"error\"]\n - self.cnt_double_fail_tests\n )\n logfile.write('')\n\n logfile.write(\n Junit.testsuite(\n self._get_global_properties_node(),\n [x.to_xml() for x in self.node_reporters_ordered],\n name=self.suite_name,\n errors=self.stats[\"error\"],\n failures=self.stats[\"failure\"],\n skipped=self.stats[\"skipped\"],\n tests=numtests,\n time=\"%.3f\" % suite_time_delta,\n ).unicode(indent=0)\n )\n logfile.close()\n\n def pytest_terminal_summary(self, terminalreporter):\n terminalreporter.write_sep(\"-\", \"generated xml file: %s\" % (self.logfile))\n\n def add_global_property(self, name, value):\n __tracebackhide__ = True\n _check_record_param_type(\"name\", name)\n self.global_properties.append((name, bin_xml_escape(value)))\n\n def _get_global_properties_node(self):\n \"\"\"Return a Junit node containing custom properties, if any.\n \"\"\"\n if self.global_properties:\n return Junit.properties(\n [\n Junit.property(name=name, value=value)\n for name, value in self.global_properties\n ]\n )\n return \"\""},{"col":0,"comment":"","endLoc":4,"header":"release.py#","id":1298,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"\nInvoke development tasks.\n\"\"\"\n\nif __name__ == \"__main__\":\n main()"},{"col":4,"comment":"null","endLoc":506,"header":"def __init__(\n self,\n logfile,\n prefix,\n suite_name=\"pytest\",\n logging=\"no\",\n report_duration=\"total\",\n family=\"xunit1\",\n log_passing_tests=True,\n )","id":1299,"name":"__init__","nodeType":"Function","startLoc":477,"text":"def __init__(\n self,\n logfile,\n prefix,\n suite_name=\"pytest\",\n logging=\"no\",\n report_duration=\"total\",\n family=\"xunit1\",\n log_passing_tests=True,\n ):\n logfile = os.path.expanduser(os.path.expandvars(logfile))\n self.logfile = os.path.normpath(os.path.abspath(logfile))\n self.prefix = prefix\n self.suite_name = suite_name\n self.logging = logging\n self.log_passing_tests = log_passing_tests\n self.report_duration = report_duration\n self.family = family\n self.stats = dict.fromkeys([\"error\", \"passed\", \"failure\", \"skipped\"], 0)\n self.node_reporters = {} # nodeid -> _NodeReporter\n self.node_reporters_ordered = []\n self.global_properties = []\n\n # List of reports that failed on call but teardown is pending.\n self.open_reports = []\n self.cnt_double_fail_tests = 0\n\n # Replaces convenience family with real family\n if self.family == \"legacy\":\n self.family = \"xunit1\""},{"col":0,"comment":"null","endLoc":90,"header":"def expandvars(path: PathLike[AnyStr] | AnyStr) -> AnyStr","id":1300,"name":"expandvars","nodeType":"Function","startLoc":90,"text":"def expandvars(path: PathLike[AnyStr] | AnyStr) -> AnyStr: ..."},{"id":1301,"name":"release-2.6.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.6.1: fixes and new xfail feature\n===========================================================================\n\npytest is a mature Python testing tool with more than a 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThe 2.6.1 release is drop-in compatible to 2.5.2 and actually fixes some\nregressions introduced with 2.6.0. It also brings a little feature\nto the xfail marker which now recognizes expected exceptions,\nsee the CHANGELOG below.\n\nSee docs at:\n\n http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n pip install -U pytest\n\nThanks to all who contributed, among them:\n\n Floris Bruynooghe\n Bruno Oliveira\n Nicolas Delaby\n\nhave fun,\nholger krekel\n\nChanges 2.6.1\n=================\n\n- No longer show line numbers in the --verbose output, the output is now\n purely the nodeid. The line number is still shown in failure reports.\n Thanks Floris Bruynooghe.\n\n- fix issue437 where assertion rewriting could cause pytest-xdist slaves\n to collect different tests. Thanks Bruno Oliveira.\n\n- fix issue555: add \"errors\" attribute to capture-streams to satisfy\n some distutils and possibly other code accessing sys.stdout.errors.\n\n- fix issue547 capsys/capfd also work when output capturing (\"-s\") is disabled.\n\n- address issue170: allow pytest.mark.xfail(...) to specify expected exceptions via\n an optional \"raises=EXC\" argument where EXC can be a single exception\n or a tuple of exception classes. Thanks David Mohr for the complete\n PR.\n\n- fix integration of pytest with unittest.mock.patch decorator when\n it uses the \"new\" argument. Thanks Nicolas Delaby for test and PR.\n\n- fix issue with detecting conftest files if the arguments contain\n \"::\" node id specifications (copy pasted from \"-v\" output)\n\n- fix issue544 by only removing \"@NUM\" at the end of \"::\" separated parts\n and if the part has a \".py\" extension\n\n- don't use py.std import helper, rather import things directly.\n Thanks Bruno Oliveira.\n"},{"id":1302,"name":"testing","nodeType":"Package"},{"fileName":"test_pluginmanager.py","filePath":"testing","id":1303,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport types\n\nimport pytest\nfrom _pytest.config import PytestPluginManager\nfrom _pytest.config.exceptions import UsageError\nfrom _pytest.main import EXIT_NOTESTSCOLLECTED\nfrom _pytest.main import Session\n\n\n@pytest.fixture\ndef pytestpm():\n return PytestPluginManager()\n\n\nclass TestPytestPluginInteractions(object):\n def test_addhooks_conftestplugin(self, testdir, _config_for_test):\n testdir.makepyfile(\n newhooks=\"\"\"\n def pytest_myhook(xyz):\n \"new hook\"\n \"\"\"\n )\n conf = testdir.makeconftest(\n \"\"\"\n import newhooks\n def pytest_addhooks(pluginmanager):\n pluginmanager.add_hookspecs(newhooks)\n def pytest_myhook(xyz):\n return xyz + 1\n \"\"\"\n )\n config = _config_for_test\n pm = config.pluginmanager\n pm.hook.pytest_addhooks.call_historic(\n kwargs=dict(pluginmanager=config.pluginmanager)\n )\n config.pluginmanager._importconftest(conf)\n # print(config.pluginmanager.get_plugins())\n res = config.hook.pytest_myhook(xyz=10)\n assert res == [11]\n\n def test_addhooks_nohooks(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import sys\n def pytest_addhooks(pluginmanager):\n pluginmanager.add_hookspecs(sys)\n \"\"\"\n )\n res = testdir.runpytest()\n assert res.ret != 0\n res.stderr.fnmatch_lines([\"*did not find*sys*\"])\n\n def test_do_option_postinitialize(self, testdir):\n config = testdir.parseconfigure()\n assert not hasattr(config.option, \"test123\")\n p = testdir.makepyfile(\n \"\"\"\n def pytest_addoption(parser):\n parser.addoption('--test123', action=\"store_true\",\n default=True)\n \"\"\"\n )\n config.pluginmanager._importconftest(p)\n assert config.option.test123\n\n def test_configure(self, testdir):\n config = testdir.parseconfig()\n values = []\n\n class A(object):\n def pytest_configure(self, config):\n values.append(self)\n\n config.pluginmanager.register(A())\n assert len(values) == 0\n config._do_configure()\n assert len(values) == 1\n config.pluginmanager.register(A()) # leads to a configured() plugin\n assert len(values) == 2\n assert values[0] != values[1]\n\n config._ensure_unconfigure()\n config.pluginmanager.register(A())\n assert len(values) == 2\n\n def test_hook_tracing(self, _config_for_test):\n pytestpm = _config_for_test.pluginmanager # fully initialized with plugins\n saveindent = []\n\n class api1(object):\n def pytest_plugin_registered(self):\n saveindent.append(pytestpm.trace.root.indent)\n\n class api2(object):\n def pytest_plugin_registered(self):\n saveindent.append(pytestpm.trace.root.indent)\n raise ValueError()\n\n values = []\n pytestpm.trace.root.setwriter(values.append)\n undo = pytestpm.enable_tracing()\n try:\n indent = pytestpm.trace.root.indent\n p = api1()\n pytestpm.register(p)\n assert pytestpm.trace.root.indent == indent\n assert len(values) >= 2\n assert \"pytest_plugin_registered\" in values[0]\n assert \"finish\" in values[1]\n\n values[:] = []\n with pytest.raises(ValueError):\n pytestpm.register(api2())\n assert pytestpm.trace.root.indent == indent\n assert saveindent[0] > indent\n finally:\n undo()\n\n def test_hook_proxy(self, testdir):\n \"\"\"Test the gethookproxy function(#2016)\"\"\"\n config = testdir.parseconfig()\n session = Session(config)\n testdir.makepyfile(**{\"tests/conftest.py\": \"\", \"tests/subdir/conftest.py\": \"\"})\n\n conftest1 = testdir.tmpdir.join(\"tests/conftest.py\")\n conftest2 = testdir.tmpdir.join(\"tests/subdir/conftest.py\")\n\n config.pluginmanager._importconftest(conftest1)\n ihook_a = session.gethookproxy(testdir.tmpdir.join(\"tests\"))\n assert ihook_a is not None\n config.pluginmanager._importconftest(conftest2)\n ihook_b = session.gethookproxy(testdir.tmpdir.join(\"tests\"))\n assert ihook_a is not ihook_b\n\n\ndef test_default_markers(testdir):\n result = testdir.runpytest(\"--markers\")\n result.stdout.fnmatch_lines([\"*tryfirst*first*\", \"*trylast*last*\"])\n\n\ndef test_importplugin_error_message(testdir, pytestpm):\n \"\"\"Don't hide import errors when importing plugins and provide\n an easy to debug message.\n\n See #375 and #1998.\n \"\"\"\n testdir.syspathinsert(testdir.tmpdir)\n testdir.makepyfile(\n qwe=\"\"\"\n # -*- coding: utf-8 -*-\n def test_traceback():\n raise ImportError(u'Not possible to import: ☺')\n test_traceback()\n \"\"\"\n )\n with pytest.raises(ImportError) as excinfo:\n pytestpm.import_plugin(\"qwe\")\n\n assert str(excinfo.value).endswith(\n 'Error importing plugin \"qwe\": Not possible to import: ☺'\n )\n assert \"in test_traceback\" in str(excinfo.traceback[-1])\n\n\nclass TestPytestPluginManager(object):\n def test_register_imported_modules(self):\n pm = PytestPluginManager()\n mod = types.ModuleType(\"x.y.pytest_hello\")\n pm.register(mod)\n assert pm.is_registered(mod)\n values = pm.get_plugins()\n assert mod in values\n pytest.raises(ValueError, pm.register, mod)\n pytest.raises(ValueError, lambda: pm.register(mod))\n # assert not pm.is_registered(mod2)\n assert pm.get_plugins() == values\n\n def test_canonical_import(self, monkeypatch):\n mod = types.ModuleType(\"pytest_xyz\")\n monkeypatch.setitem(sys.modules, \"pytest_xyz\", mod)\n pm = PytestPluginManager()\n pm.import_plugin(\"pytest_xyz\")\n assert pm.get_plugin(\"pytest_xyz\") == mod\n assert pm.is_registered(mod)\n\n def test_consider_module(self, testdir, pytestpm):\n testdir.syspathinsert()\n testdir.makepyfile(pytest_p1=\"#\")\n testdir.makepyfile(pytest_p2=\"#\")\n mod = types.ModuleType(\"temp\")\n mod.pytest_plugins = [\"pytest_p1\", \"pytest_p2\"]\n pytestpm.consider_module(mod)\n assert pytestpm.get_plugin(\"pytest_p1\").__name__ == \"pytest_p1\"\n assert pytestpm.get_plugin(\"pytest_p2\").__name__ == \"pytest_p2\"\n\n def test_consider_module_import_module(self, testdir, _config_for_test):\n pytestpm = _config_for_test.pluginmanager\n mod = types.ModuleType(\"x\")\n mod.pytest_plugins = \"pytest_a\"\n aplugin = testdir.makepyfile(pytest_a=\"#\")\n reprec = testdir.make_hook_recorder(pytestpm)\n testdir.syspathinsert(aplugin.dirpath())\n pytestpm.consider_module(mod)\n call = reprec.getcall(pytestpm.hook.pytest_plugin_registered.name)\n assert call.plugin.__name__ == \"pytest_a\"\n\n # check that it is not registered twice\n pytestpm.consider_module(mod)\n values = reprec.getcalls(\"pytest_plugin_registered\")\n assert len(values) == 1\n\n def test_consider_env_fails_to_import(self, monkeypatch, pytestpm):\n monkeypatch.setenv(\"PYTEST_PLUGINS\", \"nonexisting\", prepend=\",\")\n with pytest.raises(ImportError):\n pytestpm.consider_env()\n\n @pytest.mark.filterwarnings(\"always\")\n def test_plugin_skip(self, testdir, monkeypatch):\n p = testdir.makepyfile(\n skipping1=\"\"\"\n import pytest\n pytest.skip(\"hello\", allow_module_level=True)\n \"\"\"\n )\n p.copy(p.dirpath(\"skipping2.py\"))\n monkeypatch.setenv(\"PYTEST_PLUGINS\", \"skipping2\")\n result = testdir.runpytest(\"-rw\", \"-p\", \"skipping1\", syspathinsert=True)\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result.stdout.fnmatch_lines(\n [\"*skipped plugin*skipping1*hello*\", \"*skipped plugin*skipping2*hello*\"]\n )\n\n def test_consider_env_plugin_instantiation(self, testdir, monkeypatch, pytestpm):\n testdir.syspathinsert()\n testdir.makepyfile(xy123=\"#\")\n monkeypatch.setitem(os.environ, \"PYTEST_PLUGINS\", \"xy123\")\n l1 = len(pytestpm.get_plugins())\n pytestpm.consider_env()\n l2 = len(pytestpm.get_plugins())\n assert l2 == l1 + 1\n assert pytestpm.get_plugin(\"xy123\")\n pytestpm.consider_env()\n l3 = len(pytestpm.get_plugins())\n assert l2 == l3\n\n def test_pluginmanager_ENV_startup(self, testdir, monkeypatch):\n testdir.makepyfile(pytest_x500=\"#\")\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_hello(pytestconfig):\n plugin = pytestconfig.pluginmanager.get_plugin('pytest_x500')\n assert plugin is not None\n \"\"\"\n )\n monkeypatch.setenv(\"PYTEST_PLUGINS\", \"pytest_x500\", prepend=\",\")\n result = testdir.runpytest(p, syspathinsert=True)\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_import_plugin_importname(self, testdir, pytestpm):\n pytest.raises(ImportError, pytestpm.import_plugin, \"qweqwex.y\")\n pytest.raises(ImportError, pytestpm.import_plugin, \"pytest_qweqwx.y\")\n\n testdir.syspathinsert()\n pluginname = \"pytest_hello\"\n testdir.makepyfile(**{pluginname: \"\"})\n pytestpm.import_plugin(\"pytest_hello\")\n len1 = len(pytestpm.get_plugins())\n pytestpm.import_plugin(\"pytest_hello\")\n len2 = len(pytestpm.get_plugins())\n assert len1 == len2\n plugin1 = pytestpm.get_plugin(\"pytest_hello\")\n assert plugin1.__name__.endswith(\"pytest_hello\")\n plugin2 = pytestpm.get_plugin(\"pytest_hello\")\n assert plugin2 is plugin1\n\n def test_import_plugin_dotted_name(self, testdir, pytestpm):\n pytest.raises(ImportError, pytestpm.import_plugin, \"qweqwex.y\")\n pytest.raises(ImportError, pytestpm.import_plugin, \"pytest_qweqwex.y\")\n\n testdir.syspathinsert()\n testdir.mkpydir(\"pkg\").join(\"plug.py\").write(\"x=3\")\n pluginname = \"pkg.plug\"\n pytestpm.import_plugin(pluginname)\n mod = pytestpm.get_plugin(\"pkg.plug\")\n assert mod.x == 3\n\n def test_consider_conftest_deps(self, testdir, pytestpm):\n mod = testdir.makepyfile(\"pytest_plugins='xyz'\").pyimport()\n with pytest.raises(ImportError):\n pytestpm.consider_conftest(mod)\n\n\nclass TestPytestPluginManagerBootstrapming(object):\n def test_preparse_args(self, pytestpm):\n pytest.raises(\n ImportError, lambda: pytestpm.consider_preparse([\"xyz\", \"-p\", \"hello123\"])\n )\n\n # Handles -p without space (#3532).\n with pytest.raises(ImportError) as excinfo:\n pytestpm.consider_preparse([\"-phello123\"])\n assert '\"hello123\"' in excinfo.value.args[0]\n pytestpm.consider_preparse([\"-pno:hello123\"])\n\n # Handles -p without following arg (when used without argparse).\n pytestpm.consider_preparse([\"-p\"])\n\n with pytest.raises(UsageError, match=\"^plugin main cannot be disabled$\"):\n pytestpm.consider_preparse([\"-p\", \"no:main\"])\n\n def test_plugin_prevent_register(self, pytestpm):\n pytestpm.consider_preparse([\"xyz\", \"-p\", \"no:abc\"])\n l1 = pytestpm.get_plugins()\n pytestpm.register(42, name=\"abc\")\n l2 = pytestpm.get_plugins()\n assert len(l2) == len(l1)\n assert 42 not in l2\n\n def test_plugin_prevent_register_unregistered_alredy_registered(self, pytestpm):\n pytestpm.register(42, name=\"abc\")\n l1 = pytestpm.get_plugins()\n assert 42 in l1\n pytestpm.consider_preparse([\"xyz\", \"-p\", \"no:abc\"])\n l2 = pytestpm.get_plugins()\n assert 42 not in l2\n\n def test_plugin_prevent_register_stepwise_on_cacheprovider_unregister(\n self, pytestpm\n ):\n \"\"\" From PR #4304 : The only way to unregister a module is documented at\n the end of https://docs.pytest.org/en/latest/plugins.html.\n\n When unregister cacheprovider, then unregister stepwise too\n \"\"\"\n pytestpm.register(42, name=\"cacheprovider\")\n pytestpm.register(43, name=\"stepwise\")\n l1 = pytestpm.get_plugins()\n assert 42 in l1\n assert 43 in l1\n pytestpm.consider_preparse([\"xyz\", \"-p\", \"no:cacheprovider\"])\n l2 = pytestpm.get_plugins()\n assert 42 not in l2\n assert 43 not in l2\n\n def test_blocked_plugin_can_be_used(self, pytestpm):\n pytestpm.consider_preparse([\"xyz\", \"-p\", \"no:abc\", \"-p\", \"abc\"])\n\n assert pytestpm.has_plugin(\"abc\")\n assert not pytestpm.is_blocked(\"abc\")\n assert not pytestpm.is_blocked(\"pytest_abc\")\n"},{"id":1304,"name":"setup-coverage-vars.bat","nodeType":"TextFile","path":"scripts","text":"if \"%PYTEST_COVERAGE%\" == \"1\" (\n set \"_PYTEST_TOX_COVERAGE_RUN=coverage run -m\"\n set \"_PYTEST_TOX_EXTRA_DEP=coverage-enable-subprocess\"\n echo Coverage vars configured, PYTEST_COVERAGE=%PYTEST_COVERAGE%\n) else (\n echo Skipping coverage vars setup, PYTEST_COVERAGE=%PYTEST_COVERAGE%\n)\n"},{"className":"PytestPluginManager","col":0,"comment":"\n Overwrites :py:class:`pluggy.PluginManager ` to add pytest-specific\n functionality:\n\n * loading plugins from the command line, ``PYTEST_PLUGINS`` env variable and\n ``pytest_plugins`` global variables found in plugins being loaded;\n * ``conftest.py`` loading during start-up;\n ","endLoc":586,"id":1305,"nodeType":"Class","startLoc":214,"text":"class PytestPluginManager(PluginManager):\n \"\"\"\n Overwrites :py:class:`pluggy.PluginManager ` to add pytest-specific\n functionality:\n\n * loading plugins from the command line, ``PYTEST_PLUGINS`` env variable and\n ``pytest_plugins`` global variables found in plugins being loaded;\n * ``conftest.py`` loading during start-up;\n \"\"\"\n\n def __init__(self):\n super(PytestPluginManager, self).__init__(\"pytest\")\n self._conftest_plugins = set()\n\n # state related to local conftest plugins\n self._dirpath2confmods = {}\n self._conftestpath2mod = {}\n self._confcutdir = None\n self._noconftest = False\n self._duplicatepaths = set()\n\n self.add_hookspecs(_pytest.hookspec)\n self.register(self)\n if os.environ.get(\"PYTEST_DEBUG\"):\n err = sys.stderr\n encoding = getattr(err, \"encoding\", \"utf8\")\n try:\n err = py.io.dupfile(err, encoding=encoding)\n except Exception:\n pass\n self.trace.root.setwriter(err.write)\n self.enable_tracing()\n\n # Config._consider_importhook will set a real object if required.\n self.rewrite_hook = _pytest.assertion.DummyRewriteHook()\n # Used to know when we are importing conftests after the pytest_configure stage\n self._configured = False\n\n def addhooks(self, module_or_class):\n \"\"\"\n .. deprecated:: 2.8\n\n Use :py:meth:`pluggy.PluginManager.add_hookspecs `\n instead.\n \"\"\"\n warnings.warn(deprecated.PLUGIN_MANAGER_ADDHOOKS, stacklevel=2)\n return self.add_hookspecs(module_or_class)\n\n def parse_hookimpl_opts(self, plugin, name):\n # pytest hooks are always prefixed with pytest_\n # so we avoid accessing possibly non-readable attributes\n # (see issue #1073)\n if not name.startswith(\"pytest_\"):\n return\n # ignore names which can not be hooks\n if name == \"pytest_plugins\":\n return\n\n method = getattr(plugin, name)\n opts = super(PytestPluginManager, self).parse_hookimpl_opts(plugin, name)\n\n # consider only actual functions for hooks (#3775)\n if not inspect.isroutine(method):\n return\n\n # collect unmarked hooks as long as they have the `pytest_' prefix\n if opts is None and name.startswith(\"pytest_\"):\n opts = {}\n if opts is not None:\n # TODO: DeprecationWarning, people should use hookimpl\n # https://github.com/pytest-dev/pytest/issues/4562\n known_marks = {m.name for m in getattr(method, \"pytestmark\", [])}\n\n for name in (\"tryfirst\", \"trylast\", \"optionalhook\", \"hookwrapper\"):\n opts.setdefault(name, hasattr(method, name) or name in known_marks)\n return opts\n\n def parse_hookspec_opts(self, module_or_class, name):\n opts = super(PytestPluginManager, self).parse_hookspec_opts(\n module_or_class, name\n )\n if opts is None:\n method = getattr(module_or_class, name)\n\n if name.startswith(\"pytest_\"):\n # todo: deprecate hookspec hacks\n # https://github.com/pytest-dev/pytest/issues/4562\n known_marks = {m.name for m in getattr(method, \"pytestmark\", [])}\n opts = {\n \"firstresult\": hasattr(method, \"firstresult\")\n or \"firstresult\" in known_marks,\n \"historic\": hasattr(method, \"historic\")\n or \"historic\" in known_marks,\n }\n return opts\n\n def register(self, plugin, name=None):\n if name in [\"pytest_catchlog\", \"pytest_capturelog\"]:\n warnings.warn(\n PytestConfigWarning(\n \"{} plugin has been merged into the core, \"\n \"please remove it from your requirements.\".format(\n name.replace(\"_\", \"-\")\n )\n )\n )\n return\n ret = super(PytestPluginManager, self).register(plugin, name)\n if ret:\n self.hook.pytest_plugin_registered.call_historic(\n kwargs=dict(plugin=plugin, manager=self)\n )\n\n if isinstance(plugin, types.ModuleType):\n self.consider_module(plugin)\n return ret\n\n def getplugin(self, name):\n # support deprecated naming because plugins (xdist e.g.) use it\n return self.get_plugin(name)\n\n def hasplugin(self, name):\n \"\"\"Return True if the plugin with the given name is registered.\"\"\"\n return bool(self.get_plugin(name))\n\n def pytest_configure(self, config):\n # XXX now that the pluginmanager exposes hookimpl(tryfirst...)\n # we should remove tryfirst/trylast as markers\n config.addinivalue_line(\n \"markers\",\n \"tryfirst: mark a hook implementation function such that the \"\n \"plugin machinery will try to call it first/as early as possible.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"trylast: mark a hook implementation function such that the \"\n \"plugin machinery will try to call it last/as late as possible.\",\n )\n self._configured = True\n\n #\n # internal API for local conftest plugin handling\n #\n def _set_initial_conftests(self, namespace):\n \"\"\" load initial conftest files given a preparsed \"namespace\".\n As conftest files may add their own command line options\n which have arguments ('--my-opt somepath') we might get some\n false positives. All builtin and 3rd party plugins will have\n been loaded, however, so common options will not confuse our logic\n here.\n \"\"\"\n current = py.path.local()\n self._confcutdir = (\n current.join(namespace.confcutdir, abs=True)\n if namespace.confcutdir\n else None\n )\n self._noconftest = namespace.noconftest\n self._using_pyargs = namespace.pyargs\n testpaths = namespace.file_or_dir\n foundanchor = False\n for path in testpaths:\n path = str(path)\n # remove node-id syntax\n i = path.find(\"::\")\n if i != -1:\n path = path[:i]\n anchor = current.join(path, abs=1)\n if exists(anchor): # we found some file object\n self._try_load_conftest(anchor)\n foundanchor = True\n if not foundanchor:\n self._try_load_conftest(current)\n\n def _try_load_conftest(self, anchor):\n self._getconftestmodules(anchor)\n # let's also consider test* subdirs\n if anchor.check(dir=1):\n for x in anchor.listdir(\"test*\"):\n if x.check(dir=1):\n self._getconftestmodules(x)\n\n @lru_cache(maxsize=128)\n def _getconftestmodules(self, path):\n if self._noconftest:\n return []\n\n if path.isfile():\n directory = path.dirpath()\n else:\n directory = path\n\n if six.PY2: # py2 is not using lru_cache.\n try:\n return self._dirpath2confmods[directory]\n except KeyError:\n pass\n\n # XXX these days we may rather want to use config.rootdir\n # and allow users to opt into looking into the rootdir parent\n # directories instead of requiring to specify confcutdir\n clist = []\n for parent in directory.realpath().parts():\n if self._confcutdir and self._confcutdir.relto(parent):\n continue\n conftestpath = parent.join(\"conftest.py\")\n if conftestpath.isfile():\n # Use realpath to avoid loading the same conftest twice\n # with build systems that create build directories containing\n # symlinks to actual files.\n mod = self._importconftest(conftestpath.realpath())\n clist.append(mod)\n self._dirpath2confmods[directory] = clist\n return clist\n\n def _rget_with_confmod(self, name, path):\n modules = self._getconftestmodules(path)\n for mod in reversed(modules):\n try:\n return mod, getattr(mod, name)\n except AttributeError:\n continue\n raise KeyError(name)\n\n def _importconftest(self, conftestpath):\n try:\n return self._conftestpath2mod[conftestpath]\n except KeyError:\n pkgpath = conftestpath.pypkgpath()\n if pkgpath is None:\n _ensure_removed_sysmodule(conftestpath.purebasename)\n try:\n mod = conftestpath.pyimport()\n if (\n hasattr(mod, \"pytest_plugins\")\n and self._configured\n and not self._using_pyargs\n ):\n from _pytest.deprecated import (\n PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST,\n )\n\n fail(\n PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST.format(\n conftestpath, self._confcutdir\n ),\n pytrace=False,\n )\n except Exception:\n raise ConftestImportFailure(conftestpath, sys.exc_info())\n\n self._conftest_plugins.add(mod)\n self._conftestpath2mod[conftestpath] = mod\n dirpath = conftestpath.dirpath()\n if dirpath in self._dirpath2confmods:\n for path, mods in self._dirpath2confmods.items():\n if path and path.relto(dirpath) or path == dirpath:\n assert mod not in mods\n mods.append(mod)\n self.trace(\"loaded conftestmodule %r\" % (mod))\n self.consider_conftest(mod)\n return mod\n\n #\n # API for bootstrapping plugin loading\n #\n #\n\n def consider_preparse(self, args):\n i = 0\n n = len(args)\n while i < n:\n opt = args[i]\n i += 1\n if isinstance(opt, six.string_types):\n if opt == \"-p\":\n try:\n parg = args[i]\n except IndexError:\n return\n i += 1\n elif opt.startswith(\"-p\"):\n parg = opt[2:]\n else:\n continue\n self.consider_pluginarg(parg)\n\n def consider_pluginarg(self, arg):\n if arg.startswith(\"no:\"):\n name = arg[3:]\n if name in essential_plugins:\n raise UsageError(\"plugin %s cannot be disabled\" % name)\n\n # PR #4304 : remove stepwise if cacheprovider is blocked\n if name == \"cacheprovider\":\n self.set_blocked(\"stepwise\")\n self.set_blocked(\"pytest_stepwise\")\n\n self.set_blocked(name)\n if not name.startswith(\"pytest_\"):\n self.set_blocked(\"pytest_\" + name)\n else:\n name = arg\n # Unblock the plugin. None indicates that it has been blocked.\n # There is no interface with pluggy for this.\n if self._name2plugin.get(name, -1) is None:\n del self._name2plugin[name]\n if not name.startswith(\"pytest_\"):\n if self._name2plugin.get(\"pytest_\" + name, -1) is None:\n del self._name2plugin[\"pytest_\" + name]\n self.import_plugin(arg, consider_entry_points=True)\n\n def consider_conftest(self, conftestmodule):\n self.register(conftestmodule, name=conftestmodule.__file__)\n\n def consider_env(self):\n self._import_plugin_specs(os.environ.get(\"PYTEST_PLUGINS\"))\n\n def consider_module(self, mod):\n self._import_plugin_specs(getattr(mod, \"pytest_plugins\", []))\n\n def _import_plugin_specs(self, spec):\n plugins = _get_plugin_specs_as_list(spec)\n for import_spec in plugins:\n self.import_plugin(import_spec)\n\n def import_plugin(self, modname, consider_entry_points=False):\n \"\"\"\n Imports a plugin with ``modname``. If ``consider_entry_points`` is True, entry point\n names are also considered to find a plugin.\n \"\"\"\n # most often modname refers to builtin modules, e.g. \"pytester\",\n # \"terminal\" or \"capture\". Those plugins are registered under their\n # basename for historic purposes but must be imported with the\n # _pytest prefix.\n assert isinstance(modname, six.string_types), (\n \"module name as text required, got %r\" % modname\n )\n modname = str(modname)\n if self.is_blocked(modname) or self.get_plugin(modname) is not None:\n return\n\n importspec = \"_pytest.\" + modname if modname in builtin_plugins else modname\n self.rewrite_hook.mark_rewrite(importspec)\n\n if consider_entry_points:\n loaded = self.load_setuptools_entrypoints(\"pytest11\", name=modname)\n if loaded:\n return\n\n try:\n __import__(importspec)\n except ImportError as e:\n new_exc_message = 'Error importing plugin \"%s\": %s' % (\n modname,\n safe_str(e.args[0]),\n )\n new_exc = ImportError(new_exc_message)\n tb = sys.exc_info()[2]\n\n six.reraise(ImportError, new_exc, tb)\n\n except Skipped as e:\n from _pytest.warnings import _issue_warning_captured\n\n _issue_warning_captured(\n PytestConfigWarning(\"skipped plugin %r: %s\" % (modname, e.msg)),\n self.hook,\n stacklevel=1,\n )\n else:\n mod = sys.modules[importspec]\n self.register(mod, modname)"},{"id":1306,"name":"release-2.5.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.5.2: fixes\n===========================================================================\n\npytest is a mature Python testing tool with more than a 1000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThe 2.5.2 release fixes a few bugs with two maybe-bugs remaining and\nactively being worked on (and waiting for the bug reporter's input).\nWe also have a new contribution guide thanks to Piotr Banaszkiewicz\nand others.\n\nSee docs at:\n\n http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n pip install -U pytest\n\nThanks to the following people who contributed to this release:\n\n Anatoly Bubenkov\n Ronny Pfannschmidt\n Floris Bruynooghe\n Bruno Oliveira\n Andreas Pelme\n Jurko Gospodnetić\n Piotr Banaszkiewicz\n Simon Liedtke\n lakka\n Lukasz Balcerzak\n Philippe Muller\n Daniel Hahler\n\nhave fun,\nholger krekel\n\n2.5.2\n-----------------------------------\n\n- fix issue409 -- better interoperate with cx_freeze by not\n trying to import from collections.abc which causes problems\n for py27/cx_freeze. Thanks Wolfgang L. for reporting and tracking it down.\n\n- fixed docs and code to use \"pytest\" instead of \"py.test\" almost everywhere.\n Thanks Jurko Gospodnetic for the complete PR.\n\n- fix issue425: mention at end of \"py.test -h\" that --markers\n and --fixtures work according to specified test path (or current dir)\n\n- fix issue413: exceptions with unicode attributes are now printed\n correctly also on python2 and with pytest-xdist runs. (the fix\n requires py-1.4.20)\n\n- copy, cleanup and integrate py.io capture\n from pylib 1.4.20.dev2 (rev 13d9af95547e)\n\n- address issue416: clarify docs as to conftest.py loading semantics\n\n- fix issue429: comparing byte strings with non-ascii chars in assert\n expressions now work better. Thanks Floris Bruynooghe.\n\n- make capfd/capsys.capture private, its unused and shouldn't be exposed\n"},{"id":1307,"name":"special.rst","nodeType":"TextFile","path":"doc/en/example","text":"A session-fixture which can look at all collected tests\n----------------------------------------------------------------\n\nA session-scoped fixture effectively has access to all\ncollected test items. Here is an example of a fixture\nfunction which walks all collected tests and looks\nif their test class defines a ``callme`` method and\ncalls it::\n\n # content of conftest.py\n\n import pytest\n\n @pytest.fixture(scope=\"session\", autouse=True)\n def callattr_ahead_of_alltests(request):\n print(\"callattr_ahead_of_alltests called\")\n seen = set([None])\n session = request.node\n for item in session.items:\n cls = item.getparent(pytest.Class)\n if cls not in seen:\n if hasattr(cls.obj, \"callme\"):\n cls.obj.callme()\n seen.add(cls)\n\ntest classes may now define a ``callme`` method which\nwill be called ahead of running any tests::\n\n # content of test_module.py\n\n class TestHello(object):\n @classmethod\n def callme(cls):\n print(\"callme called!\")\n\n def test_method1(self):\n print(\"test_method1 called\")\n\n def test_method2(self):\n print(\"test_method1 called\")\n\n class TestOther(object):\n @classmethod\n def callme(cls):\n print(\"callme other called\")\n def test_other(self):\n print(\"test other\")\n\n # works with unittest as well ...\n import unittest\n\n class SomeTest(unittest.TestCase):\n @classmethod\n def callme(self):\n print(\"SomeTest callme called\")\n\n def test_unit1(self):\n print(\"test_unit1 method called\")\n\nIf you run this without output capturing:\n\n.. code-block:: pytest\n\n $ pytest -q -s test_module.py\n callattr_ahead_of_alltests called\n callme called!\n callme other called\n SomeTest callme called\n test_method1 called\n .test_method1 called\n .test other\n .test_unit1 method called\n .\n 4 passed in 0.12 seconds\n"},{"col":4,"comment":"\n .. deprecated:: 2.8\n\n Use :py:meth:`pluggy.PluginManager.add_hookspecs `\n instead.\n ","endLoc":260,"header":"def addhooks(self, module_or_class)","id":1308,"name":"addhooks","nodeType":"Function","startLoc":252,"text":"def addhooks(self, module_or_class):\n \"\"\"\n .. deprecated:: 2.8\n\n Use :py:meth:`pluggy.PluginManager.add_hookspecs `\n instead.\n \"\"\"\n warnings.warn(deprecated.PLUGIN_MANAGER_ADDHOOKS, stacklevel=2)\n return self.add_hookspecs(module_or_class)"},{"id":1309,"name":"release-3.0.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.0.0\n============\n\nThe pytest team is proud to announce the 3.0.0 release!\n\npytest is a mature Python testing tool with more than a 1600 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a lot of bugs fixes and improvements, and much of\nthe work done on it was possible because of the 2016 Sprint[1], which\nwas funded by an indiegogo campaign which raised over US$12,000 with\nnearly 100 backers.\n\nThere's a \"What's new in pytest 3.0\" [2] blog post highlighting the\nmajor features in this release.\n\nTo see the complete changelog and documentation, please visit:\n\n http://docs.pytest.org\n\nAs usual, you can upgrade from pypi via:\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n AbdealiJK\n Ana Ribeiro\n Antony Lee\n Brandon W Maister\n Brianna Laugher\n Bruno Oliveira\n Ceridwen\n Christian Boelsen\n Daniel Hahler\n Danielle Jenkins\n Dave Hunt\n Diego Russo\n Dmitry Dygalo\n Edoardo Batini\n Eli Boyarski\n Florian Bruhin\n Floris Bruynooghe\n Greg Price\n Guyzmo\n HEAD KANGAROO\n JJ\n Javi Romero\n Javier Domingo Cansino\n Kale Kundert\n Kalle Bronsen\n Marius Gedminas\n Matt Williams\n Mike Lundy\n Oliver Bestwalter\n Omar Kohl\n Raphael Pierzina\n RedBeardCode\n Roberto Polli\n Romain Dorgueil\n Roman Bolshakov\n Ronny Pfannschmidt\n Stefan Zimmermann\n Steffen Allner\n Tareq Alayan\n Ted Xiao\n Thomas Grainger\n Tom Viner\n TomV\n Vasily Kuznetsov\n aostr\n marscher\n palaviv\n satoru\n taschini\n\n\nHappy testing,\nThe Pytest Development Team\n\n[1] http://blog.pytest.org/2016/pytest-development-sprint/\n[2] http://blog.pytest.org/2016/whats-new-in-pytest-30/\n"},{"id":1310,"name":"flaky.rst","nodeType":"TextFile","path":"doc/en","text":"\nFlaky tests\n-----------\n\nA \"flaky\" test is one that exhibits intermittent or sporadic failure, that seems to have non-deterministic behaviour. Sometimes it passes, sometimes it fails, and it's not clear why. This page discusses pytest features that can help and other general strategies for identifying, fixing or mitigating them.\n\nWhy flaky tests are a problem\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nFlaky tests are particularly troublesome when a continuous integration (CI) server is being used, so that all tests must pass before a new code change can be merged. If the test result is not a reliable signal -- that a test failure means the code change broke the test -- developers can become mistrustful of the test results, which can lead to overlooking genuine failures. It is also a source of wasted time as developers must re-run test suites and investigate spurious failures.\n\n\nPotential root causes\n^^^^^^^^^^^^^^^^^^^^^\n\nSystem state\n~~~~~~~~~~~~\n\nBroadly speaking, a flaky test indicates that the test relies on some system state that is not being appropriately controlled - the test environment is not sufficiently isolated. Higher level tests are more likely to be flaky as they rely on more state.\n\nFlaky tests sometimes appear when a test suite is run in parallel (such as use of pytest-xdist). This can indicate a test is reliant on test ordering.\n\n- Perhaps a different test is failing to clean up after itself and leaving behind data which causes the flaky test to fail.\n- The flaky test is reliant on data from a previous test that doesn't clean up after itself, and in parallel runs that previous test is not always present\n- Tests that modify global state typically cannot be run in parallel.\n\n\nOverly strict assertion\n~~~~~~~~~~~~~~~~~~~~~~~\n\nOverly strict assertions can cause problems with floating point comparison as well as timing issues. `pytest.approx `_ is useful here.\n\n\nPytest features\n^^^^^^^^^^^^^^^\n\nXfail strict\n~~~~~~~~~~~~\n\n:ref:`pytest.mark.xfail ref` with ``strict=False`` can be used to mark a test so that its failure does not cause the whole build to break. This could be considered like a manual quarantine, and is rather dangerous to use permanently.\n\n\nPYTEST_CURRENT_TEST\n~~~~~~~~~~~~~~~~~~~\n\n:ref:`pytest current test env` may be useful for figuring out \"which test got stuck\".\n\n\nPlugins\n~~~~~~~\n\nRerunning any failed tests can mitigate the negative effects of flaky tests by giving them additional chances to pass, so that the overall build does not fail. Several pytest plugins support this:\n\n* `flaky `_\n* `pytest-flakefinder `_ - `blog post `_\n* `pytest-rerunfailures `_\n* `pytest-replay `_: This plugin helps to reproduce locally crashes or flaky tests observed during CI runs.\n\nPlugins to deliberately randomize tests can help expose tests with state problems:\n\n* `pytest-random-order `_\n* `pytest-randomly `_\n\n\nOther general strategies\n^^^^^^^^^^^^^^^^^^^^^^^^\n\nSplit up test suites\n~~~~~~~~~~~~~~~~~~~~\n\nIt can be common to split a single test suite into two, such as unit vs integration, and only use the unit test suite as a CI gate. This also helps keep build times manageable as high level tests tend to be slower. However, it means it does become possible for code that breaks the build to be merged, so extra vigilance is needed for monitoring the integration test results.\n\n\nVideo/screenshot on failure\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nFor UI tests these are important for understanding what the state of the UI was when the test failed. pytest-splinter can be used with plugins like pytest-bdd and can `save a screenshot on test failure `_, which can help to isolate the cause.\n\n\nDelete or rewrite the test\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf the functionality is covered by other tests, perhaps the test can be removed. If not, perhaps it can be rewritten at a lower level which will remove the flakiness or make its source more apparent.\n\n\nQuarantine\n~~~~~~~~~~\n\nMark Lapierre discusses the `Pros and Cons of Quarantined Tests `_ in a post from 2018.\n\n\n\nCI tools that rerun on failure\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAzure Pipelines (the Azure cloud CI/CD tool, formerly Visual Studio Team Services or VSTS) has a feature to `identify flaky tests `_ and rerun failed tests.\n\n\n\nResearch\n^^^^^^^^\n\nThis is a limited list, please submit an issue or pull request to expand it!\n\n* Gao, Zebao, Yalan Liang, Myra B. Cohen, Atif M. Memon, and Zhen Wang. \"Making system user interactive tests repeatable: When and what should we control?.\" In *Software Engineering (ICSE), 2015 IEEE/ACM 37th IEEE International Conference on*, vol. 1, pp. 55-65. IEEE, 2015. `PDF `__\n* Palomba, Fabio, and Andy Zaidman. \"Does refactoring of test smells induce fixing flaky tests?.\" In *Software Maintenance and Evolution (ICSME), 2017 IEEE International Conference on*, pp. 1-12. IEEE, 2017. `PDF in Google Drive `__\n* Bell, Jonathan, Owolabi Legunsen, Michael Hilton, Lamyaa Eloussi, Tifany Yung, and Darko Marinov. \"DeFlaker: Automatically detecting flaky tests.\" In *Proceedings of the 2018 International Conference on Software Engineering*. 2018. `PDF `__\n\n\nResources\n^^^^^^^^^\n\n* `Eradicating Non-Determinism in Tests `_ by Martin Fowler, 2011\n* `No more flaky tests on the Go team `_ by Pavan Sudarshan, 2012\n* `The Build That Cried Broken: Building Trust in your Continuous Integration Tests `_ talk (video) by `Angie Jones `_ at SeleniumConf Austin 2017\n* `Test and Code Podcast: Flaky Tests and How to Deal with Them `_ by Brian Okken and Anthony Shaw, 2018\n* Microsoft:\n\n * `How we approach testing VSTS to enable continuous delivery `_ by Brian Harry MS, 2017\n * `Eliminating Flaky Tests `_ blog and talk (video) by Munil Shah, 2017\n\n* Google:\n\n * `Flaky Tests at Google and How We Mitigate Them `_ by John Micco, 2016\n * `Where do Google's flaky tests come from? `_ by Jeff Listfield, 2017\n"},{"col":0,"comment":"null","endLoc":135,"header":"def test_code_getargs()","id":1311,"name":"test_code_getargs","nodeType":"Function","startLoc":112,"text":"def test_code_getargs():\n def f1(x):\n raise NotImplementedError()\n\n c1 = _pytest._code.Code(f1)\n assert c1.getargs(var=True) == (\"x\",)\n\n def f2(x, *y):\n raise NotImplementedError()\n\n c2 = _pytest._code.Code(f2)\n assert c2.getargs(var=True) == (\"x\", \"y\")\n\n def f3(x, **z):\n raise NotImplementedError()\n\n c3 = _pytest._code.Code(f3)\n assert c3.getargs(var=True) == (\"x\", \"z\")\n\n def f4(x, *y, **z):\n raise NotImplementedError()\n\n c4 = _pytest._code.Code(f4)\n assert c4.getargs(var=True) == (\"x\", \"y\", \"z\")"},{"col":4,"comment":"null","endLoc":289,"header":"def parse_hookimpl_opts(self, plugin, name)","id":1312,"name":"parse_hookimpl_opts","nodeType":"Function","startLoc":262,"text":"def parse_hookimpl_opts(self, plugin, name):\n # pytest hooks are always prefixed with pytest_\n # so we avoid accessing possibly non-readable attributes\n # (see issue #1073)\n if not name.startswith(\"pytest_\"):\n return\n # ignore names which can not be hooks\n if name == \"pytest_plugins\":\n return\n\n method = getattr(plugin, name)\n opts = super(PytestPluginManager, self).parse_hookimpl_opts(plugin, name)\n\n # consider only actual functions for hooks (#3775)\n if not inspect.isroutine(method):\n return\n\n # collect unmarked hooks as long as they have the `pytest_' prefix\n if opts is None and name.startswith(\"pytest_\"):\n opts = {}\n if opts is not None:\n # TODO: DeprecationWarning, people should use hookimpl\n # https://github.com/pytest-dev/pytest/issues/4562\n known_marks = {m.name for m in getattr(method, \"pytestmark\", [])}\n\n for name in (\"tryfirst\", \"trylast\", \"optionalhook\", \"hookwrapper\"):\n opts.setdefault(name, hasattr(method, name) or name in known_marks)\n return opts"},{"col":0,"comment":"null","endLoc":89,"header":"def expanduser(path: PathLike[AnyStr] | AnyStr) -> AnyStr","id":1313,"name":"expanduser","nodeType":"Function","startLoc":89,"text":"def expanduser(path: PathLike[AnyStr] | AnyStr) -> AnyStr: ..."},{"col":4,"comment":"null","endLoc":514,"header":"def finalize(self, report)","id":1317,"name":"finalize","nodeType":"Function","startLoc":508,"text":"def finalize(self, report):\n nodeid = getattr(report, \"nodeid\", report)\n # local hack to handle xdist report order\n slavenode = getattr(report, \"node\", None)\n reporter = self.node_reporters.pop((nodeid, slavenode))\n if reporter is not None:\n reporter.finalize()"},{"col":4,"comment":" return a tuple with the argument names for the code object\n\n if 'var' is set True also return the names of the variable and\n keyword arguments when present\n ","endLoc":100,"header":"def getargs(self, var=False)","id":1318,"name":"getargs","nodeType":"Function","startLoc":88,"text":"def getargs(self, var=False):\n \"\"\" return a tuple with the argument names for the code object\n\n if 'var' is set True also return the names of the variable and\n keyword arguments when present\n \"\"\"\n # handfull shortcut for getting args\n raw = self.raw\n argcount = raw.co_argcount\n if var:\n argcount += raw.co_flags & CO_VARARGS\n argcount += raw.co_flags & CO_VARKEYWORDS\n return raw.co_varnames[:argcount]"},{"col":4,"comment":"null","endLoc":153,"header":"def test_reasonable_defaults(self)","id":1319,"name":"test_reasonable_defaults","nodeType":"Function","startLoc":150,"text":"def test_reasonable_defaults(self):\n # Whatever the defaults are, they should work for numbers close to 1\n # than have a small amount of floating-point error.\n assert 0.1 + 0.2 == approx(0.3)"},{"col":4,"comment":"null","endLoc":172,"header":"def test_default_tolerances(self)","id":1320,"name":"test_default_tolerances","nodeType":"Function","startLoc":155,"text":"def test_default_tolerances(self):\n # This tests the defaults as they are currently set. If you change the\n # defaults, this test will fail but you should feel free to change it.\n # None of the other tests (except the doctests) should be affected by\n # the choice of defaults.\n examples = [\n # Relative tolerance used.\n (eq, 1e100 + 1e94, 1e100),\n (ne, 1e100 + 2e94, 1e100),\n (eq, 1e0 + 1e-6, 1e0),\n (ne, 1e0 + 2e-6, 1e0),\n # Absolute tolerance used.\n (eq, 1e-100, +1e-106),\n (eq, 1e-100, +2e-106),\n (eq, 1e-100, 0),\n ]\n for op, a, x in examples:\n assert op(a, approx(x))"},{"col":0,"comment":"null","endLoc":161,"header":"def test_frame_getargs()","id":1322,"name":"test_frame_getargs","nodeType":"Function","startLoc":138,"text":"def test_frame_getargs():\n def f1(x):\n return sys._getframe(0)\n\n fr1 = _pytest._code.Frame(f1(\"a\"))\n assert fr1.getargs(var=True) == [(\"x\", \"a\")]\n\n def f2(x, *y):\n return sys._getframe(0)\n\n fr2 = _pytest._code.Frame(f2(\"a\", \"b\", \"c\"))\n assert fr2.getargs(var=True) == [(\"x\", \"a\"), (\"y\", (\"b\", \"c\"))]\n\n def f3(x, **z):\n return sys._getframe(0)\n\n fr3 = _pytest._code.Frame(f3(\"a\", b=\"c\"))\n assert fr3.getargs(var=True) == [(\"x\", \"a\"), (\"z\", {\"b\": \"c\"})]\n\n def f4(x, *y, **z):\n return sys._getframe(0)\n\n fr4 = _pytest._code.Frame(f4(\"a\", \"b\", c=\"d\"))\n assert fr4.getargs(var=True) == [(\"x\", \"a\"), (\"y\", (\"b\",)), (\"z\", {\"c\": \"d\"})]"},{"col":4,"comment":"null","endLoc":308,"header":"def parse_hookspec_opts(self, module_or_class, name)","id":1325,"name":"parse_hookspec_opts","nodeType":"Function","startLoc":291,"text":"def parse_hookspec_opts(self, module_or_class, name):\n opts = super(PytestPluginManager, self).parse_hookspec_opts(\n module_or_class, name\n )\n if opts is None:\n method = getattr(module_or_class, name)\n\n if name.startswith(\"pytest_\"):\n # todo: deprecate hookspec hacks\n # https://github.com/pytest-dev/pytest/issues/4562\n known_marks = {m.name for m in getattr(method, \"pytestmark\", [])}\n opts = {\n \"firstresult\": hasattr(method, \"firstresult\")\n or \"firstresult\" in known_marks,\n \"historic\": hasattr(method, \"historic\")\n or \"historic\" in known_marks,\n }\n return opts"},{"col":4,"comment":" return a list of tuples (name, value) for all arguments\n\n if 'var' is set True also include the variable and keyword\n arguments when present\n ","endLoc":163,"header":"def getargs(self, var=False)","id":1326,"name":"getargs","nodeType":"Function","startLoc":151,"text":"def getargs(self, var=False):\n \"\"\" return a list of tuples (name, value) for all arguments\n\n if 'var' is set True also include the variable and keyword\n arguments when present\n \"\"\"\n retval = []\n for arg in self.code.getargs(var):\n try:\n retval.append((arg, self.f_locals[arg]))\n except KeyError:\n pass # this can occur when using Psyco\n return retval"},{"col":4,"comment":"null","endLoc":656,"header":"def _collectfile(self, path, handle_dupes=True)","id":1328,"name":"_collectfile","nodeType":"Function","startLoc":635,"text":"def _collectfile(self, path, handle_dupes=True):\n assert path.isfile(), \"%r is not a file (isdir=%r, exists=%r, islink=%r)\" % (\n path,\n path.isdir(),\n path.exists(),\n path.islink(),\n )\n ihook = self.gethookproxy(path)\n if not self.isinitpath(path):\n if ihook.pytest_ignore_collect(path=path, config=self.config):\n return ()\n\n if handle_dupes:\n keepduplicates = self.config.getoption(\"keepduplicates\")\n if not keepduplicates:\n duplicate_paths = self.config.pluginmanager._duplicatepaths\n if path in duplicate_paths:\n return ()\n else:\n duplicate_paths.add(path)\n\n return ihook.pytest_collect_file(path=path, parent=self)"},{"col":4,"comment":"null","endLoc":333,"header":"def getplugin(self, name)","id":1330,"name":"getplugin","nodeType":"Function","startLoc":331,"text":"def getplugin(self, name):\n # support deprecated naming because plugins (xdist e.g.) use it\n return self.get_plugin(name)"},{"col":4,"comment":"Return True if the plugin with the given name is registered.","endLoc":337,"header":"def hasplugin(self, name)","id":1331,"name":"hasplugin","nodeType":"Function","startLoc":335,"text":"def hasplugin(self, name):\n \"\"\"Return True if the plugin with the given name is registered.\"\"\"\n return bool(self.get_plugin(name))"},{"attributeType":"null","col":28,"comment":"null","endLoc":17,"id":1333,"name":"mock","nodeType":"Attribute","startLoc":17,"text":"mock"},{"col":0,"comment":"","endLoc":2,"header":"test_code.py#","id":1334,"name":"","nodeType":"Function","startLoc":2,"text":"try:\n import mock\nexcept ImportError:\n import unittest.mock as mock"},{"col":4,"comment":"null","endLoc":352,"header":"def pytest_configure(self, config)","id":1336,"name":"pytest_configure","nodeType":"Function","startLoc":339,"text":"def pytest_configure(self, config):\n # XXX now that the pluginmanager exposes hookimpl(tryfirst...)\n # we should remove tryfirst/trylast as markers\n config.addinivalue_line(\n \"markers\",\n \"tryfirst: mark a hook implementation function such that the \"\n \"plugin machinery will try to call it first/as early as possible.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"trylast: mark a hook implementation function such that the \"\n \"plugin machinery will try to call it last/as late as possible.\",\n )\n self._configured = True"},{"col":4,"comment":" load initial conftest files given a preparsed \"namespace\".\n As conftest files may add their own command line options\n which have arguments ('--my-opt somepath') we might get some\n false positives. All builtin and 3rd party plugins will have\n been loaded, however, so common options will not confuse our logic\n here.\n ","endLoc":386,"header":"def _set_initial_conftests(self, namespace)","id":1337,"name":"_set_initial_conftests","nodeType":"Function","startLoc":357,"text":"def _set_initial_conftests(self, namespace):\n \"\"\" load initial conftest files given a preparsed \"namespace\".\n As conftest files may add their own command line options\n which have arguments ('--my-opt somepath') we might get some\n false positives. All builtin and 3rd party plugins will have\n been loaded, however, so common options will not confuse our logic\n here.\n \"\"\"\n current = py.path.local()\n self._confcutdir = (\n current.join(namespace.confcutdir, abs=True)\n if namespace.confcutdir\n else None\n )\n self._noconftest = namespace.noconftest\n self._using_pyargs = namespace.pyargs\n testpaths = namespace.file_or_dir\n foundanchor = False\n for path in testpaths:\n path = str(path)\n # remove node-id syntax\n i = path.find(\"::\")\n if i != -1:\n path = path[:i]\n anchor = current.join(path, abs=1)\n if exists(anchor): # we found some file object\n self._try_load_conftest(anchor)\n foundanchor = True\n if not foundanchor:\n self._try_load_conftest(current)"},{"col":4,"comment":"null","endLoc":188,"header":"def test_custom_tolerances(self)","id":1338,"name":"test_custom_tolerances","nodeType":"Function","startLoc":174,"text":"def test_custom_tolerances(self):\n assert 1e8 + 1e0 == approx(1e8, rel=5e-8, abs=5e0)\n assert 1e8 + 1e0 == approx(1e8, rel=5e-9, abs=5e0)\n assert 1e8 + 1e0 == approx(1e8, rel=5e-8, abs=5e-1)\n assert 1e8 + 1e0 != approx(1e8, rel=5e-9, abs=5e-1)\n\n assert 1e0 + 1e-8 == approx(1e0, rel=5e-8, abs=5e-8)\n assert 1e0 + 1e-8 == approx(1e0, rel=5e-9, abs=5e-8)\n assert 1e0 + 1e-8 == approx(1e0, rel=5e-8, abs=5e-9)\n assert 1e0 + 1e-8 != approx(1e0, rel=5e-9, abs=5e-9)\n\n assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-8, abs=5e-16)\n assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-9, abs=5e-16)\n assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-8, abs=5e-17)\n assert 1e-8 + 1e-16 != approx(1e-8, rel=5e-9, abs=5e-17)"},{"col":4,"comment":"null","endLoc":194,"header":"def test_relative_tolerance(self)","id":1339,"name":"test_relative_tolerance","nodeType":"Function","startLoc":190,"text":"def test_relative_tolerance(self):\n within_1e8_rel = [(1e8 + 1e0, 1e8), (1e0 + 1e-8, 1e0), (1e-8 + 1e-16, 1e-8)]\n for a, x in within_1e8_rel:\n assert a == approx(x, rel=5e-8, abs=0.0)\n assert a != approx(x, rel=5e-9, abs=0.0)"},{"col":4,"comment":"null","endLoc":200,"header":"def test_absolute_tolerance(self)","id":1340,"name":"test_absolute_tolerance","nodeType":"Function","startLoc":196,"text":"def test_absolute_tolerance(self):\n within_1e8_abs = [(1e8 + 9e-9, 1e8), (1e0 + 9e-9, 1e0), (1e-8 + 9e-9, 1e-8)]\n for a, x in within_1e8_abs:\n assert a == approx(x, rel=0, abs=5e-8)\n assert a != approx(x, rel=0, abs=5e-9)"},{"col":4,"comment":"null","endLoc":215,"header":"def test_expecting_zero(self)","id":1341,"name":"test_expecting_zero","nodeType":"Function","startLoc":202,"text":"def test_expecting_zero(self):\n examples = [\n (ne, 1e-6, 0.0),\n (ne, -1e-6, 0.0),\n (eq, 1e-12, 0.0),\n (eq, -1e-12, 0.0),\n (ne, 2e-12, 0.0),\n (ne, -2e-12, 0.0),\n (ne, inf, 0.0),\n (ne, nan, 0.0),\n ]\n for op, a, x in examples:\n assert op(a, approx(x, rel=0.0, abs=1e-12))\n assert op(a, approx(x, rel=1e-6, abs=1e-12))"},{"col":4,"comment":"null","endLoc":226,"header":"def test_expecting_inf(self)","id":1342,"name":"test_expecting_inf","nodeType":"Function","startLoc":217,"text":"def test_expecting_inf(self):\n examples = [\n (eq, inf, inf),\n (eq, -inf, -inf),\n (ne, inf, -inf),\n (ne, 0.0, inf),\n (ne, nan, inf),\n ]\n for op, a, x in examples:\n assert op(a, approx(x))"},{"col":0,"comment":"Ensure that 'set_level' is undone after the end of the test","endLoc":50,"header":"def test_change_level_undo(testdir)","id":1344,"name":"test_change_level_undo","nodeType":"Function","startLoc":30,"text":"def test_change_level_undo(testdir):\n \"\"\"Ensure that 'set_level' is undone after the end of the test\"\"\"\n testdir.makepyfile(\n \"\"\"\n import logging\n\n def test1(caplog):\n caplog.set_level(logging.INFO)\n # using + operator here so fnmatch_lines doesn't match the code in the traceback\n logging.info('log from ' + 'test1')\n assert 0\n\n def test2(caplog):\n # using + operator here so fnmatch_lines doesn't match the code in the traceback\n logging.info('log from ' + 'test2')\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*log from test1*\", \"*2 failed in *\"])\n assert \"log from test2\" not in result.stdout.str()"},{"col":0,"comment":"null","endLoc":65,"header":"def test_with_statement(caplog)","id":1345,"name":"test_with_statement","nodeType":"Function","startLoc":53,"text":"def test_with_statement(caplog):\n with caplog.at_level(logging.INFO):\n logger.debug(\"handler DEBUG level\")\n logger.info(\"handler INFO level\")\n\n with caplog.at_level(logging.CRITICAL, logger=sublogger.name):\n sublogger.warning(\"logger WARNING level\")\n sublogger.critical(\"logger CRITICAL level\")\n\n assert \"DEBUG\" not in caplog.text\n assert \"INFO\" in caplog.text\n assert \"WARNING\" not in caplog.text\n assert \"CRITICAL\" in caplog.text"},{"col":0,"comment":"null","endLoc":73,"header":"def test_log_access(caplog)","id":1346,"name":"test_log_access","nodeType":"Function","startLoc":68,"text":"def test_log_access(caplog):\n caplog.set_level(logging.INFO)\n logger.info(\"boo %s\", \"arg\")\n assert caplog.records[0].levelname == \"INFO\"\n assert caplog.records[0].msg == \"boo %s\"\n assert \"boo arg\" in caplog.text"},{"col":0,"comment":"null","endLoc":94,"header":"def test_messages(caplog)","id":1347,"name":"test_messages","nodeType":"Function","startLoc":76,"text":"def test_messages(caplog):\n caplog.set_level(logging.INFO)\n logger.info(\"boo %s\", \"arg\")\n logger.info(\"bar %s\\nbaz %s\", \"arg1\", \"arg2\")\n assert \"boo arg\" == caplog.messages[0]\n assert \"bar arg1\\nbaz arg2\" == caplog.messages[1]\n assert caplog.text.count(\"\\n\") > len(caplog.messages)\n assert len(caplog.text.splitlines()) > len(caplog.messages)\n\n try:\n raise Exception(\"test\")\n except Exception:\n logger.exception(\"oops\")\n\n assert \"oops\" in caplog.text\n assert \"oops\" in caplog.messages[-1]\n # Tracebacks are stored in the record and not added until the formatter or handler.\n assert \"Exception\" in caplog.text\n assert \"Exception\" not in caplog.messages[-1]"},{"col":4,"comment":"null","endLoc":729,"header":"def matchnodes(self, matching, names)","id":1348,"name":"matchnodes","nodeType":"Function","startLoc":720,"text":"def matchnodes(self, matching, names):\n self.trace(\"matchnodes\", matching, names)\n self.trace.root.indent += 1\n nodes = self._matchnodes(matching, names)\n num = len(nodes)\n self.trace(\"matchnodes finished -> \", num, \"nodes\")\n self.trace.root.indent -= 1\n if num == 0:\n raise NoMatch(matching, names[:1])\n return nodes"},{"col":4,"comment":"null","endLoc":766,"header":"def _matchnodes(self, matching, names)","id":1349,"name":"_matchnodes","nodeType":"Function","startLoc":731,"text":"def _matchnodes(self, matching, names):\n if not matching or not names:\n return matching\n name = names[0]\n assert name\n nextnames = names[1:]\n resultnodes = []\n for node in matching:\n if isinstance(node, nodes.Item):\n if not names:\n resultnodes.append(node)\n continue\n assert isinstance(node, nodes.Collector)\n key = (type(node), node.nodeid)\n if key in self._node_cache:\n rep = self._node_cache[key]\n else:\n rep = collect_one_node(node)\n self._node_cache[key] = rep\n if rep.passed:\n has_matched = False\n for x in rep.result:\n # TODO: remove parametrized workaround once collection structure contains parametrization\n if x.name == name or x.name.split(\"[\")[0] == name:\n resultnodes.extend(self.matchnodes([x], nextnames))\n has_matched = True\n # XXX accept IDs that don't have \"()\" for class instances\n if not has_matched and len(rep.result) == 1 and x.name == \"()\":\n nextnames.insert(0, name)\n resultnodes.extend(self.matchnodes([x], nextnames))\n else:\n # report collection failures here to avoid failing to run some test\n # specified in the command line because the module could not be\n # imported (#134)\n node.ihook.pytest_collectreport(report=rep)\n return resultnodes"},{"col":4,"comment":"null","endLoc":532,"header":"def node_reporter(self, report)","id":1350,"name":"node_reporter","nodeType":"Function","startLoc":516,"text":"def node_reporter(self, report):\n nodeid = getattr(report, \"nodeid\", report)\n # local hack to handle xdist report order\n slavenode = getattr(report, \"node\", None)\n\n key = nodeid, slavenode\n\n if key in self.node_reporters:\n # TODO: breasks for --dist=each\n return self.node_reporters[key]\n\n reporter = _NodeReporter(nodeid, self)\n\n self.node_reporters[key] = reporter\n self.node_reporters_ordered.append(reporter)\n\n return reporter"},{"col":4,"comment":"null","endLoc":536,"header":"def add_stats(self, key)","id":1351,"name":"add_stats","nodeType":"Function","startLoc":534,"text":"def add_stats(self, key):\n if key in self.stats:\n self.stats[key] += 1"},{"col":4,"comment":"null","endLoc":541,"header":"def _opentestcase(self, report)","id":1352,"name":"_opentestcase","nodeType":"Function","startLoc":538,"text":"def _opentestcase(self, report):\n reporter = self.node_reporter(report)\n reporter.record_testreport(report)\n return reporter"},{"col":4,"comment":"null","endLoc":241,"header":"def test_expecting_nan(self)","id":1353,"name":"test_expecting_nan","nodeType":"Function","startLoc":228,"text":"def test_expecting_nan(self):\n examples = [\n (eq, nan, nan),\n (eq, -nan, -nan),\n (eq, nan, -nan),\n (ne, 0.0, nan),\n (ne, inf, nan),\n ]\n for op, a, x in examples:\n # Nothing is equal to NaN by default.\n assert a != approx(x)\n\n # If ``nan_ok=True``, then NaN is equal to NaN.\n assert op(a, approx(x, nan_ok=True))"},{"col":4,"comment":"handle a setup/call/teardown report, generating the appropriate\n xml tags as necessary.\n\n note: due to plugins like xdist, this hook may be called in interlaced\n order with reports from other nodes. for example:\n\n usual call order:\n -> setup node1\n -> call node1\n -> teardown node1\n -> setup node2\n -> call node2\n -> teardown node2\n\n possible call order in xdist:\n -> setup node1\n -> call node1\n -> setup node2\n -> call node2\n -> teardown node2\n -> teardown node1\n ","endLoc":627,"header":"def pytest_runtest_logreport(self, report)","id":1354,"name":"pytest_runtest_logreport","nodeType":"Function","startLoc":543,"text":"def pytest_runtest_logreport(self, report):\n \"\"\"handle a setup/call/teardown report, generating the appropriate\n xml tags as necessary.\n\n note: due to plugins like xdist, this hook may be called in interlaced\n order with reports from other nodes. for example:\n\n usual call order:\n -> setup node1\n -> call node1\n -> teardown node1\n -> setup node2\n -> call node2\n -> teardown node2\n\n possible call order in xdist:\n -> setup node1\n -> call node1\n -> setup node2\n -> call node2\n -> teardown node2\n -> teardown node1\n \"\"\"\n close_report = None\n if report.passed:\n if report.when == \"call\": # ignore setup/teardown\n reporter = self._opentestcase(report)\n reporter.append_pass(report)\n elif report.failed:\n if report.when == \"teardown\":\n # The following vars are needed when xdist plugin is used\n report_wid = getattr(report, \"worker_id\", None)\n report_ii = getattr(report, \"item_index\", None)\n close_report = next(\n (\n rep\n for rep in self.open_reports\n if (\n rep.nodeid == report.nodeid\n and getattr(rep, \"item_index\", None) == report_ii\n and getattr(rep, \"worker_id\", None) == report_wid\n )\n ),\n None,\n )\n if close_report:\n # We need to open new testcase in case we have failure in\n # call and error in teardown in order to follow junit\n # schema\n self.finalize(close_report)\n self.cnt_double_fail_tests += 1\n reporter = self._opentestcase(report)\n if report.when == \"call\":\n reporter.append_failure(report)\n self.open_reports.append(report)\n else:\n reporter.append_error(report)\n elif report.skipped:\n reporter = self._opentestcase(report)\n reporter.append_skipped(report)\n self.update_testcase_duration(report)\n if report.when == \"teardown\":\n reporter = self._opentestcase(report)\n reporter.write_captured_output(report)\n\n for propname, propvalue in report.user_properties:\n reporter.add_property(propname, propvalue)\n\n self.finalize(report)\n report_wid = getattr(report, \"worker_id\", None)\n report_ii = getattr(report, \"item_index\", None)\n close_report = next(\n (\n rep\n for rep in self.open_reports\n if (\n rep.nodeid == report.nodeid\n and getattr(rep, \"item_index\", None) == report_ii\n and getattr(rep, \"worker_id\", None) == report_wid\n )\n ),\n None,\n )\n if close_report:\n self.open_reports.remove(close_report)"},{"col":0,"comment":"null","endLoc":101,"header":"def test_record_tuples(caplog)","id":1356,"name":"test_record_tuples","nodeType":"Function","startLoc":97,"text":"def test_record_tuples(caplog):\n caplog.set_level(logging.INFO)\n logger.info(\"boo %s\", \"arg\")\n\n assert caplog.record_tuples == [(__name__, logging.INFO, \"boo arg\")]"},{"col":4,"comment":"null","endLoc":249,"header":"def test_int(self)","id":1357,"name":"test_int","nodeType":"Function","startLoc":243,"text":"def test_int(self):\n within_1e6 = [(1000001, 1000000), (-1000001, -1000000)]\n for a, x in within_1e6:\n assert a == approx(x, rel=5e-6, abs=0)\n assert a != approx(x, rel=5e-7, abs=0)\n assert approx(x, rel=5e-6, abs=0) == a\n assert approx(x, rel=5e-7, abs=0) != a"},{"col":0,"comment":"null","endLoc":109,"header":"def test_unicode(caplog)","id":1358,"name":"test_unicode","nodeType":"Function","startLoc":104,"text":"def test_unicode(caplog):\n caplog.set_level(logging.INFO)\n logger.info(u\"bū\")\n assert caplog.records[0].levelname == \"INFO\"\n assert caplog.records[0].msg == u\"bū\"\n assert u\"bū\" in caplog.text"},{"col":0,"comment":"null","endLoc":119,"header":"def test_clear(caplog)","id":1359,"name":"test_clear","nodeType":"Function","startLoc":112,"text":"def test_clear(caplog):\n caplog.set_level(logging.INFO)\n logger.info(u\"bū\")\n assert len(caplog.records)\n assert caplog.text\n caplog.clear()\n assert not len(caplog.records)\n assert not caplog.text"},{"col":4,"comment":"null","endLoc":261,"header":"def test_decimal(self)","id":1360,"name":"test_decimal","nodeType":"Function","startLoc":251,"text":"def test_decimal(self):\n within_1e6 = [\n (Decimal(\"1.000001\"), Decimal(\"1.0\")),\n (Decimal(\"-1.000001\"), Decimal(\"-1.0\")),\n ]\n for a, x in within_1e6:\n assert a == approx(x)\n assert a == approx(x, rel=Decimal(\"5e-6\"), abs=0)\n assert a != approx(x, rel=Decimal(\"5e-7\"), abs=0)\n assert approx(x, rel=Decimal(\"5e-6\"), abs=0) == a\n assert approx(x, rel=Decimal(\"5e-7\"), abs=0) != a"},{"col":4,"comment":"null","endLoc":669,"header":"def _recurse(self, dirpath)","id":1361,"name":"_recurse","nodeType":"Function","startLoc":658,"text":"def _recurse(self, dirpath):\n if dirpath.basename == \"__pycache__\":\n return False\n ihook = self.gethookproxy(dirpath.dirpath())\n if ihook.pytest_ignore_collect(path=dirpath, config=self.config):\n return False\n for pat in self._norecursepatterns:\n if dirpath.check(fnmatch=pat):\n return False\n ihook = self.gethookproxy(dirpath)\n ihook.pytest_collect_directory(path=dirpath, parent=self)\n return True"},{"col":0,"comment":"null","endLoc":128,"header":"@pytest.fixture\ndef logging_during_setup_and_teardown(caplog)","id":1362,"name":"logging_during_setup_and_teardown","nodeType":"Function","startLoc":122,"text":"@pytest.fixture\ndef logging_during_setup_and_teardown(caplog):\n caplog.set_level(\"INFO\")\n logger.info(\"a_setup_log\")\n yield\n logger.info(\"a_teardown_log\")\n assert [x.message for x in caplog.get_records(\"teardown\")] == [\"a_teardown_log\"]"},{"col":4,"comment":"null","endLoc":272,"header":"def test_fraction(self)","id":1363,"name":"test_fraction","nodeType":"Function","startLoc":263,"text":"def test_fraction(self):\n within_1e6 = [\n (1 + Fraction(1, 1000000), Fraction(1)),\n (-1 - Fraction(-1, 1000000), Fraction(-1)),\n ]\n for a, x in within_1e6:\n assert a == approx(x, rel=5e-6, abs=0)\n assert a != approx(x, rel=5e-7, abs=0)\n assert approx(x, rel=5e-6, abs=0) == a\n assert approx(x, rel=5e-7, abs=0) != a"},{"col":8,"comment":"null","endLoc":675,"header":"@staticmethod\n def _visit_filter(f)","id":1364,"name":"_visit_filter","nodeType":"Function","startLoc":673,"text":"@staticmethod\n def _visit_filter(f):\n return f.check(file=1) and not f.strpath.endswith(\"*.pyc\")"},{"col":8,"comment":"null","endLoc":681,"header":"@staticmethod\n def _visit_filter(f)","id":1365,"name":"_visit_filter","nodeType":"Function","startLoc":679,"text":"@staticmethod\n def _visit_filter(f):\n return f.check(file=1)"},{"attributeType":"Interrupted","col":4,"comment":"null","endLoc":422,"id":1366,"name":"Interrupted","nodeType":"Attribute","startLoc":422,"text":"Interrupted"},{"attributeType":"Failed","col":4,"comment":"null","endLoc":423,"id":1367,"name":"Failed","nodeType":"Attribute","startLoc":423,"text":"Failed"},{"attributeType":"function","col":4,"comment":"null","endLoc":473,"id":1368,"name":"pytest_collectreport","nodeType":"Attribute","startLoc":473,"text":"pytest_collectreport"},{"attributeType":"null","col":8,"comment":"null","endLoc":438,"id":1369,"name":"_node_cache","nodeType":"Attribute","startLoc":438,"text":"self._node_cache"},{"attributeType":"null","col":8,"comment":"null","endLoc":512,"id":1370,"name":"_initialparts","nodeType":"Attribute","startLoc":512,"text":"self._initialparts"},{"attributeType":"null","col":8,"comment":"null","endLoc":430,"id":1371,"name":"testscollected","nodeType":"Attribute","startLoc":430,"text":"self.testscollected"},{"attributeType":"null","col":8,"comment":"null","endLoc":434,"id":1372,"name":"_norecursepatterns","nodeType":"Attribute","startLoc":434,"text":"self._norecursepatterns"},{"attributeType":"null","col":8,"comment":"null","endLoc":433,"id":1373,"name":"trace","nodeType":"Attribute","startLoc":433,"text":"self.trace"},{"attributeType":"null","col":8,"comment":"null","endLoc":432,"id":1374,"name":"shouldfail","nodeType":"Attribute","startLoc":432,"text":"self.shouldfail"},{"attributeType":"null","col":8,"comment":"null","endLoc":510,"id":1375,"name":"_notfound","nodeType":"Attribute","startLoc":510,"text":"self._notfound"},{"attributeType":"null","col":8,"comment":"null","endLoc":439,"id":1376,"name":"_bestrelpathcache","nodeType":"Attribute","startLoc":439,"text":"self._bestrelpathcache"},{"attributeType":"null","col":8,"comment":"null","endLoc":435,"id":1377,"name":"startdir","nodeType":"Attribute","startLoc":435,"text":"self.startdir"},{"col":4,"comment":"null","endLoc":285,"header":"def test_complex(self)","id":1378,"name":"test_complex","nodeType":"Function","startLoc":274,"text":"def test_complex(self):\n within_1e6 = [\n (1.000001 + 1.0j, 1.0 + 1.0j),\n (1.0 + 1.000001j, 1.0 + 1.0j),\n (-1.000001 + 1.0j, -1.0 + 1.0j),\n (1.0 - 1.000001j, 1.0 - 1.0j),\n ]\n for a, x in within_1e6:\n assert a == approx(x, rel=5e-6, abs=0)\n assert a != approx(x, rel=5e-7, abs=0)\n assert approx(x, rel=5e-6, abs=0) == a\n assert approx(x, rel=5e-7, abs=0) != a"},{"fileName":"fixtures.py","filePath":"src/_pytest","id":1379,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\nimport inspect\nimport itertools\nimport sys\nimport warnings\nfrom collections import defaultdict\nfrom collections import deque\nfrom collections import OrderedDict\n\nimport attr\nimport py\nimport six\n\nimport _pytest\nfrom _pytest import nodes\nfrom _pytest._code.code import FormattedExcinfo\nfrom _pytest._code.code import TerminalRepr\nfrom _pytest.compat import _format_args\nfrom _pytest.compat import _PytestWrapper\nfrom _pytest.compat import exc_clear\nfrom _pytest.compat import FuncargnamesCompatAttr\nfrom _pytest.compat import get_real_func\nfrom _pytest.compat import get_real_method\nfrom _pytest.compat import getfslineno\nfrom _pytest.compat import getfuncargnames\nfrom _pytest.compat import getimfunc\nfrom _pytest.compat import getlocation\nfrom _pytest.compat import is_generator\nfrom _pytest.compat import isclass\nfrom _pytest.compat import NOTSET\nfrom _pytest.compat import safe_getattr\nfrom _pytest.deprecated import FIXTURE_FUNCTION_CALL\nfrom _pytest.deprecated import FIXTURE_NAMED_REQUEST\nfrom _pytest.outcomes import fail\nfrom _pytest.outcomes import TEST_OUTCOME\n\n\n@attr.s(frozen=True)\nclass PseudoFixtureDef(object):\n cached_result = attr.ib()\n scope = attr.ib()\n\n\ndef pytest_sessionstart(session):\n import _pytest.python\n import _pytest.nodes\n\n scopename2class.update(\n {\n \"package\": _pytest.python.Package,\n \"class\": _pytest.python.Class,\n \"module\": _pytest.python.Module,\n \"function\": _pytest.nodes.Item,\n \"session\": _pytest.main.Session,\n }\n )\n session._fixturemanager = FixtureManager(session)\n\n\nscopename2class = {}\n\n\nscope2props = dict(session=())\nscope2props[\"package\"] = (\"fspath\",)\nscope2props[\"module\"] = (\"fspath\", \"module\")\nscope2props[\"class\"] = scope2props[\"module\"] + (\"cls\",)\nscope2props[\"instance\"] = scope2props[\"class\"] + (\"instance\",)\nscope2props[\"function\"] = scope2props[\"instance\"] + (\"function\", \"keywords\")\n\n\ndef scopeproperty(name=None, doc=None):\n def decoratescope(func):\n scopename = name or func.__name__\n\n def provide(self):\n if func.__name__ in scope2props[self.scope]:\n return func(self)\n raise AttributeError(\n \"%s not available in %s-scoped context\" % (scopename, self.scope)\n )\n\n return property(provide, None, None, func.__doc__)\n\n return decoratescope\n\n\ndef get_scope_package(node, fixturedef):\n import pytest\n\n cls = pytest.Package\n current = node\n fixture_package_name = \"%s/%s\" % (fixturedef.baseid, \"__init__.py\")\n while current and (\n type(current) is not cls or fixture_package_name != current.nodeid\n ):\n current = current.parent\n if current is None:\n return node.session\n return current\n\n\ndef get_scope_node(node, scope):\n cls = scopename2class.get(scope)\n if cls is None:\n raise ValueError(\"unknown scope\")\n return node.getparent(cls)\n\n\ndef add_funcarg_pseudo_fixture_def(collector, metafunc, fixturemanager):\n # this function will transform all collected calls to a functions\n # if they use direct funcargs (i.e. direct parametrization)\n # because we want later test execution to be able to rely on\n # an existing FixtureDef structure for all arguments.\n # XXX we can probably avoid this algorithm if we modify CallSpec2\n # to directly care for creating the fixturedefs within its methods.\n if not metafunc._calls[0].funcargs:\n return # this function call does not have direct parametrization\n # collect funcargs of all callspecs into a list of values\n arg2params = {}\n arg2scope = {}\n for callspec in metafunc._calls:\n for argname, argvalue in callspec.funcargs.items():\n assert argname not in callspec.params\n callspec.params[argname] = argvalue\n arg2params_list = arg2params.setdefault(argname, [])\n callspec.indices[argname] = len(arg2params_list)\n arg2params_list.append(argvalue)\n if argname not in arg2scope:\n scopenum = callspec._arg2scopenum.get(argname, scopenum_function)\n arg2scope[argname] = scopes[scopenum]\n callspec.funcargs.clear()\n\n # register artificial FixtureDef's so that later at test execution\n # time we can rely on a proper FixtureDef to exist for fixture setup.\n arg2fixturedefs = metafunc._arg2fixturedefs\n for argname, valuelist in arg2params.items():\n # if we have a scope that is higher than function we need\n # to make sure we only ever create an according fixturedef on\n # a per-scope basis. We thus store and cache the fixturedef on the\n # node related to the scope.\n scope = arg2scope[argname]\n node = None\n if scope != \"function\":\n node = get_scope_node(collector, scope)\n if node is None:\n assert scope == \"class\" and isinstance(collector, _pytest.python.Module)\n # use module-level collector for class-scope (for now)\n node = collector\n if node and argname in node._name2pseudofixturedef:\n arg2fixturedefs[argname] = [node._name2pseudofixturedef[argname]]\n else:\n fixturedef = FixtureDef(\n fixturemanager,\n \"\",\n argname,\n get_direct_param_fixture_func,\n arg2scope[argname],\n valuelist,\n False,\n False,\n )\n arg2fixturedefs[argname] = [fixturedef]\n if node is not None:\n node._name2pseudofixturedef[argname] = fixturedef\n\n\ndef getfixturemarker(obj):\n \"\"\" return fixturemarker or None if it doesn't exist or raised\n exceptions.\"\"\"\n try:\n return getattr(obj, \"_pytestfixturefunction\", None)\n except TEST_OUTCOME:\n # some objects raise errors like request (from flask import request)\n # we don't expect them to be fixture functions\n return None\n\n\ndef get_parametrized_fixture_keys(item, scopenum):\n \"\"\" return list of keys for all parametrized arguments which match\n the specified scope. \"\"\"\n assert scopenum < scopenum_function # function\n try:\n cs = item.callspec\n except AttributeError:\n pass\n else:\n # cs.indices.items() is random order of argnames. Need to\n # sort this so that different calls to\n # get_parametrized_fixture_keys will be deterministic.\n for argname, param_index in sorted(cs.indices.items()):\n if cs._arg2scopenum[argname] != scopenum:\n continue\n if scopenum == 0: # session\n key = (argname, param_index)\n elif scopenum == 1: # package\n key = (argname, param_index, item.fspath.dirpath())\n elif scopenum == 2: # module\n key = (argname, param_index, item.fspath)\n elif scopenum == 3: # class\n key = (argname, param_index, item.fspath, item.cls)\n yield key\n\n\n# algorithm for sorting on a per-parametrized resource setup basis\n# it is called for scopenum==0 (session) first and performs sorting\n# down to the lower scopes such as to minimize number of \"high scope\"\n# setups and teardowns\n\n\ndef reorder_items(items):\n argkeys_cache = {}\n items_by_argkey = {}\n for scopenum in range(0, scopenum_function):\n argkeys_cache[scopenum] = d = {}\n items_by_argkey[scopenum] = item_d = defaultdict(deque)\n for item in items:\n keys = OrderedDict.fromkeys(get_parametrized_fixture_keys(item, scopenum))\n if keys:\n d[item] = keys\n for key in keys:\n item_d[key].append(item)\n items = OrderedDict.fromkeys(items)\n return list(reorder_items_atscope(items, argkeys_cache, items_by_argkey, 0))\n\n\ndef fix_cache_order(item, argkeys_cache, items_by_argkey):\n for scopenum in range(0, scopenum_function):\n for key in argkeys_cache[scopenum].get(item, []):\n items_by_argkey[scopenum][key].appendleft(item)\n\n\ndef reorder_items_atscope(items, argkeys_cache, items_by_argkey, scopenum):\n if scopenum >= scopenum_function or len(items) < 3:\n return items\n ignore = set()\n items_deque = deque(items)\n items_done = OrderedDict()\n scoped_items_by_argkey = items_by_argkey[scopenum]\n scoped_argkeys_cache = argkeys_cache[scopenum]\n while items_deque:\n no_argkey_group = OrderedDict()\n slicing_argkey = None\n while items_deque:\n item = items_deque.popleft()\n if item in items_done or item in no_argkey_group:\n continue\n argkeys = OrderedDict.fromkeys(\n k for k in scoped_argkeys_cache.get(item, []) if k not in ignore\n )\n if not argkeys:\n no_argkey_group[item] = None\n else:\n slicing_argkey, _ = argkeys.popitem()\n # we don't have to remove relevant items from later in the deque because they'll just be ignored\n matching_items = [\n i for i in scoped_items_by_argkey[slicing_argkey] if i in items\n ]\n for i in reversed(matching_items):\n fix_cache_order(i, argkeys_cache, items_by_argkey)\n items_deque.appendleft(i)\n break\n if no_argkey_group:\n no_argkey_group = reorder_items_atscope(\n no_argkey_group, argkeys_cache, items_by_argkey, scopenum + 1\n )\n for item in no_argkey_group:\n items_done[item] = None\n ignore.add(slicing_argkey)\n return items_done\n\n\ndef fillfixtures(function):\n \"\"\" fill missing funcargs for a test function. \"\"\"\n try:\n request = function._request\n except AttributeError:\n # XXX this special code path is only expected to execute\n # with the oejskit plugin. It uses classes with funcargs\n # and we thus have to work a bit to allow this.\n fm = function.session._fixturemanager\n fi = fm.getfixtureinfo(function.parent, function.obj, None)\n function._fixtureinfo = fi\n request = function._request = FixtureRequest(function)\n request._fillfixtures()\n # prune out funcargs for jstests\n newfuncargs = {}\n for name in fi.argnames:\n newfuncargs[name] = function.funcargs[name]\n function.funcargs = newfuncargs\n else:\n request._fillfixtures()\n\n\ndef get_direct_param_fixture_func(request):\n return request.param\n\n\n@attr.s(slots=True)\nclass FuncFixtureInfo(object):\n # original function argument names\n argnames = attr.ib(type=tuple)\n # argnames that function immediately requires. These include argnames +\n # fixture names specified via usefixtures and via autouse=True in fixture\n # definitions.\n initialnames = attr.ib(type=tuple)\n names_closure = attr.ib() # List[str]\n name2fixturedefs = attr.ib() # List[str, List[FixtureDef]]\n\n def prune_dependency_tree(self):\n \"\"\"Recompute names_closure from initialnames and name2fixturedefs\n\n Can only reduce names_closure, which means that the new closure will\n always be a subset of the old one. The order is preserved.\n\n This method is needed because direct parametrization may shadow some\n of the fixtures that were included in the originally built dependency\n tree. In this way the dependency tree can get pruned, and the closure\n of argnames may get reduced.\n \"\"\"\n closure = set()\n working_set = set(self.initialnames)\n while working_set:\n argname = working_set.pop()\n # argname may be smth not included in the original names_closure,\n # in which case we ignore it. This currently happens with pseudo\n # FixtureDefs which wrap 'get_direct_param_fixture_func(request)'.\n # So they introduce the new dependency 'request' which might have\n # been missing in the original tree (closure).\n if argname not in closure and argname in self.names_closure:\n closure.add(argname)\n if argname in self.name2fixturedefs:\n working_set.update(self.name2fixturedefs[argname][-1].argnames)\n\n self.names_closure[:] = sorted(closure, key=self.names_closure.index)\n\n\nclass FixtureRequest(FuncargnamesCompatAttr):\n \"\"\" A request for a fixture from a test or fixture function.\n\n A request object gives access to the requesting test context\n and has an optional ``param`` attribute in case\n the fixture is parametrized indirectly.\n \"\"\"\n\n def __init__(self, pyfuncitem):\n self._pyfuncitem = pyfuncitem\n #: fixture for which this request is being performed\n self.fixturename = None\n #: Scope string, one of \"function\", \"class\", \"module\", \"session\"\n self.scope = \"function\"\n self._fixture_defs = {} # argname -> FixtureDef\n fixtureinfo = pyfuncitem._fixtureinfo\n self._arg2fixturedefs = fixtureinfo.name2fixturedefs.copy()\n self._arg2index = {}\n self._fixturemanager = pyfuncitem.session._fixturemanager\n\n @property\n def fixturenames(self):\n \"\"\"names of all active fixtures in this request\"\"\"\n result = list(self._pyfuncitem._fixtureinfo.names_closure)\n result.extend(set(self._fixture_defs).difference(result))\n return result\n\n @property\n def node(self):\n \"\"\" underlying collection node (depends on current request scope)\"\"\"\n return self._getscopeitem(self.scope)\n\n def _getnextfixturedef(self, argname):\n fixturedefs = self._arg2fixturedefs.get(argname, None)\n if fixturedefs is None:\n # we arrive here because of a dynamic call to\n # getfixturevalue(argname) usage which was naturally\n # not known at parsing/collection time\n parentid = self._pyfuncitem.parent.nodeid\n fixturedefs = self._fixturemanager.getfixturedefs(argname, parentid)\n self._arg2fixturedefs[argname] = fixturedefs\n # fixturedefs list is immutable so we maintain a decreasing index\n index = self._arg2index.get(argname, 0) - 1\n if fixturedefs is None or (-index > len(fixturedefs)):\n raise FixtureLookupError(argname, self)\n self._arg2index[argname] = index\n return fixturedefs[index]\n\n @property\n def config(self):\n \"\"\" the pytest config object associated with this request. \"\"\"\n return self._pyfuncitem.config\n\n @scopeproperty()\n def function(self):\n \"\"\" test function object if the request has a per-function scope. \"\"\"\n return self._pyfuncitem.obj\n\n @scopeproperty(\"class\")\n def cls(self):\n \"\"\" class (can be None) where the test function was collected. \"\"\"\n clscol = self._pyfuncitem.getparent(_pytest.python.Class)\n if clscol:\n return clscol.obj\n\n @property\n def instance(self):\n \"\"\" instance (can be None) on which test function was collected. \"\"\"\n # unittest support hack, see _pytest.unittest.TestCaseFunction\n try:\n return self._pyfuncitem._testcase\n except AttributeError:\n function = getattr(self, \"function\", None)\n return getattr(function, \"__self__\", None)\n\n @scopeproperty()\n def module(self):\n \"\"\" python module object where the test function was collected. \"\"\"\n return self._pyfuncitem.getparent(_pytest.python.Module).obj\n\n @scopeproperty()\n def fspath(self):\n \"\"\" the file system path of the test module which collected this test. \"\"\"\n return self._pyfuncitem.fspath\n\n @property\n def keywords(self):\n \"\"\" keywords/markers dictionary for the underlying node. \"\"\"\n return self.node.keywords\n\n @property\n def session(self):\n \"\"\" pytest session object. \"\"\"\n return self._pyfuncitem.session\n\n def addfinalizer(self, finalizer):\n \"\"\" add finalizer/teardown function to be called after the\n last test within the requesting test context finished\n execution. \"\"\"\n # XXX usually this method is shadowed by fixturedef specific ones\n self._addfinalizer(finalizer, scope=self.scope)\n\n def _addfinalizer(self, finalizer, scope):\n colitem = self._getscopeitem(scope)\n self._pyfuncitem.session._setupstate.addfinalizer(\n finalizer=finalizer, colitem=colitem\n )\n\n def applymarker(self, marker):\n \"\"\" Apply a marker to a single test function invocation.\n This method is useful if you don't want to have a keyword/marker\n on all function invocations.\n\n :arg marker: a :py:class:`_pytest.mark.MarkDecorator` object\n created by a call to ``pytest.mark.NAME(...)``.\n \"\"\"\n self.node.add_marker(marker)\n\n def raiseerror(self, msg):\n \"\"\" raise a FixtureLookupError with the given message. \"\"\"\n raise self._fixturemanager.FixtureLookupError(None, self, msg)\n\n def _fillfixtures(self):\n item = self._pyfuncitem\n fixturenames = getattr(item, \"fixturenames\", self.fixturenames)\n for argname in fixturenames:\n if argname not in item.funcargs:\n item.funcargs[argname] = self.getfixturevalue(argname)\n\n def getfixturevalue(self, argname):\n \"\"\" Dynamically run a named fixture function.\n\n Declaring fixtures via function argument is recommended where possible.\n But if you can only decide whether to use another fixture at test\n setup time, you may use this function to retrieve it inside a fixture\n or test function body.\n \"\"\"\n return self._get_active_fixturedef(argname).cached_result[0]\n\n def getfuncargvalue(self, argname):\n \"\"\" Deprecated, use getfixturevalue. \"\"\"\n from _pytest import deprecated\n\n warnings.warn(deprecated.GETFUNCARGVALUE, stacklevel=2)\n return self.getfixturevalue(argname)\n\n def _get_active_fixturedef(self, argname):\n try:\n return self._fixture_defs[argname]\n except KeyError:\n try:\n fixturedef = self._getnextfixturedef(argname)\n except FixtureLookupError:\n if argname == \"request\":\n cached_result = (self, [0], None)\n scope = \"function\"\n return PseudoFixtureDef(cached_result, scope)\n raise\n # remove indent to prevent the python3 exception\n # from leaking into the call\n self._compute_fixture_value(fixturedef)\n self._fixture_defs[argname] = fixturedef\n return fixturedef\n\n def _get_fixturestack(self):\n current = self\n values = []\n while 1:\n fixturedef = getattr(current, \"_fixturedef\", None)\n if fixturedef is None:\n values.reverse()\n return values\n values.append(fixturedef)\n current = current._parent_request\n\n def _compute_fixture_value(self, fixturedef):\n \"\"\"\n Creates a SubRequest based on \"self\" and calls the execute method of the given fixturedef object. This will\n force the FixtureDef object to throw away any previous results and compute a new fixture value, which\n will be stored into the FixtureDef object itself.\n\n :param FixtureDef fixturedef:\n \"\"\"\n # prepare a subrequest object before calling fixture function\n # (latter managed by fixturedef)\n argname = fixturedef.argname\n funcitem = self._pyfuncitem\n scope = fixturedef.scope\n try:\n param = funcitem.callspec.getparam(argname)\n except (AttributeError, ValueError):\n param = NOTSET\n param_index = 0\n has_params = fixturedef.params is not None\n fixtures_not_supported = getattr(funcitem, \"nofuncargs\", False)\n if has_params and fixtures_not_supported:\n msg = (\n \"{name} does not support fixtures, maybe unittest.TestCase subclass?\\n\"\n \"Node id: {nodeid}\\n\"\n \"Function type: {typename}\"\n ).format(\n name=funcitem.name,\n nodeid=funcitem.nodeid,\n typename=type(funcitem).__name__,\n )\n fail(msg, pytrace=False)\n if has_params:\n frame = inspect.stack()[3]\n frameinfo = inspect.getframeinfo(frame[0])\n source_path = frameinfo.filename\n source_lineno = frameinfo.lineno\n source_path = py.path.local(source_path)\n if source_path.relto(funcitem.config.rootdir):\n source_path = source_path.relto(funcitem.config.rootdir)\n msg = (\n \"The requested fixture has no parameter defined for test:\\n\"\n \" {}\\n\\n\"\n \"Requested fixture '{}' defined in:\\n{}\"\n \"\\n\\nRequested here:\\n{}:{}\".format(\n funcitem.nodeid,\n fixturedef.argname,\n getlocation(fixturedef.func, funcitem.config.rootdir),\n source_path,\n source_lineno,\n )\n )\n fail(msg, pytrace=False)\n else:\n param_index = funcitem.callspec.indices[argname]\n # if a parametrize invocation set a scope it will override\n # the static scope defined with the fixture function\n paramscopenum = funcitem.callspec._arg2scopenum.get(argname)\n if paramscopenum is not None:\n scope = scopes[paramscopenum]\n\n subrequest = SubRequest(self, scope, param, param_index, fixturedef)\n\n # check if a higher-level scoped fixture accesses a lower level one\n subrequest._check_scope(argname, self.scope, scope)\n\n # clear sys.exc_info before invoking the fixture (python bug?)\n # if it's not explicitly cleared it will leak into the call\n exc_clear()\n try:\n # call the fixture function\n fixturedef.execute(request=subrequest)\n finally:\n self._schedule_finalizers(fixturedef, subrequest)\n\n def _schedule_finalizers(self, fixturedef, subrequest):\n # if fixture function failed it might have registered finalizers\n self.session._setupstate.addfinalizer(\n functools.partial(fixturedef.finish, request=subrequest), subrequest.node\n )\n\n def _check_scope(self, argname, invoking_scope, requested_scope):\n if argname == \"request\":\n return\n if scopemismatch(invoking_scope, requested_scope):\n # try to report something helpful\n lines = self._factorytraceback()\n fail(\n \"ScopeMismatch: You tried to access the %r scoped \"\n \"fixture %r with a %r scoped request object, \"\n \"involved factories\\n%s\"\n % ((requested_scope, argname, invoking_scope, \"\\n\".join(lines))),\n pytrace=False,\n )\n\n def _factorytraceback(self):\n lines = []\n for fixturedef in self._get_fixturestack():\n factory = fixturedef.func\n fs, lineno = getfslineno(factory)\n p = self._pyfuncitem.session.fspath.bestrelpath(fs)\n args = _format_args(factory)\n lines.append(\"%s:%d: def %s%s\" % (p, lineno + 1, factory.__name__, args))\n return lines\n\n def _getscopeitem(self, scope):\n if scope == \"function\":\n # this might also be a non-function Item despite its attribute name\n return self._pyfuncitem\n if scope == \"package\":\n node = get_scope_package(self._pyfuncitem, self._fixturedef)\n else:\n node = get_scope_node(self._pyfuncitem, scope)\n if node is None and scope == \"class\":\n # fallback to function item itself\n node = self._pyfuncitem\n assert node, 'Could not obtain a node for scope \"{}\" for function {!r}'.format(\n scope, self._pyfuncitem\n )\n return node\n\n def __repr__(self):\n return \"\" % (self.node)\n\n\nclass SubRequest(FixtureRequest):\n \"\"\" a sub request for handling getting a fixture from a\n test function/fixture. \"\"\"\n\n def __init__(self, request, scope, param, param_index, fixturedef):\n self._parent_request = request\n self.fixturename = fixturedef.argname\n if param is not NOTSET:\n self.param = param\n self.param_index = param_index\n self.scope = scope\n self._fixturedef = fixturedef\n self._pyfuncitem = request._pyfuncitem\n self._fixture_defs = request._fixture_defs\n self._arg2fixturedefs = request._arg2fixturedefs\n self._arg2index = request._arg2index\n self._fixturemanager = request._fixturemanager\n\n def __repr__(self):\n return \"\" % (self.fixturename, self._pyfuncitem)\n\n def addfinalizer(self, finalizer):\n self._fixturedef.addfinalizer(finalizer)\n\n def _schedule_finalizers(self, fixturedef, subrequest):\n # if the executing fixturedef was not explicitly requested in the argument list (via\n # getfixturevalue inside the fixture call) then ensure this fixture def will be finished\n # first\n if fixturedef.argname not in self.funcargnames:\n fixturedef.addfinalizer(\n functools.partial(self._fixturedef.finish, request=self)\n )\n super(SubRequest, self)._schedule_finalizers(fixturedef, subrequest)\n\n\nscopes = \"session package module class function\".split()\nscopenum_function = scopes.index(\"function\")\n\n\ndef scopemismatch(currentscope, newscope):\n return scopes.index(newscope) > scopes.index(currentscope)\n\n\ndef scope2index(scope, descr, where=None):\n \"\"\"Look up the index of ``scope`` and raise a descriptive value error\n if not defined.\n \"\"\"\n try:\n return scopes.index(scope)\n except ValueError:\n fail(\n \"{} {}got an unexpected scope value '{}'\".format(\n descr, \"from {} \".format(where) if where else \"\", scope\n ),\n pytrace=False,\n )\n\n\nclass FixtureLookupError(LookupError):\n \"\"\" could not return a requested Fixture (missing or invalid). \"\"\"\n\n def __init__(self, argname, request, msg=None):\n self.argname = argname\n self.request = request\n self.fixturestack = request._get_fixturestack()\n self.msg = msg\n\n def formatrepr(self):\n tblines = []\n addline = tblines.append\n stack = [self.request._pyfuncitem.obj]\n stack.extend(map(lambda x: x.func, self.fixturestack))\n msg = self.msg\n if msg is not None:\n # the last fixture raise an error, let's present\n # it at the requesting side\n stack = stack[:-1]\n for function in stack:\n fspath, lineno = getfslineno(function)\n try:\n lines, _ = inspect.getsourcelines(get_real_func(function))\n except (IOError, IndexError, TypeError):\n error_msg = \"file %s, line %s: source code not available\"\n addline(error_msg % (fspath, lineno + 1))\n else:\n addline(\"file %s, line %s\" % (fspath, lineno + 1))\n for i, line in enumerate(lines):\n line = line.rstrip()\n addline(\" \" + line)\n if line.lstrip().startswith(\"def\"):\n break\n\n if msg is None:\n fm = self.request._fixturemanager\n available = set()\n parentid = self.request._pyfuncitem.parent.nodeid\n for name, fixturedefs in fm._arg2fixturedefs.items():\n faclist = list(fm._matchfactories(fixturedefs, parentid))\n if faclist:\n available.add(name)\n if self.argname in available:\n msg = \" recursive dependency involving fixture '{}' detected\".format(\n self.argname\n )\n else:\n msg = \"fixture '{}' not found\".format(self.argname)\n msg += \"\\n available fixtures: {}\".format(\", \".join(sorted(available)))\n msg += \"\\n use 'pytest --fixtures [testpath]' for help on them.\"\n\n return FixtureLookupErrorRepr(fspath, lineno, tblines, msg, self.argname)\n\n\nclass FixtureLookupErrorRepr(TerminalRepr):\n def __init__(self, filename, firstlineno, tblines, errorstring, argname):\n self.tblines = tblines\n self.errorstring = errorstring\n self.filename = filename\n self.firstlineno = firstlineno\n self.argname = argname\n\n def toterminal(self, tw):\n # tw.line(\"FixtureLookupError: %s\" %(self.argname), red=True)\n for tbline in self.tblines:\n tw.line(tbline.rstrip())\n lines = self.errorstring.split(\"\\n\")\n if lines:\n tw.line(\n \"{} {}\".format(FormattedExcinfo.fail_marker, lines[0].strip()),\n red=True,\n )\n for line in lines[1:]:\n tw.line(\n \"{} {}\".format(FormattedExcinfo.flow_marker, line.strip()),\n red=True,\n )\n tw.line()\n tw.line(\"%s:%d\" % (self.filename, self.firstlineno + 1))\n\n\ndef fail_fixturefunc(fixturefunc, msg):\n fs, lineno = getfslineno(fixturefunc)\n location = \"%s:%s\" % (fs, lineno + 1)\n source = _pytest._code.Source(fixturefunc)\n fail(msg + \":\\n\\n\" + str(source.indent()) + \"\\n\" + location, pytrace=False)\n\n\ndef call_fixture_func(fixturefunc, request, kwargs):\n yieldctx = is_generator(fixturefunc)\n if yieldctx:\n it = fixturefunc(**kwargs)\n res = next(it)\n finalizer = functools.partial(_teardown_yield_fixture, fixturefunc, it)\n request.addfinalizer(finalizer)\n else:\n res = fixturefunc(**kwargs)\n return res\n\n\ndef _teardown_yield_fixture(fixturefunc, it):\n \"\"\"Executes the teardown of a fixture function by advancing the iterator after the\n yield and ensure the iteration ends (if not it means there is more than one yield in the function)\"\"\"\n try:\n next(it)\n except StopIteration:\n pass\n else:\n fail_fixturefunc(\n fixturefunc, \"yield_fixture function has more than one 'yield'\"\n )\n\n\nclass FixtureDef(object):\n \"\"\" A container for a factory definition. \"\"\"\n\n def __init__(\n self,\n fixturemanager,\n baseid,\n argname,\n func,\n scope,\n params,\n unittest=False,\n ids=None,\n ):\n self._fixturemanager = fixturemanager\n self.baseid = baseid or \"\"\n self.has_location = baseid is not None\n self.func = func\n self.argname = argname\n self.scope = scope\n self.scopenum = scope2index(\n scope or \"function\",\n descr=\"Fixture '{}'\".format(func.__name__),\n where=baseid,\n )\n self.params = params\n self.argnames = getfuncargnames(func, is_method=unittest)\n self.unittest = unittest\n self.ids = ids\n self._finalizers = []\n\n def addfinalizer(self, finalizer):\n self._finalizers.append(finalizer)\n\n def finish(self, request):\n exceptions = []\n try:\n while self._finalizers:\n try:\n func = self._finalizers.pop()\n func()\n except: # noqa\n exceptions.append(sys.exc_info())\n if exceptions:\n e = exceptions[0]\n # Ensure to not keep frame references through traceback.\n del exceptions\n six.reraise(*e)\n finally:\n hook = self._fixturemanager.session.gethookproxy(request.node.fspath)\n hook.pytest_fixture_post_finalizer(fixturedef=self, request=request)\n # even if finalization fails, we invalidate\n # the cached fixture value and remove\n # all finalizers because they may be bound methods which will\n # keep instances alive\n if hasattr(self, \"cached_result\"):\n del self.cached_result\n self._finalizers = []\n\n def execute(self, request):\n # get required arguments and register our own finish()\n # with their finalization\n for argname in self.argnames:\n fixturedef = request._get_active_fixturedef(argname)\n if argname != \"request\":\n fixturedef.addfinalizer(functools.partial(self.finish, request=request))\n\n my_cache_key = request.param_index\n cached_result = getattr(self, \"cached_result\", None)\n if cached_result is not None:\n result, cache_key, err = cached_result\n if my_cache_key == cache_key:\n if err is not None:\n six.reraise(*err)\n else:\n return result\n # we have a previous but differently parametrized fixture instance\n # so we need to tear it down before creating a new one\n self.finish(request)\n assert not hasattr(self, \"cached_result\")\n\n hook = self._fixturemanager.session.gethookproxy(request.node.fspath)\n return hook.pytest_fixture_setup(fixturedef=self, request=request)\n\n def __repr__(self):\n return \"\" % (\n self.argname,\n self.scope,\n self.baseid,\n )\n\n\ndef resolve_fixture_function(fixturedef, request):\n \"\"\"Gets the actual callable that can be called to obtain the fixture value, dealing with unittest-specific\n instances and bound methods.\n \"\"\"\n fixturefunc = fixturedef.func\n if fixturedef.unittest:\n if request.instance is not None:\n # bind the unbound method to the TestCase instance\n fixturefunc = fixturedef.func.__get__(request.instance)\n else:\n # the fixture function needs to be bound to the actual\n # request.instance so that code working with \"fixturedef\" behaves\n # as expected.\n if request.instance is not None:\n fixturefunc = getimfunc(fixturedef.func)\n if fixturefunc != fixturedef.func:\n fixturefunc = fixturefunc.__get__(request.instance)\n return fixturefunc\n\n\ndef pytest_fixture_setup(fixturedef, request):\n \"\"\" Execution of fixture setup. \"\"\"\n kwargs = {}\n for argname in fixturedef.argnames:\n fixdef = request._get_active_fixturedef(argname)\n result, arg_cache_key, exc = fixdef.cached_result\n request._check_scope(argname, request.scope, fixdef.scope)\n kwargs[argname] = result\n\n fixturefunc = resolve_fixture_function(fixturedef, request)\n my_cache_key = request.param_index\n try:\n result = call_fixture_func(fixturefunc, request, kwargs)\n except TEST_OUTCOME:\n fixturedef.cached_result = (None, my_cache_key, sys.exc_info())\n raise\n fixturedef.cached_result = (result, my_cache_key, None)\n return result\n\n\ndef _ensure_immutable_ids(ids):\n if ids is None:\n return\n if callable(ids):\n return ids\n return tuple(ids)\n\n\ndef wrap_function_to_error_out_if_called_directly(function, fixture_marker):\n \"\"\"Wrap the given fixture function so we can raise an error about it being called directly,\n instead of used as an argument in a test function.\n \"\"\"\n message = FIXTURE_FUNCTION_CALL.format(\n name=fixture_marker.name or function.__name__\n )\n\n @six.wraps(function)\n def result(*args, **kwargs):\n fail(message, pytrace=False)\n\n # keep reference to the original function in our own custom attribute so we don't unwrap\n # further than this point and lose useful wrappings like @mock.patch (#3774)\n result.__pytest_wrapped__ = _PytestWrapper(function)\n\n return result\n\n\n@attr.s(frozen=True)\nclass FixtureFunctionMarker(object):\n scope = attr.ib()\n params = attr.ib(converter=attr.converters.optional(tuple))\n autouse = attr.ib(default=False)\n ids = attr.ib(default=None, converter=_ensure_immutable_ids)\n name = attr.ib(default=None)\n\n def __call__(self, function):\n if isclass(function):\n raise ValueError(\"class fixtures not supported (maybe in the future)\")\n\n if getattr(function, \"_pytestfixturefunction\", False):\n raise ValueError(\n \"fixture is being applied more than once to the same function\"\n )\n\n function = wrap_function_to_error_out_if_called_directly(function, self)\n\n name = self.name or function.__name__\n if name == \"request\":\n warnings.warn(FIXTURE_NAMED_REQUEST)\n function._pytestfixturefunction = self\n return function\n\n\ndef fixture(scope=\"function\", params=None, autouse=False, ids=None, name=None):\n \"\"\"Decorator to mark a fixture factory function.\n\n This decorator can be used, with or without parameters, to define a\n fixture function.\n\n The name of the fixture function can later be referenced to cause its\n invocation ahead of running tests: test\n modules or classes can use the ``pytest.mark.usefixtures(fixturename)``\n marker.\n\n Test functions can directly use fixture names as input\n arguments in which case the fixture instance returned from the fixture\n function will be injected.\n\n Fixtures can provide their values to test functions using ``return`` or ``yield``\n statements. When using ``yield`` the code block after the ``yield`` statement is executed\n as teardown code regardless of the test outcome, and must yield exactly once.\n\n :arg scope: the scope for which this fixture is shared, one of\n ``\"function\"`` (default), ``\"class\"``, ``\"module\"``,\n ``\"package\"`` or ``\"session\"``.\n\n ``\"package\"`` is considered **experimental** at this time.\n\n :arg params: an optional list of parameters which will cause multiple\n invocations of the fixture function and all of the tests\n using it.\n The current parameter is available in ``request.param``.\n\n :arg autouse: if True, the fixture func is activated for all tests that\n can see it. If False (the default) then an explicit\n reference is needed to activate the fixture.\n\n :arg ids: list of string ids each corresponding to the params\n so that they are part of the test id. If no ids are provided\n they will be generated automatically from the params.\n\n :arg name: the name of the fixture. This defaults to the name of the\n decorated function. If a fixture is used in the same module in\n which it is defined, the function name of the fixture will be\n shadowed by the function arg that requests the fixture; one way\n to resolve this is to name the decorated function\n ``fixture_`` and then use\n ``@pytest.fixture(name='')``.\n \"\"\"\n if callable(scope) and params is None and autouse is False:\n # direct decoration\n return FixtureFunctionMarker(\"function\", params, autouse, name=name)(scope)\n if params is not None and not isinstance(params, (list, tuple)):\n params = list(params)\n return FixtureFunctionMarker(scope, params, autouse, ids=ids, name=name)\n\n\ndef yield_fixture(scope=\"function\", params=None, autouse=False, ids=None, name=None):\n \"\"\" (return a) decorator to mark a yield-fixture factory function.\n\n .. deprecated:: 3.0\n Use :py:func:`pytest.fixture` directly instead.\n \"\"\"\n return fixture(scope=scope, params=params, autouse=autouse, ids=ids, name=name)\n\n\ndefaultfuncargprefixmarker = fixture()\n\n\n@fixture(scope=\"session\")\ndef pytestconfig(request):\n \"\"\"Session-scoped fixture that returns the :class:`_pytest.config.Config` object.\n\n Example::\n\n def test_foo(pytestconfig):\n if pytestconfig.getoption(\"verbose\") > 0:\n ...\n\n \"\"\"\n return request.config\n\n\ndef pytest_addoption(parser):\n parser.addini(\n \"usefixtures\",\n type=\"args\",\n default=[],\n help=\"list of default fixtures to be used with this project\",\n )\n\n\nclass FixtureManager(object):\n \"\"\"\n pytest fixtures definitions and information is stored and managed\n from this class.\n\n During collection fm.parsefactories() is called multiple times to parse\n fixture function definitions into FixtureDef objects and internal\n data structures.\n\n During collection of test functions, metafunc-mechanics instantiate\n a FuncFixtureInfo object which is cached per node/func-name.\n This FuncFixtureInfo object is later retrieved by Function nodes\n which themselves offer a fixturenames attribute.\n\n The FuncFixtureInfo object holds information about fixtures and FixtureDefs\n relevant for a particular function. An initial list of fixtures is\n assembled like this:\n\n - ini-defined usefixtures\n - autouse-marked fixtures along the collection chain up from the function\n - usefixtures markers at module/class/function level\n - test function funcargs\n\n Subsequently the funcfixtureinfo.fixturenames attribute is computed\n as the closure of the fixtures needed to setup the initial fixtures,\n i. e. fixtures needed by fixture functions themselves are appended\n to the fixturenames list.\n\n Upon the test-setup phases all fixturenames are instantiated, retrieved\n by a lookup of their FuncFixtureInfo.\n \"\"\"\n\n FixtureLookupError = FixtureLookupError\n FixtureLookupErrorRepr = FixtureLookupErrorRepr\n\n def __init__(self, session):\n self.session = session\n self.config = session.config\n self._arg2fixturedefs = {}\n self._holderobjseen = set()\n self._arg2finish = {}\n self._nodeid_and_autousenames = [(\"\", self.config.getini(\"usefixtures\"))]\n session.config.pluginmanager.register(self, \"funcmanage\")\n\n def _get_direct_parametrize_args(self, node):\n \"\"\"This function returns all the direct parametrization\n arguments of a node, so we don't mistake them for fixtures\n\n Check https://github.com/pytest-dev/pytest/issues/5036\n\n This things are done later as well when dealing with parametrization\n so this could be improved\n \"\"\"\n from _pytest.mark import ParameterSet\n\n parametrize_argnames = []\n for marker in node.iter_markers(name=\"parametrize\"):\n if not marker.kwargs.get(\"indirect\", False):\n p_argnames, _ = ParameterSet._parse_parametrize_args(\n *marker.args, **marker.kwargs\n )\n parametrize_argnames.extend(p_argnames)\n\n return parametrize_argnames\n\n def getfixtureinfo(self, node, func, cls, funcargs=True):\n if funcargs and not getattr(node, \"nofuncargs\", False):\n argnames = getfuncargnames(func, cls=cls)\n else:\n argnames = ()\n\n usefixtures = itertools.chain.from_iterable(\n mark.args for mark in node.iter_markers(name=\"usefixtures\")\n )\n initialnames = tuple(usefixtures) + argnames\n fm = node.session._fixturemanager\n initialnames, names_closure, arg2fixturedefs = fm.getfixtureclosure(\n initialnames, node, ignore_args=self._get_direct_parametrize_args(node)\n )\n return FuncFixtureInfo(argnames, initialnames, names_closure, arg2fixturedefs)\n\n def pytest_plugin_registered(self, plugin):\n nodeid = None\n try:\n p = py.path.local(plugin.__file__).realpath()\n except AttributeError:\n pass\n else:\n # construct the base nodeid which is later used to check\n # what fixtures are visible for particular tests (as denoted\n # by their test id)\n if p.basename.startswith(\"conftest.py\"):\n nodeid = p.dirpath().relto(self.config.rootdir)\n if p.sep != nodes.SEP:\n nodeid = nodeid.replace(p.sep, nodes.SEP)\n\n self.parsefactories(plugin, nodeid)\n\n def _getautousenames(self, nodeid):\n \"\"\" return a tuple of fixture names to be used. \"\"\"\n autousenames = []\n for baseid, basenames in self._nodeid_and_autousenames:\n if nodeid.startswith(baseid):\n if baseid:\n i = len(baseid)\n nextchar = nodeid[i : i + 1]\n if nextchar and nextchar not in \":/\":\n continue\n autousenames.extend(basenames)\n return autousenames\n\n def getfixtureclosure(self, fixturenames, parentnode, ignore_args=()):\n # collect the closure of all fixtures , starting with the given\n # fixturenames as the initial set. As we have to visit all\n # factory definitions anyway, we also return an arg2fixturedefs\n # mapping so that the caller can reuse it and does not have\n # to re-discover fixturedefs again for each fixturename\n # (discovering matching fixtures for a given name/node is expensive)\n\n parentid = parentnode.nodeid\n fixturenames_closure = self._getautousenames(parentid)\n\n def merge(otherlist):\n for arg in otherlist:\n if arg not in fixturenames_closure:\n fixturenames_closure.append(arg)\n\n merge(fixturenames)\n\n # at this point, fixturenames_closure contains what we call \"initialnames\",\n # which is a set of fixturenames the function immediately requests. We\n # need to return it as well, so save this.\n initialnames = tuple(fixturenames_closure)\n\n arg2fixturedefs = {}\n lastlen = -1\n while lastlen != len(fixturenames_closure):\n lastlen = len(fixturenames_closure)\n for argname in fixturenames_closure:\n if argname in ignore_args:\n continue\n if argname in arg2fixturedefs:\n continue\n fixturedefs = self.getfixturedefs(argname, parentid)\n if fixturedefs:\n arg2fixturedefs[argname] = fixturedefs\n merge(fixturedefs[-1].argnames)\n\n def sort_by_scope(arg_name):\n try:\n fixturedefs = arg2fixturedefs[arg_name]\n except KeyError:\n return scopes.index(\"function\")\n else:\n return fixturedefs[-1].scopenum\n\n fixturenames_closure.sort(key=sort_by_scope)\n return initialnames, fixturenames_closure, arg2fixturedefs\n\n def pytest_generate_tests(self, metafunc):\n for argname in metafunc.fixturenames:\n faclist = metafunc._arg2fixturedefs.get(argname)\n if faclist:\n fixturedef = faclist[-1]\n if fixturedef.params is not None:\n markers = list(metafunc.definition.iter_markers(\"parametrize\"))\n for parametrize_mark in markers:\n if \"argnames\" in parametrize_mark.kwargs:\n argnames = parametrize_mark.kwargs[\"argnames\"]\n else:\n argnames = parametrize_mark.args[0]\n\n if not isinstance(argnames, (tuple, list)):\n argnames = [\n x.strip() for x in argnames.split(\",\") if x.strip()\n ]\n if argname in argnames:\n break\n else:\n metafunc.parametrize(\n argname,\n fixturedef.params,\n indirect=True,\n scope=fixturedef.scope,\n ids=fixturedef.ids,\n )\n else:\n continue # will raise FixtureLookupError at setup time\n\n def pytest_collection_modifyitems(self, items):\n # separate parametrized setups\n items[:] = reorder_items(items)\n\n def parsefactories(self, node_or_obj, nodeid=NOTSET, unittest=False):\n if nodeid is not NOTSET:\n holderobj = node_or_obj\n else:\n holderobj = node_or_obj.obj\n nodeid = node_or_obj.nodeid\n if holderobj in self._holderobjseen:\n return\n\n self._holderobjseen.add(holderobj)\n autousenames = []\n for name in dir(holderobj):\n # The attribute can be an arbitrary descriptor, so the attribute\n # access below can raise. safe_getatt() ignores such exceptions.\n obj = safe_getattr(holderobj, name, None)\n marker = getfixturemarker(obj)\n if not isinstance(marker, FixtureFunctionMarker):\n # magic globals with __getattr__ might have got us a wrong\n # fixture attribute\n continue\n\n if marker.name:\n name = marker.name\n\n # during fixture definition we wrap the original fixture function\n # to issue a warning if called directly, so here we unwrap it in order to not emit the warning\n # when pytest itself calls the fixture function\n if six.PY2 and unittest:\n # hack on Python 2 because of the unbound methods\n obj = get_real_func(obj)\n else:\n obj = get_real_method(obj, holderobj)\n\n fixture_def = FixtureDef(\n self,\n nodeid,\n name,\n obj,\n marker.scope,\n marker.params,\n unittest=unittest,\n ids=marker.ids,\n )\n\n faclist = self._arg2fixturedefs.setdefault(name, [])\n if fixture_def.has_location:\n faclist.append(fixture_def)\n else:\n # fixturedefs with no location are at the front\n # so this inserts the current fixturedef after the\n # existing fixturedefs from external plugins but\n # before the fixturedefs provided in conftests.\n i = len([f for f in faclist if not f.has_location])\n faclist.insert(i, fixture_def)\n if marker.autouse:\n autousenames.append(name)\n\n if autousenames:\n self._nodeid_and_autousenames.append((nodeid or \"\", autousenames))\n\n def getfixturedefs(self, argname, nodeid):\n \"\"\"\n Gets a list of fixtures which are applicable to the given node id.\n\n :param str argname: name of the fixture to search for\n :param str nodeid: full node id of the requesting test.\n :return: list[FixtureDef]\n \"\"\"\n try:\n fixturedefs = self._arg2fixturedefs[argname]\n except KeyError:\n return None\n return tuple(self._matchfactories(fixturedefs, nodeid))\n\n def _matchfactories(self, fixturedefs, nodeid):\n for fixturedef in fixturedefs:\n if nodes.ischildnode(fixturedef.baseid, nodeid):\n yield fixturedef\n"},{"col":4,"comment":"null","endLoc":295,"header":"def test_list(self)","id":1380,"name":"test_list","nodeType":"Function","startLoc":287,"text":"def test_list(self):\n actual = [1 + 1e-7, 2 + 1e-8]\n expected = [1, 2]\n\n # Return false if any element is outside the tolerance.\n assert actual == approx(expected, rel=5e-7, abs=0)\n assert actual != approx(expected, rel=5e-8, abs=0)\n assert approx(expected, rel=5e-7, abs=0) == actual\n assert approx(expected, rel=5e-8, abs=0) != actual"},{"col":4,"comment":"null","endLoc":299,"header":"def test_list_wrong_len(self)","id":1381,"name":"test_list_wrong_len","nodeType":"Function","startLoc":297,"text":"def test_list_wrong_len(self):\n assert [1, 2] != approx([1])\n assert [1, 2] != approx([1, 2, 3])"},{"col":4,"comment":"null","endLoc":309,"header":"def test_tuple(self)","id":1382,"name":"test_tuple","nodeType":"Function","startLoc":301,"text":"def test_tuple(self):\n actual = (1 + 1e-7, 2 + 1e-8)\n expected = (1, 2)\n\n # Return false if any element is outside the tolerance.\n assert actual == approx(expected, rel=5e-7, abs=0)\n assert actual != approx(expected, rel=5e-8, abs=0)\n assert approx(expected, rel=5e-7, abs=0) == actual\n assert approx(expected, rel=5e-8, abs=0) != actual"},{"className":"defaultdict","col":0,"comment":"null","endLoc":446,"id":1383,"nodeType":"Class","startLoc":400,"text":"class defaultdict(dict[_KT, _VT]):\n default_factory: Callable[[], _VT] | None\n @overload\n def __init__(self) -> None: ...\n @overload\n def __init__(self: defaultdict[str, _VT], **kwargs: _VT) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780\n @overload\n def __init__(self, default_factory: Callable[[], _VT] | None, /) -> None: ...\n @overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n /,\n **kwargs: _VT,\n ) -> None: ...\n @overload\n def __init__(self, default_factory: Callable[[], _VT] | None, map: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ...\n @overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n map: SupportsKeysAndGetItem[str, _VT],\n /,\n **kwargs: _VT,\n ) -> None: ...\n @overload\n def __init__(self, default_factory: Callable[[], _VT] | None, iterable: Iterable[tuple[_KT, _VT]], /) -> None: ...\n @overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n iterable: Iterable[tuple[str, _VT]],\n /,\n **kwargs: _VT,\n ) -> None: ...\n def __missing__(self, key: _KT, /) -> _VT: ...\n def __copy__(self) -> Self: ...\n def copy(self) -> Self: ...\n if sys.version_info >= (3, 9):\n @overload\n def __or__(self, value: dict[_KT, _VT], /) -> Self: ...\n @overload\n def __or__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ...\n @overload\n def __ror__(self, value: dict[_KT, _VT], /) -> Self: ...\n @overload\n def __ror__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc]"},{"col":4,"comment":"null","endLoc":313,"header":"def test_tuple_wrong_len(self)","id":1384,"name":"test_tuple_wrong_len","nodeType":"Function","startLoc":311,"text":"def test_tuple_wrong_len(self):\n assert (1, 2) != approx((1,))\n assert (1, 2) != approx((1, 2, 3))"},{"col":4,"comment":"null","endLoc":325,"header":"def test_dict(self)","id":1385,"name":"test_dict","nodeType":"Function","startLoc":315,"text":"def test_dict(self):\n actual = {\"a\": 1 + 1e-7, \"b\": 2 + 1e-8}\n # Dictionaries became ordered in python3.6, so switch up the order here\n # to make sure it doesn't matter.\n expected = {\"b\": 2, \"a\": 1}\n\n # Return false if any element is outside the tolerance.\n assert actual == approx(expected, rel=5e-7, abs=0)\n assert actual != approx(expected, rel=5e-8, abs=0)\n assert approx(expected, rel=5e-7, abs=0) == actual\n assert approx(expected, rel=5e-8, abs=0) != actual"},{"col":4,"comment":"null","endLoc":330,"header":"def test_dict_wrong_len(self)","id":1386,"name":"test_dict_wrong_len","nodeType":"Function","startLoc":327,"text":"def test_dict_wrong_len(self):\n assert {\"a\": 1, \"b\": 2} != approx({\"a\": 1})\n assert {\"a\": 1, \"b\": 2} != approx({\"a\": 1, \"c\": 2})\n assert {\"a\": 1, \"b\": 2} != approx({\"a\": 1, \"b\": 2, \"c\": 3})"},{"attributeType":"null","col":8,"comment":"null","endLoc":436,"id":1387,"name":"_initialpaths","nodeType":"Attribute","startLoc":436,"text":"self._initialpaths"},{"col":8,"comment":"null","endLoc":1867,"header":"@overload\n def __new__(cls) -> zip[Any]","id":1388,"name":"__new__","nodeType":"Function","startLoc":1866,"text":"@overload\n def __new__(cls) -> zip[Any]: ..."},{"col":8,"comment":"null","endLoc":1869,"header":"@overload\n def __new__(cls, __iter1: Iterable[_T1]) -> zip[tuple[_T1]]","id":1389,"name":"__new__","nodeType":"Function","startLoc":1868,"text":"@overload\n def __new__(cls, __iter1: Iterable[_T1]) -> zip[tuple[_T1]]: ..."},{"col":8,"comment":"null","endLoc":1871,"header":"@overload\n def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> zip[tuple[_T1, _T2]]","id":1390,"name":"__new__","nodeType":"Function","startLoc":1870,"text":"@overload\n def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> zip[tuple[_T1, _T2]]: ..."},{"col":8,"comment":"null","endLoc":1873,"header":"@overload\n def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> zip[tuple[_T1, _T2, _T3]]","id":1391,"name":"__new__","nodeType":"Function","startLoc":1872,"text":"@overload\n def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> zip[tuple[_T1, _T2, _T3]]: ..."},{"col":8,"comment":"null","endLoc":1877,"header":"@overload\n def __new__(\n cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4]\n ) -> zip[tuple[_T1, _T2, _T3, _T4]]","id":1392,"name":"__new__","nodeType":"Function","startLoc":1874,"text":"@overload\n def __new__(\n cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4]\n ) -> zip[tuple[_T1, _T2, _T3, _T4]]: ..."},{"col":8,"comment":"null","endLoc":1886,"header":"@overload\n def __new__(\n cls,\n __iter1: Iterable[_T1],\n __iter2: Iterable[_T2],\n __iter3: Iterable[_T3],\n __iter4: Iterable[_T4],\n __iter5: Iterable[_T5],\n ) -> zip[tuple[_T1, _T2, _T3, _T4, _T5]]","id":1393,"name":"__new__","nodeType":"Function","startLoc":1878,"text":"@overload\n def __new__(\n cls,\n __iter1: Iterable[_T1],\n __iter2: Iterable[_T2],\n __iter3: Iterable[_T3],\n __iter4: Iterable[_T4],\n __iter5: Iterable[_T5],\n ) -> zip[tuple[_T1, _T2, _T3, _T4, _T5]]: ..."},{"col":8,"comment":"null","endLoc":1897,"header":"@overload\n def __new__(\n cls,\n __iter1: Iterable[Any],\n __iter2: Iterable[Any],\n __iter3: Iterable[Any],\n __iter4: Iterable[Any],\n __iter5: Iterable[Any],\n __iter6: Iterable[Any],\n *iterables: Iterable[Any],\n ) -> zip[tuple[Any, ...]]","id":1394,"name":"__new__","nodeType":"Function","startLoc":1887,"text":"@overload\n def __new__(\n cls,\n __iter1: Iterable[Any],\n __iter2: Iterable[Any],\n __iter3: Iterable[Any],\n __iter4: Iterable[Any],\n __iter5: Iterable[Any],\n __iter6: Iterable[Any],\n *iterables: Iterable[Any],\n ) -> zip[tuple[Any, ...]]: ..."},{"attributeType":"null","col":8,"comment":"null","endLoc":441,"id":1395,"name":"_pkg_roots","nodeType":"Attribute","startLoc":441,"text":"self._pkg_roots"},{"attributeType":"null","col":8,"comment":"null","endLoc":429,"id":1396,"name":"testsfailed","nodeType":"Attribute","startLoc":429,"text":"self.testsfailed"},{"attributeType":"null","col":8,"comment":"null","endLoc":431,"id":1397,"name":"shouldstop","nodeType":"Attribute","startLoc":431,"text":"self.shouldstop"},{"attributeType":"null","col":8,"comment":"null","endLoc":513,"id":1398,"name":"items","nodeType":"Attribute","startLoc":513,"text":"self.items"},{"attributeType":"null","col":0,"comment":"null","endLoc":340,"id":1399,"name":"MARK_GEN","nodeType":"Attribute","startLoc":340,"text":"MARK_GEN"},{"col":0,"comment":"Specify a parameter in `pytest.mark.parametrize`_ calls or\n :ref:`parametrized fixtures `.\n\n .. code-block:: python\n\n @pytest.mark.parametrize(\"test_input,expected\", [\n (\"3+5\", 8),\n pytest.param(\"6*9\", 42, marks=pytest.mark.xfail),\n ])\n def test_eval(test_input, expected):\n assert eval(test_input) == expected\n\n :param values: variable args of the values of the parameter set, in order.\n :keyword marks: a single mark or a list of marks to be applied to this parameter set.\n :keyword str id: the id to attribute to this parameter set.\n ","endLoc":38,"header":"def param(*values, **kw)","id":1400,"name":"param","nodeType":"Function","startLoc":21,"text":"def param(*values, **kw):\n \"\"\"Specify a parameter in `pytest.mark.parametrize`_ calls or\n :ref:`parametrized fixtures `.\n\n .. code-block:: python\n\n @pytest.mark.parametrize(\"test_input,expected\", [\n (\"3+5\", 8),\n pytest.param(\"6*9\", 42, marks=pytest.mark.xfail),\n ])\n def test_eval(test_input, expected):\n assert eval(test_input) == expected\n\n :param values: variable args of the values of the parameter set, in order.\n :keyword marks: a single mark or a list of marks to be applied to this parameter set.\n :keyword str id: the id to attribute to this parameter set.\n \"\"\"\n return ParameterSet.param(*values, **kw)"},{"col":4,"comment":"null","endLoc":348,"header":"def test_numpy_array(self)","id":1401,"name":"test_numpy_array","nodeType":"Function","startLoc":332,"text":"def test_numpy_array(self):\n np = pytest.importorskip(\"numpy\")\n\n actual = np.array([1 + 1e-7, 2 + 1e-8])\n expected = np.array([1, 2])\n\n # Return false if any element is outside the tolerance.\n assert actual == approx(expected, rel=5e-7, abs=0)\n assert actual != approx(expected, rel=5e-8, abs=0)\n assert approx(expected, rel=5e-7, abs=0) == expected\n assert approx(expected, rel=5e-8, abs=0) != actual\n\n # Should be able to compare lists with numpy arrays.\n assert list(actual) == approx(expected, rel=5e-7, abs=0)\n assert list(actual) != approx(expected, rel=5e-8, abs=0)\n assert actual == approx(list(expected), rel=5e-7, abs=0)\n assert actual != approx(list(expected), rel=5e-8, abs=0)"},{"className":"Instance","col":0,"comment":"null","endLoc":807,"id":1402,"nodeType":"Class","startLoc":792,"text":"class Instance(PyCollector):\n _ALLOW_MARKERS = False # hack, destroy later\n # instances share the object with their parents in a way\n # that duplicates markers instances if not taken out\n # can be removed at node structure reorganization time\n\n def _getobj(self):\n return self.parent.obj()\n\n def collect(self):\n self.session._fixturemanager.parsefactories(self)\n return super(Instance, self).collect()\n\n def newinstance(self):\n self.obj = self._getobj()\n return self.obj"},{"col":4,"comment":"null","endLoc":799,"header":"def _getobj(self)","id":1403,"name":"_getobj","nodeType":"Function","startLoc":798,"text":"def _getobj(self):\n return self.parent.obj()"},{"col":4,"comment":"null","endLoc":803,"header":"def collect(self)","id":1404,"name":"collect","nodeType":"Function","startLoc":801,"text":"def collect(self):\n self.session._fixturemanager.parsefactories(self)\n return super(Instance, self).collect()"},{"col":43,"endLoc":1228,"id":1405,"nodeType":"Lambda","startLoc":1228,"text":"lambda: 0"},{"col":4,"comment":"null","endLoc":807,"header":"def newinstance(self)","id":1406,"name":"newinstance","nodeType":"Function","startLoc":805,"text":"def newinstance(self):\n self.obj = self._getobj()\n return self.obj"},{"attributeType":"null","col":4,"comment":"null","endLoc":793,"id":1407,"name":"_ALLOW_MARKERS","nodeType":"Attribute","startLoc":793,"text":"_ALLOW_MARKERS"},{"attributeType":"null","col":8,"comment":"null","endLoc":806,"id":1408,"name":"obj","nodeType":"Attribute","startLoc":806,"text":"self.obj"},{"className":"Module","col":0,"comment":" Collector for test classes and functions. ","endLoc":551,"id":1409,"nodeType":"Class","startLoc":436,"text":"class Module(nodes.File, PyCollector):\n \"\"\" Collector for test classes and functions. \"\"\"\n\n def _getobj(self):\n return self._importtestmodule()\n\n def collect(self):\n self._inject_setup_module_fixture()\n self._inject_setup_function_fixture()\n self.session._fixturemanager.parsefactories(self)\n return super(Module, self).collect()\n\n def _inject_setup_module_fixture(self):\n \"\"\"Injects a hidden autouse, module scoped fixture into the collected module object\n that invokes setUpModule/tearDownModule if either or both are available.\n\n Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with\n other fixtures (#517).\n \"\"\"\n setup_module = _get_non_fixture_func(self.obj, \"setUpModule\")\n if setup_module is None:\n setup_module = _get_non_fixture_func(self.obj, \"setup_module\")\n\n teardown_module = _get_non_fixture_func(self.obj, \"tearDownModule\")\n if teardown_module is None:\n teardown_module = _get_non_fixture_func(self.obj, \"teardown_module\")\n\n if setup_module is None and teardown_module is None:\n return\n\n @fixtures.fixture(autouse=True, scope=\"module\")\n def xunit_setup_module_fixture(request):\n if setup_module is not None:\n _call_with_optional_argument(setup_module, request.module)\n yield\n if teardown_module is not None:\n _call_with_optional_argument(teardown_module, request.module)\n\n self.obj.__pytest_setup_module = xunit_setup_module_fixture\n\n def _inject_setup_function_fixture(self):\n \"\"\"Injects a hidden autouse, function scoped fixture into the collected module object\n that invokes setup_function/teardown_function if either or both are available.\n\n Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with\n other fixtures (#517).\n \"\"\"\n setup_function = _get_non_fixture_func(self.obj, \"setup_function\")\n teardown_function = _get_non_fixture_func(self.obj, \"teardown_function\")\n if setup_function is None and teardown_function is None:\n return\n\n @fixtures.fixture(autouse=True, scope=\"function\")\n def xunit_setup_function_fixture(request):\n if request.instance is not None:\n # in this case we are bound to an instance, so we need to let\n # setup_method handle this\n yield\n return\n if setup_function is not None:\n _call_with_optional_argument(setup_function, request.function)\n yield\n if teardown_function is not None:\n _call_with_optional_argument(teardown_function, request.function)\n\n self.obj.__pytest_setup_function = xunit_setup_function_fixture\n\n def _importtestmodule(self):\n # we assume we are only called once per module\n importmode = self.config.getoption(\"--import-mode\")\n try:\n mod = self.fspath.pyimport(ensuresyspath=importmode)\n except SyntaxError:\n raise self.CollectError(\n _pytest._code.ExceptionInfo.from_current().getrepr(style=\"short\")\n )\n except self.fspath.ImportMismatchError:\n e = sys.exc_info()[1]\n raise self.CollectError(\n \"import file mismatch:\\n\"\n \"imported module %r has this __file__ attribute:\\n\"\n \" %s\\n\"\n \"which is not the same as the test file we want to collect:\\n\"\n \" %s\\n\"\n \"HINT: remove __pycache__ / .pyc files and/or use a \"\n \"unique basename for your test file modules\" % e.args\n )\n except ImportError:\n from _pytest._code.code import ExceptionInfo\n\n exc_info = ExceptionInfo.from_current()\n if self.config.getoption(\"verbose\") < 2:\n exc_info.traceback = exc_info.traceback.filter(filter_traceback)\n exc_repr = (\n exc_info.getrepr(style=\"short\")\n if exc_info.traceback\n else exc_info.exconly()\n )\n formatted_tb = safe_str(exc_repr)\n raise self.CollectError(\n \"ImportError while importing test module '{fspath}'.\\n\"\n \"Hint: make sure your test modules/packages have valid Python names.\\n\"\n \"Traceback:\\n\"\n \"{traceback}\".format(fspath=self.fspath, traceback=formatted_tb)\n )\n except _pytest.runner.Skipped as e:\n if e.allow_module_level:\n raise\n raise self.CollectError(\n \"Using pytest.skip outside of a test is not allowed. \"\n \"To decorate a test function, use the @pytest.mark.skip \"\n \"or @pytest.mark.skipif decorators instead, and to skip a \"\n \"module use `pytestmark = pytest.mark.{skip,skipif}.\"\n )\n self.config.pluginmanager.consider_module(mod)\n return mod"},{"col":4,"comment":"null","endLoc":440,"header":"def _getobj(self)","id":1410,"name":"_getobj","nodeType":"Function","startLoc":439,"text":"def _getobj(self):\n return self._importtestmodule()"},{"col":4,"comment":"accumulates total duration for nodeid from given report and updates\n the Junit.testcase with the new total if already created.\n ","endLoc":635,"header":"def update_testcase_duration(self, report)","id":1411,"name":"update_testcase_duration","nodeType":"Function","startLoc":629,"text":"def update_testcase_duration(self, report):\n \"\"\"accumulates total duration for nodeid from given report and updates\n the Junit.testcase with the new total if already created.\n \"\"\"\n if self.report_duration == \"total\" or report.when == self.report_duration:\n reporter = self.node_reporter(report)\n reporter.duration += getattr(report, \"duration\", 0.0)"},{"col":4,"comment":"null","endLoc":551,"header":"def _importtestmodule(self)","id":1412,"name":"_importtestmodule","nodeType":"Function","startLoc":503,"text":"def _importtestmodule(self):\n # we assume we are only called once per module\n importmode = self.config.getoption(\"--import-mode\")\n try:\n mod = self.fspath.pyimport(ensuresyspath=importmode)\n except SyntaxError:\n raise self.CollectError(\n _pytest._code.ExceptionInfo.from_current().getrepr(style=\"short\")\n )\n except self.fspath.ImportMismatchError:\n e = sys.exc_info()[1]\n raise self.CollectError(\n \"import file mismatch:\\n\"\n \"imported module %r has this __file__ attribute:\\n\"\n \" %s\\n\"\n \"which is not the same as the test file we want to collect:\\n\"\n \" %s\\n\"\n \"HINT: remove __pycache__ / .pyc files and/or use a \"\n \"unique basename for your test file modules\" % e.args\n )\n except ImportError:\n from _pytest._code.code import ExceptionInfo\n\n exc_info = ExceptionInfo.from_current()\n if self.config.getoption(\"verbose\") < 2:\n exc_info.traceback = exc_info.traceback.filter(filter_traceback)\n exc_repr = (\n exc_info.getrepr(style=\"short\")\n if exc_info.traceback\n else exc_info.exconly()\n )\n formatted_tb = safe_str(exc_repr)\n raise self.CollectError(\n \"ImportError while importing test module '{fspath}'.\\n\"\n \"Hint: make sure your test modules/packages have valid Python names.\\n\"\n \"Traceback:\\n\"\n \"{traceback}\".format(fspath=self.fspath, traceback=formatted_tb)\n )\n except _pytest.runner.Skipped as e:\n if e.allow_module_level:\n raise\n raise self.CollectError(\n \"Using pytest.skip outside of a test is not allowed. \"\n \"To decorate a test function, use the @pytest.mark.skip \"\n \"or @pytest.mark.skipif decorators instead, and to skip a \"\n \"module use `pytestmark = pytest.mark.{skip,skipif}.\"\n )\n self.config.pluginmanager.consider_module(mod)\n return mod"},{"col":4,"comment":"\n Check that numpy rel/abs args are handled correctly\n for comparison against an np.array\n Check both sides of the operator, hopefully it doesn't impact things.\n Test all permutations of where the approx and np.array() can show up\n ","endLoc":378,"header":"def test_numpy_tolerance_args(self)","id":1413,"name":"test_numpy_tolerance_args","nodeType":"Function","startLoc":350,"text":"def test_numpy_tolerance_args(self):\n \"\"\"\n Check that numpy rel/abs args are handled correctly\n for comparison against an np.array\n Check both sides of the operator, hopefully it doesn't impact things.\n Test all permutations of where the approx and np.array() can show up\n \"\"\"\n np = pytest.importorskip(\"numpy\")\n expected = 100.0\n actual = 99.0\n abs_diff = expected - actual\n rel_diff = (expected - actual) / expected\n\n tests = [\n (eq, abs_diff, 0),\n (eq, 0, rel_diff),\n (ne, 0, rel_diff / 2.0), # rel diff fail\n (ne, abs_diff / 2.0, 0), # abs diff fail\n ]\n\n for op, _abs, _rel in tests:\n assert op(np.array(actual), approx(expected, abs=_abs, rel=_rel)) # a, b\n assert op(approx(expected, abs=_abs, rel=_rel), np.array(actual)) # b, a\n\n assert op(actual, approx(np.array(expected), abs=_abs, rel=_rel)) # a, b\n assert op(approx(np.array(expected), abs=_abs, rel=_rel), actual) # b, a\n\n assert op(np.array(actual), approx(np.array(expected), abs=_abs, rel=_rel))\n assert op(approx(np.array(expected), abs=_abs, rel=_rel), np.array(actual))"},{"col":4,"comment":"null","endLoc":446,"header":"def collect(self)","id":1414,"name":"collect","nodeType":"Function","startLoc":442,"text":"def collect(self):\n self._inject_setup_module_fixture()\n self._inject_setup_function_fixture()\n self.session._fixturemanager.parsefactories(self)\n return super(Module, self).collect()"},{"fileName":"python_api.py","filePath":"src/_pytest","id":1415,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\n\nimport math\nimport pprint\nimport sys\nimport warnings\nfrom decimal import Decimal\nfrom numbers import Number\n\nfrom more_itertools.more import always_iterable\nfrom six.moves import filterfalse\nfrom six.moves import zip\n\nimport _pytest._code\nfrom _pytest import deprecated\nfrom _pytest.compat import isclass\nfrom _pytest.compat import Iterable\nfrom _pytest.compat import Mapping\nfrom _pytest.compat import Sized\nfrom _pytest.compat import STRING_TYPES\nfrom _pytest.outcomes import fail\n\nBASE_TYPE = (type, STRING_TYPES)\n\n\ndef _cmp_raises_type_error(self, other):\n \"\"\"__cmp__ implementation which raises TypeError. Used\n by Approx base classes to implement only == and != and raise a\n TypeError for other comparisons.\n\n Needed in Python 2 only, Python 3 all it takes is not implementing the\n other operators at all.\n \"\"\"\n __tracebackhide__ = True\n raise TypeError(\n \"Comparison operators other than == and != not supported by approx objects\"\n )\n\n\ndef _non_numeric_type_error(value, at):\n at_str = \" at {}\".format(at) if at else \"\"\n return TypeError(\n \"cannot make approximate comparisons to non-numeric values: {!r} {}\".format(\n value, at_str\n )\n )\n\n\n# builtin pytest.approx helper\n\n\nclass ApproxBase(object):\n \"\"\"\n Provide shared utilities for making approximate comparisons between numbers\n or sequences of numbers.\n \"\"\"\n\n # Tell numpy to use our `__eq__` operator instead of its.\n __array_ufunc__ = None\n __array_priority__ = 100\n\n def __init__(self, expected, rel=None, abs=None, nan_ok=False):\n __tracebackhide__ = True\n self.expected = expected\n self.abs = abs\n self.rel = rel\n self.nan_ok = nan_ok\n self._check_type()\n\n def __repr__(self):\n raise NotImplementedError\n\n def __eq__(self, actual):\n return all(\n a == self._approx_scalar(x) for a, x in self._yield_comparisons(actual)\n )\n\n __hash__ = None\n\n def __ne__(self, actual):\n return not (actual == self)\n\n if sys.version_info[0] == 2:\n __cmp__ = _cmp_raises_type_error\n\n def _approx_scalar(self, x):\n return ApproxScalar(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)\n\n def _yield_comparisons(self, actual):\n \"\"\"\n Yield all the pairs of numbers to be compared. This is used to\n implement the `__eq__` method.\n \"\"\"\n raise NotImplementedError\n\n def _check_type(self):\n \"\"\"\n Raise a TypeError if the expected value is not a valid type.\n \"\"\"\n # This is only a concern if the expected value is a sequence. In every\n # other case, the approx() function ensures that the expected value has\n # a numeric type. For this reason, the default is to do nothing. The\n # classes that deal with sequences should reimplement this method to\n # raise if there are any non-numeric elements in the sequence.\n pass\n\n\ndef _recursive_list_map(f, x):\n if isinstance(x, list):\n return list(_recursive_list_map(f, xi) for xi in x)\n else:\n return f(x)\n\n\nclass ApproxNumpy(ApproxBase):\n \"\"\"\n Perform approximate comparisons where the expected value is numpy array.\n \"\"\"\n\n def __repr__(self):\n list_scalars = _recursive_list_map(self._approx_scalar, self.expected.tolist())\n return \"approx({!r})\".format(list_scalars)\n\n if sys.version_info[0] == 2:\n __cmp__ = _cmp_raises_type_error\n\n def __eq__(self, actual):\n import numpy as np\n\n # self.expected is supposed to always be an array here\n\n if not np.isscalar(actual):\n try:\n actual = np.asarray(actual)\n except: # noqa\n raise TypeError(\"cannot compare '{}' to numpy.ndarray\".format(actual))\n\n if not np.isscalar(actual) and actual.shape != self.expected.shape:\n return False\n\n return ApproxBase.__eq__(self, actual)\n\n def _yield_comparisons(self, actual):\n import numpy as np\n\n # `actual` can either be a numpy array or a scalar, it is treated in\n # `__eq__` before being passed to `ApproxBase.__eq__`, which is the\n # only method that calls this one.\n\n if np.isscalar(actual):\n for i in np.ndindex(self.expected.shape):\n yield actual, self.expected[i].item()\n else:\n for i in np.ndindex(self.expected.shape):\n yield actual[i].item(), self.expected[i].item()\n\n\nclass ApproxMapping(ApproxBase):\n \"\"\"\n Perform approximate comparisons where the expected value is a mapping with\n numeric values (the keys can be anything).\n \"\"\"\n\n def __repr__(self):\n return \"approx({!r})\".format(\n {k: self._approx_scalar(v) for k, v in self.expected.items()}\n )\n\n def __eq__(self, actual):\n if set(actual.keys()) != set(self.expected.keys()):\n return False\n\n return ApproxBase.__eq__(self, actual)\n\n def _yield_comparisons(self, actual):\n for k in self.expected.keys():\n yield actual[k], self.expected[k]\n\n def _check_type(self):\n __tracebackhide__ = True\n for key, value in self.expected.items():\n if isinstance(value, type(self.expected)):\n msg = \"pytest.approx() does not support nested dictionaries: key={!r} value={!r}\\n full mapping={}\"\n raise TypeError(msg.format(key, value, pprint.pformat(self.expected)))\n elif not isinstance(value, Number):\n raise _non_numeric_type_error(self.expected, at=\"key={!r}\".format(key))\n\n\nclass ApproxSequencelike(ApproxBase):\n \"\"\"\n Perform approximate comparisons where the expected value is a sequence of\n numbers.\n \"\"\"\n\n def __repr__(self):\n seq_type = type(self.expected)\n if seq_type not in (tuple, list, set):\n seq_type = list\n return \"approx({!r})\".format(\n seq_type(self._approx_scalar(x) for x in self.expected)\n )\n\n def __eq__(self, actual):\n if len(actual) != len(self.expected):\n return False\n return ApproxBase.__eq__(self, actual)\n\n def _yield_comparisons(self, actual):\n return zip(actual, self.expected)\n\n def _check_type(self):\n __tracebackhide__ = True\n for index, x in enumerate(self.expected):\n if isinstance(x, type(self.expected)):\n msg = \"pytest.approx() does not support nested data structures: {!r} at index {}\\n full sequence: {}\"\n raise TypeError(msg.format(x, index, pprint.pformat(self.expected)))\n elif not isinstance(x, Number):\n raise _non_numeric_type_error(\n self.expected, at=\"index {}\".format(index)\n )\n\n\nclass ApproxScalar(ApproxBase):\n \"\"\"\n Perform approximate comparisons where the expected value is a single number.\n \"\"\"\n\n DEFAULT_ABSOLUTE_TOLERANCE = 1e-12\n DEFAULT_RELATIVE_TOLERANCE = 1e-6\n\n def __repr__(self):\n \"\"\"\n Return a string communicating both the expected value and the tolerance\n for the comparison being made, e.g. '1.0 +- 1e-6'. Use the unicode\n plus/minus symbol if this is python3 (it's too hard to get right for\n python2).\n \"\"\"\n if isinstance(self.expected, complex):\n return str(self.expected)\n\n # Infinities aren't compared using tolerances, so don't show a\n # tolerance.\n if math.isinf(self.expected):\n return str(self.expected)\n\n # If a sensible tolerance can't be calculated, self.tolerance will\n # raise a ValueError. In this case, display '???'.\n try:\n vetted_tolerance = \"{:.1e}\".format(self.tolerance)\n except ValueError:\n vetted_tolerance = \"???\"\n\n if sys.version_info[0] == 2:\n return \"{} +- {}\".format(self.expected, vetted_tolerance)\n else:\n return u\"{} \\u00b1 {}\".format(self.expected, vetted_tolerance)\n\n def __eq__(self, actual):\n \"\"\"\n Return true if the given value is equal to the expected value within\n the pre-specified tolerance.\n \"\"\"\n if _is_numpy_array(actual):\n # Call ``__eq__()`` manually to prevent infinite-recursion with\n # numpy<1.13. See #3748.\n return all(self.__eq__(a) for a in actual.flat)\n\n # Short-circuit exact equality.\n if actual == self.expected:\n return True\n\n # Allow the user to control whether NaNs are considered equal to each\n # other or not. The abs() calls are for compatibility with complex\n # numbers.\n if math.isnan(abs(self.expected)):\n return self.nan_ok and math.isnan(abs(actual))\n\n # Infinity shouldn't be approximately equal to anything but itself, but\n # if there's a relative tolerance, it will be infinite and infinity\n # will seem approximately equal to everything. The equal-to-itself\n # case would have been short circuited above, so here we can just\n # return false if the expected value is infinite. The abs() call is\n # for compatibility with complex numbers.\n if math.isinf(abs(self.expected)):\n return False\n\n # Return true if the two numbers are within the tolerance.\n return abs(self.expected - actual) <= self.tolerance\n\n __hash__ = None\n\n @property\n def tolerance(self):\n \"\"\"\n Return the tolerance for the comparison. This could be either an\n absolute tolerance or a relative tolerance, depending on what the user\n specified or which would be larger.\n \"\"\"\n\n def set_default(x, default):\n return x if x is not None else default\n\n # Figure out what the absolute tolerance should be. ``self.abs`` is\n # either None or a value specified by the user.\n absolute_tolerance = set_default(self.abs, self.DEFAULT_ABSOLUTE_TOLERANCE)\n\n if absolute_tolerance < 0:\n raise ValueError(\n \"absolute tolerance can't be negative: {}\".format(absolute_tolerance)\n )\n if math.isnan(absolute_tolerance):\n raise ValueError(\"absolute tolerance can't be NaN.\")\n\n # If the user specified an absolute tolerance but not a relative one,\n # just return the absolute tolerance.\n if self.rel is None:\n if self.abs is not None:\n return absolute_tolerance\n\n # Figure out what the relative tolerance should be. ``self.rel`` is\n # either None or a value specified by the user. This is done after\n # we've made sure the user didn't ask for an absolute tolerance only,\n # because we don't want to raise errors about the relative tolerance if\n # we aren't even going to use it.\n relative_tolerance = set_default(\n self.rel, self.DEFAULT_RELATIVE_TOLERANCE\n ) * abs(self.expected)\n\n if relative_tolerance < 0:\n raise ValueError(\n \"relative tolerance can't be negative: {}\".format(absolute_tolerance)\n )\n if math.isnan(relative_tolerance):\n raise ValueError(\"relative tolerance can't be NaN.\")\n\n # Return the larger of the relative and absolute tolerances.\n return max(relative_tolerance, absolute_tolerance)\n\n\nclass ApproxDecimal(ApproxScalar):\n \"\"\"\n Perform approximate comparisons where the expected value is a decimal.\n \"\"\"\n\n DEFAULT_ABSOLUTE_TOLERANCE = Decimal(\"1e-12\")\n DEFAULT_RELATIVE_TOLERANCE = Decimal(\"1e-6\")\n\n\ndef approx(expected, rel=None, abs=None, nan_ok=False):\n \"\"\"\n Assert that two numbers (or two sets of numbers) are equal to each other\n within some tolerance.\n\n Due to the `intricacies of floating-point arithmetic`__, numbers that we\n would intuitively expect to be equal are not always so::\n\n >>> 0.1 + 0.2 == 0.3\n False\n\n __ https://docs.python.org/3/tutorial/floatingpoint.html\n\n This problem is commonly encountered when writing tests, e.g. when making\n sure that floating-point values are what you expect them to be. One way to\n deal with this problem is to assert that two floating-point numbers are\n equal to within some appropriate tolerance::\n\n >>> abs((0.1 + 0.2) - 0.3) < 1e-6\n True\n\n However, comparisons like this are tedious to write and difficult to\n understand. Furthermore, absolute comparisons like the one above are\n usually discouraged because there's no tolerance that works well for all\n situations. ``1e-6`` is good for numbers around ``1``, but too small for\n very big numbers and too big for very small ones. It's better to express\n the tolerance as a fraction of the expected value, but relative comparisons\n like that are even more difficult to write correctly and concisely.\n\n The ``approx`` class performs floating-point comparisons using a syntax\n that's as intuitive as possible::\n\n >>> from pytest import approx\n >>> 0.1 + 0.2 == approx(0.3)\n True\n\n The same syntax also works for sequences of numbers::\n\n >>> (0.1 + 0.2, 0.2 + 0.4) == approx((0.3, 0.6))\n True\n\n Dictionary *values*::\n\n >>> {'a': 0.1 + 0.2, 'b': 0.2 + 0.4} == approx({'a': 0.3, 'b': 0.6})\n True\n\n ``numpy`` arrays::\n\n >>> import numpy as np # doctest: +SKIP\n >>> np.array([0.1, 0.2]) + np.array([0.2, 0.4]) == approx(np.array([0.3, 0.6])) # doctest: +SKIP\n True\n\n And for a ``numpy`` array against a scalar::\n\n >>> import numpy as np # doctest: +SKIP\n >>> np.array([0.1, 0.2]) + np.array([0.2, 0.1]) == approx(0.3) # doctest: +SKIP\n True\n\n By default, ``approx`` considers numbers within a relative tolerance of\n ``1e-6`` (i.e. one part in a million) of its expected value to be equal.\n This treatment would lead to surprising results if the expected value was\n ``0.0``, because nothing but ``0.0`` itself is relatively close to ``0.0``.\n To handle this case less surprisingly, ``approx`` also considers numbers\n within an absolute tolerance of ``1e-12`` of its expected value to be\n equal. Infinity and NaN are special cases. Infinity is only considered\n equal to itself, regardless of the relative tolerance. NaN is not\n considered equal to anything by default, but you can make it be equal to\n itself by setting the ``nan_ok`` argument to True. (This is meant to\n facilitate comparing arrays that use NaN to mean \"no data\".)\n\n Both the relative and absolute tolerances can be changed by passing\n arguments to the ``approx`` constructor::\n\n >>> 1.0001 == approx(1)\n False\n >>> 1.0001 == approx(1, rel=1e-3)\n True\n >>> 1.0001 == approx(1, abs=1e-3)\n True\n\n If you specify ``abs`` but not ``rel``, the comparison will not consider\n the relative tolerance at all. In other words, two numbers that are within\n the default relative tolerance of ``1e-6`` will still be considered unequal\n if they exceed the specified absolute tolerance. If you specify both\n ``abs`` and ``rel``, the numbers will be considered equal if either\n tolerance is met::\n\n >>> 1 + 1e-8 == approx(1)\n True\n >>> 1 + 1e-8 == approx(1, abs=1e-12)\n False\n >>> 1 + 1e-8 == approx(1, rel=1e-6, abs=1e-12)\n True\n\n If you're thinking about using ``approx``, then you might want to know how\n it compares to other good ways of comparing floating-point numbers. All of\n these algorithms are based on relative and absolute tolerances and should\n agree for the most part, but they do have meaningful differences:\n\n - ``math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0)``: True if the relative\n tolerance is met w.r.t. either ``a`` or ``b`` or if the absolute\n tolerance is met. Because the relative tolerance is calculated w.r.t.\n both ``a`` and ``b``, this test is symmetric (i.e. neither ``a`` nor\n ``b`` is a \"reference value\"). You have to specify an absolute tolerance\n if you want to compare to ``0.0`` because there is no tolerance by\n default. Only available in python>=3.5. `More information...`__\n\n __ https://docs.python.org/3/library/math.html#math.isclose\n\n - ``numpy.isclose(a, b, rtol=1e-5, atol=1e-8)``: True if the difference\n between ``a`` and ``b`` is less that the sum of the relative tolerance\n w.r.t. ``b`` and the absolute tolerance. Because the relative tolerance\n is only calculated w.r.t. ``b``, this test is asymmetric and you can\n think of ``b`` as the reference value. Support for comparing sequences\n is provided by ``numpy.allclose``. `More information...`__\n\n __ http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.isclose.html\n\n - ``unittest.TestCase.assertAlmostEqual(a, b)``: True if ``a`` and ``b``\n are within an absolute tolerance of ``1e-7``. No relative tolerance is\n considered and the absolute tolerance cannot be changed, so this function\n is not appropriate for very large or very small numbers. Also, it's only\n available in subclasses of ``unittest.TestCase`` and it's ugly because it\n doesn't follow PEP8. `More information...`__\n\n __ https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertAlmostEqual\n\n - ``a == pytest.approx(b, rel=1e-6, abs=1e-12)``: True if the relative\n tolerance is met w.r.t. ``b`` or if the absolute tolerance is met.\n Because the relative tolerance is only calculated w.r.t. ``b``, this test\n is asymmetric and you can think of ``b`` as the reference value. In the\n special case that you explicitly specify an absolute tolerance but not a\n relative tolerance, only the absolute tolerance is considered.\n\n .. warning::\n\n .. versionchanged:: 3.2\n\n In order to avoid inconsistent behavior, ``TypeError`` is\n raised for ``>``, ``>=``, ``<`` and ``<=`` comparisons.\n The example below illustrates the problem::\n\n assert approx(0.1) > 0.1 + 1e-10 # calls approx(0.1).__gt__(0.1 + 1e-10)\n assert 0.1 + 1e-10 > approx(0.1) # calls approx(0.1).__lt__(0.1 + 1e-10)\n\n In the second example one expects ``approx(0.1).__le__(0.1 + 1e-10)``\n to be called. But instead, ``approx(0.1).__lt__(0.1 + 1e-10)`` is used to\n comparison. This is because the call hierarchy of rich comparisons\n follows a fixed behavior. `More information...`__\n\n __ https://docs.python.org/3/reference/datamodel.html#object.__ge__\n \"\"\"\n\n # Delegate the comparison to a class that knows how to deal with the type\n # of the expected value (e.g. int, float, list, dict, numpy.array, etc).\n #\n # The primary responsibility of these classes is to implement ``__eq__()``\n # and ``__repr__()``. The former is used to actually check if some\n # \"actual\" value is equivalent to the given expected value within the\n # allowed tolerance. The latter is used to show the user the expected\n # value and tolerance, in the case that a test failed.\n #\n # The actual logic for making approximate comparisons can be found in\n # ApproxScalar, which is used to compare individual numbers. All of the\n # other Approx classes eventually delegate to this class. The ApproxBase\n # class provides some convenient methods and overloads, but isn't really\n # essential.\n\n __tracebackhide__ = True\n\n if isinstance(expected, Decimal):\n cls = ApproxDecimal\n elif isinstance(expected, Number):\n cls = ApproxScalar\n elif isinstance(expected, Mapping):\n cls = ApproxMapping\n elif _is_numpy_array(expected):\n cls = ApproxNumpy\n elif (\n isinstance(expected, Iterable)\n and isinstance(expected, Sized)\n and not isinstance(expected, STRING_TYPES)\n ):\n cls = ApproxSequencelike\n else:\n raise _non_numeric_type_error(expected, at=None)\n\n return cls(expected, rel, abs, nan_ok)\n\n\ndef _is_numpy_array(obj):\n \"\"\"\n Return true if the given object is a numpy array. Make a special effort to\n avoid importing numpy unless it's really necessary.\n \"\"\"\n import sys\n\n np = sys.modules.get(\"numpy\")\n if np is not None:\n return isinstance(obj, np.ndarray)\n return False\n\n\n# builtin pytest.raises helper\n\n\ndef raises(expected_exception, *args, **kwargs):\n r\"\"\"\n Assert that a code block/function call raises ``expected_exception``\n or raise a failure exception otherwise.\n\n :kwparam match: if specified, a string containing a regular expression,\n or a regular expression object, that is tested against the string\n representation of the exception using ``re.search``. To match a literal\n string that may contain `special characters`__, the pattern can\n first be escaped with ``re.escape``.\n\n __ https://docs.python.org/3/library/re.html#regular-expression-syntax\n\n :kwparam message: **(deprecated since 4.1)** if specified, provides a custom failure message\n if the exception is not raised. See :ref:`the deprecation docs ` for a workaround.\n\n .. currentmodule:: _pytest._code\n\n Use ``pytest.raises`` as a context manager, which will capture the exception of the given\n type::\n\n >>> with raises(ZeroDivisionError):\n ... 1/0\n\n If the code block does not raise the expected exception (``ZeroDivisionError`` in the example\n above), or no exception at all, the check will fail instead.\n\n You can also use the keyword argument ``match`` to assert that the\n exception matches a text or regex::\n\n >>> with raises(ValueError, match='must be 0 or None'):\n ... raise ValueError(\"value must be 0 or None\")\n\n >>> with raises(ValueError, match=r'must be \\d+$'):\n ... raise ValueError(\"value must be 42\")\n\n The context manager produces an :class:`ExceptionInfo` object which can be used to inspect the\n details of the captured exception::\n\n >>> with raises(ValueError) as exc_info:\n ... raise ValueError(\"value must be 42\")\n >>> assert exc_info.type is ValueError\n >>> assert exc_info.value.args[0] == \"value must be 42\"\n\n .. deprecated:: 4.1\n\n In the context manager form you may use the keyword argument\n ``message`` to specify a custom failure message that will be displayed\n in case the ``pytest.raises`` check fails. This has been deprecated as it\n is considered error prone as users often mean to use ``match`` instead.\n See :ref:`the deprecation docs ` for a workaround.\n\n .. note::\n\n When using ``pytest.raises`` as a context manager, it's worthwhile to\n note that normal context manager rules apply and that the exception\n raised *must* be the final line in the scope of the context manager.\n Lines of code after that, within the scope of the context manager will\n not be executed. For example::\n\n >>> value = 15\n >>> with raises(ValueError) as exc_info:\n ... if value > 10:\n ... raise ValueError(\"value must be <= 10\")\n ... assert exc_info.type is ValueError # this will not execute\n\n Instead, the following approach must be taken (note the difference in\n scope)::\n\n >>> with raises(ValueError) as exc_info:\n ... if value > 10:\n ... raise ValueError(\"value must be <= 10\")\n ...\n >>> assert exc_info.type is ValueError\n\n **Using with** ``pytest.mark.parametrize``\n\n When using :ref:`pytest.mark.parametrize ref`\n it is possible to parametrize tests such that\n some runs raise an exception and others do not.\n\n See :ref:`parametrizing_conditional_raising` for an example.\n\n **Legacy form**\n\n It is possible to specify a callable by passing a to-be-called lambda::\n\n >>> raises(ZeroDivisionError, lambda: 1/0)\n \n\n or you can specify an arbitrary callable with arguments::\n\n >>> def f(x): return 1/x\n ...\n >>> raises(ZeroDivisionError, f, 0)\n \n >>> raises(ZeroDivisionError, f, x=0)\n \n\n The form above is fully supported but discouraged for new code because the\n context manager form is regarded as more readable and less error-prone.\n\n .. note::\n Similar to caught exception objects in Python, explicitly clearing\n local references to returned ``ExceptionInfo`` objects can\n help the Python interpreter speed up its garbage collection.\n\n Clearing those references breaks a reference cycle\n (``ExceptionInfo`` --> caught exception --> frame stack raising\n the exception --> current frame stack --> local variables -->\n ``ExceptionInfo``) which makes Python keep all objects referenced\n from that cycle (including all local variables in the current\n frame) alive until the next cyclic garbage collection run. See the\n official Python ``try`` statement documentation for more detailed\n information.\n\n \"\"\"\n __tracebackhide__ = True\n for exc in filterfalse(isclass, always_iterable(expected_exception, BASE_TYPE)):\n msg = (\n \"exceptions must be old-style classes or\"\n \" derived from BaseException, not %s\"\n )\n raise TypeError(msg % type(exc))\n\n message = \"DID NOT RAISE {}\".format(expected_exception)\n match_expr = None\n\n if not args:\n if \"message\" in kwargs:\n message = kwargs.pop(\"message\")\n warnings.warn(deprecated.RAISES_MESSAGE_PARAMETER, stacklevel=2)\n if \"match\" in kwargs:\n match_expr = kwargs.pop(\"match\")\n if kwargs:\n msg = \"Unexpected keyword arguments passed to pytest.raises: \"\n msg += \", \".join(sorted(kwargs))\n raise TypeError(msg)\n return RaisesContext(expected_exception, message, match_expr)\n elif isinstance(args[0], str):\n warnings.warn(deprecated.RAISES_EXEC, stacklevel=2)\n code, = args\n assert isinstance(code, str)\n frame = sys._getframe(1)\n loc = frame.f_locals.copy()\n loc.update(kwargs)\n # print \"raises frame scope: %r\" % frame.f_locals\n try:\n code = _pytest._code.Source(code).compile(_genframe=frame)\n exec(code, frame.f_globals, loc)\n # XXX didn't mean f_globals == f_locals something special?\n # this is destroyed here ...\n except expected_exception:\n return _pytest._code.ExceptionInfo.from_current()\n else:\n func = args[0]\n try:\n func(*args[1:], **kwargs)\n except expected_exception:\n return _pytest._code.ExceptionInfo.from_current()\n fail(message)\n\n\nraises.Exception = fail.Exception\n\n\nclass RaisesContext(object):\n def __init__(self, expected_exception, message, match_expr):\n self.expected_exception = expected_exception\n self.message = message\n self.match_expr = match_expr\n self.excinfo = None\n\n def __enter__(self):\n self.excinfo = _pytest._code.ExceptionInfo.for_later()\n return self.excinfo\n\n def __exit__(self, *tp):\n __tracebackhide__ = True\n if tp[0] is None:\n fail(self.message)\n self.excinfo.__init__(tp)\n suppress_exception = issubclass(self.excinfo.type, self.expected_exception)\n if sys.version_info[0] == 2 and suppress_exception:\n sys.exc_clear()\n if self.match_expr is not None and suppress_exception:\n self.excinfo.match(self.match_expr)\n return suppress_exception\n"},{"col":4,"comment":"Injects a hidden autouse, module scoped fixture into the collected module object\n that invokes setUpModule/tearDownModule if either or both are available.\n\n Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with\n other fixtures (#517).\n ","endLoc":474,"header":"def _inject_setup_module_fixture(self)","id":1416,"name":"_inject_setup_module_fixture","nodeType":"Function","startLoc":448,"text":"def _inject_setup_module_fixture(self):\n \"\"\"Injects a hidden autouse, module scoped fixture into the collected module object\n that invokes setUpModule/tearDownModule if either or both are available.\n\n Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with\n other fixtures (#517).\n \"\"\"\n setup_module = _get_non_fixture_func(self.obj, \"setUpModule\")\n if setup_module is None:\n setup_module = _get_non_fixture_func(self.obj, \"setup_module\")\n\n teardown_module = _get_non_fixture_func(self.obj, \"tearDownModule\")\n if teardown_module is None:\n teardown_module = _get_non_fixture_func(self.obj, \"teardown_module\")\n\n if setup_module is None and teardown_module is None:\n return\n\n @fixtures.fixture(autouse=True, scope=\"module\")\n def xunit_setup_module_fixture(request):\n if setup_module is not None:\n _call_with_optional_argument(setup_module, request.module)\n yield\n if teardown_module is not None:\n _call_with_optional_argument(teardown_module, request.module)\n\n self.obj.__pytest_setup_module = xunit_setup_module_fixture"},{"className":"filterfalse","col":0,"comment":"null","endLoc":86,"id":1417,"nodeType":"Class","startLoc":83,"text":"class filterfalse(Iterator[_T]):\n def __init__(self, predicate: _Predicate[_T] | None, iterable: Iterable[_T], /) -> None: ...\n def __iter__(self) -> Self: ...\n def __next__(self) -> _T: ..."},{"col":4,"comment":"Injects a hidden autouse, function scoped fixture into the collected module object\n that invokes setup_function/teardown_function if either or both are available.\n\n Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with\n other fixtures (#517).\n ","endLoc":501,"header":"def _inject_setup_function_fixture(self)","id":1418,"name":"_inject_setup_function_fixture","nodeType":"Function","startLoc":476,"text":"def _inject_setup_function_fixture(self):\n \"\"\"Injects a hidden autouse, function scoped fixture into the collected module object\n that invokes setup_function/teardown_function if either or both are available.\n\n Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with\n other fixtures (#517).\n \"\"\"\n setup_function = _get_non_fixture_func(self.obj, \"setup_function\")\n teardown_function = _get_non_fixture_func(self.obj, \"teardown_function\")\n if setup_function is None and teardown_function is None:\n return\n\n @fixtures.fixture(autouse=True, scope=\"function\")\n def xunit_setup_function_fixture(request):\n if request.instance is not None:\n # in this case we are bound to an instance, so we need to let\n # setup_method handle this\n yield\n return\n if setup_function is not None:\n _call_with_optional_argument(setup_function, request.function)\n yield\n if teardown_function is not None:\n _call_with_optional_argument(teardown_function, request.function)\n\n self.obj.__pytest_setup_function = xunit_setup_function_fixture"},{"col":4,"comment":"null","endLoc":396,"header":"def test_numpy_expecting_nan(self)","id":1419,"name":"test_numpy_expecting_nan","nodeType":"Function","startLoc":380,"text":"def test_numpy_expecting_nan(self):\n np = pytest.importorskip(\"numpy\")\n examples = [\n (eq, nan, nan),\n (eq, -nan, -nan),\n (eq, nan, -nan),\n (ne, 0.0, nan),\n (ne, inf, nan),\n ]\n for op, a, x in examples:\n # Nothing is equal to NaN by default.\n assert np.array(a) != approx(x)\n assert a != approx(np.array(x))\n\n # If ``nan_ok=True``, then NaN is equal to NaN.\n assert op(np.array(a), approx(x, nan_ok=True))\n assert op(a, approx(np.array(x), nan_ok=True))"},{"className":"Package","col":0,"comment":"null","endLoc":666,"id":1420,"nodeType":"Class","startLoc":554,"text":"class Package(Module):\n def __init__(self, fspath, parent=None, config=None, session=None, nodeid=None):\n session = parent.session\n nodes.FSCollector.__init__(\n self, fspath, parent=parent, config=config, session=session, nodeid=nodeid\n )\n self.name = fspath.dirname\n self.trace = session.trace\n self._norecursepatterns = session._norecursepatterns\n self.fspath = fspath\n\n def setup(self):\n # not using fixtures to call setup_module here because autouse fixtures\n # from packages are not called automatically (#4085)\n setup_module = _get_non_fixture_func(self.obj, \"setUpModule\")\n if setup_module is None:\n setup_module = _get_non_fixture_func(self.obj, \"setup_module\")\n if setup_module is not None:\n _call_with_optional_argument(setup_module, self.obj)\n\n teardown_module = _get_non_fixture_func(self.obj, \"tearDownModule\")\n if teardown_module is None:\n teardown_module = _get_non_fixture_func(self.obj, \"teardown_module\")\n if teardown_module is not None:\n func = partial(_call_with_optional_argument, teardown_module, self.obj)\n self.addfinalizer(func)\n\n def _recurse(self, dirpath):\n if dirpath.basename == \"__pycache__\":\n return False\n ihook = self.gethookproxy(dirpath.dirpath())\n if ihook.pytest_ignore_collect(path=dirpath, config=self.config):\n return\n for pat in self._norecursepatterns:\n if dirpath.check(fnmatch=pat):\n return False\n ihook = self.gethookproxy(dirpath)\n ihook.pytest_collect_directory(path=dirpath, parent=self)\n return True\n\n def gethookproxy(self, fspath):\n # check if we have the common case of running\n # hooks with all conftest.py filesall conftest.py\n pm = self.config.pluginmanager\n my_conftestmodules = pm._getconftestmodules(fspath)\n remove_mods = pm._conftest_plugins.difference(my_conftestmodules)\n if remove_mods:\n # one or more conftests are not in use at this fspath\n proxy = FSHookProxy(fspath, pm, remove_mods)\n else:\n # all plugis are active for this fspath\n proxy = self.config.hook\n return proxy\n\n def _collectfile(self, path, handle_dupes=True):\n assert path.isfile(), \"%r is not a file (isdir=%r, exists=%r, islink=%r)\" % (\n path,\n path.isdir(),\n path.exists(),\n path.islink(),\n )\n ihook = self.gethookproxy(path)\n if not self.isinitpath(path):\n if ihook.pytest_ignore_collect(path=path, config=self.config):\n return ()\n\n if handle_dupes:\n keepduplicates = self.config.getoption(\"keepduplicates\")\n if not keepduplicates:\n duplicate_paths = self.config.pluginmanager._duplicatepaths\n if path in duplicate_paths:\n return ()\n else:\n duplicate_paths.add(path)\n\n if self.fspath == path: # __init__.py\n return [self]\n\n return ihook.pytest_collect_file(path=path, parent=self)\n\n def isinitpath(self, path):\n return path in self.session._initialpaths\n\n def collect(self):\n this_path = self.fspath.dirpath()\n init_module = this_path.join(\"__init__.py\")\n if init_module.check(file=1) and path_matches_patterns(\n init_module, self.config.getini(\"python_files\")\n ):\n yield Module(init_module, self)\n pkg_prefixes = set()\n for path in this_path.visit(rec=self._recurse, bf=True, sort=True):\n # We will visit our own __init__.py file, in which case we skip it.\n is_file = path.isfile()\n if is_file:\n if path.basename == \"__init__.py\" and path.dirpath() == this_path:\n continue\n\n parts_ = parts(path.strpath)\n if any(\n pkg_prefix in parts_ and pkg_prefix.join(\"__init__.py\") != path\n for pkg_prefix in pkg_prefixes\n ):\n continue\n\n if is_file:\n for x in self._collectfile(path):\n yield x\n elif not path.isdir():\n # Broken symlink or invalid/missing file.\n continue\n elif path.join(\"__init__.py\").check(file=1):\n pkg_prefixes.add(path)"},{"col":4,"comment":"null","endLoc":563,"header":"def __init__(self, fspath, parent=None, config=None, session=None, nodeid=None)","id":1421,"name":"__init__","nodeType":"Function","startLoc":555,"text":"def __init__(self, fspath, parent=None, config=None, session=None, nodeid=None):\n session = parent.session\n nodes.FSCollector.__init__(\n self, fspath, parent=parent, config=config, session=session, nodeid=nodeid\n )\n self.name = fspath.dirname\n self.trace = session.trace\n self._norecursepatterns = session._norecursepatterns\n self.fspath = fspath"},{"col":4,"comment":"null","endLoc":579,"header":"def setup(self)","id":1422,"name":"setup","nodeType":"Function","startLoc":565,"text":"def setup(self):\n # not using fixtures to call setup_module here because autouse fixtures\n # from packages are not called automatically (#4085)\n setup_module = _get_non_fixture_func(self.obj, \"setUpModule\")\n if setup_module is None:\n setup_module = _get_non_fixture_func(self.obj, \"setup_module\")\n if setup_module is not None:\n _call_with_optional_argument(setup_module, self.obj)\n\n teardown_module = _get_non_fixture_func(self.obj, \"tearDownModule\")\n if teardown_module is None:\n teardown_module = _get_non_fixture_func(self.obj, \"teardown_module\")\n if teardown_module is not None:\n func = partial(_call_with_optional_argument, teardown_module, self.obj)\n self.addfinalizer(func)"},{"col":4,"comment":"null","endLoc":403,"header":"@overload\n def __init__(self) -> None","id":1423,"name":"__init__","nodeType":"Function","startLoc":402,"text":"@overload\n def __init__(self) -> None: ..."},{"col":4,"comment":"null","endLoc":405,"header":"@overload\n def __init__(self: defaultdict[str, _VT], **kwargs: _VT) -> None","id":1424,"name":"__init__","nodeType":"Function","startLoc":404,"text":"@overload\n def __init__(self: defaultdict[str, _VT], **kwargs: _VT) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780"},{"col":4,"comment":"null","endLoc":407,"header":"@overload\n def __init__(self, default_factory: Callable[[], _VT] | None, /) -> None","id":1425,"name":"__init__","nodeType":"Function","startLoc":406,"text":"@overload\n def __init__(self, default_factory: Callable[[], _VT] | None, /) -> None: ..."},{"col":4,"comment":"null","endLoc":414,"header":"@overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n /,\n **kwargs: _VT,\n ) -> None","id":1426,"name":"__init__","nodeType":"Function","startLoc":408,"text":"@overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n /,\n **kwargs: _VT,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":416,"header":"@overload\n def __init__(self, default_factory: Callable[[], _VT] | None, map: SupportsKeysAndGetItem[_KT, _VT], /) -> None","id":1427,"name":"__init__","nodeType":"Function","startLoc":415,"text":"@overload\n def __init__(self, default_factory: Callable[[], _VT] | None, map: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ..."},{"col":4,"comment":"null","endLoc":424,"header":"@overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n map: SupportsKeysAndGetItem[str, _VT],\n /,\n **kwargs: _VT,\n ) -> None","id":1428,"name":"__init__","nodeType":"Function","startLoc":417,"text":"@overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n map: SupportsKeysAndGetItem[str, _VT],\n /,\n **kwargs: _VT,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":426,"header":"@overload\n def __init__(self, default_factory: Callable[[], _VT] | None, iterable: Iterable[tuple[_KT, _VT]], /) -> None","id":1429,"name":"__init__","nodeType":"Function","startLoc":425,"text":"@overload\n def __init__(self, default_factory: Callable[[], _VT] | None, iterable: Iterable[tuple[_KT, _VT]], /) -> None: ..."},{"col":4,"comment":"null","endLoc":434,"header":"@overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n iterable: Iterable[tuple[str, _VT]],\n /,\n **kwargs: _VT,\n ) -> None","id":1430,"name":"__init__","nodeType":"Function","startLoc":427,"text":"@overload\n def __init__(\n self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780\n default_factory: Callable[[], _VT] | None,\n iterable: Iterable[tuple[str, _VT]],\n /,\n **kwargs: _VT,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":435,"header":"def __missing__(self, key: _KT, /) -> _VT","id":1431,"name":"__missing__","nodeType":"Function","startLoc":435,"text":"def __missing__(self, key: _KT, /) -> _VT: ..."},{"col":4,"comment":"null","endLoc":436,"header":"def __copy__(self) -> Self","id":1432,"name":"__copy__","nodeType":"Function","startLoc":436,"text":"def __copy__(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":437,"header":"def copy(self) -> Self","id":1433,"name":"copy","nodeType":"Function","startLoc":437,"text":"def copy(self) -> Self: ..."},{"col":8,"comment":"null","endLoc":440,"header":"@overload\n def __or__(self, value: dict[_KT, _VT], /) -> Self","id":1434,"name":"__or__","nodeType":"Function","startLoc":439,"text":"@overload\n def __or__(self, value: dict[_KT, _VT], /) -> Self: ..."},{"col":8,"comment":"null","endLoc":442,"header":"@overload\n def __or__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]","id":1435,"name":"__or__","nodeType":"Function","startLoc":441,"text":"@overload\n def __or__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ..."},{"col":8,"comment":"null","endLoc":444,"header":"@overload\n def __ror__(self, value: dict[_KT, _VT], /) -> Self","id":1436,"name":"__ror__","nodeType":"Function","startLoc":443,"text":"@overload\n def __ror__(self, value: dict[_KT, _VT], /) -> Self: ..."},{"col":8,"comment":"null","endLoc":446,"header":"@overload\n def __ror__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]","id":1437,"name":"__ror__","nodeType":"Function","startLoc":445,"text":"@overload\n def __ror__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc]"},{"attributeType":"() -> _VT | None","col":4,"comment":"null","endLoc":401,"id":1438,"name":"default_factory","nodeType":"Attribute","startLoc":401,"text":"default_factory"},{"col":4,"comment":"null","endLoc":410,"header":"def test_numpy_expecting_inf(self)","id":1439,"name":"test_numpy_expecting_inf","nodeType":"Function","startLoc":398,"text":"def test_numpy_expecting_inf(self):\n np = pytest.importorskip(\"numpy\")\n examples = [\n (eq, inf, inf),\n (eq, -inf, -inf),\n (ne, inf, -inf),\n (ne, 0.0, inf),\n (ne, nan, inf),\n ]\n for op, a, x in examples:\n assert op(np.array(a), approx(x))\n assert op(a, approx(np.array(x)))\n assert op(np.array(a), approx(np.array(x)))"},{"className":"deque","col":0,"comment":"null","endLoc":275,"id":1440,"nodeType":"Class","startLoc":238,"text":"class deque(MutableSequence[_T]):\n @property\n def maxlen(self) -> int | None: ...\n @overload\n def __init__(self, *, maxlen: int | None = None) -> None: ...\n @overload\n def __init__(self, iterable: Iterable[_T], maxlen: int | None = None) -> None: ...\n def append(self, x: _T, /) -> None: ...\n def appendleft(self, x: _T, /) -> None: ...\n def copy(self) -> Self: ...\n def count(self, x: _T, /) -> int: ...\n def extend(self, iterable: Iterable[_T], /) -> None: ...\n def extendleft(self, iterable: Iterable[_T], /) -> None: ...\n def insert(self, i: int, x: _T, /) -> None: ...\n def index(self, x: _T, start: int = 0, stop: int = ..., /) -> int: ...\n def pop(self) -> _T: ... # type: ignore[override]\n def popleft(self) -> _T: ...\n def remove(self, value: _T, /) -> None: ...\n def rotate(self, n: int = 1, /) -> None: ...\n def __copy__(self) -> Self: ...\n def __len__(self) -> int: ...\n # These methods of deque don't take slices, unlike MutableSequence, hence the type: ignores\n def __getitem__(self, key: SupportsIndex, /) -> _T: ... # type: ignore[override]\n def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: ... # type: ignore[override]\n def __delitem__(self, key: SupportsIndex, /) -> None: ... # type: ignore[override]\n def __contains__(self, key: object, /) -> bool: ...\n def __reduce__(self) -> tuple[type[Self], tuple[()], None, Iterator[_T]]: ...\n def __iadd__(self, value: Iterable[_T], /) -> Self: ...\n def __add__(self, value: Self, /) -> Self: ...\n def __mul__(self, value: int, /) -> Self: ...\n def __imul__(self, value: int, /) -> Self: ...\n def __lt__(self, value: deque[_T], /) -> bool: ...\n def __le__(self, value: deque[_T], /) -> bool: ...\n def __gt__(self, value: deque[_T], /) -> bool: ...\n def __ge__(self, value: deque[_T], /) -> bool: ...\n def __eq__(self, value: object, /) -> bool: ...\n if sys.version_info >= (3, 9):\n def __class_getitem__(cls, item: Any, /) -> GenericAlias: ..."},{"col":4,"comment":"null","endLoc":240,"header":"@property\n def maxlen(self) -> int | None","id":1441,"name":"maxlen","nodeType":"Function","startLoc":239,"text":"@property\n def maxlen(self) -> int | None: ..."},{"col":4,"comment":"null","endLoc":242,"header":"@overload\n def __init__(self, *, maxlen: int | None = None) -> None","id":1442,"name":"__init__","nodeType":"Function","startLoc":241,"text":"@overload\n def __init__(self, *, maxlen: int | None = None) -> None: ..."},{"col":4,"comment":"null","endLoc":244,"header":"@overload\n def __init__(self, iterable: Iterable[_T], maxlen: int | None = None) -> None","id":1443,"name":"__init__","nodeType":"Function","startLoc":243,"text":"@overload\n def __init__(self, iterable: Iterable[_T], maxlen: int | None = None) -> None: ..."},{"col":4,"comment":"null","endLoc":245,"header":"def append(self, x: _T, /) -> None","id":1444,"name":"append","nodeType":"Function","startLoc":245,"text":"def append(self, x: _T, /) -> None: ..."},{"col":4,"comment":"null","endLoc":246,"header":"def appendleft(self, x: _T, /) -> None","id":1445,"name":"appendleft","nodeType":"Function","startLoc":246,"text":"def appendleft(self, x: _T, /) -> None: ..."},{"col":4,"comment":"null","endLoc":247,"header":"def copy(self) -> Self","id":1446,"name":"copy","nodeType":"Function","startLoc":247,"text":"def copy(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":248,"header":"def count(self, x: _T, /) -> int","id":1447,"name":"count","nodeType":"Function","startLoc":248,"text":"def count(self, x: _T, /) -> int: ..."},{"col":4,"comment":"null","endLoc":249,"header":"def extend(self, iterable: Iterable[_T], /) -> None","id":1448,"name":"extend","nodeType":"Function","startLoc":249,"text":"def extend(self, iterable: Iterable[_T], /) -> None: ..."},{"col":4,"comment":"null","endLoc":250,"header":"def extendleft(self, iterable: Iterable[_T], /) -> None","id":1449,"name":"extendleft","nodeType":"Function","startLoc":250,"text":"def extendleft(self, iterable: Iterable[_T], /) -> None: ..."},{"col":4,"comment":"null","endLoc":251,"header":"def insert(self, i: int, x: _T, /) -> None","id":1450,"name":"insert","nodeType":"Function","startLoc":251,"text":"def insert(self, i: int, x: _T, /) -> None: ..."},{"col":4,"comment":"null","endLoc":252,"header":"def index(self, x: _T, start: int = 0, stop: int = ..., /) -> int","id":1451,"name":"index","nodeType":"Function","startLoc":252,"text":"def index(self, x: _T, start: int = 0, stop: int = ..., /) -> int: ..."},{"col":4,"comment":"null","endLoc":253,"header":"def pop(self) -> _T","id":1452,"name":"pop","nodeType":"Function","startLoc":253,"text":"def pop(self) -> _T: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":254,"header":"def popleft(self) -> _T","id":1453,"name":"popleft","nodeType":"Function","startLoc":254,"text":"def popleft(self) -> _T: ..."},{"col":4,"comment":"null","endLoc":255,"header":"def remove(self, value: _T, /) -> None","id":1454,"name":"remove","nodeType":"Function","startLoc":255,"text":"def remove(self, value: _T, /) -> None: ..."},{"col":4,"comment":"null","endLoc":256,"header":"def rotate(self, n: int = 1, /) -> None","id":1455,"name":"rotate","nodeType":"Function","startLoc":256,"text":"def rotate(self, n: int = 1, /) -> None: ..."},{"col":4,"comment":"null","endLoc":257,"header":"def __copy__(self) -> Self","id":1456,"name":"__copy__","nodeType":"Function","startLoc":257,"text":"def __copy__(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":258,"header":"def __len__(self) -> int","id":1457,"name":"__len__","nodeType":"Function","startLoc":258,"text":"def __len__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":260,"header":"def __getitem__(self, key: SupportsIndex, /) -> _T","id":1458,"name":"__getitem__","nodeType":"Function","startLoc":260,"text":"def __getitem__(self, key: SupportsIndex, /) -> _T: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":261,"header":"def __setitem__(self, key: SupportsIndex, value: _T, /) -> None","id":1459,"name":"__setitem__","nodeType":"Function","startLoc":261,"text":"def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":262,"header":"def __delitem__(self, key: SupportsIndex, /) -> None","id":1460,"name":"__delitem__","nodeType":"Function","startLoc":262,"text":"def __delitem__(self, key: SupportsIndex, /) -> None: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":263,"header":"def __contains__(self, key: object, /) -> bool","id":1461,"name":"__contains__","nodeType":"Function","startLoc":263,"text":"def __contains__(self, key: object, /) -> bool: ..."},{"col":4,"comment":"null","endLoc":264,"header":"def __reduce__(self) -> tuple[type[Self], tuple[()], None, Iterator[_T]]","id":1462,"name":"__reduce__","nodeType":"Function","startLoc":264,"text":"def __reduce__(self) -> tuple[type[Self], tuple[()], None, Iterator[_T]]: ..."},{"col":4,"comment":"null","endLoc":265,"header":"def __iadd__(self, value: Iterable[_T], /) -> Self","id":1463,"name":"__iadd__","nodeType":"Function","startLoc":265,"text":"def __iadd__(self, value: Iterable[_T], /) -> Self: ..."},{"col":4,"comment":"null","endLoc":266,"header":"def __add__(self, value: Self, /) -> Self","id":1464,"name":"__add__","nodeType":"Function","startLoc":266,"text":"def __add__(self, value: Self, /) -> Self: ..."},{"col":4,"comment":"null","endLoc":267,"header":"def __mul__(self, value: int, /) -> Self","id":1465,"name":"__mul__","nodeType":"Function","startLoc":267,"text":"def __mul__(self, value: int, /) -> Self: ..."},{"col":4,"comment":"null","endLoc":268,"header":"def __imul__(self, value: int, /) -> Self","id":1466,"name":"__imul__","nodeType":"Function","startLoc":268,"text":"def __imul__(self, value: int, /) -> Self: ..."},{"col":4,"comment":"null","endLoc":269,"header":"def __lt__(self, value: deque[_T], /) -> bool","id":1467,"name":"__lt__","nodeType":"Function","startLoc":269,"text":"def __lt__(self, value: deque[_T], /) -> bool: ..."},{"col":4,"comment":"null","endLoc":270,"header":"def __le__(self, value: deque[_T], /) -> bool","id":1468,"name":"__le__","nodeType":"Function","startLoc":270,"text":"def __le__(self, value: deque[_T], /) -> bool: ..."},{"col":4,"comment":"null","endLoc":271,"header":"def __gt__(self, value: deque[_T], /) -> bool","id":1469,"name":"__gt__","nodeType":"Function","startLoc":271,"text":"def __gt__(self, value: deque[_T], /) -> bool: ..."},{"col":4,"comment":"null","endLoc":272,"header":"def __ge__(self, value: deque[_T], /) -> bool","id":1470,"name":"__ge__","nodeType":"Function","startLoc":272,"text":"def __ge__(self, value: deque[_T], /) -> bool: ..."},{"col":4,"comment":"null","endLoc":273,"header":"def __eq__(self, value: object, /) -> bool","id":1471,"name":"__eq__","nodeType":"Function","startLoc":273,"text":"def __eq__(self, value: object, /) -> bool: ..."},{"col":8,"comment":"null","endLoc":275,"header":"def __class_getitem__(cls, item: Any, /) -> GenericAlias","id":1472,"name":"__class_getitem__","nodeType":"Function","startLoc":275,"text":"def __class_getitem__(cls, item: Any, /) -> GenericAlias: ..."},{"className":"OrderedDict","col":0,"comment":"null","endLoc":398,"id":1473,"nodeType":"Class","startLoc":360,"text":"class OrderedDict(dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]):\n def popitem(self, last: bool = True) -> tuple[_KT, _VT]: ...\n def move_to_end(self, key: _KT, last: bool = True) -> None: ...\n def copy(self) -> Self: ...\n def __reversed__(self) -> Iterator[_KT]: ...\n def keys(self) -> _odict_keys[_KT, _VT]: ...\n def items(self) -> _odict_items[_KT, _VT]: ...\n def values(self) -> _odict_values[_KT, _VT]: ...\n # The signature of OrderedDict.fromkeys should be kept in line with `dict.fromkeys`, modulo positional-only differences.\n # Like dict.fromkeys, its true signature is not expressible in the current type system.\n # See #3800 & https://github.com/python/typing/issues/548#issuecomment-683336963.\n @classmethod\n @overload\n def fromkeys(cls, iterable: Iterable[_T], value: None = None) -> OrderedDict[_T, Any | None]: ...\n @classmethod\n @overload\n def fromkeys(cls, iterable: Iterable[_T], value: _S) -> OrderedDict[_T, _S]: ...\n # Keep OrderedDict.setdefault in line with MutableMapping.setdefault, modulo positional-only differences.\n @overload\n def setdefault(self: OrderedDict[_KT, _T | None], key: _KT, default: None = None) -> _T | None: ...\n @overload\n def setdefault(self, key: _KT, default: _VT) -> _VT: ...\n # Same as dict.pop, but accepts keyword arguments\n @overload\n def pop(self, key: _KT) -> _VT: ...\n @overload\n def pop(self, key: _KT, default: _VT) -> _VT: ...\n @overload\n def pop(self, key: _KT, default: _T) -> _VT | _T: ...\n def __eq__(self, value: object, /) -> bool: ...\n if sys.version_info >= (3, 9):\n @overload\n def __or__(self, value: dict[_KT, _VT], /) -> Self: ...\n @overload\n def __or__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ...\n @overload\n def __ror__(self, value: dict[_KT, _VT], /) -> Self: ...\n @overload\n def __ror__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc]"},{"col":4,"comment":"null","endLoc":85,"header":"def __iter__(self) -> Self","id":1474,"name":"__iter__","nodeType":"Function","startLoc":85,"text":"def __iter__(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":86,"header":"def __next__(self) -> _T","id":1475,"name":"__next__","nodeType":"Function","startLoc":86,"text":"def __next__(self) -> _T: ..."},{"className":"filterfalse","col":0,"comment":"\n Return those items of iterable for which function(item) is false.\n \n If function is None, return the items that are false.\n ","endLoc":366,"id":1476,"nodeType":"Class","startLoc":338,"text":"class filterfalse(object):\n \"\"\"\n Return those items of iterable for which function(item) is false.\n \n If function is None, return the items that are false.\n \"\"\"\n def __getattribute__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return getattr(self, name). \"\"\"\n pass\n\n def __init__(self, *args, **kwargs): # real signature unknown\n pass\n\n def __iter__(self, *args, **kwargs): # real signature unknown\n \"\"\" Implement iter(self). \"\"\"\n pass\n\n @staticmethod # known case of __new__\n def __new__(*args, **kwargs): # real signature unknown\n \"\"\" Create and return a new object. See help(type) for accurate signature. \"\"\"\n pass\n\n def __next__(self, *args, **kwargs): # real signature unknown\n \"\"\" Implement next(self). \"\"\"\n pass\n\n def __reduce__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return state information for pickling. \"\"\"\n pass"},{"col":4,"comment":"null","endLoc":419,"header":"def test_numpy_array_wrong_shape(self)","id":1477,"name":"test_numpy_array_wrong_shape","nodeType":"Function","startLoc":412,"text":"def test_numpy_array_wrong_shape(self):\n np = pytest.importorskip(\"numpy\")\n\n a12 = np.array([[1, 2]])\n a21 = np.array([[1], [2]])\n\n assert a12 != approx(a21)\n assert a21 != approx(a12)"},{"col":4,"comment":"null","endLoc":361,"header":"def popitem(self, last: bool = True) -> tuple[_KT, _VT]","id":1478,"name":"popitem","nodeType":"Function","startLoc":361,"text":"def popitem(self, last: bool = True) -> tuple[_KT, _VT]: ..."},{"col":4,"comment":"null","endLoc":362,"header":"def move_to_end(self, key: _KT, last: bool = True) -> None","id":1479,"name":"move_to_end","nodeType":"Function","startLoc":362,"text":"def move_to_end(self, key: _KT, last: bool = True) -> None: ..."},{"col":4,"comment":"null","endLoc":363,"header":"def copy(self) -> Self","id":1480,"name":"copy","nodeType":"Function","startLoc":363,"text":"def copy(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":364,"header":"def __reversed__(self) -> Iterator[_KT]","id":1481,"name":"__reversed__","nodeType":"Function","startLoc":364,"text":"def __reversed__(self) -> Iterator[_KT]: ..."},{"col":4,"comment":"null","endLoc":365,"header":"def keys(self) -> _odict_keys[_KT, _VT]","id":1482,"name":"keys","nodeType":"Function","startLoc":365,"text":"def keys(self) -> _odict_keys[_KT, _VT]: ..."},{"col":4,"comment":"null","endLoc":366,"header":"def items(self) -> _odict_items[_KT, _VT]","id":1483,"name":"items","nodeType":"Function","startLoc":366,"text":"def items(self) -> _odict_items[_KT, _VT]: ..."},{"col":4,"comment":"null","endLoc":367,"header":"def values(self) -> _odict_values[_KT, _VT]","id":1484,"name":"values","nodeType":"Function","startLoc":367,"text":"def values(self) -> _odict_values[_KT, _VT]: ..."},{"col":4,"comment":"null","endLoc":373,"header":"@classmethod\n @overload\n def fromkeys(cls, iterable: Iterable[_T], value: None = None) -> OrderedDict[_T, Any | None]","id":1485,"name":"fromkeys","nodeType":"Function","startLoc":371,"text":"@classmethod\n @overload\n def fromkeys(cls, iterable: Iterable[_T], value: None = None) -> OrderedDict[_T, Any | None]: ..."},{"col":4,"comment":"null","endLoc":427,"header":"def test_doctests(self)","id":1486,"name":"test_doctests","nodeType":"Function","startLoc":421,"text":"def test_doctests(self):\n parser = doctest.DocTestParser()\n test = parser.get_doctest(\n approx.__doc__, {\"approx\": approx}, approx.__name__, None, None\n )\n runner = MyDocTestRunner()\n runner.run(test)"},{"col":4,"comment":"null","endLoc":376,"header":"@classmethod\n @overload\n def fromkeys(cls, iterable: Iterable[_T], value: _S) -> OrderedDict[_T, _S]","id":1487,"name":"fromkeys","nodeType":"Function","startLoc":374,"text":"@classmethod\n @overload\n def fromkeys(cls, iterable: Iterable[_T], value: _S) -> OrderedDict[_T, _S]: ..."},{"col":4,"comment":"null","endLoc":379,"header":"@overload\n def setdefault(self: OrderedDict[_KT, _T | None], key: _KT, default: None = None) -> _T | None","id":1488,"name":"setdefault","nodeType":"Function","startLoc":378,"text":"@overload\n def setdefault(self: OrderedDict[_KT, _T | None], key: _KT, default: None = None) -> _T | None: ..."},{"col":4,"comment":"null","endLoc":381,"header":"@overload\n def setdefault(self, key: _KT, default: _VT) -> _VT","id":1489,"name":"setdefault","nodeType":"Function","startLoc":380,"text":"@overload\n def setdefault(self, key: _KT, default: _VT) -> _VT: ..."},{"col":4,"comment":"null","endLoc":384,"header":"@overload\n def pop(self, key: _KT) -> _VT","id":1490,"name":"pop","nodeType":"Function","startLoc":383,"text":"@overload\n def pop(self, key: _KT) -> _VT: ..."},{"col":4,"comment":"null","endLoc":386,"header":"@overload\n def pop(self, key: _KT, default: _VT) -> _VT","id":1491,"name":"pop","nodeType":"Function","startLoc":385,"text":"@overload\n def pop(self, key: _KT, default: _VT) -> _VT: ..."},{"col":4,"comment":"null","endLoc":388,"header":"@overload\n def pop(self, key: _KT, default: _T) -> _VT | _T","id":1492,"name":"pop","nodeType":"Function","startLoc":387,"text":"@overload\n def pop(self, key: _KT, default: _T) -> _VT | _T: ..."},{"col":4,"comment":"null","endLoc":389,"header":"def __eq__(self, value: object, /) -> bool","id":1493,"name":"__eq__","nodeType":"Function","startLoc":389,"text":"def __eq__(self, value: object, /) -> bool: ..."},{"col":8,"comment":"null","endLoc":392,"header":"@overload\n def __or__(self, value: dict[_KT, _VT], /) -> Self","id":1494,"name":"__or__","nodeType":"Function","startLoc":391,"text":"@overload\n def __or__(self, value: dict[_KT, _VT], /) -> Self: ..."},{"col":8,"comment":"null","endLoc":394,"header":"@overload\n def __or__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]","id":1495,"name":"__or__","nodeType":"Function","startLoc":393,"text":"@overload\n def __or__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ..."},{"col":8,"comment":"null","endLoc":396,"header":"@overload\n def __ror__(self, value: dict[_KT, _VT], /) -> Self","id":1496,"name":"__ror__","nodeType":"Function","startLoc":395,"text":"@overload\n def __ror__(self, value: dict[_KT, _VT], /) -> Self: ..."},{"col":8,"comment":"null","endLoc":398,"header":"@overload\n def __ror__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]","id":1497,"name":"__ror__","nodeType":"Function","startLoc":397,"text":"@overload\n def __ror__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc]"},{"className":"FormattedExcinfo","col":0,"comment":" presenting information about failing Functions and Generators. ","endLoc":839,"id":1498,"nodeType":"Class","startLoc":585,"text":"@attr.s\nclass FormattedExcinfo(object):\n \"\"\" presenting information about failing Functions and Generators. \"\"\"\n\n # for traceback entries\n flow_marker = \">\"\n fail_marker = \"E\"\n\n showlocals = attr.ib(default=False)\n style = attr.ib(default=\"long\")\n abspath = attr.ib(default=True)\n tbfilter = attr.ib(default=True)\n funcargs = attr.ib(default=False)\n truncate_locals = attr.ib(default=True)\n chain = attr.ib(default=True)\n astcache = attr.ib(default=attr.Factory(dict), init=False, repr=False)\n\n def _getindent(self, source):\n # figure out indent for given source\n try:\n s = str(source.getstatement(len(source) - 1))\n except KeyboardInterrupt:\n raise\n except: # noqa\n try:\n s = str(source[-1])\n except KeyboardInterrupt:\n raise\n except: # noqa\n return 0\n return 4 + (len(s) - len(s.lstrip()))\n\n def _getentrysource(self, entry):\n source = entry.getsource(self.astcache)\n if source is not None:\n source = source.deindent()\n return source\n\n def repr_args(self, entry):\n if self.funcargs:\n args = []\n for argname, argvalue in entry.frame.getargs(var=True):\n args.append((argname, saferepr(argvalue)))\n return ReprFuncArgs(args)\n\n def get_source(self, source, line_index=-1, excinfo=None, short=False):\n \"\"\" return formatted and marked up source lines. \"\"\"\n import _pytest._code\n\n lines = []\n if source is None or line_index >= len(source.lines):\n source = _pytest._code.Source(\"???\")\n line_index = 0\n if line_index < 0:\n line_index += len(source)\n space_prefix = \" \"\n if short:\n lines.append(space_prefix + source.lines[line_index].strip())\n else:\n for line in source.lines[:line_index]:\n lines.append(space_prefix + line)\n lines.append(self.flow_marker + \" \" + source.lines[line_index])\n for line in source.lines[line_index + 1 :]:\n lines.append(space_prefix + line)\n if excinfo is not None:\n indent = 4 if short else self._getindent(source)\n lines.extend(self.get_exconly(excinfo, indent=indent, markall=True))\n return lines\n\n def get_exconly(self, excinfo, indent=4, markall=False):\n lines = []\n indent = \" \" * indent\n # get the real exception information out\n exlines = excinfo.exconly(tryshort=True).split(\"\\n\")\n failindent = self.fail_marker + indent[1:]\n for line in exlines:\n lines.append(failindent + line)\n if not markall:\n failindent = indent\n return lines\n\n def repr_locals(self, locals):\n if self.showlocals:\n lines = []\n keys = [loc for loc in locals if loc[0] != \"@\"]\n keys.sort()\n for name in keys:\n value = locals[name]\n if name == \"__builtins__\":\n lines.append(\"__builtins__ = \")\n else:\n # This formatting could all be handled by the\n # _repr() function, which is only reprlib.Repr in\n # disguise, so is very configurable.\n if self.truncate_locals:\n str_repr = saferepr(value)\n else:\n str_repr = safeformat(value)\n # if len(str_repr) < 70 or not isinstance(value,\n # (list, tuple, dict)):\n lines.append(\"%-10s = %s\" % (name, str_repr))\n # else:\n # self._line(\"%-10s =\\\\\" % (name,))\n # # XXX\n # pprint.pprint(value, stream=self.excinfowriter)\n return ReprLocals(lines)\n\n def repr_traceback_entry(self, entry, excinfo=None):\n import _pytest._code\n\n source = self._getentrysource(entry)\n if source is None:\n source = _pytest._code.Source(\"???\")\n line_index = 0\n else:\n # entry.getfirstlinesource() can be -1, should be 0 on jython\n line_index = entry.lineno - max(entry.getfirstlinesource(), 0)\n\n lines = []\n style = entry._repr_style\n if style is None:\n style = self.style\n if style in (\"short\", \"long\"):\n short = style == \"short\"\n reprargs = self.repr_args(entry) if not short else None\n s = self.get_source(source, line_index, excinfo, short=short)\n lines.extend(s)\n if short:\n message = \"in %s\" % (entry.name)\n else:\n message = excinfo and excinfo.typename or \"\"\n path = self._makepath(entry.path)\n filelocrepr = ReprFileLocation(path, entry.lineno + 1, message)\n localsrepr = None\n if not short:\n localsrepr = self.repr_locals(entry.locals)\n return ReprEntry(lines, reprargs, localsrepr, filelocrepr, style)\n if excinfo:\n lines.extend(self.get_exconly(excinfo, indent=4))\n return ReprEntry(lines, None, None, None, style)\n\n def _makepath(self, path):\n if not self.abspath:\n try:\n np = py.path.local().bestrelpath(path)\n except OSError:\n return path\n if len(np) < len(str(path)):\n path = np\n return path\n\n def repr_traceback(self, excinfo):\n traceback = excinfo.traceback\n if self.tbfilter:\n traceback = traceback.filter()\n\n if is_recursion_error(excinfo):\n traceback, extraline = self._truncate_recursive_traceback(traceback)\n else:\n extraline = None\n\n last = traceback[-1]\n entries = []\n for index, entry in enumerate(traceback):\n einfo = (last == entry) and excinfo or None\n reprentry = self.repr_traceback_entry(entry, einfo)\n entries.append(reprentry)\n return ReprTraceback(entries, extraline, style=self.style)\n\n def _truncate_recursive_traceback(self, traceback):\n \"\"\"\n Truncate the given recursive traceback trying to find the starting point\n of the recursion.\n\n The detection is done by going through each traceback entry and finding the\n point in which the locals of the frame are equal to the locals of a previous frame (see ``recursionindex()``.\n\n Handle the situation where the recursion process might raise an exception (for example\n comparing numpy arrays using equality raises a TypeError), in which case we do our best to\n warn the user of the error and show a limited traceback.\n \"\"\"\n try:\n recursionindex = traceback.recursionindex()\n except Exception as e:\n max_frames = 10\n extraline = (\n \"!!! Recursion error detected, but an error occurred locating the origin of recursion.\\n\"\n \" The following exception happened when comparing locals in the stack frame:\\n\"\n \" {exc_type}: {exc_msg}\\n\"\n \" Displaying first and last {max_frames} stack frames out of {total}.\"\n ).format(\n exc_type=type(e).__name__,\n exc_msg=safe_str(e),\n max_frames=max_frames,\n total=len(traceback),\n )\n traceback = traceback[:max_frames] + traceback[-max_frames:]\n else:\n if recursionindex is not None:\n extraline = \"!!! Recursion detected (same locals & position)\"\n traceback = traceback[: recursionindex + 1]\n else:\n extraline = None\n\n return traceback, extraline\n\n def repr_excinfo(self, excinfo):\n if _PY2:\n reprtraceback = self.repr_traceback(excinfo)\n reprcrash = excinfo._getreprcrash()\n\n return ReprExceptionInfo(reprtraceback, reprcrash)\n else:\n repr_chain = []\n e = excinfo.value\n descr = None\n seen = set()\n while e is not None and id(e) not in seen:\n seen.add(id(e))\n if excinfo:\n reprtraceback = self.repr_traceback(excinfo)\n reprcrash = excinfo._getreprcrash()\n else:\n # fallback to native repr if the exception doesn't have a traceback:\n # ExceptionInfo objects require a full traceback to work\n reprtraceback = ReprTracebackNative(\n traceback.format_exception(type(e), e, None)\n )\n reprcrash = None\n\n repr_chain += [(reprtraceback, reprcrash, descr)]\n if e.__cause__ is not None and self.chain:\n e = e.__cause__\n excinfo = (\n ExceptionInfo((type(e), e, e.__traceback__))\n if e.__traceback__\n else None\n )\n descr = \"The above exception was the direct cause of the following exception:\"\n elif (\n e.__context__ is not None\n and not e.__suppress_context__\n and self.chain\n ):\n e = e.__context__\n excinfo = (\n ExceptionInfo((type(e), e, e.__traceback__))\n if e.__traceback__\n else None\n )\n descr = \"During handling of the above exception, another exception occurred:\"\n else:\n e = None\n repr_chain.reverse()\n return ExceptionChainRepr(repr_chain)"},{"col":4,"comment":"null","endLoc":615,"header":"def _getindent(self, source)","id":1499,"name":"_getindent","nodeType":"Function","startLoc":602,"text":"def _getindent(self, source):\n # figure out indent for given source\n try:\n s = str(source.getstatement(len(source) - 1))\n except KeyboardInterrupt:\n raise\n except: # noqa\n try:\n s = str(source[-1])\n except KeyboardInterrupt:\n raise\n except: # noqa\n return 0\n return 4 + (len(s) - len(s.lstrip()))"},{"col":4,"comment":"null","endLoc":132,"header":"def __new__(cls, func: Callable[..., _T], /, *args: Any, **kwargs: Any) -> Self","id":1500,"name":"__new__","nodeType":"Function","startLoc":132,"text":"def __new__(cls, func: Callable[..., _T], /, *args: Any, **kwargs: Any) -> Self: ..."},{"col":4,"comment":" Return getattr(self, name). ","endLoc":346,"header":"def __getattribute__(self, *args, **kwargs)","id":1501,"name":"__getattribute__","nodeType":"Function","startLoc":344,"text":"def __getattribute__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return getattr(self, name). \"\"\"\n pass"},{"col":4,"comment":"null","endLoc":349,"header":"def __init__(self, *args, **kwargs)","id":1502,"name":"__init__","nodeType":"Function","startLoc":348,"text":"def __init__(self, *args, **kwargs): # real signature unknown\n pass"},{"col":4,"comment":" Implement iter(self). ","endLoc":353,"header":"def __iter__(self, *args, **kwargs)","id":1503,"name":"__iter__","nodeType":"Function","startLoc":351,"text":"def __iter__(self, *args, **kwargs): # real signature unknown\n \"\"\" Implement iter(self). \"\"\"\n pass"},{"col":4,"comment":" Create and return a new object. See help(type) for accurate signature. ","endLoc":358,"header":"@staticmethod # known case of __new__\n def __new__(*args, **kwargs)","id":1504,"name":"__new__","nodeType":"Function","startLoc":355,"text":"@staticmethod # known case of __new__\n def __new__(*args, **kwargs): # real signature unknown\n \"\"\" Create and return a new object. See help(type) for accurate signature. \"\"\"\n pass"},{"col":4,"comment":" Implement next(self). ","endLoc":362,"header":"def __next__(self, *args, **kwargs)","id":1505,"name":"__next__","nodeType":"Function","startLoc":360,"text":"def __next__(self, *args, **kwargs): # real signature unknown\n \"\"\" Implement next(self). \"\"\"\n pass"},{"col":4,"comment":" Return state information for pickling. ","endLoc":366,"header":"def __reduce__(self, *args, **kwargs)","id":1506,"name":"__reduce__","nodeType":"Function","startLoc":364,"text":"def __reduce__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return state information for pickling. \"\"\"\n pass"},{"col":4,"comment":"null","endLoc":643,"header":"def pytest_collectreport(self, report)","id":1507,"name":"pytest_collectreport","nodeType":"Function","startLoc":637,"text":"def pytest_collectreport(self, report):\n if not report.passed:\n reporter = self._opentestcase(report)\n if report.failed:\n reporter.append_collect_error(report)\n else:\n reporter.append_collect_skipped(report)"},{"col":4,"comment":"null","endLoc":648,"header":"def pytest_internalerror(self, excrepr)","id":1508,"name":"pytest_internalerror","nodeType":"Function","startLoc":645,"text":"def pytest_internalerror(self, excrepr):\n reporter = self.node_reporter(\"internal\")\n reporter.attrs.update(classname=\"pytest\", name=\"internal\")\n reporter._add_simple(Junit.error, \"internal error\", excrepr)"},{"className":"zip","col":0,"comment":"null","endLoc":1900,"id":1509,"nodeType":"Class","startLoc":1820,"text":"class zip(Iterator[_T_co], Generic[_T_co]):\n if sys.version_info >= (3, 10):\n @overload\n def __new__(cls, *, strict: bool = ...) -> zip[Any]: ...\n @overload\n def __new__(cls, __iter1: Iterable[_T1], *, strict: bool = ...) -> zip[tuple[_T1]]: ...\n @overload\n def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], *, strict: bool = ...) -> zip[tuple[_T1, _T2]]: ...\n @overload\n def __new__(\n cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], *, strict: bool = ...\n ) -> zip[tuple[_T1, _T2, _T3]]: ...\n @overload\n def __new__(\n cls,\n __iter1: Iterable[_T1],\n __iter2: Iterable[_T2],\n __iter3: Iterable[_T3],\n __iter4: Iterable[_T4],\n *,\n strict: bool = ...,\n ) -> zip[tuple[_T1, _T2, _T3, _T4]]: ...\n @overload\n def __new__(\n cls,\n __iter1: Iterable[_T1],\n __iter2: Iterable[_T2],\n __iter3: Iterable[_T3],\n __iter4: Iterable[_T4],\n __iter5: Iterable[_T5],\n *,\n strict: bool = ...,\n ) -> zip[tuple[_T1, _T2, _T3, _T4, _T5]]: ...\n @overload\n def __new__(\n cls,\n __iter1: Iterable[Any],\n __iter2: Iterable[Any],\n __iter3: Iterable[Any],\n __iter4: Iterable[Any],\n __iter5: Iterable[Any],\n __iter6: Iterable[Any],\n *iterables: Iterable[Any],\n strict: bool = ...,\n ) -> zip[tuple[Any, ...]]: ...\n else:\n @overload\n def __new__(cls) -> zip[Any]: ...\n @overload\n def __new__(cls, __iter1: Iterable[_T1]) -> zip[tuple[_T1]]: ...\n @overload\n def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> zip[tuple[_T1, _T2]]: ...\n @overload\n def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> zip[tuple[_T1, _T2, _T3]]: ...\n @overload\n def __new__(\n cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4]\n ) -> zip[tuple[_T1, _T2, _T3, _T4]]: ...\n @overload\n def __new__(\n cls,\n __iter1: Iterable[_T1],\n __iter2: Iterable[_T2],\n __iter3: Iterable[_T3],\n __iter4: Iterable[_T4],\n __iter5: Iterable[_T5],\n ) -> zip[tuple[_T1, _T2, _T3, _T4, _T5]]: ...\n @overload\n def __new__(\n cls,\n __iter1: Iterable[Any],\n __iter2: Iterable[Any],\n __iter3: Iterable[Any],\n __iter4: Iterable[Any],\n __iter5: Iterable[Any],\n __iter6: Iterable[Any],\n *iterables: Iterable[Any],\n ) -> zip[tuple[Any, ...]]: ...\n\n def __iter__(self) -> Self: ...\n def __next__(self) -> _T_co: ..."},{"col":4,"comment":"null","endLoc":1899,"header":"def __iter__(self) -> Self","id":1511,"name":"__iter__","nodeType":"Function","startLoc":1899,"text":"def __iter__(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":1900,"header":"def __next__(self) -> _T_co","id":1512,"name":"__next__","nodeType":"Function","startLoc":1900,"text":"def __next__(self) -> _T_co: ..."},{"className":"zip","col":0,"comment":"\n zip(*iterables) --> A zip object yielding tuples until an input is exhausted.\n \n >>> list(zip('abcdefg', range(3), range(4)))\n [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]\n \n The zip object yields n-length tuples, where n is the number of iterables\n passed as positional arguments to zip(). The i-th element in every tuple\n comes from the i-th iterable argument to zip(). This continues until the\n shortest argument is exhausted.\n ","endLoc":5951,"id":1513,"nodeType":"Class","startLoc":5917,"text":"class zip(object):\n \"\"\"\n zip(*iterables) --> A zip object yielding tuples until an input is exhausted.\n \n >>> list(zip('abcdefg', range(3), range(4)))\n [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]\n \n The zip object yields n-length tuples, where n is the number of iterables\n passed as positional arguments to zip(). The i-th element in every tuple\n comes from the i-th iterable argument to zip(). This continues until the\n shortest argument is exhausted.\n \"\"\"\n def __getattribute__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return getattr(self, name). \"\"\"\n pass\n\n def __init__(self, *iterables): # real signature unknown; restored from __doc__\n pass\n\n def __iter__(self, *args, **kwargs): # real signature unknown\n \"\"\" Implement iter(self). \"\"\"\n pass\n\n @staticmethod # known case of __new__\n def __new__(*args, **kwargs): # real signature unknown\n \"\"\" Create and return a new object. See help(type) for accurate signature. \"\"\"\n pass\n\n def __next__(self, *args, **kwargs): # real signature unknown\n \"\"\" Implement next(self). \"\"\"\n pass\n\n def __reduce__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return state information for pickling. \"\"\"\n pass"},{"col":4,"comment":"null","endLoc":651,"header":"def pytest_sessionstart(self)","id":1514,"name":"pytest_sessionstart","nodeType":"Function","startLoc":650,"text":"def pytest_sessionstart(self):\n self.suite_start_time = time.time()"},{"col":0,"comment":"null","endLoc":78,"header":"def time() -> float","id":1515,"name":"time","nodeType":"Function","startLoc":78,"text":"def time() -> float: ..."},{"col":4,"comment":"null","endLoc":592,"header":"def _recurse(self, dirpath)","id":1516,"name":"_recurse","nodeType":"Function","startLoc":581,"text":"def _recurse(self, dirpath):\n if dirpath.basename == \"__pycache__\":\n return False\n ihook = self.gethookproxy(dirpath.dirpath())\n if ihook.pytest_ignore_collect(path=dirpath, config=self.config):\n return\n for pat in self._norecursepatterns:\n if dirpath.check(fnmatch=pat):\n return False\n ihook = self.gethookproxy(dirpath)\n ihook.pytest_collect_directory(path=dirpath, parent=self)\n return True"},{"col":4,"comment":"null","endLoc":682,"header":"def pytest_sessionfinish(self)","id":1517,"name":"pytest_sessionfinish","nodeType":"Function","startLoc":653,"text":"def pytest_sessionfinish(self):\n dirname = os.path.dirname(os.path.abspath(self.logfile))\n if not os.path.isdir(dirname):\n os.makedirs(dirname)\n logfile = open(self.logfile, \"w\", encoding=\"utf-8\")\n suite_stop_time = time.time()\n suite_time_delta = suite_stop_time - self.suite_start_time\n\n numtests = (\n self.stats[\"passed\"]\n + self.stats[\"failure\"]\n + self.stats[\"skipped\"]\n + self.stats[\"error\"]\n - self.cnt_double_fail_tests\n )\n logfile.write('')\n\n logfile.write(\n Junit.testsuite(\n self._get_global_properties_node(),\n [x.to_xml() for x in self.node_reporters_ordered],\n name=self.suite_name,\n errors=self.stats[\"error\"],\n failures=self.stats[\"failure\"],\n skipped=self.stats[\"skipped\"],\n tests=numtests,\n time=\"%.3f\" % suite_time_delta,\n ).unicode(indent=0)\n )\n logfile.close()"},{"col":4,"comment":"null","endLoc":606,"header":"def gethookproxy(self, fspath)","id":1520,"name":"gethookproxy","nodeType":"Function","startLoc":594,"text":"def gethookproxy(self, fspath):\n # check if we have the common case of running\n # hooks with all conftest.py filesall conftest.py\n pm = self.config.pluginmanager\n my_conftestmodules = pm._getconftestmodules(fspath)\n remove_mods = pm._conftest_plugins.difference(my_conftestmodules)\n if remove_mods:\n # one or more conftests are not in use at this fspath\n proxy = FSHookProxy(fspath, pm, remove_mods)\n else:\n # all plugis are active for this fspath\n proxy = self.config.hook\n return proxy"},{"col":4,"comment":"null","endLoc":632,"header":"def _collectfile(self, path, handle_dupes=True)","id":1521,"name":"_collectfile","nodeType":"Function","startLoc":608,"text":"def _collectfile(self, path, handle_dupes=True):\n assert path.isfile(), \"%r is not a file (isdir=%r, exists=%r, islink=%r)\" % (\n path,\n path.isdir(),\n path.exists(),\n path.islink(),\n )\n ihook = self.gethookproxy(path)\n if not self.isinitpath(path):\n if ihook.pytest_ignore_collect(path=path, config=self.config):\n return ()\n\n if handle_dupes:\n keepduplicates = self.config.getoption(\"keepduplicates\")\n if not keepduplicates:\n duplicate_paths = self.config.pluginmanager._duplicatepaths\n if path in duplicate_paths:\n return ()\n else:\n duplicate_paths.add(path)\n\n if self.fspath == path: # __init__.py\n return [self]\n\n return ihook.pytest_collect_file(path=path, parent=self)"},{"col":4,"comment":"\n Comparing approx instances inside lists should not produce an error in the detailed diff.\n Integration test for issue #2111.\n ","endLoc":445,"header":"def test_unicode_plus_minus(self, testdir)","id":1522,"name":"test_unicode_plus_minus","nodeType":"Function","startLoc":429,"text":"def test_unicode_plus_minus(self, testdir):\n \"\"\"\n Comparing approx instances inside lists should not produce an error in the detailed diff.\n Integration test for issue #2111.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_foo():\n assert [3] == [pytest.approx(4)]\n \"\"\"\n )\n expected = \"4.0e-06\"\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"*At index 0 diff: 3 != 4 * {}\".format(expected), \"=* 1 failed in *=\"]\n )"},{"col":4,"comment":"null","endLoc":635,"header":"def isinitpath(self, path)","id":1523,"name":"isinitpath","nodeType":"Function","startLoc":634,"text":"def isinitpath(self, path):\n return path in self.session._initialpaths"},{"col":4,"comment":"null","endLoc":666,"header":"def collect(self)","id":1524,"name":"collect","nodeType":"Function","startLoc":637,"text":"def collect(self):\n this_path = self.fspath.dirpath()\n init_module = this_path.join(\"__init__.py\")\n if init_module.check(file=1) and path_matches_patterns(\n init_module, self.config.getini(\"python_files\")\n ):\n yield Module(init_module, self)\n pkg_prefixes = set()\n for path in this_path.visit(rec=self._recurse, bf=True, sort=True):\n # We will visit our own __init__.py file, in which case we skip it.\n is_file = path.isfile()\n if is_file:\n if path.basename == \"__init__.py\" and path.dirpath() == this_path:\n continue\n\n parts_ = parts(path.strpath)\n if any(\n pkg_prefix in parts_ and pkg_prefix.join(\"__init__.py\") != path\n for pkg_prefix in pkg_prefixes\n ):\n continue\n\n if is_file:\n for x in self._collectfile(path):\n yield x\n elif not path.isdir():\n # Broken symlink or invalid/missing file.\n continue\n elif path.join(\"__init__.py\").check(file=1):\n pkg_prefixes.add(path)"},{"col":4,"comment":"null","endLoc":460,"header":"@pytest.mark.parametrize(\n \"x\",\n [\n pytest.param(None),\n pytest.param(\"string\"),\n pytest.param([\"string\"], id=\"nested-str\"),\n pytest.param([[1]], id=\"nested-list\"),\n pytest.param({\"key\"","id":1525,"name":"test_expected_value_type_error","nodeType":"Function","startLoc":447,"text":"@pytest.mark.parametrize(\n \"x\",\n [\n pytest.param(None),\n pytest.param(\"string\"),\n pytest.param([\"string\"], id=\"nested-str\"),\n pytest.param([[1]], id=\"nested-list\"),\n pytest.param({\"key\": \"string\"}, id=\"dict-with-string\"),\n pytest.param({\"key\": {\"key\": 1}}, id=\"nested-dict\"),\n ],\n )\n def test_expected_value_type_error(self, x):\n with pytest.raises(TypeError):\n approx(x)"},{"col":4,"comment":"Return a Junit node containing custom properties, if any.\n ","endLoc":702,"header":"def _get_global_properties_node(self)","id":1526,"name":"_get_global_properties_node","nodeType":"Function","startLoc":692,"text":"def _get_global_properties_node(self):\n \"\"\"Return a Junit node containing custom properties, if any.\n \"\"\"\n if self.global_properties:\n return Junit.properties(\n [\n Junit.property(name=name, value=value)\n for name, value in self.global_properties\n ]\n )\n return \"\""},{"col":0,"comment":"Returns True if the given py.path.local matches one of the patterns in the list of globs given","endLoc":192,"header":"def path_matches_patterns(path, patterns)","id":1527,"name":"path_matches_patterns","nodeType":"Function","startLoc":190,"text":"def path_matches_patterns(path, patterns):\n \"\"\"Returns True if the given py.path.local matches one of the patterns in the list of globs given\"\"\"\n return any(path.fnmatch(pattern) for pattern in patterns)"},{"col":4,"comment":"null","endLoc":685,"header":"def pytest_terminal_summary(self, terminalreporter)","id":1529,"name":"pytest_terminal_summary","nodeType":"Function","startLoc":684,"text":"def pytest_terminal_summary(self, terminalreporter):\n terminalreporter.write_sep(\"-\", \"generated xml file: %s\" % (self.logfile))"},{"col":4,"comment":"null","endLoc":621,"header":"def _getentrysource(self, entry)","id":1530,"name":"_getentrysource","nodeType":"Function","startLoc":617,"text":"def _getentrysource(self, entry):\n source = entry.getsource(self.astcache)\n if source is not None:\n source = source.deindent()\n return source"},{"col":4,"comment":"null","endLoc":690,"header":"def add_global_property(self, name, value)","id":1531,"name":"add_global_property","nodeType":"Function","startLoc":687,"text":"def add_global_property(self, name, value):\n __tracebackhide__ = True\n _check_record_param_type(\"name\", name)\n self.global_properties.append((name, bin_xml_escape(value)))"},{"col":0,"comment":"Used by record_testsuite_property to check that the given parameter name is of the proper\n type","endLoc":358,"header":"def _check_record_param_type(param, v)","id":1532,"name":"_check_record_param_type","nodeType":"Function","startLoc":352,"text":"def _check_record_param_type(param, v):\n \"\"\"Used by record_testsuite_property to check that the given parameter name is of the proper\n type\"\"\"\n __tracebackhide__ = True\n if not isinstance(v, six.string_types):\n msg = \"{param} parameter needs to be a string, but {g} given\"\n raise TypeError(msg.format(param=param, g=type(v).__name__))"},{"col":4,"comment":"null","endLoc":628,"header":"def repr_args(self, entry)","id":1533,"name":"repr_args","nodeType":"Function","startLoc":623,"text":"def repr_args(self, entry):\n if self.funcargs:\n args = []\n for argname, argvalue in entry.frame.getargs(var=True):\n args.append((argname, saferepr(argvalue)))\n return ReprFuncArgs(args)"},{"col":4,"comment":" return formatted and marked up source lines. ","endLoc":652,"header":"def get_source(self, source, line_index=-1, excinfo=None, short=False)","id":1534,"name":"get_source","nodeType":"Function","startLoc":630,"text":"def get_source(self, source, line_index=-1, excinfo=None, short=False):\n \"\"\" return formatted and marked up source lines. \"\"\"\n import _pytest._code\n\n lines = []\n if source is None or line_index >= len(source.lines):\n source = _pytest._code.Source(\"???\")\n line_index = 0\n if line_index < 0:\n line_index += len(source)\n space_prefix = \" \"\n if short:\n lines.append(space_prefix + source.lines[line_index].strip())\n else:\n for line in source.lines[:line_index]:\n lines.append(space_prefix + line)\n lines.append(self.flow_marker + \" \" + source.lines[line_index])\n for line in source.lines[line_index + 1 :]:\n lines.append(space_prefix + line)\n if excinfo is not None:\n indent = 4 if short else self._getindent(source)\n lines.extend(self.get_exconly(excinfo, indent=indent, markall=True))\n return lines"},{"col":4,"comment":"\n pytest.approx should raise TypeError for operators other than == and != (#2003).\n ","endLoc":476,"header":"@pytest.mark.parametrize(\n \"op\",\n [\n pytest.param(operator.le, id=\"<=\"),\n pytest.param(operator.lt, id=\"<\"),\n pytest.param(operator.ge, id=\">=\"),\n pytest.param(operator.gt, id=\">\"),\n ],\n )\n def test_comparison_operator_type_error(self, op)","id":1535,"name":"test_comparison_operator_type_error","nodeType":"Function","startLoc":462,"text":"@pytest.mark.parametrize(\n \"op\",\n [\n pytest.param(operator.le, id=\"<=\"),\n pytest.param(operator.lt, id=\"<\"),\n pytest.param(operator.ge, id=\">=\"),\n pytest.param(operator.gt, id=\">\"),\n ],\n )\n def test_comparison_operator_type_error(self, op):\n \"\"\"\n pytest.approx should raise TypeError for operators other than == and != (#2003).\n \"\"\"\n with pytest.raises(TypeError):\n op(1, approx(1, rel=1e-6, abs=1e-12))"},{"attributeType":"list","col":8,"comment":"null","endLoc":498,"id":1536,"name":"global_properties","nodeType":"Attribute","startLoc":498,"text":"self.global_properties"},{"attributeType":"float","col":8,"comment":"null","endLoc":651,"id":1537,"name":"suite_start_time","nodeType":"Attribute","startLoc":651,"text":"self.suite_start_time"},{"col":0,"comment":"null","endLoc":365,"header":"def parts(s)","id":1538,"name":"parts","nodeType":"Function","startLoc":363,"text":"def parts(s):\n parts = s.split(sep)\n return {sep.join(parts[: i + 1]) or sep for i in range(len(parts))}"},{"col":4,"comment":"null","endLoc":487,"header":"def test_numpy_array_with_scalar(self)","id":1539,"name":"test_numpy_array_with_scalar","nodeType":"Function","startLoc":478,"text":"def test_numpy_array_with_scalar(self):\n np = pytest.importorskip(\"numpy\")\n\n actual = np.array([1 + 1e-7, 1 - 1e-8])\n expected = 1.0\n\n assert actual == approx(expected, rel=5e-7, abs=0)\n assert actual != approx(expected, rel=5e-8, abs=0)\n assert approx(expected, rel=5e-7, abs=0) == actual\n assert approx(expected, rel=5e-8, abs=0) != actual"},{"attributeType":"str | bytes | LiteralString","col":8,"comment":"null","endLoc":488,"id":1540,"name":"logfile","nodeType":"Attribute","startLoc":488,"text":"self.logfile"},{"col":4,"comment":"null","endLoc":664,"header":"def get_exconly(self, excinfo, indent=4, markall=False)","id":1541,"name":"get_exconly","nodeType":"Function","startLoc":654,"text":"def get_exconly(self, excinfo, indent=4, markall=False):\n lines = []\n indent = \" \" * indent\n # get the real exception information out\n exlines = excinfo.exconly(tryshort=True).split(\"\\n\")\n failindent = self.fail_marker + indent[1:]\n for line in exlines:\n lines.append(failindent + line)\n if not markall:\n failindent = indent\n return lines"},{"col":4,"comment":"null","endLoc":498,"header":"def test_numpy_scalar_with_array(self)","id":1542,"name":"test_numpy_scalar_with_array","nodeType":"Function","startLoc":489,"text":"def test_numpy_scalar_with_array(self):\n np = pytest.importorskip(\"numpy\")\n\n actual = 1.0\n expected = np.array([1 + 1e-7, 1 - 1e-8])\n\n assert actual == approx(expected, rel=5e-7, abs=0)\n assert actual != approx(expected, rel=5e-8, abs=0)\n assert approx(expected, rel=5e-7, abs=0) == actual\n assert approx(expected, rel=5e-8, abs=0) != actual"},{"col":4,"comment":"null","endLoc":690,"header":"def repr_locals(self, locals)","id":1543,"name":"repr_locals","nodeType":"Function","startLoc":666,"text":"def repr_locals(self, locals):\n if self.showlocals:\n lines = []\n keys = [loc for loc in locals if loc[0] != \"@\"]\n keys.sort()\n for name in keys:\n value = locals[name]\n if name == \"__builtins__\":\n lines.append(\"__builtins__ = \")\n else:\n # This formatting could all be handled by the\n # _repr() function, which is only reprlib.Repr in\n # disguise, so is very configurable.\n if self.truncate_locals:\n str_repr = saferepr(value)\n else:\n str_repr = safeformat(value)\n # if len(str_repr) < 70 or not isinstance(value,\n # (list, tuple, dict)):\n lines.append(\"%-10s = %s\" % (name, str_repr))\n # else:\n # self._line(\"%-10s =\\\\\" % (name,))\n # # XXX\n # pprint.pprint(value, stream=self.excinfowriter)\n return ReprLocals(lines)"},{"col":4,"comment":"null","endLoc":509,"header":"def test_generic_sized_iterable_object(self)","id":1544,"name":"test_generic_sized_iterable_object","nodeType":"Function","startLoc":500,"text":"def test_generic_sized_iterable_object(self):\n class MySizedIterable(object):\n def __iter__(self):\n return iter([1, 2, 3, 4])\n\n def __len__(self):\n return 4\n\n expected = MySizedIterable()\n assert [1, 2, 3, 4] == approx(expected)"},{"col":0,"comment":"return a pretty printed string for the given object.\n Failing __repr__ functions of user instances will be represented\n with a short exception info.\n ","endLoc":68,"header":"def safeformat(obj)","id":1549,"name":"safeformat","nodeType":"Function","startLoc":63,"text":"def safeformat(obj):\n \"\"\"return a pretty printed string for the given object.\n Failing __repr__ functions of user instances will be represented\n with a short exception info.\n \"\"\"\n return _call_and_format_exception(pprint.pformat, obj)"},{"col":0,"comment":"null","endLoc":22,"header":"def _call_and_format_exception(call, x, *args)","id":1550,"name":"_call_and_format_exception","nodeType":"Function","startLoc":7,"text":"def _call_and_format_exception(call, x, *args):\n try:\n # Try the vanilla repr and make sure that the result is a string\n return call(x, *args)\n except Exception as exc:\n exc_name = type(exc).__name__\n try:\n exc_info = str(exc)\n except Exception:\n exc_info = \"unknown\"\n return '<[%s(\"%s\") raised in repr()] %s object at 0x%x>' % (\n exc_name,\n exc_info,\n x.__class__.__name__,\n id(x),\n )"},{"attributeType":"float","col":0,"comment":"null","endLoc":13,"id":1551,"name":"inf","nodeType":"Attribute","startLoc":13,"text":"inf"},{"attributeType":"float","col":5,"comment":"null","endLoc":13,"id":1552,"name":"nan","nodeType":"Attribute","startLoc":13,"text":"nan"},{"col":0,"comment":"","endLoc":2,"header":"approx.py#","id":1553,"name":"","nodeType":"Function","startLoc":2,"text":"inf, nan = float(\"inf\"), float(\"nan\")"},{"id":1555,"name":"doc/en/proposals","nodeType":"Package"},{"id":1556,"name":"parametrize_with_fixtures.rst","nodeType":"TextFile","path":"doc/en/proposals","text":":orphan:\n\n===================================\nPROPOSAL: Parametrize with fixtures\n===================================\n\n.. warning::\n\n This document outlines a proposal around using fixtures as input\n of parametrized tests or fixtures.\n\nProblem\n-------\n\nAs a user I have functional tests that I would like to run against various\nscenarios.\n\nIn this particular example we want to generate a new project based on a\ncookiecutter template. We want to test default values but also data that\nemulates user input.\n\n- use default values\n\n- emulate user input\n\n - specify 'author'\n\n - specify 'project_slug'\n\n - specify 'author' and 'project_slug'\n\nThis is how a functional test could look like:\n\n.. code-block:: python\n\n import pytest\n\n\n @pytest.fixture\n def default_context():\n return {\"extra_context\": {}}\n\n\n @pytest.fixture(\n params=[\n {\"author\": \"alice\"},\n {\"project_slug\": \"helloworld\"},\n {\"author\": \"bob\", \"project_slug\": \"foobar\"},\n ]\n )\n def extra_context(request):\n return {\"extra_context\": request.param}\n\n\n @pytest.fixture(params=[\"default\", \"extra\"])\n def context(request):\n if request.param == \"default\":\n return request.getfuncargvalue(\"default_context\")\n else:\n return request.getfuncargvalue(\"extra_context\")\n\n\n def test_generate_project(cookies, context):\n \"\"\"Call the cookiecutter API to generate a new project from a\n template.\n \"\"\"\n result = cookies.bake(extra_context=context)\n\n assert result.exit_code == 0\n assert result.exception is None\n assert result.project.isdir()\n\n\nIssues\n------\n\n* By using ``request.getfuncargvalue()`` we rely on actual fixture function\n execution to know what fixtures are involved, due to its dynamic nature\n* More importantly, ``request.getfuncargvalue()`` cannot be combined with\n parametrized fixtures, such as ``extra_context``\n* This is very inconvenient if you wish to extend an existing test suite by\n certain parameters for fixtures that are already used by tests\n\npytest version 3.0 reports an error if you try to run above code::\n\n Failed: The requested fixture has no parameter defined for the current\n test.\n\n Requested fixture 'extra_context'\n\n\nProposed solution\n-----------------\n\nA new function that can be used in modules can be used to dynamically define\nfixtures from existing ones.\n\n.. code-block:: python\n\n pytest.define_combined_fixture(\n name=\"context\", fixtures=[\"default_context\", \"extra_context\"]\n )\n\nThe new fixture ``context`` inherits the scope from the used fixtures and yield\nthe following values.\n\n- ``{}``\n\n- ``{'author': 'alice'}``\n\n- ``{'project_slug': 'helloworld'}``\n\n- ``{'author': 'bob', 'project_slug': 'foobar'}``\n\nAlternative approach\n--------------------\n\nA new helper function named ``fixture_request`` would tell pytest to yield\nall parameters marked as a fixture.\n\n.. note::\n\n The `pytest-lazy-fixture `_ plugin implements a very\n similar solution to the proposal below, make sure to check it out.\n\n.. code-block:: python\n\n @pytest.fixture(\n params=[\n pytest.fixture_request(\"default_context\"),\n pytest.fixture_request(\"extra_context\"),\n ]\n )\n def context(request):\n \"\"\"Returns all values for ``default_context``, one-by-one before it\n does the same for ``extra_context``.\n\n request.param:\n - {}\n - {'author': 'alice'}\n - {'project_slug': 'helloworld'}\n - {'author': 'bob', 'project_slug': 'foobar'}\n \"\"\"\n return request.param\n\nThe same helper can be used in combination with ``pytest.mark.parametrize``.\n\n.. code-block:: python\n\n\n @pytest.mark.parametrize(\n \"context, expected_response_code\",\n [\n (pytest.fixture_request(\"default_context\"), 0),\n (pytest.fixture_request(\"extra_context\"), 0),\n ],\n )\n def test_generate_project(cookies, context, exit_code):\n \"\"\"Call the cookiecutter API to generate a new project from a\n template.\n \"\"\"\n result = cookies.bake(extra_context=context)\n\n assert result.exit_code == exit_code\n"},{"id":1557,"name":"testing/example_scripts/fixtures","nodeType":"Package"},{"fileName":"test_getfixturevalue_dynamic.py","filePath":"testing/example_scripts/fixtures","id":1558,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\n@pytest.fixture\ndef dynamic():\n pass\n\n\n@pytest.fixture\ndef a(request):\n request.getfixturevalue(\"dynamic\")\n\n\n@pytest.fixture\ndef b(a):\n pass\n\n\ndef test(b, request):\n assert request.fixturenames == [\"b\", \"request\", \"a\", \"dynamic\"]\n"},{"attributeType":"null","col":8,"comment":"null","endLoc":489,"id":1559,"name":"prefix","nodeType":"Attribute","startLoc":489,"text":"self.prefix"},{"col":0,"comment":"null","endLoc":7,"header":"@pytest.fixture\ndef dynamic()","id":1560,"name":"dynamic","nodeType":"Function","startLoc":5,"text":"@pytest.fixture\ndef dynamic():\n pass"},{"col":0,"comment":"null","endLoc":12,"header":"@pytest.fixture\ndef a(request)","id":1561,"name":"a","nodeType":"Function","startLoc":10,"text":"@pytest.fixture\ndef a(request):\n request.getfixturevalue(\"dynamic\")"},{"attributeType":"bool","col":8,"comment":"null","endLoc":492,"id":1562,"name":"log_passing_tests","nodeType":"Attribute","startLoc":492,"text":"self.log_passing_tests"},{"col":4,"comment":"null","endLoc":871,"header":"def __init__(self, metafunc)","id":1563,"name":"__init__","nodeType":"Function","startLoc":862,"text":"def __init__(self, metafunc):\n self.metafunc = metafunc\n self.funcargs = {}\n self._idlist = []\n self.params = {}\n self._globalid = NOTSET\n self._globalparam = NOTSET\n self._arg2scopenum = {} # used for sorting parametrized resources\n self.marks = []\n self.indices = {}"},{"attributeType":"str","col":8,"comment":"null","endLoc":490,"id":1564,"name":"suite_name","nodeType":"Attribute","startLoc":490,"text":"self.suite_name"},{"attributeType":"str","col":8,"comment":"null","endLoc":493,"id":1565,"name":"report_duration","nodeType":"Attribute","startLoc":493,"text":"self.report_duration"},{"attributeType":"list","col":8,"comment":"null","endLoc":501,"id":1566,"name":"open_reports","nodeType":"Attribute","startLoc":501,"text":"self.open_reports"},{"attributeType":"int","col":8,"comment":"null","endLoc":502,"id":1567,"name":"cnt_double_fail_tests","nodeType":"Attribute","startLoc":502,"text":"self.cnt_double_fail_tests"},{"attributeType":"list","col":8,"comment":"null","endLoc":497,"id":1568,"name":"node_reporters_ordered","nodeType":"Attribute","startLoc":497,"text":"self.node_reporters_ordered"},{"attributeType":"dict","col":8,"comment":"null","endLoc":495,"id":1569,"name":"stats","nodeType":"Attribute","startLoc":495,"text":"self.stats"},{"col":4,"comment":"null","endLoc":999,"header":"def __init__(self, lines)","id":1571,"name":"__init__","nodeType":"Function","startLoc":998,"text":"def __init__(self, lines):\n self.lines = lines"},{"col":4,"comment":"null","endLoc":724,"header":"def repr_traceback_entry(self, entry, excinfo=None)","id":1572,"name":"repr_traceback_entry","nodeType":"Function","startLoc":692,"text":"def repr_traceback_entry(self, entry, excinfo=None):\n import _pytest._code\n\n source = self._getentrysource(entry)\n if source is None:\n source = _pytest._code.Source(\"???\")\n line_index = 0\n else:\n # entry.getfirstlinesource() can be -1, should be 0 on jython\n line_index = entry.lineno - max(entry.getfirstlinesource(), 0)\n\n lines = []\n style = entry._repr_style\n if style is None:\n style = self.style\n if style in (\"short\", \"long\"):\n short = style == \"short\"\n reprargs = self.repr_args(entry) if not short else None\n s = self.get_source(source, line_index, excinfo, short=short)\n lines.extend(s)\n if short:\n message = \"in %s\" % (entry.name)\n else:\n message = excinfo and excinfo.typename or \"\"\n path = self._makepath(entry.path)\n filelocrepr = ReprFileLocation(path, entry.lineno + 1, message)\n localsrepr = None\n if not short:\n localsrepr = self.repr_locals(entry.locals)\n return ReprEntry(lines, reprargs, localsrepr, filelocrepr, style)\n if excinfo:\n lines.extend(self.get_exconly(excinfo, indent=4))\n return ReprEntry(lines, None, None, None, style)"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":496,"id":1573,"name":"node_reporters","nodeType":"Attribute","startLoc":496,"text":"self.node_reporters"},{"attributeType":"str","col":8,"comment":"null","endLoc":491,"id":1574,"name":"logging","nodeType":"Attribute","startLoc":491,"text":"self.logging"},{"attributeType":"str","col":12,"comment":"null","endLoc":506,"id":1575,"name":"family","nodeType":"Attribute","startLoc":506,"text":"self.family"},{"col":34,"endLoc":63,"id":1576,"nodeType":"Lambda","startLoc":63,"text":"lambda: metafunc.parametrize(\"x\", [5, 6])"},{"col":34,"endLoc":64,"id":1577,"nodeType":"Lambda","startLoc":64,"text":"lambda: metafunc.parametrize(\"x\", [5, 6])"},{"col":34,"endLoc":66,"id":1578,"nodeType":"Lambda","startLoc":66,"text":"lambda: metafunc.parametrize(\"y\", [5, 6])"},{"col":34,"endLoc":67,"id":1579,"nodeType":"Lambda","startLoc":67,"text":"lambda: metafunc.parametrize(\"y\", [5, 6])"},{"col":4,"comment":"null","endLoc":734,"header":"def _makepath(self, path)","id":1580,"name":"_makepath","nodeType":"Function","startLoc":726,"text":"def _makepath(self, path):\n if not self.abspath:\n try:\n np = py.path.local().bestrelpath(path)\n except OSError:\n return path\n if len(np) < len(str(path)):\n path = np\n return path"},{"col":4,"comment":"null","endLoc":78,"header":"def test_parametrize_bad_scope(self, testdir)","id":1581,"name":"test_parametrize_bad_scope","nodeType":"Function","startLoc":69,"text":"def test_parametrize_bad_scope(self, testdir):\n def func(x):\n pass\n\n metafunc = self.Metafunc(func)\n with pytest.raises(\n pytest.fail.Exception,\n match=r\"parametrize\\(\\) call in func got an unexpected scope value 'doggy'\",\n ):\n metafunc.parametrize(\"x\", [1], scope=\"doggy\")"},{"col":0,"comment":"null","endLoc":77,"header":"def merge_family(left, right)","id":1582,"name":"merge_family","nodeType":"Function","startLoc":70,"text":"def merge_family(left, right):\n result = {}\n for kl, vl in left.items():\n for kr, vr in right.items():\n if not isinstance(vl, list):\n raise TypeError(type(vl))\n result[kl] = vl + vr\n left.update(result)"},{"col":4,"comment":"unittest for _find_parametrized_scope (#3941)","endLoc":124,"header":"def test_find_parametrized_scope(self)","id":1583,"name":"test_find_parametrized_scope","nodeType":"Function","startLoc":80,"text":"def test_find_parametrized_scope(self):\n \"\"\"unittest for _find_parametrized_scope (#3941)\"\"\"\n from _pytest.python import _find_parametrized_scope\n\n @attr.s\n class DummyFixtureDef(object):\n scope = attr.ib()\n\n fixtures_defs = dict(\n session_fix=[DummyFixtureDef(\"session\")],\n package_fix=[DummyFixtureDef(\"package\")],\n module_fix=[DummyFixtureDef(\"module\")],\n class_fix=[DummyFixtureDef(\"class\")],\n func_fix=[DummyFixtureDef(\"function\")],\n )\n\n # use arguments to determine narrow scope; the cause of the bug is that it would look on all\n # fixture defs given to the method\n def find_scope(argnames, indirect):\n return _find_parametrized_scope(argnames, fixtures_defs, indirect=indirect)\n\n assert find_scope([\"func_fix\"], indirect=True) == \"function\"\n assert find_scope([\"class_fix\"], indirect=True) == \"class\"\n assert find_scope([\"module_fix\"], indirect=True) == \"module\"\n assert find_scope([\"package_fix\"], indirect=True) == \"package\"\n assert find_scope([\"session_fix\"], indirect=True) == \"session\"\n\n assert find_scope([\"class_fix\", \"func_fix\"], indirect=True) == \"function\"\n assert find_scope([\"func_fix\", \"session_fix\"], indirect=True) == \"function\"\n assert find_scope([\"session_fix\", \"class_fix\"], indirect=True) == \"class\"\n assert find_scope([\"package_fix\", \"session_fix\"], indirect=True) == \"package\"\n assert find_scope([\"module_fix\", \"session_fix\"], indirect=True) == \"module\"\n\n # when indirect is False or is not for all scopes, always use function\n assert find_scope([\"session_fix\", \"module_fix\"], indirect=False) == \"function\"\n assert (\n find_scope([\"session_fix\", \"module_fix\"], indirect=[\"module_fix\"])\n == \"function\"\n )\n assert (\n find_scope(\n [\"session_fix\", \"module_fix\"], indirect=[\"session_fix\", \"module_fix\"]\n )\n == \"module\"\n )"},{"col":4,"comment":"null","endLoc":984,"header":"def __init__(self, path, lineno, message)","id":1584,"name":"__init__","nodeType":"Function","startLoc":981,"text":"def __init__(self, path, lineno, message):\n self.path = str(path)\n self.lineno = lineno\n self.message = message"},{"col":4,"comment":"null","endLoc":953,"header":"def __init__(self, lines, reprfuncargs, reprlocals, filelocrepr, style)","id":1585,"name":"__init__","nodeType":"Function","startLoc":948,"text":"def __init__(self, lines, reprfuncargs, reprlocals, filelocrepr, style):\n self.lines = lines\n self.reprfuncargs = reprfuncargs\n self.reprlocals = reprlocals\n self.reprfileloc = filelocrepr\n self.style = style"},{"col":4,"comment":"null","endLoc":752,"header":"def repr_traceback(self, excinfo)","id":1586,"name":"repr_traceback","nodeType":"Function","startLoc":736,"text":"def repr_traceback(self, excinfo):\n traceback = excinfo.traceback\n if self.tbfilter:\n traceback = traceback.filter()\n\n if is_recursion_error(excinfo):\n traceback, extraline = self._truncate_recursive_traceback(traceback)\n else:\n extraline = None\n\n last = traceback[-1]\n entries = []\n for index, entry in enumerate(traceback):\n einfo = (last == entry) and excinfo or None\n reprentry = self.repr_traceback_entry(entry, einfo)\n entries.append(reprentry)\n return ReprTraceback(entries, extraline, style=self.style)"},{"col":0,"comment":"Emits a PytestWarning about the given fixture being incompatible with newer xunit revisions","endLoc":300,"header":"def _warn_incompatibility_with_xunit2(request, fixture_name)","id":1587,"name":"_warn_incompatibility_with_xunit2","nodeType":"Function","startLoc":288,"text":"def _warn_incompatibility_with_xunit2(request, fixture_name):\n \"\"\"Emits a PytestWarning about the given fixture being incompatible with newer xunit revisions\"\"\"\n from _pytest.warning_types import PytestWarning\n\n xml = getattr(request.config, \"_xml\", None)\n if xml is not None and xml.family not in (\"xunit1\", \"legacy\"):\n request.node.warn(\n PytestWarning(\n \"{fixture_name} is incompatible with junit_family '{family}' (use 'legacy' or 'xunit1')\".format(\n fixture_name=fixture_name, family=xml.family\n )\n )\n )"},{"col":4,"comment":"null","endLoc":1049,"header":"def is_recursion_error(excinfo)","id":1588,"name":"is_recursion_error","nodeType":"Function","startLoc":1048,"text":"def is_recursion_error(excinfo):\n return excinfo.errisinstance(RecursionError) # noqa"},{"col":4,"comment":"null","endLoc":1060,"header":"def is_recursion_error(excinfo)","id":1589,"name":"is_recursion_error","nodeType":"Function","startLoc":1054,"text":"def is_recursion_error(excinfo):\n if not excinfo.errisinstance(RuntimeError):\n return False\n try:\n return \"maximum recursion depth exceeded\" in str(excinfo.value)\n except UnicodeError:\n return False"},{"attributeType":"null","col":8,"comment":"null","endLoc":561,"id":1590,"name":"trace","nodeType":"Attribute","startLoc":561,"text":"self.trace"},{"col":4,"comment":"\n Truncate the given recursive traceback trying to find the starting point\n of the recursion.\n\n The detection is done by going through each traceback entry and finding the\n point in which the locals of the frame are equal to the locals of a previous frame (see ``recursionindex()``.\n\n Handle the situation where the recursion process might raise an exception (for example\n comparing numpy arrays using equality raises a TypeError), in which case we do our best to\n warn the user of the error and show a limited traceback.\n ","endLoc":789,"header":"def _truncate_recursive_traceback(self, traceback)","id":1591,"name":"_truncate_recursive_traceback","nodeType":"Function","startLoc":754,"text":"def _truncate_recursive_traceback(self, traceback):\n \"\"\"\n Truncate the given recursive traceback trying to find the starting point\n of the recursion.\n\n The detection is done by going through each traceback entry and finding the\n point in which the locals of the frame are equal to the locals of a previous frame (see ``recursionindex()``.\n\n Handle the situation where the recursion process might raise an exception (for example\n comparing numpy arrays using equality raises a TypeError), in which case we do our best to\n warn the user of the error and show a limited traceback.\n \"\"\"\n try:\n recursionindex = traceback.recursionindex()\n except Exception as e:\n max_frames = 10\n extraline = (\n \"!!! Recursion error detected, but an error occurred locating the origin of recursion.\\n\"\n \" The following exception happened when comparing locals in the stack frame:\\n\"\n \" {exc_type}: {exc_msg}\\n\"\n \" Displaying first and last {max_frames} stack frames out of {total}.\"\n ).format(\n exc_type=type(e).__name__,\n exc_msg=safe_str(e),\n max_frames=max_frames,\n total=len(traceback),\n )\n traceback = traceback[:max_frames] + traceback[-max_frames:]\n else:\n if recursionindex is not None:\n extraline = \"!!! Recursion detected (same locals & position)\"\n traceback = traceback[: recursionindex + 1]\n else:\n extraline = None\n\n return traceback, extraline"},{"attributeType":"null","col":8,"comment":"null","endLoc":563,"id":1592,"name":"fspath","nodeType":"Attribute","startLoc":563,"text":"self.fspath"},{"attributeType":"null","col":8,"comment":"null","endLoc":560,"id":1593,"name":"name","nodeType":"Attribute","startLoc":560,"text":"self.name"},{"attributeType":"null","col":8,"comment":"null","endLoc":562,"id":1594,"name":"_norecursepatterns","nodeType":"Attribute","startLoc":562,"text":"self._norecursepatterns"},{"col":0,"comment":"Add an extra properties the calling test.\n User properties become part of the test report and are available to the\n configured reporters, like JUnit XML.\n The fixture is callable with ``(name, value)``, with value being automatically\n xml-encoded.\n\n Example::\n\n def test_function(record_property):\n record_property(\"example_key\", 1)\n ","endLoc":321,"header":"@pytest.fixture\ndef record_property(request)","id":1595,"name":"record_property","nodeType":"Function","startLoc":303,"text":"@pytest.fixture\ndef record_property(request):\n \"\"\"Add an extra properties the calling test.\n User properties become part of the test report and are available to the\n configured reporters, like JUnit XML.\n The fixture is callable with ``(name, value)``, with value being automatically\n xml-encoded.\n\n Example::\n\n def test_function(record_property):\n record_property(\"example_key\", 1)\n \"\"\"\n _warn_incompatibility_with_xunit2(request, \"record_property\")\n\n def append_property(name, value):\n request.node.user_properties.append((name, value))\n\n return append_property"},{"col":4,"comment":"null","endLoc":135,"header":"def test_parametrize_and_id(self)","id":1597,"name":"test_parametrize_and_id","nodeType":"Function","startLoc":126,"text":"def test_parametrize_and_id(self):\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n\n metafunc.parametrize(\"x\", [1, 2], ids=[\"basic\", \"advanced\"])\n metafunc.parametrize(\"y\", [\"abc\", \"def\"])\n ids = [x.id for x in metafunc._calls]\n assert ids == [\"basic-abc\", \"basic-def\", \"advanced-abc\", \"advanced-def\"]"},{"col":4,"comment":"Allow unicode strings for \"ids\" parameter in Python 2 (##1905)","endLoc":146,"header":"def test_parametrize_and_id_unicode(self)","id":1598,"name":"test_parametrize_and_id_unicode","nodeType":"Function","startLoc":137,"text":"def test_parametrize_and_id_unicode(self):\n \"\"\"Allow unicode strings for \"ids\" parameter in Python 2 (##1905)\"\"\"\n\n def func(x):\n pass\n\n metafunc = self.Metafunc(func)\n metafunc.parametrize(\"x\", [1, 2], ids=[u\"basic\", u\"advanced\"])\n ids = [x.id for x in metafunc._calls]\n assert ids == [u\"basic\", u\"advanced\"]"},{"col":4,"comment":"null","endLoc":160,"header":"def test_parametrize_with_wrong_number_of_ids(self, testdir)","id":1599,"name":"test_parametrize_with_wrong_number_of_ids","nodeType":"Function","startLoc":148,"text":"def test_parametrize_with_wrong_number_of_ids(self, testdir):\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n\n with pytest.raises(pytest.fail.Exception):\n metafunc.parametrize(\"x\", [1, 2], ids=[\"basic\"])\n\n with pytest.raises(pytest.fail.Exception):\n metafunc.parametrize(\n (\"x\", \"y\"), [(\"abc\", \"def\"), (\"ghi\", \"jkl\")], ids=[\"one\"]\n )"},{"col":4,"comment":"#510","endLoc":181,"header":"def test_parametrize_empty_list(self)","id":1600,"name":"test_parametrize_empty_list","nodeType":"Function","startLoc":162,"text":"def test_parametrize_empty_list(self):\n \"\"\"#510\"\"\"\n\n def func(y):\n pass\n\n class MockConfig(object):\n def getini(self, name):\n return \"\"\n\n @property\n def hook(self):\n return self\n\n def pytest_make_parametrize_id(self, **kw):\n pass\n\n metafunc = self.Metafunc(func, MockConfig())\n metafunc.parametrize(\"y\", [])\n assert \"skip\" == metafunc._calls[0].marks[0].name"},{"col":4,"comment":"null","endLoc":909,"header":"def __init__(self, reprentries, extraline, style)","id":1601,"name":"__init__","nodeType":"Function","startLoc":906,"text":"def __init__(self, reprentries, extraline, style):\n self.reprentries = reprentries\n self.extraline = extraline\n self.style = style"},{"col":4,"comment":"null","endLoc":839,"header":"def repr_excinfo(self, excinfo)","id":1602,"name":"repr_excinfo","nodeType":"Function","startLoc":791,"text":"def repr_excinfo(self, excinfo):\n if _PY2:\n reprtraceback = self.repr_traceback(excinfo)\n reprcrash = excinfo._getreprcrash()\n\n return ReprExceptionInfo(reprtraceback, reprcrash)\n else:\n repr_chain = []\n e = excinfo.value\n descr = None\n seen = set()\n while e is not None and id(e) not in seen:\n seen.add(id(e))\n if excinfo:\n reprtraceback = self.repr_traceback(excinfo)\n reprcrash = excinfo._getreprcrash()\n else:\n # fallback to native repr if the exception doesn't have a traceback:\n # ExceptionInfo objects require a full traceback to work\n reprtraceback = ReprTracebackNative(\n traceback.format_exception(type(e), e, None)\n )\n reprcrash = None\n\n repr_chain += [(reprtraceback, reprcrash, descr)]\n if e.__cause__ is not None and self.chain:\n e = e.__cause__\n excinfo = (\n ExceptionInfo((type(e), e, e.__traceback__))\n if e.__traceback__\n else None\n )\n descr = \"The above exception was the direct cause of the following exception:\"\n elif (\n e.__context__ is not None\n and not e.__suppress_context__\n and self.chain\n ):\n e = e.__context__\n excinfo = (\n ExceptionInfo((type(e), e, e.__traceback__))\n if e.__traceback__\n else None\n )\n descr = \"During handling of the above exception, another exception occurred:\"\n else:\n e = None\n repr_chain.reverse()\n return ExceptionChainRepr(repr_chain)"},{"col":4,"comment":"null","endLoc":197,"header":"def test_parametrize_with_userobjects(self)","id":1603,"name":"test_parametrize_with_userobjects","nodeType":"Function","startLoc":183,"text":"def test_parametrize_with_userobjects(self):\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n\n class A(object):\n pass\n\n metafunc.parametrize(\"x\", [A(), A()])\n metafunc.parametrize(\"y\", list(\"ab\"))\n assert metafunc._calls[0].id == \"x0-a\"\n assert metafunc._calls[1].id == \"x0-b\"\n assert metafunc._calls[2].id == \"x1-a\"\n assert metafunc._calls[3].id == \"x1-b\""},{"col":4,"comment":"null","endLoc":896,"header":"def __init__(self, reprtraceback, reprcrash)","id":1604,"name":"__init__","nodeType":"Function","startLoc":893,"text":"def __init__(self, reprtraceback, reprcrash):\n super(ReprExceptionInfo, self).__init__()\n self.reprtraceback = reprtraceback\n self.reprcrash = reprcrash"},{"className":"object","col":0,"comment":"\n The base class of the class hierarchy.\n \n When called, it accepts no arguments and returns a new featureless\n instance that has no instance attributes and cannot be given any.\n ","endLoc":840,"id":1605,"nodeType":"Class","startLoc":732,"text":"class object:\n \"\"\"\n The base class of the class hierarchy.\n \n When called, it accepts no arguments and returns a new featureless\n instance that has no instance attributes and cannot be given any.\n \"\"\"\n def __delattr__(self, *args, **kwargs): # real signature unknown\n \"\"\" Implement delattr(self, name). \"\"\"\n pass\n\n def __dir__(self, *args, **kwargs): # real signature unknown\n \"\"\" Default dir() implementation. \"\"\"\n pass\n\n def __eq__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self==value. \"\"\"\n pass\n\n def __format__(self, *args, **kwargs): # real signature unknown\n \"\"\" Default object formatter. \"\"\"\n pass\n\n def __getattribute__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return getattr(self, name). \"\"\"\n pass\n\n def __ge__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self>=value. \"\"\"\n pass\n\n def __gt__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self>value. \"\"\"\n pass\n\n def __hash__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return hash(self). \"\"\"\n pass\n\n def __init_subclass__(self, *args, **kwargs): # real signature unknown\n \"\"\"\n This method is called when a class is subclassed.\n \n The default implementation does nothing. It may be\n overridden to extend subclasses.\n \"\"\"\n pass\n\n def __init__(self): # known special case of object.__init__\n \"\"\" Initialize self. See help(type(self)) for accurate signature. \"\"\"\n pass\n\n def __le__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self<=value. \"\"\"\n pass\n\n def __lt__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self\"\n __dict__ = {}\n __doc__ = ''\n __module__ = ''"},{"col":4,"comment":" Implement delattr(self, name). ","endLoc":741,"header":"def __delattr__(self, *args, **kwargs)","id":1606,"name":"__delattr__","nodeType":"Function","startLoc":739,"text":"def __delattr__(self, *args, **kwargs): # real signature unknown\n \"\"\" Implement delattr(self, name). \"\"\"\n pass"},{"col":4,"comment":" Default dir() implementation. ","endLoc":745,"header":"def __dir__(self, *args, **kwargs)","id":1607,"name":"__dir__","nodeType":"Function","startLoc":743,"text":"def __dir__(self, *args, **kwargs): # real signature unknown\n \"\"\" Default dir() implementation. \"\"\"\n pass"},{"col":4,"comment":" Return self==value. ","endLoc":749,"header":"def __eq__(self, *args, **kwargs)","id":1608,"name":"__eq__","nodeType":"Function","startLoc":747,"text":"def __eq__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self==value. \"\"\"\n pass"},{"col":4,"comment":" Default object formatter. ","endLoc":753,"header":"def __format__(self, *args, **kwargs)","id":1609,"name":"__format__","nodeType":"Function","startLoc":751,"text":"def __format__(self, *args, **kwargs): # real signature unknown\n \"\"\" Default object formatter. \"\"\"\n pass"},{"col":4,"comment":" Return getattr(self, name). ","endLoc":757,"header":"def __getattribute__(self, *args, **kwargs)","id":1610,"name":"__getattribute__","nodeType":"Function","startLoc":755,"text":"def __getattribute__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return getattr(self, name). \"\"\"\n pass"},{"col":4,"comment":" Return self>=value. ","endLoc":761,"header":"def __ge__(self, *args, **kwargs)","id":1611,"name":"__ge__","nodeType":"Function","startLoc":759,"text":"def __ge__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self>=value. \"\"\"\n pass"},{"col":4,"comment":" Return self>value. ","endLoc":765,"header":"def __gt__(self, *args, **kwargs)","id":1612,"name":"__gt__","nodeType":"Function","startLoc":763,"text":"def __gt__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self>value. \"\"\"\n pass"},{"col":4,"comment":" Return hash(self). ","endLoc":769,"header":"def __hash__(self, *args, **kwargs)","id":1613,"name":"__hash__","nodeType":"Function","startLoc":767,"text":"def __hash__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return hash(self). \"\"\"\n pass"},{"col":4,"comment":"\n This method is called when a class is subclassed.\n \n The default implementation does nothing. It may be\n overridden to extend subclasses.\n ","endLoc":778,"header":"def __init_subclass__(self, *args, **kwargs)","id":1614,"name":"__init_subclass__","nodeType":"Function","startLoc":771,"text":"def __init_subclass__(self, *args, **kwargs): # real signature unknown\n \"\"\"\n This method is called when a class is subclassed.\n \n The default implementation does nothing. It may be\n overridden to extend subclasses.\n \"\"\"\n pass"},{"col":4,"comment":" Initialize self. See help(type(self)) for accurate signature. ","endLoc":782,"header":"def __init__(self)","id":1615,"name":"__init__","nodeType":"Function","startLoc":780,"text":"def __init__(self): # known special case of object.__init__\n \"\"\" Initialize self. See help(type(self)) for accurate signature. \"\"\"\n pass"},{"col":4,"comment":" Return self<=value. ","endLoc":786,"header":"def __le__(self, *args, **kwargs)","id":1616,"name":"__le__","nodeType":"Function","startLoc":784,"text":"def __le__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self<=value. \"\"\"\n pass"},{"col":4,"comment":" Return self Iterator[_T_co]: ..."},{"col":4,"comment":"null","endLoc":423,"header":"@abstractmethod\n def __iter__(self) -> Iterator[_T_co]","id":1640,"name":"__iter__","nodeType":"Function","startLoc":422,"text":"@abstractmethod\n def __iter__(self) -> Iterator[_T_co]: ..."},{"className":"Mapping","col":0,"comment":"null","endLoc":691,"id":1641,"nodeType":"Class","startLoc":677,"text":"class Mapping(Collection[_KT], Generic[_KT, _VT_co]):\n # TODO: We wish the key type could also be covariant, but that doesn't work,\n # see discussion in https://github.com/python/typing/pull/273.\n @abstractmethod\n def __getitem__(self, key: _KT, /) -> _VT_co: ...\n # Mixin methods\n @overload\n def get(self, key: _KT, /) -> _VT_co | None: ...\n @overload\n def get(self, key: _KT, /, default: _VT_co | _T) -> _VT_co | _T: ...\n def items(self) -> ItemsView[_KT, _VT_co]: ...\n def keys(self) -> KeysView[_KT]: ...\n def values(self) -> ValuesView[_VT_co]: ...\n def __contains__(self, key: object, /) -> bool: ...\n def __eq__(self, other: object, /) -> bool: ..."},{"col":4,"comment":"null","endLoc":681,"header":"@abstractmethod\n def __getitem__(self, key: _KT, /) -> _VT_co","id":1642,"name":"__getitem__","nodeType":"Function","startLoc":680,"text":"@abstractmethod\n def __getitem__(self, key: _KT, /) -> _VT_co: ..."},{"col":4,"comment":"null","endLoc":687,"header":"def items(self) -> ItemsView[_KT, _VT_co]","id":1643,"name":"items","nodeType":"Function","startLoc":687,"text":"def items(self) -> ItemsView[_KT, _VT_co]: ..."},{"col":4,"comment":"null","endLoc":688,"header":"def keys(self) -> KeysView[_KT]","id":1644,"name":"keys","nodeType":"Function","startLoc":688,"text":"def keys(self) -> KeysView[_KT]: ..."},{"col":4,"comment":"null","endLoc":689,"header":"def values(self) -> ValuesView[_VT_co]","id":1645,"name":"values","nodeType":"Function","startLoc":689,"text":"def values(self) -> ValuesView[_VT_co]: ..."},{"col":4,"comment":"null","endLoc":690,"header":"def __contains__(self, key: object, /) -> bool","id":1646,"name":"__contains__","nodeType":"Function","startLoc":690,"text":"def __contains__(self, key: object, /) -> bool: ..."},{"col":4,"comment":"null","endLoc":691,"header":"def __eq__(self, other: object, /) -> bool","id":1647,"name":"__eq__","nodeType":"Function","startLoc":691,"text":"def __eq__(self, other: object, /) -> bool: ..."},{"className":"Sized","col":0,"comment":"null","endLoc":410,"id":1648,"nodeType":"Class","startLoc":407,"text":"@runtime_checkable\nclass Sized(Protocol, metaclass=ABCMeta):\n @abstractmethod\n def __len__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":410,"header":"@abstractmethod\n def __len__(self) -> int","id":1649,"name":"__len__","nodeType":"Function","startLoc":409,"text":"@abstractmethod\n def __len__(self) -> int: ..."},{"attributeType":"(str)","col":4,"comment":"null","endLoc":244,"id":1650,"name":"STRING_TYPES","nodeType":"Attribute","startLoc":244,"text":"STRING_TYPES"},{"attributeType":"null","col":4,"comment":"null","endLoc":199,"id":1651,"name":"STRING_TYPES","nodeType":"Attribute","startLoc":199,"text":"STRING_TYPES"},{"col":4,"comment":"null","endLoc":208,"header":"@hypothesis.given(strategies.text() | strategies.binary())\n @hypothesis.settings(\n deadline=400.0\n ) # very close to std deadline and CI boxes are not reliable in CPU power\n def test_idval_hypothesis(self, value)","id":1653,"name":"test_idval_hypothesis","nodeType":"Function","startLoc":199,"text":"@hypothesis.given(strategies.text() | strategies.binary())\n @hypothesis.settings(\n deadline=400.0\n ) # very close to std deadline and CI boxes are not reliable in CPU power\n def test_idval_hypothesis(self, value):\n from _pytest.python import _idval\n\n escaped = _idval(value, \"a\", 6, None, item=None, config=None)\n assert isinstance(escaped, six.text_type)\n escaped.encode(\"ascii\")"},{"className":"ApproxBase","col":0,"comment":"\n Provide shared utilities for making approximate comparisons between numbers\n or sequences of numbers.\n ","endLoc":106,"id":1654,"nodeType":"Class","startLoc":53,"text":"class ApproxBase(object):\n \"\"\"\n Provide shared utilities for making approximate comparisons between numbers\n or sequences of numbers.\n \"\"\"\n\n # Tell numpy to use our `__eq__` operator instead of its.\n __array_ufunc__ = None\n __array_priority__ = 100\n\n def __init__(self, expected, rel=None, abs=None, nan_ok=False):\n __tracebackhide__ = True\n self.expected = expected\n self.abs = abs\n self.rel = rel\n self.nan_ok = nan_ok\n self._check_type()\n\n def __repr__(self):\n raise NotImplementedError\n\n def __eq__(self, actual):\n return all(\n a == self._approx_scalar(x) for a, x in self._yield_comparisons(actual)\n )\n\n __hash__ = None\n\n def __ne__(self, actual):\n return not (actual == self)\n\n if sys.version_info[0] == 2:\n __cmp__ = _cmp_raises_type_error\n\n def _approx_scalar(self, x):\n return ApproxScalar(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)\n\n def _yield_comparisons(self, actual):\n \"\"\"\n Yield all the pairs of numbers to be compared. This is used to\n implement the `__eq__` method.\n \"\"\"\n raise NotImplementedError\n\n def _check_type(self):\n \"\"\"\n Raise a TypeError if the expected value is not a valid type.\n \"\"\"\n # This is only a concern if the expected value is a sequence. In every\n # other case, the approx() function ensures that the expected value has\n # a numeric type. For this reason, the default is to do nothing. The\n # classes that deal with sequences should reimplement this method to\n # raise if there are any non-numeric elements in the sequence.\n pass"},{"col":4,"comment":"null","endLoc":72,"header":"def __repr__(self)","id":1655,"name":"__repr__","nodeType":"Function","startLoc":71,"text":"def __repr__(self):\n raise NotImplementedError"},{"col":4,"comment":"null","endLoc":77,"header":"def __eq__(self, actual)","id":1656,"name":"__eq__","nodeType":"Function","startLoc":74,"text":"def __eq__(self, actual):\n return all(\n a == self._approx_scalar(x) for a, x in self._yield_comparisons(actual)\n )"},{"col":4,"comment":"null","endLoc":88,"header":"def _approx_scalar(self, x)","id":1657,"name":"_approx_scalar","nodeType":"Function","startLoc":87,"text":"def _approx_scalar(self, x):\n return ApproxScalar(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)"},{"col":4,"comment":"\n Yield all the pairs of numbers to be compared. This is used to\n implement the `__eq__` method.\n ","endLoc":95,"header":"def _yield_comparisons(self, actual)","id":1658,"name":"_yield_comparisons","nodeType":"Function","startLoc":90,"text":"def _yield_comparisons(self, actual):\n \"\"\"\n Yield all the pairs of numbers to be compared. This is used to\n implement the `__eq__` method.\n \"\"\"\n raise NotImplementedError"},{"col":4,"comment":"null","endLoc":82,"header":"def __ne__(self, actual)","id":1660,"name":"__ne__","nodeType":"Function","startLoc":81,"text":"def __ne__(self, actual):\n return not (actual == self)"},{"attributeType":"None","col":4,"comment":"null","endLoc":60,"id":1661,"name":"__array_ufunc__","nodeType":"Attribute","startLoc":60,"text":"__array_ufunc__"},{"attributeType":"int","col":4,"comment":"null","endLoc":61,"id":1662,"name":"__array_priority__","nodeType":"Attribute","startLoc":61,"text":"__array_priority__"},{"attributeType":"None","col":4,"comment":"null","endLoc":79,"id":1663,"name":"__hash__","nodeType":"Attribute","startLoc":79,"text":"__hash__"},{"attributeType":"function","col":8,"comment":"null","endLoc":85,"id":1664,"name":"__cmp__","nodeType":"Attribute","startLoc":85,"text":"__cmp__"},{"col":4,"comment":"This tests that Unicode strings outside the ASCII character set get\n escaped, using byte escapes if they're in that range or unicode\n escapes if they're not.\n\n ","endLoc":230,"header":"def test_unicode_idval(self)","id":1665,"name":"test_unicode_idval","nodeType":"Function","startLoc":210,"text":"def test_unicode_idval(self):\n \"\"\"This tests that Unicode strings outside the ASCII character set get\n escaped, using byte escapes if they're in that range or unicode\n escapes if they're not.\n\n \"\"\"\n from _pytest.python import _idval\n\n values = [\n (u\"\", \"\"),\n (u\"ascii\", \"ascii\"),\n (u\"ação\", \"a\\\\xe7\\\\xe3o\"),\n (u\"josé@blah.com\", \"jos\\\\xe9@blah.com\"),\n (\n u\"δοκ.ιμή@παράδειγμα.δοκιμή\",\n \"\\\\u03b4\\\\u03bf\\\\u03ba.\\\\u03b9\\\\u03bc\\\\u03ae@\\\\u03c0\\\\u03b1\\\\u03c1\\\\u03ac\\\\u03b4\\\\u03b5\\\\u03b9\\\\u03b3\"\n \"\\\\u03bc\\\\u03b1.\\\\u03b4\\\\u03bf\\\\u03ba\\\\u03b9\\\\u03bc\\\\u03ae\",\n ),\n ]\n for val, expected in values:\n assert _idval(val, \"a\", 6, None, item=None, config=None) == expected"},{"col":4,"comment":"unittest for expected behavior to obtain ids with\n disable_test_id_escaping_and_forfeit_all_rights_to_community_support\n option. (#5294)\n ","endLoc":260,"header":"def test_unicode_idval_with_config(self)","id":1666,"name":"test_unicode_idval_with_config","nodeType":"Function","startLoc":232,"text":"def test_unicode_idval_with_config(self):\n \"\"\"unittest for expected behavior to obtain ids with\n disable_test_id_escaping_and_forfeit_all_rights_to_community_support\n option. (#5294)\n \"\"\"\n from _pytest.python import _idval\n\n class MockConfig(object):\n def __init__(self, config):\n self.config = config\n\n @property\n def hook(self):\n return self\n\n def pytest_make_parametrize_id(self, **kw):\n pass\n\n def getini(self, name):\n return self.config[name]\n\n option = \"disable_test_id_escaping_and_forfeit_all_rights_to_community_support\"\n\n values = [\n (u\"ação\", MockConfig({option: True}), u\"ação\"),\n (u\"ação\", MockConfig({option: False}), \"a\\\\xe7\\\\xe3o\"),\n ]\n for val, config, expected in values:\n assert _idval(val, \"a\", 6, None, item=None, config=config) == expected"},{"col":4,"comment":"null","endLoc":934,"header":"def __init__(self, tblines)","id":1667,"name":"__init__","nodeType":"Function","startLoc":931,"text":"def __init__(self, tblines):\n self.style = \"native\"\n self.reprentries = [ReprEntryNative(tblines)]\n self.extraline = None"},{"attributeType":"null","col":8,"comment":"null","endLoc":66,"id":1668,"name":"abs","nodeType":"Attribute","startLoc":66,"text":"self.abs"},{"col":4,"comment":"null","endLoc":941,"header":"def __init__(self, tblines)","id":1669,"name":"__init__","nodeType":"Function","startLoc":940,"text":"def __init__(self, tblines):\n self.lines = tblines"},{"attributeType":"null","col":8,"comment":"null","endLoc":65,"id":1671,"name":"expected","nodeType":"Attribute","startLoc":65,"text":"self.expected"},{"col":4,"comment":"unittest for the expected behavior to obtain ids for parametrized\n bytes values:\n - python2: non-ascii strings are considered bytes and formatted using\n \"binary escape\", where any byte < 127 is escaped into its hex form.\n - python3: bytes objects are always escaped using \"binary escape\".\n ","endLoc":278,"header":"def test_bytes_idval(self)","id":1672,"name":"test_bytes_idval","nodeType":"Function","startLoc":262,"text":"def test_bytes_idval(self):\n \"\"\"unittest for the expected behavior to obtain ids for parametrized\n bytes values:\n - python2: non-ascii strings are considered bytes and formatted using\n \"binary escape\", where any byte < 127 is escaped into its hex form.\n - python3: bytes objects are always escaped using \"binary escape\".\n \"\"\"\n from _pytest.python import _idval\n\n values = [\n (b\"\", \"\"),\n (b\"\\xc3\\xb4\\xff\\xe4\", \"\\\\xc3\\\\xb4\\\\xff\\\\xe4\"),\n (b\"ascii\", \"ascii\"),\n (u\"αρά\".encode(\"utf-8\"), \"\\\\xce\\\\xb1\\\\xcf\\\\x81\\\\xce\\\\xac\"),\n ]\n for val, expected in values:\n assert _idval(val, \"a\", 6, idfn=None, item=None, config=None) == expected"},{"col":4,"comment":"null","endLoc":881,"header":"def __init__(self, chain)","id":1673,"name":"__init__","nodeType":"Function","startLoc":875,"text":"def __init__(self, chain):\n super(ExceptionChainRepr, self).__init__()\n self.chain = chain\n # reprcrash and reprtraceback of the outermost (the newest) exception\n # in the chain\n self.reprtraceback = chain[-1][0]\n self.reprcrash = chain[-1][1]"},{"attributeType":"null","col":8,"comment":"null","endLoc":67,"id":1674,"name":"rel","nodeType":"Attribute","startLoc":67,"text":"self.rel"},{"col":4,"comment":"unittest for the expected behavior to obtain ids for parametrized\n values that are classes or functions: their __name__.\n ","endLoc":294,"header":"def test_class_or_function_idval(self)","id":1675,"name":"test_class_or_function_idval","nodeType":"Function","startLoc":280,"text":"def test_class_or_function_idval(self):\n \"\"\"unittest for the expected behavior to obtain ids for parametrized\n values that are classes or functions: their __name__.\n \"\"\"\n from _pytest.python import _idval\n\n class TestClass(object):\n pass\n\n def test_function():\n pass\n\n values = [(TestClass, \"TestClass\"), (test_function, \"test_function\")]\n for val, expected in values:\n assert _idval(val, \"a\", 6, None, item=None, config=None) == expected"},{"col":4,"comment":"#250","endLoc":311,"header":"def test_idmaker_autoname(self)","id":1676,"name":"test_idmaker_autoname","nodeType":"Function","startLoc":296,"text":"def test_idmaker_autoname(self):\n \"\"\"#250\"\"\"\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"a\", \"b\"), [pytest.param(\"string\", 1.0), pytest.param(\"st-ring\", 2.0)]\n )\n assert result == [\"string-1.0\", \"st-ring-2.0\"]\n\n result = idmaker(\n (\"a\", \"b\"), [pytest.param(object(), 1.0), pytest.param(object(), object())]\n )\n assert result == [\"a0-1.0\", \"a1-b1\"]\n # unicode mixing, issue250\n result = idmaker((u\"a\", \"b\"), [pytest.param({}, b\"\\xc3\\xb4\")])\n assert result == [\"a0-\\\\xc3\\\\xb4\"]"},{"attributeType":"bool","col":8,"comment":"null","endLoc":68,"id":1677,"name":"nan_ok","nodeType":"Attribute","startLoc":68,"text":"self.nan_ok"},{"attributeType":"null","col":4,"comment":"null","endLoc":590,"id":1678,"name":"flow_marker","nodeType":"Attribute","startLoc":590,"text":"flow_marker"},{"attributeType":"null","col":4,"comment":"null","endLoc":591,"id":1679,"name":"fail_marker","nodeType":"Attribute","startLoc":591,"text":"fail_marker"},{"attributeType":"null","col":4,"comment":"null","endLoc":593,"id":1680,"name":"showlocals","nodeType":"Attribute","startLoc":593,"text":"showlocals"},{"attributeType":"null","col":4,"comment":"null","endLoc":594,"id":1681,"name":"style","nodeType":"Attribute","startLoc":594,"text":"style"},{"attributeType":"null","col":4,"comment":"null","endLoc":595,"id":1682,"name":"abspath","nodeType":"Attribute","startLoc":595,"text":"abspath"},{"className":"ApproxNumpy","col":0,"comment":"\n Perform approximate comparisons where the expected value is numpy array.\n ","endLoc":156,"id":1683,"nodeType":"Class","startLoc":116,"text":"class ApproxNumpy(ApproxBase):\n \"\"\"\n Perform approximate comparisons where the expected value is numpy array.\n \"\"\"\n\n def __repr__(self):\n list_scalars = _recursive_list_map(self._approx_scalar, self.expected.tolist())\n return \"approx({!r})\".format(list_scalars)\n\n if sys.version_info[0] == 2:\n __cmp__ = _cmp_raises_type_error\n\n def __eq__(self, actual):\n import numpy as np\n\n # self.expected is supposed to always be an array here\n\n if not np.isscalar(actual):\n try:\n actual = np.asarray(actual)\n except: # noqa\n raise TypeError(\"cannot compare '{}' to numpy.ndarray\".format(actual))\n\n if not np.isscalar(actual) and actual.shape != self.expected.shape:\n return False\n\n return ApproxBase.__eq__(self, actual)\n\n def _yield_comparisons(self, actual):\n import numpy as np\n\n # `actual` can either be a numpy array or a scalar, it is treated in\n # `__eq__` before being passed to `ApproxBase.__eq__`, which is the\n # only method that calls this one.\n\n if np.isscalar(actual):\n for i in np.ndindex(self.expected.shape):\n yield actual, self.expected[i].item()\n else:\n for i in np.ndindex(self.expected.shape):\n yield actual[i].item(), self.expected[i].item()"},{"attributeType":"null","col":4,"comment":"null","endLoc":596,"id":1684,"name":"tbfilter","nodeType":"Attribute","startLoc":596,"text":"tbfilter"},{"col":4,"comment":"null","endLoc":123,"header":"def __repr__(self)","id":1685,"name":"__repr__","nodeType":"Function","startLoc":121,"text":"def __repr__(self):\n list_scalars = _recursive_list_map(self._approx_scalar, self.expected.tolist())\n return \"approx({!r})\".format(list_scalars)"},{"attributeType":"null","col":4,"comment":"null","endLoc":597,"id":1686,"name":"funcargs","nodeType":"Attribute","startLoc":597,"text":"funcargs"},{"attributeType":"null","col":4,"comment":"null","endLoc":598,"id":1687,"name":"truncate_locals","nodeType":"Attribute","startLoc":598,"text":"truncate_locals"},{"attributeType":"null","col":4,"comment":"null","endLoc":599,"id":1688,"name":"chain","nodeType":"Attribute","startLoc":599,"text":"chain"},{"attributeType":"null","col":4,"comment":"null","endLoc":600,"id":1689,"name":"astcache","nodeType":"Attribute","startLoc":600,"text":"astcache"},{"col":0,"comment":"null","endLoc":113,"header":"def _recursive_list_map(f, x)","id":1690,"name":"_recursive_list_map","nodeType":"Function","startLoc":109,"text":"def _recursive_list_map(f, x):\n if isinstance(x, list):\n return list(_recursive_list_map(f, xi) for xi in x)\n else:\n return f(x)"},{"className":"TerminalRepr","col":0,"comment":"null","endLoc":858,"id":1691,"nodeType":"Class","startLoc":842,"text":"class TerminalRepr(object):\n def __str__(self):\n s = self.__unicode__()\n if _PY2:\n s = s.encode(\"utf-8\")\n return s\n\n def __unicode__(self):\n # FYI this is called from pytest-xdist's serialization of exception\n # information.\n io = py.io.TextIO()\n tw = py.io.TerminalWriter(file=io)\n self.toterminal(tw)\n return io.getvalue().strip()\n\n def __repr__(self):\n return \"<%s instance at %0x>\" % (self.__class__, id(self))"},{"col":4,"comment":"null","endLoc":847,"header":"def __str__(self)","id":1692,"name":"__str__","nodeType":"Function","startLoc":843,"text":"def __str__(self):\n s = self.__unicode__()\n if _PY2:\n s = s.encode(\"utf-8\")\n return s"},{"col":4,"comment":"null","endLoc":855,"header":"def __unicode__(self)","id":1693,"name":"__unicode__","nodeType":"Function","startLoc":849,"text":"def __unicode__(self):\n # FYI this is called from pytest-xdist's serialization of exception\n # information.\n io = py.io.TextIO()\n tw = py.io.TerminalWriter(file=io)\n self.toterminal(tw)\n return io.getvalue().strip()"},{"col":4,"comment":"null","endLoc":858,"header":"def __repr__(self)","id":1694,"name":"__repr__","nodeType":"Function","startLoc":857,"text":"def __repr__(self):\n return \"<%s instance at %0x>\" % (self.__class__, id(self))"},{"col":0,"comment":"null","endLoc":65,"header":"def _format_args(func)","id":1695,"name":"_format_args","nodeType":"Function","startLoc":64,"text":"def _format_args(func):\n return str(signature(func))"},{"col":4,"comment":"null","endLoc":317,"header":"def test_idmaker_with_bytes_regex(self)","id":1696,"name":"test_idmaker_with_bytes_regex","nodeType":"Function","startLoc":313,"text":"def test_idmaker_with_bytes_regex(self):\n from _pytest.python import idmaker\n\n result = idmaker((\"a\"), [pytest.param(re.compile(b\"foo\"), 1.0)])\n assert result == [\"foo\"]"},{"col":4,"comment":"null","endLoc":352,"header":"def test_idmaker_native_strings(self)","id":1697,"name":"test_idmaker_native_strings","nodeType":"Function","startLoc":319,"text":"def test_idmaker_native_strings(self):\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"a\", \"b\"),\n [\n pytest.param(1.0, -1.1),\n pytest.param(2, -202),\n pytest.param(\"three\", \"three hundred\"),\n pytest.param(True, False),\n pytest.param(None, None),\n pytest.param(re.compile(\"foo\"), re.compile(\"bar\")),\n pytest.param(str, int),\n pytest.param(list(\"six\"), [66, 66]),\n pytest.param({7}, set(\"seven\")),\n pytest.param(tuple(\"eight\"), (8, -8, 8)),\n pytest.param(b\"\\xc3\\xb4\", b\"name\"),\n pytest.param(b\"\\xc3\\xb4\", u\"other\"),\n ],\n )\n assert result == [\n \"1.0--1.1\",\n \"2--202\",\n \"three-three hundred\",\n \"True-False\",\n \"None-None\",\n \"foo-bar\",\n \"str-int\",\n \"a7-b7\",\n \"a8-b8\",\n \"a9-b9\",\n \"\\\\xc3\\\\xb4-name\",\n \"\\\\xc3\\\\xb4-other\",\n ]"},{"className":"_PytestWrapper","col":0,"comment":"Dummy wrapper around a function object for internal use only.\n\n Used to correctly unwrap the underlying function object\n when we are creating fixtures, because we wrap the function object ourselves with a decorator\n to issue warnings when the fixture function is called directly.\n ","endLoc":275,"id":1698,"nodeType":"Class","startLoc":266,"text":"class _PytestWrapper(object):\n \"\"\"Dummy wrapper around a function object for internal use only.\n\n Used to correctly unwrap the underlying function object\n when we are creating fixtures, because we wrap the function object ourselves with a decorator\n to issue warnings when the fixture function is called directly.\n \"\"\"\n\n def __init__(self, obj):\n self.obj = obj"},{"attributeType":"null","col":8,"comment":"null","endLoc":275,"id":1699,"name":"obj","nodeType":"Attribute","startLoc":275,"text":"self.obj"},{"attributeType":"null","col":0,"comment":"null","endLoc":71,"id":1700,"name":"exc_clear","nodeType":"Attribute","startLoc":71,"text":"exc_clear"},{"col":0,"comment":"\n Attempts to obtain the real function object that might be wrapping ``obj``, while at the same time\n returning a bound method to ``holder`` if the original object was a bound method.\n ","endLoc":318,"header":"def get_real_method(obj, holder)","id":1701,"name":"get_real_method","nodeType":"Function","startLoc":306,"text":"def get_real_method(obj, holder):\n \"\"\"\n Attempts to obtain the real function object that might be wrapping ``obj``, while at the same time\n returning a bound method to ``holder`` if the original object was a bound method.\n \"\"\"\n try:\n is_method = hasattr(obj, \"__func__\")\n obj = get_real_func(obj)\n except Exception:\n return obj\n if is_method and hasattr(obj, \"__get__\") and callable(obj.__get__):\n obj = obj.__get__(holder)\n return obj"},{"col":0,"comment":"null","endLoc":98,"header":"def getlocation(function, curdir)","id":1702,"name":"getlocation","nodeType":"Function","startLoc":92,"text":"def getlocation(function, curdir):\n function = get_real_func(function)\n fn = py.path.local(inspect.getfile(function))\n lineno = function.__code__.co_firstlineno\n if fn.relto(curdir):\n fn = fn.relto(curdir)\n return \"%s:%d\" % (fn, lineno + 1)"},{"col":0,"comment":"null","endLoc":78,"header":"def is_generator(func)","id":1704,"name":"is_generator","nodeType":"Function","startLoc":76,"text":"def is_generator(func):\n genfunc = inspect.isgeneratorfunction(func)\n return genfunc and not iscoroutinefunction(func)"},{"col":0,"comment":"Return True if func is a decorated coroutine function.\n\n Note: copied and modified from Python 3.5's builtin couroutines.py to avoid import asyncio directly,\n which in turns also initializes the \"logging\" module as side-effect (see issue #8).\n ","endLoc":89,"header":"def iscoroutinefunction(func)","id":1708,"name":"iscoroutinefunction","nodeType":"Function","startLoc":81,"text":"def iscoroutinefunction(func):\n \"\"\"Return True if func is a decorated coroutine function.\n\n Note: copied and modified from Python 3.5's builtin couroutines.py to avoid import asyncio directly,\n which in turns also initializes the \"logging\" module as side-effect (see issue #8).\n \"\"\"\n return getattr(func, \"_is_coroutine\", False) or (\n hasattr(inspect, \"iscoroutinefunction\") and inspect.iscoroutinefunction(func)\n )"},{"attributeType":"null","col":0,"comment":"null","endLoc":40,"id":1713,"name":"NOTSET","nodeType":"Attribute","startLoc":40,"text":"NOTSET"},{"className":"PseudoFixtureDef","col":0,"comment":"null","endLoc":46,"id":1714,"nodeType":"Class","startLoc":43,"text":"@attr.s(frozen=True)\nclass PseudoFixtureDef(object):\n cached_result = attr.ib()\n scope = attr.ib()"},{"attributeType":"null","col":4,"comment":"null","endLoc":45,"id":1715,"name":"cached_result","nodeType":"Attribute","startLoc":45,"text":"cached_result"},{"attributeType":"null","col":4,"comment":"null","endLoc":46,"id":1716,"name":"scope","nodeType":"Attribute","startLoc":46,"text":"scope"},{"className":"FuncFixtureInfo","col":0,"comment":"null","endLoc":339,"id":1717,"nodeType":"Class","startLoc":303,"text":"@attr.s(slots=True)\nclass FuncFixtureInfo(object):\n # original function argument names\n argnames = attr.ib(type=tuple)\n # argnames that function immediately requires. These include argnames +\n # fixture names specified via usefixtures and via autouse=True in fixture\n # definitions.\n initialnames = attr.ib(type=tuple)\n names_closure = attr.ib() # List[str]\n name2fixturedefs = attr.ib() # List[str, List[FixtureDef]]\n\n def prune_dependency_tree(self):\n \"\"\"Recompute names_closure from initialnames and name2fixturedefs\n\n Can only reduce names_closure, which means that the new closure will\n always be a subset of the old one. The order is preserved.\n\n This method is needed because direct parametrization may shadow some\n of the fixtures that were included in the originally built dependency\n tree. In this way the dependency tree can get pruned, and the closure\n of argnames may get reduced.\n \"\"\"\n closure = set()\n working_set = set(self.initialnames)\n while working_set:\n argname = working_set.pop()\n # argname may be smth not included in the original names_closure,\n # in which case we ignore it. This currently happens with pseudo\n # FixtureDefs which wrap 'get_direct_param_fixture_func(request)'.\n # So they introduce the new dependency 'request' which might have\n # been missing in the original tree (closure).\n if argname not in closure and argname in self.names_closure:\n closure.add(argname)\n if argname in self.name2fixturedefs:\n working_set.update(self.name2fixturedefs[argname][-1].argnames)\n\n self.names_closure[:] = sorted(closure, key=self.names_closure.index)"},{"col":4,"comment":"Recompute names_closure from initialnames and name2fixturedefs\n\n Can only reduce names_closure, which means that the new closure will\n always be a subset of the old one. The order is preserved.\n\n This method is needed because direct parametrization may shadow some\n of the fixtures that were included in the originally built dependency\n tree. In this way the dependency tree can get pruned, and the closure\n of argnames may get reduced.\n ","endLoc":339,"header":"def prune_dependency_tree(self)","id":1718,"name":"prune_dependency_tree","nodeType":"Function","startLoc":314,"text":"def prune_dependency_tree(self):\n \"\"\"Recompute names_closure from initialnames and name2fixturedefs\n\n Can only reduce names_closure, which means that the new closure will\n always be a subset of the old one. The order is preserved.\n\n This method is needed because direct parametrization may shadow some\n of the fixtures that were included in the originally built dependency\n tree. In this way the dependency tree can get pruned, and the closure\n of argnames may get reduced.\n \"\"\"\n closure = set()\n working_set = set(self.initialnames)\n while working_set:\n argname = working_set.pop()\n # argname may be smth not included in the original names_closure,\n # in which case we ignore it. This currently happens with pseudo\n # FixtureDefs which wrap 'get_direct_param_fixture_func(request)'.\n # So they introduce the new dependency 'request' which might have\n # been missing in the original tree (closure).\n if argname not in closure and argname in self.names_closure:\n closure.add(argname)\n if argname in self.name2fixturedefs:\n working_set.update(self.name2fixturedefs[argname][-1].argnames)\n\n self.names_closure[:] = sorted(closure, key=self.names_closure.index)"},{"col":4,"comment":"null","endLoc":368,"header":"def test_idmaker_non_printable_characters(self)","id":1719,"name":"test_idmaker_non_printable_characters","nodeType":"Function","startLoc":354,"text":"def test_idmaker_non_printable_characters(self):\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"s\", \"n\"),\n [\n pytest.param(\"\\x00\", 1),\n pytest.param(\"\\x05\", 2),\n pytest.param(b\"\\x00\", 3),\n pytest.param(b\"\\x05\", 4),\n pytest.param(\"\\t\", 5),\n pytest.param(b\"\\t\", 6),\n ],\n )\n assert result == [\"\\\\x00-1\", \"\\\\x05-2\", \"\\\\x00-3\", \"\\\\x05-4\", \"\\\\t-5\", \"\\\\t-6\"]"},{"col":4,"comment":"null","endLoc":380,"header":"def test_idmaker_manual_ids_must_be_printable(self)","id":1720,"name":"test_idmaker_manual_ids_must_be_printable","nodeType":"Function","startLoc":370,"text":"def test_idmaker_manual_ids_must_be_printable(self):\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"s\",),\n [\n pytest.param(\"x00\", id=\"hello \\x00\"),\n pytest.param(\"x05\", id=\"hello \\x05\"),\n ],\n )\n assert result == [\"hello \\\\x00\", \"hello \\\\x05\"]"},{"col":4,"comment":"null","endLoc":388,"header":"def test_idmaker_enum(self)","id":1721,"name":"test_idmaker_enum","nodeType":"Function","startLoc":382,"text":"def test_idmaker_enum(self):\n from _pytest.python import idmaker\n\n enum = pytest.importorskip(\"enum\")\n e = enum.Enum(\"Foo\", \"one, two\")\n result = idmaker((\"a\", \"b\"), [pytest.param(e.one, e.two)])\n assert result == [\"Foo.one-Foo.two\"]"},{"col":4,"comment":"null","endLoc":142,"header":"def __eq__(self, actual)","id":1722,"name":"__eq__","nodeType":"Function","startLoc":128,"text":"def __eq__(self, actual):\n import numpy as np\n\n # self.expected is supposed to always be an array here\n\n if not np.isscalar(actual):\n try:\n actual = np.asarray(actual)\n except: # noqa\n raise TypeError(\"cannot compare '{}' to numpy.ndarray\".format(actual))\n\n if not np.isscalar(actual) and actual.shape != self.expected.shape:\n return False\n\n return ApproxBase.__eq__(self, actual)"},{"col":4,"comment":"#351","endLoc":407,"header":"def test_idmaker_idfn(self)","id":1723,"name":"test_idmaker_idfn","nodeType":"Function","startLoc":390,"text":"def test_idmaker_idfn(self):\n \"\"\"#351\"\"\"\n from _pytest.python import idmaker\n\n def ids(val):\n if isinstance(val, Exception):\n return repr(val)\n\n result = idmaker(\n (\"a\", \"b\"),\n [\n pytest.param(10.0, IndexError()),\n pytest.param(20, KeyError()),\n pytest.param(\"three\", [1, 2, 3]),\n ],\n idfn=ids,\n )\n assert result == [\"10.0-IndexError()\", \"20-KeyError()\", \"three-b2\"]"},{"col":4,"comment":"#351","endLoc":425,"header":"def test_idmaker_idfn_unique_names(self)","id":1726,"name":"test_idmaker_idfn_unique_names","nodeType":"Function","startLoc":409,"text":"def test_idmaker_idfn_unique_names(self):\n \"\"\"#351\"\"\"\n from _pytest.python import idmaker\n\n def ids(val):\n return \"a\"\n\n result = idmaker(\n (\"a\", \"b\"),\n [\n pytest.param(10.0, IndexError()),\n pytest.param(20, KeyError()),\n pytest.param(\"three\", [1, 2, 3]),\n ],\n idfn=ids,\n )\n assert result == [\"a-a0\", \"a-a1\", \"a-a2\"]"},{"attributeType":"null","col":4,"comment":"null","endLoc":306,"id":1728,"name":"argnames","nodeType":"Attribute","startLoc":306,"text":"argnames"},{"attributeType":"null","col":4,"comment":"null","endLoc":310,"id":1729,"name":"initialnames","nodeType":"Attribute","startLoc":310,"text":"initialnames"},{"attributeType":"null","col":4,"comment":"null","endLoc":311,"id":1730,"name":"names_closure","nodeType":"Attribute","startLoc":311,"text":"names_closure"},{"attributeType":"null","col":4,"comment":"null","endLoc":312,"id":1731,"name":"name2fixturedefs","nodeType":"Attribute","startLoc":312,"text":"name2fixturedefs"},{"className":"FixtureRequest","col":0,"comment":" A request for a fixture from a test or fixture function.\n\n A request object gives access to the requesting test context\n and has an optional ``param`` attribute in case\n the fixture is parametrized indirectly.\n ","endLoc":638,"id":1732,"nodeType":"Class","startLoc":342,"text":"class FixtureRequest(FuncargnamesCompatAttr):\n \"\"\" A request for a fixture from a test or fixture function.\n\n A request object gives access to the requesting test context\n and has an optional ``param`` attribute in case\n the fixture is parametrized indirectly.\n \"\"\"\n\n def __init__(self, pyfuncitem):\n self._pyfuncitem = pyfuncitem\n #: fixture for which this request is being performed\n self.fixturename = None\n #: Scope string, one of \"function\", \"class\", \"module\", \"session\"\n self.scope = \"function\"\n self._fixture_defs = {} # argname -> FixtureDef\n fixtureinfo = pyfuncitem._fixtureinfo\n self._arg2fixturedefs = fixtureinfo.name2fixturedefs.copy()\n self._arg2index = {}\n self._fixturemanager = pyfuncitem.session._fixturemanager\n\n @property\n def fixturenames(self):\n \"\"\"names of all active fixtures in this request\"\"\"\n result = list(self._pyfuncitem._fixtureinfo.names_closure)\n result.extend(set(self._fixture_defs).difference(result))\n return result\n\n @property\n def node(self):\n \"\"\" underlying collection node (depends on current request scope)\"\"\"\n return self._getscopeitem(self.scope)\n\n def _getnextfixturedef(self, argname):\n fixturedefs = self._arg2fixturedefs.get(argname, None)\n if fixturedefs is None:\n # we arrive here because of a dynamic call to\n # getfixturevalue(argname) usage which was naturally\n # not known at parsing/collection time\n parentid = self._pyfuncitem.parent.nodeid\n fixturedefs = self._fixturemanager.getfixturedefs(argname, parentid)\n self._arg2fixturedefs[argname] = fixturedefs\n # fixturedefs list is immutable so we maintain a decreasing index\n index = self._arg2index.get(argname, 0) - 1\n if fixturedefs is None or (-index > len(fixturedefs)):\n raise FixtureLookupError(argname, self)\n self._arg2index[argname] = index\n return fixturedefs[index]\n\n @property\n def config(self):\n \"\"\" the pytest config object associated with this request. \"\"\"\n return self._pyfuncitem.config\n\n @scopeproperty()\n def function(self):\n \"\"\" test function object if the request has a per-function scope. \"\"\"\n return self._pyfuncitem.obj\n\n @scopeproperty(\"class\")\n def cls(self):\n \"\"\" class (can be None) where the test function was collected. \"\"\"\n clscol = self._pyfuncitem.getparent(_pytest.python.Class)\n if clscol:\n return clscol.obj\n\n @property\n def instance(self):\n \"\"\" instance (can be None) on which test function was collected. \"\"\"\n # unittest support hack, see _pytest.unittest.TestCaseFunction\n try:\n return self._pyfuncitem._testcase\n except AttributeError:\n function = getattr(self, \"function\", None)\n return getattr(function, \"__self__\", None)\n\n @scopeproperty()\n def module(self):\n \"\"\" python module object where the test function was collected. \"\"\"\n return self._pyfuncitem.getparent(_pytest.python.Module).obj\n\n @scopeproperty()\n def fspath(self):\n \"\"\" the file system path of the test module which collected this test. \"\"\"\n return self._pyfuncitem.fspath\n\n @property\n def keywords(self):\n \"\"\" keywords/markers dictionary for the underlying node. \"\"\"\n return self.node.keywords\n\n @property\n def session(self):\n \"\"\" pytest session object. \"\"\"\n return self._pyfuncitem.session\n\n def addfinalizer(self, finalizer):\n \"\"\" add finalizer/teardown function to be called after the\n last test within the requesting test context finished\n execution. \"\"\"\n # XXX usually this method is shadowed by fixturedef specific ones\n self._addfinalizer(finalizer, scope=self.scope)\n\n def _addfinalizer(self, finalizer, scope):\n colitem = self._getscopeitem(scope)\n self._pyfuncitem.session._setupstate.addfinalizer(\n finalizer=finalizer, colitem=colitem\n )\n\n def applymarker(self, marker):\n \"\"\" Apply a marker to a single test function invocation.\n This method is useful if you don't want to have a keyword/marker\n on all function invocations.\n\n :arg marker: a :py:class:`_pytest.mark.MarkDecorator` object\n created by a call to ``pytest.mark.NAME(...)``.\n \"\"\"\n self.node.add_marker(marker)\n\n def raiseerror(self, msg):\n \"\"\" raise a FixtureLookupError with the given message. \"\"\"\n raise self._fixturemanager.FixtureLookupError(None, self, msg)\n\n def _fillfixtures(self):\n item = self._pyfuncitem\n fixturenames = getattr(item, \"fixturenames\", self.fixturenames)\n for argname in fixturenames:\n if argname not in item.funcargs:\n item.funcargs[argname] = self.getfixturevalue(argname)\n\n def getfixturevalue(self, argname):\n \"\"\" Dynamically run a named fixture function.\n\n Declaring fixtures via function argument is recommended where possible.\n But if you can only decide whether to use another fixture at test\n setup time, you may use this function to retrieve it inside a fixture\n or test function body.\n \"\"\"\n return self._get_active_fixturedef(argname).cached_result[0]\n\n def getfuncargvalue(self, argname):\n \"\"\" Deprecated, use getfixturevalue. \"\"\"\n from _pytest import deprecated\n\n warnings.warn(deprecated.GETFUNCARGVALUE, stacklevel=2)\n return self.getfixturevalue(argname)\n\n def _get_active_fixturedef(self, argname):\n try:\n return self._fixture_defs[argname]\n except KeyError:\n try:\n fixturedef = self._getnextfixturedef(argname)\n except FixtureLookupError:\n if argname == \"request\":\n cached_result = (self, [0], None)\n scope = \"function\"\n return PseudoFixtureDef(cached_result, scope)\n raise\n # remove indent to prevent the python3 exception\n # from leaking into the call\n self._compute_fixture_value(fixturedef)\n self._fixture_defs[argname] = fixturedef\n return fixturedef\n\n def _get_fixturestack(self):\n current = self\n values = []\n while 1:\n fixturedef = getattr(current, \"_fixturedef\", None)\n if fixturedef is None:\n values.reverse()\n return values\n values.append(fixturedef)\n current = current._parent_request\n\n def _compute_fixture_value(self, fixturedef):\n \"\"\"\n Creates a SubRequest based on \"self\" and calls the execute method of the given fixturedef object. This will\n force the FixtureDef object to throw away any previous results and compute a new fixture value, which\n will be stored into the FixtureDef object itself.\n\n :param FixtureDef fixturedef:\n \"\"\"\n # prepare a subrequest object before calling fixture function\n # (latter managed by fixturedef)\n argname = fixturedef.argname\n funcitem = self._pyfuncitem\n scope = fixturedef.scope\n try:\n param = funcitem.callspec.getparam(argname)\n except (AttributeError, ValueError):\n param = NOTSET\n param_index = 0\n has_params = fixturedef.params is not None\n fixtures_not_supported = getattr(funcitem, \"nofuncargs\", False)\n if has_params and fixtures_not_supported:\n msg = (\n \"{name} does not support fixtures, maybe unittest.TestCase subclass?\\n\"\n \"Node id: {nodeid}\\n\"\n \"Function type: {typename}\"\n ).format(\n name=funcitem.name,\n nodeid=funcitem.nodeid,\n typename=type(funcitem).__name__,\n )\n fail(msg, pytrace=False)\n if has_params:\n frame = inspect.stack()[3]\n frameinfo = inspect.getframeinfo(frame[0])\n source_path = frameinfo.filename\n source_lineno = frameinfo.lineno\n source_path = py.path.local(source_path)\n if source_path.relto(funcitem.config.rootdir):\n source_path = source_path.relto(funcitem.config.rootdir)\n msg = (\n \"The requested fixture has no parameter defined for test:\\n\"\n \" {}\\n\\n\"\n \"Requested fixture '{}' defined in:\\n{}\"\n \"\\n\\nRequested here:\\n{}:{}\".format(\n funcitem.nodeid,\n fixturedef.argname,\n getlocation(fixturedef.func, funcitem.config.rootdir),\n source_path,\n source_lineno,\n )\n )\n fail(msg, pytrace=False)\n else:\n param_index = funcitem.callspec.indices[argname]\n # if a parametrize invocation set a scope it will override\n # the static scope defined with the fixture function\n paramscopenum = funcitem.callspec._arg2scopenum.get(argname)\n if paramscopenum is not None:\n scope = scopes[paramscopenum]\n\n subrequest = SubRequest(self, scope, param, param_index, fixturedef)\n\n # check if a higher-level scoped fixture accesses a lower level one\n subrequest._check_scope(argname, self.scope, scope)\n\n # clear sys.exc_info before invoking the fixture (python bug?)\n # if it's not explicitly cleared it will leak into the call\n exc_clear()\n try:\n # call the fixture function\n fixturedef.execute(request=subrequest)\n finally:\n self._schedule_finalizers(fixturedef, subrequest)\n\n def _schedule_finalizers(self, fixturedef, subrequest):\n # if fixture function failed it might have registered finalizers\n self.session._setupstate.addfinalizer(\n functools.partial(fixturedef.finish, request=subrequest), subrequest.node\n )\n\n def _check_scope(self, argname, invoking_scope, requested_scope):\n if argname == \"request\":\n return\n if scopemismatch(invoking_scope, requested_scope):\n # try to report something helpful\n lines = self._factorytraceback()\n fail(\n \"ScopeMismatch: You tried to access the %r scoped \"\n \"fixture %r with a %r scoped request object, \"\n \"involved factories\\n%s\"\n % ((requested_scope, argname, invoking_scope, \"\\n\".join(lines))),\n pytrace=False,\n )\n\n def _factorytraceback(self):\n lines = []\n for fixturedef in self._get_fixturestack():\n factory = fixturedef.func\n fs, lineno = getfslineno(factory)\n p = self._pyfuncitem.session.fspath.bestrelpath(fs)\n args = _format_args(factory)\n lines.append(\"%s:%d: def %s%s\" % (p, lineno + 1, factory.__name__, args))\n return lines\n\n def _getscopeitem(self, scope):\n if scope == \"function\":\n # this might also be a non-function Item despite its attribute name\n return self._pyfuncitem\n if scope == \"package\":\n node = get_scope_package(self._pyfuncitem, self._fixturedef)\n else:\n node = get_scope_node(self._pyfuncitem, scope)\n if node is None and scope == \"class\":\n # fallback to function item itself\n node = self._pyfuncitem\n assert node, 'Could not obtain a node for scope \"{}\" for function {!r}'.format(\n scope, self._pyfuncitem\n )\n return node\n\n def __repr__(self):\n return \"\" % (self.node)"},{"col":4,"comment":"names of all active fixtures in this request","endLoc":367,"header":"@property\n def fixturenames(self)","id":1733,"name":"fixturenames","nodeType":"Function","startLoc":362,"text":"@property\n def fixturenames(self):\n \"\"\"names of all active fixtures in this request\"\"\"\n result = list(self._pyfuncitem._fixtureinfo.names_closure)\n result.extend(set(self._fixture_defs).difference(result))\n return result"},{"col":4,"comment":"null","endLoc":156,"header":"def _yield_comparisons(self, actual)","id":1734,"name":"_yield_comparisons","nodeType":"Function","startLoc":144,"text":"def _yield_comparisons(self, actual):\n import numpy as np\n\n # `actual` can either be a numpy array or a scalar, it is treated in\n # `__eq__` before being passed to `ApproxBase.__eq__`, which is the\n # only method that calls this one.\n\n if np.isscalar(actual):\n for i in np.ndindex(self.expected.shape):\n yield actual, self.expected[i].item()\n else:\n for i in np.ndindex(self.expected.shape):\n yield actual[i].item(), self.expected[i].item()"},{"attributeType":"function","col":8,"comment":"null","endLoc":126,"id":1735,"name":"__cmp__","nodeType":"Attribute","startLoc":126,"text":"__cmp__"},{"className":"ApproxMapping","col":0,"comment":"\n Perform approximate comparisons where the expected value is a mapping with\n numeric values (the keys can be anything).\n ","endLoc":187,"id":1736,"nodeType":"Class","startLoc":159,"text":"class ApproxMapping(ApproxBase):\n \"\"\"\n Perform approximate comparisons where the expected value is a mapping with\n numeric values (the keys can be anything).\n \"\"\"\n\n def __repr__(self):\n return \"approx({!r})\".format(\n {k: self._approx_scalar(v) for k, v in self.expected.items()}\n )\n\n def __eq__(self, actual):\n if set(actual.keys()) != set(self.expected.keys()):\n return False\n\n return ApproxBase.__eq__(self, actual)\n\n def _yield_comparisons(self, actual):\n for k in self.expected.keys():\n yield actual[k], self.expected[k]\n\n def _check_type(self):\n __tracebackhide__ = True\n for key, value in self.expected.items():\n if isinstance(value, type(self.expected)):\n msg = \"pytest.approx() does not support nested dictionaries: key={!r} value={!r}\\n full mapping={}\"\n raise TypeError(msg.format(key, value, pprint.pformat(self.expected)))\n elif not isinstance(value, Number):\n raise _non_numeric_type_error(self.expected, at=\"key={!r}\".format(key))"},{"col":4,"comment":"null","endLoc":168,"header":"def __repr__(self)","id":1737,"name":"__repr__","nodeType":"Function","startLoc":165,"text":"def __repr__(self):\n return \"approx({!r})\".format(\n {k: self._approx_scalar(v) for k, v in self.expected.items()}\n )"},{"col":4,"comment":"null","endLoc":174,"header":"def __eq__(self, actual)","id":1738,"name":"__eq__","nodeType":"Function","startLoc":170,"text":"def __eq__(self, actual):\n if set(actual.keys()) != set(self.expected.keys()):\n return False\n\n return ApproxBase.__eq__(self, actual)"},{"col":4,"comment":"unittest for expected behavior to create ids with idfn and\n disable_test_id_escaping_and_forfeit_all_rights_to_community_support\n option. (#5294)\n ","endLoc":458,"header":"def test_idmaker_with_idfn_and_config(self)","id":1739,"name":"test_idmaker_with_idfn_and_config","nodeType":"Function","startLoc":427,"text":"def test_idmaker_with_idfn_and_config(self):\n \"\"\"unittest for expected behavior to create ids with idfn and\n disable_test_id_escaping_and_forfeit_all_rights_to_community_support\n option. (#5294)\n \"\"\"\n from _pytest.python import idmaker\n\n class MockConfig(object):\n def __init__(self, config):\n self.config = config\n\n @property\n def hook(self):\n return self\n\n def pytest_make_parametrize_id(self, **kw):\n pass\n\n def getini(self, name):\n return self.config[name]\n\n option = \"disable_test_id_escaping_and_forfeit_all_rights_to_community_support\"\n\n values = [\n (MockConfig({option: True}), u\"ação\"),\n (MockConfig({option: False}), \"a\\\\xe7\\\\xe3o\"),\n ]\n for config, expected in values:\n result = idmaker(\n (\"a\",), [pytest.param(\"string\")], idfn=lambda _: u\"ação\", config=config\n )\n assert result == [expected]"},{"col":55,"endLoc":456,"id":1741,"nodeType":"Lambda","startLoc":456,"text":"lambda _: u\"ação\""},{"col":4,"comment":"unittest for expected behavior to create ids with ids and\n disable_test_id_escaping_and_forfeit_all_rights_to_community_support\n option. (#5294)\n ","endLoc":491,"header":"def test_idmaker_with_ids_and_config(self)","id":1742,"name":"test_idmaker_with_ids_and_config","nodeType":"Function","startLoc":460,"text":"def test_idmaker_with_ids_and_config(self):\n \"\"\"unittest for expected behavior to create ids with ids and\n disable_test_id_escaping_and_forfeit_all_rights_to_community_support\n option. (#5294)\n \"\"\"\n from _pytest.python import idmaker\n\n class MockConfig(object):\n def __init__(self, config):\n self.config = config\n\n @property\n def hook(self):\n return self\n\n def pytest_make_parametrize_id(self, **kw):\n pass\n\n def getini(self, name):\n return self.config[name]\n\n option = \"disable_test_id_escaping_and_forfeit_all_rights_to_community_support\"\n\n values = [\n (MockConfig({option: True}), u\"ação\"),\n (MockConfig({option: False}), \"a\\\\xe7\\\\xe3o\"),\n ]\n for config, expected in values:\n result = idmaker(\n (\"a\",), [pytest.param(\"string\")], ids=[u\"ação\"], config=config\n )\n assert result == [expected]"},{"col":4,"comment":"null","endLoc":178,"header":"def _yield_comparisons(self, actual)","id":1744,"name":"_yield_comparisons","nodeType":"Function","startLoc":176,"text":"def _yield_comparisons(self, actual):\n for k in self.expected.keys():\n yield actual[k], self.expected[k]"},{"col":4,"comment":"\n :param testdir: the instance of Testdir class, a temporary\n test directory.\n ","endLoc":516,"header":"def test_parametrize_ids_exception(self, testdir)","id":1745,"name":"test_parametrize_ids_exception","nodeType":"Function","startLoc":493,"text":"def test_parametrize_ids_exception(self, testdir):\n \"\"\"\n :param testdir: the instance of Testdir class, a temporary\n test directory.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n def ids(arg):\n raise Exception(\"bad ids\")\n\n @pytest.mark.parametrize(\"arg\", [\"a\", \"b\"], ids=ids)\n def test_foo(arg):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*test_foo: error raised while trying to determine id of parameter 'arg' at position 0\",\n \"*Exception: bad ids\",\n ]\n )"},{"col":4,"comment":"null","endLoc":531,"header":"def test_parametrize_ids_returns_non_string(self, testdir)","id":1746,"name":"test_parametrize_ids_returns_non_string","nodeType":"Function","startLoc":518,"text":"def test_parametrize_ids_returns_non_string(self, testdir):\n testdir.makepyfile(\n \"\"\"\\\n import pytest\n\n def ids(d):\n return d\n\n @pytest.mark.parametrize(\"arg\", ({1: 2}, {3, 4}), ids=ids)\n def test(arg):\n assert arg\n \"\"\"\n )\n assert testdir.runpytest().ret == 0"},{"col":4,"comment":"null","endLoc":539,"header":"def test_idmaker_with_ids(self)","id":1747,"name":"test_idmaker_with_ids","nodeType":"Function","startLoc":533,"text":"def test_idmaker_with_ids(self):\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"a\", \"b\"), [pytest.param(1, 2), pytest.param(3, 4)], ids=[\"a\", None]\n )\n assert result == [\"a\", \"3-4\"]"},{"col":4,"comment":"null","endLoc":187,"header":"def _check_type(self)","id":1748,"name":"_check_type","nodeType":"Function","startLoc":180,"text":"def _check_type(self):\n __tracebackhide__ = True\n for key, value in self.expected.items():\n if isinstance(value, type(self.expected)):\n msg = \"pytest.approx() does not support nested dictionaries: key={!r} value={!r}\\n full mapping={}\"\n raise TypeError(msg.format(key, value, pprint.pformat(self.expected)))\n elif not isinstance(value, Number):\n raise _non_numeric_type_error(self.expected, at=\"key={!r}\".format(key))"},{"col":4,"comment":"null","endLoc":549,"header":"def test_idmaker_with_paramset_id(self)","id":1749,"name":"test_idmaker_with_paramset_id","nodeType":"Function","startLoc":541,"text":"def test_idmaker_with_paramset_id(self):\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"a\", \"b\"),\n [pytest.param(1, 2, id=\"me\"), pytest.param(3, 4, id=\"you\")],\n ids=[\"a\", None],\n )\n assert result == [\"me\", \"you\"]"},{"col":4,"comment":"null","endLoc":557,"header":"def test_idmaker_with_ids_unique_names(self)","id":1750,"name":"test_idmaker_with_ids_unique_names","nodeType":"Function","startLoc":551,"text":"def test_idmaker_with_ids_unique_names(self):\n from _pytest.python import idmaker\n\n result = idmaker(\n (\"a\"), map(pytest.param, [1, 2, 3, 4, 5]), ids=[\"a\", \"a\", \"b\", \"c\", \"b\"]\n )\n assert result == [\"a0\", \"a1\", \"b0\", \"c\", \"b1\"]"},{"col":4,"comment":" underlying collection node (depends on current request scope)","endLoc":372,"header":"@property\n def node(self)","id":1752,"name":"node","nodeType":"Function","startLoc":369,"text":"@property\n def node(self):\n \"\"\" underlying collection node (depends on current request scope)\"\"\"\n return self._getscopeitem(self.scope)"},{"className":"ApproxSequencelike","col":0,"comment":"\n Perform approximate comparisons where the expected value is a sequence of\n numbers.\n ","endLoc":221,"id":1754,"nodeType":"Class","startLoc":190,"text":"class ApproxSequencelike(ApproxBase):\n \"\"\"\n Perform approximate comparisons where the expected value is a sequence of\n numbers.\n \"\"\"\n\n def __repr__(self):\n seq_type = type(self.expected)\n if seq_type not in (tuple, list, set):\n seq_type = list\n return \"approx({!r})\".format(\n seq_type(self._approx_scalar(x) for x in self.expected)\n )\n\n def __eq__(self, actual):\n if len(actual) != len(self.expected):\n return False\n return ApproxBase.__eq__(self, actual)\n\n def _yield_comparisons(self, actual):\n return zip(actual, self.expected)\n\n def _check_type(self):\n __tracebackhide__ = True\n for index, x in enumerate(self.expected):\n if isinstance(x, type(self.expected)):\n msg = \"pytest.approx() does not support nested data structures: {!r} at index {}\\n full sequence: {}\"\n raise TypeError(msg.format(x, index, pprint.pformat(self.expected)))\n elif not isinstance(x, Number):\n raise _non_numeric_type_error(\n self.expected, at=\"index {}\".format(index)\n )"},{"col":4,"comment":"null","endLoc":202,"header":"def __repr__(self)","id":1755,"name":"__repr__","nodeType":"Function","startLoc":196,"text":"def __repr__(self):\n seq_type = type(self.expected)\n if seq_type not in (tuple, list, set):\n seq_type = list\n return \"approx({!r})\".format(\n seq_type(self._approx_scalar(x) for x in self.expected)\n )"},{"col":4,"comment":"null","endLoc":207,"header":"def __eq__(self, actual)","id":1756,"name":"__eq__","nodeType":"Function","startLoc":204,"text":"def __eq__(self, actual):\n if len(actual) != len(self.expected):\n return False\n return ApproxBase.__eq__(self, actual)"},{"col":4,"comment":"null","endLoc":210,"header":"def _yield_comparisons(self, actual)","id":1757,"name":"_yield_comparisons","nodeType":"Function","startLoc":209,"text":"def _yield_comparisons(self, actual):\n return zip(actual, self.expected)"},{"col":4,"comment":"#714","endLoc":572,"header":"def test_parametrize_indirect(self)","id":1758,"name":"test_parametrize_indirect","nodeType":"Function","startLoc":559,"text":"def test_parametrize_indirect(self):\n \"\"\"#714\"\"\"\n\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n metafunc.parametrize(\"x\", [1], indirect=True)\n metafunc.parametrize(\"y\", [2, 3], indirect=True)\n assert len(metafunc._calls) == 2\n assert metafunc._calls[0].funcargs == {}\n assert metafunc._calls[1].funcargs == {}\n assert metafunc._calls[0].params == dict(x=1, y=2)\n assert metafunc._calls[1].params == dict(x=1, y=3)"},{"col":4,"comment":"null","endLoc":635,"header":"def _getscopeitem(self, scope)","id":1759,"name":"_getscopeitem","nodeType":"Function","startLoc":621,"text":"def _getscopeitem(self, scope):\n if scope == \"function\":\n # this might also be a non-function Item despite its attribute name\n return self._pyfuncitem\n if scope == \"package\":\n node = get_scope_package(self._pyfuncitem, self._fixturedef)\n else:\n node = get_scope_node(self._pyfuncitem, scope)\n if node is None and scope == \"class\":\n # fallback to function item itself\n node = self._pyfuncitem\n assert node, 'Could not obtain a node for scope \"{}\" for function {!r}'.format(\n scope, self._pyfuncitem\n )\n return node"},{"col":0,"comment":"null","endLoc":104,"header":"def get_scope_package(node, fixturedef)","id":1760,"name":"get_scope_package","nodeType":"Function","startLoc":92,"text":"def get_scope_package(node, fixturedef):\n import pytest\n\n cls = pytest.Package\n current = node\n fixture_package_name = \"%s/%s\" % (fixturedef.baseid, \"__init__.py\")\n while current and (\n type(current) is not cls or fixture_package_name != current.nodeid\n ):\n current = current.parent\n if current is None:\n return node.session\n return current"},{"col":4,"comment":"null","endLoc":388,"header":"def _getnextfixturedef(self, argname)","id":1761,"name":"_getnextfixturedef","nodeType":"Function","startLoc":374,"text":"def _getnextfixturedef(self, argname):\n fixturedefs = self._arg2fixturedefs.get(argname, None)\n if fixturedefs is None:\n # we arrive here because of a dynamic call to\n # getfixturevalue(argname) usage which was naturally\n # not known at parsing/collection time\n parentid = self._pyfuncitem.parent.nodeid\n fixturedefs = self._fixturemanager.getfixturedefs(argname, parentid)\n self._arg2fixturedefs[argname] = fixturedefs\n # fixturedefs list is immutable so we maintain a decreasing index\n index = self._arg2index.get(argname, 0) - 1\n if fixturedefs is None or (-index > len(fixturedefs)):\n raise FixtureLookupError(argname, self)\n self._arg2index[argname] = index\n return fixturedefs[index]"},{"col":4,"comment":"null","endLoc":706,"header":"def __init__(self, argname, request, msg=None)","id":1762,"name":"__init__","nodeType":"Function","startLoc":702,"text":"def __init__(self, argname, request, msg=None):\n self.argname = argname\n self.request = request\n self.fixturestack = request._get_fixturestack()\n self.msg = msg"},{"col":4,"comment":" the pytest config object associated with this request. ","endLoc":393,"header":"@property\n def config(self)","id":1763,"name":"config","nodeType":"Function","startLoc":390,"text":"@property\n def config(self):\n \"\"\" the pytest config object associated with this request. \"\"\"\n return self._pyfuncitem.config"},{"col":4,"comment":" test function object if the request has a per-function scope. ","endLoc":398,"header":"@scopeproperty()\n def function(self)","id":1764,"name":"function","nodeType":"Function","startLoc":395,"text":"@scopeproperty()\n def function(self):\n \"\"\" test function object if the request has a per-function scope. \"\"\"\n return self._pyfuncitem.obj"},{"col":0,"comment":"null","endLoc":89,"header":"def scopeproperty(name=None, doc=None)","id":1765,"name":"scopeproperty","nodeType":"Function","startLoc":76,"text":"def scopeproperty(name=None, doc=None):\n def decoratescope(func):\n scopename = name or func.__name__\n\n def provide(self):\n if func.__name__ in scope2props[self.scope]:\n return func(self)\n raise AttributeError(\n \"%s not available in %s-scoped context\" % (scopename, self.scope)\n )\n\n return property(provide, None, None, func.__doc__)\n\n return decoratescope"},{"col":4,"comment":"#714","endLoc":583,"header":"def test_parametrize_indirect_list(self)","id":1766,"name":"test_parametrize_indirect_list","nodeType":"Function","startLoc":574,"text":"def test_parametrize_indirect_list(self):\n \"\"\"#714\"\"\"\n\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n metafunc.parametrize(\"x, y\", [(\"a\", \"b\")], indirect=[\"x\"])\n assert metafunc._calls[0].funcargs == dict(y=\"b\")\n assert metafunc._calls[0].params == dict(x=\"a\")"},{"col":4,"comment":" class (can be None) where the test function was collected. ","endLoc":405,"header":"@scopeproperty(\"class\")\n def cls(self)","id":1767,"name":"cls","nodeType":"Function","startLoc":400,"text":"@scopeproperty(\"class\")\n def cls(self):\n \"\"\" class (can be None) where the test function was collected. \"\"\"\n clscol = self._pyfuncitem.getparent(_pytest.python.Class)\n if clscol:\n return clscol.obj"},{"col":4,"comment":" instance (can be None) on which test function was collected. ","endLoc":415,"header":"@property\n def instance(self)","id":1768,"name":"instance","nodeType":"Function","startLoc":407,"text":"@property\n def instance(self):\n \"\"\" instance (can be None) on which test function was collected. \"\"\"\n # unittest support hack, see _pytest.unittest.TestCaseFunction\n try:\n return self._pyfuncitem._testcase\n except AttributeError:\n function = getattr(self, \"function\", None)\n return getattr(function, \"__self__\", None)"},{"col":4,"comment":" python module object where the test function was collected. ","endLoc":420,"header":"@scopeproperty()\n def module(self)","id":1769,"name":"module","nodeType":"Function","startLoc":417,"text":"@scopeproperty()\n def module(self):\n \"\"\" python module object where the test function was collected. \"\"\"\n return self._pyfuncitem.getparent(_pytest.python.Module).obj"},{"col":4,"comment":"null","endLoc":221,"header":"def _check_type(self)","id":1770,"name":"_check_type","nodeType":"Function","startLoc":212,"text":"def _check_type(self):\n __tracebackhide__ = True\n for index, x in enumerate(self.expected):\n if isinstance(x, type(self.expected)):\n msg = \"pytest.approx() does not support nested data structures: {!r} at index {}\\n full sequence: {}\"\n raise TypeError(msg.format(x, index, pprint.pformat(self.expected)))\n elif not isinstance(x, Number):\n raise _non_numeric_type_error(\n self.expected, at=\"index {}\".format(index)\n )"},{"col":4,"comment":" the file system path of the test module which collected this test. ","endLoc":425,"header":"@scopeproperty()\n def fspath(self)","id":1771,"name":"fspath","nodeType":"Function","startLoc":422,"text":"@scopeproperty()\n def fspath(self):\n \"\"\" the file system path of the test module which collected this test. \"\"\"\n return self._pyfuncitem.fspath"},{"col":4,"comment":" keywords/markers dictionary for the underlying node. ","endLoc":430,"header":"@property\n def keywords(self)","id":1772,"name":"keywords","nodeType":"Function","startLoc":427,"text":"@property\n def keywords(self):\n \"\"\" keywords/markers dictionary for the underlying node. \"\"\"\n return self.node.keywords"},{"col":4,"comment":" pytest session object. ","endLoc":435,"header":"@property\n def session(self)","id":1773,"name":"session","nodeType":"Function","startLoc":432,"text":"@property\n def session(self):\n \"\"\" pytest session object. \"\"\"\n return self._pyfuncitem.session"},{"col":4,"comment":" add finalizer/teardown function to be called after the\n last test within the requesting test context finished\n execution. ","endLoc":442,"header":"def addfinalizer(self, finalizer)","id":1774,"name":"addfinalizer","nodeType":"Function","startLoc":437,"text":"def addfinalizer(self, finalizer):\n \"\"\" add finalizer/teardown function to be called after the\n last test within the requesting test context finished\n execution. \"\"\"\n # XXX usually this method is shadowed by fixturedef specific ones\n self._addfinalizer(finalizer, scope=self.scope)"},{"col":4,"comment":"null","endLoc":448,"header":"def _addfinalizer(self, finalizer, scope)","id":1775,"name":"_addfinalizer","nodeType":"Function","startLoc":444,"text":"def _addfinalizer(self, finalizer, scope):\n colitem = self._getscopeitem(scope)\n self._pyfuncitem.session._setupstate.addfinalizer(\n finalizer=finalizer, colitem=colitem\n )"},{"col":4,"comment":" Apply a marker to a single test function invocation.\n This method is useful if you don't want to have a keyword/marker\n on all function invocations.\n\n :arg marker: a :py:class:`_pytest.mark.MarkDecorator` object\n created by a call to ``pytest.mark.NAME(...)``.\n ","endLoc":458,"header":"def applymarker(self, marker)","id":1776,"name":"applymarker","nodeType":"Function","startLoc":450,"text":"def applymarker(self, marker):\n \"\"\" Apply a marker to a single test function invocation.\n This method is useful if you don't want to have a keyword/marker\n on all function invocations.\n\n :arg marker: a :py:class:`_pytest.mark.MarkDecorator` object\n created by a call to ``pytest.mark.NAME(...)``.\n \"\"\"\n self.node.add_marker(marker)"},{"col":4,"comment":" raise a FixtureLookupError with the given message. ","endLoc":462,"header":"def raiseerror(self, msg)","id":1777,"name":"raiseerror","nodeType":"Function","startLoc":460,"text":"def raiseerror(self, msg):\n \"\"\" raise a FixtureLookupError with the given message. \"\"\"\n raise self._fixturemanager.FixtureLookupError(None, self, msg)"},{"col":4,"comment":"null","endLoc":469,"header":"def _fillfixtures(self)","id":1778,"name":"_fillfixtures","nodeType":"Function","startLoc":464,"text":"def _fillfixtures(self):\n item = self._pyfuncitem\n fixturenames = getattr(item, \"fixturenames\", self.fixturenames)\n for argname in fixturenames:\n if argname not in item.funcargs:\n item.funcargs[argname] = self.getfixturevalue(argname)"},{"className":"ApproxScalar","col":0,"comment":"\n Perform approximate comparisons where the expected value is a single number.\n ","endLoc":338,"id":1779,"nodeType":"Class","startLoc":224,"text":"class ApproxScalar(ApproxBase):\n \"\"\"\n Perform approximate comparisons where the expected value is a single number.\n \"\"\"\n\n DEFAULT_ABSOLUTE_TOLERANCE = 1e-12\n DEFAULT_RELATIVE_TOLERANCE = 1e-6\n\n def __repr__(self):\n \"\"\"\n Return a string communicating both the expected value and the tolerance\n for the comparison being made, e.g. '1.0 +- 1e-6'. Use the unicode\n plus/minus symbol if this is python3 (it's too hard to get right for\n python2).\n \"\"\"\n if isinstance(self.expected, complex):\n return str(self.expected)\n\n # Infinities aren't compared using tolerances, so don't show a\n # tolerance.\n if math.isinf(self.expected):\n return str(self.expected)\n\n # If a sensible tolerance can't be calculated, self.tolerance will\n # raise a ValueError. In this case, display '???'.\n try:\n vetted_tolerance = \"{:.1e}\".format(self.tolerance)\n except ValueError:\n vetted_tolerance = \"???\"\n\n if sys.version_info[0] == 2:\n return \"{} +- {}\".format(self.expected, vetted_tolerance)\n else:\n return u\"{} \\u00b1 {}\".format(self.expected, vetted_tolerance)\n\n def __eq__(self, actual):\n \"\"\"\n Return true if the given value is equal to the expected value within\n the pre-specified tolerance.\n \"\"\"\n if _is_numpy_array(actual):\n # Call ``__eq__()`` manually to prevent infinite-recursion with\n # numpy<1.13. See #3748.\n return all(self.__eq__(a) for a in actual.flat)\n\n # Short-circuit exact equality.\n if actual == self.expected:\n return True\n\n # Allow the user to control whether NaNs are considered equal to each\n # other or not. The abs() calls are for compatibility with complex\n # numbers.\n if math.isnan(abs(self.expected)):\n return self.nan_ok and math.isnan(abs(actual))\n\n # Infinity shouldn't be approximately equal to anything but itself, but\n # if there's a relative tolerance, it will be infinite and infinity\n # will seem approximately equal to everything. The equal-to-itself\n # case would have been short circuited above, so here we can just\n # return false if the expected value is infinite. The abs() call is\n # for compatibility with complex numbers.\n if math.isinf(abs(self.expected)):\n return False\n\n # Return true if the two numbers are within the tolerance.\n return abs(self.expected - actual) <= self.tolerance\n\n __hash__ = None\n\n @property\n def tolerance(self):\n \"\"\"\n Return the tolerance for the comparison. This could be either an\n absolute tolerance or a relative tolerance, depending on what the user\n specified or which would be larger.\n \"\"\"\n\n def set_default(x, default):\n return x if x is not None else default\n\n # Figure out what the absolute tolerance should be. ``self.abs`` is\n # either None or a value specified by the user.\n absolute_tolerance = set_default(self.abs, self.DEFAULT_ABSOLUTE_TOLERANCE)\n\n if absolute_tolerance < 0:\n raise ValueError(\n \"absolute tolerance can't be negative: {}\".format(absolute_tolerance)\n )\n if math.isnan(absolute_tolerance):\n raise ValueError(\"absolute tolerance can't be NaN.\")\n\n # If the user specified an absolute tolerance but not a relative one,\n # just return the absolute tolerance.\n if self.rel is None:\n if self.abs is not None:\n return absolute_tolerance\n\n # Figure out what the relative tolerance should be. ``self.rel`` is\n # either None or a value specified by the user. This is done after\n # we've made sure the user didn't ask for an absolute tolerance only,\n # because we don't want to raise errors about the relative tolerance if\n # we aren't even going to use it.\n relative_tolerance = set_default(\n self.rel, self.DEFAULT_RELATIVE_TOLERANCE\n ) * abs(self.expected)\n\n if relative_tolerance < 0:\n raise ValueError(\n \"relative tolerance can't be negative: {}\".format(absolute_tolerance)\n )\n if math.isnan(relative_tolerance):\n raise ValueError(\"relative tolerance can't be NaN.\")\n\n # Return the larger of the relative and absolute tolerances.\n return max(relative_tolerance, absolute_tolerance)"},{"col":4,"comment":"\n Return a string communicating both the expected value and the tolerance\n for the comparison being made, e.g. '1.0 +- 1e-6'. Use the unicode\n plus/minus symbol if this is python3 (it's too hard to get right for\n python2).\n ","endLoc":257,"header":"def __repr__(self)","id":1780,"name":"__repr__","nodeType":"Function","startLoc":232,"text":"def __repr__(self):\n \"\"\"\n Return a string communicating both the expected value and the tolerance\n for the comparison being made, e.g. '1.0 +- 1e-6'. Use the unicode\n plus/minus symbol if this is python3 (it's too hard to get right for\n python2).\n \"\"\"\n if isinstance(self.expected, complex):\n return str(self.expected)\n\n # Infinities aren't compared using tolerances, so don't show a\n # tolerance.\n if math.isinf(self.expected):\n return str(self.expected)\n\n # If a sensible tolerance can't be calculated, self.tolerance will\n # raise a ValueError. In this case, display '???'.\n try:\n vetted_tolerance = \"{:.1e}\".format(self.tolerance)\n except ValueError:\n vetted_tolerance = \"???\"\n\n if sys.version_info[0] == 2:\n return \"{} +- {}\".format(self.expected, vetted_tolerance)\n else:\n return u\"{} \\u00b1 {}\".format(self.expected, vetted_tolerance)"},{"col":4,"comment":"#714","endLoc":594,"header":"def test_parametrize_indirect_list_all(self)","id":1781,"name":"test_parametrize_indirect_list_all","nodeType":"Function","startLoc":585,"text":"def test_parametrize_indirect_list_all(self):\n \"\"\"#714\"\"\"\n\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n metafunc.parametrize(\"x, y\", [(\"a\", \"b\")], indirect=[\"x\", \"y\"])\n assert metafunc._calls[0].funcargs == {}\n assert metafunc._calls[0].params == dict(x=\"a\", y=\"b\")"},{"col":4,"comment":"#714","endLoc":605,"header":"def test_parametrize_indirect_list_empty(self)","id":1782,"name":"test_parametrize_indirect_list_empty","nodeType":"Function","startLoc":596,"text":"def test_parametrize_indirect_list_empty(self):\n \"\"\"#714\"\"\"\n\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n metafunc.parametrize(\"x, y\", [(\"a\", \"b\")], indirect=[])\n assert metafunc._calls[0].funcargs == dict(x=\"a\", y=\"b\")\n assert metafunc._calls[0].params == {}"},{"col":4,"comment":"\n #714\n Test parametrization with 'indirect' parameter applied on\n particular arguments. As y is is direct, its value should\n be used directly rather than being passed to the fixture\n y.\n\n :param testdir: the instance of Testdir class, a temporary\n test directory.\n ","endLoc":634,"header":"def test_parametrize_indirect_list_functional(self, testdir)","id":1783,"name":"test_parametrize_indirect_list_functional","nodeType":"Function","startLoc":607,"text":"def test_parametrize_indirect_list_functional(self, testdir):\n \"\"\"\n #714\n Test parametrization with 'indirect' parameter applied on\n particular arguments. As y is is direct, its value should\n be used directly rather than being passed to the fixture\n y.\n\n :param testdir: the instance of Testdir class, a temporary\n test directory.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope='function')\n def x(request):\n return request.param * 3\n @pytest.fixture(scope='function')\n def y(request):\n return request.param * 2\n @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x'])\n def test_simple(x,y):\n assert len(x) == 3\n assert len(y) == 1\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines([\"*test_simple*a-b*\", \"*1 passed*\"])"},{"col":4,"comment":"#714","endLoc":644,"header":"def test_parametrize_indirect_list_error(self, testdir)","id":1784,"name":"test_parametrize_indirect_list_error","nodeType":"Function","startLoc":636,"text":"def test_parametrize_indirect_list_error(self, testdir):\n \"\"\"#714\"\"\"\n\n def func(x, y):\n pass\n\n metafunc = self.Metafunc(func)\n with pytest.raises(pytest.fail.Exception):\n metafunc.parametrize(\"x, y\", [(\"a\", \"b\")], indirect=[\"x\", \"z\"])"},{"col":4,"comment":"The 'uses no fixture' error tells the user at collection time\n that the parametrize data they've set up doesn't correspond to the\n fixtures in their test function, rather than silently ignoring this\n and letting the test potentially pass.\n\n #714\n ","endLoc":664,"header":"def test_parametrize_uses_no_fixture_error_indirect_false(self, testdir)","id":1785,"name":"test_parametrize_uses_no_fixture_error_indirect_false","nodeType":"Function","startLoc":646,"text":"def test_parametrize_uses_no_fixture_error_indirect_false(self, testdir):\n \"\"\"The 'uses no fixture' error tells the user at collection time\n that the parametrize data they've set up doesn't correspond to the\n fixtures in their test function, rather than silently ignoring this\n and letting the test potentially pass.\n\n #714\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=False)\n def test_simple(x):\n assert len(x) == 3\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*uses no argument 'y'*\"])"},{"col":4,"comment":"#714","endLoc":684,"header":"def test_parametrize_uses_no_fixture_error_indirect_true(self, testdir)","id":1786,"name":"test_parametrize_uses_no_fixture_error_indirect_true","nodeType":"Function","startLoc":666,"text":"def test_parametrize_uses_no_fixture_error_indirect_true(self, testdir):\n \"\"\"#714\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope='function')\n def x(request):\n return request.param * 3\n @pytest.fixture(scope='function')\n def y(request):\n return request.param * 2\n\n @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=True)\n def test_simple(x):\n assert len(x) == 3\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*uses no fixture 'y'*\"])"},{"col":4,"comment":"#714","endLoc":701,"header":"def test_parametrize_indirect_uses_no_fixture_error_indirect_string(self, testdir)","id":1787,"name":"test_parametrize_indirect_uses_no_fixture_error_indirect_string","nodeType":"Function","startLoc":686,"text":"def test_parametrize_indirect_uses_no_fixture_error_indirect_string(self, testdir):\n \"\"\"#714\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope='function')\n def x(request):\n return request.param * 3\n\n @pytest.mark.parametrize('x, y', [('a', 'b')], indirect='y')\n def test_simple(x):\n assert len(x) == 3\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*uses no fixture 'y'*\"])"},{"col":4,"comment":"#714","endLoc":718,"header":"def test_parametrize_indirect_uses_no_fixture_error_indirect_list(self, testdir)","id":1788,"name":"test_parametrize_indirect_uses_no_fixture_error_indirect_list","nodeType":"Function","startLoc":703,"text":"def test_parametrize_indirect_uses_no_fixture_error_indirect_list(self, testdir):\n \"\"\"#714\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope='function')\n def x(request):\n return request.param * 3\n\n @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['y'])\n def test_simple(x):\n assert len(x) == 3\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*uses no fixture 'y'*\"])"},{"col":4,"comment":"#714","endLoc":735,"header":"def test_parametrize_argument_not_in_indirect_list(self, testdir)","id":1789,"name":"test_parametrize_argument_not_in_indirect_list","nodeType":"Function","startLoc":720,"text":"def test_parametrize_argument_not_in_indirect_list(self, testdir):\n \"\"\"#714\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope='function')\n def x(request):\n return request.param * 3\n\n @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x'])\n def test_simple(x):\n assert len(x) == 3\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*uses no argument 'y'*\"])"},{"col":4,"comment":"null","endLoc":752,"header":"def test_parametrize_gives_indicative_error_on_function_with_default_argument(\n self, testdir\n )","id":1790,"name":"test_parametrize_gives_indicative_error_on_function_with_default_argument","nodeType":"Function","startLoc":737,"text":"def test_parametrize_gives_indicative_error_on_function_with_default_argument(\n self, testdir\n ):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize('x, y', [('a', 'b')])\n def test_simple(x, y=1):\n assert len(x) == 1\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines(\n [\"*already takes an argument 'y' with a default value\"]\n )"},{"col":4,"comment":"null","endLoc":773,"header":"def test_parametrize_functional(self, testdir)","id":1792,"name":"test_parametrize_functional","nodeType":"Function","startLoc":754,"text":"def test_parametrize_functional(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('x', [1,2], indirect=True)\n metafunc.parametrize('y', [2])\n @pytest.fixture\n def x(request):\n return request.param * 10\n\n def test_simple(x,y):\n assert x in (10,20)\n assert y == 2\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n [\"*test_simple*1-2*\", \"*test_simple*2-2*\", \"*2 passed*\"]\n )"},{"col":4,"comment":"null","endLoc":782,"header":"def test_parametrize_onearg(self)","id":1793,"name":"test_parametrize_onearg","nodeType":"Function","startLoc":775,"text":"def test_parametrize_onearg(self):\n metafunc = self.Metafunc(lambda x: None)\n metafunc.parametrize(\"x\", [1, 2])\n assert len(metafunc._calls) == 2\n assert metafunc._calls[0].funcargs == dict(x=1)\n assert metafunc._calls[0].id == \"1\"\n assert metafunc._calls[1].funcargs == dict(x=2)\n assert metafunc._calls[1].id == \"2\""},{"col":33,"endLoc":776,"id":1794,"nodeType":"Lambda","startLoc":776,"text":"lambda x: None"},{"col":0,"comment":"context manager that can be used to ensure a block of code triggers a\n ``DeprecationWarning`` or ``PendingDeprecationWarning``::\n\n >>> import warnings\n >>> def api_call_v2():\n ... warnings.warn('use v3 of this api', DeprecationWarning)\n ... return 200\n\n >>> with deprecated_call():\n ... assert api_call_v2() == 200\n\n ``deprecated_call`` can also be used by passing a function and ``*args`` and ``*kwargs``,\n in which case it will ensure calling ``func(*args, **kwargs)`` produces one of the warnings\n types above.\n ","endLoc":53,"header":"def deprecated_call(func=None, *args, **kwargs)","id":1795,"name":"deprecated_call","nodeType":"Function","startLoc":34,"text":"def deprecated_call(func=None, *args, **kwargs):\n \"\"\"context manager that can be used to ensure a block of code triggers a\n ``DeprecationWarning`` or ``PendingDeprecationWarning``::\n\n >>> import warnings\n >>> def api_call_v2():\n ... warnings.warn('use v3 of this api', DeprecationWarning)\n ... return 200\n\n >>> with deprecated_call():\n ... assert api_call_v2() == 200\n\n ``deprecated_call`` can also be used by passing a function and ``*args`` and ``*kwargs``,\n in which case it will ensure calling ``func(*args, **kwargs)`` produces one of the warnings\n types above.\n \"\"\"\n __tracebackhide__ = True\n if func is not None:\n args = (func,) + args\n return warns((DeprecationWarning, PendingDeprecationWarning), *args, **kwargs)"},{"col":0,"comment":"null","endLoc":14,"header":"def exists(path, ignore=EnvironmentError)","id":1796,"name":"exists","nodeType":"Function","startLoc":10,"text":"def exists(path, ignore=EnvironmentError):\n try:\n return path.check()\n except ignore:\n return False"},{"col":0,"comment":"Assert that code raises a particular class of warning.\n\n Specifically, the parameter ``expected_warning`` can be a warning class or\n sequence of warning classes, and the inside the ``with`` block must issue a warning of that class or\n classes.\n\n This helper produces a list of :class:`warnings.WarningMessage` objects,\n one for each warning raised.\n\n This function can be used as a context manager, or any of the other ways\n ``pytest.raises`` can be used::\n\n >>> with warns(RuntimeWarning):\n ... warnings.warn(\"my warning\", RuntimeWarning)\n\n In the context manager form you may use the keyword argument ``match`` to assert\n that the exception matches a text or regex::\n\n >>> with warns(UserWarning, match='must be 0 or None'):\n ... warnings.warn(\"value must be 0 or None\", UserWarning)\n\n >>> with warns(UserWarning, match=r'must be \\d+$'):\n ... warnings.warn(\"value must be 42\", UserWarning)\n\n >>> with warns(UserWarning, match=r'must be \\d+$'):\n ... warnings.warn(\"this is not here\", UserWarning)\n Traceback (most recent call last):\n ...\n Failed: DID NOT WARN. No warnings of type ...UserWarning... was emitted...\n\n ","endLoc":110,"header":"def warns(expected_warning, *args, **kwargs)","id":1797,"name":"warns","nodeType":"Function","startLoc":56,"text":"def warns(expected_warning, *args, **kwargs):\n r\"\"\"Assert that code raises a particular class of warning.\n\n Specifically, the parameter ``expected_warning`` can be a warning class or\n sequence of warning classes, and the inside the ``with`` block must issue a warning of that class or\n classes.\n\n This helper produces a list of :class:`warnings.WarningMessage` objects,\n one for each warning raised.\n\n This function can be used as a context manager, or any of the other ways\n ``pytest.raises`` can be used::\n\n >>> with warns(RuntimeWarning):\n ... warnings.warn(\"my warning\", RuntimeWarning)\n\n In the context manager form you may use the keyword argument ``match`` to assert\n that the exception matches a text or regex::\n\n >>> with warns(UserWarning, match='must be 0 or None'):\n ... warnings.warn(\"value must be 0 or None\", UserWarning)\n\n >>> with warns(UserWarning, match=r'must be \\d+$'):\n ... warnings.warn(\"value must be 42\", UserWarning)\n\n >>> with warns(UserWarning, match=r'must be \\d+$'):\n ... warnings.warn(\"this is not here\", UserWarning)\n Traceback (most recent call last):\n ...\n Failed: DID NOT WARN. No warnings of type ...UserWarning... was emitted...\n\n \"\"\"\n __tracebackhide__ = True\n if not args:\n match_expr = kwargs.pop(\"match\", None)\n if kwargs:\n warnings.warn(\n PYTEST_WARNS_UNKNOWN_KWARGS.format(args=sorted(kwargs)), stacklevel=2\n )\n return WarningsChecker(expected_warning, match_expr=match_expr)\n elif isinstance(args[0], str):\n warnings.warn(WARNS_EXEC, stacklevel=2)\n code, = args\n assert isinstance(code, str)\n frame = sys._getframe(1)\n loc = frame.f_locals.copy()\n loc.update(kwargs)\n\n with WarningsChecker(expected_warning):\n code = _pytest._code.Source(code).compile()\n exec(code, frame.f_globals, loc)\n else:\n func = args[0]\n with WarningsChecker(expected_warning):\n return func(*args[1:], **kwargs)"},{"col":4,"comment":"null","endLoc":394,"header":"def _try_load_conftest(self, anchor)","id":1798,"name":"_try_load_conftest","nodeType":"Function","startLoc":388,"text":"def _try_load_conftest(self, anchor):\n self._getconftestmodules(anchor)\n # let's also consider test* subdirs\n if anchor.check(dir=1):\n for x in anchor.listdir(\"test*\"):\n if x.check(dir=1):\n self._getconftestmodules(x)"},{"col":4,"comment":"null","endLoc":427,"header":"@lru_cache(maxsize=128)\n def _getconftestmodules(self, path)","id":1799,"name":"_getconftestmodules","nodeType":"Function","startLoc":396,"text":"@lru_cache(maxsize=128)\n def _getconftestmodules(self, path):\n if self._noconftest:\n return []\n\n if path.isfile():\n directory = path.dirpath()\n else:\n directory = path\n\n if six.PY2: # py2 is not using lru_cache.\n try:\n return self._dirpath2confmods[directory]\n except KeyError:\n pass\n\n # XXX these days we may rather want to use config.rootdir\n # and allow users to opt into looking into the rootdir parent\n # directories instead of requiring to specify confcutdir\n clist = []\n for parent in directory.realpath().parts():\n if self._confcutdir and self._confcutdir.relto(parent):\n continue\n conftestpath = parent.join(\"conftest.py\")\n if conftestpath.isfile():\n # Use realpath to avoid loading the same conftest twice\n # with build systems that create build directories containing\n # symlinks to actual files.\n mod = self._importconftest(conftestpath.realpath())\n clist.append(mod)\n self._dirpath2confmods[directory] = clist\n return clist"},{"col":4,"comment":"\n Return true if the given value is equal to the expected value within\n the pre-specified tolerance.\n ","endLoc":289,"header":"def __eq__(self, actual)","id":1800,"name":"__eq__","nodeType":"Function","startLoc":259,"text":"def __eq__(self, actual):\n \"\"\"\n Return true if the given value is equal to the expected value within\n the pre-specified tolerance.\n \"\"\"\n if _is_numpy_array(actual):\n # Call ``__eq__()`` manually to prevent infinite-recursion with\n # numpy<1.13. See #3748.\n return all(self.__eq__(a) for a in actual.flat)\n\n # Short-circuit exact equality.\n if actual == self.expected:\n return True\n\n # Allow the user to control whether NaNs are considered equal to each\n # other or not. The abs() calls are for compatibility with complex\n # numbers.\n if math.isnan(abs(self.expected)):\n return self.nan_ok and math.isnan(abs(actual))\n\n # Infinity shouldn't be approximately equal to anything but itself, but\n # if there's a relative tolerance, it will be infinite and infinity\n # will seem approximately equal to everything. The equal-to-itself\n # case would have been short circuited above, so here we can just\n # return false if the expected value is infinite. The abs() call is\n # for compatibility with complex numbers.\n if math.isinf(abs(self.expected)):\n return False\n\n # Return true if the two numbers are within the tolerance.\n return abs(self.expected - actual) <= self.tolerance"},{"col":4,"comment":"null","endLoc":219,"header":"def __init__(self, expected_warning=None, match_expr=None)","id":1801,"name":"__init__","nodeType":"Function","startLoc":205,"text":"def __init__(self, expected_warning=None, match_expr=None):\n super(WarningsChecker, self).__init__()\n\n msg = \"exceptions must be old-style classes or derived from Warning, not %s\"\n if isinstance(expected_warning, tuple):\n for exc in expected_warning:\n if not inspect.isclass(exc):\n raise TypeError(msg % type(exc))\n elif inspect.isclass(expected_warning):\n expected_warning = (expected_warning,)\n elif expected_warning is not None:\n raise TypeError(msg % type(expected_warning))\n\n self.expected_warning = expected_warning\n self.match_expr = match_expr"},{"col":4,"comment":"null","endLoc":453,"header":"def lru_cache(*_, **__)","id":1802,"name":"lru_cache","nodeType":"Function","startLoc":449,"text":"def lru_cache(*_, **__):\n def dec(fn):\n return fn\n\n return dec"},{"col":0,"comment":"null","endLoc":67,"header":"@overload\ndef lru_cache(maxsize: int | None = 128, typed: bool = False) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]","id":1803,"name":"lru_cache","nodeType":"Function","startLoc":66,"text":"@overload\ndef lru_cache(maxsize: int | None = 128, typed: bool = False) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]: ..."},{"col":4,"comment":"null","endLoc":122,"header":"def __init__(self)","id":1804,"name":"__init__","nodeType":"Function","startLoc":119,"text":"def __init__(self):\n super(WarningsRecorder, self).__init__(record=True)\n self._entered = False\n self._list = []"},{"col":4,"comment":"null","endLoc":790,"header":"def test_parametrize_onearg_indirect(self)","id":1805,"name":"test_parametrize_onearg_indirect","nodeType":"Function","startLoc":784,"text":"def test_parametrize_onearg_indirect(self):\n metafunc = self.Metafunc(lambda x: None)\n metafunc.parametrize(\"x\", [1, 2], indirect=True)\n assert metafunc._calls[0].params == dict(x=1)\n assert metafunc._calls[0].id == \"1\"\n assert metafunc._calls[1].params == dict(x=2)\n assert metafunc._calls[1].id == \"2\""},{"col":33,"endLoc":785,"id":1806,"nodeType":"Lambda","startLoc":785,"text":"lambda x: None"},{"col":0,"comment":"null","endLoc":69,"header":"@overload\ndef lru_cache(maxsize: Callable[..., _T], typed: bool = False) -> _lru_cache_wrapper[_T]","id":1807,"name":"lru_cache","nodeType":"Function","startLoc":68,"text":"@overload\ndef lru_cache(maxsize: Callable[..., _T], typed: bool = False) -> _lru_cache_wrapper[_T]: ..."},{"col":4,"comment":"null","endLoc":475,"header":"def _importconftest(self, conftestpath)","id":1808,"name":"_importconftest","nodeType":"Function","startLoc":438,"text":"def _importconftest(self, conftestpath):\n try:\n return self._conftestpath2mod[conftestpath]\n except KeyError:\n pkgpath = conftestpath.pypkgpath()\n if pkgpath is None:\n _ensure_removed_sysmodule(conftestpath.purebasename)\n try:\n mod = conftestpath.pyimport()\n if (\n hasattr(mod, \"pytest_plugins\")\n and self._configured\n and not self._using_pyargs\n ):\n from _pytest.deprecated import (\n PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST,\n )\n\n fail(\n PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST.format(\n conftestpath, self._confcutdir\n ),\n pytrace=False,\n )\n except Exception:\n raise ConftestImportFailure(conftestpath, sys.exc_info())\n\n self._conftest_plugins.add(mod)\n self._conftestpath2mod[conftestpath] = mod\n dirpath = conftestpath.dirpath()\n if dirpath in self._dirpath2confmods:\n for path, mods in self._dirpath2confmods.items():\n if path and path.relto(dirpath) or path == dirpath:\n assert mod not in mods\n mods.append(mod)\n self.trace(\"loaded conftestmodule %r\" % (mod))\n self.consider_conftest(mod)\n return mod"},{"col":0,"comment":"null","endLoc":613,"header":"def _ensure_removed_sysmodule(modname)","id":1809,"name":"_ensure_removed_sysmodule","nodeType":"Function","startLoc":609,"text":"def _ensure_removed_sysmodule(modname):\n try:\n del sys.modules[modname]\n except KeyError:\n pass"},{"col":4,"comment":"null","endLoc":48,"header":"def __init__(self, path, excinfo)","id":1810,"name":"__init__","nodeType":"Function","startLoc":45,"text":"def __init__(self, path, excinfo):\n Exception.__init__(self, path, excinfo)\n self.path = path\n self.excinfo = excinfo"},{"col":4,"comment":"null","endLoc":527,"header":"def consider_conftest(self, conftestmodule)","id":1811,"name":"consider_conftest","nodeType":"Function","startLoc":526,"text":"def consider_conftest(self, conftestmodule):\n self.register(conftestmodule, name=conftestmodule.__file__)"},{"col":4,"comment":"null","endLoc":436,"header":"def _rget_with_confmod(self, name, path)","id":1812,"name":"_rget_with_confmod","nodeType":"Function","startLoc":429,"text":"def _rget_with_confmod(self, name, path):\n modules = self._getconftestmodules(path)\n for mod in reversed(modules):\n try:\n return mod, getattr(mod, name)\n except AttributeError:\n continue\n raise KeyError(name)"},{"col":0,"comment":"Add extra xml attributes to the tag for the calling test.\n The fixture is callable with ``(name, value)``, with value being\n automatically xml-encoded\n ","endLoc":349,"header":"@pytest.fixture\ndef record_xml_attribute(request)","id":1813,"name":"record_xml_attribute","nodeType":"Function","startLoc":324,"text":"@pytest.fixture\ndef record_xml_attribute(request):\n \"\"\"Add extra xml attributes to the tag for the calling test.\n The fixture is callable with ``(name, value)``, with value being\n automatically xml-encoded\n \"\"\"\n from _pytest.warning_types import PytestExperimentalApiWarning\n\n request.node.warn(\n PytestExperimentalApiWarning(\"record_xml_attribute is an experimental feature\")\n )\n\n _warn_incompatibility_with_xunit2(request, \"record_xml_attribute\")\n\n # Declare noop\n def add_attr_noop(name, value):\n pass\n\n attr_func = add_attr_noop\n\n xml = getattr(request.config, \"_xml\", None)\n if xml is not None:\n node_reporter = xml.node_reporter(request.node.nodeid)\n attr_func = node_reporter.add_attribute\n\n return attr_func"},{"fileName":"fixtures.py","filePath":"testing/python","id":1814,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport sys\nimport textwrap\n\nimport pytest\nfrom _pytest import fixtures\nfrom _pytest.fixtures import FixtureLookupError\nfrom _pytest.fixtures import FixtureRequest\nfrom _pytest.pathlib import Path\nfrom _pytest.pytester import get_public_names\nfrom _pytest.warnings import SHOW_PYTEST_WARNINGS_ARG\n\n\ndef test_getfuncargnames():\n def f():\n pass\n\n assert not fixtures.getfuncargnames(f)\n\n def g(arg):\n pass\n\n assert fixtures.getfuncargnames(g) == (\"arg\",)\n\n def h(arg1, arg2=\"hello\"):\n pass\n\n assert fixtures.getfuncargnames(h) == (\"arg1\",)\n\n def h(arg1, arg2, arg3=\"hello\"):\n pass\n\n assert fixtures.getfuncargnames(h) == (\"arg1\", \"arg2\")\n\n class A(object):\n def f(self, arg1, arg2=\"hello\"):\n pass\n\n @staticmethod\n def static(arg1, arg2):\n pass\n\n assert fixtures.getfuncargnames(A().f) == (\"arg1\",)\n assert fixtures.getfuncargnames(A.static, cls=A) == (\"arg1\", \"arg2\")\n\n\n@pytest.mark.pytester_example_path(\"fixtures/fill_fixtures\")\nclass TestFillFixtures(object):\n def test_fillfuncargs_exposed(self):\n # used by oejskit, kept for compatibility\n assert pytest._fillfuncargs == fixtures.fillfixtures\n\n def test_funcarg_lookupfails(self, testdir):\n testdir.copy_example()\n result = testdir.runpytest() # \"--collect-only\")\n assert result.ret != 0\n result.stdout.fnmatch_lines(\n \"\"\"\n *def test_func(some)*\n *fixture*some*not found*\n *xyzsomething*\n \"\"\"\n )\n\n def test_detect_recursive_dependency_error(self, testdir):\n testdir.copy_example()\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"*recursive dependency involving fixture 'fix1' detected*\"]\n )\n\n def test_funcarg_basic(self, testdir):\n testdir.copy_example()\n item = testdir.getitem(Path(\"test_funcarg_basic.py\"))\n fixtures.fillfixtures(item)\n del item.funcargs[\"request\"]\n assert len(get_public_names(item.funcargs)) == 2\n assert item.funcargs[\"some\"] == \"test_func\"\n assert item.funcargs[\"other\"] == 42\n\n def test_funcarg_lookup_modulelevel(self, testdir):\n testdir.copy_example()\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_funcarg_lookup_classlevel(self, testdir):\n p = testdir.copy_example()\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_conftest_funcargs_only_available_in_subdir(self, testdir):\n testdir.copy_example()\n result = testdir.runpytest(\"-v\")\n result.assert_outcomes(passed=2)\n\n def test_extend_fixture_module_class(self, testdir):\n testfile = testdir.copy_example()\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest(testfile)\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_extend_fixture_conftest_module(self, testdir):\n p = testdir.copy_example()\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest(next(p.visit(\"test_*.py\")))\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_extend_fixture_conftest_conftest(self, testdir):\n p = testdir.copy_example()\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest(next(p.visit(\"test_*.py\")))\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_extend_fixture_conftest_plugin(self, testdir):\n testdir.makepyfile(\n testplugin=\"\"\"\n import pytest\n\n @pytest.fixture\n def foo():\n return 7\n \"\"\"\n )\n testdir.syspathinsert()\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n pytest_plugins = 'testplugin'\n\n @pytest.fixture\n def foo(foo):\n return foo + 7\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_foo(foo):\n assert foo == 14\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n assert result.ret == 0\n\n def test_extend_fixture_plugin_plugin(self, testdir):\n # Two plugins should extend each order in loading order\n testdir.makepyfile(\n testplugin0=\"\"\"\n import pytest\n\n @pytest.fixture\n def foo():\n return 7\n \"\"\"\n )\n testdir.makepyfile(\n testplugin1=\"\"\"\n import pytest\n\n @pytest.fixture\n def foo(foo):\n return foo + 7\n \"\"\"\n )\n testdir.syspathinsert()\n testdir.makepyfile(\n \"\"\"\n pytest_plugins = ['testplugin0', 'testplugin1']\n\n def test_foo(foo):\n assert foo == 14\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0\n\n def test_override_parametrized_fixture_conftest_module(self, testdir):\n \"\"\"Test override of the parametrized fixture with non-parametrized one on the test module level.\"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[1, 2, 3])\n def spam(request):\n return request.param\n \"\"\"\n )\n testfile = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def spam():\n return 'spam'\n\n def test_spam(spam):\n assert spam == 'spam'\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest(testfile)\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_override_parametrized_fixture_conftest_conftest(self, testdir):\n \"\"\"Test override of the parametrized fixture with non-parametrized one on the conftest level.\"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[1, 2, 3])\n def spam(request):\n return request.param\n \"\"\"\n )\n subdir = testdir.mkpydir(\"subdir\")\n subdir.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n\n @pytest.fixture\n def spam():\n return 'spam'\n \"\"\"\n )\n )\n testfile = subdir.join(\"test_spam.py\")\n testfile.write(\n textwrap.dedent(\n \"\"\"\\\n def test_spam(spam):\n assert spam == \"spam\"\n \"\"\"\n )\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest(testfile)\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_override_non_parametrized_fixture_conftest_module(self, testdir):\n \"\"\"Test override of the non-parametrized fixture with parametrized one on the test module level.\"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def spam():\n return 'spam'\n \"\"\"\n )\n testfile = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[1, 2, 3])\n def spam(request):\n return request.param\n\n params = {'spam': 1}\n\n def test_spam(spam):\n assert spam == params['spam']\n params['spam'] += 1\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n result = testdir.runpytest(testfile)\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n\n def test_override_non_parametrized_fixture_conftest_conftest(self, testdir):\n \"\"\"Test override of the non-parametrized fixture with parametrized one on the conftest level.\"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def spam():\n return 'spam'\n \"\"\"\n )\n subdir = testdir.mkpydir(\"subdir\")\n subdir.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n\n @pytest.fixture(params=[1, 2, 3])\n def spam(request):\n return request.param\n \"\"\"\n )\n )\n testfile = subdir.join(\"test_spam.py\")\n testfile.write(\n textwrap.dedent(\n \"\"\"\\\n params = {'spam': 1}\n\n def test_spam(spam):\n assert spam == params['spam']\n params['spam'] += 1\n \"\"\"\n )\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n result = testdir.runpytest(testfile)\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n\n def test_override_autouse_fixture_with_parametrized_fixture_conftest_conftest(\n self, testdir\n ):\n \"\"\"Test override of the autouse fixture with parametrized one on the conftest level.\n This test covers the issue explained in issue 1601\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(autouse=True)\n def spam():\n return 'spam'\n \"\"\"\n )\n subdir = testdir.mkpydir(\"subdir\")\n subdir.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n\n @pytest.fixture(params=[1, 2, 3])\n def spam(request):\n return request.param\n \"\"\"\n )\n )\n testfile = subdir.join(\"test_spam.py\")\n testfile.write(\n textwrap.dedent(\n \"\"\"\\\n params = {'spam': 1}\n\n def test_spam(spam):\n assert spam == params['spam']\n params['spam'] += 1\n \"\"\"\n )\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n result = testdir.runpytest(testfile)\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n\n def test_autouse_fixture_plugin(self, testdir):\n # A fixture from a plugin has no baseid set, which screwed up\n # the autouse fixture handling.\n testdir.makepyfile(\n testplugin=\"\"\"\n import pytest\n\n @pytest.fixture(autouse=True)\n def foo(request):\n request.function.foo = 7\n \"\"\"\n )\n testdir.syspathinsert()\n testdir.makepyfile(\n \"\"\"\n pytest_plugins = 'testplugin'\n\n def test_foo(request):\n assert request.function.foo == 7\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0\n\n def test_funcarg_lookup_error(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def a_fixture(): pass\n\n @pytest.fixture\n def b_fixture(): pass\n\n @pytest.fixture\n def c_fixture(): pass\n\n @pytest.fixture\n def d_fixture(): pass\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_lookup_error(unknown):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*ERROR at setup of test_lookup_error*\",\n \" def test_lookup_error(unknown):*\",\n \"E fixture 'unknown' not found\",\n \"> available fixtures:*a_fixture,*b_fixture,*c_fixture,*d_fixture*monkeypatch,*\", # sorted\n \"> use 'py*test --fixtures *' for help on them.\",\n \"*1 error*\",\n ]\n )\n assert \"INTERNAL\" not in result.stdout.str()\n\n def test_fixture_excinfo_leak(self, testdir):\n # on python2 sys.excinfo would leak into fixture executions\n testdir.makepyfile(\n \"\"\"\n import sys\n import traceback\n import pytest\n\n @pytest.fixture\n def leak():\n if sys.exc_info()[0]: # python3 bug :)\n traceback.print_exc()\n #fails\n assert sys.exc_info() == (None, None, None)\n\n def test_leak(leak):\n if sys.exc_info()[0]: # python3 bug :)\n traceback.print_exc()\n assert sys.exc_info() == (None, None, None)\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0\n\n\nclass TestRequestBasic(object):\n def test_request_attributes(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def something(request): pass\n def test_func(something): pass\n \"\"\"\n )\n req = fixtures.FixtureRequest(item)\n assert req.function == item.obj\n assert req.keywords == item.keywords\n assert hasattr(req.module, \"test_func\")\n assert req.cls is None\n assert req.function.__name__ == \"test_func\"\n assert req.config == item.config\n assert repr(req).find(req.function.__name__) != -1\n\n def test_request_attributes_method(self, testdir):\n item, = testdir.getitems(\n \"\"\"\n import pytest\n class TestB(object):\n\n @pytest.fixture\n def something(self, request):\n return 1\n def test_func(self, something):\n pass\n \"\"\"\n )\n req = item._request\n assert req.cls.__name__ == \"TestB\"\n assert req.instance.__class__ == req.cls\n\n def test_request_contains_funcarg_arg2fixturedefs(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n import pytest\n @pytest.fixture\n def something(request):\n pass\n class TestClass(object):\n def test_method(self, something):\n pass\n \"\"\"\n )\n item1, = testdir.genitems([modcol])\n assert item1.name == \"test_method\"\n arg2fixturedefs = fixtures.FixtureRequest(item1)._arg2fixturedefs\n assert len(arg2fixturedefs) == 1\n assert arg2fixturedefs[\"something\"][0].argname == \"something\"\n\n @pytest.mark.skipif(\n hasattr(sys, \"pypy_version_info\"),\n reason=\"this method of test doesn't work on pypy\",\n )\n def test_request_garbage(self, testdir):\n try:\n import xdist # noqa\n except ImportError:\n pass\n else:\n pytest.xfail(\"this test is flaky when executed with xdist\")\n testdir.makepyfile(\n \"\"\"\n import sys\n import pytest\n from _pytest.fixtures import PseudoFixtureDef\n import gc\n\n @pytest.fixture(autouse=True)\n def something(request):\n original = gc.get_debug()\n gc.set_debug(gc.DEBUG_SAVEALL)\n gc.collect()\n\n yield\n\n try:\n gc.collect()\n leaked = [x for _ in gc.garbage if isinstance(_, PseudoFixtureDef)]\n assert leaked == []\n finally:\n gc.set_debug(original)\n\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"* 1 passed in *\"])\n\n def test_getfixturevalue_recursive(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def something(request):\n return 1\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def something(request):\n return request.getfixturevalue(\"something\") + 1\n def test_func(something):\n assert something == 2\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_getfixturevalue_teardown(self, testdir):\n \"\"\"\n Issue #1895\n\n `test_inner` requests `inner` fixture, which in turn requests `resource`\n using `getfixturevalue`. `test_func` then requests `resource`.\n\n `resource` is teardown before `inner` because the fixture mechanism won't consider\n `inner` dependent on `resource` when it is used via `getfixturevalue`: `test_func`\n will then cause the `resource`'s finalizer to be called first because of this.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='session')\n def resource():\n r = ['value']\n yield r\n r.pop()\n\n @pytest.fixture(scope='session')\n def inner(request):\n resource = request.getfixturevalue('resource')\n assert resource == ['value']\n yield\n assert resource == ['value']\n\n def test_inner(inner):\n pass\n\n def test_func(resource):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed in *\"])\n\n @pytest.mark.parametrize(\"getfixmethod\", (\"getfixturevalue\", \"getfuncargvalue\"))\n def test_getfixturevalue(self, testdir, getfixmethod):\n item = testdir.getitem(\n \"\"\"\n import pytest\n values = [2]\n @pytest.fixture\n def something(request): return 1\n @pytest.fixture\n def other(request):\n return values.pop()\n def test_func(something): pass\n \"\"\"\n )\n import contextlib\n\n if getfixmethod == \"getfuncargvalue\":\n warning_expectation = pytest.warns(DeprecationWarning)\n else:\n # see #1830 for a cleaner way to accomplish this\n @contextlib.contextmanager\n def expecting_no_warning():\n yield\n\n warning_expectation = expecting_no_warning()\n\n req = item._request\n with warning_expectation:\n fixture_fetcher = getattr(req, getfixmethod)\n with pytest.raises(FixtureLookupError):\n fixture_fetcher(\"notexists\")\n val = fixture_fetcher(\"something\")\n assert val == 1\n val = fixture_fetcher(\"something\")\n assert val == 1\n val2 = fixture_fetcher(\"other\")\n assert val2 == 2\n val2 = fixture_fetcher(\"other\") # see about caching\n assert val2 == 2\n pytest._fillfuncargs(item)\n assert item.funcargs[\"something\"] == 1\n assert len(get_public_names(item.funcargs)) == 2\n assert \"request\" in item.funcargs\n\n def test_request_addfinalizer(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n teardownlist = []\n @pytest.fixture\n def something(request):\n request.addfinalizer(lambda: teardownlist.append(1))\n def test_func(something): pass\n \"\"\"\n )\n item.session._setupstate.prepare(item)\n pytest._fillfuncargs(item)\n # successively check finalization calls\n teardownlist = item.getparent(pytest.Module).obj.teardownlist\n ss = item.session._setupstate\n assert not teardownlist\n ss.teardown_exact(item, None)\n print(ss.stack)\n assert teardownlist == [1]\n\n def test_request_addfinalizer_failing_setup(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = [1]\n @pytest.fixture\n def myfix(request):\n request.addfinalizer(values.pop)\n assert 0\n def test_fix(myfix):\n pass\n def test_finalizer_ran():\n assert not values\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(failed=1, passed=1)\n\n def test_request_addfinalizer_failing_setup_module(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = [1, 2]\n @pytest.fixture(scope=\"module\")\n def myfix(request):\n request.addfinalizer(values.pop)\n request.addfinalizer(values.pop)\n assert 0\n def test_fix(myfix):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n mod = reprec.getcalls(\"pytest_runtest_setup\")[0].item.module\n assert not mod.values\n\n def test_request_addfinalizer_partial_setup_failure(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture\n def something(request):\n request.addfinalizer(lambda: values.append(None))\n def test_func(something, missingarg):\n pass\n def test_second():\n assert len(values) == 1\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\"*1 error*\"] # XXX the whole module collection fails\n )\n\n def test_request_subrequest_addfinalizer_exceptions(self, testdir):\n \"\"\"\n Ensure exceptions raised during teardown by a finalizer are suppressed\n until all finalizers are called, re-raising the first exception (#2440)\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n def _excepts(where):\n raise Exception('Error in %s fixture' % where)\n @pytest.fixture\n def subrequest(request):\n return request\n @pytest.fixture\n def something(subrequest):\n subrequest.addfinalizer(lambda: values.append(1))\n subrequest.addfinalizer(lambda: values.append(2))\n subrequest.addfinalizer(lambda: _excepts('something'))\n @pytest.fixture\n def excepts(subrequest):\n subrequest.addfinalizer(lambda: _excepts('excepts'))\n subrequest.addfinalizer(lambda: values.append(3))\n def test_first(something, excepts):\n pass\n def test_second():\n assert values == [3, 2, 1]\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"*Exception: Error in excepts fixture\", \"* 2 passed, 1 error in *\"]\n )\n\n def test_request_getmodulepath(self, testdir):\n modcol = testdir.getmodulecol(\"def test_somefunc(): pass\")\n item, = testdir.genitems([modcol])\n req = fixtures.FixtureRequest(item)\n assert req.fspath == modcol.fspath\n\n def test_request_fixturenames(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n from _pytest.pytester import get_public_names\n @pytest.fixture()\n def arg1():\n pass\n @pytest.fixture()\n def farg(arg1):\n pass\n @pytest.fixture(autouse=True)\n def sarg(tmpdir):\n pass\n def test_function(request, farg):\n assert set(get_public_names(request.fixturenames)) == \\\n set([\"tmpdir\", \"sarg\", \"arg1\", \"request\", \"farg\",\n \"tmp_path\", \"tmp_path_factory\"])\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_request_fixturenames_dynamic_fixture(self, testdir):\n \"\"\"Regression test for #3057\"\"\"\n testdir.copy_example(\"fixtures/test_getfixturevalue_dynamic.py\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_funcargnames_compatattr(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n assert metafunc.funcargnames == metafunc.fixturenames\n @pytest.fixture\n def fn(request):\n assert request._pyfuncitem.funcargnames == \\\n request._pyfuncitem.fixturenames\n return request.funcargnames, request.fixturenames\n\n def test_hello(fn):\n assert fn[0] == fn[1]\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_setupdecorator_and_xunit(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(scope='module', autouse=True)\n def setup_module():\n values.append(\"module\")\n @pytest.fixture(autouse=True)\n def setup_function():\n values.append(\"function\")\n\n def test_func():\n pass\n\n class TestClass(object):\n @pytest.fixture(scope=\"class\", autouse=True)\n def setup_class(self):\n values.append(\"class\")\n @pytest.fixture(autouse=True)\n def setup_method(self):\n values.append(\"method\")\n def test_method(self):\n pass\n def test_all():\n assert values == [\"module\", \"function\", \"class\",\n \"function\", \"method\", \"function\"]\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\")\n reprec.assertoutcome(passed=3)\n\n def test_fixtures_sub_subdir_normalize_sep(self, testdir):\n # this tests that normalization of nodeids takes place\n b = testdir.mkdir(\"tests\").mkdir(\"unit\")\n b.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def arg1():\n pass\n \"\"\"\n )\n )\n p = b.join(\"test_module.py\")\n p.write(\"def test_func(arg1): pass\")\n result = testdir.runpytest(p, \"--fixtures\")\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n \"\"\"\n *fixtures defined*conftest*\n *arg1*\n \"\"\"\n )\n\n def test_show_fixtures_color_yes(self, testdir):\n testdir.makepyfile(\"def test_this(): assert 1\")\n result = testdir.runpytest(\"--color=yes\", \"--fixtures\")\n assert \"\\x1b[32mtmpdir\" in result.stdout.str()\n\n def test_newstyle_with_request(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture()\n def arg(request):\n pass\n def test_1(arg):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_setupcontext_no_param(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(params=[1,2])\n def arg(request):\n return request.param\n\n @pytest.fixture(autouse=True)\n def mysetup(request, arg):\n assert not hasattr(request, \"param\")\n def test_1(arg):\n assert arg in (1,2)\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n\nclass TestRequestMarking(object):\n def test_applymarker(self, testdir):\n item1, item2 = testdir.getitems(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def something(request):\n pass\n class TestClass(object):\n def test_func1(self, something):\n pass\n def test_func2(self, something):\n pass\n \"\"\"\n )\n req1 = fixtures.FixtureRequest(item1)\n assert \"xfail\" not in item1.keywords\n req1.applymarker(pytest.mark.xfail)\n assert \"xfail\" in item1.keywords\n assert \"skipif\" not in item1.keywords\n req1.applymarker(pytest.mark.skipif)\n assert \"skipif\" in item1.keywords\n with pytest.raises(ValueError):\n req1.applymarker(42)\n\n def test_accesskeywords(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture()\n def keywords(request):\n return request.keywords\n @pytest.mark.XYZ\n def test_function(keywords):\n assert keywords[\"XYZ\"]\n assert \"abc\" not in keywords\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_accessmarker_dynamic(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture()\n def keywords(request):\n return request.keywords\n\n @pytest.fixture(scope=\"class\", autouse=True)\n def marking(request):\n request.applymarker(pytest.mark.XYZ(\"hello\"))\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_fun1(keywords):\n assert keywords[\"XYZ\"] is not None\n assert \"abc\" not in keywords\n def test_fun2(keywords):\n assert keywords[\"XYZ\"] is not None\n assert \"abc\" not in keywords\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n\nclass TestFixtureUsages(object):\n def test_noargfixturedec(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def arg1():\n return 1\n\n def test_func(arg1):\n assert arg1 == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_receives_funcargs(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture()\n def arg1():\n return 1\n\n @pytest.fixture()\n def arg2(arg1):\n return arg1 + 1\n\n def test_add(arg2):\n assert arg2 == 2\n def test_all(arg1, arg2):\n assert arg1 == 1\n assert arg2 == 2\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_receives_funcargs_scope_mismatch(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=\"function\")\n def arg1():\n return 1\n\n @pytest.fixture(scope=\"module\")\n def arg2(arg1):\n return arg1 + 1\n\n def test_add(arg2):\n assert arg2 == 2\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*ScopeMismatch*involved factories*\",\n \"test_receives_funcargs_scope_mismatch.py:6: def arg2(arg1)\",\n \"test_receives_funcargs_scope_mismatch.py:2: def arg1()\",\n \"*1 error*\",\n ]\n )\n\n def test_receives_funcargs_scope_mismatch_issue660(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=\"function\")\n def arg1():\n return 1\n\n @pytest.fixture(scope=\"module\")\n def arg2(arg1):\n return arg1 + 1\n\n def test_add(arg1, arg2):\n assert arg2 == 2\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"*ScopeMismatch*involved factories*\", \"* def arg2*\", \"*1 error*\"]\n )\n\n def test_invalid_scope(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=\"functions\")\n def badscope():\n pass\n\n def test_nothing(badscope):\n pass\n \"\"\"\n )\n result = testdir.runpytest_inprocess()\n result.stdout.fnmatch_lines(\n \"*Fixture 'badscope' from test_invalid_scope.py got an unexpected scope value 'functions'\"\n )\n\n def test_funcarg_parametrized_and_used_twice(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(params=[1,2])\n def arg1(request):\n values.append(1)\n return request.param\n\n @pytest.fixture()\n def arg2(arg1):\n return arg1 + 1\n\n def test_add(arg1, arg2):\n assert arg2 == arg1 + 1\n assert len(values) == arg1\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n def test_factory_uses_unknown_funcarg_as_dependency_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture()\n def fail(missing):\n return\n\n @pytest.fixture()\n def call_fail(fail):\n return\n\n def test_missing(call_fail):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n \"\"\"\n *pytest.fixture()*\n *def call_fail(fail)*\n *pytest.fixture()*\n *def fail*\n *fixture*'missing'*not found*\n \"\"\"\n )\n\n def test_factory_setup_as_classes_fails(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n class arg1(object):\n def __init__(self, request):\n self.x = 1\n arg1 = pytest.fixture()(arg1)\n\n \"\"\"\n )\n reprec = testdir.inline_run()\n values = reprec.getfailedcollections()\n assert len(values) == 1\n\n @pytest.mark.filterwarnings(\"ignore::pytest.PytestDeprecationWarning\")\n def test_request_can_be_overridden(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture()\n def request(request):\n request.a = 1\n return request\n def test_request(request):\n assert request.a == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_usefixtures_marker(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n values = []\n\n @pytest.fixture(scope=\"class\")\n def myfix(request):\n request.cls.hello = \"world\"\n values.append(1)\n\n class TestClass(object):\n def test_one(self):\n assert self.hello == \"world\"\n assert len(values) == 1\n def test_two(self):\n assert self.hello == \"world\"\n assert len(values) == 1\n pytest.mark.usefixtures(\"myfix\")(TestClass)\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_usefixtures_ini(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n usefixtures = myfix\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"class\")\n def myfix(request):\n request.cls.hello = \"world\"\n\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n class TestClass(object):\n def test_one(self):\n assert self.hello == \"world\"\n def test_two(self):\n assert self.hello == \"world\"\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_usefixtures_seen_in_showmarkers(self, testdir):\n result = testdir.runpytest(\"--markers\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *usefixtures(fixturename1*mark tests*fixtures*\n \"\"\"\n )\n\n def test_request_instance_issue203(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n class TestClass(object):\n @pytest.fixture\n def setup1(self, request):\n assert self == request.instance\n self.arg1 = 1\n def test_hello(self, setup1):\n assert self.arg1 == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_fixture_parametrized_with_iterator(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n values = []\n def f():\n yield 1\n yield 2\n dec = pytest.fixture(scope=\"module\", params=f())\n\n @dec\n def arg(request):\n return request.param\n @dec\n def arg2(request):\n return request.param\n\n def test_1(arg):\n values.append(arg)\n def test_2(arg2):\n values.append(arg2*10)\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\")\n reprec.assertoutcome(passed=4)\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n assert values == [1, 2, 10, 20]\n\n def test_setup_functions_as_fixtures(self, testdir):\n \"\"\"Ensure setup_* methods obey fixture scope rules (#517, #3094).\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n DB_INITIALIZED = None\n\n @pytest.yield_fixture(scope=\"session\", autouse=True)\n def db():\n global DB_INITIALIZED\n DB_INITIALIZED = True\n yield\n DB_INITIALIZED = False\n\n def setup_module():\n assert DB_INITIALIZED\n\n def teardown_module():\n assert DB_INITIALIZED\n\n class TestClass(object):\n\n def setup_method(self, method):\n assert DB_INITIALIZED\n\n def teardown_method(self, method):\n assert DB_INITIALIZED\n\n def test_printer_1(self):\n pass\n\n def test_printer_2(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed in *\"])\n\n\nclass TestFixtureManagerParseFactories(object):\n @pytest.fixture\n def testdir(self, request):\n testdir = request.getfixturevalue(\"testdir\")\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def hello(request):\n return \"conftest\"\n\n @pytest.fixture\n def fm(request):\n return request._fixturemanager\n\n @pytest.fixture\n def item(request):\n return request._pyfuncitem\n \"\"\"\n )\n return testdir\n\n def test_parsefactories_evil_objects_issue214(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class A(object):\n def __call__(self):\n pass\n def __getattr__(self, name):\n raise RuntimeError()\n a = A()\n def test_hello():\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1, failed=0)\n\n def test_parsefactories_conftest(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_hello(item, fm):\n for name in (\"fm\", \"hello\", \"item\"):\n faclist = fm.getfixturedefs(name, item.nodeid)\n assert len(faclist) == 1\n fac = faclist[0]\n assert fac.func.__name__ == name\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=1)\n\n def test_parsefactories_conftest_and_module_and_class(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n import six\n\n @pytest.fixture\n def hello(request):\n return \"module\"\n class TestClass(object):\n @pytest.fixture\n def hello(self, request):\n return \"class\"\n def test_hello(self, item, fm):\n faclist = fm.getfixturedefs(\"hello\", item.nodeid)\n print(faclist)\n assert len(faclist) == 3\n\n assert faclist[0].func(item._request) == \"conftest\"\n assert faclist[1].func(item._request) == \"module\"\n assert faclist[2].func(item._request) == \"class\"\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=1)\n\n def test_parsefactories_relative_node_ids(self, testdir):\n # example mostly taken from:\n # https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html\n runner = testdir.mkdir(\"runner\")\n package = testdir.mkdir(\"package\")\n package.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def one():\n return 1\n \"\"\"\n )\n )\n package.join(\"test_x.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_x(one):\n assert one == 1\n \"\"\"\n )\n )\n sub = package.mkdir(\"sub\")\n sub.join(\"__init__.py\").ensure()\n sub.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def one():\n return 2\n \"\"\"\n )\n )\n sub.join(\"test_y.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_x(one):\n assert one == 2\n \"\"\"\n )\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n with runner.as_cwd():\n reprec = testdir.inline_run(\"..\")\n reprec.assertoutcome(passed=2)\n\n def test_package_xunit_fixture(self, testdir):\n testdir.makepyfile(\n __init__=\"\"\"\\\n values = []\n \"\"\"\n )\n package = testdir.mkdir(\"package\")\n package.join(\"__init__.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def setup_module():\n values.append(\"package\")\n def teardown_module():\n values[:] = []\n \"\"\"\n )\n )\n package.join(\"test_x.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def test_x():\n assert values == [\"package\"]\n \"\"\"\n )\n )\n package = testdir.mkdir(\"package2\")\n package.join(\"__init__.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def setup_module():\n values.append(\"package2\")\n def teardown_module():\n values[:] = []\n \"\"\"\n )\n )\n package.join(\"test_x.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def test_x():\n assert values == [\"package2\"]\n \"\"\"\n )\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_package_fixture_complex(self, testdir):\n testdir.makepyfile(\n __init__=\"\"\"\\\n values = []\n \"\"\"\n )\n testdir.syspathinsert(testdir.tmpdir.dirname)\n package = testdir.mkdir(\"package\")\n package.join(\"__init__.py\").write(\"\")\n package.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n from .. import values\n @pytest.fixture(scope=\"package\")\n def one():\n values.append(\"package\")\n yield values\n values.pop()\n @pytest.fixture(scope=\"package\", autouse=True)\n def two():\n values.append(\"package-auto\")\n yield values\n values.pop()\n \"\"\"\n )\n )\n package.join(\"test_x.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def test_package_autouse():\n assert values == [\"package-auto\"]\n def test_package(one):\n assert values == [\"package-auto\", \"package\"]\n \"\"\"\n )\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_collect_custom_items(self, testdir):\n testdir.copy_example(\"fixtures/custom_item\")\n result = testdir.runpytest(\"foo\")\n result.stdout.fnmatch_lines([\"*passed*\"])\n\n\nclass TestAutouseDiscovery(object):\n @pytest.fixture\n def testdir(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture(autouse=True)\n def perfunction(request, tmpdir):\n pass\n\n @pytest.fixture()\n def arg1(tmpdir):\n pass\n @pytest.fixture(autouse=True)\n def perfunction2(arg1):\n pass\n\n @pytest.fixture\n def fm(request):\n return request._fixturemanager\n\n @pytest.fixture\n def item(request):\n return request._pyfuncitem\n \"\"\"\n )\n return testdir\n\n def test_parsefactories_conftest(self, testdir):\n testdir.makepyfile(\n \"\"\"\n from _pytest.pytester import get_public_names\n def test_check_setup(item, fm):\n autousenames = fm._getautousenames(item.nodeid)\n assert len(get_public_names(autousenames)) == 2\n assert \"perfunction2\" in autousenames\n assert \"perfunction\" in autousenames\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=1)\n\n def test_two_classes_separated_autouse(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n class TestA(object):\n values = []\n @pytest.fixture(autouse=True)\n def setup1(self):\n self.values.append(1)\n def test_setup1(self):\n assert self.values == [1]\n class TestB(object):\n values = []\n @pytest.fixture(autouse=True)\n def setup2(self):\n self.values.append(1)\n def test_setup2(self):\n assert self.values == [1]\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_setup_at_classlevel(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n class TestClass(object):\n @pytest.fixture(autouse=True)\n def permethod(self, request):\n request.instance.funcname = request.function.__name__\n def test_method1(self):\n assert self.funcname == \"test_method1\"\n def test_method2(self):\n assert self.funcname == \"test_method2\"\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=2)\n\n @pytest.mark.xfail(reason=\"'enabled' feature not implemented\")\n def test_setup_enabled_functionnode(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n def enabled(parentnode, markers):\n return \"needsdb\" in markers\n\n @pytest.fixture(params=[1,2])\n def db(request):\n return request.param\n\n @pytest.fixture(enabled=enabled, autouse=True)\n def createdb(db):\n pass\n\n def test_func1(request):\n assert \"db\" not in request.fixturenames\n\n @pytest.mark.needsdb\n def test_func2(request):\n assert \"db\" in request.fixturenames\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=2)\n\n def test_callables_nocode(self, testdir):\n \"\"\"\n an imported mock.call would break setup/factory discovery\n due to it being callable and __code__ not being a code object\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n class _call(tuple):\n def __call__(self, *k, **kw):\n pass\n def __getattr__(self, k):\n return self\n\n call = _call()\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(failed=0, passed=0)\n\n def test_autouse_in_conftests(self, testdir):\n a = testdir.mkdir(\"a\")\n b = testdir.mkdir(\"a1\")\n conftest = testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture(autouse=True)\n def hello():\n xxx\n \"\"\"\n )\n conftest.move(a.join(conftest.basename))\n a.join(\"test_something.py\").write(\"def test_func(): pass\")\n b.join(\"test_otherthing.py\").write(\"def test_func(): pass\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n \"\"\"\n *1 passed*1 error*\n \"\"\"\n )\n\n def test_autouse_in_module_and_two_classes(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(autouse=True)\n def append1():\n values.append(\"module\")\n def test_x():\n assert values == [\"module\"]\n\n class TestA(object):\n @pytest.fixture(autouse=True)\n def append2(self):\n values.append(\"A\")\n def test_hello(self):\n assert values == [\"module\", \"module\", \"A\"], values\n class TestA2(object):\n def test_world(self):\n assert values == [\"module\", \"module\", \"A\", \"module\"], values\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=3)\n\n\nclass TestAutouseManagement(object):\n def test_autouse_conftest_mid_directory(self, testdir):\n pkgdir = testdir.mkpydir(\"xyz123\")\n pkgdir.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture(autouse=True)\n def app():\n import sys\n sys._myapp = \"hello\"\n \"\"\"\n )\n )\n t = pkgdir.ensure(\"tests\", \"test_app.py\")\n t.write(\n textwrap.dedent(\n \"\"\"\\\n import sys\n def test_app():\n assert sys._myapp == \"hello\"\n \"\"\"\n )\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=1)\n\n def test_funcarg_and_setup(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(scope=\"module\")\n def arg():\n values.append(1)\n return 0\n @pytest.fixture(scope=\"module\", autouse=True)\n def something(arg):\n values.append(2)\n\n def test_hello(arg):\n assert len(values) == 2\n assert values == [1,2]\n assert arg == 0\n\n def test_hello2(arg):\n assert len(values) == 2\n assert values == [1,2]\n assert arg == 0\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_uses_parametrized_resource(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(params=[1,2])\n def arg(request):\n return request.param\n\n @pytest.fixture(autouse=True)\n def something(arg):\n values.append(arg)\n\n def test_hello():\n if len(values) == 1:\n assert values == [1]\n elif len(values) == 2:\n assert values == [1, 2]\n else:\n 0/0\n\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=2)\n\n def test_session_parametrized_function(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n values = []\n\n @pytest.fixture(scope=\"session\", params=[1,2])\n def arg(request):\n return request.param\n\n @pytest.fixture(scope=\"function\", autouse=True)\n def append(request, arg):\n if request.function.__name__ == \"test_some\":\n values.append(arg)\n\n def test_some():\n pass\n\n def test_result(arg):\n assert len(values) == arg\n assert values[:arg] == [1,2][:arg]\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\", \"-s\")\n reprec.assertoutcome(passed=4)\n\n def test_class_function_parametrization_finalization(self, testdir):\n p = testdir.makeconftest(\n \"\"\"\n import pytest\n import pprint\n\n values = []\n\n @pytest.fixture(scope=\"function\", params=[1,2])\n def farg(request):\n return request.param\n\n @pytest.fixture(scope=\"class\", params=list(\"ab\"))\n def carg(request):\n return request.param\n\n @pytest.fixture(scope=\"function\", autouse=True)\n def append(request, farg, carg):\n def fin():\n values.append(\"fin_%s%s\" % (carg, farg))\n request.addfinalizer(fin)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n class TestClass(object):\n def test_1(self):\n pass\n class TestClass2(object):\n def test_2(self):\n pass\n \"\"\"\n )\n confcut = \"--confcutdir={}\".format(testdir.tmpdir)\n reprec = testdir.inline_run(\"-v\", \"-s\", confcut)\n reprec.assertoutcome(passed=8)\n config = reprec.getcalls(\"pytest_unconfigure\")[0].config\n values = config.pluginmanager._getconftestmodules(p)[0].values\n assert values == [\"fin_a1\", \"fin_a2\", \"fin_b1\", \"fin_b2\"] * 2\n\n def test_scope_ordering(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(scope=\"function\", autouse=True)\n def fappend2():\n values.append(2)\n @pytest.fixture(scope=\"class\", autouse=True)\n def classappend3():\n values.append(3)\n @pytest.fixture(scope=\"module\", autouse=True)\n def mappend():\n values.append(1)\n\n class TestHallo(object):\n def test_method(self):\n assert values == [1,3,2]\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_parametrization_setup_teardown_ordering(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n def pytest_generate_tests(metafunc):\n if metafunc.cls is None:\n assert metafunc.function is test_finish\n if metafunc.cls is not None:\n metafunc.parametrize(\"item\", [1,2], scope=\"class\")\n class TestClass(object):\n @pytest.fixture(scope=\"class\", autouse=True)\n def addteardown(self, item, request):\n values.append(\"setup-%d\" % item)\n request.addfinalizer(lambda: values.append(\"teardown-%d\" % item))\n def test_step1(self, item):\n values.append(\"step1-%d\" % item)\n def test_step2(self, item):\n values.append(\"step2-%d\" % item)\n\n def test_finish():\n print(values)\n assert values == [\"setup-1\", \"step1-1\", \"step2-1\", \"teardown-1\",\n \"setup-2\", \"step1-2\", \"step2-2\", \"teardown-2\",]\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=5)\n\n def test_ordering_autouse_before_explicit(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n values = []\n @pytest.fixture(autouse=True)\n def fix1():\n values.append(1)\n @pytest.fixture()\n def arg1():\n values.append(2)\n def test_hello(arg1):\n assert values == [1,2]\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n @pytest.mark.parametrize(\"param1\", [\"\", \"params=[1]\"], ids=[\"p00\", \"p01\"])\n @pytest.mark.parametrize(\"param2\", [\"\", \"params=[1]\"], ids=[\"p10\", \"p11\"])\n def test_ordering_dependencies_torndown_first(self, testdir, param1, param2):\n \"\"\"#226\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(%(param1)s)\n def arg1(request):\n request.addfinalizer(lambda: values.append(\"fin1\"))\n values.append(\"new1\")\n @pytest.fixture(%(param2)s)\n def arg2(request, arg1):\n request.addfinalizer(lambda: values.append(\"fin2\"))\n values.append(\"new2\")\n\n def test_arg(arg2):\n pass\n def test_check():\n assert values == [\"new1\", \"new2\", \"fin2\", \"fin1\"]\n \"\"\"\n % locals()\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=2)\n\n\nclass TestFixtureMarker(object):\n def test_parametrize(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(params=[\"a\", \"b\", \"c\"])\n def arg(request):\n return request.param\n values = []\n def test_param(arg):\n values.append(arg)\n def test_result():\n assert values == list(\"abc\")\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=4)\n\n def test_multiple_parametrization_issue_736(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[1,2,3])\n def foo(request):\n return request.param\n\n @pytest.mark.parametrize('foobar', [4,5,6])\n def test_issue(foo, foobar):\n assert foo in [1,2,3]\n assert foobar in [4,5,6]\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=9)\n\n @pytest.mark.parametrize(\n \"param_args\",\n [\"'fixt, val'\", \"'fixt,val'\", \"['fixt', 'val']\", \"('fixt', 'val')\"],\n )\n def test_override_parametrized_fixture_issue_979(self, testdir, param_args):\n \"\"\"Make sure a parametrized argument can override a parametrized fixture.\n\n This was a regression introduced in the fix for #736.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[1, 2])\n def fixt(request):\n return request.param\n\n @pytest.mark.parametrize(%s, [(3, 'x'), (4, 'x')])\n def test_foo(fixt, val):\n pass\n \"\"\"\n % param_args\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_scope_session(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(scope=\"module\")\n def arg():\n values.append(1)\n return 1\n\n def test_1(arg):\n assert arg == 1\n def test_2(arg):\n assert arg == 1\n assert len(values) == 1\n class TestClass(object):\n def test3(self, arg):\n assert arg == 1\n assert len(values) == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=3)\n\n def test_scope_session_exc(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(scope=\"session\")\n def fix():\n values.append(1)\n pytest.skip('skipping')\n\n def test_1(fix):\n pass\n def test_2(fix):\n pass\n def test_last():\n assert values == [1]\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(skipped=2, passed=1)\n\n def test_scope_session_exc_two_fix(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n m = []\n @pytest.fixture(scope=\"session\")\n def a():\n values.append(1)\n pytest.skip('skipping')\n @pytest.fixture(scope=\"session\")\n def b(a):\n m.append(1)\n\n def test_1(b):\n pass\n def test_2(b):\n pass\n def test_last():\n assert values == [1]\n assert m == []\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(skipped=2, passed=1)\n\n def test_scope_exc(self, testdir):\n testdir.makepyfile(\n test_foo=\"\"\"\n def test_foo(fix):\n pass\n \"\"\",\n test_bar=\"\"\"\n def test_bar(fix):\n pass\n \"\"\",\n conftest=\"\"\"\n import pytest\n reqs = []\n @pytest.fixture(scope=\"session\")\n def fix(request):\n reqs.append(1)\n pytest.skip()\n @pytest.fixture\n def req_list():\n return reqs\n \"\"\",\n test_real=\"\"\"\n def test_last(req_list):\n assert req_list == [1]\n \"\"\",\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(skipped=2, passed=1)\n\n def test_scope_module_uses_session(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(scope=\"module\")\n def arg():\n values.append(1)\n return 1\n\n def test_1(arg):\n assert arg == 1\n def test_2(arg):\n assert arg == 1\n assert len(values) == 1\n class TestClass(object):\n def test3(self, arg):\n assert arg == 1\n assert len(values) == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=3)\n\n def test_scope_module_and_finalizer(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n finalized_list = []\n created_list = []\n @pytest.fixture(scope=\"module\")\n def arg(request):\n created_list.append(1)\n assert request.scope == \"module\"\n request.addfinalizer(lambda: finalized_list.append(1))\n @pytest.fixture\n def created(request):\n return len(created_list)\n @pytest.fixture\n def finalized(request):\n return len(finalized_list)\n \"\"\"\n )\n testdir.makepyfile(\n test_mod1=\"\"\"\n def test_1(arg, created, finalized):\n assert created == 1\n assert finalized == 0\n def test_2(arg, created, finalized):\n assert created == 1\n assert finalized == 0\"\"\",\n test_mod2=\"\"\"\n def test_3(arg, created, finalized):\n assert created == 2\n assert finalized == 1\"\"\",\n test_mode3=\"\"\"\n def test_4(arg, created, finalized):\n assert created == 3\n assert finalized == 2\n \"\"\",\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=4)\n\n def test_scope_mismatch_various(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n finalized = []\n created = []\n @pytest.fixture(scope=\"function\")\n def arg(request):\n pass\n \"\"\"\n )\n testdir.makepyfile(\n test_mod1=\"\"\"\n import pytest\n @pytest.fixture(scope=\"session\")\n def arg(request):\n request.getfixturevalue(\"arg\")\n def test_1(arg):\n pass\n \"\"\"\n )\n result = testdir.runpytest(SHOW_PYTEST_WARNINGS_ARG)\n assert result.ret != 0\n result.stdout.fnmatch_lines(\n [\"*ScopeMismatch*You tried*function*session*request*\"]\n )\n\n def test_register_only_with_mark(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture()\n def arg():\n return 1\n \"\"\"\n )\n testdir.makepyfile(\n test_mod1=\"\"\"\n import pytest\n @pytest.fixture()\n def arg(arg):\n return arg + 1\n def test_1(arg):\n assert arg == 2\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_parametrize_and_scope(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=\"module\", params=[\"a\", \"b\", \"c\"])\n def arg(request):\n return request.param\n values = []\n def test_param(arg):\n values.append(arg)\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\")\n reprec.assertoutcome(passed=3)\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n assert len(values) == 3\n assert \"a\" in values\n assert \"b\" in values\n assert \"c\" in values\n\n def test_scope_mismatch(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture(scope=\"function\")\n def arg(request):\n pass\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=\"session\")\n def arg(arg):\n pass\n def test_mismatch(arg):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*ScopeMismatch*\", \"*1 error*\"])\n\n def test_parametrize_separated_order(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"module\", params=[1, 2])\n def arg(request):\n return request.param\n\n values = []\n def test_1(arg):\n values.append(arg)\n def test_2(arg):\n values.append(arg)\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\")\n reprec.assertoutcome(passed=4)\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n assert values == [1, 1, 2, 2]\n\n def test_module_parametrized_ordering(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style=classic\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"session\", params=\"s1 s2\".split())\n def sarg():\n pass\n @pytest.fixture(scope=\"module\", params=\"m1 m2\".split())\n def marg():\n pass\n \"\"\"\n )\n testdir.makepyfile(\n test_mod1=\"\"\"\n def test_func(sarg):\n pass\n def test_func1(marg):\n pass\n \"\"\",\n test_mod2=\"\"\"\n def test_func2(sarg):\n pass\n def test_func3(sarg, marg):\n pass\n def test_func3b(sarg, marg):\n pass\n def test_func4(marg):\n pass\n \"\"\",\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n \"\"\"\n test_mod1.py::test_func[s1] PASSED\n test_mod2.py::test_func2[s1] PASSED\n test_mod2.py::test_func3[s1-m1] PASSED\n test_mod2.py::test_func3b[s1-m1] PASSED\n test_mod2.py::test_func3[s1-m2] PASSED\n test_mod2.py::test_func3b[s1-m2] PASSED\n test_mod1.py::test_func[s2] PASSED\n test_mod2.py::test_func2[s2] PASSED\n test_mod2.py::test_func3[s2-m1] PASSED\n test_mod2.py::test_func3b[s2-m1] PASSED\n test_mod2.py::test_func4[m1] PASSED\n test_mod2.py::test_func3[s2-m2] PASSED\n test_mod2.py::test_func3b[s2-m2] PASSED\n test_mod2.py::test_func4[m2] PASSED\n test_mod1.py::test_func1[m1] PASSED\n test_mod1.py::test_func1[m2] PASSED\n \"\"\"\n )\n\n def test_dynamic_parametrized_ordering(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style=classic\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n def pytest_configure(config):\n class DynamicFixturePlugin(object):\n @pytest.fixture(scope='session', params=['flavor1', 'flavor2'])\n def flavor(self, request):\n return request.param\n config.pluginmanager.register(DynamicFixturePlugin(), 'flavor-fixture')\n\n @pytest.fixture(scope='session', params=['vxlan', 'vlan'])\n def encap(request):\n return request.param\n\n @pytest.fixture(scope='session', autouse='True')\n def reprovision(request, flavor, encap):\n pass\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test(reprovision):\n pass\n def test2(reprovision):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n \"\"\"\n test_dynamic_parametrized_ordering.py::test[flavor1-vxlan] PASSED\n test_dynamic_parametrized_ordering.py::test2[flavor1-vxlan] PASSED\n test_dynamic_parametrized_ordering.py::test[flavor2-vxlan] PASSED\n test_dynamic_parametrized_ordering.py::test2[flavor2-vxlan] PASSED\n test_dynamic_parametrized_ordering.py::test[flavor2-vlan] PASSED\n test_dynamic_parametrized_ordering.py::test2[flavor2-vlan] PASSED\n test_dynamic_parametrized_ordering.py::test[flavor1-vlan] PASSED\n test_dynamic_parametrized_ordering.py::test2[flavor1-vlan] PASSED\n \"\"\"\n )\n\n def test_class_ordering(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style=classic\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n values = []\n\n @pytest.fixture(scope=\"function\", params=[1,2])\n def farg(request):\n return request.param\n\n @pytest.fixture(scope=\"class\", params=list(\"ab\"))\n def carg(request):\n return request.param\n\n @pytest.fixture(scope=\"function\", autouse=True)\n def append(request, farg, carg):\n def fin():\n values.append(\"fin_%s%s\" % (carg, farg))\n request.addfinalizer(fin)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n class TestClass2(object):\n def test_1(self):\n pass\n def test_2(self):\n pass\n class TestClass(object):\n def test_3(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-vs\")\n result.stdout.re_match_lines(\n r\"\"\"\n test_class_ordering.py::TestClass2::test_1\\[a-1\\] PASSED\n test_class_ordering.py::TestClass2::test_1\\[a-2\\] PASSED\n test_class_ordering.py::TestClass2::test_2\\[a-1\\] PASSED\n test_class_ordering.py::TestClass2::test_2\\[a-2\\] PASSED\n test_class_ordering.py::TestClass2::test_1\\[b-1\\] PASSED\n test_class_ordering.py::TestClass2::test_1\\[b-2\\] PASSED\n test_class_ordering.py::TestClass2::test_2\\[b-1\\] PASSED\n test_class_ordering.py::TestClass2::test_2\\[b-2\\] PASSED\n test_class_ordering.py::TestClass::test_3\\[a-1\\] PASSED\n test_class_ordering.py::TestClass::test_3\\[a-2\\] PASSED\n test_class_ordering.py::TestClass::test_3\\[b-1\\] PASSED\n test_class_ordering.py::TestClass::test_3\\[b-2\\] PASSED\n \"\"\"\n )\n\n def test_parametrize_separated_order_higher_scope_first(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"function\", params=[1, 2])\n def arg(request):\n param = request.param\n request.addfinalizer(lambda: values.append(\"fin:%s\" % param))\n values.append(\"create:%s\" % param)\n return request.param\n\n @pytest.fixture(scope=\"module\", params=[\"mod1\", \"mod2\"])\n def modarg(request):\n param = request.param\n request.addfinalizer(lambda: values.append(\"fin:%s\" % param))\n values.append(\"create:%s\" % param)\n return request.param\n\n values = []\n def test_1(arg):\n values.append(\"test1\")\n def test_2(modarg):\n values.append(\"test2\")\n def test_3(arg, modarg):\n values.append(\"test3\")\n def test_4(modarg, arg):\n values.append(\"test4\")\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\")\n reprec.assertoutcome(passed=12)\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n expected = [\n \"create:1\",\n \"test1\",\n \"fin:1\",\n \"create:2\",\n \"test1\",\n \"fin:2\",\n \"create:mod1\",\n \"test2\",\n \"create:1\",\n \"test3\",\n \"fin:1\",\n \"create:2\",\n \"test3\",\n \"fin:2\",\n \"create:1\",\n \"test4\",\n \"fin:1\",\n \"create:2\",\n \"test4\",\n \"fin:2\",\n \"fin:mod1\",\n \"create:mod2\",\n \"test2\",\n \"create:1\",\n \"test3\",\n \"fin:1\",\n \"create:2\",\n \"test3\",\n \"fin:2\",\n \"create:1\",\n \"test4\",\n \"fin:1\",\n \"create:2\",\n \"test4\",\n \"fin:2\",\n \"fin:mod2\",\n ]\n import pprint\n\n pprint.pprint(list(zip(values, expected)))\n assert values == expected\n\n def test_parametrized_fixture_teardown_order(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(params=[1,2], scope=\"class\")\n def param1(request):\n return request.param\n\n values = []\n\n class TestClass(object):\n @classmethod\n @pytest.fixture(scope=\"class\", autouse=True)\n def setup1(self, request, param1):\n values.append(1)\n request.addfinalizer(self.teardown1)\n @classmethod\n def teardown1(self):\n assert values.pop() == 1\n @pytest.fixture(scope=\"class\", autouse=True)\n def setup2(self, request, param1):\n values.append(2)\n request.addfinalizer(self.teardown2)\n @classmethod\n def teardown2(self):\n assert values.pop() == 2\n def test(self):\n pass\n\n def test_finish():\n assert not values\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *3 passed*\n \"\"\"\n )\n assert \"error\" not in result.stdout.str()\n\n def test_fixture_finalizer(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n import sys\n\n @pytest.fixture\n def browser(request):\n\n def finalize():\n sys.stdout.write('Finalized')\n request.addfinalizer(finalize)\n return {}\n \"\"\"\n )\n b = testdir.mkdir(\"subdir\")\n b.join(\"test_overridden_fixture_finalizer.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def browser(browser):\n browser['visited'] = True\n return browser\n\n def test_browser(browser):\n assert browser['visited'] is True\n \"\"\"\n )\n )\n reprec = testdir.runpytest(\"-s\")\n for test in [\"test_browser\"]:\n reprec.stdout.fnmatch_lines([\"*Finalized*\"])\n\n def test_class_scope_with_normal_tests(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import pytest\n\n class Box(object):\n value = 0\n\n @pytest.fixture(scope='class')\n def a(request):\n Box.value += 1\n return Box.value\n\n def test_a(a):\n assert a == 1\n\n class Test1(object):\n def test_b(self, a):\n assert a == 2\n\n class Test2(object):\n def test_c(self, a):\n assert a == 3\"\"\"\n )\n reprec = testdir.inline_run(testpath)\n for test in [\"test_a\", \"test_b\", \"test_c\"]:\n assert reprec.matchreport(test).passed\n\n def test_request_is_clean(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(params=[1, 2])\n def fix(request):\n request.addfinalizer(lambda: values.append(request.param))\n def test_fix(fix):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n assert values == [1, 2]\n\n def test_parametrize_separated_lifecycle(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n values = []\n @pytest.fixture(scope=\"module\", params=[1, 2])\n def arg(request):\n x = request.param\n request.addfinalizer(lambda: values.append(\"fin%s\" % x))\n return request.param\n def test_1(arg):\n values.append(arg)\n def test_2(arg):\n values.append(arg)\n \"\"\"\n )\n reprec = testdir.inline_run(\"-vs\")\n reprec.assertoutcome(passed=4)\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n import pprint\n\n pprint.pprint(values)\n # assert len(values) == 6\n assert values[0] == values[1] == 1\n assert values[2] == \"fin1\"\n assert values[3] == values[4] == 2\n assert values[5] == \"fin2\"\n\n def test_parametrize_function_scoped_finalizers_called(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"function\", params=[1, 2])\n def arg(request):\n x = request.param\n request.addfinalizer(lambda: values.append(\"fin%s\" % x))\n return request.param\n\n values = []\n def test_1(arg):\n values.append(arg)\n def test_2(arg):\n values.append(arg)\n def test_3():\n assert len(values) == 8\n assert values == [1, \"fin1\", 2, \"fin2\", 1, \"fin1\", 2, \"fin2\"]\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\")\n reprec.assertoutcome(passed=5)\n\n @pytest.mark.parametrize(\"scope\", [\"session\", \"function\", \"module\"])\n def test_finalizer_order_on_parametrization(self, scope, testdir):\n \"\"\"#246\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n\n @pytest.fixture(scope=%(scope)r, params=[\"1\"])\n def fix1(request):\n return request.param\n\n @pytest.fixture(scope=%(scope)r)\n def fix2(request, base):\n def cleanup_fix2():\n assert not values, \"base should not have been finalized\"\n request.addfinalizer(cleanup_fix2)\n\n @pytest.fixture(scope=%(scope)r)\n def base(request, fix1):\n def cleanup_base():\n values.append(\"fin_base\")\n print(\"finalizing base\")\n request.addfinalizer(cleanup_base)\n\n def test_begin():\n pass\n def test_baz(base, fix2):\n pass\n def test_other():\n pass\n \"\"\"\n % {\"scope\": scope}\n )\n reprec = testdir.inline_run(\"-lvs\")\n reprec.assertoutcome(passed=3)\n\n def test_class_scope_parametrization_ordering(self, testdir):\n \"\"\"#396\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(params=[\"John\", \"Doe\"], scope=\"class\")\n def human(request):\n request.addfinalizer(lambda: values.append(\"fin %s\" % request.param))\n return request.param\n\n class TestGreetings(object):\n def test_hello(self, human):\n values.append(\"test_hello\")\n\n class TestMetrics(object):\n def test_name(self, human):\n values.append(\"test_name\")\n\n def test_population(self, human):\n values.append(\"test_population\")\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=6)\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n assert values == [\n \"test_hello\",\n \"fin John\",\n \"test_hello\",\n \"fin Doe\",\n \"test_name\",\n \"test_population\",\n \"fin John\",\n \"test_name\",\n \"test_population\",\n \"fin Doe\",\n ]\n\n def test_parametrize_setup_function(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"module\", params=[1, 2])\n def arg(request):\n return request.param\n\n @pytest.fixture(scope=\"module\", autouse=True)\n def mysetup(request, arg):\n request.addfinalizer(lambda: values.append(\"fin%s\" % arg))\n values.append(\"setup%s\" % arg)\n\n values = []\n def test_1(arg):\n values.append(arg)\n def test_2(arg):\n values.append(arg)\n def test_3():\n import pprint\n pprint.pprint(values)\n if arg == 1:\n assert values == [\"setup1\", 1, 1, ]\n elif arg == 2:\n assert values == [\"setup1\", 1, 1, \"fin1\",\n \"setup2\", 2, 2, ]\n\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\")\n reprec.assertoutcome(passed=6)\n\n def test_fixture_marked_function_not_collected_as_test(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def test_app():\n return 1\n\n def test_something(test_app):\n assert test_app == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_params_and_ids(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[object(), object()],\n ids=['alpha', 'beta'])\n def fix(request):\n return request.param\n\n def test_foo(fix):\n assert 1\n \"\"\"\n )\n res = testdir.runpytest(\"-v\")\n res.stdout.fnmatch_lines([\"*test_foo*alpha*\", \"*test_foo*beta*\"])\n\n def test_params_and_ids_yieldfixture(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.yield_fixture(params=[object(), object()],\n ids=['alpha', 'beta'])\n def fix(request):\n yield request.param\n\n def test_foo(fix):\n assert 1\n \"\"\"\n )\n res = testdir.runpytest(\"-v\")\n res.stdout.fnmatch_lines([\"*test_foo*alpha*\", \"*test_foo*beta*\"])\n\n def test_deterministic_fixture_collection(self, testdir, monkeypatch):\n \"\"\"#920\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"module\",\n params=[\"A\",\n \"B\",\n \"C\"])\n def A(request):\n return request.param\n\n @pytest.fixture(scope=\"module\",\n params=[\"DDDDDDDDD\", \"EEEEEEEEEEEE\", \"FFFFFFFFFFF\", \"banansda\"])\n def B(request, A):\n return request.param\n\n def test_foo(B):\n # Something funky is going on here.\n # Despite specified seeds, on what is collected,\n # sometimes we get unexpected passes. hashing B seems\n # to help?\n assert hash(B) or True\n \"\"\"\n )\n monkeypatch.setenv(\"PYTHONHASHSEED\", \"1\")\n out1 = testdir.runpytest_subprocess(\"-v\")\n monkeypatch.setenv(\"PYTHONHASHSEED\", \"2\")\n out2 = testdir.runpytest_subprocess(\"-v\")\n out1 = [\n line\n for line in out1.outlines\n if line.startswith(\"test_deterministic_fixture_collection.py::test_foo\")\n ]\n out2 = [\n line\n for line in out2.outlines\n if line.startswith(\"test_deterministic_fixture_collection.py::test_foo\")\n ]\n assert len(out1) == 12\n assert out1 == out2\n\n\nclass TestRequestScopeAccess(object):\n pytestmark = pytest.mark.parametrize(\n (\"scope\", \"ok\", \"error\"),\n [\n [\"session\", \"\", \"fspath class function module\"],\n [\"module\", \"module fspath\", \"cls function\"],\n [\"class\", \"module fspath cls\", \"function\"],\n [\"function\", \"module fspath cls function\", \"\"],\n ],\n )\n\n def test_setup(self, testdir, scope, ok, error):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=%r, autouse=True)\n def myscoped(request):\n for x in %r:\n assert hasattr(request, x)\n for x in %r:\n pytest.raises(AttributeError, lambda:\n getattr(request, x))\n assert request.session\n assert request.config\n def test_func():\n pass\n \"\"\"\n % (scope, ok.split(), error.split())\n )\n reprec = testdir.inline_run(\"-l\")\n reprec.assertoutcome(passed=1)\n\n def test_funcarg(self, testdir, scope, ok, error):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=%r)\n def arg(request):\n for x in %r:\n assert hasattr(request, x)\n for x in %r:\n pytest.raises(AttributeError, lambda:\n getattr(request, x))\n assert request.session\n assert request.config\n def test_func(arg):\n pass\n \"\"\"\n % (scope, ok.split(), error.split())\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n\nclass TestErrors(object):\n def test_subfactory_missing_funcarg(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture()\n def gen(qwe123):\n return 1\n def test_something(gen):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret != 0\n result.stdout.fnmatch_lines(\n [\"*def gen(qwe123):*\", \"*fixture*qwe123*not found*\", \"*1 error*\"]\n )\n\n def test_issue498_fixture_finalizer_failing(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def fix1(request):\n def f():\n raise KeyError\n request.addfinalizer(f)\n return object()\n\n values = []\n def test_1(fix1):\n values.append(fix1)\n def test_2(fix1):\n values.append(fix1)\n def test_3():\n assert values[0] != values[1]\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n \"\"\"\n *ERROR*teardown*test_1*\n *KeyError*\n *ERROR*teardown*test_2*\n *KeyError*\n *3 pass*2 error*\n \"\"\"\n )\n\n def test_setupfunc_missing_funcarg(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(autouse=True)\n def gen(qwe123):\n return 1\n def test_something():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret != 0\n result.stdout.fnmatch_lines(\n [\"*def gen(qwe123):*\", \"*fixture*qwe123*not found*\", \"*1 error*\"]\n )\n\n\nclass TestShowFixtures(object):\n def test_funcarg_compat(self, testdir):\n config = testdir.parseconfigure(\"--funcargs\")\n assert config.option.showfixtures\n\n def test_show_fixtures(self, testdir):\n result = testdir.runpytest(\"--fixtures\")\n result.stdout.fnmatch_lines(\n [\n \"tmpdir_factory [[]session scope[]]\",\n \"*for the test session*\",\n \"tmpdir\",\n \"*temporary directory*\",\n ]\n )\n\n def test_show_fixtures_verbose(self, testdir):\n result = testdir.runpytest(\"--fixtures\", \"-v\")\n result.stdout.fnmatch_lines(\n [\n \"tmpdir_factory [[]session scope[]] -- *tmpdir.py*\",\n \"*for the test session*\",\n \"tmpdir -- *tmpdir.py*\",\n \"*temporary directory*\",\n ]\n )\n\n def test_show_fixtures_testmodule(self, testdir):\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture\n def _arg0():\n \"\"\" hidden \"\"\"\n @pytest.fixture\n def arg1():\n \"\"\" hello world \"\"\"\n '''\n )\n result = testdir.runpytest(\"--fixtures\", p)\n result.stdout.fnmatch_lines(\n \"\"\"\n *tmpdir\n *fixtures defined from*\n *arg1*\n *hello world*\n \"\"\"\n )\n assert \"arg0\" not in result.stdout.str()\n\n @pytest.mark.parametrize(\"testmod\", [True, False])\n def test_show_fixtures_conftest(self, testdir, testmod):\n testdir.makeconftest(\n '''\n import pytest\n @pytest.fixture\n def arg1():\n \"\"\" hello world \"\"\"\n '''\n )\n if testmod:\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--fixtures\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *tmpdir*\n *fixtures defined from*conftest*\n *arg1*\n *hello world*\n \"\"\"\n )\n\n def test_show_fixtures_trimmed_doc(self, testdir):\n p = testdir.makepyfile(\n textwrap.dedent(\n '''\\\n import pytest\n @pytest.fixture\n def arg1():\n \"\"\"\n line1\n line2\n\n \"\"\"\n @pytest.fixture\n def arg2():\n \"\"\"\n line1\n line2\n\n \"\"\"\n '''\n )\n )\n result = testdir.runpytest(\"--fixtures\", p)\n result.stdout.fnmatch_lines(\n textwrap.dedent(\n \"\"\"\\\n * fixtures defined from test_show_fixtures_trimmed_doc *\n arg2\n line1\n line2\n arg1\n line1\n line2\n \"\"\"\n )\n )\n\n def test_show_fixtures_indented_doc(self, testdir):\n p = testdir.makepyfile(\n textwrap.dedent(\n '''\\\n import pytest\n @pytest.fixture\n def fixture1():\n \"\"\"\n line1\n indented line\n \"\"\"\n '''\n )\n )\n result = testdir.runpytest(\"--fixtures\", p)\n result.stdout.fnmatch_lines(\n textwrap.dedent(\n \"\"\"\\\n * fixtures defined from test_show_fixtures_indented_doc *\n fixture1\n line1\n indented line\n \"\"\"\n )\n )\n\n def test_show_fixtures_indented_doc_first_line_unindented(self, testdir):\n p = testdir.makepyfile(\n textwrap.dedent(\n '''\\\n import pytest\n @pytest.fixture\n def fixture1():\n \"\"\"line1\n line2\n indented line\n \"\"\"\n '''\n )\n )\n result = testdir.runpytest(\"--fixtures\", p)\n result.stdout.fnmatch_lines(\n textwrap.dedent(\n \"\"\"\\\n * fixtures defined from test_show_fixtures_indented_doc_first_line_unindented *\n fixture1\n line1\n line2\n indented line\n \"\"\"\n )\n )\n\n def test_show_fixtures_indented_in_class(self, testdir):\n p = testdir.makepyfile(\n textwrap.dedent(\n '''\\\n import pytest\n class TestClass(object):\n @pytest.fixture\n def fixture1(self):\n \"\"\"line1\n line2\n indented line\n \"\"\"\n '''\n )\n )\n result = testdir.runpytest(\"--fixtures\", p)\n result.stdout.fnmatch_lines(\n textwrap.dedent(\n \"\"\"\\\n * fixtures defined from test_show_fixtures_indented_in_class *\n fixture1\n line1\n line2\n indented line\n \"\"\"\n )\n )\n\n def test_show_fixtures_different_files(self, testdir):\n \"\"\"\n #833: --fixtures only shows fixtures from first file\n \"\"\"\n testdir.makepyfile(\n test_a='''\n import pytest\n\n @pytest.fixture\n def fix_a():\n \"\"\"Fixture A\"\"\"\n pass\n\n def test_a(fix_a):\n pass\n '''\n )\n testdir.makepyfile(\n test_b='''\n import pytest\n\n @pytest.fixture\n def fix_b():\n \"\"\"Fixture B\"\"\"\n pass\n\n def test_b(fix_b):\n pass\n '''\n )\n result = testdir.runpytest(\"--fixtures\")\n result.stdout.fnmatch_lines(\n \"\"\"\n * fixtures defined from test_a *\n fix_a\n Fixture A\n\n * fixtures defined from test_b *\n fix_b\n Fixture B\n \"\"\"\n )\n\n def test_show_fixtures_with_same_name(self, testdir):\n testdir.makeconftest(\n '''\n import pytest\n @pytest.fixture\n def arg1():\n \"\"\"Hello World in conftest.py\"\"\"\n return \"Hello World\"\n '''\n )\n testdir.makepyfile(\n \"\"\"\n def test_foo(arg1):\n assert arg1 == \"Hello World\"\n \"\"\"\n )\n testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture\n def arg1():\n \"\"\"Hi from test module\"\"\"\n return \"Hi\"\n def test_bar(arg1):\n assert arg1 == \"Hi\"\n '''\n )\n result = testdir.runpytest(\"--fixtures\")\n result.stdout.fnmatch_lines(\n \"\"\"\n * fixtures defined from conftest *\n arg1\n Hello World in conftest.py\n\n * fixtures defined from test_show_fixtures_with_same_name *\n arg1\n Hi from test module\n \"\"\"\n )\n\n def test_fixture_disallow_twice(self):\n \"\"\"Test that applying @pytest.fixture twice generates an error (#2334).\"\"\"\n with pytest.raises(ValueError):\n\n @pytest.fixture\n @pytest.fixture\n def foo():\n pass\n\n\nclass TestContextManagerFixtureFuncs(object):\n @pytest.fixture(params=[\"fixture\", \"yield_fixture\"])\n def flavor(self, request, testdir, monkeypatch):\n monkeypatch.setenv(\"PYTEST_FIXTURE_FLAVOR\", request.param)\n testdir.makepyfile(\n test_context=\"\"\"\n import os\n import pytest\n import warnings\n VAR = \"PYTEST_FIXTURE_FLAVOR\"\n if VAR not in os.environ:\n warnings.warn(\"PYTEST_FIXTURE_FLAVOR was not set, assuming fixture\")\n fixture = pytest.fixture\n else:\n fixture = getattr(pytest, os.environ[VAR])\n \"\"\"\n )\n\n def test_simple(self, testdir, flavor):\n testdir.makepyfile(\n \"\"\"\n from __future__ import print_function\n from test_context import fixture\n @fixture\n def arg1():\n print(\"setup\")\n yield 1\n print(\"teardown\")\n def test_1(arg1):\n print(\"test1\", arg1)\n def test_2(arg1):\n print(\"test2\", arg1)\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *setup*\n *test1 1*\n *teardown*\n *setup*\n *test2 1*\n *teardown*\n \"\"\"\n )\n\n def test_scoped(self, testdir, flavor):\n testdir.makepyfile(\n \"\"\"\n from __future__ import print_function\n from test_context import fixture\n @fixture(scope=\"module\")\n def arg1():\n print(\"setup\")\n yield 1\n print(\"teardown\")\n def test_1(arg1):\n print(\"test1\", arg1)\n def test_2(arg1):\n print(\"test2\", arg1)\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *setup*\n *test1 1*\n *test2 1*\n *teardown*\n \"\"\"\n )\n\n def test_setup_exception(self, testdir, flavor):\n testdir.makepyfile(\n \"\"\"\n from test_context import fixture\n @fixture(scope=\"module\")\n def arg1():\n pytest.fail(\"setup\")\n yield 1\n def test_1(arg1):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *pytest.fail*setup*\n *1 error*\n \"\"\"\n )\n\n def test_teardown_exception(self, testdir, flavor):\n testdir.makepyfile(\n \"\"\"\n from test_context import fixture\n @fixture(scope=\"module\")\n def arg1():\n yield 1\n pytest.fail(\"teardown\")\n def test_1(arg1):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *pytest.fail*teardown*\n *1 passed*1 error*\n \"\"\"\n )\n\n def test_yields_more_than_one(self, testdir, flavor):\n testdir.makepyfile(\n \"\"\"\n from test_context import fixture\n @fixture(scope=\"module\")\n def arg1():\n yield 1\n yield 2\n def test_1(arg1):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *fixture function*\n *test_yields*:2*\n \"\"\"\n )\n\n def test_custom_name(self, testdir, flavor):\n testdir.makepyfile(\n \"\"\"\n from test_context import fixture\n @fixture(name='meow')\n def arg1():\n return 'mew'\n def test_1(meow):\n print(meow)\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines([\"*mew*\"])\n\n\nclass TestParameterizedSubRequest(object):\n def test_call_from_fixture(self, testdir):\n testdir.makepyfile(\n test_call_from_fixture=\"\"\"\n import pytest\n\n @pytest.fixture(params=[0, 1, 2])\n def fix_with_param(request):\n return request.param\n\n @pytest.fixture\n def get_named_fixture(request):\n return request.getfixturevalue('fix_with_param')\n\n def test_foo(request, get_named_fixture):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"The requested fixture has no parameter defined for test:\",\n \" test_call_from_fixture.py::test_foo\",\n \"Requested fixture 'fix_with_param' defined in:\",\n \"test_call_from_fixture.py:4\",\n \"Requested here:\",\n \"test_call_from_fixture.py:9\",\n \"*1 error in*\",\n ]\n )\n\n def test_call_from_test(self, testdir):\n testdir.makepyfile(\n test_call_from_test=\"\"\"\n import pytest\n\n @pytest.fixture(params=[0, 1, 2])\n def fix_with_param(request):\n return request.param\n\n def test_foo(request):\n request.getfixturevalue('fix_with_param')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"The requested fixture has no parameter defined for test:\",\n \" test_call_from_test.py::test_foo\",\n \"Requested fixture 'fix_with_param' defined in:\",\n \"test_call_from_test.py:4\",\n \"Requested here:\",\n \"test_call_from_test.py:8\",\n \"*1 failed*\",\n ]\n )\n\n def test_external_fixture(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[0, 1, 2])\n def fix_with_param(request):\n return request.param\n \"\"\"\n )\n\n testdir.makepyfile(\n test_external_fixture=\"\"\"\n def test_foo(request):\n request.getfixturevalue('fix_with_param')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"The requested fixture has no parameter defined for test:\",\n \" test_external_fixture.py::test_foo\",\n \"\",\n \"Requested fixture 'fix_with_param' defined in:\",\n \"conftest.py:4\",\n \"Requested here:\",\n \"test_external_fixture.py:2\",\n \"*1 failed*\",\n ]\n )\n\n def test_non_relative_path(self, testdir):\n tests_dir = testdir.mkdir(\"tests\")\n fixdir = testdir.mkdir(\"fixtures\")\n fixfile = fixdir.join(\"fix.py\")\n fixfile.write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n\n @pytest.fixture(params=[0, 1, 2])\n def fix_with_param(request):\n return request.param\n \"\"\"\n )\n )\n\n testfile = tests_dir.join(\"test_foos.py\")\n testfile.write(\n textwrap.dedent(\n \"\"\"\\\n from fix import fix_with_param\n\n def test_foo(request):\n request.getfixturevalue('fix_with_param')\n \"\"\"\n )\n )\n\n tests_dir.chdir()\n testdir.syspathinsert(fixdir)\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"The requested fixture has no parameter defined for test:\",\n \" test_foos.py::test_foo\",\n \"\",\n \"Requested fixture 'fix_with_param' defined in:\",\n \"*fix.py:4\",\n \"Requested here:\",\n \"test_foos.py:4\",\n \"*1 failed*\",\n ]\n )\n\n\ndef test_pytest_fixture_setup_and_post_finalizer_hook(testdir):\n testdir.makeconftest(\n \"\"\"\n from __future__ import print_function\n def pytest_fixture_setup(fixturedef, request):\n print('ROOT setup hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))\n def pytest_fixture_post_finalizer(fixturedef, request):\n print('ROOT finalizer hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))\n \"\"\"\n )\n testdir.makepyfile(\n **{\n \"tests/conftest.py\": \"\"\"\n from __future__ import print_function\n def pytest_fixture_setup(fixturedef, request):\n print('TESTS setup hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))\n def pytest_fixture_post_finalizer(fixturedef, request):\n print('TESTS finalizer hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))\n \"\"\",\n \"tests/test_hooks.py\": \"\"\"\n from __future__ import print_function\n import pytest\n\n @pytest.fixture()\n def my_fixture():\n return 'some'\n\n def test_func(my_fixture):\n print('TEST test_func')\n assert my_fixture == 'some'\n \"\"\",\n }\n )\n result = testdir.runpytest(\"-s\")\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n [\n \"*TESTS setup hook called for my_fixture from test_func*\",\n \"*ROOT setup hook called for my_fixture from test_func*\",\n \"*TEST test_func*\",\n \"*TESTS finalizer hook called for my_fixture from test_func*\",\n \"*ROOT finalizer hook called for my_fixture from test_func*\",\n ]\n )\n\n\nclass TestScopeOrdering(object):\n \"\"\"Class of tests that ensure fixtures are ordered based on their scopes (#2405)\"\"\"\n\n @pytest.mark.parametrize(\"variant\", [\"mark\", \"autouse\"])\n def test_func_closure_module_auto(self, testdir, variant, monkeypatch):\n \"\"\"Semantically identical to the example posted in #2405 when ``use_mark=True``\"\"\"\n monkeypatch.setenv(\"FIXTURE_ACTIVATION_VARIANT\", variant)\n testdir.makepyfile(\n \"\"\"\n import warnings\n import os\n import pytest\n VAR = 'FIXTURE_ACTIVATION_VARIANT'\n VALID_VARS = ('autouse', 'mark')\n\n VARIANT = os.environ.get(VAR)\n if VARIANT is None or VARIANT not in VALID_VARS:\n warnings.warn(\"{!r} is not in {}, assuming autouse\".format(VARIANT, VALID_VARS) )\n variant = 'mark'\n\n @pytest.fixture(scope='module', autouse=VARIANT == 'autouse')\n def m1(): pass\n\n if VARIANT=='mark':\n pytestmark = pytest.mark.usefixtures('m1')\n\n @pytest.fixture(scope='function', autouse=True)\n def f1(): pass\n\n def test_func(m1):\n pass\n \"\"\"\n )\n items, _ = testdir.inline_genitems()\n request = FixtureRequest(items[0])\n assert request.fixturenames == \"m1 f1\".split()\n\n def test_func_closure_with_native_fixtures(self, testdir, monkeypatch):\n \"\"\"Sanity check that verifies the order returned by the closures and the actual fixture execution order:\n The execution order may differ because of fixture inter-dependencies.\n \"\"\"\n monkeypatch.setattr(pytest, \"FIXTURE_ORDER\", [], raising=False)\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n FIXTURE_ORDER = pytest.FIXTURE_ORDER\n\n @pytest.fixture(scope=\"session\")\n def s1():\n FIXTURE_ORDER.append('s1')\n\n @pytest.fixture(scope=\"package\")\n def p1():\n FIXTURE_ORDER.append('p1')\n\n @pytest.fixture(scope=\"module\")\n def m1():\n FIXTURE_ORDER.append('m1')\n\n @pytest.fixture(scope='session')\n def my_tmpdir_factory():\n FIXTURE_ORDER.append('my_tmpdir_factory')\n\n @pytest.fixture\n def my_tmpdir(my_tmpdir_factory):\n FIXTURE_ORDER.append('my_tmpdir')\n\n @pytest.fixture\n def f1(my_tmpdir):\n FIXTURE_ORDER.append('f1')\n\n @pytest.fixture\n def f2():\n FIXTURE_ORDER.append('f2')\n\n def test_foo(f1, p1, m1, f2, s1): pass\n \"\"\"\n )\n items, _ = testdir.inline_genitems()\n request = FixtureRequest(items[0])\n # order of fixtures based on their scope and position in the parameter list\n assert (\n request.fixturenames == \"s1 my_tmpdir_factory p1 m1 f1 f2 my_tmpdir\".split()\n )\n testdir.runpytest()\n # actual fixture execution differs: dependent fixtures must be created first (\"my_tmpdir\")\n assert (\n pytest.FIXTURE_ORDER == \"s1 my_tmpdir_factory p1 m1 my_tmpdir f1 f2\".split()\n )\n\n def test_func_closure_module(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='module')\n def m1(): pass\n\n @pytest.fixture(scope='function')\n def f1(): pass\n\n def test_func(f1, m1):\n pass\n \"\"\"\n )\n items, _ = testdir.inline_genitems()\n request = FixtureRequest(items[0])\n assert request.fixturenames == \"m1 f1\".split()\n\n def test_func_closure_scopes_reordered(self, testdir):\n \"\"\"Test ensures that fixtures are ordered by scope regardless of the order of the parameters, although\n fixtures of same scope keep the declared order\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='session')\n def s1(): pass\n\n @pytest.fixture(scope='module')\n def m1(): pass\n\n @pytest.fixture(scope='function')\n def f1(): pass\n\n @pytest.fixture(scope='function')\n def f2(): pass\n\n class Test:\n\n @pytest.fixture(scope='class')\n def c1(cls): pass\n\n def test_func(self, f2, f1, c1, m1, s1):\n pass\n \"\"\"\n )\n items, _ = testdir.inline_genitems()\n request = FixtureRequest(items[0])\n assert request.fixturenames == \"s1 m1 c1 f2 f1\".split()\n\n def test_func_closure_same_scope_closer_root_first(self, testdir):\n \"\"\"Auto-use fixtures of same scope are ordered by closer-to-root first\"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='module', autouse=True)\n def m_conf(): pass\n \"\"\"\n )\n testdir.makepyfile(\n **{\n \"sub/conftest.py\": \"\"\"\n import pytest\n\n @pytest.fixture(scope='package', autouse=True)\n def p_sub(): pass\n\n @pytest.fixture(scope='module', autouse=True)\n def m_sub(): pass\n \"\"\",\n \"sub/__init__.py\": \"\",\n \"sub/test_func.py\": \"\"\"\n import pytest\n\n @pytest.fixture(scope='module', autouse=True)\n def m_test(): pass\n\n @pytest.fixture(scope='function')\n def f1(): pass\n\n def test_func(m_test, f1):\n pass\n \"\"\",\n }\n )\n items, _ = testdir.inline_genitems()\n request = FixtureRequest(items[0])\n assert request.fixturenames == \"p_sub m_conf m_sub m_test f1\".split()\n\n def test_func_closure_all_scopes_complex(self, testdir):\n \"\"\"Complex test involving all scopes and mixing autouse with normal fixtures\"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='session')\n def s1(): pass\n\n @pytest.fixture(scope='package', autouse=True)\n def p1(): pass\n \"\"\"\n )\n testdir.makepyfile(**{\"__init__.py\": \"\"})\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='module', autouse=True)\n def m1(): pass\n\n @pytest.fixture(scope='module')\n def m2(s1): pass\n\n @pytest.fixture(scope='function')\n def f1(): pass\n\n @pytest.fixture(scope='function')\n def f2(): pass\n\n class Test:\n\n @pytest.fixture(scope='class', autouse=True)\n def c1(self):\n pass\n\n def test_func(self, f2, f1, m2):\n pass\n \"\"\"\n )\n items, _ = testdir.inline_genitems()\n request = FixtureRequest(items[0])\n assert request.fixturenames == \"s1 p1 m1 m2 c1 f2 f1\".split()\n\n def test_multiple_packages(self, testdir):\n \"\"\"Complex test involving multiple package fixtures. Make sure teardowns\n are executed in order.\n .\n └── root\n ├── __init__.py\n ├── sub1\n │ ├── __init__.py\n │ ├── conftest.py\n │ └���─ test_1.py\n └── sub2\n ├── __init__.py\n ├── conftest.py\n └── test_2.py\n \"\"\"\n root = testdir.mkdir(\"root\")\n root.join(\"__init__.py\").write(\"values = []\")\n sub1 = root.mkdir(\"sub1\")\n sub1.ensure(\"__init__.py\")\n sub1.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n from .. import values\n @pytest.fixture(scope=\"package\")\n def fix():\n values.append(\"pre-sub1\")\n yield values\n assert values.pop() == \"pre-sub1\"\n \"\"\"\n )\n )\n sub1.join(\"test_1.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def test_1(fix):\n assert values == [\"pre-sub1\"]\n \"\"\"\n )\n )\n sub2 = root.mkdir(\"sub2\")\n sub2.ensure(\"__init__.py\")\n sub2.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n from .. import values\n @pytest.fixture(scope=\"package\")\n def fix():\n values.append(\"pre-sub2\")\n yield values\n assert values.pop() == \"pre-sub2\"\n \"\"\"\n )\n )\n sub2.join(\"test_2.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def test_2(fix):\n assert values == [\"pre-sub2\"]\n \"\"\"\n )\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n\ndef test_call_fixture_function_error():\n \"\"\"Check if an error is raised if a fixture function is called directly (#4545)\"\"\"\n\n @pytest.fixture\n def fix():\n return 1\n\n with pytest.raises(pytest.fail.Exception):\n assert fix() == 1\n\n\ndef test_fixture_param_shadowing(testdir):\n \"\"\"Parametrized arguments would be shadowed if a fixture with the same name also exists (#5036)\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=['a', 'b'])\n def argroot(request):\n return request.param\n\n @pytest.fixture\n def arg(argroot):\n return argroot\n\n # This should only be parametrized directly\n @pytest.mark.parametrize(\"arg\", [1])\n def test_direct(arg):\n assert arg == 1\n\n # This should be parametrized based on the fixtures\n def test_normal_fixture(arg):\n assert isinstance(arg, str)\n\n # Indirect should still work:\n\n @pytest.fixture\n def arg2(request):\n return 2*request.param\n\n @pytest.mark.parametrize(\"arg2\", [1], indirect=True)\n def test_indirect(arg2):\n assert arg2 == 2\n \"\"\"\n )\n # Only one test should have run\n result = testdir.runpytest(\"-v\")\n result.assert_outcomes(passed=4)\n result.stdout.fnmatch_lines([\"*::test_direct[[]1[]]*\"])\n result.stdout.fnmatch_lines([\"*::test_normal_fixture[[]a[]]*\"])\n result.stdout.fnmatch_lines([\"*::test_normal_fixture[[]b[]]*\"])\n result.stdout.fnmatch_lines([\"*::test_indirect[[]1[]]*\"])\n"},{"className":"FixtureLookupError","col":0,"comment":" could not return a requested Fixture (missing or invalid). ","endLoc":750,"id":1815,"nodeType":"Class","startLoc":699,"text":"class FixtureLookupError(LookupError):\n \"\"\" could not return a requested Fixture (missing or invalid). \"\"\"\n\n def __init__(self, argname, request, msg=None):\n self.argname = argname\n self.request = request\n self.fixturestack = request._get_fixturestack()\n self.msg = msg\n\n def formatrepr(self):\n tblines = []\n addline = tblines.append\n stack = [self.request._pyfuncitem.obj]\n stack.extend(map(lambda x: x.func, self.fixturestack))\n msg = self.msg\n if msg is not None:\n # the last fixture raise an error, let's present\n # it at the requesting side\n stack = stack[:-1]\n for function in stack:\n fspath, lineno = getfslineno(function)\n try:\n lines, _ = inspect.getsourcelines(get_real_func(function))\n except (IOError, IndexError, TypeError):\n error_msg = \"file %s, line %s: source code not available\"\n addline(error_msg % (fspath, lineno + 1))\n else:\n addline(\"file %s, line %s\" % (fspath, lineno + 1))\n for i, line in enumerate(lines):\n line = line.rstrip()\n addline(\" \" + line)\n if line.lstrip().startswith(\"def\"):\n break\n\n if msg is None:\n fm = self.request._fixturemanager\n available = set()\n parentid = self.request._pyfuncitem.parent.nodeid\n for name, fixturedefs in fm._arg2fixturedefs.items():\n faclist = list(fm._matchfactories(fixturedefs, parentid))\n if faclist:\n available.add(name)\n if self.argname in available:\n msg = \" recursive dependency involving fixture '{}' detected\".format(\n self.argname\n )\n else:\n msg = \"fixture '{}' not found\".format(self.argname)\n msg += \"\\n available fixtures: {}\".format(\", \".join(sorted(available)))\n msg += \"\\n use 'pytest --fixtures [testpath]' for help on them.\"\n\n return FixtureLookupErrorRepr(fspath, lineno, tblines, msg, self.argname)"},{"className":"LookupError","col":0,"comment":"null","endLoc":1986,"id":1816,"nodeType":"Class","startLoc":1986,"text":"class LookupError(Exception): ..."},{"col":0,"comment":"null","endLoc":140,"header":"def test_caplog_captures_for_all_stages(caplog, logging_during_setup_and_teardown)","id":1817,"name":"test_caplog_captures_for_all_stages","nodeType":"Function","startLoc":131,"text":"def test_caplog_captures_for_all_stages(caplog, logging_during_setup_and_teardown):\n assert not caplog.records\n assert not caplog.get_records(\"call\")\n logger.info(\"a_call_log\")\n assert [x.message for x in caplog.get_records(\"call\")] == [\"a_call_log\"]\n\n assert [x.message for x in caplog.get_records(\"setup\")] == [\"a_setup_log\"]\n\n # This reaches into private API, don't use this type of thing in real tests!\n assert set(caplog._item.catch_log_handlers.keys()) == {\"setup\", \"call\"}"},{"col":4,"comment":"null","endLoc":750,"header":"def formatrepr(self)","id":1818,"name":"formatrepr","nodeType":"Function","startLoc":708,"text":"def formatrepr(self):\n tblines = []\n addline = tblines.append\n stack = [self.request._pyfuncitem.obj]\n stack.extend(map(lambda x: x.func, self.fixturestack))\n msg = self.msg\n if msg is not None:\n # the last fixture raise an error, let's present\n # it at the requesting side\n stack = stack[:-1]\n for function in stack:\n fspath, lineno = getfslineno(function)\n try:\n lines, _ = inspect.getsourcelines(get_real_func(function))\n except (IOError, IndexError, TypeError):\n error_msg = \"file %s, line %s: source code not available\"\n addline(error_msg % (fspath, lineno + 1))\n else:\n addline(\"file %s, line %s\" % (fspath, lineno + 1))\n for i, line in enumerate(lines):\n line = line.rstrip()\n addline(\" \" + line)\n if line.lstrip().startswith(\"def\"):\n break\n\n if msg is None:\n fm = self.request._fixturemanager\n available = set()\n parentid = self.request._pyfuncitem.parent.nodeid\n for name, fixturedefs in fm._arg2fixturedefs.items():\n faclist = list(fm._matchfactories(fixturedefs, parentid))\n if faclist:\n available.add(name)\n if self.argname in available:\n msg = \" recursive dependency involving fixture '{}' detected\".format(\n self.argname\n )\n else:\n msg = \"fixture '{}' not found\".format(self.argname)\n msg += \"\\n available fixtures: {}\".format(\", \".join(sorted(available)))\n msg += \"\\n use 'pytest --fixtures [testpath]' for help on them.\"\n\n return FixtureLookupErrorRepr(fspath, lineno, tblines, msg, self.argname)"},{"col":25,"endLoc":712,"id":1819,"nodeType":"Lambda","startLoc":712,"text":"lambda x: x.func"},{"col":0,"comment":"null","endLoc":17,"header":"@pytest.fixture\ndef b(a)","id":1820,"name":"b","nodeType":"Function","startLoc":15,"text":"@pytest.fixture\ndef b(a):\n pass"},{"col":0,"comment":"null","endLoc":21,"header":"def test(b, request)","id":1821,"name":"test","nodeType":"Function","startLoc":20,"text":"def test(b, request):\n assert request.fixturenames == [\"b\", \"request\", \"a\", \"dynamic\"]"},{"col":0,"comment":"\n Records a new ```` tag as child of the root ````. This is suitable to\n writing global information regarding the entire test suite, and is compatible with ``xunit2`` JUnit family.\n\n This is a ``session``-scoped fixture which is called with ``(name, value)``. Example:\n\n .. code-block:: python\n\n def test_foo(record_testsuite_property):\n record_testsuite_property(\"ARCH\", \"PPC\")\n record_testsuite_property(\"STORAGE_TYPE\", \"CEPH\")\n\n ``name`` must be a string, ``value`` will be converted to a string and properly xml-escaped.\n ","endLoc":388,"header":"@pytest.fixture(scope=\"session\")\ndef record_testsuite_property(request)","id":1822,"name":"record_testsuite_property","nodeType":"Function","startLoc":361,"text":"@pytest.fixture(scope=\"session\")\ndef record_testsuite_property(request):\n \"\"\"\n Records a new ```` tag as child of the root ````. This is suitable to\n writing global information regarding the entire test suite, and is compatible with ``xunit2`` JUnit family.\n\n This is a ``session``-scoped fixture which is called with ``(name, value)``. Example:\n\n .. code-block:: python\n\n def test_foo(record_testsuite_property):\n record_testsuite_property(\"ARCH\", \"PPC\")\n record_testsuite_property(\"STORAGE_TYPE\", \"CEPH\")\n\n ``name`` must be a string, ``value`` will be converted to a string and properly xml-escaped.\n \"\"\"\n\n __tracebackhide__ = True\n\n def record_func(name, value):\n \"\"\"noop function in case --junitxml was not passed in the command-line\"\"\"\n __tracebackhide__ = True\n _check_record_param_type(\"name\", name)\n\n xml = getattr(request.config, \"_xml\", None)\n if xml is not None:\n record_func = xml.add_global_property # noqa\n return record_func"},{"col":4,"comment":"null","endLoc":499,"header":"def consider_preparse(self, args)","id":1823,"name":"consider_preparse","nodeType":"Function","startLoc":482,"text":"def consider_preparse(self, args):\n i = 0\n n = len(args)\n while i < n:\n opt = args[i]\n i += 1\n if isinstance(opt, six.string_types):\n if opt == \"-p\":\n try:\n parg = args[i]\n except IndexError:\n return\n i += 1\n elif opt.startswith(\"-p\"):\n parg = opt[2:]\n else:\n continue\n self.consider_pluginarg(parg)"},{"col":4,"comment":"null","endLoc":524,"header":"def consider_pluginarg(self, arg)","id":1824,"name":"consider_pluginarg","nodeType":"Function","startLoc":501,"text":"def consider_pluginarg(self, arg):\n if arg.startswith(\"no:\"):\n name = arg[3:]\n if name in essential_plugins:\n raise UsageError(\"plugin %s cannot be disabled\" % name)\n\n # PR #4304 : remove stepwise if cacheprovider is blocked\n if name == \"cacheprovider\":\n self.set_blocked(\"stepwise\")\n self.set_blocked(\"pytest_stepwise\")\n\n self.set_blocked(name)\n if not name.startswith(\"pytest_\"):\n self.set_blocked(\"pytest_\" + name)\n else:\n name = arg\n # Unblock the plugin. None indicates that it has been blocked.\n # There is no interface with pluggy for this.\n if self._name2plugin.get(name, -1) is None:\n del self._name2plugin[name]\n if not name.startswith(\"pytest_\"):\n if self._name2plugin.get(\"pytest_\" + name, -1) is None:\n del self._name2plugin[\"pytest_\" + name]\n self.import_plugin(arg, consider_entry_points=True)"},{"col":4,"comment":"null","endLoc":799,"header":"def test_parametrize_twoargs(self)","id":1825,"name":"test_parametrize_twoargs","nodeType":"Function","startLoc":792,"text":"def test_parametrize_twoargs(self):\n metafunc = self.Metafunc(lambda x, y: None)\n metafunc.parametrize((\"x\", \"y\"), [(1, 2), (3, 4)])\n assert len(metafunc._calls) == 2\n assert metafunc._calls[0].funcargs == dict(x=1, y=2)\n assert metafunc._calls[0].id == \"1-2\"\n assert metafunc._calls[1].funcargs == dict(x=3, y=4)\n assert metafunc._calls[1].id == \"3-4\""},{"col":33,"endLoc":793,"id":1826,"nodeType":"Lambda","startLoc":793,"text":"lambda x, y: None"},{"col":4,"comment":"null","endLoc":530,"header":"def consider_env(self)","id":1827,"name":"consider_env","nodeType":"Function","startLoc":529,"text":"def consider_env(self):\n self._import_plugin_specs(os.environ.get(\"PYTEST_PLUGINS\"))"},{"col":4,"comment":"\n Return the tolerance for the comparison. This could be either an\n absolute tolerance or a relative tolerance, depending on what the user\n specified or which would be larger.\n ","endLoc":338,"header":"@property\n def tolerance(self)","id":1830,"name":"tolerance","nodeType":"Function","startLoc":293,"text":"@property\n def tolerance(self):\n \"\"\"\n Return the tolerance for the comparison. This could be either an\n absolute tolerance or a relative tolerance, depending on what the user\n specified or which would be larger.\n \"\"\"\n\n def set_default(x, default):\n return x if x is not None else default\n\n # Figure out what the absolute tolerance should be. ``self.abs`` is\n # either None or a value specified by the user.\n absolute_tolerance = set_default(self.abs, self.DEFAULT_ABSOLUTE_TOLERANCE)\n\n if absolute_tolerance < 0:\n raise ValueError(\n \"absolute tolerance can't be negative: {}\".format(absolute_tolerance)\n )\n if math.isnan(absolute_tolerance):\n raise ValueError(\"absolute tolerance can't be NaN.\")\n\n # If the user specified an absolute tolerance but not a relative one,\n # just return the absolute tolerance.\n if self.rel is None:\n if self.abs is not None:\n return absolute_tolerance\n\n # Figure out what the relative tolerance should be. ``self.rel`` is\n # either None or a value specified by the user. This is done after\n # we've made sure the user didn't ask for an absolute tolerance only,\n # because we don't want to raise errors about the relative tolerance if\n # we aren't even going to use it.\n relative_tolerance = set_default(\n self.rel, self.DEFAULT_RELATIVE_TOLERANCE\n ) * abs(self.expected)\n\n if relative_tolerance < 0:\n raise ValueError(\n \"relative tolerance can't be negative: {}\".format(absolute_tolerance)\n )\n if math.isnan(relative_tolerance):\n raise ValueError(\"relative tolerance can't be NaN.\")\n\n # Return the larger of the relative and absolute tolerances.\n return max(relative_tolerance, absolute_tolerance)"},{"col":0,"comment":"null","endLoc":435,"header":"def pytest_addoption(parser)","id":1832,"name":"pytest_addoption","nodeType":"Function","startLoc":391,"text":"def pytest_addoption(parser):\n group = parser.getgroup(\"terminal reporting\")\n group.addoption(\n \"--junitxml\",\n \"--junit-xml\",\n action=\"store\",\n dest=\"xmlpath\",\n metavar=\"path\",\n type=functools.partial(filename_arg, optname=\"--junitxml\"),\n default=None,\n help=\"create junit-xml style report file at given path.\",\n )\n group.addoption(\n \"--junitprefix\",\n \"--junit-prefix\",\n action=\"store\",\n metavar=\"str\",\n default=None,\n help=\"prepend prefix to classnames in junit-xml output\",\n )\n parser.addini(\n \"junit_suite_name\", \"Test suite name for JUnit report\", default=\"pytest\"\n )\n parser.addini(\n \"junit_logging\",\n \"Write captured log messages to JUnit report: \"\n \"one of no|system-out|system-err\",\n default=\"no\",\n ) # choices=['no', 'stdout', 'stderr'])\n parser.addini(\n \"junit_log_passing_tests\",\n \"Capture log information for passing tests to JUnit report: \",\n type=\"bool\",\n default=True,\n )\n parser.addini(\n \"junit_duration_report\",\n \"Duration time to report: one of total|call\",\n default=\"total\",\n ) # choices=['total', 'call'])\n parser.addini(\n \"junit_family\",\n \"Emit XML for schema: one of legacy|xunit1|xunit2\",\n default=\"xunit1\",\n )"},{"attributeType":"float","col":4,"comment":"null","endLoc":229,"id":1833,"name":"DEFAULT_ABSOLUTE_TOLERANCE","nodeType":"Attribute","startLoc":229,"text":"DEFAULT_ABSOLUTE_TOLERANCE"},{"attributeType":"float","col":4,"comment":"null","endLoc":230,"id":1834,"name":"DEFAULT_RELATIVE_TOLERANCE","nodeType":"Attribute","startLoc":230,"text":"DEFAULT_RELATIVE_TOLERANCE"},{"attributeType":"None","col":4,"comment":"null","endLoc":291,"id":1835,"name":"__hash__","nodeType":"Attribute","startLoc":291,"text":"__hash__"},{"className":"ApproxDecimal","col":0,"comment":"\n Perform approximate comparisons where the expected value is a decimal.\n ","endLoc":347,"id":1836,"nodeType":"Class","startLoc":341,"text":"class ApproxDecimal(ApproxScalar):\n \"\"\"\n Perform approximate comparisons where the expected value is a decimal.\n \"\"\"\n\n DEFAULT_ABSOLUTE_TOLERANCE = Decimal(\"1e-12\")\n DEFAULT_RELATIVE_TOLERANCE = Decimal(\"1e-6\")"},{"attributeType":"Decimal","col":4,"comment":"null","endLoc":346,"id":1837,"name":"DEFAULT_ABSOLUTE_TOLERANCE","nodeType":"Attribute","startLoc":346,"text":"DEFAULT_ABSOLUTE_TOLERANCE"},{"col":4,"comment":"null","endLoc":816,"header":"def test_parametrize_multiple_times(self, testdir)","id":1838,"name":"test_parametrize_multiple_times","nodeType":"Function","startLoc":801,"text":"def test_parametrize_multiple_times(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n pytestmark = pytest.mark.parametrize(\"x\", [1,2])\n def test_func(x):\n assert 0, x\n class TestClass(object):\n pytestmark = pytest.mark.parametrize(\"y\", [3,4])\n def test_meth(self, x, y):\n assert 0, x\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.assert_outcomes(failed=6)"},{"col":4,"comment":"null","endLoc":828,"header":"def test_parametrize_CSV(self, testdir)","id":1839,"name":"test_parametrize_CSV","nodeType":"Function","startLoc":818,"text":"def test_parametrize_CSV(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize(\"x, y,\", [(1,2), (2,3)])\n def test_func(x, y):\n assert x+1 == y\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)"},{"attributeType":"null","col":8,"comment":"null","endLoc":226,"id":1840,"name":"_conftest_plugins","nodeType":"Attribute","startLoc":226,"text":"self._conftest_plugins"},{"attributeType":"null","col":8,"comment":"null","endLoc":248,"id":1841,"name":"rewrite_hook","nodeType":"Attribute","startLoc":248,"text":"self.rewrite_hook"},{"col":4,"comment":"null","endLoc":870,"header":"def test_parametrize_class_scenarios(self, testdir)","id":1842,"name":"test_parametrize_class_scenarios","nodeType":"Function","startLoc":830,"text":"def test_parametrize_class_scenarios(self, testdir):\n testdir.makepyfile(\n \"\"\"\n # same as doc/en/example/parametrize scenario example\n def pytest_generate_tests(metafunc):\n idlist = []\n argvalues = []\n for scenario in metafunc.cls.scenarios:\n idlist.append(scenario[0])\n items = scenario[1].items()\n argnames = [x[0] for x in items]\n argvalues.append(([x[1] for x in items]))\n metafunc.parametrize(argnames, argvalues, ids=idlist, scope=\"class\")\n\n class Test(object):\n scenarios = [['1', {'arg': {1: 2}, \"arg2\": \"value2\"}],\n ['2', {'arg':'value2', \"arg2\": \"value2\"}]]\n\n def test_1(self, arg, arg2):\n pass\n\n def test_2(self, arg2, arg):\n pass\n\n def test_3(self, arg, arg2):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n \"\"\"\n *test_1*1*\n *test_2*1*\n *test_3*1*\n *test_1*2*\n *test_2*2*\n *test_3*2*\n *6 passed*\n \"\"\"\n )"},{"attributeType":"null","col":8,"comment":"null","endLoc":250,"id":1843,"name":"_configured","nodeType":"Attribute","startLoc":250,"text":"self._configured"},{"col":4,"comment":"null","endLoc":891,"header":"def test_format_args(self)","id":1844,"name":"test_format_args","nodeType":"Function","startLoc":872,"text":"def test_format_args(self):\n def function1():\n pass\n\n assert fixtures._format_args(function1) == \"()\"\n\n def function2(arg1):\n pass\n\n assert fixtures._format_args(function2) == \"(arg1)\"\n\n def function3(arg1, arg2=\"qwe\"):\n pass\n\n assert fixtures._format_args(function3) == \"(arg1, arg2='qwe')\"\n\n def function4(arg1, *args, **kwargs):\n pass\n\n assert fixtures._format_args(function4) == \"(arg1, *args, **kwargs)\""},{"attributeType":"null","col":8,"comment":"null","endLoc":372,"id":1845,"name":"_using_pyargs","nodeType":"Attribute","startLoc":372,"text":"self._using_pyargs"},{"attributeType":"Decimal","col":4,"comment":"null","endLoc":347,"id":1846,"name":"DEFAULT_RELATIVE_TOLERANCE","nodeType":"Attribute","startLoc":347,"text":"DEFAULT_RELATIVE_TOLERANCE"},{"attributeType":"null","col":8,"comment":"null","endLoc":233,"id":1847,"name":"_duplicatepaths","nodeType":"Attribute","startLoc":233,"text":"self._duplicatepaths"},{"className":"TestMetafuncFunctional","col":0,"comment":"null","endLoc":1327,"id":1848,"nodeType":"Class","startLoc":894,"text":"class TestMetafuncFunctional(object):\n def test_attributes(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n # assumes that generate/provide runs in the same process\n import sys, pytest, six\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('metafunc', [metafunc])\n\n @pytest.fixture\n def metafunc(request):\n return request.param\n\n def test_function(metafunc, pytestconfig):\n assert metafunc.config == pytestconfig\n assert metafunc.module.__name__ == __name__\n assert metafunc.function == test_function\n assert metafunc.cls is None\n\n class TestClass(object):\n def test_method(self, metafunc, pytestconfig):\n assert metafunc.config == pytestconfig\n assert metafunc.module.__name__ == __name__\n unbound = six.get_unbound_function(TestClass.test_method)\n assert metafunc.function == unbound\n assert metafunc.cls == TestClass\n \"\"\"\n )\n result = testdir.runpytest(p, \"-v\", SHOW_PYTEST_WARNINGS_ARG)\n result.assert_outcomes(passed=2)\n\n def test_two_functions(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('arg1', [10, 20], ids=['0', '1'])\n\n def test_func1(arg1):\n assert arg1 == 10\n\n def test_func2(arg1):\n assert arg1 in (10, 20)\n \"\"\"\n )\n result = testdir.runpytest(\"-v\", p, SHOW_PYTEST_WARNINGS_ARG)\n result.stdout.fnmatch_lines(\n [\n \"*test_func1*0*PASS*\",\n \"*test_func1*1*FAIL*\",\n \"*test_func2*PASS*\",\n \"*test_func2*PASS*\",\n \"*1 failed, 3 passed*\",\n ]\n )\n\n def test_noself_in_method(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n assert 'xyz' not in metafunc.fixturenames\n\n class TestHello(object):\n def test_hello(xyz):\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.assert_outcomes(passed=1)\n\n def test_generate_tests_in_class(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n class TestClass(object):\n def pytest_generate_tests(self, metafunc):\n metafunc.parametrize('hello', ['world'], ids=['hellow'])\n\n def test_myfunc(self, hello):\n assert hello == \"world\"\n \"\"\"\n )\n result = testdir.runpytest(\"-v\", p, SHOW_PYTEST_WARNINGS_ARG)\n result.stdout.fnmatch_lines([\"*test_myfunc*hello*PASS*\", \"*1 passed*\"])\n\n def test_two_functions_not_same_instance(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('arg1', [10, 20], ids=[\"0\", \"1\"])\n\n class TestClass(object):\n def test_func(self, arg1):\n assert not hasattr(self, 'x')\n self.x = 1\n \"\"\"\n )\n result = testdir.runpytest(\"-v\", p, SHOW_PYTEST_WARNINGS_ARG)\n result.stdout.fnmatch_lines(\n [\"*test_func*0*PASS*\", \"*test_func*1*PASS*\", \"*2 pass*\"]\n )\n\n def test_issue28_setup_method_in_generate_tests(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('arg1', [1])\n\n class TestClass(object):\n def test_method(self, arg1):\n assert arg1 == self.val\n def setup_method(self, func):\n self.val = 1\n \"\"\"\n )\n result = testdir.runpytest(p, SHOW_PYTEST_WARNINGS_ARG)\n result.assert_outcomes(passed=1)\n\n def test_parametrize_functional2(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n metafunc.parametrize(\"arg1\", [1,2])\n metafunc.parametrize(\"arg2\", [4,5])\n def test_hello(arg1, arg2):\n assert 0, (arg1, arg2)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"*(1, 4)*\", \"*(1, 5)*\", \"*(2, 4)*\", \"*(2, 5)*\", \"*4 failed*\"]\n )\n\n def test_parametrize_and_inner_getfixturevalue(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n metafunc.parametrize(\"arg1\", [1], indirect=True)\n metafunc.parametrize(\"arg2\", [10], indirect=True)\n\n import pytest\n @pytest.fixture\n def arg1(request):\n x = request.getfixturevalue(\"arg2\")\n return x + request.param\n\n @pytest.fixture\n def arg2(request):\n return request.param\n\n def test_func1(arg1, arg2):\n assert arg1 == 11\n \"\"\"\n )\n result = testdir.runpytest(\"-v\", p)\n result.stdout.fnmatch_lines([\"*test_func1*1*PASS*\", \"*1 passed*\"])\n\n def test_parametrize_on_setup_arg(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n assert \"arg1\" in metafunc.fixturenames\n metafunc.parametrize(\"arg1\", [1], indirect=True)\n\n import pytest\n @pytest.fixture\n def arg1(request):\n return request.param\n\n @pytest.fixture\n def arg2(request, arg1):\n return 10 * arg1\n\n def test_func(arg2):\n assert arg2 == 10\n \"\"\"\n )\n result = testdir.runpytest(\"-v\", p)\n result.stdout.fnmatch_lines([\"*test_func*1*PASS*\", \"*1 passed*\"])\n\n def test_parametrize_with_ids(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style=classic\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n metafunc.parametrize((\"a\", \"b\"), [(1,1), (1,2)],\n ids=[\"basic\", \"advanced\"])\n\n def test_function(a, b):\n assert a == b\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n assert result.ret == 1\n result.stdout.fnmatch_lines_random(\n [\"*test_function*basic*PASSED\", \"*test_function*advanced*FAILED\"]\n )\n\n def test_parametrize_without_ids(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n metafunc.parametrize((\"a\", \"b\"),\n [(1,object()), (1.3,object())])\n\n def test_function(a, b):\n assert 1\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *test_function*1-b0*\n *test_function*1.3-b1*\n \"\"\"\n )\n\n def test_parametrize_with_None_in_ids(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n metafunc.parametrize((\"a\", \"b\"), [(1,1), (1,1), (1,2)],\n ids=[\"basic\", None, \"advanced\"])\n\n def test_function(a, b):\n assert a == b\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n assert result.ret == 1\n result.stdout.fnmatch_lines_random(\n [\n \"*test_function*basic*PASSED*\",\n \"*test_function*1-1*PASSED*\",\n \"*test_function*advanced*FAILED*\",\n ]\n )\n\n def test_fixture_parametrized_empty_ids(self, testdir):\n \"\"\"Fixtures parametrized with empty ids cause an internal error (#1849).\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"module\", ids=[], params=[])\n def temp(request):\n return request.param\n\n def test_temp(temp):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 skipped *\"])\n\n def test_parametrized_empty_ids(self, testdir):\n \"\"\"Tests parametrized with empty ids cause an internal error (#1849).\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize('temp', [], ids=list())\n def test_temp(temp):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 skipped *\"])\n\n def test_parametrized_ids_invalid_type(self, testdir):\n \"\"\"Tests parametrized with ids as non-strings (#1857).\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize(\"x, expected\", [(10, 20), (40, 80)], ids=(None, 2))\n def test_ids_numbers(x,expected):\n assert x * 2 == expected\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*In test_ids_numbers: ids must be list of strings, found: 2 (type: *'int'>)*\"\n ]\n )\n\n def test_parametrize_with_identical_ids_get_unique_names(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n metafunc.parametrize((\"a\", \"b\"), [(1,1), (1,2)],\n ids=[\"a\", \"a\"])\n\n def test_function(a, b):\n assert a == b\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n assert result.ret == 1\n result.stdout.fnmatch_lines_random(\n [\"*test_function*a0*PASSED*\", \"*test_function*a1*FAILED*\"]\n )\n\n @pytest.mark.parametrize((\"scope\", \"length\"), [(\"module\", 2), (\"function\", 4)])\n def test_parametrize_scope_overrides(self, testdir, scope, length):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n def pytest_generate_tests(metafunc):\n if \"arg\" in metafunc.funcargnames:\n metafunc.parametrize(\"arg\", [1,2], indirect=True,\n scope=%r)\n @pytest.fixture\n def arg(request):\n values.append(request.param)\n return request.param\n def test_hello(arg):\n assert arg in (1,2)\n def test_world(arg):\n assert arg in (1,2)\n def test_checklength():\n assert len(values) == %d\n \"\"\"\n % (scope, length)\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=5)\n\n def test_parametrize_issue323(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='module', params=range(966))\n def foo(request):\n return request.param\n\n def test_it(foo):\n pass\n def test_it2(foo):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(\"--collect-only\")\n assert not reprec.getcalls(\"pytest_internalerror\")\n\n def test_usefixtures_seen_in_generate_tests(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n assert \"abc\" in metafunc.fixturenames\n metafunc.parametrize(\"abc\", [1])\n\n @pytest.mark.usefixtures(\"abc\")\n def test_function():\n pass\n \"\"\"\n )\n reprec = testdir.runpytest()\n reprec.assert_outcomes(passed=1)\n\n def test_generate_tests_only_done_in_subdir(self, testdir):\n sub1 = testdir.mkpydir(\"sub1\")\n sub2 = testdir.mkpydir(\"sub2\")\n sub1.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def pytest_generate_tests(metafunc):\n assert metafunc.function.__name__ == \"test_1\"\n \"\"\"\n )\n )\n sub2.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def pytest_generate_tests(metafunc):\n assert metafunc.function.__name__ == \"test_2\"\n \"\"\"\n )\n )\n sub1.join(\"test_in_sub1.py\").write(\"def test_1(): pass\")\n sub2.join(\"test_in_sub2.py\").write(\"def test_2(): pass\")\n result = testdir.runpytest(\"--keep-duplicates\", \"-v\", \"-s\", sub1, sub2, sub1)\n result.assert_outcomes(passed=3)\n\n def test_generate_same_function_names_issue403(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n def make_tests():\n @pytest.mark.parametrize(\"x\", range(2))\n def test_foo(x):\n pass\n return test_foo\n\n test_x = make_tests()\n test_y = make_tests()\n \"\"\"\n )\n reprec = testdir.runpytest()\n reprec.assert_outcomes(passed=4)\n\n @pytest.mark.parametrize(\"attr\", [\"parametrise\", \"parameterize\", \"parameterise\"])\n def test_parametrize_misspelling(self, testdir, attr):\n \"\"\"#463\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.{}(\"x\", range(2))\n def test_foo(x):\n pass\n \"\"\".format(\n attr\n )\n )\n result = testdir.runpytest(\"--collectonly\")\n result.stdout.fnmatch_lines(\n [\n \"test_foo has '{}' mark, spelling should be 'parametrize'\".format(attr),\n \"*1 error in*\",\n ]\n )"},{"attributeType":"null","col":8,"comment":"null","endLoc":231,"id":1849,"name":"_confcutdir","nodeType":"Attribute","startLoc":231,"text":"self._confcutdir"},{"attributeType":"null","col":8,"comment":"null","endLoc":230,"id":1850,"name":"_conftestpath2mod","nodeType":"Attribute","startLoc":230,"text":"self._conftestpath2mod"},{"attributeType":"null","col":8,"comment":"null","endLoc":229,"id":1851,"name":"_dirpath2confmods","nodeType":"Attribute","startLoc":229,"text":"self._dirpath2confmods"},{"attributeType":"null","col":8,"comment":"null","endLoc":232,"id":1852,"name":"_noconftest","nodeType":"Attribute","startLoc":232,"text":"self._noconftest"},{"attributeType":"null","col":0,"comment":"null","endLoc":34,"id":1853,"name":"EXIT_NOTESTSCOLLECTED","nodeType":"Attribute","startLoc":34,"text":"EXIT_NOTESTSCOLLECTED"},{"className":"RaisesContext","col":0,"comment":"null","endLoc":743,"id":1854,"nodeType":"Class","startLoc":722,"text":"class RaisesContext(object):\n def __init__(self, expected_exception, message, match_expr):\n self.expected_exception = expected_exception\n self.message = message\n self.match_expr = match_expr\n self.excinfo = None\n\n def __enter__(self):\n self.excinfo = _pytest._code.ExceptionInfo.for_later()\n return self.excinfo\n\n def __exit__(self, *tp):\n __tracebackhide__ = True\n if tp[0] is None:\n fail(self.message)\n self.excinfo.__init__(tp)\n suppress_exception = issubclass(self.excinfo.type, self.expected_exception)\n if sys.version_info[0] == 2 and suppress_exception:\n sys.exc_clear()\n if self.match_expr is not None and suppress_exception:\n self.excinfo.match(self.match_expr)\n return suppress_exception"},{"col":4,"comment":"null","endLoc":923,"header":"def test_attributes(self, testdir)","id":1855,"name":"test_attributes","nodeType":"Function","startLoc":895,"text":"def test_attributes(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n # assumes that generate/provide runs in the same process\n import sys, pytest, six\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('metafunc', [metafunc])\n\n @pytest.fixture\n def metafunc(request):\n return request.param\n\n def test_function(metafunc, pytestconfig):\n assert metafunc.config == pytestconfig\n assert metafunc.module.__name__ == __name__\n assert metafunc.function == test_function\n assert metafunc.cls is None\n\n class TestClass(object):\n def test_method(self, metafunc, pytestconfig):\n assert metafunc.config == pytestconfig\n assert metafunc.module.__name__ == __name__\n unbound = six.get_unbound_function(TestClass.test_method)\n assert metafunc.function == unbound\n assert metafunc.cls == TestClass\n \"\"\"\n )\n result = testdir.runpytest(p, \"-v\", SHOW_PYTEST_WARNINGS_ARG)\n result.assert_outcomes(passed=2)"},{"attributeType":"Logger","col":0,"comment":"null","endLoc":6,"id":1856,"name":"logger","nodeType":"Attribute","startLoc":6,"text":"logger"},{"attributeType":"Logger","col":0,"comment":"null","endLoc":7,"id":1857,"name":"sublogger","nodeType":"Attribute","startLoc":7,"text":"sublogger"},{"col":0,"comment":"","endLoc":2,"header":"test_fixture.py#","id":1858,"name":"","nodeType":"Function","startLoc":2,"text":"logger = logging.getLogger(__name__)\n\nsublogger = logging.getLogger(__name__ + \".baz\")"},{"className":"TestPytestPluginInteractions","col":0,"comment":"null","endLoc":141,"id":1860,"nodeType":"Class","startLoc":22,"text":"class TestPytestPluginInteractions(object):\n def test_addhooks_conftestplugin(self, testdir, _config_for_test):\n testdir.makepyfile(\n newhooks=\"\"\"\n def pytest_myhook(xyz):\n \"new hook\"\n \"\"\"\n )\n conf = testdir.makeconftest(\n \"\"\"\n import newhooks\n def pytest_addhooks(pluginmanager):\n pluginmanager.add_hookspecs(newhooks)\n def pytest_myhook(xyz):\n return xyz + 1\n \"\"\"\n )\n config = _config_for_test\n pm = config.pluginmanager\n pm.hook.pytest_addhooks.call_historic(\n kwargs=dict(pluginmanager=config.pluginmanager)\n )\n config.pluginmanager._importconftest(conf)\n # print(config.pluginmanager.get_plugins())\n res = config.hook.pytest_myhook(xyz=10)\n assert res == [11]\n\n def test_addhooks_nohooks(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import sys\n def pytest_addhooks(pluginmanager):\n pluginmanager.add_hookspecs(sys)\n \"\"\"\n )\n res = testdir.runpytest()\n assert res.ret != 0\n res.stderr.fnmatch_lines([\"*did not find*sys*\"])\n\n def test_do_option_postinitialize(self, testdir):\n config = testdir.parseconfigure()\n assert not hasattr(config.option, \"test123\")\n p = testdir.makepyfile(\n \"\"\"\n def pytest_addoption(parser):\n parser.addoption('--test123', action=\"store_true\",\n default=True)\n \"\"\"\n )\n config.pluginmanager._importconftest(p)\n assert config.option.test123\n\n def test_configure(self, testdir):\n config = testdir.parseconfig()\n values = []\n\n class A(object):\n def pytest_configure(self, config):\n values.append(self)\n\n config.pluginmanager.register(A())\n assert len(values) == 0\n config._do_configure()\n assert len(values) == 1\n config.pluginmanager.register(A()) # leads to a configured() plugin\n assert len(values) == 2\n assert values[0] != values[1]\n\n config._ensure_unconfigure()\n config.pluginmanager.register(A())\n assert len(values) == 2\n\n def test_hook_tracing(self, _config_for_test):\n pytestpm = _config_for_test.pluginmanager # fully initialized with plugins\n saveindent = []\n\n class api1(object):\n def pytest_plugin_registered(self):\n saveindent.append(pytestpm.trace.root.indent)\n\n class api2(object):\n def pytest_plugin_registered(self):\n saveindent.append(pytestpm.trace.root.indent)\n raise ValueError()\n\n values = []\n pytestpm.trace.root.setwriter(values.append)\n undo = pytestpm.enable_tracing()\n try:\n indent = pytestpm.trace.root.indent\n p = api1()\n pytestpm.register(p)\n assert pytestpm.trace.root.indent == indent\n assert len(values) >= 2\n assert \"pytest_plugin_registered\" in values[0]\n assert \"finish\" in values[1]\n\n values[:] = []\n with pytest.raises(ValueError):\n pytestpm.register(api2())\n assert pytestpm.trace.root.indent == indent\n assert saveindent[0] > indent\n finally:\n undo()\n\n def test_hook_proxy(self, testdir):\n \"\"\"Test the gethookproxy function(#2016)\"\"\"\n config = testdir.parseconfig()\n session = Session(config)\n testdir.makepyfile(**{\"tests/conftest.py\": \"\", \"tests/subdir/conftest.py\": \"\"})\n\n conftest1 = testdir.tmpdir.join(\"tests/conftest.py\")\n conftest2 = testdir.tmpdir.join(\"tests/subdir/conftest.py\")\n\n config.pluginmanager._importconftest(conftest1)\n ihook_a = session.gethookproxy(testdir.tmpdir.join(\"tests\"))\n assert ihook_a is not None\n config.pluginmanager._importconftest(conftest2)\n ihook_b = session.gethookproxy(testdir.tmpdir.join(\"tests\"))\n assert ihook_a is not ihook_b"},{"col":4,"comment":"null","endLoc":731,"header":"def __enter__(self)","id":1861,"name":"__enter__","nodeType":"Function","startLoc":729,"text":"def __enter__(self):\n self.excinfo = _pytest._code.ExceptionInfo.for_later()\n return self.excinfo"},{"col":4,"comment":"null","endLoc":947,"header":"def test_two_functions(self, testdir)","id":1862,"name":"test_two_functions","nodeType":"Function","startLoc":925,"text":"def test_two_functions(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('arg1', [10, 20], ids=['0', '1'])\n\n def test_func1(arg1):\n assert arg1 == 10\n\n def test_func2(arg1):\n assert arg1 in (10, 20)\n \"\"\"\n )\n result = testdir.runpytest(\"-v\", p, SHOW_PYTEST_WARNINGS_ARG)\n result.stdout.fnmatch_lines(\n [\n \"*test_func1*0*PASS*\",\n \"*test_func1*1*FAIL*\",\n \"*test_func2*PASS*\",\n \"*test_func2*PASS*\",\n \"*1 failed, 3 passed*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":47,"header":"def test_addhooks_conftestplugin(self, testdir, _config_for_test)","id":1863,"name":"test_addhooks_conftestplugin","nodeType":"Function","startLoc":23,"text":"def test_addhooks_conftestplugin(self, testdir, _config_for_test):\n testdir.makepyfile(\n newhooks=\"\"\"\n def pytest_myhook(xyz):\n \"new hook\"\n \"\"\"\n )\n conf = testdir.makeconftest(\n \"\"\"\n import newhooks\n def pytest_addhooks(pluginmanager):\n pluginmanager.add_hookspecs(newhooks)\n def pytest_myhook(xyz):\n return xyz + 1\n \"\"\"\n )\n config = _config_for_test\n pm = config.pluginmanager\n pm.hook.pytest_addhooks.call_historic(\n kwargs=dict(pluginmanager=config.pluginmanager)\n )\n config.pluginmanager._importconftest(conf)\n # print(config.pluginmanager.get_plugins())\n res = config.hook.pytest_myhook(xyz=10)\n assert res == [11]"},{"col":4,"comment":"null","endLoc":961,"header":"def test_noself_in_method(self, testdir)","id":1864,"name":"test_noself_in_method","nodeType":"Function","startLoc":949,"text":"def test_noself_in_method(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n assert 'xyz' not in metafunc.fixturenames\n\n class TestHello(object):\n def test_hello(xyz):\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.assert_outcomes(passed=1)"},{"col":4,"comment":"return an unfilled ExceptionInfo\n ","endLoc":431,"header":"@classmethod\n def for_later(cls)","id":1865,"name":"for_later","nodeType":"Function","startLoc":427,"text":"@classmethod\n def for_later(cls):\n \"\"\"return an unfilled ExceptionInfo\n \"\"\"\n return cls(None)"},{"col":4,"comment":"null","endLoc":975,"header":"def test_generate_tests_in_class(self, testdir)","id":1866,"name":"test_generate_tests_in_class","nodeType":"Function","startLoc":963,"text":"def test_generate_tests_in_class(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n class TestClass(object):\n def pytest_generate_tests(self, metafunc):\n metafunc.parametrize('hello', ['world'], ids=['hellow'])\n\n def test_myfunc(self, hello):\n assert hello == \"world\"\n \"\"\"\n )\n result = testdir.runpytest(\"-v\", p, SHOW_PYTEST_WARNINGS_ARG)\n result.stdout.fnmatch_lines([\"*test_myfunc*hello*PASS*\", \"*1 passed*\"])"},{"col":4,"comment":"null","endLoc":992,"header":"def test_two_functions_not_same_instance(self, testdir)","id":1867,"name":"test_two_functions_not_same_instance","nodeType":"Function","startLoc":977,"text":"def test_two_functions_not_same_instance(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('arg1', [10, 20], ids=[\"0\", \"1\"])\n\n class TestClass(object):\n def test_func(self, arg1):\n assert not hasattr(self, 'x')\n self.x = 1\n \"\"\"\n )\n result = testdir.runpytest(\"-v\", p, SHOW_PYTEST_WARNINGS_ARG)\n result.stdout.fnmatch_lines(\n [\"*test_func*0*PASS*\", \"*test_func*1*PASS*\", \"*2 pass*\"]\n )"},{"id":1868,"name":"sidebarintro.html","nodeType":"TextFile","path":"doc/en/_templates","text":"

About pytest

\n

\n pytest is a mature full-featured Python testing tool that helps\n you write better programs.\n

\n"},{"col":4,"comment":"null","endLoc":1008,"header":"def test_issue28_setup_method_in_generate_tests(self, testdir)","id":1869,"name":"test_issue28_setup_method_in_generate_tests","nodeType":"Function","startLoc":994,"text":"def test_issue28_setup_method_in_generate_tests(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('arg1', [1])\n\n class TestClass(object):\n def test_method(self, arg1):\n assert arg1 == self.val\n def setup_method(self, func):\n self.val = 1\n \"\"\"\n )\n result = testdir.runpytest(p, SHOW_PYTEST_WARNINGS_ARG)\n result.assert_outcomes(passed=1)"},{"col":4,"comment":"null","endLoc":743,"header":"def __exit__(self, *tp)","id":1870,"name":"__exit__","nodeType":"Function","startLoc":733,"text":"def __exit__(self, *tp):\n __tracebackhide__ = True\n if tp[0] is None:\n fail(self.message)\n self.excinfo.__init__(tp)\n suppress_exception = issubclass(self.excinfo.type, self.expected_exception)\n if sys.version_info[0] == 2 and suppress_exception:\n sys.exc_clear()\n if self.match_expr is not None and suppress_exception:\n self.excinfo.match(self.match_expr)\n return suppress_exception"},{"col":4,"comment":"null","endLoc":1023,"header":"def test_parametrize_functional2(self, testdir)","id":1871,"name":"test_parametrize_functional2","nodeType":"Function","startLoc":1010,"text":"def test_parametrize_functional2(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n metafunc.parametrize(\"arg1\", [1,2])\n metafunc.parametrize(\"arg2\", [4,5])\n def test_hello(arg1, arg2):\n assert 0, (arg1, arg2)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"*(1, 4)*\", \"*(1, 5)*\", \"*(2, 4)*\", \"*(2, 5)*\", \"*4 failed*\"]\n )"},{"col":4,"comment":"null","endLoc":1047,"header":"def test_parametrize_and_inner_getfixturevalue(self, testdir)","id":1872,"name":"test_parametrize_and_inner_getfixturevalue","nodeType":"Function","startLoc":1025,"text":"def test_parametrize_and_inner_getfixturevalue(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n metafunc.parametrize(\"arg1\", [1], indirect=True)\n metafunc.parametrize(\"arg2\", [10], indirect=True)\n\n import pytest\n @pytest.fixture\n def arg1(request):\n x = request.getfixturevalue(\"arg2\")\n return x + request.param\n\n @pytest.fixture\n def arg2(request):\n return request.param\n\n def test_func1(arg1, arg2):\n assert arg1 == 11\n \"\"\"\n )\n result = testdir.runpytest(\"-v\", p)\n result.stdout.fnmatch_lines([\"*test_func1*1*PASS*\", \"*1 passed*\"])"},{"col":4,"comment":"null","endLoc":1070,"header":"def test_parametrize_on_setup_arg(self, testdir)","id":1874,"name":"test_parametrize_on_setup_arg","nodeType":"Function","startLoc":1049,"text":"def test_parametrize_on_setup_arg(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n assert \"arg1\" in metafunc.fixturenames\n metafunc.parametrize(\"arg1\", [1], indirect=True)\n\n import pytest\n @pytest.fixture\n def arg1(request):\n return request.param\n\n @pytest.fixture\n def arg2(request, arg1):\n return 10 * arg1\n\n def test_func(arg2):\n assert arg2 == 10\n \"\"\"\n )\n result = testdir.runpytest(\"-v\", p)\n result.stdout.fnmatch_lines([\"*test_func*1*PASS*\", \"*1 passed*\"])"},{"col":0,"comment":"null","endLoc":451,"header":"def pytest_configure(config)","id":1876,"name":"pytest_configure","nodeType":"Function","startLoc":438,"text":"def pytest_configure(config):\n xmlpath = config.option.xmlpath\n # prevent opening xmllog on slave nodes (xdist)\n if xmlpath and not hasattr(config, \"slaveinput\"):\n config._xml = LogXML(\n xmlpath,\n config.option.junitprefix,\n config.getini(\"junit_suite_name\"),\n config.getini(\"junit_logging\"),\n config.getini(\"junit_duration_report\"),\n config.getini(\"junit_family\"),\n config.getini(\"junit_log_passing_tests\"),\n )\n config.pluginmanager.register(config._xml)"},{"col":4,"comment":"null","endLoc":1094,"header":"def test_parametrize_with_ids(self, testdir)","id":1877,"name":"test_parametrize_with_ids","nodeType":"Function","startLoc":1072,"text":"def test_parametrize_with_ids(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style=classic\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n metafunc.parametrize((\"a\", \"b\"), [(1,1), (1,2)],\n ids=[\"basic\", \"advanced\"])\n\n def test_function(a, b):\n assert a == b\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n assert result.ret == 1\n result.stdout.fnmatch_lines_random(\n [\"*test_function*basic*PASSED\", \"*test_function*advanced*FAILED\"]\n )"},{"col":0,"comment":"null","endLoc":458,"header":"def pytest_unconfigure(config)","id":1878,"name":"pytest_unconfigure","nodeType":"Function","startLoc":454,"text":"def pytest_unconfigure(config):\n xml = getattr(config, \"_xml\", None)\n if xml:\n del config._xml\n config.pluginmanager.unregister(xml)"},{"col":4,"comment":"null","endLoc":1114,"header":"def test_parametrize_without_ids(self, testdir)","id":1879,"name":"test_parametrize_without_ids","nodeType":"Function","startLoc":1096,"text":"def test_parametrize_without_ids(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n metafunc.parametrize((\"a\", \"b\"),\n [(1,object()), (1.3,object())])\n\n def test_function(a, b):\n assert 1\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *test_function*1-b0*\n *test_function*1.3-b1*\n \"\"\"\n )"},{"col":4,"comment":" Dynamically run a named fixture function.\n\n Declaring fixtures via function argument is recommended where possible.\n But if you can only decide whether to use another fixture at test\n setup time, you may use this function to retrieve it inside a fixture\n or test function body.\n ","endLoc":479,"header":"def getfixturevalue(self, argname)","id":1880,"name":"getfixturevalue","nodeType":"Function","startLoc":471,"text":"def getfixturevalue(self, argname):\n \"\"\" Dynamically run a named fixture function.\n\n Declaring fixtures via function argument is recommended where possible.\n But if you can only decide whether to use another fixture at test\n setup time, you may use this function to retrieve it inside a fixture\n or test function body.\n \"\"\"\n return self._get_active_fixturedef(argname).cached_result[0]"},{"col":4,"comment":"null","endLoc":504,"header":"def _get_active_fixturedef(self, argname)","id":1881,"name":"_get_active_fixturedef","nodeType":"Function","startLoc":488,"text":"def _get_active_fixturedef(self, argname):\n try:\n return self._fixture_defs[argname]\n except KeyError:\n try:\n fixturedef = self._getnextfixturedef(argname)\n except FixtureLookupError:\n if argname == \"request\":\n cached_result = (self, [0], None)\n scope = \"function\"\n return PseudoFixtureDef(cached_result, scope)\n raise\n # remove indent to prevent the python3 exception\n # from leaking into the call\n self._compute_fixture_value(fixturedef)\n self._fixture_defs[argname] = fixturedef\n return fixturedef"},{"col":4,"comment":"\n Creates a SubRequest based on \"self\" and calls the execute method of the given fixturedef object. This will\n force the FixtureDef object to throw away any previous results and compute a new fixture value, which\n will be stored into the FixtureDef object itself.\n\n :param FixtureDef fixturedef:\n ","endLoc":589,"header":"def _compute_fixture_value(self, fixturedef)","id":1882,"name":"_compute_fixture_value","nodeType":"Function","startLoc":517,"text":"def _compute_fixture_value(self, fixturedef):\n \"\"\"\n Creates a SubRequest based on \"self\" and calls the execute method of the given fixturedef object. This will\n force the FixtureDef object to throw away any previous results and compute a new fixture value, which\n will be stored into the FixtureDef object itself.\n\n :param FixtureDef fixturedef:\n \"\"\"\n # prepare a subrequest object before calling fixture function\n # (latter managed by fixturedef)\n argname = fixturedef.argname\n funcitem = self._pyfuncitem\n scope = fixturedef.scope\n try:\n param = funcitem.callspec.getparam(argname)\n except (AttributeError, ValueError):\n param = NOTSET\n param_index = 0\n has_params = fixturedef.params is not None\n fixtures_not_supported = getattr(funcitem, \"nofuncargs\", False)\n if has_params and fixtures_not_supported:\n msg = (\n \"{name} does not support fixtures, maybe unittest.TestCase subclass?\\n\"\n \"Node id: {nodeid}\\n\"\n \"Function type: {typename}\"\n ).format(\n name=funcitem.name,\n nodeid=funcitem.nodeid,\n typename=type(funcitem).__name__,\n )\n fail(msg, pytrace=False)\n if has_params:\n frame = inspect.stack()[3]\n frameinfo = inspect.getframeinfo(frame[0])\n source_path = frameinfo.filename\n source_lineno = frameinfo.lineno\n source_path = py.path.local(source_path)\n if source_path.relto(funcitem.config.rootdir):\n source_path = source_path.relto(funcitem.config.rootdir)\n msg = (\n \"The requested fixture has no parameter defined for test:\\n\"\n \" {}\\n\\n\"\n \"Requested fixture '{}' defined in:\\n{}\"\n \"\\n\\nRequested here:\\n{}:{}\".format(\n funcitem.nodeid,\n fixturedef.argname,\n getlocation(fixturedef.func, funcitem.config.rootdir),\n source_path,\n source_lineno,\n )\n )\n fail(msg, pytrace=False)\n else:\n param_index = funcitem.callspec.indices[argname]\n # if a parametrize invocation set a scope it will override\n # the static scope defined with the fixture function\n paramscopenum = funcitem.callspec._arg2scopenum.get(argname)\n if paramscopenum is not None:\n scope = scopes[paramscopenum]\n\n subrequest = SubRequest(self, scope, param, param_index, fixturedef)\n\n # check if a higher-level scoped fixture accesses a lower level one\n subrequest._check_scope(argname, self.scope, scope)\n\n # clear sys.exc_info before invoking the fixture (python bug?)\n # if it's not explicitly cleared it will leak into the call\n exc_clear()\n try:\n # call the fixture function\n fixturedef.execute(request=subrequest)\n finally:\n self._schedule_finalizers(fixturedef, subrequest)"},{"col":4,"comment":"null","endLoc":657,"header":"def __init__(self, request, scope, param, param_index, fixturedef)","id":1885,"name":"__init__","nodeType":"Function","startLoc":645,"text":"def __init__(self, request, scope, param, param_index, fixturedef):\n self._parent_request = request\n self.fixturename = fixturedef.argname\n if param is not NOTSET:\n self.param = param\n self.param_index = param_index\n self.scope = scope\n self._fixturedef = fixturedef\n self._pyfuncitem = request._pyfuncitem\n self._fixture_defs = request._fixture_defs\n self._arg2fixturedefs = request._arg2fixturedefs\n self._arg2index = request._arg2index\n self._fixturemanager = request._fixturemanager"},{"col":4,"comment":"null","endLoc":609,"header":"def _check_scope(self, argname, invoking_scope, requested_scope)","id":1886,"name":"_check_scope","nodeType":"Function","startLoc":597,"text":"def _check_scope(self, argname, invoking_scope, requested_scope):\n if argname == \"request\":\n return\n if scopemismatch(invoking_scope, requested_scope):\n # try to report something helpful\n lines = self._factorytraceback()\n fail(\n \"ScopeMismatch: You tried to access the %r scoped \"\n \"fixture %r with a %r scoped request object, \"\n \"involved factories\\n%s\"\n % ((requested_scope, argname, invoking_scope, \"\\n\".join(lines))),\n pytrace=False,\n )"},{"col":0,"comment":"null","endLoc":681,"header":"def scopemismatch(currentscope, newscope)","id":1887,"name":"scopemismatch","nodeType":"Function","startLoc":680,"text":"def scopemismatch(currentscope, newscope):\n return scopes.index(newscope) > scopes.index(currentscope)"},{"col":4,"comment":"null","endLoc":1019,"header":"def index(self, __value: _T, __start: SupportsIndex = 0, __stop: SupportsIndex = sys.maxsize) -> int","id":1888,"name":"index","nodeType":"Function","startLoc":1019,"text":"def index(self, __value: _T, __start: SupportsIndex = 0, __stop: SupportsIndex = sys.maxsize) -> int: ..."},{"col":4,"comment":"null","endLoc":1136,"header":"def test_parametrize_with_None_in_ids(self, testdir)","id":1889,"name":"test_parametrize_with_None_in_ids","nodeType":"Function","startLoc":1116,"text":"def test_parametrize_with_None_in_ids(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n metafunc.parametrize((\"a\", \"b\"), [(1,1), (1,1), (1,2)],\n ids=[\"basic\", None, \"advanced\"])\n\n def test_function(a, b):\n assert a == b\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n assert result.ret == 1\n result.stdout.fnmatch_lines_random(\n [\n \"*test_function*basic*PASSED*\",\n \"*test_function*1-1*PASSED*\",\n \"*test_function*advanced*FAILED*\",\n ]\n )"},{"attributeType":"(int, int, int)","col":0,"comment":"null","endLoc":43,"id":1890,"name":"_legal_chars","nodeType":"Attribute","startLoc":43,"text":"_legal_chars"},{"attributeType":"((int, int), (int, int), (int, int), (int, int))","col":0,"comment":"null","endLoc":44,"id":1891,"name":"_legal_ranges","nodeType":"Attribute","startLoc":44,"text":"_legal_ranges"},{"attributeType":"list","col":0,"comment":"null","endLoc":45,"id":1892,"name":"_legal_xml_re","nodeType":"Attribute","startLoc":45,"text":"_legal_xml_re"},{"attributeType":"int","col":9,"comment":"null","endLoc":47,"id":1893,"name":"low","nodeType":"Attribute","startLoc":47,"text":"low"},{"attributeType":"int","col":14,"comment":"null","endLoc":47,"id":1894,"name":"high","nodeType":"Attribute","startLoc":47,"text":"high"},{"attributeType":"list","col":0,"comment":"null","endLoc":50,"id":1895,"name":"_legal_xml_re","nodeType":"Attribute","startLoc":50,"text":"_legal_xml_re"},{"attributeType":"int","col":35,"comment":"null","endLoc":50,"id":1896,"name":"x","nodeType":"Attribute","startLoc":50,"text":"x"},{"attributeType":"Pattern","col":0,"comment":"null","endLoc":51,"id":1897,"name":"illegal_xml_re","nodeType":"Attribute","startLoc":51,"text":"illegal_xml_re"},{"attributeType":"Pattern","col":0,"comment":"null","endLoc":56,"id":1898,"name":"_py_ext_re","nodeType":"Attribute","startLoc":56,"text":"_py_ext_re"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":80,"id":1899,"name":"families","nodeType":"Attribute","startLoc":80,"text":"families"},{"col":0,"comment":"","endLoc":11,"header":"junitxml.py#","id":1900,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"\n report test results in JUnit-XML format,\n for use with Jenkins and build integration servers.\n\n\nBased on initial code from Ross Lawley.\n\nOutput conforms to https://github.com/jenkinsci/xunit-plugin/blob/master/\nsrc/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd\n\"\"\"\n\nif sys.version_info[0] < 3:\n from codecs import open\n\n_legal_chars = (0x09, 0x0A, 0x0D)\n\n_legal_ranges = ((0x20, 0x7E), (0x80, 0xD7FF), (0xE000, 0xFFFD), (0x10000, 0x10FFFF))\n\n_legal_xml_re = [\n u\"%s-%s\" % (six.unichr(low), six.unichr(high))\n for (low, high) in _legal_ranges\n if low < sys.maxunicode\n]\n\n_legal_xml_re = [six.unichr(x) for x in _legal_chars] + _legal_xml_re\n\nillegal_xml_re = re.compile(u\"[^%s]\" % u\"\".join(_legal_xml_re))\n\ndel _legal_chars\n\ndel _legal_ranges\n\ndel _legal_xml_re\n\n_py_ext_re = re.compile(r\"\\.py$\")\n\nfamilies = {}\n\nfamilies[\"_base\"] = {\"testcase\": [\"classname\", \"name\"]}\n\nfamilies[\"_base_legacy\"] = {\"testcase\": [\"file\", \"line\", \"url\"]}\n\nfamilies[\"xunit1\"] = families[\"_base\"].copy()\n\nmerge_family(families[\"xunit1\"], families[\"_base_legacy\"])\n\nfamilies[\"xunit2\"] = families[\"_base\"]"},{"col":4,"comment":"null","endLoc":1085,"header":"def copy(self) -> dict[_KT, _VT]","id":1902,"name":"copy","nodeType":"Function","startLoc":1085,"text":"def copy(self) -> dict[_KT, _VT]: ..."},{"col":4,"comment":"Fixtures parametrized with empty ids cause an internal error (#1849).","endLoc":1153,"header":"def test_fixture_parametrized_empty_ids(self, testdir)","id":1903,"name":"test_fixture_parametrized_empty_ids","nodeType":"Function","startLoc":1138,"text":"def test_fixture_parametrized_empty_ids(self, testdir):\n \"\"\"Fixtures parametrized with empty ids cause an internal error (#1849).\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"module\", ids=[], params=[])\n def temp(request):\n return request.param\n\n def test_temp(temp):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 skipped *\"])"},{"col":4,"comment":"Tests parametrized with empty ids cause an internal error (#1849).","endLoc":1167,"header":"def test_parametrized_empty_ids(self, testdir)","id":1904,"name":"test_parametrized_empty_ids","nodeType":"Function","startLoc":1155,"text":"def test_parametrized_empty_ids(self, testdir):\n \"\"\"Tests parametrized with empty ids cause an internal error (#1849).\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize('temp', [], ids=list())\n def test_temp(temp):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 skipped *\"])"},{"id":1905,"name":"release-4.4.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-4.4.2\n=======================================\n\npytest 4.4.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Allan Lewis\n* Anthony Sottile\n* Bruno Oliveira\n* DamianSkrzypczak\n* Daniel Hahler\n* Don Kirkby\n* Douglas Thor\n* Hugo\n* Ilya Konstantinov\n* Jon Dufresne\n* Matt Cooper\n* Nikolay Kondratyev\n* Ondřej Súkup\n* Peter Schutt\n* Romain Chossart\n* Sitaktif\n\n\nHappy testing,\nThe pytest Development Team\n"},{"col":4,"comment":"Tests parametrized with ids as non-strings (#1857).","endLoc":1185,"header":"def test_parametrized_ids_invalid_type(self, testdir)","id":1906,"name":"test_parametrized_ids_invalid_type","nodeType":"Function","startLoc":1169,"text":"def test_parametrized_ids_invalid_type(self, testdir):\n \"\"\"Tests parametrized with ids as non-strings (#1857).\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize(\"x, expected\", [(10, 20), (40, 80)], ids=(None, 2))\n def test_ids_numbers(x,expected):\n assert x * 2 == expected\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*In test_ids_numbers: ids must be list of strings, found: 2 (type: *'int'>)*\"\n ]\n )"},{"fileName":"pathlib.py","filePath":"src/_pytest","id":1907,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\n\nimport atexit\nimport errno\nimport fnmatch\nimport itertools\nimport operator\nimport os\nimport shutil\nimport sys\nimport uuid\nimport warnings\nfrom functools import partial\nfrom functools import reduce\nfrom os.path import expanduser\nfrom os.path import expandvars\nfrom os.path import isabs\nfrom os.path import sep\nfrom posixpath import sep as posix_sep\n\nimport six\nfrom six.moves import map\n\nfrom .compat import PY36\nfrom _pytest.warning_types import PytestWarning\n\nif PY36:\n from pathlib import Path, PurePath\nelse:\n from pathlib2 import Path, PurePath\n\n__all__ = [\"Path\", \"PurePath\"]\n\n\nLOCK_TIMEOUT = 60 * 60 * 3\n\nget_lock_path = operator.methodcaller(\"joinpath\", \".lock\")\n\n\ndef ensure_reset_dir(path):\n \"\"\"\n ensures the given path is an empty directory\n \"\"\"\n if path.exists():\n rm_rf(path)\n path.mkdir()\n\n\ndef on_rm_rf_error(func, path, exc, **kwargs):\n \"\"\"Handles known read-only errors during rmtree.\"\"\"\n start_path = kwargs[\"start_path\"]\n excvalue = exc[1]\n\n if not isinstance(excvalue, OSError) or excvalue.errno not in (\n errno.EACCES,\n errno.EPERM,\n ):\n warnings.warn(\n PytestWarning(\"(rm_rf) error removing {}: {}\".format(path, excvalue))\n )\n return\n\n if func not in (os.rmdir, os.remove, os.unlink):\n warnings.warn(\n PytestWarning(\"(rm_rf) error removing {}: {}\".format(path, excvalue))\n )\n return\n\n # Chmod + retry.\n import stat\n\n def chmod_rw(p):\n mode = os.stat(p).st_mode\n os.chmod(p, mode | stat.S_IRUSR | stat.S_IWUSR)\n\n # For files, we need to recursively go upwards in the directories to\n # ensure they all are also writable.\n p = Path(path)\n if p.is_file():\n for parent in p.parents:\n chmod_rw(str(parent))\n # stop when we reach the original path passed to rm_rf\n if parent == start_path:\n break\n chmod_rw(str(path))\n\n func(path)\n\n\ndef rm_rf(path):\n \"\"\"Remove the path contents recursively, even if some elements\n are read-only.\n \"\"\"\n onerror = partial(on_rm_rf_error, start_path=path)\n shutil.rmtree(str(path), onerror=onerror)\n\n\ndef find_prefixed(root, prefix):\n \"\"\"finds all elements in root that begin with the prefix, case insensitive\"\"\"\n l_prefix = prefix.lower()\n for x in root.iterdir():\n if x.name.lower().startswith(l_prefix):\n yield x\n\n\ndef extract_suffixes(iter, prefix):\n \"\"\"\n :param iter: iterator over path names\n :param prefix: expected prefix of the path names\n :returns: the parts of the paths following the prefix\n \"\"\"\n p_len = len(prefix)\n for p in iter:\n yield p.name[p_len:]\n\n\ndef find_suffixes(root, prefix):\n \"\"\"combines find_prefixes and extract_suffixes\n \"\"\"\n return extract_suffixes(find_prefixed(root, prefix), prefix)\n\n\ndef parse_num(maybe_num):\n \"\"\"parses number path suffixes, returns -1 on error\"\"\"\n try:\n return int(maybe_num)\n except ValueError:\n return -1\n\n\nif six.PY2:\n\n def _max(iterable, default):\n \"\"\"needed due to python2.7 lacking the default argument for max\"\"\"\n return reduce(max, iterable, default)\n\n\nelse:\n _max = max\n\n\ndef _force_symlink(root, target, link_to):\n \"\"\"helper to create the current symlink\n\n it's full of race conditions that are reasonably ok to ignore\n for the context of best effort linking to the latest testrun\n\n the presumption being thatin case of much parallelism\n the inaccuracy is going to be acceptable\n \"\"\"\n current_symlink = root.joinpath(target)\n try:\n current_symlink.unlink()\n except OSError:\n pass\n try:\n current_symlink.symlink_to(link_to)\n except Exception:\n pass\n\n\ndef make_numbered_dir(root, prefix):\n \"\"\"create a directory with an increased number as suffix for the given prefix\"\"\"\n for i in range(10):\n # try up to 10 times to create the folder\n max_existing = _max(map(parse_num, find_suffixes(root, prefix)), default=-1)\n new_number = max_existing + 1\n new_path = root.joinpath(\"{}{}\".format(prefix, new_number))\n try:\n new_path.mkdir()\n except Exception:\n pass\n else:\n _force_symlink(root, prefix + \"current\", new_path)\n return new_path\n else:\n raise EnvironmentError(\n \"could not create numbered dir with prefix \"\n \"{prefix} in {root} after 10 tries\".format(prefix=prefix, root=root)\n )\n\n\ndef create_cleanup_lock(p):\n \"\"\"crates a lock to prevent premature folder cleanup\"\"\"\n lock_path = get_lock_path(p)\n try:\n fd = os.open(str(lock_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)\n except OSError as e:\n if e.errno == errno.EEXIST:\n six.raise_from(\n EnvironmentError(\"cannot create lockfile in {path}\".format(path=p)), e\n )\n else:\n raise\n else:\n pid = os.getpid()\n spid = str(pid)\n if not isinstance(spid, bytes):\n spid = spid.encode(\"ascii\")\n os.write(fd, spid)\n os.close(fd)\n if not lock_path.is_file():\n raise EnvironmentError(\"lock path got renamed after successful creation\")\n return lock_path\n\n\ndef register_cleanup_lock_removal(lock_path, register=atexit.register):\n \"\"\"registers a cleanup function for removing a lock, by default on atexit\"\"\"\n pid = os.getpid()\n\n def cleanup_on_exit(lock_path=lock_path, original_pid=pid):\n current_pid = os.getpid()\n if current_pid != original_pid:\n # fork\n return\n try:\n lock_path.unlink()\n except (OSError, IOError):\n pass\n\n return register(cleanup_on_exit)\n\n\ndef maybe_delete_a_numbered_dir(path):\n \"\"\"removes a numbered directory if its lock can be obtained and it does not seem to be in use\"\"\"\n lock_path = None\n try:\n lock_path = create_cleanup_lock(path)\n parent = path.parent\n\n garbage = parent.joinpath(\"garbage-{}\".format(uuid.uuid4()))\n path.rename(garbage)\n rm_rf(garbage)\n except (OSError, EnvironmentError):\n # known races:\n # * other process did a cleanup at the same time\n # * deletable folder was found\n # * process cwd (Windows)\n return\n finally:\n # if we created the lock, ensure we remove it even if we failed\n # to properly remove the numbered dir\n if lock_path is not None:\n try:\n lock_path.unlink()\n except (OSError, IOError):\n pass\n\n\ndef ensure_deletable(path, consider_lock_dead_if_created_before):\n \"\"\"checks if a lock exists and breaks it if its considered dead\"\"\"\n if path.is_symlink():\n return False\n lock = get_lock_path(path)\n if not lock.exists():\n return True\n try:\n lock_time = lock.stat().st_mtime\n except Exception:\n return False\n else:\n if lock_time < consider_lock_dead_if_created_before:\n lock.unlink()\n return True\n else:\n return False\n\n\ndef try_cleanup(path, consider_lock_dead_if_created_before):\n \"\"\"tries to cleanup a folder if we can ensure it's deletable\"\"\"\n if ensure_deletable(path, consider_lock_dead_if_created_before):\n maybe_delete_a_numbered_dir(path)\n\n\ndef cleanup_candidates(root, prefix, keep):\n \"\"\"lists candidates for numbered directories to be removed - follows py.path\"\"\"\n max_existing = _max(map(parse_num, find_suffixes(root, prefix)), default=-1)\n max_delete = max_existing - keep\n paths = find_prefixed(root, prefix)\n paths, paths2 = itertools.tee(paths)\n numbers = map(parse_num, extract_suffixes(paths2, prefix))\n for path, number in zip(paths, numbers):\n if number <= max_delete:\n yield path\n\n\ndef cleanup_numbered_dir(root, prefix, keep, consider_lock_dead_if_created_before):\n \"\"\"cleanup for lock driven numbered directories\"\"\"\n for path in cleanup_candidates(root, prefix, keep):\n try_cleanup(path, consider_lock_dead_if_created_before)\n for path in root.glob(\"garbage-*\"):\n try_cleanup(path, consider_lock_dead_if_created_before)\n\n\ndef make_numbered_dir_with_cleanup(root, prefix, keep, lock_timeout):\n \"\"\"creates a numbered dir with a cleanup lock and removes old ones\"\"\"\n e = None\n for i in range(10):\n try:\n p = make_numbered_dir(root, prefix)\n lock_path = create_cleanup_lock(p)\n register_cleanup_lock_removal(lock_path)\n except Exception as exc:\n e = exc\n else:\n consider_lock_dead_if_created_before = p.stat().st_mtime - lock_timeout\n cleanup_numbered_dir(\n root=root,\n prefix=prefix,\n keep=keep,\n consider_lock_dead_if_created_before=consider_lock_dead_if_created_before,\n )\n return p\n assert e is not None\n raise e\n\n\ndef resolve_from_str(input, root):\n assert not isinstance(input, Path), \"would break on py2\"\n root = Path(root)\n input = expanduser(input)\n input = expandvars(input)\n if isabs(input):\n return Path(input)\n else:\n return root.joinpath(input)\n\n\ndef fnmatch_ex(pattern, path):\n \"\"\"FNMatcher port from py.path.common which works with PurePath() instances.\n\n The difference between this algorithm and PurePath.match() is that the latter matches \"**\" glob expressions\n for each part of the path, while this algorithm uses the whole path instead.\n\n For example:\n \"tests/foo/bar/doc/test_foo.py\" matches pattern \"tests/**/doc/test*.py\" with this algorithm, but not with\n PurePath.match().\n\n This algorithm was ported to keep backward-compatibility with existing settings which assume paths match according\n this logic.\n\n References:\n * https://bugs.python.org/issue29249\n * https://bugs.python.org/issue34731\n \"\"\"\n path = PurePath(path)\n iswin32 = sys.platform.startswith(\"win\")\n\n if iswin32 and sep not in pattern and posix_sep in pattern:\n # Running on Windows, the pattern has no Windows path separators,\n # and the pattern has one or more Posix path separators. Replace\n # the Posix path separators with the Windows path separator.\n pattern = pattern.replace(posix_sep, sep)\n\n if sep not in pattern:\n name = path.name\n else:\n name = six.text_type(path)\n return fnmatch.fnmatch(name, pattern)\n\n\ndef parts(s):\n parts = s.split(sep)\n return {sep.join(parts[: i + 1]) or sep for i in range(len(parts))}\n"},{"className":"partial","col":0,"comment":"null","endLoc":135,"id":1908,"nodeType":"Class","startLoc":125,"text":"class partial(Generic[_T]):\n @property\n def func(self) -> Callable[..., _T]: ...\n @property\n def args(self) -> tuple[Any, ...]: ...\n @property\n def keywords(self) -> dict[str, Any]: ...\n def __new__(cls, func: Callable[..., _T], /, *args: Any, **kwargs: Any) -> Self: ...\n def __call__(self, /, *args: Any, **kwargs: Any) -> _T: ...\n if sys.version_info >= (3, 9):\n def __class_getitem__(cls, item: Any, /) -> GenericAlias: ..."},{"col":4,"comment":"null","endLoc":127,"header":"@property\n def func(self) -> Callable[..., _T]","id":1909,"name":"func","nodeType":"Function","startLoc":126,"text":"@property\n def func(self) -> Callable[..., _T]: ..."},{"col":4,"comment":"null","endLoc":129,"header":"@property\n def args(self) -> tuple[Any, ...]","id":1910,"name":"args","nodeType":"Function","startLoc":128,"text":"@property\n def args(self) -> tuple[Any, ...]: ..."},{"col":4,"comment":"null","endLoc":131,"header":"@property\n def keywords(self) -> dict[str, Any]","id":1911,"name":"keywords","nodeType":"Function","startLoc":130,"text":"@property\n def keywords(self) -> dict[str, Any]: ..."},{"col":4,"comment":"null","endLoc":133,"header":"def __call__(self, /, *args: Any, **kwargs: Any) -> _T","id":1912,"name":"__call__","nodeType":"Function","startLoc":133,"text":"def __call__(self, /, *args: Any, **kwargs: Any) -> _T: ..."},{"col":8,"comment":"null","endLoc":135,"header":"def __class_getitem__(cls, item: Any, /) -> GenericAlias","id":1913,"name":"__class_getitem__","nodeType":"Function","startLoc":135,"text":"def __class_getitem__(cls, item: Any, /) -> GenericAlias: ..."},{"col":0,"comment":"null","endLoc":39,"header":"@overload\ndef reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T, /) -> _T","id":1914,"name":"reduce","nodeType":"Function","startLoc":38,"text":"@overload\ndef reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T, /) -> _T: ..."},{"col":0,"comment":"null","endLoc":41,"header":"@overload\ndef reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T], /) -> _T","id":1915,"name":"reduce","nodeType":"Function","startLoc":40,"text":"@overload\ndef reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T], /) -> _T: ..."},{"col":0,"comment":"null","endLoc":146,"header":"def isabs(s: StrOrBytesPath) -> bool","id":1916,"name":"isabs","nodeType":"Function","startLoc":146,"text":"def isabs(s: StrOrBytesPath) -> bool: ..."},{"col":4,"comment":"null","endLoc":1203,"header":"def test_parametrize_with_identical_ids_get_unique_names(self, testdir)","id":1917,"name":"test_parametrize_with_identical_ids_get_unique_names","nodeType":"Function","startLoc":1187,"text":"def test_parametrize_with_identical_ids_get_unique_names(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n metafunc.parametrize((\"a\", \"b\"), [(1,1), (1,2)],\n ids=[\"a\", \"a\"])\n\n def test_function(a, b):\n assert a == b\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n assert result.ret == 1\n result.stdout.fnmatch_lines_random(\n [\"*test_function*a0*PASSED*\", \"*test_function*a1*FAILED*\"]\n )"},{"id":1918,"name":"pyproject.toml","nodeType":"TextFile","path":"","text":"[build-system]\nrequires = [\n # sync with setup.py until we discard non-pep-517/518\n \"setuptools>=40.0\",\n \"setuptools-scm\",\n \"wheel\",\n]\nbuild-backend = \"setuptools.build_meta\"\n\n[tool.towncrier]\npackage = \"pytest\"\npackage_dir = \"src\"\nfilename = \"CHANGELOG.rst\"\ndirectory = \"changelog/\"\ntitle_format = \"pytest {version} ({project_date})\"\ntemplate = \"changelog/_template.rst\"\n\n [[tool.towncrier.type]]\n directory = \"removal\"\n name = \"Removals\"\n showcontent = true\n\n [[tool.towncrier.type]]\n directory = \"deprecation\"\n name = \"Deprecations\"\n showcontent = true\n\n [[tool.towncrier.type]]\n directory = \"feature\"\n name = \"Features\"\n showcontent = true\n\n [[tool.towncrier.type]]\n directory = \"bugfix\"\n name = \"Bug Fixes\"\n showcontent = true\n\n [[tool.towncrier.type]]\n directory = \"vendor\"\n name = \"Vendored Libraries\"\n showcontent = true\n\n [[tool.towncrier.type]]\n directory = \"doc\"\n name = \"Improved Documentation\"\n showcontent = true\n\n [[tool.towncrier.type]]\n directory = \"trivial\"\n name = \"Trivial/Internal Changes\"\n showcontent = true\n"},{"attributeType":"LiteralString","col":0,"comment":"null","endLoc":73,"id":1919,"name":"sep","nodeType":"Attribute","startLoc":73,"text":"sep"},{"className":"map","col":0,"comment":"null","endLoc":1515,"id":1920,"nodeType":"Class","startLoc":1474,"text":"class map(Iterator[_S], Generic[_S]):\n @overload\n def __init__(self, __func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> None: ...\n @overload\n def __init__(self, __func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> None: ...\n @overload\n def __init__(\n self, __func: Callable[[_T1, _T2, _T3], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]\n ) -> None: ...\n @overload\n def __init__(\n self,\n __func: Callable[[_T1, _T2, _T3, _T4], _S],\n __iter1: Iterable[_T1],\n __iter2: Iterable[_T2],\n __iter3: Iterable[_T3],\n __iter4: Iterable[_T4],\n ) -> None: ...\n @overload\n def __init__(\n self,\n __func: Callable[[_T1, _T2, _T3, _T4, _T5], _S],\n __iter1: Iterable[_T1],\n __iter2: Iterable[_T2],\n __iter3: Iterable[_T3],\n __iter4: Iterable[_T4],\n __iter5: Iterable[_T5],\n ) -> None: ...\n @overload\n def __init__(\n self,\n __func: Callable[..., _S],\n __iter1: Iterable[Any],\n __iter2: Iterable[Any],\n __iter3: Iterable[Any],\n __iter4: Iterable[Any],\n __iter5: Iterable[Any],\n __iter6: Iterable[Any],\n *iterables: Iterable[Any],\n ) -> None: ...\n def __iter__(self: Self) -> Self: ...\n def __next__(self) -> _S: ..."},{"id":1921,"name":".travis.yml","nodeType":"TextFile","path":"","text":"language: python\ndist: xenial\nstages:\n- baseline\n- name: test\n if: repo = pytest-dev/pytest AND tag IS NOT present\n- name: deploy\n if: repo = pytest-dev/pytest AND tag IS present\npython: '3.7'\ncache: false\n\nenv:\n global:\n - PYTEST_ADDOPTS=-vv\n\n# setuptools-scm needs all tags in order to obtain a proper version\ngit:\n depth: false\n\ninstall:\n - python -m pip install --upgrade --pre tox\n\njobs:\n include:\n # OSX tests - first (in test stage), since they are the slower ones.\n - &test-macos\n os: osx\n osx_image: xcode10.1\n language: generic\n # Coverage for:\n # - py2 with symlink in test_cmdline_python_package_symlink.\n env: TOXENV=py27-xdist PYTEST_COVERAGE=1\n before_install:\n - python -V\n - test $(python -c 'import sys; print(\"%d%d\" % sys.version_info[0:2])') = 27\n - <<: *test-macos\n env: TOXENV=py37-pexpect,py37-xdist PYTEST_COVERAGE=1\n before_install:\n - which python3\n - python3 -V\n - ln -sfn \"$(which python3)\" /usr/local/bin/python\n - python -V\n - test $(python -c 'import sys; print(\"%d%d\" % sys.version_info[0:2])') = 37\n\n # Full run of latest (major) supported versions, without xdist.\n - env: TOXENV=py27\n python: '2.7'\n - env: TOXENV=py37\n python: '3.7'\n\n # Coverage tracking is slow with pypy, skip it.\n - env: TOXENV=pypy-xdist\n python: 'pypy'\n - env: TOXENV=pypy3-xdist\n python: 'pypy3'\n\n - env: TOXENV=py34-xdist\n python: '3.4'\n - env: TOXENV=py35-xdist\n python: '3.5'\n\n # Coverage for:\n # - pytester's LsofFdLeakChecker\n # - TestArgComplete (linux only)\n # - numpy\n # Empty PYTEST_ADDOPTS to run this non-verbose.\n - env: TOXENV=py37-lsof-numpy-xdist PYTEST_COVERAGE=1 PYTEST_ADDOPTS=\n\n # Specialized factors for py27.\n - env: TOXENV=py27-nobyte-numpy-xdist\n python: '2.7'\n - env: TOXENV=py27-pluggymaster-xdist\n python: '2.7'\n\n # Specialized factors for py37.\n # Coverage for:\n # - test_sys_breakpoint_interception (via pexpect).\n - env: TOXENV=py37-pexpect,py37-twisted PYTEST_COVERAGE=1\n - env: TOXENV=py37-pluggymaster-xdist\n - env: TOXENV=py37-freeze\n\n # Jobs only run via Travis cron jobs (currently daily).\n - env: TOXENV=py38-xdist\n python: '3.8-dev'\n if: type = cron\n\n - stage: baseline\n # Coverage for:\n # - _pytest.unittest._handle_skip (via pexpect).\n env: TOXENV=py27-pexpect,py27-twisted PYTEST_COVERAGE=1\n python: '2.7'\n # Use py36 here for faster baseline.\n - env: TOXENV=py36-xdist\n python: '3.6'\n - env: TOXENV=linting,docs,doctesting PYTEST_COVERAGE=1\n cache:\n directories:\n - $HOME/.cache/pre-commit\n\n - stage: deploy\n python: '3.6'\n install: pip install -U setuptools setuptools_scm tox\n script: skip\n # token to upload github release notes: GH_RELEASE_NOTES_TOKEN\n env:\n - secure: \"OjOeL7/0JUDkV00SsTs732e8vQjHynpbG9FKTNtZZJ+1Zn4Cib+hAlwmlBnvVukML0X60YpcfjnC4quDOIGLPsh5zeXnvJmYtAIIUNQXjWz8NhcGYrhyzuP1rqV22U68RTCdmOq3lMYU/W2acwHP7T49PwJtOiUM5kF120UAQ0Zi5EmkqkIvH8oM5mO9Dlver+/U7Htpz9rhKrHBXQNCMZI6yj2aUyukqB2PN2fjAlDbCF//+FmvYw9NjT4GeFOSkTCf4ER9yfqs7yglRfwiLtOCZ2qKQhWZNsSJDB89rxIRXWavJUjJKeY2EW2/NkomYJDpqJLIF4JeFRw/HhA47CYPeo6BJqyyNV+0CovL1frpWfi9UQw2cMbgFUkUIUk3F6DD59PHNIOX2R/HX56dQsw7WKl3QuHlCOkICXYg8F7Ta684IoKjeTX03/6QNOkURfDBwfGszY0FpbxrjCSWKom6RyZdyidnESaxv9RzjcIRZVh1rp8KMrwS1OrwRSdG0zjlsPr49hWMenN/8fKgcHTV4/r1Tj6mip0dorSRCrgUNIeRBKgmui6FS8642ab5JNKOxMteVPVR2sFuhjOQ0Jy+PmvceYY9ZMWc3+/B/KVh0dZ3hwvLGZep/vxDS2PwCA5/xw31714vT5LxidKo8yECjBynMU/wUTTS695D3NY=\"\n addons:\n apt:\n packages:\n # required by publish_gh_release_notes\n - pandoc\n after_deploy: tox -e publish_gh_release_notes\n deploy:\n provider: pypi\n user: nicoddemus\n distributions: sdist bdist_wheel\n skip_upload_docs: true\n password:\n secure: xanTgTUu6XDQVqB/0bwJQXoDMnU5tkwZc5koz6mBkkqZhKdNOi2CLoC1XhiSZ+ah24l4V1E0GAqY5kBBcy9d7NVe4WNg4tD095LsHw+CRU6/HCVIFfyk2IZ+FPAlguesCcUiJSXOrlBF+Wj68wEvLoK7EoRFbJeiZ/f91Ww1sbtDlqXABWGHrmhPJL5Wva7o7+wG7JwJowqdZg1pbQExsCc7b53w4v2RBu3D6TJaTAzHiVsW+nUSI67vKI/uf+cR/OixsTfy37wlHgSwihYmrYLFls3V0bSpahCim3bCgMaFZx8S8xrdgJ++PzBCof2HeflFKvW+VCkoYzGEG4NrTWJoNz6ni4red9GdvfjGH3YCjAKS56h9x58zp2E5rpsb/kVq5/45xzV+dq6JRuhQ1nJWjBC6fSKAc/bfwnuFK3EBxNLkvBssLHvsNjj5XG++cB8DdS9wVGUqjpoK4puaXUWFqy4q3S9F86HEsKNgExtieA9qNx+pCIZVs6JCXZNjr0I5eVNzqJIyggNgJG6RyravsU35t9Zd9doL5g4Y7UKmAGTn1Sz24HQ4sMQgXdm2SyD8gEK5je4tlhUvfGtDvMSlstq71kIn9nRpFnqB6MFlbYSEAZmo8dGbCquoUc++6Rum208wcVbrzzVtGlXB/Ow9AbFMYeAGA0+N/K1e59c=\n on:\n tags: true\n repo: pytest-dev/pytest\n\nmatrix:\n allow_failures:\n - python: '3.8-dev'\n env: TOXENV=py38-xdist\n # Temporary (https://github.com/pytest-dev/pytest/pull/5334).\n - env: TOXENV=pypy3-xdist\n python: 'pypy3'\n\nbefore_script:\n - |\n # Do not (re-)upload coverage with cron runs.\n if [[ \"$TRAVIS_EVENT_TYPE\" = cron ]]; then\n PYTEST_COVERAGE=0\n fi\n - |\n if [[ \"$PYTEST_COVERAGE\" = 1 ]]; then\n export COVERAGE_FILE=\"$PWD/.coverage\"\n export COVERAGE_PROCESS_START=\"$PWD/.coveragerc\"\n export _PYTEST_TOX_COVERAGE_RUN=\"coverage run -m\"\n export _PYTEST_TOX_EXTRA_DEP=coverage-enable-subprocess\n fi\n\nscript: tox\n\nafter_success:\n - |\n if [[ \"$PYTEST_COVERAGE\" = 1 ]]; then\n set -e\n # Add last TOXENV to $PATH.\n PATH=\"$PWD/.tox/${TOXENV##*,}/bin:$PATH\"\n coverage combine\n coverage xml\n coverage report -m\n bash <(curl -s https://codecov.io/bash) -Z -X gcov -X coveragepy -X search -X xcode -X gcovout -X fix -f coverage.xml -n $TOXENV-$TRAVIS_OS_NAME\n fi\n\nnotifications:\n irc:\n channels:\n - \"chat.freenode.net#pytest\"\n on_success: change\n on_failure: change\n skip_join: true\n email:\n - pytest-commit@python.org\n"},{"col":4,"comment":"null","endLoc":1229,"header":"@pytest.mark.parametrize((\"scope\", \"length\"), [(\"module\", 2), (\"function\", 4)])\n def test_parametrize_scope_overrides(self, testdir, scope, length)","id":1922,"name":"test_parametrize_scope_overrides","nodeType":"Function","startLoc":1205,"text":"@pytest.mark.parametrize((\"scope\", \"length\"), [(\"module\", 2), (\"function\", 4)])\n def test_parametrize_scope_overrides(self, testdir, scope, length):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n def pytest_generate_tests(metafunc):\n if \"arg\" in metafunc.funcargnames:\n metafunc.parametrize(\"arg\", [1,2], indirect=True,\n scope=%r)\n @pytest.fixture\n def arg(request):\n values.append(request.param)\n return request.param\n def test_hello(arg):\n assert arg in (1,2)\n def test_world(arg):\n assert arg in (1,2)\n def test_checklength():\n assert len(values) == %d\n \"\"\"\n % (scope, length)\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=5)"},{"id":1923,"name":"release-2.0.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"py.test 2.0.1: bug fixes\n===========================================================================\n\nWelcome to pytest-2.0.1, a maintenance and bug fix release of pytest,\na mature testing tool for Python, supporting CPython 2.4-3.2, Jython\nand latest PyPy interpreters. See extensive docs with tested examples here:\n\n http://pytest.org/\n\nIf you want to install or upgrade pytest, just type one of::\n\n pip install -U pytest # or\n easy_install -U pytest\n\nMany thanks to all issue reporters and people asking questions or\ncomplaining. Particular thanks to Floris Bruynooghe and Ronny Pfannschmidt\nfor their great coding contributions and many others for feedback and help.\n\nbest,\nholger krekel\n\nChanges between 2.0.0 and 2.0.1\n----------------------------------------------\n\n- refine and unify initial capturing so that it works nicely\n even if the logging module is used on an early-loaded conftest.py\n file or plugin.\n- fix issue12 - show plugin versions with \"--version\" and\n \"--traceconfig\" and also document how to add extra information\n to reporting test header\n- fix issue17 (import-* reporting issue on python3) by\n requiring py>1.4.0 (1.4.1 is going to include it)\n- fix issue10 (numpy arrays truth checking) by refining\n assertion interpretation in py lib\n- fix issue15: make nose compatibility tests compatible\n with python3 (now that nose-1.0 supports python3)\n- remove somewhat surprising \"same-conftest\" detection because\n it ignores conftest.py when they appear in several subdirs.\n- improve assertions (\"not in\"), thanks Floris Bruynooghe\n- improve behaviour/warnings when running on top of \"python -OO\"\n (assertions and docstrings are turned off, leading to potential\n false positives)\n- introduce a pytest_cmdline_processargs(args) hook\n to allow dynamic computation of command line arguments.\n This fixes a regression because py.test prior to 2.0\n allowed to set command line options from conftest.py\n files which so far pytest-2.0 only allowed from ini-files now.\n- fix issue7: assert failures in doctest modules.\n unexpected failures in doctests will not generally\n show nicer, i.e. within the doctest failing context.\n- fix issue9: setup/teardown functions for an xfail-marked\n test will report as xfail if they fail but report as normally\n passing (not xpassing) if they succeed. This only is true\n for \"direct\" setup/teardown invocations because teardown_class/\n teardown_module cannot closely relate to a single test.\n- fix issue14: no logging errors at process exit\n- refinements to \"collecting\" output on non-ttys\n- refine internal plugin registration and --traceconfig output\n- introduce a mechanism to prevent/unregister plugins from the\n command line, see http://pytest.org/latest/plugins.html#cmdunregister\n- activate resultlog plugin by default\n- fix regression wrt yielded tests which due to the\n collection-before-running semantics were not\n setup as with pytest 1.3.4. Note, however, that\n the recommended and much cleaner way to do test\n parametrization remains the \"pytest_generate_tests\"\n mechanism, see the docs.\n"},{"col":4,"comment":"null","endLoc":1514,"header":"def __iter__(self: Self) -> Self","id":1924,"name":"__iter__","nodeType":"Function","startLoc":1514,"text":"def __iter__(self: Self) -> Self: ..."},{"col":4,"comment":"null","endLoc":1515,"header":"def __next__(self) -> _S","id":1925,"name":"__next__","nodeType":"Function","startLoc":1515,"text":"def __next__(self) -> _S: ..."},{"className":"map","col":0,"comment":"\n map(func, *iterables) --> map object\n \n Make an iterator that computes the function using arguments from\n each of the iterables. Stops when the shortest iterable is exhausted.\n ","endLoc":3925,"id":1926,"nodeType":"Class","startLoc":3896,"text":"class map(object):\n \"\"\"\n map(func, *iterables) --> map object\n \n Make an iterator that computes the function using arguments from\n each of the iterables. Stops when the shortest iterable is exhausted.\n \"\"\"\n def __getattribute__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return getattr(self, name). \"\"\"\n pass\n\n def __init__(self, func, *iterables): # real signature unknown; restored from __doc__\n pass\n\n def __iter__(self, *args, **kwargs): # real signature unknown\n \"\"\" Implement iter(self). \"\"\"\n pass\n\n @staticmethod # known case of __new__\n def __new__(*args, **kwargs): # real signature unknown\n \"\"\" Create and return a new object. See help(type) for accurate signature. \"\"\"\n pass\n\n def __next__(self, *args, **kwargs): # real signature unknown\n \"\"\" Implement next(self). \"\"\"\n pass\n\n def __reduce__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return state information for pickling. \"\"\"\n pass"},{"col":4,"comment":" Return getattr(self, name). ","endLoc":3905,"header":"def __getattribute__(self, *args, **kwargs)","id":1927,"name":"__getattribute__","nodeType":"Function","startLoc":3903,"text":"def __getattribute__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return getattr(self, name). \"\"\"\n pass"},{"col":4,"comment":"null","endLoc":3908,"header":"def __init__(self, func, *iterables)","id":1928,"name":"__init__","nodeType":"Function","startLoc":3907,"text":"def __init__(self, func, *iterables): # real signature unknown; restored from __doc__\n pass"},{"col":4,"comment":" Implement iter(self). ","endLoc":3912,"header":"def __iter__(self, *args, **kwargs)","id":1929,"name":"__iter__","nodeType":"Function","startLoc":3910,"text":"def __iter__(self, *args, **kwargs): # real signature unknown\n \"\"\" Implement iter(self). \"\"\"\n pass"},{"col":4,"comment":" Create and return a new object. See help(type) for accurate signature. ","endLoc":3917,"header":"@staticmethod # known case of __new__\n def __new__(*args, **kwargs)","id":1930,"name":"__new__","nodeType":"Function","startLoc":3914,"text":"@staticmethod # known case of __new__\n def __new__(*args, **kwargs): # real signature unknown\n \"\"\" Create and return a new object. See help(type) for accurate signature. \"\"\"\n pass"},{"col":4,"comment":" Implement next(self). ","endLoc":3921,"header":"def __next__(self, *args, **kwargs)","id":1931,"name":"__next__","nodeType":"Function","startLoc":3919,"text":"def __next__(self, *args, **kwargs): # real signature unknown\n \"\"\" Implement next(self). \"\"\"\n pass"},{"col":4,"comment":" Return state information for pickling. ","endLoc":3925,"header":"def __reduce__(self, *args, **kwargs)","id":1932,"name":"__reduce__","nodeType":"Function","startLoc":3923,"text":"def __reduce__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return state information for pickling. \"\"\"\n pass"},{"attributeType":"null","col":0,"comment":"null","endLoc":43,"id":1933,"name":"PY36","nodeType":"Attribute","startLoc":43,"text":"PY36"},{"col":4,"comment":"null","endLoc":1247,"header":"def test_parametrize_issue323(self, testdir)","id":1934,"name":"test_parametrize_issue323","nodeType":"Function","startLoc":1231,"text":"def test_parametrize_issue323(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='module', params=range(966))\n def foo(request):\n return request.param\n\n def test_it(foo):\n pass\n def test_it2(foo):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(\"--collect-only\")\n assert not reprec.getcalls(\"pytest_internalerror\")"},{"col":4,"comment":"null","endLoc":1263,"header":"def test_usefixtures_seen_in_generate_tests(self, testdir)","id":1935,"name":"test_usefixtures_seen_in_generate_tests","nodeType":"Function","startLoc":1249,"text":"def test_usefixtures_seen_in_generate_tests(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n assert \"abc\" in metafunc.fixturenames\n metafunc.parametrize(\"abc\", [1])\n\n @pytest.mark.usefixtures(\"abc\")\n def test_function():\n pass\n \"\"\"\n )\n reprec = testdir.runpytest()\n reprec.assert_outcomes(passed=1)"},{"col":0,"comment":"\n ensures the given path is an empty directory\n ","endLoc":47,"header":"def ensure_reset_dir(path)","id":1936,"name":"ensure_reset_dir","nodeType":"Function","startLoc":41,"text":"def ensure_reset_dir(path):\n \"\"\"\n ensures the given path is an empty directory\n \"\"\"\n if path.exists():\n rm_rf(path)\n path.mkdir()"},{"col":4,"comment":"null","endLoc":1287,"header":"def test_generate_tests_only_done_in_subdir(self, testdir)","id":1937,"name":"test_generate_tests_only_done_in_subdir","nodeType":"Function","startLoc":1265,"text":"def test_generate_tests_only_done_in_subdir(self, testdir):\n sub1 = testdir.mkpydir(\"sub1\")\n sub2 = testdir.mkpydir(\"sub2\")\n sub1.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def pytest_generate_tests(metafunc):\n assert metafunc.function.__name__ == \"test_1\"\n \"\"\"\n )\n )\n sub2.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def pytest_generate_tests(metafunc):\n assert metafunc.function.__name__ == \"test_2\"\n \"\"\"\n )\n )\n sub1.join(\"test_in_sub1.py\").write(\"def test_1(): pass\")\n sub2.join(\"test_in_sub2.py\").write(\"def test_2(): pass\")\n result = testdir.runpytest(\"--keep-duplicates\", \"-v\", \"-s\", sub1, sub2, sub1)\n result.assert_outcomes(passed=3)"},{"col":0,"comment":"Remove the path contents recursively, even if some elements\n are read-only.\n ","endLoc":96,"header":"def rm_rf(path)","id":1938,"name":"rm_rf","nodeType":"Function","startLoc":91,"text":"def rm_rf(path):\n \"\"\"Remove the path contents recursively, even if some elements\n are read-only.\n \"\"\"\n onerror = partial(on_rm_rf_error, start_path=path)\n shutil.rmtree(str(path), onerror=onerror)"},{"col":4,"comment":"null","endLoc":1305,"header":"def test_generate_same_function_names_issue403(self, testdir)","id":1939,"name":"test_generate_same_function_names_issue403","nodeType":"Function","startLoc":1289,"text":"def test_generate_same_function_names_issue403(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n def make_tests():\n @pytest.mark.parametrize(\"x\", range(2))\n def test_foo(x):\n pass\n return test_foo\n\n test_x = make_tests()\n test_y = make_tests()\n \"\"\"\n )\n reprec = testdir.runpytest()\n reprec.assert_outcomes(passed=4)"},{"col":4,"comment":"#463","endLoc":1327,"header":"@pytest.mark.parametrize(\"attr\", [\"parametrise\", \"parameterize\", \"parameterise\"])\n def test_parametrize_misspelling(self, testdir, attr)","id":1940,"name":"test_parametrize_misspelling","nodeType":"Function","startLoc":1307,"text":"@pytest.mark.parametrize(\"attr\", [\"parametrise\", \"parameterize\", \"parameterise\"])\n def test_parametrize_misspelling(self, testdir, attr):\n \"\"\"#463\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.{}(\"x\", range(2))\n def test_foo(x):\n pass\n \"\"\".format(\n attr\n )\n )\n result = testdir.runpytest(\"--collectonly\")\n result.stdout.fnmatch_lines(\n [\n \"test_foo has '{}' mark, spelling should be 'parametrize'\".format(attr),\n \"*1 error in*\",\n ]\n )"},{"className":"TestMetafuncFunctionalAuto","col":0,"comment":"\n Tests related to automatically find out the correct scope for parametrized tests (#1832).\n ","endLoc":1489,"id":1942,"nodeType":"Class","startLoc":1330,"text":"class TestMetafuncFunctionalAuto(object):\n \"\"\"\n Tests related to automatically find out the correct scope for parametrized tests (#1832).\n \"\"\"\n\n def test_parametrize_auto_scope(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='session', autouse=True)\n def fixture():\n return 1\n\n @pytest.mark.parametrize('animal', [\"dog\", \"cat\"])\n def test_1(animal):\n assert animal in ('dog', 'cat')\n\n @pytest.mark.parametrize('animal', ['fish'])\n def test_2(animal):\n assert animal == 'fish'\n\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 3 passed *\"])\n\n def test_parametrize_auto_scope_indirect(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='session')\n def echo(request):\n return request.param\n\n @pytest.mark.parametrize('animal, echo', [(\"dog\", 1), (\"cat\", 2)], indirect=['echo'])\n def test_1(animal, echo):\n assert animal in ('dog', 'cat')\n assert echo in (1, 2, 3)\n\n @pytest.mark.parametrize('animal, echo', [('fish', 3)], indirect=['echo'])\n def test_2(animal, echo):\n assert animal == 'fish'\n assert echo in (1, 2, 3)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 3 passed *\"])\n\n def test_parametrize_auto_scope_override_fixture(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='session', autouse=True)\n def animal():\n return 'fox'\n\n @pytest.mark.parametrize('animal', [\"dog\", \"cat\"])\n def test_1(animal):\n assert animal in ('dog', 'cat')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed *\"])\n\n def test_parametrize_all_indirects(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture()\n def animal(request):\n return request.param\n\n @pytest.fixture(scope='session')\n def echo(request):\n return request.param\n\n @pytest.mark.parametrize('animal, echo', [(\"dog\", 1), (\"cat\", 2)], indirect=True)\n def test_1(animal, echo):\n assert animal in ('dog', 'cat')\n assert echo in (1, 2, 3)\n\n @pytest.mark.parametrize('animal, echo', [(\"fish\", 3)], indirect=True)\n def test_2(animal, echo):\n assert animal == 'fish'\n assert echo in (1, 2, 3)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 3 passed *\"])\n\n def test_parametrize_some_arguments_auto_scope(self, testdir, monkeypatch):\n \"\"\"Integration test for (#3941)\"\"\"\n class_fix_setup = []\n monkeypatch.setattr(sys, \"class_fix_setup\", class_fix_setup, raising=False)\n func_fix_setup = []\n monkeypatch.setattr(sys, \"func_fix_setup\", func_fix_setup, raising=False)\n\n testdir.makepyfile(\n \"\"\"\n import pytest\n import sys\n\n @pytest.fixture(scope='class', autouse=True)\n def class_fix(request):\n sys.class_fix_setup.append(request.param)\n\n @pytest.fixture(autouse=True)\n def func_fix():\n sys.func_fix_setup.append(True)\n\n @pytest.mark.parametrize('class_fix', [10, 20], indirect=True)\n class Test:\n def test_foo(self):\n pass\n def test_bar(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest_inprocess()\n result.stdout.fnmatch_lines([\"* 4 passed in *\"])\n assert func_fix_setup == [True] * 4\n assert class_fix_setup == [10, 20]\n\n def test_parametrize_issue634(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='module')\n def foo(request):\n print('preparing foo-%d' % request.param)\n return 'foo-%d' % request.param\n\n def test_one(foo):\n pass\n\n def test_two(foo):\n pass\n\n test_two.test_with = (2, 3)\n\n def pytest_generate_tests(metafunc):\n params = (1, 2, 3, 4)\n if not 'foo' in metafunc.fixturenames:\n return\n\n test_with = getattr(metafunc.function, 'test_with', None)\n if test_with:\n params = test_with\n metafunc.parametrize('foo', params, indirect=True)\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n output = result.stdout.str()\n assert output.count(\"preparing foo-2\") == 1\n assert output.count(\"preparing foo-3\") == 1"},{"col":4,"comment":"null","endLoc":1355,"header":"def test_parametrize_auto_scope(self, testdir)","id":1943,"name":"test_parametrize_auto_scope","nodeType":"Function","startLoc":1335,"text":"def test_parametrize_auto_scope(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='session', autouse=True)\n def fixture():\n return 1\n\n @pytest.mark.parametrize('animal', [\"dog\", \"cat\"])\n def test_1(animal):\n assert animal in ('dog', 'cat')\n\n @pytest.mark.parametrize('animal', ['fish'])\n def test_2(animal):\n assert animal == 'fish'\n\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 3 passed *\"])"},{"attributeType":"None","col":8,"comment":"null","endLoc":727,"id":1944,"name":"excinfo","nodeType":"Attribute","startLoc":727,"text":"self.excinfo"},{"attributeType":"null","col":8,"comment":"null","endLoc":724,"id":1945,"name":"expected_exception","nodeType":"Attribute","startLoc":724,"text":"self.expected_exception"},{"attributeType":"bool","col":4,"comment":"null","endLoc":35,"id":1946,"name":"nofuncargs","nodeType":"Attribute","startLoc":35,"text":"nofuncargs"},{"className":"TestCaseFunction","col":0,"comment":"null","endLoc":237,"id":1947,"nodeType":"Class","startLoc":109,"text":"class TestCaseFunction(Function):\n nofuncargs = True\n _excinfo = None\n _testcase = None\n\n def setup(self):\n self._testcase = self.parent.obj(self.name)\n self._fix_unittest_skip_decorator()\n self._obj = getattr(self._testcase, self.name)\n if hasattr(self, \"_request\"):\n self._request._fillfixtures()\n\n def _fix_unittest_skip_decorator(self):\n \"\"\"\n The @unittest.skip decorator calls functools.wraps(self._testcase)\n The call to functools.wraps() fails unless self._testcase\n has a __name__ attribute. This is usually automatically supplied\n if the test is a function or method, but we need to add manually\n here.\n\n See issue #1169\n \"\"\"\n if sys.version_info[0] == 2:\n setattr(self._testcase, \"__name__\", self.name)\n\n def teardown(self):\n self._testcase = None\n self._obj = None\n\n def startTest(self, testcase):\n pass\n\n def _addexcinfo(self, rawexcinfo):\n # unwrap potential exception info (see twisted trial support below)\n rawexcinfo = getattr(rawexcinfo, \"_rawexcinfo\", rawexcinfo)\n try:\n excinfo = _pytest._code.ExceptionInfo(rawexcinfo)\n # invoke the attributes to trigger storing the traceback\n # trial causes some issue there\n excinfo.value\n excinfo.traceback\n except TypeError:\n try:\n try:\n values = traceback.format_exception(*rawexcinfo)\n values.insert(\n 0,\n \"NOTE: Incompatible Exception Representation, \"\n \"displaying natively:\\n\\n\",\n )\n fail(\"\".join(values), pytrace=False)\n except (fail.Exception, KeyboardInterrupt):\n raise\n except: # noqa\n fail(\n \"ERROR: Unknown Incompatible Exception \"\n \"representation:\\n%r\" % (rawexcinfo,),\n pytrace=False,\n )\n except KeyboardInterrupt:\n raise\n except fail.Exception:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n self.__dict__.setdefault(\"_excinfo\", []).append(excinfo)\n\n def addError(self, testcase, rawexcinfo):\n self._addexcinfo(rawexcinfo)\n\n def addFailure(self, testcase, rawexcinfo):\n self._addexcinfo(rawexcinfo)\n\n def addSkip(self, testcase, reason):\n try:\n skip(reason)\n except skip.Exception:\n self._skipped_by_mark = True\n self._addexcinfo(sys.exc_info())\n\n def addExpectedFailure(self, testcase, rawexcinfo, reason=\"\"):\n try:\n xfail(str(reason))\n except xfail.Exception:\n self._addexcinfo(sys.exc_info())\n\n def addUnexpectedSuccess(self, testcase, reason=\"\"):\n self._unexpectedsuccess = reason\n\n def addSuccess(self, testcase):\n pass\n\n def stopTest(self, testcase):\n pass\n\n def _handle_skip(self):\n # implements the skipping machinery (see #2137)\n # analog to pythons Lib/unittest/case.py:run\n testMethod = getattr(self._testcase, self._testcase._testMethodName)\n if getattr(self._testcase.__class__, \"__unittest_skip__\", False) or getattr(\n testMethod, \"__unittest_skip__\", False\n ):\n # If the class or method was skipped.\n skip_why = getattr(\n self._testcase.__class__, \"__unittest_skip_why__\", \"\"\n ) or getattr(testMethod, \"__unittest_skip_why__\", \"\")\n try: # PY3, unittest2 on PY2\n self._testcase._addSkip(self, self._testcase, skip_why)\n except TypeError: # PY2\n if sys.version_info[0] != 2:\n raise\n self._testcase._addSkip(self, skip_why)\n return True\n return False\n\n def runtest(self):\n if self.config.pluginmanager.get_plugin(\"pdbinvoke\") is None:\n self._testcase(result=self)\n else:\n # disables tearDown and cleanups for post mortem debugging (see #1890)\n if self._handle_skip():\n return\n self._testcase.debug()\n\n def _prunetraceback(self, excinfo):\n Function._prunetraceback(self, excinfo)\n traceback = excinfo.traceback.filter(\n lambda x: not x.frame.f_globals.get(\"__unittest\")\n )\n if traceback:\n excinfo.traceback = traceback"},{"col":4,"comment":"null","endLoc":119,"header":"def setup(self)","id":1948,"name":"setup","nodeType":"Function","startLoc":114,"text":"def setup(self):\n self._testcase = self.parent.obj(self.name)\n self._fix_unittest_skip_decorator()\n self._obj = getattr(self._testcase, self.name)\n if hasattr(self, \"_request\"):\n self._request._fillfixtures()"},{"attributeType":"null","col":8,"comment":"null","endLoc":726,"id":1949,"name":"match_expr","nodeType":"Attribute","startLoc":726,"text":"self.match_expr"},{"attributeType":"null","col":8,"comment":"null","endLoc":725,"id":1950,"name":"message","nodeType":"Attribute","startLoc":725,"text":"self.message"},{"col":4,"comment":"null","endLoc":1378,"header":"def test_parametrize_auto_scope_indirect(self, testdir)","id":1951,"name":"test_parametrize_auto_scope_indirect","nodeType":"Function","startLoc":1357,"text":"def test_parametrize_auto_scope_indirect(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='session')\n def echo(request):\n return request.param\n\n @pytest.mark.parametrize('animal, echo', [(\"dog\", 1), (\"cat\", 2)], indirect=['echo'])\n def test_1(animal, echo):\n assert animal in ('dog', 'cat')\n assert echo in (1, 2, 3)\n\n @pytest.mark.parametrize('animal, echo', [('fish', 3)], indirect=['echo'])\n def test_2(animal, echo):\n assert animal == 'fish'\n assert echo in (1, 2, 3)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 3 passed *\"])"},{"col":4,"comment":"\n The @unittest.skip decorator calls functools.wraps(self._testcase)\n The call to functools.wraps() fails unless self._testcase\n has a __name__ attribute. This is usually automatically supplied\n if the test is a function or method, but we need to add manually\n here.\n\n See issue #1169\n ","endLoc":132,"header":"def _fix_unittest_skip_decorator(self)","id":1952,"name":"_fix_unittest_skip_decorator","nodeType":"Function","startLoc":121,"text":"def _fix_unittest_skip_decorator(self):\n \"\"\"\n The @unittest.skip decorator calls functools.wraps(self._testcase)\n The call to functools.wraps() fails unless self._testcase\n has a __name__ attribute. This is usually automatically supplied\n if the test is a function or method, but we need to add manually\n here.\n\n See issue #1169\n \"\"\"\n if sys.version_info[0] == 2:\n setattr(self._testcase, \"__name__\", self.name)"},{"col":0,"comment":"null","endLoc":1774,"header":"def setattr(__obj: object, __name: str, __value: Any) -> None","id":1953,"name":"setattr","nodeType":"Function","startLoc":1774,"text":"def setattr(__obj: object, __name: str, __value: Any) -> None: ..."},{"col":0,"comment":"__cmp__ implementation which raises TypeError. Used\n by Approx base classes to implement only == and != and raise a\n TypeError for other comparisons.\n\n Needed in Python 2 only, Python 3 all it takes is not implementing the\n other operators at all.\n ","endLoc":38,"header":"def _cmp_raises_type_error(self, other)","id":1954,"name":"_cmp_raises_type_error","nodeType":"Function","startLoc":27,"text":"def _cmp_raises_type_error(self, other):\n \"\"\"__cmp__ implementation which raises TypeError. Used\n by Approx base classes to implement only == and != and raise a\n TypeError for other comparisons.\n\n Needed in Python 2 only, Python 3 all it takes is not implementing the\n other operators at all.\n \"\"\"\n __tracebackhide__ = True\n raise TypeError(\n \"Comparison operators other than == and != not supported by approx objects\"\n )"},{"col":4,"comment":"null","endLoc":619,"header":"def _factorytraceback(self)","id":1955,"name":"_factorytraceback","nodeType":"Function","startLoc":611,"text":"def _factorytraceback(self):\n lines = []\n for fixturedef in self._get_fixturestack():\n factory = fixturedef.func\n fs, lineno = getfslineno(factory)\n p = self._pyfuncitem.session.fspath.bestrelpath(fs)\n args = _format_args(factory)\n lines.append(\"%s:%d: def %s%s\" % (p, lineno + 1, factory.__name__, args))\n return lines"},{"col":4,"comment":"null","endLoc":515,"header":"def _get_fixturestack(self)","id":1956,"name":"_get_fixturestack","nodeType":"Function","startLoc":506,"text":"def _get_fixturestack(self):\n current = self\n values = []\n while 1:\n fixturedef = getattr(current, \"_fixturedef\", None)\n if fixturedef is None:\n values.reverse()\n return values\n values.append(fixturedef)\n current = current._parent_request"},{"col":4,"comment":"null","endLoc":894,"header":"def execute(self, request)","id":1958,"name":"execute","nodeType":"Function","startLoc":871,"text":"def execute(self, request):\n # get required arguments and register our own finish()\n # with their finalization\n for argname in self.argnames:\n fixturedef = request._get_active_fixturedef(argname)\n if argname != \"request\":\n fixturedef.addfinalizer(functools.partial(self.finish, request=request))\n\n my_cache_key = request.param_index\n cached_result = getattr(self, \"cached_result\", None)\n if cached_result is not None:\n result, cache_key, err = cached_result\n if my_cache_key == cache_key:\n if err is not None:\n six.reraise(*err)\n else:\n return result\n # we have a previous but differently parametrized fixture instance\n # so we need to tear it down before creating a new one\n self.finish(request)\n assert not hasattr(self, \"cached_result\")\n\n hook = self._fixturemanager.session.gethookproxy(request.node.fspath)\n return hook.pytest_fixture_setup(fixturedef=self, request=request)"},{"col":4,"comment":"null","endLoc":869,"header":"def finish(self, request)","id":1959,"name":"finish","nodeType":"Function","startLoc":846,"text":"def finish(self, request):\n exceptions = []\n try:\n while self._finalizers:\n try:\n func = self._finalizers.pop()\n func()\n except: # noqa\n exceptions.append(sys.exc_info())\n if exceptions:\n e = exceptions[0]\n # Ensure to not keep frame references through traceback.\n del exceptions\n six.reraise(*e)\n finally:\n hook = self._fixturemanager.session.gethookproxy(request.node.fspath)\n hook.pytest_fixture_post_finalizer(fixturedef=self, request=request)\n # even if finalization fails, we invalidate\n # the cached fixture value and remove\n # all finalizers because they may be bound methods which will\n # keep instances alive\n if hasattr(self, \"cached_result\"):\n del self.cached_result\n self._finalizers = []"},{"col":4,"comment":"null","endLoc":136,"header":"def teardown(self)","id":1960,"name":"teardown","nodeType":"Function","startLoc":134,"text":"def teardown(self):\n self._testcase = None\n self._obj = None"},{"col":4,"comment":"null","endLoc":139,"header":"def startTest(self, testcase)","id":1961,"name":"startTest","nodeType":"Function","startLoc":138,"text":"def startTest(self, testcase):\n pass"},{"col":4,"comment":"null","endLoc":172,"header":"def _addexcinfo(self, rawexcinfo)","id":1962,"name":"_addexcinfo","nodeType":"Function","startLoc":141,"text":"def _addexcinfo(self, rawexcinfo):\n # unwrap potential exception info (see twisted trial support below)\n rawexcinfo = getattr(rawexcinfo, \"_rawexcinfo\", rawexcinfo)\n try:\n excinfo = _pytest._code.ExceptionInfo(rawexcinfo)\n # invoke the attributes to trigger storing the traceback\n # trial causes some issue there\n excinfo.value\n excinfo.traceback\n except TypeError:\n try:\n try:\n values = traceback.format_exception(*rawexcinfo)\n values.insert(\n 0,\n \"NOTE: Incompatible Exception Representation, \"\n \"displaying natively:\\n\\n\",\n )\n fail(\"\".join(values), pytrace=False)\n except (fail.Exception, KeyboardInterrupt):\n raise\n except: # noqa\n fail(\n \"ERROR: Unknown Incompatible Exception \"\n \"representation:\\n%r\" % (rawexcinfo,),\n pytrace=False,\n )\n except KeyboardInterrupt:\n raise\n except fail.Exception:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n self.__dict__.setdefault(\"_excinfo\", []).append(excinfo)"},{"col":4,"comment":"null","endLoc":595,"header":"def _schedule_finalizers(self, fixturedef, subrequest)","id":1963,"name":"_schedule_finalizers","nodeType":"Function","startLoc":591,"text":"def _schedule_finalizers(self, fixturedef, subrequest):\n # if fixture function failed it might have registered finalizers\n self.session._setupstate.addfinalizer(\n functools.partial(fixturedef.finish, request=subrequest), subrequest.node\n )"},{"col":4,"comment":" Deprecated, use getfixturevalue. ","endLoc":486,"header":"def getfuncargvalue(self, argname)","id":1964,"name":"getfuncargvalue","nodeType":"Function","startLoc":481,"text":"def getfuncargvalue(self, argname):\n \"\"\" Deprecated, use getfixturevalue. \"\"\"\n from _pytest import deprecated\n\n warnings.warn(deprecated.GETFUNCARGVALUE, stacklevel=2)\n return self.getfixturevalue(argname)"},{"attributeType":"(type, (str))","col":0,"comment":"null","endLoc":24,"id":1965,"name":"BASE_TYPE","nodeType":"Attribute","startLoc":24,"text":"BASE_TYPE"},{"col":4,"comment":"null","endLoc":638,"header":"def __repr__(self)","id":1966,"name":"__repr__","nodeType":"Function","startLoc":637,"text":"def __repr__(self):\n return \"\" % (self.node)"},{"attributeType":"null","col":8,"comment":"null","endLoc":358,"id":1967,"name":"_arg2fixturedefs","nodeType":"Attribute","startLoc":358,"text":"self._arg2fixturedefs"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":359,"id":1968,"name":"_arg2index","nodeType":"Attribute","startLoc":359,"text":"self._arg2index"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":356,"id":1969,"name":"_fixture_defs","nodeType":"Attribute","startLoc":356,"text":"self._fixture_defs"},{"attributeType":"str","col":8,"comment":"null","endLoc":355,"id":1970,"name":"scope","nodeType":"Attribute","startLoc":355,"text":"self.scope"},{"col":0,"comment":"","endLoc":2,"header":"python_api.py#","id":1971,"name":"","nodeType":"Function","startLoc":2,"text":"BASE_TYPE = (type, STRING_TYPES)\n\nraises.Exception = fail.Exception"},{"col":4,"comment":"null","endLoc":1395,"header":"def test_parametrize_auto_scope_override_fixture(self, testdir)","id":1972,"name":"test_parametrize_auto_scope_override_fixture","nodeType":"Function","startLoc":1380,"text":"def test_parametrize_auto_scope_override_fixture(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='session', autouse=True)\n def animal():\n return 'fox'\n\n @pytest.mark.parametrize('animal', [\"dog\", \"cat\"])\n def test_1(animal):\n assert animal in ('dog', 'cat')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed *\"])"},{"attributeType":"None","col":8,"comment":"null","endLoc":353,"id":1973,"name":"fixturename","nodeType":"Attribute","startLoc":353,"text":"self.fixturename"},{"col":4,"comment":"null","endLoc":1422,"header":"def test_parametrize_all_indirects(self, testdir)","id":1974,"name":"test_parametrize_all_indirects","nodeType":"Function","startLoc":1397,"text":"def test_parametrize_all_indirects(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture()\n def animal(request):\n return request.param\n\n @pytest.fixture(scope='session')\n def echo(request):\n return request.param\n\n @pytest.mark.parametrize('animal, echo', [(\"dog\", 1), (\"cat\", 2)], indirect=True)\n def test_1(animal, echo):\n assert animal in ('dog', 'cat')\n assert echo in (1, 2, 3)\n\n @pytest.mark.parametrize('animal, echo', [(\"fish\", 3)], indirect=True)\n def test_2(animal, echo):\n assert animal == 'fish'\n assert echo in (1, 2, 3)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 3 passed *\"])"},{"attributeType":"null","col":8,"comment":"null","endLoc":360,"id":1975,"name":"_fixturemanager","nodeType":"Attribute","startLoc":360,"text":"self._fixturemanager"},{"attributeType":"{_fixtureinfo, session}","col":8,"comment":"null","endLoc":351,"id":1976,"name":"_pyfuncitem","nodeType":"Attribute","startLoc":351,"text":"self._pyfuncitem"},{"className":"SubRequest","col":0,"comment":" a sub request for handling getting a fixture from a\n test function/fixture. ","endLoc":673,"id":1977,"nodeType":"Class","startLoc":641,"text":"class SubRequest(FixtureRequest):\n \"\"\" a sub request for handling getting a fixture from a\n test function/fixture. \"\"\"\n\n def __init__(self, request, scope, param, param_index, fixturedef):\n self._parent_request = request\n self.fixturename = fixturedef.argname\n if param is not NOTSET:\n self.param = param\n self.param_index = param_index\n self.scope = scope\n self._fixturedef = fixturedef\n self._pyfuncitem = request._pyfuncitem\n self._fixture_defs = request._fixture_defs\n self._arg2fixturedefs = request._arg2fixturedefs\n self._arg2index = request._arg2index\n self._fixturemanager = request._fixturemanager\n\n def __repr__(self):\n return \"\" % (self.fixturename, self._pyfuncitem)\n\n def addfinalizer(self, finalizer):\n self._fixturedef.addfinalizer(finalizer)\n\n def _schedule_finalizers(self, fixturedef, subrequest):\n # if the executing fixturedef was not explicitly requested in the argument list (via\n # getfixturevalue inside the fixture call) then ensure this fixture def will be finished\n # first\n if fixturedef.argname not in self.funcargnames:\n fixturedef.addfinalizer(\n functools.partial(self._fixturedef.finish, request=self)\n )\n super(SubRequest, self)._schedule_finalizers(fixturedef, subrequest)"},{"col":4,"comment":"null","endLoc":660,"header":"def __repr__(self)","id":1978,"name":"__repr__","nodeType":"Function","startLoc":659,"text":"def __repr__(self):\n return \"\" % (self.fixturename, self._pyfuncitem)"},{"col":4,"comment":"null","endLoc":663,"header":"def addfinalizer(self, finalizer)","id":1979,"name":"addfinalizer","nodeType":"Function","startLoc":662,"text":"def addfinalizer(self, finalizer):\n self._fixturedef.addfinalizer(finalizer)"},{"col":4,"comment":"Integration test for (#3941)","endLoc":1455,"header":"def test_parametrize_some_arguments_auto_scope(self, testdir, monkeypatch)","id":1980,"name":"test_parametrize_some_arguments_auto_scope","nodeType":"Function","startLoc":1424,"text":"def test_parametrize_some_arguments_auto_scope(self, testdir, monkeypatch):\n \"\"\"Integration test for (#3941)\"\"\"\n class_fix_setup = []\n monkeypatch.setattr(sys, \"class_fix_setup\", class_fix_setup, raising=False)\n func_fix_setup = []\n monkeypatch.setattr(sys, \"func_fix_setup\", func_fix_setup, raising=False)\n\n testdir.makepyfile(\n \"\"\"\n import pytest\n import sys\n\n @pytest.fixture(scope='class', autouse=True)\n def class_fix(request):\n sys.class_fix_setup.append(request.param)\n\n @pytest.fixture(autouse=True)\n def func_fix():\n sys.func_fix_setup.append(True)\n\n @pytest.mark.parametrize('class_fix', [10, 20], indirect=True)\n class Test:\n def test_foo(self):\n pass\n def test_bar(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest_inprocess()\n result.stdout.fnmatch_lines([\"* 4 passed in *\"])\n assert func_fix_setup == [True] * 4\n assert class_fix_setup == [10, 20]"},{"col":4,"comment":"null","endLoc":673,"header":"def _schedule_finalizers(self, fixturedef, subrequest)","id":1981,"name":"_schedule_finalizers","nodeType":"Function","startLoc":665,"text":"def _schedule_finalizers(self, fixturedef, subrequest):\n # if the executing fixturedef was not explicitly requested in the argument list (via\n # getfixturevalue inside the fixture call) then ensure this fixture def will be finished\n # first\n if fixturedef.argname not in self.funcargnames:\n fixturedef.addfinalizer(\n functools.partial(self._fixturedef.finish, request=self)\n )\n super(SubRequest, self)._schedule_finalizers(fixturedef, subrequest)"},{"col":4,"comment":"null","endLoc":1489,"header":"def test_parametrize_issue634(self, testdir)","id":1982,"name":"test_parametrize_issue634","nodeType":"Function","startLoc":1457,"text":"def test_parametrize_issue634(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='module')\n def foo(request):\n print('preparing foo-%d' % request.param)\n return 'foo-%d' % request.param\n\n def test_one(foo):\n pass\n\n def test_two(foo):\n pass\n\n test_two.test_with = (2, 3)\n\n def pytest_generate_tests(metafunc):\n params = (1, 2, 3, 4)\n if not 'foo' in metafunc.fixturenames:\n return\n\n test_with = getattr(metafunc.function, 'test_with', None)\n if test_with:\n params = test_with\n metafunc.parametrize('foo', params, indirect=True)\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n output = result.stdout.str()\n assert output.count(\"preparing foo-2\") == 1\n assert output.count(\"preparing foo-3\") == 1"},{"id":1983,"name":"release-4.1.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-4.1.1\n=======================================\n\npytest 4.1.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Anton Lodder\n* Bruno Oliveira\n* Daniel Hahler\n* David Vo\n* Oscar Benjamin\n* Ronny Pfannschmidt\n* Victor Maryama\n* Yoav Caspi\n* dmitry.dygalo\n\n\nHappy testing,\nThe pytest Development Team\n"},{"className":"TestMarkersWithParametrization","col":0,"comment":"#308","endLoc":1780,"id":1984,"nodeType":"Class","startLoc":1492,"text":"class TestMarkersWithParametrization(object):\n \"\"\"#308\"\"\"\n\n def test_simple_mark(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.foo\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(1, 3, marks=pytest.mark.bar),\n (2, 3),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n items = testdir.getitems(s)\n assert len(items) == 3\n for item in items:\n assert \"foo\" in item.keywords\n assert \"bar\" not in items[0].keywords\n assert \"bar\" in items[1].keywords\n assert \"bar\" not in items[2].keywords\n\n def test_select_based_on_mark(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(2, 3, marks=pytest.mark.foo),\n (3, 4),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n testdir.makepyfile(s)\n rec = testdir.inline_run(\"-m\", \"foo\", SHOW_PYTEST_WARNINGS_ARG)\n passed, skipped, fail = rec.listoutcomes()\n assert len(passed) == 1\n assert len(skipped) == 0\n assert len(fail) == 0\n\n @pytest.mark.xfail(reason=\"is this important to support??\")\n def test_nested_marks(self, testdir):\n s = \"\"\"\n import pytest\n mastermark = pytest.mark.foo(pytest.mark.bar)\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n mastermark((1, 3)),\n (2, 3),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n items = testdir.getitems(s)\n assert len(items) == 3\n for mark in [\"foo\", \"bar\"]:\n assert mark not in items[0].keywords\n assert mark in items[1].keywords\n assert mark not in items[2].keywords\n\n def test_simple_xfail(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(1, 3, marks=pytest.mark.xfail),\n (2, 3),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n # xfail is skip??\n reprec.assertoutcome(passed=2, skipped=1)\n\n def test_simple_xfail_single_argname(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize(\"n\", [\n 2,\n pytest.param(3, marks=pytest.mark.xfail),\n 4,\n ])\n def test_isEven(n):\n assert n % 2 == 0\n \"\"\"\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n reprec.assertoutcome(passed=2, skipped=1)\n\n def test_xfail_with_arg(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(1, 3, marks=pytest.mark.xfail(\"True\")),\n (2, 3),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n reprec.assertoutcome(passed=2, skipped=1)\n\n def test_xfail_with_kwarg(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(1, 3, marks=pytest.mark.xfail(reason=\"some bug\")),\n (2, 3),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n reprec.assertoutcome(passed=2, skipped=1)\n\n def test_xfail_with_arg_and_kwarg(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(1, 3, marks=pytest.mark.xfail(\"True\", reason=\"some bug\")),\n (2, 3),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n reprec.assertoutcome(passed=2, skipped=1)\n\n @pytest.mark.parametrize(\"strict\", [True, False])\n def test_xfail_passing_is_xpass(self, testdir, strict):\n s = \"\"\"\n import pytest\n\n m = pytest.mark.xfail(\"sys.version_info > (0, 0, 0)\", reason=\"some bug\", strict={strict})\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(2, 3, marks=m),\n (3, 4),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\".format(\n strict=strict\n )\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n passed, failed = (2, 1) if strict else (3, 0)\n reprec.assertoutcome(passed=passed, failed=failed)\n\n def test_parametrize_called_in_generate_tests(self, testdir):\n s = \"\"\"\n import pytest\n\n\n def pytest_generate_tests(metafunc):\n passingTestData = [(1, 2),\n (2, 3)]\n failingTestData = [(1, 3),\n (2, 2)]\n\n testData = passingTestData + [pytest.param(*d, marks=pytest.mark.xfail)\n for d in failingTestData]\n metafunc.parametrize((\"n\", \"expected\"), testData)\n\n\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n reprec.assertoutcome(passed=2, skipped=2)\n\n def test_parametrize_ID_generation_string_int_works(self, testdir):\n \"\"\"#290\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def myfixture():\n return 'example'\n @pytest.mark.parametrize(\n 'limit', (0, '0'))\n def test_limit(limit, myfixture):\n return\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n @pytest.mark.parametrize(\"strict\", [True, False])\n def test_parametrize_marked_value(self, testdir, strict):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n pytest.param(\n 2,3,\n marks=pytest.mark.xfail(\"sys.version_info > (0, 0, 0)\", reason=\"some bug\", strict={strict}),\n ),\n pytest.param(\n 2,3,\n marks=[pytest.mark.xfail(\"sys.version_info > (0, 0, 0)\", reason=\"some bug\", strict={strict})],\n ),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\".format(\n strict=strict\n )\n testdir.makepyfile(s)\n reprec = testdir.inline_run()\n passed, failed = (0, 2) if strict else (2, 0)\n reprec.assertoutcome(passed=passed, failed=failed)\n\n def test_pytest_make_parametrize_id(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_make_parametrize_id(config, val):\n return str(val * 2)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize(\"x\", range(2))\n def test_func(x):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines([\"*test_func*0*PASS*\", \"*test_func*2*PASS*\"])\n\n def test_pytest_make_parametrize_id_with_argname(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_make_parametrize_id(config, val, argname):\n return str(val * 2 if argname == 'x' else val * 10)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize(\"x\", range(2))\n def test_func_a(x):\n pass\n\n @pytest.mark.parametrize(\"y\", [1])\n def test_func_b(y):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n [\"*test_func_a*0*PASS*\", \"*test_func_a*2*PASS*\", \"*test_func_b*10*PASS*\"]\n )\n\n def test_parametrize_positional_args(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize(\"a\", [1], False)\n def test_foo(a):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.assert_outcomes(passed=1)"},{"col":4,"comment":"null","endLoc":1514,"header":"def test_simple_mark(self, testdir)","id":1985,"name":"test_simple_mark","nodeType":"Function","startLoc":1495,"text":"def test_simple_mark(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.foo\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(1, 3, marks=pytest.mark.bar),\n (2, 3),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n items = testdir.getitems(s)\n assert len(items) == 3\n for item in items:\n assert \"foo\" in item.keywords\n assert \"bar\" not in items[0].keywords\n assert \"bar\" in items[1].keywords\n assert \"bar\" not in items[2].keywords"},{"col":4,"comment":"null","endLoc":1533,"header":"def test_select_based_on_mark(self, testdir)","id":1986,"name":"test_select_based_on_mark","nodeType":"Function","startLoc":1516,"text":"def test_select_based_on_mark(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(2, 3, marks=pytest.mark.foo),\n (3, 4),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n testdir.makepyfile(s)\n rec = testdir.inline_run(\"-m\", \"foo\", SHOW_PYTEST_WARNINGS_ARG)\n passed, skipped, fail = rec.listoutcomes()\n assert len(passed) == 1\n assert len(skipped) == 0\n assert len(fail) == 0"},{"attributeType":"null","col":8,"comment":"null","endLoc":655,"id":1987,"name":"_arg2fixturedefs","nodeType":"Attribute","startLoc":655,"text":"self._arg2fixturedefs"},{"id":1988,"name":"src/_pytest/config","nodeType":"Package"},{"fileName":"findpaths.py","filePath":"src/_pytest/config","id":1989,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport os\n\nimport py\n\nfrom .exceptions import UsageError\nfrom _pytest.outcomes import fail\n\n\ndef exists(path, ignore=EnvironmentError):\n try:\n return path.check()\n except ignore:\n return False\n\n\ndef getcfg(args, config=None):\n \"\"\"\n Search the list of arguments for a valid ini-file for pytest,\n and return a tuple of (rootdir, inifile, cfg-dict).\n\n note: config is optional and used only to issue warnings explicitly (#2891).\n \"\"\"\n from _pytest.deprecated import CFG_PYTEST_SECTION\n\n inibasenames = [\"pytest.ini\", \"tox.ini\", \"setup.cfg\"]\n args = [x for x in args if not str(x).startswith(\"-\")]\n if not args:\n args = [py.path.local()]\n for arg in args:\n arg = py.path.local(arg)\n for base in arg.parts(reverse=True):\n for inibasename in inibasenames:\n p = base.join(inibasename)\n if exists(p):\n try:\n iniconfig = py.iniconfig.IniConfig(p)\n except py.iniconfig.ParseError as exc:\n raise UsageError(str(exc))\n\n if (\n inibasename == \"setup.cfg\"\n and \"tool:pytest\" in iniconfig.sections\n ):\n return base, p, iniconfig[\"tool:pytest\"]\n elif \"pytest\" in iniconfig.sections:\n if inibasename == \"setup.cfg\" and config is not None:\n\n fail(\n CFG_PYTEST_SECTION.format(filename=inibasename),\n pytrace=False,\n )\n return base, p, iniconfig[\"pytest\"]\n elif inibasename == \"pytest.ini\":\n # allowed to be empty\n return base, p, {}\n return None, None, None\n\n\ndef get_common_ancestor(paths):\n common_ancestor = None\n for path in paths:\n if not path.exists():\n continue\n if common_ancestor is None:\n common_ancestor = path\n else:\n if path.relto(common_ancestor) or path == common_ancestor:\n continue\n elif common_ancestor.relto(path):\n common_ancestor = path\n else:\n shared = path.common(common_ancestor)\n if shared is not None:\n common_ancestor = shared\n if common_ancestor is None:\n common_ancestor = py.path.local()\n elif common_ancestor.isfile():\n common_ancestor = common_ancestor.dirpath()\n return common_ancestor\n\n\ndef get_dirs_from_args(args):\n def is_option(x):\n return str(x).startswith(\"-\")\n\n def get_file_part_from_node_id(x):\n return str(x).split(\"::\")[0]\n\n def get_dir_from_path(path):\n if path.isdir():\n return path\n return py.path.local(path.dirname)\n\n # These look like paths but may not exist\n possible_paths = (\n py.path.local(get_file_part_from_node_id(arg))\n for arg in args\n if not is_option(arg)\n )\n\n return [get_dir_from_path(path) for path in possible_paths if path.exists()]\n\n\ndef determine_setup(inifile, args, rootdir_cmd_arg=None, config=None):\n dirs = get_dirs_from_args(args)\n if inifile:\n iniconfig = py.iniconfig.IniConfig(inifile)\n is_cfg_file = str(inifile).endswith(\".cfg\")\n sections = [\"tool:pytest\", \"pytest\"] if is_cfg_file else [\"pytest\"]\n for section in sections:\n try:\n inicfg = iniconfig[section]\n if is_cfg_file and section == \"pytest\" and config is not None:\n from _pytest.deprecated import CFG_PYTEST_SECTION\n\n fail(\n CFG_PYTEST_SECTION.format(filename=str(inifile)), pytrace=False\n )\n break\n except KeyError:\n inicfg = None\n if rootdir_cmd_arg is None:\n rootdir = get_common_ancestor(dirs)\n else:\n ancestor = get_common_ancestor(dirs)\n rootdir, inifile, inicfg = getcfg([ancestor], config=config)\n if rootdir is None and rootdir_cmd_arg is None:\n for possible_rootdir in ancestor.parts(reverse=True):\n if possible_rootdir.join(\"setup.py\").exists():\n rootdir = possible_rootdir\n break\n else:\n if dirs != [ancestor]:\n rootdir, inifile, inicfg = getcfg(dirs, config=config)\n if rootdir is None:\n if config is not None:\n cwd = config.invocation_dir\n else:\n cwd = py.path.local()\n rootdir = get_common_ancestor([cwd, ancestor])\n is_fs_root = os.path.splitdrive(str(rootdir))[1] == \"/\"\n if is_fs_root:\n rootdir = ancestor\n if rootdir_cmd_arg:\n rootdir = py.path.local(os.path.expandvars(rootdir_cmd_arg))\n if not rootdir.isdir():\n raise UsageError(\n \"Directory '{}' not found. Check your '--rootdir' option.\".format(\n rootdir\n )\n )\n return rootdir, inifile, inicfg or {}\n"},{"col":4,"comment":"null","endLoc":1554,"header":"@pytest.mark.xfail(reason=\"is this important to support??\")\n def test_nested_marks(self, testdir)","id":1990,"name":"test_nested_marks","nodeType":"Function","startLoc":1535,"text":"@pytest.mark.xfail(reason=\"is this important to support??\")\n def test_nested_marks(self, testdir):\n s = \"\"\"\n import pytest\n mastermark = pytest.mark.foo(pytest.mark.bar)\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n mastermark((1, 3)),\n (2, 3),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n items = testdir.getitems(s)\n assert len(items) == 3\n for mark in [\"foo\", \"bar\"]:\n assert mark not in items[0].keywords\n assert mark in items[1].keywords\n assert mark not in items[2].keywords"},{"col":0,"comment":"\n Search the list of arguments for a valid ini-file for pytest,\n and return a tuple of (rootdir, inifile, cfg-dict).\n\n note: config is optional and used only to issue warnings explicitly (#2891).\n ","endLoc":57,"header":"def getcfg(args, config=None)","id":1991,"name":"getcfg","nodeType":"Function","startLoc":17,"text":"def getcfg(args, config=None):\n \"\"\"\n Search the list of arguments for a valid ini-file for pytest,\n and return a tuple of (rootdir, inifile, cfg-dict).\n\n note: config is optional and used only to issue warnings explicitly (#2891).\n \"\"\"\n from _pytest.deprecated import CFG_PYTEST_SECTION\n\n inibasenames = [\"pytest.ini\", \"tox.ini\", \"setup.cfg\"]\n args = [x for x in args if not str(x).startswith(\"-\")]\n if not args:\n args = [py.path.local()]\n for arg in args:\n arg = py.path.local(arg)\n for base in arg.parts(reverse=True):\n for inibasename in inibasenames:\n p = base.join(inibasename)\n if exists(p):\n try:\n iniconfig = py.iniconfig.IniConfig(p)\n except py.iniconfig.ParseError as exc:\n raise UsageError(str(exc))\n\n if (\n inibasename == \"setup.cfg\"\n and \"tool:pytest\" in iniconfig.sections\n ):\n return base, p, iniconfig[\"tool:pytest\"]\n elif \"pytest\" in iniconfig.sections:\n if inibasename == \"setup.cfg\" and config is not None:\n\n fail(\n CFG_PYTEST_SECTION.format(filename=inibasename),\n pytrace=False,\n )\n return base, p, iniconfig[\"pytest\"]\n elif inibasename == \"pytest.ini\":\n # allowed to be empty\n return base, p, {}\n return None, None, None"},{"attributeType":"null","col":8,"comment":"null","endLoc":656,"id":1992,"name":"_arg2index","nodeType":"Attribute","startLoc":656,"text":"self._arg2index"},{"col":4,"comment":"null","endLoc":1571,"header":"def test_simple_xfail(self, testdir)","id":1993,"name":"test_simple_xfail","nodeType":"Function","startLoc":1556,"text":"def test_simple_xfail(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(1, 3, marks=pytest.mark.xfail),\n (2, 3),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n # xfail is skip??\n reprec.assertoutcome(passed=2, skipped=1)"},{"attributeType":"{argname}","col":8,"comment":"null","endLoc":652,"id":1994,"name":"_fixturedef","nodeType":"Attribute","startLoc":652,"text":"self._fixturedef"},{"attributeType":"null","col":8,"comment":"null","endLoc":654,"id":1995,"name":"_fixture_defs","nodeType":"Attribute","startLoc":654,"text":"self._fixture_defs"},{"col":4,"comment":"null","endLoc":1587,"header":"def test_simple_xfail_single_argname(self, testdir)","id":1996,"name":"test_simple_xfail_single_argname","nodeType":"Function","startLoc":1573,"text":"def test_simple_xfail_single_argname(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize(\"n\", [\n 2,\n pytest.param(3, marks=pytest.mark.xfail),\n 4,\n ])\n def test_isEven(n):\n assert n % 2 == 0\n \"\"\"\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n reprec.assertoutcome(passed=2, skipped=1)"},{"attributeType":"null","col":12,"comment":"null","endLoc":649,"id":1997,"name":"param","nodeType":"Attribute","startLoc":649,"text":"self.param"},{"col":4,"comment":"null","endLoc":1603,"header":"def test_xfail_with_arg(self, testdir)","id":1998,"name":"test_xfail_with_arg","nodeType":"Function","startLoc":1589,"text":"def test_xfail_with_arg(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(1, 3, marks=pytest.mark.xfail(\"True\")),\n (2, 3),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n reprec.assertoutcome(passed=2, skipped=1)"},{"col":4,"comment":"null","endLoc":1619,"header":"def test_xfail_with_kwarg(self, testdir)","id":1999,"name":"test_xfail_with_kwarg","nodeType":"Function","startLoc":1605,"text":"def test_xfail_with_kwarg(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(1, 3, marks=pytest.mark.xfail(reason=\"some bug\")),\n (2, 3),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n reprec.assertoutcome(passed=2, skipped=1)"},{"attributeType":"{_pyfuncitem, _fixture_defs, _arg2fixturedefs, _arg2index, _fixturemanager}","col":8,"comment":"null","endLoc":646,"id":2000,"name":"_parent_request","nodeType":"Attribute","startLoc":646,"text":"self._parent_request"},{"attributeType":"null","col":8,"comment":"null","endLoc":651,"id":2001,"name":"scope","nodeType":"Attribute","startLoc":651,"text":"self.scope"},{"attributeType":"null","col":8,"comment":"null","endLoc":647,"id":2002,"name":"fixturename","nodeType":"Attribute","startLoc":647,"text":"self.fixturename"},{"col":4,"comment":"null","endLoc":1635,"header":"def test_xfail_with_arg_and_kwarg(self, testdir)","id":2003,"name":"test_xfail_with_arg_and_kwarg","nodeType":"Function","startLoc":1621,"text":"def test_xfail_with_arg_and_kwarg(self, testdir):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(1, 3, marks=pytest.mark.xfail(\"True\", reason=\"some bug\")),\n (2, 3),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n reprec.assertoutcome(passed=2, skipped=1)"},{"attributeType":"null","col":8,"comment":"null","endLoc":657,"id":2004,"name":"_fixturemanager","nodeType":"Attribute","startLoc":657,"text":"self._fixturemanager"},{"attributeType":"null","col":8,"comment":"null","endLoc":650,"id":2005,"name":"param_index","nodeType":"Attribute","startLoc":650,"text":"self.param_index"},{"col":4,"comment":"null","endLoc":1657,"header":"@pytest.mark.parametrize(\"strict\", [True, False])\n def test_xfail_passing_is_xpass(self, testdir, strict)","id":2006,"name":"test_xfail_passing_is_xpass","nodeType":"Function","startLoc":1637,"text":"@pytest.mark.parametrize(\"strict\", [True, False])\n def test_xfail_passing_is_xpass(self, testdir, strict):\n s = \"\"\"\n import pytest\n\n m = pytest.mark.xfail(\"sys.version_info > (0, 0, 0)\", reason=\"some bug\", strict={strict})\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n (1, 2),\n pytest.param(2, 3, marks=m),\n (3, 4),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\".format(\n strict=strict\n )\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n passed, failed = (2, 1) if strict else (3, 0)\n reprec.assertoutcome(passed=passed, failed=failed)"},{"attributeType":"null","col":8,"comment":"null","endLoc":653,"id":2007,"name":"_pyfuncitem","nodeType":"Attribute","startLoc":653,"text":"self._pyfuncitem"},{"className":"FixtureLookupErrorRepr","col":0,"comment":"null","endLoc":777,"id":2008,"nodeType":"Class","startLoc":753,"text":"class FixtureLookupErrorRepr(TerminalRepr):\n def __init__(self, filename, firstlineno, tblines, errorstring, argname):\n self.tblines = tblines\n self.errorstring = errorstring\n self.filename = filename\n self.firstlineno = firstlineno\n self.argname = argname\n\n def toterminal(self, tw):\n # tw.line(\"FixtureLookupError: %s\" %(self.argname), red=True)\n for tbline in self.tblines:\n tw.line(tbline.rstrip())\n lines = self.errorstring.split(\"\\n\")\n if lines:\n tw.line(\n \"{} {}\".format(FormattedExcinfo.fail_marker, lines[0].strip()),\n red=True,\n )\n for line in lines[1:]:\n tw.line(\n \"{} {}\".format(FormattedExcinfo.flow_marker, line.strip()),\n red=True,\n )\n tw.line()\n tw.line(\"%s:%d\" % (self.filename, self.firstlineno + 1))"},{"col":4,"comment":"null","endLoc":759,"header":"def __init__(self, filename, firstlineno, tblines, errorstring, argname)","id":2009,"name":"__init__","nodeType":"Function","startLoc":754,"text":"def __init__(self, filename, firstlineno, tblines, errorstring, argname):\n self.tblines = tblines\n self.errorstring = errorstring\n self.filename = filename\n self.firstlineno = firstlineno\n self.argname = argname"},{"col":4,"comment":"null","endLoc":777,"header":"def toterminal(self, tw)","id":2010,"name":"toterminal","nodeType":"Function","startLoc":761,"text":"def toterminal(self, tw):\n # tw.line(\"FixtureLookupError: %s\" %(self.argname), red=True)\n for tbline in self.tblines:\n tw.line(tbline.rstrip())\n lines = self.errorstring.split(\"\\n\")\n if lines:\n tw.line(\n \"{} {}\".format(FormattedExcinfo.fail_marker, lines[0].strip()),\n red=True,\n )\n for line in lines[1:]:\n tw.line(\n \"{} {}\".format(FormattedExcinfo.flow_marker, line.strip()),\n red=True,\n )\n tw.line()\n tw.line(\"%s:%d\" % (self.filename, self.firstlineno + 1))"},{"col":4,"comment":"null","endLoc":59,"header":"def test_addhooks_nohooks(self, testdir)","id":2011,"name":"test_addhooks_nohooks","nodeType":"Function","startLoc":49,"text":"def test_addhooks_nohooks(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import sys\n def pytest_addhooks(pluginmanager):\n pluginmanager.add_hookspecs(sys)\n \"\"\"\n )\n res = testdir.runpytest()\n assert res.ret != 0\n res.stderr.fnmatch_lines([\"*did not find*sys*\"])"},{"col":4,"comment":"null","endLoc":72,"header":"def test_do_option_postinitialize(self, testdir)","id":2012,"name":"test_do_option_postinitialize","nodeType":"Function","startLoc":61,"text":"def test_do_option_postinitialize(self, testdir):\n config = testdir.parseconfigure()\n assert not hasattr(config.option, \"test123\")\n p = testdir.makepyfile(\n \"\"\"\n def pytest_addoption(parser):\n parser.addoption('--test123', action=\"store_true\",\n default=True)\n \"\"\"\n )\n config.pluginmanager._importconftest(p)\n assert config.option.test123"},{"col":4,"comment":"null","endLoc":1680,"header":"def test_parametrize_called_in_generate_tests(self, testdir)","id":2013,"name":"test_parametrize_called_in_generate_tests","nodeType":"Function","startLoc":1659,"text":"def test_parametrize_called_in_generate_tests(self, testdir):\n s = \"\"\"\n import pytest\n\n\n def pytest_generate_tests(metafunc):\n passingTestData = [(1, 2),\n (2, 3)]\n failingTestData = [(1, 3),\n (2, 2)]\n\n testData = passingTestData + [pytest.param(*d, marks=pytest.mark.xfail)\n for d in failingTestData]\n metafunc.parametrize((\"n\", \"expected\"), testData)\n\n\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\"\n testdir.makepyfile(s)\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n reprec.assertoutcome(passed=2, skipped=2)"},{"col":4,"comment":"null","endLoc":92,"header":"def test_configure(self, testdir)","id":2014,"name":"test_configure","nodeType":"Function","startLoc":74,"text":"def test_configure(self, testdir):\n config = testdir.parseconfig()\n values = []\n\n class A(object):\n def pytest_configure(self, config):\n values.append(self)\n\n config.pluginmanager.register(A())\n assert len(values) == 0\n config._do_configure()\n assert len(values) == 1\n config.pluginmanager.register(A()) # leads to a configured() plugin\n assert len(values) == 2\n assert values[0] != values[1]\n\n config._ensure_unconfigure()\n config.pluginmanager.register(A())\n assert len(values) == 2"},{"attributeType":"null","col":8,"comment":"null","endLoc":755,"id":2015,"name":"tblines","nodeType":"Attribute","startLoc":755,"text":"self.tblines"},{"attributeType":"null","col":8,"comment":"null","endLoc":759,"id":2016,"name":"argname","nodeType":"Attribute","startLoc":759,"text":"self.argname"},{"attributeType":"null","col":8,"comment":"null","endLoc":706,"id":2017,"name":"msg","nodeType":"Attribute","startLoc":706,"text":"self.msg"},{"col":4,"comment":"#290","endLoc":1698,"header":"def test_parametrize_ID_generation_string_int_works(self, testdir)","id":2018,"name":"test_parametrize_ID_generation_string_int_works","nodeType":"Function","startLoc":1682,"text":"def test_parametrize_ID_generation_string_int_works(self, testdir):\n \"\"\"#290\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def myfixture():\n return 'example'\n @pytest.mark.parametrize(\n 'limit', (0, '0'))\n def test_limit(limit, myfixture):\n return\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)"},{"col":4,"comment":"null","endLoc":1723,"header":"@pytest.mark.parametrize(\"strict\", [True, False])\n def test_parametrize_marked_value(self, testdir, strict)","id":2019,"name":"test_parametrize_marked_value","nodeType":"Function","startLoc":1700,"text":"@pytest.mark.parametrize(\"strict\", [True, False])\n def test_parametrize_marked_value(self, testdir, strict):\n s = \"\"\"\n import pytest\n\n @pytest.mark.parametrize((\"n\", \"expected\"), [\n pytest.param(\n 2,3,\n marks=pytest.mark.xfail(\"sys.version_info > (0, 0, 0)\", reason=\"some bug\", strict={strict}),\n ),\n pytest.param(\n 2,3,\n marks=[pytest.mark.xfail(\"sys.version_info > (0, 0, 0)\", reason=\"some bug\", strict={strict})],\n ),\n ])\n def test_increment(n, expected):\n assert n + 1 == expected\n \"\"\".format(\n strict=strict\n )\n testdir.makepyfile(s)\n reprec = testdir.inline_run()\n passed, failed = (0, 2) if strict else (2, 0)\n reprec.assertoutcome(passed=passed, failed=failed)"},{"col":4,"comment":"null","endLoc":1742,"header":"def test_pytest_make_parametrize_id(self, testdir)","id":2020,"name":"test_pytest_make_parametrize_id","nodeType":"Function","startLoc":1725,"text":"def test_pytest_make_parametrize_id(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_make_parametrize_id(config, val):\n return str(val * 2)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize(\"x\", range(2))\n def test_func(x):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines([\"*test_func*0*PASS*\", \"*test_func*2*PASS*\"])"},{"col":4,"comment":"null","endLoc":1767,"header":"def test_pytest_make_parametrize_id_with_argname(self, testdir)","id":2021,"name":"test_pytest_make_parametrize_id_with_argname","nodeType":"Function","startLoc":1744,"text":"def test_pytest_make_parametrize_id_with_argname(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_make_parametrize_id(config, val, argname):\n return str(val * 2 if argname == 'x' else val * 10)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize(\"x\", range(2))\n def test_func_a(x):\n pass\n\n @pytest.mark.parametrize(\"y\", [1])\n def test_func_b(y):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n [\"*test_func_a*0*PASS*\", \"*test_func_a*2*PASS*\", \"*test_func_b*10*PASS*\"]\n )"},{"col":4,"comment":"null","endLoc":1780,"header":"def test_parametrize_positional_args(self, testdir)","id":2022,"name":"test_parametrize_positional_args","nodeType":"Function","startLoc":1769,"text":"def test_parametrize_positional_args(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize(\"a\", [1], False)\n def test_foo(a):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.assert_outcomes(passed=1)"},{"attributeType":"bool","col":0,"comment":"null","endLoc":16,"id":2023,"name":"PY3","nodeType":"Attribute","startLoc":16,"text":"PY3"},{"col":4,"comment":"null","endLoc":125,"header":"def test_hook_tracing(self, _config_for_test)","id":2024,"name":"test_hook_tracing","nodeType":"Function","startLoc":94,"text":"def test_hook_tracing(self, _config_for_test):\n pytestpm = _config_for_test.pluginmanager # fully initialized with plugins\n saveindent = []\n\n class api1(object):\n def pytest_plugin_registered(self):\n saveindent.append(pytestpm.trace.root.indent)\n\n class api2(object):\n def pytest_plugin_registered(self):\n saveindent.append(pytestpm.trace.root.indent)\n raise ValueError()\n\n values = []\n pytestpm.trace.root.setwriter(values.append)\n undo = pytestpm.enable_tracing()\n try:\n indent = pytestpm.trace.root.indent\n p = api1()\n pytestpm.register(p)\n assert pytestpm.trace.root.indent == indent\n assert len(values) >= 2\n assert \"pytest_plugin_registered\" in values[0]\n assert \"finish\" in values[1]\n\n values[:] = []\n with pytest.raises(ValueError):\n pytestpm.register(api2())\n assert pytestpm.trace.root.indent == indent\n assert saveindent[0] > indent\n finally:\n undo()"},{"attributeType":"null","col":8,"comment":"null","endLoc":704,"id":2025,"name":"request","nodeType":"Attribute","startLoc":704,"text":"self.request"},{"attributeType":"null","col":8,"comment":"null","endLoc":703,"id":2026,"name":"argname","nodeType":"Attribute","startLoc":703,"text":"self.argname"},{"attributeType":"null","col":8,"comment":"null","endLoc":757,"id":2027,"name":"filename","nodeType":"Attribute","startLoc":757,"text":"self.filename"},{"attributeType":"null","col":8,"comment":"null","endLoc":758,"id":2028,"name":"firstlineno","nodeType":"Attribute","startLoc":758,"text":"self.firstlineno"},{"attributeType":"null","col":8,"comment":"null","endLoc":756,"id":2029,"name":"errorstring","nodeType":"Attribute","startLoc":756,"text":"self.errorstring"},{"className":"FixtureDef","col":0,"comment":" A container for a factory definition. ","endLoc":901,"id":2030,"nodeType":"Class","startLoc":812,"text":"class FixtureDef(object):\n \"\"\" A container for a factory definition. \"\"\"\n\n def __init__(\n self,\n fixturemanager,\n baseid,\n argname,\n func,\n scope,\n params,\n unittest=False,\n ids=None,\n ):\n self._fixturemanager = fixturemanager\n self.baseid = baseid or \"\"\n self.has_location = baseid is not None\n self.func = func\n self.argname = argname\n self.scope = scope\n self.scopenum = scope2index(\n scope or \"function\",\n descr=\"Fixture '{}'\".format(func.__name__),\n where=baseid,\n )\n self.params = params\n self.argnames = getfuncargnames(func, is_method=unittest)\n self.unittest = unittest\n self.ids = ids\n self._finalizers = []\n\n def addfinalizer(self, finalizer):\n self._finalizers.append(finalizer)\n\n def finish(self, request):\n exceptions = []\n try:\n while self._finalizers:\n try:\n func = self._finalizers.pop()\n func()\n except: # noqa\n exceptions.append(sys.exc_info())\n if exceptions:\n e = exceptions[0]\n # Ensure to not keep frame references through traceback.\n del exceptions\n six.reraise(*e)\n finally:\n hook = self._fixturemanager.session.gethookproxy(request.node.fspath)\n hook.pytest_fixture_post_finalizer(fixturedef=self, request=request)\n # even if finalization fails, we invalidate\n # the cached fixture value and remove\n # all finalizers because they may be bound methods which will\n # keep instances alive\n if hasattr(self, \"cached_result\"):\n del self.cached_result\n self._finalizers = []\n\n def execute(self, request):\n # get required arguments and register our own finish()\n # with their finalization\n for argname in self.argnames:\n fixturedef = request._get_active_fixturedef(argname)\n if argname != \"request\":\n fixturedef.addfinalizer(functools.partial(self.finish, request=request))\n\n my_cache_key = request.param_index\n cached_result = getattr(self, \"cached_result\", None)\n if cached_result is not None:\n result, cache_key, err = cached_result\n if my_cache_key == cache_key:\n if err is not None:\n six.reraise(*err)\n else:\n return result\n # we have a previous but differently parametrized fixture instance\n # so we need to tear it down before creating a new one\n self.finish(request)\n assert not hasattr(self, \"cached_result\")\n\n hook = self._fixturemanager.session.gethookproxy(request.node.fspath)\n return hook.pytest_fixture_setup(fixturedef=self, request=request)\n\n def __repr__(self):\n return \"\" % (\n self.argname,\n self.scope,\n self.baseid,\n )"},{"col":4,"comment":"null","endLoc":844,"header":"def addfinalizer(self, finalizer)","id":2031,"name":"addfinalizer","nodeType":"Function","startLoc":843,"text":"def addfinalizer(self, finalizer):\n self._finalizers.append(finalizer)"},{"col":4,"comment":"null","endLoc":901,"header":"def __repr__(self)","id":2032,"name":"__repr__","nodeType":"Function","startLoc":896,"text":"def __repr__(self):\n return \"\" % (\n self.argname,\n self.scope,\n self.baseid,\n )"},{"attributeType":"int | None","col":8,"comment":"null","endLoc":832,"id":2033,"name":"scopenum","nodeType":"Attribute","startLoc":832,"text":"self.scopenum"},{"attributeType":"null","col":8,"comment":"null","endLoc":705,"id":2034,"name":"fixturestack","nodeType":"Attribute","startLoc":705,"text":"self.fixturestack"},{"col":0,"comment":"Only return names from iterator values without a leading underscore.","endLoc":181,"header":"def get_public_names(values)","id":2035,"name":"get_public_names","nodeType":"Function","startLoc":179,"text":"def get_public_names(values):\n \"\"\"Only return names from iterator values without a leading underscore.\"\"\"\n return [x for x in values if x[0] != \"_\"]"},{"attributeType":"null","col":8,"comment":"null","endLoc":830,"id":2036,"name":"argname","nodeType":"Attribute","startLoc":830,"text":"self.argname"},{"attributeType":"list","col":8,"comment":"null","endLoc":841,"id":2037,"name":"_finalizers","nodeType":"Attribute","startLoc":841,"text":"self._finalizers"},{"attributeType":"{__name__}","col":8,"comment":"null","endLoc":829,"id":2038,"name":"func","nodeType":"Attribute","startLoc":829,"text":"self.func"},{"attributeType":"null","col":8,"comment":"null","endLoc":838,"id":2039,"name":"argnames","nodeType":"Attribute","startLoc":838,"text":"self.argnames"},{"attributeType":"null","col":8,"comment":"null","endLoc":831,"id":2040,"name":"scope","nodeType":"Attribute","startLoc":831,"text":"self.scope"},{"col":0,"comment":"null","endLoc":80,"header":"def get_common_ancestor(paths)","id":2041,"name":"get_common_ancestor","nodeType":"Function","startLoc":60,"text":"def get_common_ancestor(paths):\n common_ancestor = None\n for path in paths:\n if not path.exists():\n continue\n if common_ancestor is None:\n common_ancestor = path\n else:\n if path.relto(common_ancestor) or path == common_ancestor:\n continue\n elif common_ancestor.relto(path):\n common_ancestor = path\n else:\n shared = path.common(common_ancestor)\n if shared is not None:\n common_ancestor = shared\n if common_ancestor is None:\n common_ancestor = py.path.local()\n elif common_ancestor.isfile():\n common_ancestor = common_ancestor.dirpath()\n return common_ancestor"},{"attributeType":"null","col":8,"comment":"null","endLoc":840,"id":2042,"name":"ids","nodeType":"Attribute","startLoc":840,"text":"self.ids"},{"col":4,"comment":"Test the gethookproxy function(#2016)","endLoc":141,"header":"def test_hook_proxy(self, testdir)","id":2043,"name":"test_hook_proxy","nodeType":"Function","startLoc":127,"text":"def test_hook_proxy(self, testdir):\n \"\"\"Test the gethookproxy function(#2016)\"\"\"\n config = testdir.parseconfig()\n session = Session(config)\n testdir.makepyfile(**{\"tests/conftest.py\": \"\", \"tests/subdir/conftest.py\": \"\"})\n\n conftest1 = testdir.tmpdir.join(\"tests/conftest.py\")\n conftest2 = testdir.tmpdir.join(\"tests/subdir/conftest.py\")\n\n config.pluginmanager._importconftest(conftest1)\n ihook_a = session.gethookproxy(testdir.tmpdir.join(\"tests\"))\n assert ihook_a is not None\n config.pluginmanager._importconftest(conftest2)\n ihook_b = session.gethookproxy(testdir.tmpdir.join(\"tests\"))\n assert ihook_a is not ihook_b"},{"attributeType":"bool","col":8,"comment":"null","endLoc":839,"id":2044,"name":"unittest","nodeType":"Attribute","startLoc":839,"text":"self.unittest"},{"col":0,"comment":"null","endLoc":102,"header":"def get_dirs_from_args(args)","id":2045,"name":"get_dirs_from_args","nodeType":"Function","startLoc":83,"text":"def get_dirs_from_args(args):\n def is_option(x):\n return str(x).startswith(\"-\")\n\n def get_file_part_from_node_id(x):\n return str(x).split(\"::\")[0]\n\n def get_dir_from_path(path):\n if path.isdir():\n return path\n return py.path.local(path.dirname)\n\n # These look like paths but may not exist\n possible_paths = (\n py.path.local(get_file_part_from_node_id(arg))\n for arg in args\n if not is_option(arg)\n )\n\n return [get_dir_from_path(path) for path in possible_paths if path.exists()]"},{"col":4,"comment":"null","endLoc":713,"header":"@overload\n def setdefault(self: MutableMapping[_KT, _T | None], key: _KT, default: None = None, /) -> _T | None","id":2046,"name":"setdefault","nodeType":"Function","startLoc":712,"text":"@overload\n def setdefault(self: MutableMapping[_KT, _T | None], key: _KT, default: None = None, /) -> _T | None: ..."},{"col":4,"comment":"null","endLoc":715,"header":"@overload\n def setdefault(self, key: _KT, default: _VT, /) -> _VT","id":2047,"name":"setdefault","nodeType":"Function","startLoc":714,"text":"@overload\n def setdefault(self, key: _KT, default: _VT, /) -> _VT: ..."},{"attributeType":"null","col":8,"comment":"null","endLoc":826,"id":2048,"name":"_fixturemanager","nodeType":"Attribute","startLoc":826,"text":"self._fixturemanager"},{"attributeType":"str","col":8,"comment":"null","endLoc":827,"id":2049,"name":"baseid","nodeType":"Attribute","startLoc":827,"text":"self.baseid"},{"fileName":"debugging.py","filePath":"src/_pytest","id":2050,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\" interactive debugging with PDB, the Python Debugger. \"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport pdb\nimport sys\nfrom doctest import UnexpectedException\n\nfrom _pytest import outcomes\nfrom _pytest.config import hookimpl\nfrom _pytest.config.exceptions import UsageError\n\n\ndef _validate_usepdb_cls(value):\n \"\"\"Validate syntax of --pdbcls option.\"\"\"\n try:\n modname, classname = value.split(\":\")\n except ValueError:\n raise argparse.ArgumentTypeError(\n \"{!r} is not in the format 'modname:classname'\".format(value)\n )\n return (modname, classname)\n\n\ndef pytest_addoption(parser):\n group = parser.getgroup(\"general\")\n group._addoption(\n \"--pdb\",\n dest=\"usepdb\",\n action=\"store_true\",\n help=\"start the interactive Python debugger on errors or KeyboardInterrupt.\",\n )\n group._addoption(\n \"--pdbcls\",\n dest=\"usepdb_cls\",\n metavar=\"modulename:classname\",\n type=_validate_usepdb_cls,\n help=\"start a custom interactive Python debugger on errors. \"\n \"For example: --pdbcls=IPython.terminal.debugger:TerminalPdb\",\n )\n group._addoption(\n \"--trace\",\n dest=\"trace\",\n action=\"store_true\",\n help=\"Immediately break when running each test.\",\n )\n\n\ndef pytest_configure(config):\n if config.getvalue(\"trace\"):\n config.pluginmanager.register(PdbTrace(), \"pdbtrace\")\n if config.getvalue(\"usepdb\"):\n config.pluginmanager.register(PdbInvoke(), \"pdbinvoke\")\n\n pytestPDB._saved.append(\n (pdb.set_trace, pytestPDB._pluginmanager, pytestPDB._config)\n )\n pdb.set_trace = pytestPDB.set_trace\n pytestPDB._pluginmanager = config.pluginmanager\n pytestPDB._config = config\n\n # NOTE: not using pytest_unconfigure, since it might get called although\n # pytest_configure was not (if another plugin raises UsageError).\n def fin():\n (\n pdb.set_trace,\n pytestPDB._pluginmanager,\n pytestPDB._config,\n ) = pytestPDB._saved.pop()\n\n config._cleanup.append(fin)\n\n\nclass pytestPDB(object):\n \"\"\" Pseudo PDB that defers to the real pdb. \"\"\"\n\n _pluginmanager = None\n _config = None\n _saved = []\n _recursive_debug = 0\n _wrapped_pdb_cls = None\n\n @classmethod\n def _is_capturing(cls, capman):\n if capman:\n return capman.is_capturing()\n return False\n\n @classmethod\n def _import_pdb_cls(cls, capman):\n if not cls._config:\n # Happens when using pytest.set_trace outside of a test.\n return pdb.Pdb\n\n usepdb_cls = cls._config.getvalue(\"usepdb_cls\")\n\n if cls._wrapped_pdb_cls and cls._wrapped_pdb_cls[0] == usepdb_cls:\n return cls._wrapped_pdb_cls[1]\n\n if usepdb_cls:\n modname, classname = usepdb_cls\n\n try:\n __import__(modname)\n mod = sys.modules[modname]\n\n # Handle --pdbcls=pdb:pdb.Pdb (useful e.g. with pdbpp).\n parts = classname.split(\".\")\n pdb_cls = getattr(mod, parts[0])\n for part in parts[1:]:\n pdb_cls = getattr(pdb_cls, part)\n except Exception as exc:\n value = \":\".join((modname, classname))\n raise UsageError(\n \"--pdbcls: could not import {!r}: {}\".format(value, exc)\n )\n else:\n pdb_cls = pdb.Pdb\n\n wrapped_cls = cls._get_pdb_wrapper_class(pdb_cls, capman)\n cls._wrapped_pdb_cls = (usepdb_cls, wrapped_cls)\n return wrapped_cls\n\n @classmethod\n def _get_pdb_wrapper_class(cls, pdb_cls, capman):\n import _pytest.config\n\n class PytestPdbWrapper(pdb_cls, object):\n _pytest_capman = capman\n _continued = False\n\n def do_debug(self, arg):\n cls._recursive_debug += 1\n ret = super(PytestPdbWrapper, self).do_debug(arg)\n cls._recursive_debug -= 1\n return ret\n\n def do_continue(self, arg):\n ret = super(PytestPdbWrapper, self).do_continue(arg)\n if cls._recursive_debug == 0:\n tw = _pytest.config.create_terminal_writer(cls._config)\n tw.line()\n\n capman = self._pytest_capman\n capturing = pytestPDB._is_capturing(capman)\n if capturing:\n if capturing == \"global\":\n tw.sep(\">\", \"PDB continue (IO-capturing resumed)\")\n else:\n tw.sep(\n \">\",\n \"PDB continue (IO-capturing resumed for %s)\"\n % capturing,\n )\n capman.resume()\n else:\n tw.sep(\">\", \"PDB continue\")\n cls._pluginmanager.hook.pytest_leave_pdb(config=cls._config, pdb=self)\n self._continued = True\n return ret\n\n do_c = do_cont = do_continue\n\n def do_quit(self, arg):\n \"\"\"Raise Exit outcome when quit command is used in pdb.\n\n This is a bit of a hack - it would be better if BdbQuit\n could be handled, but this would require to wrap the\n whole pytest run, and adjust the report etc.\n \"\"\"\n ret = super(PytestPdbWrapper, self).do_quit(arg)\n\n if cls._recursive_debug == 0:\n outcomes.exit(\"Quitting debugger\")\n\n return ret\n\n do_q = do_quit\n do_exit = do_quit\n\n def setup(self, f, tb):\n \"\"\"Suspend on setup().\n\n Needed after do_continue resumed, and entering another\n breakpoint again.\n \"\"\"\n ret = super(PytestPdbWrapper, self).setup(f, tb)\n if not ret and self._continued:\n # pdb.setup() returns True if the command wants to exit\n # from the interaction: do not suspend capturing then.\n if self._pytest_capman:\n self._pytest_capman.suspend_global_capture(in_=True)\n return ret\n\n def get_stack(self, f, t):\n stack, i = super(PytestPdbWrapper, self).get_stack(f, t)\n if f is None:\n # Find last non-hidden frame.\n i = max(0, len(stack) - 1)\n while i and stack[i][0].f_locals.get(\"__tracebackhide__\", False):\n i -= 1\n return stack, i\n\n return PytestPdbWrapper\n\n @classmethod\n def _init_pdb(cls, method, *args, **kwargs):\n \"\"\" Initialize PDB debugging, dropping any IO capturing. \"\"\"\n import _pytest.config\n\n if cls._pluginmanager is not None:\n capman = cls._pluginmanager.getplugin(\"capturemanager\")\n else:\n capman = None\n if capman:\n capman.suspend(in_=True)\n\n if cls._config:\n tw = _pytest.config.create_terminal_writer(cls._config)\n tw.line()\n\n if cls._recursive_debug == 0:\n # Handle header similar to pdb.set_trace in py37+.\n header = kwargs.pop(\"header\", None)\n if header is not None:\n tw.sep(\">\", header)\n else:\n capturing = cls._is_capturing(capman)\n if capturing == \"global\":\n tw.sep(\">\", \"PDB %s (IO-capturing turned off)\" % (method,))\n elif capturing:\n tw.sep(\n \">\",\n \"PDB %s (IO-capturing turned off for %s)\"\n % (method, capturing),\n )\n else:\n tw.sep(\">\", \"PDB %s\" % (method,))\n\n _pdb = cls._import_pdb_cls(capman)(**kwargs)\n\n if cls._pluginmanager:\n cls._pluginmanager.hook.pytest_enter_pdb(config=cls._config, pdb=_pdb)\n return _pdb\n\n @classmethod\n def set_trace(cls, *args, **kwargs):\n \"\"\"Invoke debugging via ``Pdb.set_trace``, dropping any IO capturing.\"\"\"\n frame = sys._getframe().f_back\n _pdb = cls._init_pdb(\"set_trace\", *args, **kwargs)\n _pdb.set_trace(frame)\n\n\nclass PdbInvoke(object):\n def pytest_exception_interact(self, node, call, report):\n capman = node.config.pluginmanager.getplugin(\"capturemanager\")\n if capman:\n capman.suspend_global_capture(in_=True)\n out, err = capman.read_global_capture()\n sys.stdout.write(out)\n sys.stdout.write(err)\n _enter_pdb(node, call.excinfo, report)\n\n def pytest_internalerror(self, excrepr, excinfo):\n tb = _postmortem_traceback(excinfo)\n post_mortem(tb)\n\n\nclass PdbTrace(object):\n @hookimpl(hookwrapper=True)\n def pytest_pyfunc_call(self, pyfuncitem):\n _test_pytest_function(pyfuncitem)\n yield\n\n\ndef _test_pytest_function(pyfuncitem):\n _pdb = pytestPDB._init_pdb(\"runcall\")\n testfunction = pyfuncitem.obj\n pyfuncitem.obj = _pdb.runcall\n if \"func\" in pyfuncitem._fixtureinfo.argnames: # pragma: no branch\n raise ValueError(\"--trace can't be used with a fixture named func!\")\n pyfuncitem.funcargs[\"func\"] = testfunction\n new_list = list(pyfuncitem._fixtureinfo.argnames)\n new_list.append(\"func\")\n pyfuncitem._fixtureinfo.argnames = tuple(new_list)\n\n\ndef _enter_pdb(node, excinfo, rep):\n # XXX we re-use the TerminalReporter's terminalwriter\n # because this seems to avoid some encoding related troubles\n # for not completely clear reasons.\n tw = node.config.pluginmanager.getplugin(\"terminalreporter\")._tw\n tw.line()\n\n showcapture = node.config.option.showcapture\n\n for sectionname, content in (\n (\"stdout\", rep.capstdout),\n (\"stderr\", rep.capstderr),\n (\"log\", rep.caplog),\n ):\n if showcapture in (sectionname, \"all\") and content:\n tw.sep(\">\", \"captured \" + sectionname)\n if content[-1:] == \"\\n\":\n content = content[:-1]\n tw.line(content)\n\n tw.sep(\">\", \"traceback\")\n rep.toterminal(tw)\n tw.sep(\">\", \"entering PDB\")\n tb = _postmortem_traceback(excinfo)\n rep._pdbshown = True\n post_mortem(tb)\n return rep\n\n\ndef _postmortem_traceback(excinfo):\n if isinstance(excinfo.value, UnexpectedException):\n # A doctest.UnexpectedException is not useful for post_mortem.\n # Use the underlying exception instead:\n return excinfo.value.exc_info[2]\n else:\n return excinfo._excinfo[2]\n\n\ndef post_mortem(t):\n p = pytestPDB._init_pdb(\"post_mortem\")\n p.reset()\n p.interaction(None, t)\n if p.quitting:\n outcomes.exit(\"Quitting debugger\")\n"},{"className":"TestFillFixtures","col":0,"comment":"null","endLoc":443,"id":2051,"nodeType":"Class","startLoc":47,"text":"@pytest.mark.pytester_example_path(\"fixtures/fill_fixtures\")\nclass TestFillFixtures(object):\n def test_fillfuncargs_exposed(self):\n # used by oejskit, kept for compatibility\n assert pytest._fillfuncargs == fixtures.fillfixtures\n\n def test_funcarg_lookupfails(self, testdir):\n testdir.copy_example()\n result = testdir.runpytest() # \"--collect-only\")\n assert result.ret != 0\n result.stdout.fnmatch_lines(\n \"\"\"\n *def test_func(some)*\n *fixture*some*not found*\n *xyzsomething*\n \"\"\"\n )\n\n def test_detect_recursive_dependency_error(self, testdir):\n testdir.copy_example()\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"*recursive dependency involving fixture 'fix1' detected*\"]\n )\n\n def test_funcarg_basic(self, testdir):\n testdir.copy_example()\n item = testdir.getitem(Path(\"test_funcarg_basic.py\"))\n fixtures.fillfixtures(item)\n del item.funcargs[\"request\"]\n assert len(get_public_names(item.funcargs)) == 2\n assert item.funcargs[\"some\"] == \"test_func\"\n assert item.funcargs[\"other\"] == 42\n\n def test_funcarg_lookup_modulelevel(self, testdir):\n testdir.copy_example()\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_funcarg_lookup_classlevel(self, testdir):\n p = testdir.copy_example()\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_conftest_funcargs_only_available_in_subdir(self, testdir):\n testdir.copy_example()\n result = testdir.runpytest(\"-v\")\n result.assert_outcomes(passed=2)\n\n def test_extend_fixture_module_class(self, testdir):\n testfile = testdir.copy_example()\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest(testfile)\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_extend_fixture_conftest_module(self, testdir):\n p = testdir.copy_example()\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest(next(p.visit(\"test_*.py\")))\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_extend_fixture_conftest_conftest(self, testdir):\n p = testdir.copy_example()\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest(next(p.visit(\"test_*.py\")))\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_extend_fixture_conftest_plugin(self, testdir):\n testdir.makepyfile(\n testplugin=\"\"\"\n import pytest\n\n @pytest.fixture\n def foo():\n return 7\n \"\"\"\n )\n testdir.syspathinsert()\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n pytest_plugins = 'testplugin'\n\n @pytest.fixture\n def foo(foo):\n return foo + 7\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_foo(foo):\n assert foo == 14\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n assert result.ret == 0\n\n def test_extend_fixture_plugin_plugin(self, testdir):\n # Two plugins should extend each order in loading order\n testdir.makepyfile(\n testplugin0=\"\"\"\n import pytest\n\n @pytest.fixture\n def foo():\n return 7\n \"\"\"\n )\n testdir.makepyfile(\n testplugin1=\"\"\"\n import pytest\n\n @pytest.fixture\n def foo(foo):\n return foo + 7\n \"\"\"\n )\n testdir.syspathinsert()\n testdir.makepyfile(\n \"\"\"\n pytest_plugins = ['testplugin0', 'testplugin1']\n\n def test_foo(foo):\n assert foo == 14\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0\n\n def test_override_parametrized_fixture_conftest_module(self, testdir):\n \"\"\"Test override of the parametrized fixture with non-parametrized one on the test module level.\"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[1, 2, 3])\n def spam(request):\n return request.param\n \"\"\"\n )\n testfile = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def spam():\n return 'spam'\n\n def test_spam(spam):\n assert spam == 'spam'\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest(testfile)\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_override_parametrized_fixture_conftest_conftest(self, testdir):\n \"\"\"Test override of the parametrized fixture with non-parametrized one on the conftest level.\"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[1, 2, 3])\n def spam(request):\n return request.param\n \"\"\"\n )\n subdir = testdir.mkpydir(\"subdir\")\n subdir.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n\n @pytest.fixture\n def spam():\n return 'spam'\n \"\"\"\n )\n )\n testfile = subdir.join(\"test_spam.py\")\n testfile.write(\n textwrap.dedent(\n \"\"\"\\\n def test_spam(spam):\n assert spam == \"spam\"\n \"\"\"\n )\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest(testfile)\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_override_non_parametrized_fixture_conftest_module(self, testdir):\n \"\"\"Test override of the non-parametrized fixture with parametrized one on the test module level.\"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def spam():\n return 'spam'\n \"\"\"\n )\n testfile = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[1, 2, 3])\n def spam(request):\n return request.param\n\n params = {'spam': 1}\n\n def test_spam(spam):\n assert spam == params['spam']\n params['spam'] += 1\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n result = testdir.runpytest(testfile)\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n\n def test_override_non_parametrized_fixture_conftest_conftest(self, testdir):\n \"\"\"Test override of the non-parametrized fixture with parametrized one on the conftest level.\"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def spam():\n return 'spam'\n \"\"\"\n )\n subdir = testdir.mkpydir(\"subdir\")\n subdir.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n\n @pytest.fixture(params=[1, 2, 3])\n def spam(request):\n return request.param\n \"\"\"\n )\n )\n testfile = subdir.join(\"test_spam.py\")\n testfile.write(\n textwrap.dedent(\n \"\"\"\\\n params = {'spam': 1}\n\n def test_spam(spam):\n assert spam == params['spam']\n params['spam'] += 1\n \"\"\"\n )\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n result = testdir.runpytest(testfile)\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n\n def test_override_autouse_fixture_with_parametrized_fixture_conftest_conftest(\n self, testdir\n ):\n \"\"\"Test override of the autouse fixture with parametrized one on the conftest level.\n This test covers the issue explained in issue 1601\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(autouse=True)\n def spam():\n return 'spam'\n \"\"\"\n )\n subdir = testdir.mkpydir(\"subdir\")\n subdir.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n\n @pytest.fixture(params=[1, 2, 3])\n def spam(request):\n return request.param\n \"\"\"\n )\n )\n testfile = subdir.join(\"test_spam.py\")\n testfile.write(\n textwrap.dedent(\n \"\"\"\\\n params = {'spam': 1}\n\n def test_spam(spam):\n assert spam == params['spam']\n params['spam'] += 1\n \"\"\"\n )\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n result = testdir.runpytest(testfile)\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n\n def test_autouse_fixture_plugin(self, testdir):\n # A fixture from a plugin has no baseid set, which screwed up\n # the autouse fixture handling.\n testdir.makepyfile(\n testplugin=\"\"\"\n import pytest\n\n @pytest.fixture(autouse=True)\n def foo(request):\n request.function.foo = 7\n \"\"\"\n )\n testdir.syspathinsert()\n testdir.makepyfile(\n \"\"\"\n pytest_plugins = 'testplugin'\n\n def test_foo(request):\n assert request.function.foo == 7\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0\n\n def test_funcarg_lookup_error(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def a_fixture(): pass\n\n @pytest.fixture\n def b_fixture(): pass\n\n @pytest.fixture\n def c_fixture(): pass\n\n @pytest.fixture\n def d_fixture(): pass\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_lookup_error(unknown):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*ERROR at setup of test_lookup_error*\",\n \" def test_lookup_error(unknown):*\",\n \"E fixture 'unknown' not found\",\n \"> available fixtures:*a_fixture,*b_fixture,*c_fixture,*d_fixture*monkeypatch,*\", # sorted\n \"> use 'py*test --fixtures *' for help on them.\",\n \"*1 error*\",\n ]\n )\n assert \"INTERNAL\" not in result.stdout.str()\n\n def test_fixture_excinfo_leak(self, testdir):\n # on python2 sys.excinfo would leak into fixture executions\n testdir.makepyfile(\n \"\"\"\n import sys\n import traceback\n import pytest\n\n @pytest.fixture\n def leak():\n if sys.exc_info()[0]: # python3 bug :)\n traceback.print_exc()\n #fails\n assert sys.exc_info() == (None, None, None)\n\n def test_leak(leak):\n if sys.exc_info()[0]: # python3 bug :)\n traceback.print_exc()\n assert sys.exc_info() == (None, None, None)\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0"},{"col":4,"comment":"null","endLoc":51,"header":"def test_fillfuncargs_exposed(self)","id":2052,"name":"test_fillfuncargs_exposed","nodeType":"Function","startLoc":49,"text":"def test_fillfuncargs_exposed(self):\n # used by oejskit, kept for compatibility\n assert pytest._fillfuncargs == fixtures.fillfixtures"},{"col":4,"comment":"null","endLoc":63,"header":"def test_funcarg_lookupfails(self, testdir)","id":2053,"name":"test_funcarg_lookupfails","nodeType":"Function","startLoc":53,"text":"def test_funcarg_lookupfails(self, testdir):\n testdir.copy_example()\n result = testdir.runpytest() # \"--collect-only\")\n assert result.ret != 0\n result.stdout.fnmatch_lines(\n \"\"\"\n *def test_func(some)*\n *fixture*some*not found*\n *xyzsomething*\n \"\"\"\n )"},{"attributeType":"null","col":8,"comment":"null","endLoc":837,"id":2054,"name":"params","nodeType":"Attribute","startLoc":837,"text":"self.params"},{"className":"UnexpectedException","col":0,"comment":"null","endLoc":163,"id":2055,"nodeType":"Class","startLoc":159,"text":"class UnexpectedException(Exception):\n test: DocTest\n example: Example\n exc_info: ExcInfo\n def __init__(self, test: DocTest, example: Example, exc_info: ExcInfo) -> None: ..."},{"col":4,"comment":"null","endLoc":163,"header":"def __init__(self, test: DocTest, example: Example, exc_info: ExcInfo) -> None","id":2056,"name":"__init__","nodeType":"Function","startLoc":163,"text":"def __init__(self, test: DocTest, example: Example, exc_info: ExcInfo) -> None: ..."},{"attributeType":"DocTest","col":4,"comment":"null","endLoc":160,"id":2057,"name":"test","nodeType":"Attribute","startLoc":160,"text":"test"},{"attributeType":"null","col":8,"comment":"null","endLoc":828,"id":2058,"name":"has_location","nodeType":"Attribute","startLoc":828,"text":"self.has_location"},{"attributeType":"Example","col":4,"comment":"null","endLoc":161,"id":2059,"name":"example","nodeType":"Attribute","startLoc":161,"text":"example"},{"className":"FixtureFunctionMarker","col":0,"comment":"null","endLoc":994,"id":2060,"nodeType":"Class","startLoc":971,"text":"@attr.s(frozen=True)\nclass FixtureFunctionMarker(object):\n scope = attr.ib()\n params = attr.ib(converter=attr.converters.optional(tuple))\n autouse = attr.ib(default=False)\n ids = attr.ib(default=None, converter=_ensure_immutable_ids)\n name = attr.ib(default=None)\n\n def __call__(self, function):\n if isclass(function):\n raise ValueError(\"class fixtures not supported (maybe in the future)\")\n\n if getattr(function, \"_pytestfixturefunction\", False):\n raise ValueError(\n \"fixture is being applied more than once to the same function\"\n )\n\n function = wrap_function_to_error_out_if_called_directly(function, self)\n\n name = self.name or function.__name__\n if name == \"request\":\n warnings.warn(FIXTURE_NAMED_REQUEST)\n function._pytestfixturefunction = self\n return function"},{"attributeType":"null","col":4,"comment":"null","endLoc":973,"id":2061,"name":"scope","nodeType":"Attribute","startLoc":973,"text":"scope"},{"attributeType":"(BaseException, BaseException, TracebackType)","col":4,"comment":"null","endLoc":162,"id":2062,"name":"exc_info","nodeType":"Attribute","startLoc":162,"text":"exc_info"},{"attributeType":"null","col":4,"comment":"null","endLoc":974,"id":2063,"name":"params","nodeType":"Attribute","startLoc":974,"text":"params"},{"attributeType":"null","col":4,"comment":"null","endLoc":975,"id":2064,"name":"autouse","nodeType":"Attribute","startLoc":975,"text":"autouse"},{"attributeType":"null","col":4,"comment":"null","endLoc":976,"id":2065,"name":"ids","nodeType":"Attribute","startLoc":976,"text":"ids"},{"col":4,"comment":"null","endLoc":175,"header":"def addError(self, testcase, rawexcinfo)","id":2066,"name":"addError","nodeType":"Function","startLoc":174,"text":"def addError(self, testcase, rawexcinfo):\n self._addexcinfo(rawexcinfo)"},{"col":0,"comment":"","endLoc":2,"header":"metafunc.py#","id":2067,"name":"","nodeType":"Function","startLoc":2,"text":"PY3 = sys.version_info >= (3, 0)"},{"className":"TestPytestPluginManager","col":0,"comment":"null","endLoc":300,"id":2068,"nodeType":"Class","startLoc":173,"text":"class TestPytestPluginManager(object):\n def test_register_imported_modules(self):\n pm = PytestPluginManager()\n mod = types.ModuleType(\"x.y.pytest_hello\")\n pm.register(mod)\n assert pm.is_registered(mod)\n values = pm.get_plugins()\n assert mod in values\n pytest.raises(ValueError, pm.register, mod)\n pytest.raises(ValueError, lambda: pm.register(mod))\n # assert not pm.is_registered(mod2)\n assert pm.get_plugins() == values\n\n def test_canonical_import(self, monkeypatch):\n mod = types.ModuleType(\"pytest_xyz\")\n monkeypatch.setitem(sys.modules, \"pytest_xyz\", mod)\n pm = PytestPluginManager()\n pm.import_plugin(\"pytest_xyz\")\n assert pm.get_plugin(\"pytest_xyz\") == mod\n assert pm.is_registered(mod)\n\n def test_consider_module(self, testdir, pytestpm):\n testdir.syspathinsert()\n testdir.makepyfile(pytest_p1=\"#\")\n testdir.makepyfile(pytest_p2=\"#\")\n mod = types.ModuleType(\"temp\")\n mod.pytest_plugins = [\"pytest_p1\", \"pytest_p2\"]\n pytestpm.consider_module(mod)\n assert pytestpm.get_plugin(\"pytest_p1\").__name__ == \"pytest_p1\"\n assert pytestpm.get_plugin(\"pytest_p2\").__name__ == \"pytest_p2\"\n\n def test_consider_module_import_module(self, testdir, _config_for_test):\n pytestpm = _config_for_test.pluginmanager\n mod = types.ModuleType(\"x\")\n mod.pytest_plugins = \"pytest_a\"\n aplugin = testdir.makepyfile(pytest_a=\"#\")\n reprec = testdir.make_hook_recorder(pytestpm)\n testdir.syspathinsert(aplugin.dirpath())\n pytestpm.consider_module(mod)\n call = reprec.getcall(pytestpm.hook.pytest_plugin_registered.name)\n assert call.plugin.__name__ == \"pytest_a\"\n\n # check that it is not registered twice\n pytestpm.consider_module(mod)\n values = reprec.getcalls(\"pytest_plugin_registered\")\n assert len(values) == 1\n\n def test_consider_env_fails_to_import(self, monkeypatch, pytestpm):\n monkeypatch.setenv(\"PYTEST_PLUGINS\", \"nonexisting\", prepend=\",\")\n with pytest.raises(ImportError):\n pytestpm.consider_env()\n\n @pytest.mark.filterwarnings(\"always\")\n def test_plugin_skip(self, testdir, monkeypatch):\n p = testdir.makepyfile(\n skipping1=\"\"\"\n import pytest\n pytest.skip(\"hello\", allow_module_level=True)\n \"\"\"\n )\n p.copy(p.dirpath(\"skipping2.py\"))\n monkeypatch.setenv(\"PYTEST_PLUGINS\", \"skipping2\")\n result = testdir.runpytest(\"-rw\", \"-p\", \"skipping1\", syspathinsert=True)\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result.stdout.fnmatch_lines(\n [\"*skipped plugin*skipping1*hello*\", \"*skipped plugin*skipping2*hello*\"]\n )\n\n def test_consider_env_plugin_instantiation(self, testdir, monkeypatch, pytestpm):\n testdir.syspathinsert()\n testdir.makepyfile(xy123=\"#\")\n monkeypatch.setitem(os.environ, \"PYTEST_PLUGINS\", \"xy123\")\n l1 = len(pytestpm.get_plugins())\n pytestpm.consider_env()\n l2 = len(pytestpm.get_plugins())\n assert l2 == l1 + 1\n assert pytestpm.get_plugin(\"xy123\")\n pytestpm.consider_env()\n l3 = len(pytestpm.get_plugins())\n assert l2 == l3\n\n def test_pluginmanager_ENV_startup(self, testdir, monkeypatch):\n testdir.makepyfile(pytest_x500=\"#\")\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_hello(pytestconfig):\n plugin = pytestconfig.pluginmanager.get_plugin('pytest_x500')\n assert plugin is not None\n \"\"\"\n )\n monkeypatch.setenv(\"PYTEST_PLUGINS\", \"pytest_x500\", prepend=\",\")\n result = testdir.runpytest(p, syspathinsert=True)\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_import_plugin_importname(self, testdir, pytestpm):\n pytest.raises(ImportError, pytestpm.import_plugin, \"qweqwex.y\")\n pytest.raises(ImportError, pytestpm.import_plugin, \"pytest_qweqwx.y\")\n\n testdir.syspathinsert()\n pluginname = \"pytest_hello\"\n testdir.makepyfile(**{pluginname: \"\"})\n pytestpm.import_plugin(\"pytest_hello\")\n len1 = len(pytestpm.get_plugins())\n pytestpm.import_plugin(\"pytest_hello\")\n len2 = len(pytestpm.get_plugins())\n assert len1 == len2\n plugin1 = pytestpm.get_plugin(\"pytest_hello\")\n assert plugin1.__name__.endswith(\"pytest_hello\")\n plugin2 = pytestpm.get_plugin(\"pytest_hello\")\n assert plugin2 is plugin1\n\n def test_import_plugin_dotted_name(self, testdir, pytestpm):\n pytest.raises(ImportError, pytestpm.import_plugin, \"qweqwex.y\")\n pytest.raises(ImportError, pytestpm.import_plugin, \"pytest_qweqwex.y\")\n\n testdir.syspathinsert()\n testdir.mkpydir(\"pkg\").join(\"plug.py\").write(\"x=3\")\n pluginname = \"pkg.plug\"\n pytestpm.import_plugin(pluginname)\n mod = pytestpm.get_plugin(\"pkg.plug\")\n assert mod.x == 3\n\n def test_consider_conftest_deps(self, testdir, pytestpm):\n mod = testdir.makepyfile(\"pytest_plugins='xyz'\").pyimport()\n with pytest.raises(ImportError):\n pytestpm.consider_conftest(mod)"},{"attributeType":"null","col":4,"comment":"null","endLoc":977,"id":2069,"name":"name","nodeType":"Attribute","startLoc":977,"text":"name"},{"fileName":"test_mark.py","filePath":"testing","id":2070,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\n\nimport six\n\nimport pytest\nfrom _pytest.main import EXIT_INTERRUPTED\nfrom _pytest.mark import EMPTY_PARAMETERSET_OPTION\nfrom _pytest.mark import MarkGenerator as Mark\nfrom _pytest.nodes import Collector\nfrom _pytest.nodes import Node\nfrom _pytest.warning_types import PytestDeprecationWarning\nfrom _pytest.warnings import SHOW_PYTEST_WARNINGS_ARG\n\ntry:\n import mock\nexcept ImportError:\n import unittest.mock as mock\n\nignore_markinfo = pytest.mark.filterwarnings(\n \"ignore:MarkInfo objects:pytest.RemovedInPytest4Warning\"\n)\n\n\nclass TestMark(object):\n @pytest.mark.parametrize(\"attr\", [\"mark\", \"param\"])\n @pytest.mark.parametrize(\"modulename\", [\"py.test\", \"pytest\"])\n def test_pytest_exists_in_namespace_all(self, attr, modulename):\n module = sys.modules[modulename]\n assert attr in module.__all__\n\n def test_pytest_mark_notcallable(self):\n mark = Mark()\n pytest.raises((AttributeError, TypeError), mark)\n\n def test_mark_with_param(self):\n def some_function(abc):\n pass\n\n class SomeClass(object):\n pass\n\n assert pytest.mark.foo(some_function) is some_function\n assert pytest.mark.foo.with_args(some_function) is not some_function\n\n assert pytest.mark.foo(SomeClass) is SomeClass\n assert pytest.mark.foo.with_args(SomeClass) is not SomeClass\n\n def test_pytest_mark_name_starts_with_underscore(self):\n mark = Mark()\n with pytest.raises(AttributeError):\n mark._some_name\n\n\ndef test_marked_class_run_twice(testdir, request):\n \"\"\"Test fails file is run twice that contains marked class.\n See issue#683.\n \"\"\"\n py_file = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('abc', [1, 2, 3])\n class Test1(object):\n def test_1(self, abc):\n assert abc in [1, 2, 3]\n \"\"\"\n )\n file_name = os.path.basename(py_file.strpath)\n rec = testdir.inline_run(file_name, file_name)\n rec.assertoutcome(passed=6)\n\n\ndef test_ini_markers(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n markers =\n a1: this is a webtest marker\n a2: this is a smoke marker\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_markers(pytestconfig):\n markers = pytestconfig.getini(\"markers\")\n print(markers)\n assert len(markers) >= 2\n assert markers[0].startswith(\"a1:\")\n assert markers[1].startswith(\"a2:\")\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(passed=1)\n\n\ndef test_markers_option(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n markers =\n a1: this is a webtest marker\n a1some: another marker\n nodescription\n \"\"\"\n )\n result = testdir.runpytest(\"--markers\")\n result.stdout.fnmatch_lines(\n [\"*a1*this is a webtest*\", \"*a1some*another marker\", \"*nodescription*\"]\n )\n\n\ndef test_ini_markers_whitespace(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n markers =\n a1 : this is a whitespace marker\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.a1\n def test_markers():\n assert True\n \"\"\"\n )\n rec = testdir.inline_run(\"--strict-markers\", \"-m\", \"a1\")\n rec.assertoutcome(passed=1)\n\n\ndef test_marker_without_description(testdir):\n testdir.makefile(\n \".cfg\",\n setup=\"\"\"\n [tool:pytest]\n markers=slow\n \"\"\",\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n pytest.mark.xfail('FAIL')\n \"\"\"\n )\n ftdir = testdir.mkdir(\"ft1_dummy\")\n testdir.tmpdir.join(\"conftest.py\").move(ftdir.join(\"conftest.py\"))\n rec = testdir.runpytest(\"--strict-markers\")\n rec.assert_outcomes()\n\n\ndef test_markers_option_with_plugin_in_current_dir(testdir):\n testdir.makeconftest('pytest_plugins = \"flip_flop\"')\n testdir.makepyfile(\n flip_flop=\"\"\"\\\n def pytest_configure(config):\n config.addinivalue_line(\"markers\", \"flip:flop\")\n\n def pytest_generate_tests(metafunc):\n try:\n mark = metafunc.function.flipper\n except AttributeError:\n return\n metafunc.parametrize(\"x\", (10, 20))\"\"\"\n )\n testdir.makepyfile(\n \"\"\"\\\n import pytest\n @pytest.mark.flipper\n def test_example(x):\n assert x\"\"\"\n )\n\n result = testdir.runpytest(\"--markers\")\n result.stdout.fnmatch_lines([\"*flip*flop*\"])\n\n\ndef test_mark_on_pseudo_function(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.r(lambda x: 0/0)\n def test_hello():\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n\n@pytest.mark.parametrize(\"option_name\", [\"--strict-markers\", \"--strict\"])\ndef test_strict_prohibits_unregistered_markers(testdir, option_name):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.unregisteredmark\n def test_hello():\n pass\n \"\"\"\n )\n result = testdir.runpytest(option_name)\n assert result.ret != 0\n result.stdout.fnmatch_lines(\n [\"'unregisteredmark' not found in `markers` configuration option\"]\n )\n\n\n@pytest.mark.parametrize(\n \"spec\",\n [\n (\"xyz\", (\"test_one\",)),\n (\"xyz and xyz2\", ()),\n (\"xyz2\", (\"test_two\",)),\n (\"xyz or xyz2\", (\"test_one\", \"test_two\")),\n ],\n)\ndef test_mark_option(spec, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xyz\n def test_one():\n pass\n @pytest.mark.xyz2\n def test_two():\n pass\n \"\"\"\n )\n opt, passed_result = spec\n rec = testdir.inline_run(\"-m\", opt)\n passed, skipped, fail = rec.listoutcomes()\n passed = [x.nodeid.split(\"::\")[-1] for x in passed]\n assert len(passed) == len(passed_result)\n assert list(passed) == list(passed_result)\n\n\n@pytest.mark.parametrize(\n \"spec\", [(\"interface\", (\"test_interface\",)), (\"not interface\", (\"test_nointer\",))]\n)\ndef test_mark_option_custom(spec, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_collection_modifyitems(items):\n for item in items:\n if \"interface\" in item.nodeid:\n item.add_marker(pytest.mark.interface)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_interface():\n pass\n def test_nointer():\n pass\n \"\"\"\n )\n opt, passed_result = spec\n rec = testdir.inline_run(\"-m\", opt)\n passed, skipped, fail = rec.listoutcomes()\n passed = [x.nodeid.split(\"::\")[-1] for x in passed]\n assert len(passed) == len(passed_result)\n assert list(passed) == list(passed_result)\n\n\n@pytest.mark.parametrize(\n \"spec\",\n [\n (\"interface\", (\"test_interface\",)),\n (\"not interface\", (\"test_nointer\", \"test_pass\")),\n (\"pass\", (\"test_pass\",)),\n (\"not pass\", (\"test_interface\", \"test_nointer\")),\n ],\n)\ndef test_keyword_option_custom(spec, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_interface():\n pass\n def test_nointer():\n pass\n def test_pass():\n pass\n \"\"\"\n )\n opt, passed_result = spec\n rec = testdir.inline_run(\"-k\", opt)\n passed, skipped, fail = rec.listoutcomes()\n passed = [x.nodeid.split(\"::\")[-1] for x in passed]\n assert len(passed) == len(passed_result)\n assert list(passed) == list(passed_result)\n\n\ndef test_keyword_option_considers_mark(testdir):\n testdir.copy_example(\"marks/marks_considered_keywords\")\n rec = testdir.inline_run(\"-k\", \"foo\")\n passed = rec.listoutcomes()[0]\n assert len(passed) == 1\n\n\n@pytest.mark.parametrize(\n \"spec\",\n [\n (\"None\", (\"test_func[None]\",)),\n (\"1.3\", (\"test_func[1.3]\",)),\n (\"2-3\", (\"test_func[2-3]\",)),\n ],\n)\ndef test_keyword_option_parametrize(spec, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize(\"arg\", [None, 1.3, \"2-3\"])\n def test_func(arg):\n pass\n \"\"\"\n )\n opt, passed_result = spec\n rec = testdir.inline_run(\"-k\", opt)\n passed, skipped, fail = rec.listoutcomes()\n passed = [x.nodeid.split(\"::\")[-1] for x in passed]\n assert len(passed) == len(passed_result)\n assert list(passed) == list(passed_result)\n\n\n@pytest.mark.parametrize(\n \"spec\",\n [\n (\n \"foo or import\",\n \"ERROR: Python keyword 'import' not accepted in expressions passed to '-k'\",\n ),\n (\"foo or\", \"ERROR: Wrong expression passed to '-k': foo or\"),\n ],\n)\ndef test_keyword_option_wrong_arguments(spec, testdir, capsys):\n testdir.makepyfile(\n \"\"\"\n def test_func(arg):\n pass\n \"\"\"\n )\n opt, expected_result = spec\n testdir.inline_run(\"-k\", opt)\n out = capsys.readouterr().err\n assert expected_result in out\n\n\ndef test_parametrized_collected_from_command_line(testdir):\n \"\"\"Parametrized test not collected if test named specified\n in command line issue#649.\n \"\"\"\n py_file = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize(\"arg\", [None, 1.3, \"2-3\"])\n def test_func(arg):\n pass\n \"\"\"\n )\n file_name = os.path.basename(py_file.strpath)\n rec = testdir.inline_run(file_name + \"::\" + \"test_func\")\n rec.assertoutcome(passed=3)\n\n\ndef test_parametrized_collect_with_wrong_args(testdir):\n \"\"\"Test collect parametrized func with wrong number of args.\"\"\"\n py_file = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize('foo, bar', [(1, 2, 3)])\n def test_func(foo, bar):\n pass\n \"\"\"\n )\n\n result = testdir.runpytest(py_file)\n result.stdout.fnmatch_lines(\n [\n 'test_parametrized_collect_with_wrong_args.py::test_func: in \"parametrize\" the number of names (2):',\n \" ['foo', 'bar']\",\n \"must be equal to the number of values (3):\",\n \" (1, 2, 3)\",\n ]\n )\n\n\ndef test_parametrized_with_kwargs(testdir):\n \"\"\"Test collect parametrized func with wrong number of args.\"\"\"\n py_file = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[1,2])\n def a(request):\n return request.param\n\n @pytest.mark.parametrize(argnames='b', argvalues=[1, 2])\n def test_func(a, b):\n pass\n \"\"\"\n )\n\n result = testdir.runpytest(py_file)\n assert result.ret == 0\n\n\ndef test_parametrize_iterator(testdir):\n \"\"\"parametrize should work with generators (#5354).\"\"\"\n py_file = testdir.makepyfile(\n \"\"\"\\\n import pytest\n\n def gen():\n yield 1\n yield 2\n yield 3\n\n @pytest.mark.parametrize('a', gen())\n def test(a):\n assert a >= 1\n \"\"\"\n )\n result = testdir.runpytest(py_file)\n assert result.ret == 0\n # should not skip any tests\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n\n\nclass TestFunctional(object):\n def test_merging_markers_deep(self, testdir):\n # issue 199 - propagate markers into nested classes\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n class TestA(object):\n pytestmark = pytest.mark.a\n def test_b(self):\n assert True\n class TestC(object):\n # this one didnt get marked\n def test_d(self):\n assert True\n \"\"\"\n )\n items, rec = testdir.inline_genitems(p)\n for item in items:\n print(item, item.keywords)\n assert [x for x in item.iter_markers() if x.name == \"a\"]\n\n def test_mark_decorator_subclass_does_not_propagate_to_base(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.a\n class Base(object): pass\n\n @pytest.mark.b\n class Test1(Base):\n def test_foo(self): pass\n\n class Test2(Base):\n def test_bar(self): pass\n \"\"\"\n )\n items, rec = testdir.inline_genitems(p)\n self.assert_markers(items, test_foo=(\"a\", \"b\"), test_bar=(\"a\",))\n\n def test_mark_should_not_pass_to_siebling_class(self, testdir):\n \"\"\"#568\"\"\"\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n class TestBase(object):\n def test_foo(self):\n pass\n\n @pytest.mark.b\n class TestSub(TestBase):\n pass\n\n\n class TestOtherSub(TestBase):\n pass\n\n \"\"\"\n )\n items, rec = testdir.inline_genitems(p)\n base_item, sub_item, sub_item_other = items\n print(items, [x.nodeid for x in items])\n # new api seregates\n assert not list(base_item.iter_markers(name=\"b\"))\n assert not list(sub_item_other.iter_markers(name=\"b\"))\n assert list(sub_item.iter_markers(name=\"b\"))\n\n def test_mark_decorator_baseclasses_merged(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.a\n class Base(object): pass\n\n @pytest.mark.b\n class Base2(Base): pass\n\n @pytest.mark.c\n class Test1(Base2):\n def test_foo(self): pass\n\n class Test2(Base2):\n @pytest.mark.d\n def test_bar(self): pass\n \"\"\"\n )\n items, rec = testdir.inline_genitems(p)\n self.assert_markers(items, test_foo=(\"a\", \"b\", \"c\"), test_bar=(\"a\", \"b\", \"d\"))\n\n def test_mark_closest(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.c(location=\"class\")\n class Test:\n @pytest.mark.c(location=\"function\")\n def test_has_own():\n pass\n\n def test_has_inherited():\n pass\n\n \"\"\"\n )\n items, rec = testdir.inline_genitems(p)\n has_own, has_inherited = items\n assert has_own.get_closest_marker(\"c\").kwargs == {\"location\": \"function\"}\n assert has_inherited.get_closest_marker(\"c\").kwargs == {\"location\": \"class\"}\n assert has_own.get_closest_marker(\"missing\") is None\n\n def test_mark_with_wrong_marker(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n import pytest\n class pytestmark(object):\n pass\n def test_func():\n pass\n \"\"\"\n )\n values = reprec.getfailedcollections()\n assert len(values) == 1\n assert \"TypeError\" in str(values[0].longrepr)\n\n def test_mark_dynamically_in_funcarg(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture\n def arg(request):\n request.applymarker(pytest.mark.hello)\n def pytest_terminal_summary(terminalreporter):\n values = terminalreporter.stats['passed']\n terminalreporter._tw.line(\"keyword: %s\" % values[0].keywords)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_func(arg):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"keyword: *hello*\"])\n\n def test_no_marker_match_on_unmarked_names(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.shouldmatch\n def test_marked():\n assert 1\n\n def test_unmarked():\n assert 1\n \"\"\"\n )\n reprec = testdir.inline_run(\"-m\", \"test_unmarked\", p)\n passed, skipped, failed = reprec.listoutcomes()\n assert len(passed) + len(skipped) + len(failed) == 0\n dlist = reprec.getcalls(\"pytest_deselected\")\n deselected_tests = dlist[0].items\n assert len(deselected_tests) == 2\n\n def test_invalid_m_option(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_a():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-m bogus/\")\n result.stdout.fnmatch_lines(\n [\"INTERNALERROR> Marker expression must be valid Python!\"]\n )\n\n def test_keywords_at_node_level(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=\"session\", autouse=True)\n def some(request):\n request.keywords[\"hello\"] = 42\n assert \"world\" not in request.keywords\n\n @pytest.fixture(scope=\"function\", autouse=True)\n def funcsetup(request):\n assert \"world\" in request.keywords\n assert \"hello\" in request.keywords\n\n @pytest.mark.world\n def test_function():\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n @ignore_markinfo\n def test_keyword_added_for_session(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_collection_modifyitems(session):\n session.add_marker(\"mark1\")\n session.add_marker(pytest.mark.mark2)\n session.add_marker(pytest.mark.mark3)\n pytest.raises(ValueError, lambda:\n session.add_marker(10))\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_some(request):\n assert \"mark1\" in request.keywords\n assert \"mark2\" in request.keywords\n assert \"mark3\" in request.keywords\n assert 10 not in request.keywords\n marker = request.node.get_closest_marker(\"mark1\")\n assert marker.name == \"mark1\"\n assert marker.args == ()\n assert marker.kwargs == {}\n \"\"\"\n )\n reprec = testdir.inline_run(\"-m\", \"mark1\", SHOW_PYTEST_WARNINGS_ARG)\n reprec.assertoutcome(passed=1)\n\n def assert_markers(self, items, **expected):\n \"\"\"assert that given items have expected marker names applied to them.\n expected should be a dict of (item name -> seq of expected marker names)\n\n .. note:: this could be moved to ``testdir`` if proven to be useful\n to other modules.\n \"\"\"\n\n items = {x.name: x for x in items}\n for name, expected_markers in expected.items():\n markers = {m.name for m in items[name].iter_markers()}\n assert markers == set(expected_markers)\n\n @pytest.mark.filterwarnings(\"ignore\")\n def test_mark_from_parameters(self, testdir):\n \"\"\"#1540\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n pytestmark = pytest.mark.skipif(True, reason='skip all')\n\n # skipifs inside fixture params\n params = [pytest.mark.skipif(False, reason='dont skip')('parameter')]\n\n\n @pytest.fixture(params=params)\n def parameter(request):\n return request.param\n\n\n def test_1(parameter):\n assert True\n \"\"\"\n )\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n reprec.assertoutcome(skipped=1)\n\n\nclass TestKeywordSelection(object):\n def test_select_simple(self, testdir):\n file_test = testdir.makepyfile(\n \"\"\"\n def test_one():\n assert 0\n class TestClass(object):\n def test_method_one(self):\n assert 42 == 43\n \"\"\"\n )\n\n def check(keyword, name):\n reprec = testdir.inline_run(\"-s\", \"-k\", keyword, file_test)\n passed, skipped, failed = reprec.listoutcomes()\n assert len(failed) == 1\n assert failed[0].nodeid.split(\"::\")[-1] == name\n assert len(reprec.getcalls(\"pytest_deselected\")) == 1\n\n for keyword in [\"test_one\", \"est_on\"]:\n check(keyword, \"test_one\")\n check(\"TestClass and test\", \"test_method_one\")\n\n @pytest.mark.parametrize(\n \"keyword\",\n [\n \"xxx\",\n \"xxx and test_2\",\n \"TestClass\",\n \"xxx and not test_1\",\n \"TestClass and test_2\",\n \"xxx and TestClass and test_2\",\n ],\n )\n def test_select_extra_keywords(self, testdir, keyword):\n p = testdir.makepyfile(\n test_select=\"\"\"\n def test_1():\n pass\n class TestClass(object):\n def test_2(self):\n pass\n \"\"\"\n )\n testdir.makepyfile(\n conftest=\"\"\"\n import pytest\n @pytest.hookimpl(hookwrapper=True)\n def pytest_pycollect_makeitem(name):\n outcome = yield\n if name == \"TestClass\":\n item = outcome.get_result()\n item.extra_keyword_matches.add(\"xxx\")\n \"\"\"\n )\n reprec = testdir.inline_run(p.dirpath(), \"-s\", \"-k\", keyword)\n print(\"keyword\", repr(keyword))\n passed, skipped, failed = reprec.listoutcomes()\n assert len(passed) == 1\n assert passed[0].nodeid.endswith(\"test_2\")\n dlist = reprec.getcalls(\"pytest_deselected\")\n assert len(dlist) == 1\n assert dlist[0].items[0].name == \"test_1\"\n\n def test_select_starton(self, testdir):\n threepass = testdir.makepyfile(\n test_threepass=\"\"\"\n def test_one(): assert 1\n def test_two(): assert 1\n def test_three(): assert 1\n \"\"\"\n )\n reprec = testdir.inline_run(\"-k\", \"test_two:\", threepass)\n passed, skipped, failed = reprec.listoutcomes()\n assert len(passed) == 2\n assert not failed\n dlist = reprec.getcalls(\"pytest_deselected\")\n assert len(dlist) == 1\n item = dlist[0].items[0]\n assert item.name == \"test_one\"\n\n def test_keyword_extra(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_one():\n assert 0\n test_one.mykeyword = True\n \"\"\"\n )\n reprec = testdir.inline_run(\"-k\", \"mykeyword\", p)\n passed, skipped, failed = reprec.countoutcomes()\n assert failed == 1\n\n @pytest.mark.xfail\n def test_keyword_extra_dash(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_one():\n assert 0\n test_one.mykeyword = True\n \"\"\"\n )\n # with argparse the argument to an option cannot\n # start with '-'\n reprec = testdir.inline_run(\"-k\", \"-mykeyword\", p)\n passed, skipped, failed = reprec.countoutcomes()\n assert passed + skipped + failed == 0\n\n def test_no_magic_values(self, testdir):\n \"\"\"Make sure the tests do not match on magic values,\n no double underscored values, like '__dict__',\n and no instance values, like '()'.\n \"\"\"\n p = testdir.makepyfile(\n \"\"\"\n def test_one(): assert 1\n \"\"\"\n )\n\n def assert_test_is_not_selected(keyword):\n reprec = testdir.inline_run(\"-k\", keyword, p)\n passed, skipped, failed = reprec.countoutcomes()\n dlist = reprec.getcalls(\"pytest_deselected\")\n assert passed + skipped + failed == 0\n deselected_tests = dlist[0].items\n assert len(deselected_tests) == 1\n\n assert_test_is_not_selected(\"__\")\n assert_test_is_not_selected(\"()\")\n\n\nclass TestMarkDecorator(object):\n @pytest.mark.parametrize(\n \"lhs, rhs, expected\",\n [\n (pytest.mark.foo(), pytest.mark.foo(), True),\n (pytest.mark.foo(), pytest.mark.bar(), False),\n (pytest.mark.foo(), \"bar\", False),\n (\"foo\", pytest.mark.bar(), False),\n ],\n )\n def test__eq__(self, lhs, rhs, expected):\n assert (lhs == rhs) == expected\n\n\n@pytest.mark.parametrize(\"mark\", [None, \"\", \"skip\", \"xfail\"])\ndef test_parameterset_for_parametrize_marks(testdir, mark):\n if mark is not None:\n testdir.makeini(\n \"\"\"\n [pytest]\n {}={}\n \"\"\".format(\n EMPTY_PARAMETERSET_OPTION, mark\n )\n )\n\n config = testdir.parseconfig()\n from _pytest.mark import pytest_configure, get_empty_parameterset_mark\n\n pytest_configure(config)\n result_mark = get_empty_parameterset_mark(config, [\"a\"], all)\n if mark in (None, \"\"):\n # normalize to the requested name\n mark = \"skip\"\n assert result_mark.name == mark\n assert result_mark.kwargs[\"reason\"].startswith(\"got empty parameter set \")\n if mark == \"xfail\":\n assert result_mark.kwargs.get(\"run\") is False\n\n\ndef test_parameterset_for_fail_at_collect(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n {}=fail_at_collect\n \"\"\".format(\n EMPTY_PARAMETERSET_OPTION\n )\n )\n\n config = testdir.parseconfig()\n from _pytest.mark import pytest_configure, get_empty_parameterset_mark\n\n pytest_configure(config)\n\n with pytest.raises(\n Collector.CollectError,\n match=r\"Empty parameter set in 'pytest_configure' at line \\d\\d+\",\n ):\n get_empty_parameterset_mark(config, [\"a\"], pytest_configure)\n\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize(\"empty\", [])\n def test():\n pass\n \"\"\"\n )\n result = testdir.runpytest(str(p1))\n result.stdout.fnmatch_lines(\n [\n \"collected 0 items / 1 errors\",\n \"* ERROR collecting test_parameterset_for_fail_at_collect.py *\",\n \"Empty parameter set in 'test' at line 3\",\n \"*= 1 error in *\",\n ]\n )\n assert result.ret == EXIT_INTERRUPTED\n\n\ndef test_parameterset_for_parametrize_bad_markname(testdir):\n with pytest.raises(pytest.UsageError):\n test_parameterset_for_parametrize_marks(testdir, \"bad\")\n\n\ndef test_mark_expressions_no_smear(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n class BaseTests(object):\n def test_something(self):\n pass\n\n @pytest.mark.FOO\n class TestFooClass(BaseTests):\n pass\n\n @pytest.mark.BAR\n class TestBarClass(BaseTests):\n pass\n \"\"\"\n )\n\n reprec = testdir.inline_run(\"-m\", \"FOO\")\n passed, skipped, failed = reprec.countoutcomes()\n dlist = reprec.getcalls(\"pytest_deselected\")\n assert passed == 1\n assert skipped == failed == 0\n deselected_tests = dlist[0].items\n assert len(deselected_tests) == 1\n\n # todo: fixed\n # keywords smear - expected behaviour\n # reprec_keywords = testdir.inline_run(\"-k\", \"FOO\")\n # passed_k, skipped_k, failed_k = reprec_keywords.countoutcomes()\n # assert passed_k == 2\n # assert skipped_k == failed_k == 0\n\n\ndef test_addmarker_order():\n node = Node(\"Test\", config=mock.Mock(), session=mock.Mock(), nodeid=\"Test\")\n node.add_marker(\"foo\")\n node.add_marker(\"bar\")\n node.add_marker(\"baz\", append=False)\n extracted = [x.name for x in node.iter_markers()]\n assert extracted == [\"baz\", \"foo\", \"bar\"]\n\n\n@pytest.mark.filterwarnings(\"ignore\")\ndef test_markers_from_parametrize(testdir):\n \"\"\"#3605\"\"\"\n testdir.makepyfile(\n \"\"\"\n from __future__ import print_function\n import pytest\n\n first_custom_mark = pytest.mark.custom_marker\n custom_mark = pytest.mark.custom_mark\n @pytest.fixture(autouse=True)\n def trigger(request):\n custom_mark = list(request.node.iter_markers('custom_mark'))\n print(\"Custom mark %s\" % custom_mark)\n\n @custom_mark(\"custom mark non parametrized\")\n def test_custom_mark_non_parametrized():\n print(\"Hey from test\")\n\n @pytest.mark.parametrize(\n \"obj_type\",\n [\n first_custom_mark(\"first custom mark\")(\"template\"),\n pytest.param( # Think this should be recommended way?\n \"disk\",\n marks=custom_mark('custom mark1')\n ),\n custom_mark(\"custom mark2\")(\"vm\"), # Tried also this\n ]\n )\n def test_custom_mark_parametrized(obj_type):\n print(\"obj_type is:\", obj_type)\n \"\"\"\n )\n\n result = testdir.runpytest(SHOW_PYTEST_WARNINGS_ARG)\n result.assert_outcomes(passed=4)\n\n\ndef test_pytest_param_id_requires_string():\n with pytest.raises(TypeError) as excinfo:\n pytest.param(id=True)\n msg, = excinfo.value.args\n if six.PY2:\n assert msg == \"Expected id to be a string, got : True\"\n else:\n assert msg == \"Expected id to be a string, got : True\"\n\n\n@pytest.mark.parametrize(\"s\", (None, \"hello world\"))\ndef test_pytest_param_id_allows_none_or_string(s):\n assert pytest.param(id=s)\n\n\ndef test_pytest_param_warning_on_unknown_kwargs():\n with pytest.warns(PytestDeprecationWarning) as warninfo:\n # typo, should be marks=\n pytest.param(1, 2, mark=pytest.mark.xfail())\n assert warninfo[0].filename == __file__\n msg, = warninfo[0].message.args\n assert msg == (\n \"pytest.param() got unexpected keyword arguments: ['mark'].\\n\"\n \"This will be an error in future versions.\"\n )\n"},{"col":4,"comment":"null","endLoc":184,"header":"def test_register_imported_modules(self)","id":2071,"name":"test_register_imported_modules","nodeType":"Function","startLoc":174,"text":"def test_register_imported_modules(self):\n pm = PytestPluginManager()\n mod = types.ModuleType(\"x.y.pytest_hello\")\n pm.register(mod)\n assert pm.is_registered(mod)\n values = pm.get_plugins()\n assert mod in values\n pytest.raises(ValueError, pm.register, mod)\n pytest.raises(ValueError, lambda: pm.register(mod))\n # assert not pm.is_registered(mod2)\n assert pm.get_plugins() == values"},{"attributeType":"null","col":0,"comment":"null","endLoc":31,"id":2072,"name":"EXIT_INTERRUPTED","nodeType":"Attribute","startLoc":31,"text":"EXIT_INTERRUPTED"},{"className":"FixtureManager","col":0,"comment":"\n pytest fixtures definitions and information is stored and managed\n from this class.\n\n During collection fm.parsefactories() is called multiple times to parse\n fixture function definitions into FixtureDef objects and internal\n data structures.\n\n During collection of test functions, metafunc-mechanics instantiate\n a FuncFixtureInfo object which is cached per node/func-name.\n This FuncFixtureInfo object is later retrieved by Function nodes\n which themselves offer a fixturenames attribute.\n\n The FuncFixtureInfo object holds information about fixtures and FixtureDefs\n relevant for a particular function. An initial list of fixtures is\n assembled like this:\n\n - ini-defined usefixtures\n - autouse-marked fixtures along the collection chain up from the function\n - usefixtures markers at module/class/function level\n - test function funcargs\n\n Subsequently the funcfixtureinfo.fixturenames attribute is computed\n as the closure of the fixtures needed to setup the initial fixtures,\n i. e. fixtures needed by fixture functions themselves are appended\n to the fixturenames list.\n\n Upon the test-setup phases all fixturenames are instantiated, retrieved\n by a lookup of their FuncFixtureInfo.\n ","endLoc":1356,"id":2073,"nodeType":"Class","startLoc":1086,"text":"class FixtureManager(object):\n \"\"\"\n pytest fixtures definitions and information is stored and managed\n from this class.\n\n During collection fm.parsefactories() is called multiple times to parse\n fixture function definitions into FixtureDef objects and internal\n data structures.\n\n During collection of test functions, metafunc-mechanics instantiate\n a FuncFixtureInfo object which is cached per node/func-name.\n This FuncFixtureInfo object is later retrieved by Function nodes\n which themselves offer a fixturenames attribute.\n\n The FuncFixtureInfo object holds information about fixtures and FixtureDefs\n relevant for a particular function. An initial list of fixtures is\n assembled like this:\n\n - ini-defined usefixtures\n - autouse-marked fixtures along the collection chain up from the function\n - usefixtures markers at module/class/function level\n - test function funcargs\n\n Subsequently the funcfixtureinfo.fixturenames attribute is computed\n as the closure of the fixtures needed to setup the initial fixtures,\n i. e. fixtures needed by fixture functions themselves are appended\n to the fixturenames list.\n\n Upon the test-setup phases all fixturenames are instantiated, retrieved\n by a lookup of their FuncFixtureInfo.\n \"\"\"\n\n FixtureLookupError = FixtureLookupError\n FixtureLookupErrorRepr = FixtureLookupErrorRepr\n\n def __init__(self, session):\n self.session = session\n self.config = session.config\n self._arg2fixturedefs = {}\n self._holderobjseen = set()\n self._arg2finish = {}\n self._nodeid_and_autousenames = [(\"\", self.config.getini(\"usefixtures\"))]\n session.config.pluginmanager.register(self, \"funcmanage\")\n\n def _get_direct_parametrize_args(self, node):\n \"\"\"This function returns all the direct parametrization\n arguments of a node, so we don't mistake them for fixtures\n\n Check https://github.com/pytest-dev/pytest/issues/5036\n\n This things are done later as well when dealing with parametrization\n so this could be improved\n \"\"\"\n from _pytest.mark import ParameterSet\n\n parametrize_argnames = []\n for marker in node.iter_markers(name=\"parametrize\"):\n if not marker.kwargs.get(\"indirect\", False):\n p_argnames, _ = ParameterSet._parse_parametrize_args(\n *marker.args, **marker.kwargs\n )\n parametrize_argnames.extend(p_argnames)\n\n return parametrize_argnames\n\n def getfixtureinfo(self, node, func, cls, funcargs=True):\n if funcargs and not getattr(node, \"nofuncargs\", False):\n argnames = getfuncargnames(func, cls=cls)\n else:\n argnames = ()\n\n usefixtures = itertools.chain.from_iterable(\n mark.args for mark in node.iter_markers(name=\"usefixtures\")\n )\n initialnames = tuple(usefixtures) + argnames\n fm = node.session._fixturemanager\n initialnames, names_closure, arg2fixturedefs = fm.getfixtureclosure(\n initialnames, node, ignore_args=self._get_direct_parametrize_args(node)\n )\n return FuncFixtureInfo(argnames, initialnames, names_closure, arg2fixturedefs)\n\n def pytest_plugin_registered(self, plugin):\n nodeid = None\n try:\n p = py.path.local(plugin.__file__).realpath()\n except AttributeError:\n pass\n else:\n # construct the base nodeid which is later used to check\n # what fixtures are visible for particular tests (as denoted\n # by their test id)\n if p.basename.startswith(\"conftest.py\"):\n nodeid = p.dirpath().relto(self.config.rootdir)\n if p.sep != nodes.SEP:\n nodeid = nodeid.replace(p.sep, nodes.SEP)\n\n self.parsefactories(plugin, nodeid)\n\n def _getautousenames(self, nodeid):\n \"\"\" return a tuple of fixture names to be used. \"\"\"\n autousenames = []\n for baseid, basenames in self._nodeid_and_autousenames:\n if nodeid.startswith(baseid):\n if baseid:\n i = len(baseid)\n nextchar = nodeid[i : i + 1]\n if nextchar and nextchar not in \":/\":\n continue\n autousenames.extend(basenames)\n return autousenames\n\n def getfixtureclosure(self, fixturenames, parentnode, ignore_args=()):\n # collect the closure of all fixtures , starting with the given\n # fixturenames as the initial set. As we have to visit all\n # factory definitions anyway, we also return an arg2fixturedefs\n # mapping so that the caller can reuse it and does not have\n # to re-discover fixturedefs again for each fixturename\n # (discovering matching fixtures for a given name/node is expensive)\n\n parentid = parentnode.nodeid\n fixturenames_closure = self._getautousenames(parentid)\n\n def merge(otherlist):\n for arg in otherlist:\n if arg not in fixturenames_closure:\n fixturenames_closure.append(arg)\n\n merge(fixturenames)\n\n # at this point, fixturenames_closure contains what we call \"initialnames\",\n # which is a set of fixturenames the function immediately requests. We\n # need to return it as well, so save this.\n initialnames = tuple(fixturenames_closure)\n\n arg2fixturedefs = {}\n lastlen = -1\n while lastlen != len(fixturenames_closure):\n lastlen = len(fixturenames_closure)\n for argname in fixturenames_closure:\n if argname in ignore_args:\n continue\n if argname in arg2fixturedefs:\n continue\n fixturedefs = self.getfixturedefs(argname, parentid)\n if fixturedefs:\n arg2fixturedefs[argname] = fixturedefs\n merge(fixturedefs[-1].argnames)\n\n def sort_by_scope(arg_name):\n try:\n fixturedefs = arg2fixturedefs[arg_name]\n except KeyError:\n return scopes.index(\"function\")\n else:\n return fixturedefs[-1].scopenum\n\n fixturenames_closure.sort(key=sort_by_scope)\n return initialnames, fixturenames_closure, arg2fixturedefs\n\n def pytest_generate_tests(self, metafunc):\n for argname in metafunc.fixturenames:\n faclist = metafunc._arg2fixturedefs.get(argname)\n if faclist:\n fixturedef = faclist[-1]\n if fixturedef.params is not None:\n markers = list(metafunc.definition.iter_markers(\"parametrize\"))\n for parametrize_mark in markers:\n if \"argnames\" in parametrize_mark.kwargs:\n argnames = parametrize_mark.kwargs[\"argnames\"]\n else:\n argnames = parametrize_mark.args[0]\n\n if not isinstance(argnames, (tuple, list)):\n argnames = [\n x.strip() for x in argnames.split(\",\") if x.strip()\n ]\n if argname in argnames:\n break\n else:\n metafunc.parametrize(\n argname,\n fixturedef.params,\n indirect=True,\n scope=fixturedef.scope,\n ids=fixturedef.ids,\n )\n else:\n continue # will raise FixtureLookupError at setup time\n\n def pytest_collection_modifyitems(self, items):\n # separate parametrized setups\n items[:] = reorder_items(items)\n\n def parsefactories(self, node_or_obj, nodeid=NOTSET, unittest=False):\n if nodeid is not NOTSET:\n holderobj = node_or_obj\n else:\n holderobj = node_or_obj.obj\n nodeid = node_or_obj.nodeid\n if holderobj in self._holderobjseen:\n return\n\n self._holderobjseen.add(holderobj)\n autousenames = []\n for name in dir(holderobj):\n # The attribute can be an arbitrary descriptor, so the attribute\n # access below can raise. safe_getatt() ignores such exceptions.\n obj = safe_getattr(holderobj, name, None)\n marker = getfixturemarker(obj)\n if not isinstance(marker, FixtureFunctionMarker):\n # magic globals with __getattr__ might have got us a wrong\n # fixture attribute\n continue\n\n if marker.name:\n name = marker.name\n\n # during fixture definition we wrap the original fixture function\n # to issue a warning if called directly, so here we unwrap it in order to not emit the warning\n # when pytest itself calls the fixture function\n if six.PY2 and unittest:\n # hack on Python 2 because of the unbound methods\n obj = get_real_func(obj)\n else:\n obj = get_real_method(obj, holderobj)\n\n fixture_def = FixtureDef(\n self,\n nodeid,\n name,\n obj,\n marker.scope,\n marker.params,\n unittest=unittest,\n ids=marker.ids,\n )\n\n faclist = self._arg2fixturedefs.setdefault(name, [])\n if fixture_def.has_location:\n faclist.append(fixture_def)\n else:\n # fixturedefs with no location are at the front\n # so this inserts the current fixturedef after the\n # existing fixturedefs from external plugins but\n # before the fixturedefs provided in conftests.\n i = len([f for f in faclist if not f.has_location])\n faclist.insert(i, fixture_def)\n if marker.autouse:\n autousenames.append(name)\n\n if autousenames:\n self._nodeid_and_autousenames.append((nodeid or \"\", autousenames))\n\n def getfixturedefs(self, argname, nodeid):\n \"\"\"\n Gets a list of fixtures which are applicable to the given node id.\n\n :param str argname: name of the fixture to search for\n :param str nodeid: full node id of the requesting test.\n :return: list[FixtureDef]\n \"\"\"\n try:\n fixturedefs = self._arg2fixturedefs[argname]\n except KeyError:\n return None\n return tuple(self._matchfactories(fixturedefs, nodeid))\n\n def _matchfactories(self, fixturedefs, nodeid):\n for fixturedef in fixturedefs:\n if nodes.ischildnode(fixturedef.baseid, nodeid):\n yield fixturedef"},{"attributeType":"null","col":0,"comment":"null","endLoc":18,"id":2074,"name":"EMPTY_PARAMETERSET_OPTION","nodeType":"Attribute","startLoc":18,"text":"EMPTY_PARAMETERSET_OPTION"},{"className":"PdbInvoke","col":0,"comment":"null","endLoc":269,"id":2075,"nodeType":"Class","startLoc":257,"text":"class PdbInvoke(object):\n def pytest_exception_interact(self, node, call, report):\n capman = node.config.pluginmanager.getplugin(\"capturemanager\")\n if capman:\n capman.suspend_global_capture(in_=True)\n out, err = capman.read_global_capture()\n sys.stdout.write(out)\n sys.stdout.write(err)\n _enter_pdb(node, call.excinfo, report)\n\n def pytest_internalerror(self, excrepr, excinfo):\n tb = _postmortem_traceback(excinfo)\n post_mortem(tb)"},{"col":4,"comment":"null","endLoc":265,"header":"def pytest_exception_interact(self, node, call, report)","id":2076,"name":"pytest_exception_interact","nodeType":"Function","startLoc":258,"text":"def pytest_exception_interact(self, node, call, report):\n capman = node.config.pluginmanager.getplugin(\"capturemanager\")\n if capman:\n capman.suspend_global_capture(in_=True)\n out, err = capman.read_global_capture()\n sys.stdout.write(out)\n sys.stdout.write(err)\n _enter_pdb(node, call.excinfo, report)"},{"className":"MarkGenerator","col":0,"comment":" Factory for :class:`MarkDecorator` objects - exposed as\n a ``pytest.mark`` singleton instance. Example::\n\n import pytest\n @pytest.mark.slowtest\n def test_function():\n pass\n\n will set a 'slowtest' :class:`MarkInfo` object\n on the ``test_function`` object. ","endLoc":337,"id":2077,"nodeType":"Class","startLoc":290,"text":"class MarkGenerator(object):\n \"\"\" Factory for :class:`MarkDecorator` objects - exposed as\n a ``pytest.mark`` singleton instance. Example::\n\n import pytest\n @pytest.mark.slowtest\n def test_function():\n pass\n\n will set a 'slowtest' :class:`MarkInfo` object\n on the ``test_function`` object. \"\"\"\n\n _config = None\n _markers = set()\n\n def __getattr__(self, name):\n if name[0] == \"_\":\n raise AttributeError(\"Marker name must NOT start with underscore\")\n\n if self._config is not None:\n # We store a set of markers as a performance optimisation - if a mark\n # name is in the set we definitely know it, but a mark may be known and\n # not in the set. We therefore start by updating the set!\n if name not in self._markers:\n for line in self._config.getini(\"markers\"):\n # example lines: \"skipif(condition): skip the given test if...\"\n # or \"hypothesis: tests which use Hypothesis\", so to get the\n # marker name we split on both `:` and `(`.\n marker = line.split(\":\")[0].split(\"(\")[0].strip()\n self._markers.add(marker)\n\n # If the name is not in the set of known marks after updating,\n # then it really is time to issue a warning or an error.\n if name not in self._markers:\n if self._config.option.strict_markers:\n fail(\n \"{!r} not found in `markers` configuration option\".format(name),\n pytrace=False,\n )\n else:\n warnings.warn(\n \"Unknown pytest.mark.%s - is this a typo? You can register \"\n \"custom marks to avoid this warning - for details, see \"\n \"https://docs.pytest.org/en/latest/mark.html\" % name,\n PytestUnknownMarkWarning,\n )\n\n return MarkDecorator(Mark(name, (), {}))"},{"col":4,"comment":"null","endLoc":1128,"header":"def __init__(self, session)","id":2078,"name":"__init__","nodeType":"Function","startLoc":1121,"text":"def __init__(self, session):\n self.session = session\n self.config = session.config\n self._arg2fixturedefs = {}\n self._holderobjseen = set()\n self._arg2finish = {}\n self._nodeid_and_autousenames = [(\"\", self.config.getini(\"usefixtures\"))]\n session.config.pluginmanager.register(self, \"funcmanage\")"},{"col":4,"comment":"null","endLoc":337,"header":"def __getattr__(self, name)","id":2079,"name":"__getattr__","nodeType":"Function","startLoc":305,"text":"def __getattr__(self, name):\n if name[0] == \"_\":\n raise AttributeError(\"Marker name must NOT start with underscore\")\n\n if self._config is not None:\n # We store a set of markers as a performance optimisation - if a mark\n # name is in the set we definitely know it, but a mark may be known and\n # not in the set. We therefore start by updating the set!\n if name not in self._markers:\n for line in self._config.getini(\"markers\"):\n # example lines: \"skipif(condition): skip the given test if...\"\n # or \"hypothesis: tests which use Hypothesis\", so to get the\n # marker name we split on both `:` and `(`.\n marker = line.split(\":\")[0].split(\"(\")[0].strip()\n self._markers.add(marker)\n\n # If the name is not in the set of known marks after updating,\n # then it really is time to issue a warning or an error.\n if name not in self._markers:\n if self._config.option.strict_markers:\n fail(\n \"{!r} not found in `markers` configuration option\".format(name),\n pytrace=False,\n )\n else:\n warnings.warn(\n \"Unknown pytest.mark.%s - is this a typo? You can register \"\n \"custom marks to avoid this warning - for details, see \"\n \"https://docs.pytest.org/en/latest/mark.html\" % name,\n PytestUnknownMarkWarning,\n )\n\n return MarkDecorator(Mark(name, (), {}))"},{"col":4,"comment":"null","endLoc":70,"header":"def test_detect_recursive_dependency_error(self, testdir)","id":2080,"name":"test_detect_recursive_dependency_error","nodeType":"Function","startLoc":65,"text":"def test_detect_recursive_dependency_error(self, testdir):\n testdir.copy_example()\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"*recursive dependency involving fixture 'fix1' detected*\"]\n )"},{"col":4,"comment":"null","endLoc":178,"header":"def addFailure(self, testcase, rawexcinfo)","id":2081,"name":"addFailure","nodeType":"Function","startLoc":177,"text":"def addFailure(self, testcase, rawexcinfo):\n self._addexcinfo(rawexcinfo)"},{"col":4,"comment":"null","endLoc":185,"header":"def addSkip(self, testcase, reason)","id":2083,"name":"addSkip","nodeType":"Function","startLoc":180,"text":"def addSkip(self, testcase, reason):\n try:\n skip(reason)\n except skip.Exception:\n self._skipped_by_mark = True\n self._addexcinfo(sys.exc_info())"},{"col":4,"comment":"null","endLoc":79,"header":"def test_funcarg_basic(self, testdir)","id":2084,"name":"test_funcarg_basic","nodeType":"Function","startLoc":72,"text":"def test_funcarg_basic(self, testdir):\n testdir.copy_example()\n item = testdir.getitem(Path(\"test_funcarg_basic.py\"))\n fixtures.fillfixtures(item)\n del item.funcargs[\"request\"]\n assert len(get_public_names(item.funcargs)) == 2\n assert item.funcargs[\"some\"] == \"test_func\"\n assert item.funcargs[\"other\"] == 42"},{"col":4,"comment":"null","endLoc":84,"header":"def test_funcarg_lookup_modulelevel(self, testdir)","id":2085,"name":"test_funcarg_lookup_modulelevel","nodeType":"Function","startLoc":81,"text":"def test_funcarg_lookup_modulelevel(self, testdir):\n testdir.copy_example()\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)"},{"col":4,"comment":"null","endLoc":191,"header":"def addExpectedFailure(self, testcase, rawexcinfo, reason=\"\")","id":2086,"name":"addExpectedFailure","nodeType":"Function","startLoc":187,"text":"def addExpectedFailure(self, testcase, rawexcinfo, reason=\"\"):\n try:\n xfail(str(reason))\n except xfail.Exception:\n self._addexcinfo(sys.exc_info())"},{"col":4,"comment":"This function returns all the direct parametrization\n arguments of a node, so we don't mistake them for fixtures\n\n Check https://github.com/pytest-dev/pytest/issues/5036\n\n This things are done later as well when dealing with parametrization\n so this could be improved\n ","endLoc":1149,"header":"def _get_direct_parametrize_args(self, node)","id":2087,"name":"_get_direct_parametrize_args","nodeType":"Function","startLoc":1130,"text":"def _get_direct_parametrize_args(self, node):\n \"\"\"This function returns all the direct parametrization\n arguments of a node, so we don't mistake them for fixtures\n\n Check https://github.com/pytest-dev/pytest/issues/5036\n\n This things are done later as well when dealing with parametrization\n so this could be improved\n \"\"\"\n from _pytest.mark import ParameterSet\n\n parametrize_argnames = []\n for marker in node.iter_markers(name=\"parametrize\"):\n if not marker.kwargs.get(\"indirect\", False):\n p_argnames, _ = ParameterSet._parse_parametrize_args(\n *marker.args, **marker.kwargs\n )\n parametrize_argnames.extend(p_argnames)\n\n return parametrize_argnames"},{"col":4,"comment":"null","endLoc":89,"header":"def test_funcarg_lookup_classlevel(self, testdir)","id":2088,"name":"test_funcarg_lookup_classlevel","nodeType":"Function","startLoc":86,"text":"def test_funcarg_lookup_classlevel(self, testdir):\n p = testdir.copy_example()\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":4,"comment":"null","endLoc":94,"header":"def test_conftest_funcargs_only_available_in_subdir(self, testdir)","id":2089,"name":"test_conftest_funcargs_only_available_in_subdir","nodeType":"Function","startLoc":91,"text":"def test_conftest_funcargs_only_available_in_subdir(self, testdir):\n testdir.copy_example()\n result = testdir.runpytest(\"-v\")\n result.assert_outcomes(passed=2)"},{"col":4,"comment":"null","endLoc":1165,"header":"def getfixtureinfo(self, node, func, cls, funcargs=True)","id":2090,"name":"getfixtureinfo","nodeType":"Function","startLoc":1151,"text":"def getfixtureinfo(self, node, func, cls, funcargs=True):\n if funcargs and not getattr(node, \"nofuncargs\", False):\n argnames = getfuncargnames(func, cls=cls)\n else:\n argnames = ()\n\n usefixtures = itertools.chain.from_iterable(\n mark.args for mark in node.iter_markers(name=\"usefixtures\")\n )\n initialnames = tuple(usefixtures) + argnames\n fm = node.session._fixturemanager\n initialnames, names_closure, arg2fixturedefs = fm.getfixtureclosure(\n initialnames, node, ignore_args=self._get_direct_parametrize_args(node)\n )\n return FuncFixtureInfo(argnames, initialnames, names_closure, arg2fixturedefs)"},{"col":4,"comment":"null","endLoc":101,"header":"def test_extend_fixture_module_class(self, testdir)","id":2093,"name":"test_extend_fixture_module_class","nodeType":"Function","startLoc":96,"text":"def test_extend_fixture_module_class(self, testdir):\n testfile = testdir.copy_example()\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest(testfile)\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":34,"endLoc":182,"id":2094,"nodeType":"Lambda","startLoc":182,"text":"lambda: pm.register(mod)"},{"col":4,"comment":"null","endLoc":108,"header":"def test_extend_fixture_conftest_module(self, testdir)","id":2095,"name":"test_extend_fixture_conftest_module","nodeType":"Function","startLoc":103,"text":"def test_extend_fixture_conftest_module(self, testdir):\n p = testdir.copy_example()\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest(next(p.visit(\"test_*.py\")))\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":4,"comment":"null","endLoc":192,"header":"def test_canonical_import(self, monkeypatch)","id":2096,"name":"test_canonical_import","nodeType":"Function","startLoc":186,"text":"def test_canonical_import(self, monkeypatch):\n mod = types.ModuleType(\"pytest_xyz\")\n monkeypatch.setitem(sys.modules, \"pytest_xyz\", mod)\n pm = PytestPluginManager()\n pm.import_plugin(\"pytest_xyz\")\n assert pm.get_plugin(\"pytest_xyz\") == mod\n assert pm.is_registered(mod)"},{"col":0,"comment":"null","endLoc":317,"header":"def _enter_pdb(node, excinfo, rep)","id":2097,"name":"_enter_pdb","nodeType":"Function","startLoc":291,"text":"def _enter_pdb(node, excinfo, rep):\n # XXX we re-use the TerminalReporter's terminalwriter\n # because this seems to avoid some encoding related troubles\n # for not completely clear reasons.\n tw = node.config.pluginmanager.getplugin(\"terminalreporter\")._tw\n tw.line()\n\n showcapture = node.config.option.showcapture\n\n for sectionname, content in (\n (\"stdout\", rep.capstdout),\n (\"stderr\", rep.capstderr),\n (\"log\", rep.caplog),\n ):\n if showcapture in (sectionname, \"all\") and content:\n tw.sep(\">\", \"captured \" + sectionname)\n if content[-1:] == \"\\n\":\n content = content[:-1]\n tw.line(content)\n\n tw.sep(\">\", \"traceback\")\n rep.toterminal(tw)\n tw.sep(\">\", \"entering PDB\")\n tb = _postmortem_traceback(excinfo)\n rep._pdbshown = True\n post_mortem(tb)\n return rep"},{"col":4,"comment":"null","endLoc":115,"header":"def test_extend_fixture_conftest_conftest(self, testdir)","id":2098,"name":"test_extend_fixture_conftest_conftest","nodeType":"Function","startLoc":110,"text":"def test_extend_fixture_conftest_conftest(self, testdir):\n p = testdir.copy_example()\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest(next(p.visit(\"test_*.py\")))\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":4,"comment":"null","endLoc":202,"header":"def test_consider_module(self, testdir, pytestpm)","id":2099,"name":"test_consider_module","nodeType":"Function","startLoc":194,"text":"def test_consider_module(self, testdir, pytestpm):\n testdir.syspathinsert()\n testdir.makepyfile(pytest_p1=\"#\")\n testdir.makepyfile(pytest_p2=\"#\")\n mod = types.ModuleType(\"temp\")\n mod.pytest_plugins = [\"pytest_p1\", \"pytest_p2\"]\n pytestpm.consider_module(mod)\n assert pytestpm.get_plugin(\"pytest_p1\").__name__ == \"pytest_p1\"\n assert pytestpm.get_plugin(\"pytest_p2\").__name__ == \"pytest_p2\""},{"col":4,"comment":"null","endLoc":146,"header":"def test_extend_fixture_conftest_plugin(self, testdir)","id":2100,"name":"test_extend_fixture_conftest_plugin","nodeType":"Function","startLoc":117,"text":"def test_extend_fixture_conftest_plugin(self, testdir):\n testdir.makepyfile(\n testplugin=\"\"\"\n import pytest\n\n @pytest.fixture\n def foo():\n return 7\n \"\"\"\n )\n testdir.syspathinsert()\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n pytest_plugins = 'testplugin'\n\n @pytest.fixture\n def foo(foo):\n return foo + 7\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_foo(foo):\n assert foo == 14\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n assert result.ret == 0"},{"col":4,"comment":"null","endLoc":178,"header":"def test_extend_fixture_plugin_plugin(self, testdir)","id":2101,"name":"test_extend_fixture_plugin_plugin","nodeType":"Function","startLoc":148,"text":"def test_extend_fixture_plugin_plugin(self, testdir):\n # Two plugins should extend each order in loading order\n testdir.makepyfile(\n testplugin0=\"\"\"\n import pytest\n\n @pytest.fixture\n def foo():\n return 7\n \"\"\"\n )\n testdir.makepyfile(\n testplugin1=\"\"\"\n import pytest\n\n @pytest.fixture\n def foo(foo):\n return foo + 7\n \"\"\"\n )\n testdir.syspathinsert()\n testdir.makepyfile(\n \"\"\"\n pytest_plugins = ['testplugin0', 'testplugin1']\n\n def test_foo(foo):\n assert foo == 14\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0"},{"col":4,"comment":"Test override of the parametrized fixture with non-parametrized one on the test module level.","endLoc":206,"header":"def test_override_parametrized_fixture_conftest_module(self, testdir)","id":2102,"name":"test_override_parametrized_fixture_conftest_module","nodeType":"Function","startLoc":180,"text":"def test_override_parametrized_fixture_conftest_module(self, testdir):\n \"\"\"Test override of the parametrized fixture with non-parametrized one on the test module level.\"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[1, 2, 3])\n def spam(request):\n return request.param\n \"\"\"\n )\n testfile = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def spam():\n return 'spam'\n\n def test_spam(spam):\n assert spam == 'spam'\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest(testfile)\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":0,"comment":"null","endLoc":326,"header":"def _postmortem_traceback(excinfo)","id":2103,"name":"_postmortem_traceback","nodeType":"Function","startLoc":320,"text":"def _postmortem_traceback(excinfo):\n if isinstance(excinfo.value, UnexpectedException):\n # A doctest.UnexpectedException is not useful for post_mortem.\n # Use the underlying exception instead:\n return excinfo.value.exc_info[2]\n else:\n return excinfo._excinfo[2]"},{"col":4,"comment":"Test override of the parametrized fixture with non-parametrized one on the conftest level.","endLoc":243,"header":"def test_override_parametrized_fixture_conftest_conftest(self, testdir)","id":2104,"name":"test_override_parametrized_fixture_conftest_conftest","nodeType":"Function","startLoc":208,"text":"def test_override_parametrized_fixture_conftest_conftest(self, testdir):\n \"\"\"Test override of the parametrized fixture with non-parametrized one on the conftest level.\"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[1, 2, 3])\n def spam(request):\n return request.param\n \"\"\"\n )\n subdir = testdir.mkpydir(\"subdir\")\n subdir.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n\n @pytest.fixture\n def spam():\n return 'spam'\n \"\"\"\n )\n )\n testfile = subdir.join(\"test_spam.py\")\n testfile.write(\n textwrap.dedent(\n \"\"\"\\\n def test_spam(spam):\n assert spam == \"spam\"\n \"\"\"\n )\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest(testfile)\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":0,"comment":"null","endLoc":334,"header":"def post_mortem(t)","id":2105,"name":"post_mortem","nodeType":"Function","startLoc":329,"text":"def post_mortem(t):\n p = pytestPDB._init_pdb(\"post_mortem\")\n p.reset()\n p.interaction(None, t)\n if p.quitting:\n outcomes.exit(\"Quitting debugger\")"},{"col":4,"comment":"null","endLoc":218,"header":"def test_consider_module_import_module(self, testdir, _config_for_test)","id":2106,"name":"test_consider_module_import_module","nodeType":"Function","startLoc":204,"text":"def test_consider_module_import_module(self, testdir, _config_for_test):\n pytestpm = _config_for_test.pluginmanager\n mod = types.ModuleType(\"x\")\n mod.pytest_plugins = \"pytest_a\"\n aplugin = testdir.makepyfile(pytest_a=\"#\")\n reprec = testdir.make_hook_recorder(pytestpm)\n testdir.syspathinsert(aplugin.dirpath())\n pytestpm.consider_module(mod)\n call = reprec.getcall(pytestpm.hook.pytest_plugin_registered.name)\n assert call.plugin.__name__ == \"pytest_a\"\n\n # check that it is not registered twice\n pytestpm.consider_module(mod)\n values = reprec.getcalls(\"pytest_plugin_registered\")\n assert len(values) == 1"},{"col":4,"comment":"null","endLoc":194,"header":"def addUnexpectedSuccess(self, testcase, reason=\"\")","id":2108,"name":"addUnexpectedSuccess","nodeType":"Function","startLoc":193,"text":"def addUnexpectedSuccess(self, testcase, reason=\"\"):\n self._unexpectedsuccess = reason"},{"col":4,"comment":"null","endLoc":197,"header":"def addSuccess(self, testcase)","id":2109,"name":"addSuccess","nodeType":"Function","startLoc":196,"text":"def addSuccess(self, testcase):\n pass"},{"col":4,"comment":"null","endLoc":200,"header":"def stopTest(self, testcase)","id":2110,"name":"stopTest","nodeType":"Function","startLoc":199,"text":"def stopTest(self, testcase):\n pass"},{"col":4,"comment":"null","endLoc":220,"header":"def _handle_skip(self)","id":2111,"name":"_handle_skip","nodeType":"Function","startLoc":202,"text":"def _handle_skip(self):\n # implements the skipping machinery (see #2137)\n # analog to pythons Lib/unittest/case.py:run\n testMethod = getattr(self._testcase, self._testcase._testMethodName)\n if getattr(self._testcase.__class__, \"__unittest_skip__\", False) or getattr(\n testMethod, \"__unittest_skip__\", False\n ):\n # If the class or method was skipped.\n skip_why = getattr(\n self._testcase.__class__, \"__unittest_skip_why__\", \"\"\n ) or getattr(testMethod, \"__unittest_skip_why__\", \"\")\n try: # PY3, unittest2 on PY2\n self._testcase._addSkip(self, self._testcase, skip_why)\n except TypeError: # PY2\n if sys.version_info[0] != 2:\n raise\n self._testcase._addSkip(self, skip_why)\n return True\n return False"},{"col":4,"comment":"Test override of the non-parametrized fixture with parametrized one on the test module level.","endLoc":274,"header":"def test_override_non_parametrized_fixture_conftest_module(self, testdir)","id":2113,"name":"test_override_non_parametrized_fixture_conftest_module","nodeType":"Function","startLoc":245,"text":"def test_override_non_parametrized_fixture_conftest_module(self, testdir):\n \"\"\"Test override of the non-parametrized fixture with parametrized one on the test module level.\"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def spam():\n return 'spam'\n \"\"\"\n )\n testfile = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[1, 2, 3])\n def spam(request):\n return request.param\n\n params = {'spam': 1}\n\n def test_spam(spam):\n assert spam == params['spam']\n params['spam'] += 1\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n result = testdir.runpytest(testfile)\n result.stdout.fnmatch_lines([\"*3 passed*\"])"},{"attributeType":"null","col":4,"comment":"null","endLoc":302,"id":2116,"name":"_config","nodeType":"Attribute","startLoc":302,"text":"_config"},{"col":4,"comment":"null","endLoc":223,"header":"def test_consider_env_fails_to_import(self, monkeypatch, pytestpm)","id":2117,"name":"test_consider_env_fails_to_import","nodeType":"Function","startLoc":220,"text":"def test_consider_env_fails_to_import(self, monkeypatch, pytestpm):\n monkeypatch.setenv(\"PYTEST_PLUGINS\", \"nonexisting\", prepend=\",\")\n with pytest.raises(ImportError):\n pytestpm.consider_env()"},{"attributeType":"null","col":4,"comment":"null","endLoc":303,"id":2118,"name":"_markers","nodeType":"Attribute","startLoc":303,"text":"_markers"},{"className":"TestMark","col":0,"comment":"null","endLoc":57,"id":2119,"nodeType":"Class","startLoc":30,"text":"class TestMark(object):\n @pytest.mark.parametrize(\"attr\", [\"mark\", \"param\"])\n @pytest.mark.parametrize(\"modulename\", [\"py.test\", \"pytest\"])\n def test_pytest_exists_in_namespace_all(self, attr, modulename):\n module = sys.modules[modulename]\n assert attr in module.__all__\n\n def test_pytest_mark_notcallable(self):\n mark = Mark()\n pytest.raises((AttributeError, TypeError), mark)\n\n def test_mark_with_param(self):\n def some_function(abc):\n pass\n\n class SomeClass(object):\n pass\n\n assert pytest.mark.foo(some_function) is some_function\n assert pytest.mark.foo.with_args(some_function) is not some_function\n\n assert pytest.mark.foo(SomeClass) is SomeClass\n assert pytest.mark.foo.with_args(SomeClass) is not SomeClass\n\n def test_pytest_mark_name_starts_with_underscore(self):\n mark = Mark()\n with pytest.raises(AttributeError):\n mark._some_name"},{"col":4,"comment":"null","endLoc":35,"header":"@pytest.mark.parametrize(\"attr\", [\"mark\", \"param\"])\n @pytest.mark.parametrize(\"modulename\", [\"py.test\", \"pytest\"])\n def test_pytest_exists_in_namespace_all(self, attr, modulename)","id":2120,"name":"test_pytest_exists_in_namespace_all","nodeType":"Function","startLoc":31,"text":"@pytest.mark.parametrize(\"attr\", [\"mark\", \"param\"])\n @pytest.mark.parametrize(\"modulename\", [\"py.test\", \"pytest\"])\n def test_pytest_exists_in_namespace_all(self, attr, modulename):\n module = sys.modules[modulename]\n assert attr in module.__all__"},{"col":4,"comment":"Test override of the non-parametrized fixture with parametrized one on the conftest level.","endLoc":314,"header":"def test_override_non_parametrized_fixture_conftest_conftest(self, testdir)","id":2121,"name":"test_override_non_parametrized_fixture_conftest_conftest","nodeType":"Function","startLoc":276,"text":"def test_override_non_parametrized_fixture_conftest_conftest(self, testdir):\n \"\"\"Test override of the non-parametrized fixture with parametrized one on the conftest level.\"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def spam():\n return 'spam'\n \"\"\"\n )\n subdir = testdir.mkpydir(\"subdir\")\n subdir.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n\n @pytest.fixture(params=[1, 2, 3])\n def spam(request):\n return request.param\n \"\"\"\n )\n )\n testfile = subdir.join(\"test_spam.py\")\n testfile.write(\n textwrap.dedent(\n \"\"\"\\\n params = {'spam': 1}\n\n def test_spam(spam):\n assert spam == params['spam']\n params['spam'] += 1\n \"\"\"\n )\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n result = testdir.runpytest(testfile)\n result.stdout.fnmatch_lines([\"*3 passed*\"])"},{"col":4,"comment":"null","endLoc":39,"header":"def test_pytest_mark_notcallable(self)","id":2122,"name":"test_pytest_mark_notcallable","nodeType":"Function","startLoc":37,"text":"def test_pytest_mark_notcallable(self):\n mark = Mark()\n pytest.raises((AttributeError, TypeError), mark)"},{"className":"PytestAssertRewriteWarning","col":0,"comment":"\n Bases: :class:`PytestWarning`.\n\n Warning emitted by the pytest assert rewrite module.\n ","endLoc":18,"id":2123,"nodeType":"Class","startLoc":13,"text":"class PytestAssertRewriteWarning(PytestWarning):\n \"\"\"\n Bases: :class:`PytestWarning`.\n\n Warning emitted by the pytest assert rewrite module.\n \"\"\""},{"className":"PytestCacheWarning","col":0,"comment":"\n Bases: :class:`PytestWarning`.\n\n Warning emitted by the cache plugin in various situations.\n ","endLoc":26,"id":2124,"nodeType":"Class","startLoc":21,"text":"class PytestCacheWarning(PytestWarning):\n \"\"\"\n Bases: :class:`PytestWarning`.\n\n Warning emitted by the cache plugin in various situations.\n \"\"\""},{"className":"PytestCollectionWarning","col":0,"comment":"\n Bases: :class:`PytestWarning`.\n\n Warning emitted when pytest is not able to collect a file or symbol in a module.\n ","endLoc":42,"id":2125,"nodeType":"Class","startLoc":37,"text":"class PytestCollectionWarning(PytestWarning):\n \"\"\"\n Bases: :class:`PytestWarning`.\n\n Warning emitted when pytest is not able to collect a file or symbol in a module.\n \"\"\""},{"className":"PytestConfigWarning","col":0,"comment":"\n Bases: :class:`PytestWarning`.\n\n Warning emitted for configuration issues.\n ","endLoc":34,"id":2126,"nodeType":"Class","startLoc":29,"text":"class PytestConfigWarning(PytestWarning):\n \"\"\"\n Bases: :class:`PytestWarning`.\n\n Warning emitted for configuration issues.\n \"\"\""},{"col":4,"comment":"null","endLoc":52,"header":"def test_mark_with_param(self)","id":2127,"name":"test_mark_with_param","nodeType":"Function","startLoc":41,"text":"def test_mark_with_param(self):\n def some_function(abc):\n pass\n\n class SomeClass(object):\n pass\n\n assert pytest.mark.foo(some_function) is some_function\n assert pytest.mark.foo.with_args(some_function) is not some_function\n\n assert pytest.mark.foo(SomeClass) is SomeClass\n assert pytest.mark.foo.with_args(SomeClass) is not SomeClass"},{"className":"PytestExperimentalApiWarning","col":0,"comment":"\n Bases: :class:`pytest.PytestWarning`, :class:`FutureWarning`.\n\n Warning category used to denote experiments in pytest. Use sparingly as the API might change or even be\n removed completely in future version\n ","endLoc":67,"id":2128,"nodeType":"Class","startLoc":53,"text":"class PytestExperimentalApiWarning(PytestWarning, FutureWarning):\n \"\"\"\n Bases: :class:`pytest.PytestWarning`, :class:`FutureWarning`.\n\n Warning category used to denote experiments in pytest. Use sparingly as the API might change or even be\n removed completely in future version\n \"\"\"\n\n @classmethod\n def simple(cls, apiname):\n return cls(\n \"{apiname} is an experimental api that may change over time\".format(\n apiname=apiname\n )\n )"},{"className":"FutureWarning","col":0,"comment":"null","endLoc":2072,"id":2129,"nodeType":"Class","startLoc":2072,"text":"class FutureWarning(Warning): ..."},{"col":4,"comment":"null","endLoc":67,"header":"@classmethod\n def simple(cls, apiname)","id":2130,"name":"simple","nodeType":"Function","startLoc":61,"text":"@classmethod\n def simple(cls, apiname):\n return cls(\n \"{apiname} is an experimental api that may change over time\".format(\n apiname=apiname\n )\n )"},{"col":4,"comment":"null","endLoc":57,"header":"def test_pytest_mark_name_starts_with_underscore(self)","id":2131,"name":"test_pytest_mark_name_starts_with_underscore","nodeType":"Function","startLoc":54,"text":"def test_pytest_mark_name_starts_with_underscore(self):\n mark = Mark()\n with pytest.raises(AttributeError):\n mark._some_name"},{"col":4,"comment":"null","endLoc":239,"header":"@pytest.mark.filterwarnings(\"always\")\n def test_plugin_skip(self, testdir, monkeypatch)","id":2132,"name":"test_plugin_skip","nodeType":"Function","startLoc":225,"text":"@pytest.mark.filterwarnings(\"always\")\n def test_plugin_skip(self, testdir, monkeypatch):\n p = testdir.makepyfile(\n skipping1=\"\"\"\n import pytest\n pytest.skip(\"hello\", allow_module_level=True)\n \"\"\"\n )\n p.copy(p.dirpath(\"skipping2.py\"))\n monkeypatch.setenv(\"PYTEST_PLUGINS\", \"skipping2\")\n result = testdir.runpytest(\"-rw\", \"-p\", \"skipping1\", syspathinsert=True)\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result.stdout.fnmatch_lines(\n [\"*skipped plugin*skipping1*hello*\", \"*skipped plugin*skipping2*hello*\"]\n )"},{"className":"TestFunctional","col":0,"comment":"null","endLoc":704,"id":2133,"nodeType":"Class","startLoc":438,"text":"class TestFunctional(object):\n def test_merging_markers_deep(self, testdir):\n # issue 199 - propagate markers into nested classes\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n class TestA(object):\n pytestmark = pytest.mark.a\n def test_b(self):\n assert True\n class TestC(object):\n # this one didnt get marked\n def test_d(self):\n assert True\n \"\"\"\n )\n items, rec = testdir.inline_genitems(p)\n for item in items:\n print(item, item.keywords)\n assert [x for x in item.iter_markers() if x.name == \"a\"]\n\n def test_mark_decorator_subclass_does_not_propagate_to_base(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.a\n class Base(object): pass\n\n @pytest.mark.b\n class Test1(Base):\n def test_foo(self): pass\n\n class Test2(Base):\n def test_bar(self): pass\n \"\"\"\n )\n items, rec = testdir.inline_genitems(p)\n self.assert_markers(items, test_foo=(\"a\", \"b\"), test_bar=(\"a\",))\n\n def test_mark_should_not_pass_to_siebling_class(self, testdir):\n \"\"\"#568\"\"\"\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n class TestBase(object):\n def test_foo(self):\n pass\n\n @pytest.mark.b\n class TestSub(TestBase):\n pass\n\n\n class TestOtherSub(TestBase):\n pass\n\n \"\"\"\n )\n items, rec = testdir.inline_genitems(p)\n base_item, sub_item, sub_item_other = items\n print(items, [x.nodeid for x in items])\n # new api seregates\n assert not list(base_item.iter_markers(name=\"b\"))\n assert not list(sub_item_other.iter_markers(name=\"b\"))\n assert list(sub_item.iter_markers(name=\"b\"))\n\n def test_mark_decorator_baseclasses_merged(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.a\n class Base(object): pass\n\n @pytest.mark.b\n class Base2(Base): pass\n\n @pytest.mark.c\n class Test1(Base2):\n def test_foo(self): pass\n\n class Test2(Base2):\n @pytest.mark.d\n def test_bar(self): pass\n \"\"\"\n )\n items, rec = testdir.inline_genitems(p)\n self.assert_markers(items, test_foo=(\"a\", \"b\", \"c\"), test_bar=(\"a\", \"b\", \"d\"))\n\n def test_mark_closest(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.c(location=\"class\")\n class Test:\n @pytest.mark.c(location=\"function\")\n def test_has_own():\n pass\n\n def test_has_inherited():\n pass\n\n \"\"\"\n )\n items, rec = testdir.inline_genitems(p)\n has_own, has_inherited = items\n assert has_own.get_closest_marker(\"c\").kwargs == {\"location\": \"function\"}\n assert has_inherited.get_closest_marker(\"c\").kwargs == {\"location\": \"class\"}\n assert has_own.get_closest_marker(\"missing\") is None\n\n def test_mark_with_wrong_marker(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n import pytest\n class pytestmark(object):\n pass\n def test_func():\n pass\n \"\"\"\n )\n values = reprec.getfailedcollections()\n assert len(values) == 1\n assert \"TypeError\" in str(values[0].longrepr)\n\n def test_mark_dynamically_in_funcarg(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture\n def arg(request):\n request.applymarker(pytest.mark.hello)\n def pytest_terminal_summary(terminalreporter):\n values = terminalreporter.stats['passed']\n terminalreporter._tw.line(\"keyword: %s\" % values[0].keywords)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_func(arg):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"keyword: *hello*\"])\n\n def test_no_marker_match_on_unmarked_names(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.shouldmatch\n def test_marked():\n assert 1\n\n def test_unmarked():\n assert 1\n \"\"\"\n )\n reprec = testdir.inline_run(\"-m\", \"test_unmarked\", p)\n passed, skipped, failed = reprec.listoutcomes()\n assert len(passed) + len(skipped) + len(failed) == 0\n dlist = reprec.getcalls(\"pytest_deselected\")\n deselected_tests = dlist[0].items\n assert len(deselected_tests) == 2\n\n def test_invalid_m_option(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_a():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-m bogus/\")\n result.stdout.fnmatch_lines(\n [\"INTERNALERROR> Marker expression must be valid Python!\"]\n )\n\n def test_keywords_at_node_level(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=\"session\", autouse=True)\n def some(request):\n request.keywords[\"hello\"] = 42\n assert \"world\" not in request.keywords\n\n @pytest.fixture(scope=\"function\", autouse=True)\n def funcsetup(request):\n assert \"world\" in request.keywords\n assert \"hello\" in request.keywords\n\n @pytest.mark.world\n def test_function():\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n @ignore_markinfo\n def test_keyword_added_for_session(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_collection_modifyitems(session):\n session.add_marker(\"mark1\")\n session.add_marker(pytest.mark.mark2)\n session.add_marker(pytest.mark.mark3)\n pytest.raises(ValueError, lambda:\n session.add_marker(10))\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_some(request):\n assert \"mark1\" in request.keywords\n assert \"mark2\" in request.keywords\n assert \"mark3\" in request.keywords\n assert 10 not in request.keywords\n marker = request.node.get_closest_marker(\"mark1\")\n assert marker.name == \"mark1\"\n assert marker.args == ()\n assert marker.kwargs == {}\n \"\"\"\n )\n reprec = testdir.inline_run(\"-m\", \"mark1\", SHOW_PYTEST_WARNINGS_ARG)\n reprec.assertoutcome(passed=1)\n\n def assert_markers(self, items, **expected):\n \"\"\"assert that given items have expected marker names applied to them.\n expected should be a dict of (item name -> seq of expected marker names)\n\n .. note:: this could be moved to ``testdir`` if proven to be useful\n to other modules.\n \"\"\"\n\n items = {x.name: x for x in items}\n for name, expected_markers in expected.items():\n markers = {m.name for m in items[name].iter_markers()}\n assert markers == set(expected_markers)\n\n @pytest.mark.filterwarnings(\"ignore\")\n def test_mark_from_parameters(self, testdir):\n \"\"\"#1540\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n pytestmark = pytest.mark.skipif(True, reason='skip all')\n\n # skipifs inside fixture params\n params = [pytest.mark.skipif(False, reason='dont skip')('parameter')]\n\n\n @pytest.fixture(params=params)\n def parameter(request):\n return request.param\n\n\n def test_1(parameter):\n assert True\n \"\"\"\n )\n reprec = testdir.inline_run(SHOW_PYTEST_WARNINGS_ARG)\n reprec.assertoutcome(skipped=1)"},{"col":4,"comment":"null","endLoc":457,"header":"def test_merging_markers_deep(self, testdir)","id":2134,"name":"test_merging_markers_deep","nodeType":"Function","startLoc":439,"text":"def test_merging_markers_deep(self, testdir):\n # issue 199 - propagate markers into nested classes\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n class TestA(object):\n pytestmark = pytest.mark.a\n def test_b(self):\n assert True\n class TestC(object):\n # this one didnt get marked\n def test_d(self):\n assert True\n \"\"\"\n )\n items, rec = testdir.inline_genitems(p)\n for item in items:\n print(item, item.keywords)\n assert [x for x in item.iter_markers() if x.name == \"a\"]"},{"col":4,"comment":"null","endLoc":252,"header":"def test_consider_env_plugin_instantiation(self, testdir, monkeypatch, pytestpm)","id":2135,"name":"test_consider_env_plugin_instantiation","nodeType":"Function","startLoc":241,"text":"def test_consider_env_plugin_instantiation(self, testdir, monkeypatch, pytestpm):\n testdir.syspathinsert()\n testdir.makepyfile(xy123=\"#\")\n monkeypatch.setitem(os.environ, \"PYTEST_PLUGINS\", \"xy123\")\n l1 = len(pytestpm.get_plugins())\n pytestpm.consider_env()\n l2 = len(pytestpm.get_plugins())\n assert l2 == l1 + 1\n assert pytestpm.get_plugin(\"xy123\")\n pytestpm.consider_env()\n l3 = len(pytestpm.get_plugins())\n assert l2 == l3"},{"col":0,"comment":"null","endLoc":153,"header":"def determine_setup(inifile, args, rootdir_cmd_arg=None, config=None)","id":2136,"name":"determine_setup","nodeType":"Function","startLoc":105,"text":"def determine_setup(inifile, args, rootdir_cmd_arg=None, config=None):\n dirs = get_dirs_from_args(args)\n if inifile:\n iniconfig = py.iniconfig.IniConfig(inifile)\n is_cfg_file = str(inifile).endswith(\".cfg\")\n sections = [\"tool:pytest\", \"pytest\"] if is_cfg_file else [\"pytest\"]\n for section in sections:\n try:\n inicfg = iniconfig[section]\n if is_cfg_file and section == \"pytest\" and config is not None:\n from _pytest.deprecated import CFG_PYTEST_SECTION\n\n fail(\n CFG_PYTEST_SECTION.format(filename=str(inifile)), pytrace=False\n )\n break\n except KeyError:\n inicfg = None\n if rootdir_cmd_arg is None:\n rootdir = get_common_ancestor(dirs)\n else:\n ancestor = get_common_ancestor(dirs)\n rootdir, inifile, inicfg = getcfg([ancestor], config=config)\n if rootdir is None and rootdir_cmd_arg is None:\n for possible_rootdir in ancestor.parts(reverse=True):\n if possible_rootdir.join(\"setup.py\").exists():\n rootdir = possible_rootdir\n break\n else:\n if dirs != [ancestor]:\n rootdir, inifile, inicfg = getcfg(dirs, config=config)\n if rootdir is None:\n if config is not None:\n cwd = config.invocation_dir\n else:\n cwd = py.path.local()\n rootdir = get_common_ancestor([cwd, ancestor])\n is_fs_root = os.path.splitdrive(str(rootdir))[1] == \"/\"\n if is_fs_root:\n rootdir = ancestor\n if rootdir_cmd_arg:\n rootdir = py.path.local(os.path.expandvars(rootdir_cmd_arg))\n if not rootdir.isdir():\n raise UsageError(\n \"Directory '{}' not found. Check your '--rootdir' option.\".format(\n rootdir\n )\n )\n return rootdir, inifile, inicfg or {}"},{"col":4,"comment":"Test override of the autouse fixture with parametrized one on the conftest level.\n This test covers the issue explained in issue 1601\n ","endLoc":358,"header":"def test_override_autouse_fixture_with_parametrized_fixture_conftest_conftest(\n self, testdir\n )","id":2138,"name":"test_override_autouse_fixture_with_parametrized_fixture_conftest_conftest","nodeType":"Function","startLoc":316,"text":"def test_override_autouse_fixture_with_parametrized_fixture_conftest_conftest(\n self, testdir\n ):\n \"\"\"Test override of the autouse fixture with parametrized one on the conftest level.\n This test covers the issue explained in issue 1601\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(autouse=True)\n def spam():\n return 'spam'\n \"\"\"\n )\n subdir = testdir.mkpydir(\"subdir\")\n subdir.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n\n @pytest.fixture(params=[1, 2, 3])\n def spam(request):\n return request.param\n \"\"\"\n )\n )\n testfile = subdir.join(\"test_spam.py\")\n testfile.write(\n textwrap.dedent(\n \"\"\"\\\n params = {'spam': 1}\n\n def test_spam(spam):\n assert spam == params['spam']\n params['spam'] += 1\n \"\"\"\n )\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n result = testdir.runpytest(testfile)\n result.stdout.fnmatch_lines([\"*3 passed*\"])"},{"col":4,"comment":"null","endLoc":382,"header":"def test_autouse_fixture_plugin(self, testdir)","id":2139,"name":"test_autouse_fixture_plugin","nodeType":"Function","startLoc":360,"text":"def test_autouse_fixture_plugin(self, testdir):\n # A fixture from a plugin has no baseid set, which screwed up\n # the autouse fixture handling.\n testdir.makepyfile(\n testplugin=\"\"\"\n import pytest\n\n @pytest.fixture(autouse=True)\n def foo(request):\n request.function.foo = 7\n \"\"\"\n )\n testdir.syspathinsert()\n testdir.makepyfile(\n \"\"\"\n pytest_plugins = 'testplugin'\n\n def test_foo(request):\n assert request.function.foo == 7\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0"},{"col":4,"comment":"null","endLoc":419,"header":"def test_funcarg_lookup_error(self, testdir)","id":2140,"name":"test_funcarg_lookup_error","nodeType":"Function","startLoc":384,"text":"def test_funcarg_lookup_error(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def a_fixture(): pass\n\n @pytest.fixture\n def b_fixture(): pass\n\n @pytest.fixture\n def c_fixture(): pass\n\n @pytest.fixture\n def d_fixture(): pass\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_lookup_error(unknown):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*ERROR at setup of test_lookup_error*\",\n \" def test_lookup_error(unknown):*\",\n \"E fixture 'unknown' not found\",\n \"> available fixtures:*a_fixture,*b_fixture,*c_fixture,*d_fixture*monkeypatch,*\", # sorted\n \"> use 'py*test --fixtures *' for help on them.\",\n \"*1 error*\",\n ]\n )\n assert \"INTERNAL\" not in result.stdout.str()"},{"className":"PytestUnhandledCoroutineWarning","col":0,"comment":"\n Bases: :class:`PytestWarning`.\n\n Warning emitted when pytest encounters a test function which is a coroutine,\n but it was not handled by any async-aware plugin. Coroutine test functions\n are not natively supported.\n ","endLoc":77,"id":2141,"nodeType":"Class","startLoc":70,"text":"class PytestUnhandledCoroutineWarning(PytestWarning):\n \"\"\"\n Bases: :class:`PytestWarning`.\n\n Warning emitted when pytest encounters a test function which is a coroutine,\n but it was not handled by any async-aware plugin. Coroutine test functions\n are not natively supported.\n \"\"\""},{"className":"PytestUnknownMarkWarning","col":0,"comment":"\n Bases: :class:`PytestWarning`.\n\n Warning emitted on use of unknown markers.\n See https://docs.pytest.org/en/latest/mark.html for details.\n ","endLoc":86,"id":2142,"nodeType":"Class","startLoc":80,"text":"class PytestUnknownMarkWarning(PytestWarning):\n \"\"\"\n Bases: :class:`PytestWarning`.\n\n Warning emitted on use of unknown markers.\n See https://docs.pytest.org/en/latest/mark.html for details.\n \"\"\""},{"attributeType":"function","col":0,"comment":"null","endLoc":50,"id":2143,"name":"set_trace","nodeType":"Attribute","startLoc":50,"text":"set_trace"},{"col":4,"comment":"null","endLoc":443,"header":"def test_fixture_excinfo_leak(self, testdir)","id":2144,"name":"test_fixture_excinfo_leak","nodeType":"Function","startLoc":421,"text":"def test_fixture_excinfo_leak(self, testdir):\n # on python2 sys.excinfo would leak into fixture executions\n testdir.makepyfile(\n \"\"\"\n import sys\n import traceback\n import pytest\n\n @pytest.fixture\n def leak():\n if sys.exc_info()[0]: # python3 bug :)\n traceback.print_exc()\n #fails\n assert sys.exc_info() == (None, None, None)\n\n def test_leak(leak):\n if sys.exc_info()[0]: # python3 bug :)\n traceback.print_exc()\n assert sys.exc_info() == (None, None, None)\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0"},{"className":"TestRequestBasic","col":0,"comment":"null","endLoc":902,"id":2147,"nodeType":"Class","startLoc":446,"text":"class TestRequestBasic(object):\n def test_request_attributes(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def something(request): pass\n def test_func(something): pass\n \"\"\"\n )\n req = fixtures.FixtureRequest(item)\n assert req.function == item.obj\n assert req.keywords == item.keywords\n assert hasattr(req.module, \"test_func\")\n assert req.cls is None\n assert req.function.__name__ == \"test_func\"\n assert req.config == item.config\n assert repr(req).find(req.function.__name__) != -1\n\n def test_request_attributes_method(self, testdir):\n item, = testdir.getitems(\n \"\"\"\n import pytest\n class TestB(object):\n\n @pytest.fixture\n def something(self, request):\n return 1\n def test_func(self, something):\n pass\n \"\"\"\n )\n req = item._request\n assert req.cls.__name__ == \"TestB\"\n assert req.instance.__class__ == req.cls\n\n def test_request_contains_funcarg_arg2fixturedefs(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n import pytest\n @pytest.fixture\n def something(request):\n pass\n class TestClass(object):\n def test_method(self, something):\n pass\n \"\"\"\n )\n item1, = testdir.genitems([modcol])\n assert item1.name == \"test_method\"\n arg2fixturedefs = fixtures.FixtureRequest(item1)._arg2fixturedefs\n assert len(arg2fixturedefs) == 1\n assert arg2fixturedefs[\"something\"][0].argname == \"something\"\n\n @pytest.mark.skipif(\n hasattr(sys, \"pypy_version_info\"),\n reason=\"this method of test doesn't work on pypy\",\n )\n def test_request_garbage(self, testdir):\n try:\n import xdist # noqa\n except ImportError:\n pass\n else:\n pytest.xfail(\"this test is flaky when executed with xdist\")\n testdir.makepyfile(\n \"\"\"\n import sys\n import pytest\n from _pytest.fixtures import PseudoFixtureDef\n import gc\n\n @pytest.fixture(autouse=True)\n def something(request):\n original = gc.get_debug()\n gc.set_debug(gc.DEBUG_SAVEALL)\n gc.collect()\n\n yield\n\n try:\n gc.collect()\n leaked = [x for _ in gc.garbage if isinstance(_, PseudoFixtureDef)]\n assert leaked == []\n finally:\n gc.set_debug(original)\n\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"* 1 passed in *\"])\n\n def test_getfixturevalue_recursive(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def something(request):\n return 1\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def something(request):\n return request.getfixturevalue(\"something\") + 1\n def test_func(something):\n assert something == 2\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_getfixturevalue_teardown(self, testdir):\n \"\"\"\n Issue #1895\n\n `test_inner` requests `inner` fixture, which in turn requests `resource`\n using `getfixturevalue`. `test_func` then requests `resource`.\n\n `resource` is teardown before `inner` because the fixture mechanism won't consider\n `inner` dependent on `resource` when it is used via `getfixturevalue`: `test_func`\n will then cause the `resource`'s finalizer to be called first because of this.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='session')\n def resource():\n r = ['value']\n yield r\n r.pop()\n\n @pytest.fixture(scope='session')\n def inner(request):\n resource = request.getfixturevalue('resource')\n assert resource == ['value']\n yield\n assert resource == ['value']\n\n def test_inner(inner):\n pass\n\n def test_func(resource):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed in *\"])\n\n @pytest.mark.parametrize(\"getfixmethod\", (\"getfixturevalue\", \"getfuncargvalue\"))\n def test_getfixturevalue(self, testdir, getfixmethod):\n item = testdir.getitem(\n \"\"\"\n import pytest\n values = [2]\n @pytest.fixture\n def something(request): return 1\n @pytest.fixture\n def other(request):\n return values.pop()\n def test_func(something): pass\n \"\"\"\n )\n import contextlib\n\n if getfixmethod == \"getfuncargvalue\":\n warning_expectation = pytest.warns(DeprecationWarning)\n else:\n # see #1830 for a cleaner way to accomplish this\n @contextlib.contextmanager\n def expecting_no_warning():\n yield\n\n warning_expectation = expecting_no_warning()\n\n req = item._request\n with warning_expectation:\n fixture_fetcher = getattr(req, getfixmethod)\n with pytest.raises(FixtureLookupError):\n fixture_fetcher(\"notexists\")\n val = fixture_fetcher(\"something\")\n assert val == 1\n val = fixture_fetcher(\"something\")\n assert val == 1\n val2 = fixture_fetcher(\"other\")\n assert val2 == 2\n val2 = fixture_fetcher(\"other\") # see about caching\n assert val2 == 2\n pytest._fillfuncargs(item)\n assert item.funcargs[\"something\"] == 1\n assert len(get_public_names(item.funcargs)) == 2\n assert \"request\" in item.funcargs\n\n def test_request_addfinalizer(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n teardownlist = []\n @pytest.fixture\n def something(request):\n request.addfinalizer(lambda: teardownlist.append(1))\n def test_func(something): pass\n \"\"\"\n )\n item.session._setupstate.prepare(item)\n pytest._fillfuncargs(item)\n # successively check finalization calls\n teardownlist = item.getparent(pytest.Module).obj.teardownlist\n ss = item.session._setupstate\n assert not teardownlist\n ss.teardown_exact(item, None)\n print(ss.stack)\n assert teardownlist == [1]\n\n def test_request_addfinalizer_failing_setup(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = [1]\n @pytest.fixture\n def myfix(request):\n request.addfinalizer(values.pop)\n assert 0\n def test_fix(myfix):\n pass\n def test_finalizer_ran():\n assert not values\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(failed=1, passed=1)\n\n def test_request_addfinalizer_failing_setup_module(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = [1, 2]\n @pytest.fixture(scope=\"module\")\n def myfix(request):\n request.addfinalizer(values.pop)\n request.addfinalizer(values.pop)\n assert 0\n def test_fix(myfix):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n mod = reprec.getcalls(\"pytest_runtest_setup\")[0].item.module\n assert not mod.values\n\n def test_request_addfinalizer_partial_setup_failure(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture\n def something(request):\n request.addfinalizer(lambda: values.append(None))\n def test_func(something, missingarg):\n pass\n def test_second():\n assert len(values) == 1\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\"*1 error*\"] # XXX the whole module collection fails\n )\n\n def test_request_subrequest_addfinalizer_exceptions(self, testdir):\n \"\"\"\n Ensure exceptions raised during teardown by a finalizer are suppressed\n until all finalizers are called, re-raising the first exception (#2440)\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n def _excepts(where):\n raise Exception('Error in %s fixture' % where)\n @pytest.fixture\n def subrequest(request):\n return request\n @pytest.fixture\n def something(subrequest):\n subrequest.addfinalizer(lambda: values.append(1))\n subrequest.addfinalizer(lambda: values.append(2))\n subrequest.addfinalizer(lambda: _excepts('something'))\n @pytest.fixture\n def excepts(subrequest):\n subrequest.addfinalizer(lambda: _excepts('excepts'))\n subrequest.addfinalizer(lambda: values.append(3))\n def test_first(something, excepts):\n pass\n def test_second():\n assert values == [3, 2, 1]\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"*Exception: Error in excepts fixture\", \"* 2 passed, 1 error in *\"]\n )\n\n def test_request_getmodulepath(self, testdir):\n modcol = testdir.getmodulecol(\"def test_somefunc(): pass\")\n item, = testdir.genitems([modcol])\n req = fixtures.FixtureRequest(item)\n assert req.fspath == modcol.fspath\n\n def test_request_fixturenames(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n from _pytest.pytester import get_public_names\n @pytest.fixture()\n def arg1():\n pass\n @pytest.fixture()\n def farg(arg1):\n pass\n @pytest.fixture(autouse=True)\n def sarg(tmpdir):\n pass\n def test_function(request, farg):\n assert set(get_public_names(request.fixturenames)) == \\\n set([\"tmpdir\", \"sarg\", \"arg1\", \"request\", \"farg\",\n \"tmp_path\", \"tmp_path_factory\"])\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_request_fixturenames_dynamic_fixture(self, testdir):\n \"\"\"Regression test for #3057\"\"\"\n testdir.copy_example(\"fixtures/test_getfixturevalue_dynamic.py\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_funcargnames_compatattr(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n assert metafunc.funcargnames == metafunc.fixturenames\n @pytest.fixture\n def fn(request):\n assert request._pyfuncitem.funcargnames == \\\n request._pyfuncitem.fixturenames\n return request.funcargnames, request.fixturenames\n\n def test_hello(fn):\n assert fn[0] == fn[1]\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_setupdecorator_and_xunit(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(scope='module', autouse=True)\n def setup_module():\n values.append(\"module\")\n @pytest.fixture(autouse=True)\n def setup_function():\n values.append(\"function\")\n\n def test_func():\n pass\n\n class TestClass(object):\n @pytest.fixture(scope=\"class\", autouse=True)\n def setup_class(self):\n values.append(\"class\")\n @pytest.fixture(autouse=True)\n def setup_method(self):\n values.append(\"method\")\n def test_method(self):\n pass\n def test_all():\n assert values == [\"module\", \"function\", \"class\",\n \"function\", \"method\", \"function\"]\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\")\n reprec.assertoutcome(passed=3)\n\n def test_fixtures_sub_subdir_normalize_sep(self, testdir):\n # this tests that normalization of nodeids takes place\n b = testdir.mkdir(\"tests\").mkdir(\"unit\")\n b.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def arg1():\n pass\n \"\"\"\n )\n )\n p = b.join(\"test_module.py\")\n p.write(\"def test_func(arg1): pass\")\n result = testdir.runpytest(p, \"--fixtures\")\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n \"\"\"\n *fixtures defined*conftest*\n *arg1*\n \"\"\"\n )\n\n def test_show_fixtures_color_yes(self, testdir):\n testdir.makepyfile(\"def test_this(): assert 1\")\n result = testdir.runpytest(\"--color=yes\", \"--fixtures\")\n assert \"\\x1b[32mtmpdir\" in result.stdout.str()\n\n def test_newstyle_with_request(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture()\n def arg(request):\n pass\n def test_1(arg):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_setupcontext_no_param(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(params=[1,2])\n def arg(request):\n return request.param\n\n @pytest.fixture(autouse=True)\n def mysetup(request, arg):\n assert not hasattr(request, \"param\")\n def test_1(arg):\n assert arg in (1,2)\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)"},{"col":4,"comment":"null","endLoc":464,"header":"def test_request_attributes(self, testdir)","id":2148,"name":"test_request_attributes","nodeType":"Function","startLoc":447,"text":"def test_request_attributes(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def something(request): pass\n def test_func(something): pass\n \"\"\"\n )\n req = fixtures.FixtureRequest(item)\n assert req.function == item.obj\n assert req.keywords == item.keywords\n assert hasattr(req.module, \"test_func\")\n assert req.cls is None\n assert req.function.__name__ == \"test_func\"\n assert req.config == item.config\n assert repr(req).find(req.function.__name__) != -1"},{"attributeType":"null","col":0,"comment":"null","endLoc":52,"id":2149,"name":"__all__","nodeType":"Attribute","startLoc":52,"text":"__all__"},{"col":0,"comment":"","endLoc":5,"header":"pytest.py#","id":2150,"name":"","nodeType":"Function","startLoc":3,"text":"\"\"\"\npytest: unit and functional testing with Python.\n\"\"\"\n\nset_trace = __pytestPDB.set_trace\n\n__all__ = [\n \"__version__\",\n \"_fillfuncargs\",\n \"approx\",\n \"Class\",\n \"cmdline\",\n \"Collector\",\n \"deprecated_call\",\n \"exit\",\n \"fail\",\n \"File\",\n \"fixture\",\n \"freeze_includes\",\n \"Function\",\n \"hookimpl\",\n \"hookspec\",\n \"importorskip\",\n \"Instance\",\n \"Item\",\n \"main\",\n \"mark\",\n \"Module\",\n \"Package\",\n \"param\",\n \"PytestAssertRewriteWarning\",\n \"PytestCacheWarning\",\n \"PytestCollectionWarning\",\n \"PytestConfigWarning\",\n \"PytestDeprecationWarning\",\n \"PytestExperimentalApiWarning\",\n \"PytestUnhandledCoroutineWarning\",\n \"PytestUnknownMarkWarning\",\n \"PytestWarning\",\n \"raises\",\n \"register_assert_rewrite\",\n \"RemovedInPytest4Warning\",\n \"Session\",\n \"set_trace\",\n \"skip\",\n \"UsageError\",\n \"warns\",\n \"xfail\",\n \"yield_fixture\",\n]\n\nif __name__ == \"__main__\":\n # if run as a script or by 'python -m pytest'\n # we trigger the below \"else\" condition by the following import\n import pytest\n\n raise SystemExit(pytest.main())\nelse:\n\n from _pytest.compat import _setup_collect_fakemodule\n\n _setup_collect_fakemodule()"},{"col":4,"comment":"null","endLoc":267,"header":"def test_pluginmanager_ENV_startup(self, testdir, monkeypatch)","id":2153,"name":"test_pluginmanager_ENV_startup","nodeType":"Function","startLoc":254,"text":"def test_pluginmanager_ENV_startup(self, testdir, monkeypatch):\n testdir.makepyfile(pytest_x500=\"#\")\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_hello(pytestconfig):\n plugin = pytestconfig.pluginmanager.get_plugin('pytest_x500')\n assert plugin is not None\n \"\"\"\n )\n monkeypatch.setenv(\"PYTEST_PLUGINS\", \"pytest_x500\", prepend=\",\")\n result = testdir.runpytest(p, syspathinsert=True)\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":4,"comment":"null","endLoc":229,"header":"def runtest(self)","id":2154,"name":"runtest","nodeType":"Function","startLoc":222,"text":"def runtest(self):\n if self.config.pluginmanager.get_plugin(\"pdbinvoke\") is None:\n self._testcase(result=self)\n else:\n # disables tearDown and cleanups for post mortem debugging (see #1890)\n if self._handle_skip():\n return\n self._testcase.debug()"},{"col":0,"comment":"Handles known read-only errors during rmtree.","endLoc":88,"header":"def on_rm_rf_error(func, path, exc, **kwargs)","id":2155,"name":"on_rm_rf_error","nodeType":"Function","startLoc":50,"text":"def on_rm_rf_error(func, path, exc, **kwargs):\n \"\"\"Handles known read-only errors during rmtree.\"\"\"\n start_path = kwargs[\"start_path\"]\n excvalue = exc[1]\n\n if not isinstance(excvalue, OSError) or excvalue.errno not in (\n errno.EACCES,\n errno.EPERM,\n ):\n warnings.warn(\n PytestWarning(\"(rm_rf) error removing {}: {}\".format(path, excvalue))\n )\n return\n\n if func not in (os.rmdir, os.remove, os.unlink):\n warnings.warn(\n PytestWarning(\"(rm_rf) error removing {}: {}\".format(path, excvalue))\n )\n return\n\n # Chmod + retry.\n import stat\n\n def chmod_rw(p):\n mode = os.stat(p).st_mode\n os.chmod(p, mode | stat.S_IRUSR | stat.S_IWUSR)\n\n # For files, we need to recursively go upwards in the directories to\n # ensure they all are also writable.\n p = Path(path)\n if p.is_file():\n for parent in p.parents:\n chmod_rw(str(parent))\n # stop when we reach the original path passed to rm_rf\n if parent == start_path:\n break\n chmod_rw(str(path))\n\n func(path)"},{"col":4,"comment":"null","endLoc":284,"header":"def test_import_plugin_importname(self, testdir, pytestpm)","id":2156,"name":"test_import_plugin_importname","nodeType":"Function","startLoc":269,"text":"def test_import_plugin_importname(self, testdir, pytestpm):\n pytest.raises(ImportError, pytestpm.import_plugin, \"qweqwex.y\")\n pytest.raises(ImportError, pytestpm.import_plugin, \"pytest_qweqwx.y\")\n\n testdir.syspathinsert()\n pluginname = \"pytest_hello\"\n testdir.makepyfile(**{pluginname: \"\"})\n pytestpm.import_plugin(\"pytest_hello\")\n len1 = len(pytestpm.get_plugins())\n pytestpm.import_plugin(\"pytest_hello\")\n len2 = len(pytestpm.get_plugins())\n assert len1 == len2\n plugin1 = pytestpm.get_plugin(\"pytest_hello\")\n assert plugin1.__name__.endswith(\"pytest_hello\")\n plugin2 = pytestpm.get_plugin(\"pytest_hello\")\n assert plugin2 is plugin1"},{"col":4,"comment":"null","endLoc":237,"header":"def _prunetraceback(self, excinfo)","id":2157,"name":"_prunetraceback","nodeType":"Function","startLoc":231,"text":"def _prunetraceback(self, excinfo):\n Function._prunetraceback(self, excinfo)\n traceback = excinfo.traceback.filter(\n lambda x: not x.frame.f_globals.get(\"__unittest\")\n )\n if traceback:\n excinfo.traceback = traceback"},{"col":0,"comment":"null","endLoc":410,"header":"def _setup_collect_fakemodule()","id":2158,"name":"_setup_collect_fakemodule","nodeType":"Function","startLoc":403,"text":"def _setup_collect_fakemodule():\n from types import ModuleType\n import pytest\n\n pytest.collect = ModuleType(\"pytest.collect\")\n pytest.collect.__all__ = [] # used for setns\n for attr in COLLECT_FAKEMODULE_ATTRIBUTES:\n setattr(pytest.collect, attr, getattr(pytest, attr))"},{"col":4,"comment":"null","endLoc":269,"header":"def pytest_internalerror(self, excrepr, excinfo)","id":2159,"name":"pytest_internalerror","nodeType":"Function","startLoc":267,"text":"def pytest_internalerror(self, excrepr, excinfo):\n tb = _postmortem_traceback(excinfo)\n post_mortem(tb)"},{"className":"PdbTrace","col":0,"comment":"null","endLoc":276,"id":2160,"nodeType":"Class","startLoc":272,"text":"class PdbTrace(object):\n @hookimpl(hookwrapper=True)\n def pytest_pyfunc_call(self, pyfuncitem):\n _test_pytest_function(pyfuncitem)\n yield"},{"col":0,"comment":"null","endLoc":288,"header":"def _test_pytest_function(pyfuncitem)","id":2162,"name":"_test_pytest_function","nodeType":"Function","startLoc":279,"text":"def _test_pytest_function(pyfuncitem):\n _pdb = pytestPDB._init_pdb(\"runcall\")\n testfunction = pyfuncitem.obj\n pyfuncitem.obj = _pdb.runcall\n if \"func\" in pyfuncitem._fixtureinfo.argnames: # pragma: no branch\n raise ValueError(\"--trace can't be used with a fixture named func!\")\n pyfuncitem.funcargs[\"func\"] = testfunction\n new_list = list(pyfuncitem._fixtureinfo.argnames)\n new_list.append(\"func\")\n pyfuncitem._fixtureinfo.argnames = tuple(new_list)"},{"col":4,"comment":"null","endLoc":295,"header":"def test_import_plugin_dotted_name(self, testdir, pytestpm)","id":2163,"name":"test_import_plugin_dotted_name","nodeType":"Function","startLoc":286,"text":"def test_import_plugin_dotted_name(self, testdir, pytestpm):\n pytest.raises(ImportError, pytestpm.import_plugin, \"qweqwex.y\")\n pytest.raises(ImportError, pytestpm.import_plugin, \"pytest_qweqwex.y\")\n\n testdir.syspathinsert()\n testdir.mkpydir(\"pkg\").join(\"plug.py\").write(\"x=3\")\n pluginname = \"pkg.plug\"\n pytestpm.import_plugin(pluginname)\n mod = pytestpm.get_plugin(\"pkg.plug\")\n assert mod.x == 3"},{"col":12,"endLoc":234,"id":2164,"nodeType":"Lambda","startLoc":234,"text":"lambda x: not x.frame.f_globals.get(\"__unittest\")"},{"col":4,"comment":"null","endLoc":481,"header":"def test_request_attributes_method(self, testdir)","id":2166,"name":"test_request_attributes_method","nodeType":"Function","startLoc":466,"text":"def test_request_attributes_method(self, testdir):\n item, = testdir.getitems(\n \"\"\"\n import pytest\n class TestB(object):\n\n @pytest.fixture\n def something(self, request):\n return 1\n def test_func(self, something):\n pass\n \"\"\"\n )\n req = item._request\n assert req.cls.__name__ == \"TestB\"\n assert req.instance.__class__ == req.cls"},{"attributeType":"bool","col":4,"comment":"null","endLoc":110,"id":2167,"name":"nofuncargs","nodeType":"Attribute","startLoc":110,"text":"nofuncargs"},{"attributeType":"None","col":4,"comment":"null","endLoc":111,"id":2168,"name":"_excinfo","nodeType":"Attribute","startLoc":111,"text":"_excinfo"},{"col":4,"comment":"null","endLoc":300,"header":"def test_consider_conftest_deps(self, testdir, pytestpm)","id":2169,"name":"test_consider_conftest_deps","nodeType":"Function","startLoc":297,"text":"def test_consider_conftest_deps(self, testdir, pytestpm):\n mod = testdir.makepyfile(\"pytest_plugins='xyz'\").pyimport()\n with pytest.raises(ImportError):\n pytestpm.consider_conftest(mod)"},{"attributeType":"None","col":4,"comment":"null","endLoc":112,"id":2170,"name":"_testcase","nodeType":"Attribute","startLoc":112,"text":"_testcase"},{"attributeType":"null","col":8,"comment":"null","endLoc":115,"id":2171,"name":"_testcase","nodeType":"Attribute","startLoc":115,"text":"self._testcase"},{"attributeType":"null","col":8,"comment":"null","endLoc":117,"id":2172,"name":"_obj","nodeType":"Attribute","startLoc":117,"text":"self._obj"},{"className":"TestPytestPluginManagerBootstrapming","col":0,"comment":"null","endLoc":360,"id":2173,"nodeType":"Class","startLoc":303,"text":"class TestPytestPluginManagerBootstrapming(object):\n def test_preparse_args(self, pytestpm):\n pytest.raises(\n ImportError, lambda: pytestpm.consider_preparse([\"xyz\", \"-p\", \"hello123\"])\n )\n\n # Handles -p without space (#3532).\n with pytest.raises(ImportError) as excinfo:\n pytestpm.consider_preparse([\"-phello123\"])\n assert '\"hello123\"' in excinfo.value.args[0]\n pytestpm.consider_preparse([\"-pno:hello123\"])\n\n # Handles -p without following arg (when used without argparse).\n pytestpm.consider_preparse([\"-p\"])\n\n with pytest.raises(UsageError, match=\"^plugin main cannot be disabled$\"):\n pytestpm.consider_preparse([\"-p\", \"no:main\"])\n\n def test_plugin_prevent_register(self, pytestpm):\n pytestpm.consider_preparse([\"xyz\", \"-p\", \"no:abc\"])\n l1 = pytestpm.get_plugins()\n pytestpm.register(42, name=\"abc\")\n l2 = pytestpm.get_plugins()\n assert len(l2) == len(l1)\n assert 42 not in l2\n\n def test_plugin_prevent_register_unregistered_alredy_registered(self, pytestpm):\n pytestpm.register(42, name=\"abc\")\n l1 = pytestpm.get_plugins()\n assert 42 in l1\n pytestpm.consider_preparse([\"xyz\", \"-p\", \"no:abc\"])\n l2 = pytestpm.get_plugins()\n assert 42 not in l2\n\n def test_plugin_prevent_register_stepwise_on_cacheprovider_unregister(\n self, pytestpm\n ):\n \"\"\" From PR #4304 : The only way to unregister a module is documented at\n the end of https://docs.pytest.org/en/latest/plugins.html.\n\n When unregister cacheprovider, then unregister stepwise too\n \"\"\"\n pytestpm.register(42, name=\"cacheprovider\")\n pytestpm.register(43, name=\"stepwise\")\n l1 = pytestpm.get_plugins()\n assert 42 in l1\n assert 43 in l1\n pytestpm.consider_preparse([\"xyz\", \"-p\", \"no:cacheprovider\"])\n l2 = pytestpm.get_plugins()\n assert 42 not in l2\n assert 43 not in l2\n\n def test_blocked_plugin_can_be_used(self, pytestpm):\n pytestpm.consider_preparse([\"xyz\", \"-p\", \"no:abc\", \"-p\", \"abc\"])\n\n assert pytestpm.has_plugin(\"abc\")\n assert not pytestpm.is_blocked(\"abc\")\n assert not pytestpm.is_blocked(\"pytest_abc\")"},{"col":4,"comment":"null","endLoc":319,"header":"def test_preparse_args(self, pytestpm)","id":2174,"name":"test_preparse_args","nodeType":"Function","startLoc":304,"text":"def test_preparse_args(self, pytestpm):\n pytest.raises(\n ImportError, lambda: pytestpm.consider_preparse([\"xyz\", \"-p\", \"hello123\"])\n )\n\n # Handles -p without space (#3532).\n with pytest.raises(ImportError) as excinfo:\n pytestpm.consider_preparse([\"-phello123\"])\n assert '\"hello123\"' in excinfo.value.args[0]\n pytestpm.consider_preparse([\"-pno:hello123\"])\n\n # Handles -p without following arg (when used without argparse).\n pytestpm.consider_preparse([\"-p\"])\n\n with pytest.raises(UsageError, match=\"^plugin main cannot be disabled$\"):\n pytestpm.consider_preparse([\"-p\", \"no:main\"])"},{"col":4,"comment":"null","endLoc":499,"header":"def test_request_contains_funcarg_arg2fixturedefs(self, testdir)","id":2175,"name":"test_request_contains_funcarg_arg2fixturedefs","nodeType":"Function","startLoc":483,"text":"def test_request_contains_funcarg_arg2fixturedefs(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n import pytest\n @pytest.fixture\n def something(request):\n pass\n class TestClass(object):\n def test_method(self, something):\n pass\n \"\"\"\n )\n item1, = testdir.genitems([modcol])\n assert item1.name == \"test_method\"\n arg2fixturedefs = fixtures.FixtureRequest(item1)._arg2fixturedefs\n assert len(arg2fixturedefs) == 1\n assert arg2fixturedefs[\"something\"][0].argname == \"something\""},{"fileName":"test_pytester.py","filePath":"testing","id":2176,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport subprocess\nimport sys\nimport time\n\nimport py.path\n\nimport _pytest.pytester as pytester\nimport pytest\nfrom _pytest.config import PytestPluginManager\nfrom _pytest.main import EXIT_NOTESTSCOLLECTED\nfrom _pytest.main import EXIT_OK\nfrom _pytest.main import EXIT_TESTSFAILED\nfrom _pytest.pytester import CwdSnapshot\nfrom _pytest.pytester import HookRecorder\nfrom _pytest.pytester import LineMatcher\nfrom _pytest.pytester import SysModulesSnapshot\nfrom _pytest.pytester import SysPathsSnapshot\n\n\ndef test_make_hook_recorder(testdir):\n item = testdir.getitem(\"def test_func(): pass\")\n recorder = testdir.make_hook_recorder(item.config.pluginmanager)\n assert not recorder.getfailures()\n\n pytest.xfail(\"internal reportrecorder tests need refactoring\")\n\n class rep(object):\n excinfo = None\n passed = False\n failed = True\n skipped = False\n when = \"call\"\n\n recorder.hook.pytest_runtest_logreport(report=rep)\n failures = recorder.getfailures()\n assert failures == [rep]\n failures = recorder.getfailures()\n assert failures == [rep]\n\n class rep(object):\n excinfo = None\n passed = False\n failed = False\n skipped = True\n when = \"call\"\n\n rep.passed = False\n rep.skipped = True\n recorder.hook.pytest_runtest_logreport(report=rep)\n\n modcol = testdir.getmodulecol(\"\")\n rep = modcol.config.hook.pytest_make_collect_report(collector=modcol)\n rep.passed = False\n rep.failed = True\n rep.skipped = False\n recorder.hook.pytest_collectreport(report=rep)\n\n passed, skipped, failed = recorder.listoutcomes()\n assert not passed and skipped and failed\n\n numpassed, numskipped, numfailed = recorder.countoutcomes()\n assert numpassed == 0\n assert numskipped == 1\n assert numfailed == 1\n assert len(recorder.getfailedcollections()) == 1\n\n recorder.unregister()\n recorder.clear()\n recorder.hook.pytest_runtest_logreport(report=rep)\n pytest.raises(ValueError, recorder.getfailures)\n\n\ndef test_parseconfig(testdir):\n config1 = testdir.parseconfig()\n config2 = testdir.parseconfig()\n assert config2 != config1\n assert config1 != pytest.config\n\n\ndef test_testdir_runs_with_plugin(testdir):\n testdir.makepyfile(\n \"\"\"\n pytest_plugins = \"pytester\"\n def test_hello(testdir):\n assert 1\n \"\"\"\n )\n result = testdir.runpytest()\n result.assert_outcomes(passed=1)\n\n\ndef test_runresult_assertion_on_xfail(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n pytest_plugins = \"pytester\"\n\n @pytest.mark.xfail\n def test_potato():\n assert False\n \"\"\"\n )\n result = testdir.runpytest()\n result.assert_outcomes(xfailed=1)\n assert result.ret == 0\n\n\ndef test_runresult_assertion_on_xpassed(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n pytest_plugins = \"pytester\"\n\n @pytest.mark.xfail\n def test_potato():\n assert True\n \"\"\"\n )\n result = testdir.runpytest()\n result.assert_outcomes(xpassed=1)\n assert result.ret == 0\n\n\ndef test_runresult_repr():\n from _pytest.pytester import RunResult\n\n assert (\n repr(\n RunResult(ret=\"ret\", outlines=[\"\"], errlines=[\"some\", \"errors\"], duration=1)\n )\n == \"\"\n )\n\n\ndef test_xpassed_with_strict_is_considered_a_failure(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n pytest_plugins = \"pytester\"\n\n @pytest.mark.xfail(strict=True)\n def test_potato():\n assert True\n \"\"\"\n )\n result = testdir.runpytest()\n result.assert_outcomes(failed=1)\n assert result.ret != 0\n\n\ndef make_holder():\n class apiclass(object):\n def pytest_xyz(self, arg):\n \"x\"\n\n def pytest_xyz_noarg(self):\n \"x\"\n\n apimod = type(os)(\"api\")\n\n def pytest_xyz(arg):\n \"x\"\n\n def pytest_xyz_noarg():\n \"x\"\n\n apimod.pytest_xyz = pytest_xyz\n apimod.pytest_xyz_noarg = pytest_xyz_noarg\n return apiclass, apimod\n\n\n@pytest.mark.parametrize(\"holder\", make_holder())\ndef test_hookrecorder_basic(holder):\n pm = PytestPluginManager()\n pm.add_hookspecs(holder)\n rec = HookRecorder(pm)\n pm.hook.pytest_xyz(arg=123)\n call = rec.popcall(\"pytest_xyz\")\n assert call.arg == 123\n assert call._name == \"pytest_xyz\"\n pytest.raises(pytest.fail.Exception, rec.popcall, \"abc\")\n pm.hook.pytest_xyz_noarg()\n call = rec.popcall(\"pytest_xyz_noarg\")\n assert call._name == \"pytest_xyz_noarg\"\n\n\ndef test_makepyfile_unicode(testdir):\n global unichr\n try:\n unichr(65)\n except NameError:\n unichr = chr\n testdir.makepyfile(unichr(0xFFFD))\n\n\ndef test_makepyfile_utf8(testdir):\n \"\"\"Ensure makepyfile accepts utf-8 bytes as input (#2738)\"\"\"\n utf8_contents = u\"\"\"\n def setup_function(function):\n mixed_encoding = u'São Paulo'\n \"\"\".encode(\n \"utf-8\"\n )\n p = testdir.makepyfile(utf8_contents)\n assert u\"mixed_encoding = u'São Paulo'\".encode(\"utf-8\") in p.read(\"rb\")\n\n\nclass TestInlineRunModulesCleanup(object):\n def test_inline_run_test_module_not_cleaned_up(self, testdir):\n test_mod = testdir.makepyfile(\"def test_foo(): assert True\")\n result = testdir.inline_run(str(test_mod))\n assert result.ret == EXIT_OK\n # rewrite module, now test should fail if module was re-imported\n test_mod.write(\"def test_foo(): assert False\")\n result2 = testdir.inline_run(str(test_mod))\n assert result2.ret == EXIT_TESTSFAILED\n\n def spy_factory(self):\n class SysModulesSnapshotSpy(object):\n instances = []\n\n def __init__(self, preserve=None):\n SysModulesSnapshotSpy.instances.append(self)\n self._spy_restore_count = 0\n self._spy_preserve = preserve\n self.__snapshot = SysModulesSnapshot(preserve=preserve)\n\n def restore(self):\n self._spy_restore_count += 1\n return self.__snapshot.restore()\n\n return SysModulesSnapshotSpy\n\n def test_inline_run_taking_and_restoring_a_sys_modules_snapshot(\n self, testdir, monkeypatch\n ):\n spy_factory = self.spy_factory()\n monkeypatch.setattr(pytester, \"SysModulesSnapshot\", spy_factory)\n testdir.syspathinsert()\n original = dict(sys.modules)\n testdir.makepyfile(import1=\"# you son of a silly person\")\n testdir.makepyfile(import2=\"# my hovercraft is full of eels\")\n test_mod = testdir.makepyfile(\n \"\"\"\n import import1\n def test_foo(): import import2\"\"\"\n )\n testdir.inline_run(str(test_mod))\n assert len(spy_factory.instances) == 1\n spy = spy_factory.instances[0]\n assert spy._spy_restore_count == 1\n assert sys.modules == original\n assert all(sys.modules[x] is original[x] for x in sys.modules)\n\n def test_inline_run_sys_modules_snapshot_restore_preserving_modules(\n self, testdir, monkeypatch\n ):\n spy_factory = self.spy_factory()\n monkeypatch.setattr(pytester, \"SysModulesSnapshot\", spy_factory)\n test_mod = testdir.makepyfile(\"def test_foo(): pass\")\n testdir.inline_run(str(test_mod))\n spy = spy_factory.instances[0]\n assert not spy._spy_preserve(\"black_knight\")\n assert spy._spy_preserve(\"zope\")\n assert spy._spy_preserve(\"zope.interface\")\n assert spy._spy_preserve(\"zopelicious\")\n\n def test_external_test_module_imports_not_cleaned_up(self, testdir):\n testdir.syspathinsert()\n testdir.makepyfile(imported=\"data = 'you son of a silly person'\")\n import imported\n\n test_mod = testdir.makepyfile(\n \"\"\"\n def test_foo():\n import imported\n imported.data = 42\"\"\"\n )\n testdir.inline_run(str(test_mod))\n assert imported.data == 42\n\n\ndef test_assert_outcomes_after_pytest_error(testdir):\n testdir.makepyfile(\"def test_foo(): assert True\")\n\n result = testdir.runpytest(\"--unexpected-argument\")\n with pytest.raises(ValueError, match=\"Pytest terminal report not found\"):\n result.assert_outcomes(passed=0)\n\n\ndef test_cwd_snapshot(tmpdir):\n foo = tmpdir.ensure(\"foo\", dir=1)\n bar = tmpdir.ensure(\"bar\", dir=1)\n foo.chdir()\n snapshot = CwdSnapshot()\n bar.chdir()\n assert py.path.local() == bar\n snapshot.restore()\n assert py.path.local() == foo\n\n\nclass TestSysModulesSnapshot(object):\n key = \"my-test-module\"\n\n def test_remove_added(self):\n original = dict(sys.modules)\n assert self.key not in sys.modules\n snapshot = SysModulesSnapshot()\n sys.modules[self.key] = \"something\"\n assert self.key in sys.modules\n snapshot.restore()\n assert sys.modules == original\n\n def test_add_removed(self, monkeypatch):\n assert self.key not in sys.modules\n monkeypatch.setitem(sys.modules, self.key, \"something\")\n assert self.key in sys.modules\n original = dict(sys.modules)\n snapshot = SysModulesSnapshot()\n del sys.modules[self.key]\n assert self.key not in sys.modules\n snapshot.restore()\n assert sys.modules == original\n\n def test_restore_reloaded(self, monkeypatch):\n assert self.key not in sys.modules\n monkeypatch.setitem(sys.modules, self.key, \"something\")\n assert self.key in sys.modules\n original = dict(sys.modules)\n snapshot = SysModulesSnapshot()\n sys.modules[self.key] = \"something else\"\n snapshot.restore()\n assert sys.modules == original\n\n def test_preserve_modules(self, monkeypatch):\n key = [self.key + str(i) for i in range(3)]\n assert not any(k in sys.modules for k in key)\n for i, k in enumerate(key):\n monkeypatch.setitem(sys.modules, k, \"something\" + str(i))\n original = dict(sys.modules)\n\n def preserve(name):\n return name in (key[0], key[1], \"some-other-key\")\n\n snapshot = SysModulesSnapshot(preserve=preserve)\n sys.modules[key[0]] = original[key[0]] = \"something else0\"\n sys.modules[key[1]] = original[key[1]] = \"something else1\"\n sys.modules[key[2]] = \"something else2\"\n snapshot.restore()\n assert sys.modules == original\n\n def test_preserve_container(self, monkeypatch):\n original = dict(sys.modules)\n assert self.key not in original\n replacement = dict(sys.modules)\n replacement[self.key] = \"life of brian\"\n snapshot = SysModulesSnapshot()\n monkeypatch.setattr(sys, \"modules\", replacement)\n snapshot.restore()\n assert sys.modules is replacement\n assert sys.modules == original\n\n\n@pytest.mark.parametrize(\"path_type\", (\"path\", \"meta_path\"))\nclass TestSysPathsSnapshot(object):\n other_path = {\"path\": \"meta_path\", \"meta_path\": \"path\"}\n\n @staticmethod\n def path(n):\n return \"my-dirty-little-secret-\" + str(n)\n\n def test_restore(self, monkeypatch, path_type):\n other_path_type = self.other_path[path_type]\n for i in range(10):\n assert self.path(i) not in getattr(sys, path_type)\n sys_path = [self.path(i) for i in range(6)]\n monkeypatch.setattr(sys, path_type, sys_path)\n original = list(sys_path)\n original_other = list(getattr(sys, other_path_type))\n snapshot = SysPathsSnapshot()\n transformation = {\"source\": (0, 1, 2, 3, 4, 5), \"target\": (6, 2, 9, 7, 5, 8)}\n assert sys_path == [self.path(x) for x in transformation[\"source\"]]\n sys_path[1] = self.path(6)\n sys_path[3] = self.path(7)\n sys_path.append(self.path(8))\n del sys_path[4]\n sys_path[3:3] = [self.path(9)]\n del sys_path[0]\n assert sys_path == [self.path(x) for x in transformation[\"target\"]]\n snapshot.restore()\n assert getattr(sys, path_type) is sys_path\n assert getattr(sys, path_type) == original\n assert getattr(sys, other_path_type) == original_other\n\n def test_preserve_container(self, monkeypatch, path_type):\n other_path_type = self.other_path[path_type]\n original_data = list(getattr(sys, path_type))\n original_other = getattr(sys, other_path_type)\n original_other_data = list(original_other)\n new = []\n snapshot = SysPathsSnapshot()\n monkeypatch.setattr(sys, path_type, new)\n snapshot.restore()\n assert getattr(sys, path_type) is new\n assert getattr(sys, path_type) == original_data\n assert getattr(sys, other_path_type) is original_other\n assert getattr(sys, other_path_type) == original_other_data\n\n\ndef test_testdir_subprocess(testdir):\n testfile = testdir.makepyfile(\"def test_one(): pass\")\n assert testdir.runpytest_subprocess(testfile).ret == 0\n\n\ndef test_unicode_args(testdir):\n result = testdir.runpytest(\"-k\", u\"💩\")\n assert result.ret == EXIT_NOTESTSCOLLECTED\n\n\ndef test_testdir_run_no_timeout(testdir):\n testfile = testdir.makepyfile(\"def test_no_timeout(): pass\")\n assert testdir.runpytest_subprocess(testfile).ret == EXIT_OK\n\n\ndef test_testdir_run_with_timeout(testdir):\n testfile = testdir.makepyfile(\"def test_no_timeout(): pass\")\n\n timeout = 120\n\n start = time.time()\n result = testdir.runpytest_subprocess(testfile, timeout=timeout)\n end = time.time()\n duration = end - start\n\n assert result.ret == EXIT_OK\n assert duration < timeout\n\n\ndef test_testdir_run_timeout_expires(testdir):\n testfile = testdir.makepyfile(\n \"\"\"\n import time\n\n def test_timeout():\n time.sleep(10)\"\"\"\n )\n with pytest.raises(testdir.TimeoutExpired):\n testdir.runpytest_subprocess(testfile, timeout=1)\n\n\ndef test_linematcher_with_nonlist():\n \"\"\"Test LineMatcher with regard to passing in a set (accidentally).\"\"\"\n lm = LineMatcher([])\n\n with pytest.raises(AssertionError):\n lm.fnmatch_lines(set())\n with pytest.raises(AssertionError):\n lm.fnmatch_lines({})\n lm.fnmatch_lines([])\n lm.fnmatch_lines(())\n\n assert lm._getlines({}) == {}\n assert lm._getlines(set()) == set()\n\n\ndef test_pytester_addopts(request, monkeypatch):\n monkeypatch.setenv(\"PYTEST_ADDOPTS\", \"--orig-unused\")\n\n testdir = request.getfixturevalue(\"testdir\")\n\n try:\n assert \"PYTEST_ADDOPTS\" not in os.environ\n finally:\n testdir.finalize()\n\n assert os.environ[\"PYTEST_ADDOPTS\"] == \"--orig-unused\"\n\n\ndef test_run_stdin(testdir):\n with pytest.raises(testdir.TimeoutExpired):\n testdir.run(\n sys.executable,\n \"-c\",\n \"import sys, time; time.sleep(1); print(sys.stdin.read())\",\n stdin=subprocess.PIPE,\n timeout=0.1,\n )\n\n with pytest.raises(testdir.TimeoutExpired):\n result = testdir.run(\n sys.executable,\n \"-c\",\n \"import sys, time; time.sleep(1); print(sys.stdin.read())\",\n stdin=b\"input\\n2ndline\",\n timeout=0.1,\n )\n\n result = testdir.run(\n sys.executable,\n \"-c\",\n \"import sys; print(sys.stdin.read())\",\n stdin=b\"input\\n2ndline\",\n )\n assert result.stdout.lines == [\"input\", \"2ndline\"]\n assert result.stderr.str() == \"\"\n assert result.ret == 0\n\n\ndef test_popen_stdin_pipe(testdir):\n proc = testdir.popen(\n [sys.executable, \"-c\", \"import sys; print(sys.stdin.read())\"],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n stdin=subprocess.PIPE,\n )\n stdin = b\"input\\n2ndline\"\n stdout, stderr = proc.communicate(input=stdin)\n assert stdout.decode(\"utf8\").splitlines() == [\"input\", \"2ndline\"]\n assert stderr == b\"\"\n assert proc.returncode == 0\n\n\ndef test_popen_stdin_bytes(testdir):\n proc = testdir.popen(\n [sys.executable, \"-c\", \"import sys; print(sys.stdin.read())\"],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n stdin=b\"input\\n2ndline\",\n )\n stdout, stderr = proc.communicate()\n assert stdout.decode(\"utf8\").splitlines() == [\"input\", \"2ndline\"]\n assert stderr == b\"\"\n assert proc.returncode == 0\n\n\ndef test_popen_default_stdin_stderr_and_stdin_None(testdir):\n # stdout, stderr default to pipes,\n # stdin can be None to not close the pipe, avoiding\n # \"ValueError: flush of closed file\" with `communicate()`.\n p1 = testdir.makepyfile(\n \"\"\"\n import sys\n print(sys.stdin.read()) # empty\n print('stdout')\n sys.stderr.write('stderr')\n \"\"\"\n )\n proc = testdir.popen([sys.executable, str(p1)], stdin=None)\n stdout, stderr = proc.communicate(b\"ignored\")\n assert stdout.splitlines() == [b\"\", b\"stdout\"]\n assert stderr.splitlines() == [b\"stderr\"]\n assert proc.returncode == 0\n\n\ndef test_spawn_uses_tmphome(testdir):\n import os\n\n tmphome = str(testdir.tmpdir)\n\n # Does use HOME only during run.\n assert os.environ.get(\"HOME\") != tmphome\n\n testdir._env_run_update[\"CUSTOMENV\"] = \"42\"\n\n p1 = testdir.makepyfile(\n \"\"\"\n import os\n\n def test():\n assert os.environ[\"HOME\"] == {tmphome!r}\n assert os.environ[\"CUSTOMENV\"] == \"42\"\n \"\"\".format(\n tmphome=tmphome\n )\n )\n child = testdir.spawn_pytest(str(p1))\n out = child.read()\n assert child.wait() == 0, out.decode(\"utf8\")\n"},{"attributeType":"null","col":0,"comment":"null","endLoc":29,"id":2177,"name":"EXIT_OK","nodeType":"Attribute","startLoc":29,"text":"EXIT_OK"},{"attributeType":"null","col":0,"comment":"null","endLoc":30,"id":2178,"name":"EXIT_TESTSFAILED","nodeType":"Attribute","startLoc":30,"text":"EXIT_TESTSFAILED"},{"attributeType":"str","col":8,"comment":"null","endLoc":194,"id":2180,"name":"_unexpectedsuccess","nodeType":"Attribute","startLoc":194,"text":"self._unexpectedsuccess"},{"col":25,"endLoc":306,"id":2181,"nodeType":"Lambda","startLoc":306,"text":"lambda: pytestpm.consider_preparse([\"xyz\", \"-p\", \"hello123\"])"},{"attributeType":"bool","col":12,"comment":"null","endLoc":184,"id":2182,"name":"_skipped_by_mark","nodeType":"Attribute","startLoc":184,"text":"self._skipped_by_mark"},{"col":0,"comment":"null","endLoc":29,"header":"def pytest_pycollect_makeitem(collector, name, obj)","id":2183,"name":"pytest_pycollect_makeitem","nodeType":"Function","startLoc":21,"text":"def pytest_pycollect_makeitem(collector, name, obj):\n # has unittest been imported and is obj a subclass of its TestCase?\n try:\n if not issubclass(obj, sys.modules[\"unittest\"].TestCase):\n return\n except Exception:\n return\n # yes, so let's collect it\n return UnitTestCase(name, parent=collector)"},{"col":4,"comment":"null","endLoc":327,"header":"def test_plugin_prevent_register(self, pytestpm)","id":2184,"name":"test_plugin_prevent_register","nodeType":"Function","startLoc":321,"text":"def test_plugin_prevent_register(self, pytestpm):\n pytestpm.consider_preparse([\"xyz\", \"-p\", \"no:abc\"])\n l1 = pytestpm.get_plugins()\n pytestpm.register(42, name=\"abc\")\n l2 = pytestpm.get_plugins()\n assert len(l2) == len(l1)\n assert 42 not in l2"},{"col":4,"comment":"null","endLoc":539,"header":"@pytest.mark.skipif(\n hasattr(sys, \"pypy_version_info\"),\n reason=\"this method of test doesn't work on pypy\",\n )\n def test_request_garbage(self, testdir)","id":2186,"name":"test_request_garbage","nodeType":"Function","startLoc":501,"text":"@pytest.mark.skipif(\n hasattr(sys, \"pypy_version_info\"),\n reason=\"this method of test doesn't work on pypy\",\n )\n def test_request_garbage(self, testdir):\n try:\n import xdist # noqa\n except ImportError:\n pass\n else:\n pytest.xfail(\"this test is flaky when executed with xdist\")\n testdir.makepyfile(\n \"\"\"\n import sys\n import pytest\n from _pytest.fixtures import PseudoFixtureDef\n import gc\n\n @pytest.fixture(autouse=True)\n def something(request):\n original = gc.get_debug()\n gc.set_debug(gc.DEBUG_SAVEALL)\n gc.collect()\n\n yield\n\n try:\n gc.collect()\n leaked = [x for _ in gc.garbage if isinstance(_, PseudoFixtureDef)]\n assert leaked == []\n finally:\n gc.set_debug(original)\n\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"* 1 passed in *\"])"},{"col":4,"comment":"null","endLoc":335,"header":"def test_plugin_prevent_register_unregistered_alredy_registered(self, pytestpm)","id":2187,"name":"test_plugin_prevent_register_unregistered_alredy_registered","nodeType":"Function","startLoc":329,"text":"def test_plugin_prevent_register_unregistered_alredy_registered(self, pytestpm):\n pytestpm.register(42, name=\"abc\")\n l1 = pytestpm.get_plugins()\n assert 42 in l1\n pytestpm.consider_preparse([\"xyz\", \"-p\", \"no:abc\"])\n l2 = pytestpm.get_plugins()\n assert 42 not in l2"},{"col":0,"comment":"null","endLoc":248,"header":"@hookimpl(tryfirst=True)\ndef pytest_runtest_makereport(item, call)","id":2188,"name":"pytest_runtest_makereport","nodeType":"Function","startLoc":240,"text":"@hookimpl(tryfirst=True)\ndef pytest_runtest_makereport(item, call):\n if isinstance(item, TestCaseFunction):\n if item._excinfo:\n call.excinfo = item._excinfo.pop(0)\n try:\n del call.result\n except AttributeError:\n pass"},{"col":4,"comment":" From PR #4304 : The only way to unregister a module is documented at\n the end of https://docs.pytest.org/en/latest/plugins.html.\n\n When unregister cacheprovider, then unregister stepwise too\n ","endLoc":353,"header":"def test_plugin_prevent_register_stepwise_on_cacheprovider_unregister(\n self, pytestpm\n )","id":2189,"name":"test_plugin_prevent_register_stepwise_on_cacheprovider_unregister","nodeType":"Function","startLoc":337,"text":"def test_plugin_prevent_register_stepwise_on_cacheprovider_unregister(\n self, pytestpm\n ):\n \"\"\" From PR #4304 : The only way to unregister a module is documented at\n the end of https://docs.pytest.org/en/latest/plugins.html.\n\n When unregister cacheprovider, then unregister stepwise too\n \"\"\"\n pytestpm.register(42, name=\"cacheprovider\")\n pytestpm.register(43, name=\"stepwise\")\n l1 = pytestpm.get_plugins()\n assert 42 in l1\n assert 43 in l1\n pytestpm.consider_preparse([\"xyz\", \"-p\", \"no:cacheprovider\"])\n l2 = pytestpm.get_plugins()\n assert 42 not in l2\n assert 43 not in l2"},{"id":2190,"name":"release-2.8.6.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.8.6\n============\n\npytest is a mature Python testing tool with more than a 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is supposed to be drop-in compatible to 2.8.5.\n\nSee below for the changes and see docs at:\n\n http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n AMiT Kumar\n Bruno Oliveira\n Erik M. Bray\n Florian Bruhin\n Georgy Dyuldin\n Jeff Widman\n Kartik Singhal\n Loïc Estève\n Manu Phatak\n Peter Demin\n Rick van Hattem\n Ronny Pfannschmidt\n Ulrich Petri\n foxx\n\n\nHappy testing,\nThe py.test Development Team\n\n\n2.8.6 (compared to 2.8.5)\n-------------------------\n\n- fix #1259: allow for double nodeids in junitxml,\n this was a regression failing plugins combinations\n like pytest-pep8 + pytest-flakes\n\n- Workaround for exception that occurs in pyreadline when using\n ``--pdb`` with standard I/O capture enabled.\n Thanks Erik M. Bray for the PR.\n\n- fix #900: Better error message in case the target of a ``monkeypatch`` call\n raises an ``ImportError``.\n\n- fix #1292: monkeypatch calls (setattr, setenv, etc.) are now O(1).\n Thanks David R. MacIver for the report and Bruno Oliveira for the PR.\n\n- fix #1223: captured stdout and stderr are now properly displayed before\n entering pdb when ``--pdb`` is used instead of being thrown away.\n Thanks Cal Leeming for the PR.\n\n- fix #1305: pytest warnings emitted during ``pytest_terminal_summary`` are now\n properly displayed.\n Thanks Ionel Maries Cristian for the report and Bruno Oliveira for the PR.\n\n- fix #628: fixed internal UnicodeDecodeError when doctests contain unicode.\n Thanks Jason R. Coombs for the report and Bruno Oliveira for the PR.\n\n- fix #1334: Add captured stdout to jUnit XML report on setup error.\n Thanks Georgy Dyuldin for the PR.\n"},{"id":2191,"name":"release-2.6.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.6.0: shorter tracebacks, new warning system, test runner compat\n===========================================================================\n\npytest is a mature Python testing tool with more than a 1000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThe 2.6.0 release should be drop-in backward compatible to 2.5.2 and\nfixes a number of bugs and brings some new features, mainly:\n\n- shorter tracebacks by default: only the first (test function) entry\n and the last (failure location) entry are shown, the ones between\n only in \"short\" format. Use ``--tb=long`` to get back the old\n behaviour of showing \"long\" entries everywhere.\n\n- a new warning system which reports oddities during collection\n and execution. For example, ignoring collecting Test* classes with an\n ``__init__`` now produces a warning.\n\n- various improvements to nose/mock/unittest integration\n\nNote also that 2.6.0 departs with the \"zero reported bugs\" policy\nbecause it has been too hard to keep up with it, unfortunately.\nInstead we are for now rather bound to work on \"upvoted\" issues in\nthe https://bitbucket.org/pytest-dev/pytest/issues?status=new&status=open&sort=-votes\nissue tracker.\n\nSee docs at:\n\n http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n pip install -U pytest\n\nThanks to all who contributed, among them:\n\n Benjamin Peterson\n Jurko Gospodnetić\n Floris Bruynooghe\n Marc Abramowitz\n Marc Schlaich\n Trevor Bekolay\n Bruno Oliveira\n Alex Groenholm\n\nhave fun,\nholger krekel\n\n2.6.0\n-----------------------------------\n\n- fix issue537: Avoid importing old assertion reinterpretation code by default.\n Thanks Benjamin Peterson.\n\n- fix issue364: shorten and enhance tracebacks representation by default.\n The new \"--tb=auto\" option (default) will only display long tracebacks\n for the first and last entry. You can get the old behaviour of printing\n all entries as long entries with \"--tb=long\". Also short entries by\n default are now printed very similarly to \"--tb=native\" ones.\n\n- fix issue514: teach assertion reinterpretation about private class attributes\n Thanks Benjamin Peterson.\n\n- change -v output to include full node IDs of tests. Users can copy\n a node ID from a test run, including line number, and use it as a\n positional argument in order to run only a single test.\n\n- fix issue 475: fail early and comprehensible if calling\n pytest.raises with wrong exception type.\n\n- fix issue516: tell in getting-started about current dependencies.\n\n- cleanup setup.py a bit and specify supported versions. Thanks Jurko\n Gospodnetic for the PR.\n\n- change XPASS colour to yellow rather then red when tests are run\n with -v.\n\n- fix issue473: work around mock putting an unbound method into a class\n dict when double-patching.\n\n- fix issue498: if a fixture finalizer fails, make sure that\n the fixture is still invalidated.\n\n- fix issue453: the result of the pytest_assertrepr_compare hook now gets\n it's newlines escaped so that format_exception does not blow up.\n\n- internal new warning system: pytest will now produce warnings when\n it detects oddities in your test collection or execution.\n Warnings are ultimately sent to a new pytest_logwarning hook which is\n currently only implemented by the terminal plugin which displays\n warnings in the summary line and shows more details when -rw (report on\n warnings) is specified.\n\n- change skips into warnings for test classes with an __init__ and\n callables in test modules which look like a test but are not functions.\n\n- fix issue436: improved finding of initial conftest files from command\n line arguments by using the result of parse_known_args rather than\n the previous flaky heuristics. Thanks Marc Abramowitz for tests\n and initial fixing approaches in this area.\n\n- fix issue #479: properly handle nose/unittest(2) SkipTest exceptions\n during collection/loading of test modules. Thanks to Marc Schlaich\n for the complete PR.\n\n- fix issue490: include pytest_load_initial_conftests in documentation\n and improve docstring.\n\n- fix issue472: clarify that ``pytest.config.getvalue()`` cannot work\n if it's triggered ahead of command line parsing.\n\n- merge PR123: improved integration with mock.patch decorator on tests.\n\n- fix issue412: messing with stdout/stderr FD-level streams is now\n captured without crashes.\n\n- fix issue483: trial/py33 works now properly. Thanks Daniel Grana for PR.\n\n- improve example for pytest integration with \"python setup.py test\"\n which now has a generic \"-a\" or \"--pytest-args\" option where you\n can pass additional options as a quoted string. Thanks Trevor Bekolay.\n\n- simplified internal capturing mechanism and made it more robust\n against tests or setups changing FD1/FD2, also better integrated\n now with pytest.pdb() in single tests.\n\n- improvements to pytest's own test-suite leakage detection, courtesy of PRs\n from Marc Abramowitz\n\n- fix issue492: avoid leak in test_writeorg. Thanks Marc Abramowitz.\n\n- fix issue493: don't run tests in doc directory with ``python setup.py test``\n (use tox -e doctesting for that)\n\n- fix issue486: better reporting and handling of early conftest loading failures\n\n- some cleanup and simplification of internal conftest handling.\n\n- work a bit harder to break reference cycles when catching exceptions.\n Thanks Jurko Gospodnetic.\n\n- fix issue443: fix skip examples to use proper comparison. Thanks Alex\n Groenholm.\n\n- support nose-style ``__test__`` attribute on modules, classes and\n functions, including unittest-style Classes. If set to False, the\n test will not be collected.\n\n- fix issue512: show \"\" for arguments which might not be set\n in monkeypatch plugin. Improves output in documentation.\n\n- avoid importing \"py.test\" (an old alias module for \"pytest\")\n"},{"col":4,"comment":"null","endLoc":360,"header":"def test_blocked_plugin_can_be_used(self, pytestpm)","id":2192,"name":"test_blocked_plugin_can_be_used","nodeType":"Function","startLoc":355,"text":"def test_blocked_plugin_can_be_used(self, pytestpm):\n pytestpm.consider_preparse([\"xyz\", \"-p\", \"no:abc\", \"-p\", \"abc\"])\n\n assert pytestpm.has_plugin(\"abc\")\n assert not pytestpm.is_blocked(\"abc\")\n assert not pytestpm.is_blocked(\"pytest_abc\")"},{"col":0,"comment":"null","endLoc":19,"header":"@pytest.fixture\ndef pytestpm()","id":2193,"name":"pytestpm","nodeType":"Function","startLoc":17,"text":"@pytest.fixture\ndef pytestpm():\n return PytestPluginManager()"},{"col":4,"comment":"null","endLoc":563,"header":"def test_getfixturevalue_recursive(self, testdir)","id":2194,"name":"test_getfixturevalue_recursive","nodeType":"Function","startLoc":541,"text":"def test_getfixturevalue_recursive(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def something(request):\n return 1\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def something(request):\n return request.getfixturevalue(\"something\") + 1\n def test_func(something):\n assert something == 2\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":0,"comment":"null","endLoc":146,"header":"def test_default_markers(testdir)","id":2195,"name":"test_default_markers","nodeType":"Function","startLoc":144,"text":"def test_default_markers(testdir):\n result = testdir.runpytest(\"--markers\")\n result.stdout.fnmatch_lines([\"*tryfirst*first*\", \"*trylast*last*\"])"},{"col":4,"comment":"\n Issue #1895\n\n `test_inner` requests `inner` fixture, which in turn requests `resource`\n using `getfixturevalue`. `test_func` then requests `resource`.\n\n `resource` is teardown before `inner` because the fixture mechanism won't consider\n `inner` dependent on `resource` when it is used via `getfixturevalue`: `test_func`\n will then cause the `resource`'s finalizer to be called first because of this.\n ","endLoc":601,"header":"def test_getfixturevalue_teardown(self, testdir)","id":2196,"name":"test_getfixturevalue_teardown","nodeType":"Function","startLoc":565,"text":"def test_getfixturevalue_teardown(self, testdir):\n \"\"\"\n Issue #1895\n\n `test_inner` requests `inner` fixture, which in turn requests `resource`\n using `getfixturevalue`. `test_func` then requests `resource`.\n\n `resource` is teardown before `inner` because the fixture mechanism won't consider\n `inner` dependent on `resource` when it is used via `getfixturevalue`: `test_func`\n will then cause the `resource`'s finalizer to be called first because of this.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='session')\n def resource():\n r = ['value']\n yield r\n r.pop()\n\n @pytest.fixture(scope='session')\n def inner(request):\n resource = request.getfixturevalue('resource')\n assert resource == ['value']\n yield\n assert resource == ['value']\n\n def test_inner(inner):\n pass\n\n def test_func(resource):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed in *\"])"},{"col":0,"comment":"Don't hide import errors when importing plugins and provide\n an easy to debug message.\n\n See #375 and #1998.\n ","endLoc":170,"header":"def test_importplugin_error_message(testdir, pytestpm)","id":2197,"name":"test_importplugin_error_message","nodeType":"Function","startLoc":149,"text":"def test_importplugin_error_message(testdir, pytestpm):\n \"\"\"Don't hide import errors when importing plugins and provide\n an easy to debug message.\n\n See #375 and #1998.\n \"\"\"\n testdir.syspathinsert(testdir.tmpdir)\n testdir.makepyfile(\n qwe=\"\"\"\n # -*- coding: utf-8 -*-\n def test_traceback():\n raise ImportError(u'Not possible to import: ☺')\n test_traceback()\n \"\"\"\n )\n with pytest.raises(ImportError) as excinfo:\n pytestpm.import_plugin(\"qwe\")\n\n assert str(excinfo.value).endswith(\n 'Error importing plugin \"qwe\": Not possible to import: ☺'\n )\n assert \"in test_traceback\" in str(excinfo.traceback[-1])"},{"col":4,"comment":"null","endLoc":645,"header":"@pytest.mark.parametrize(\"getfixmethod\", (\"getfixturevalue\", \"getfuncargvalue\"))\n def test_getfixturevalue(self, testdir, getfixmethod)","id":2198,"name":"test_getfixturevalue","nodeType":"Function","startLoc":603,"text":"@pytest.mark.parametrize(\"getfixmethod\", (\"getfixturevalue\", \"getfuncargvalue\"))\n def test_getfixturevalue(self, testdir, getfixmethod):\n item = testdir.getitem(\n \"\"\"\n import pytest\n values = [2]\n @pytest.fixture\n def something(request): return 1\n @pytest.fixture\n def other(request):\n return values.pop()\n def test_func(something): pass\n \"\"\"\n )\n import contextlib\n\n if getfixmethod == \"getfuncargvalue\":\n warning_expectation = pytest.warns(DeprecationWarning)\n else:\n # see #1830 for a cleaner way to accomplish this\n @contextlib.contextmanager\n def expecting_no_warning():\n yield\n\n warning_expectation = expecting_no_warning()\n\n req = item._request\n with warning_expectation:\n fixture_fetcher = getattr(req, getfixmethod)\n with pytest.raises(FixtureLookupError):\n fixture_fetcher(\"notexists\")\n val = fixture_fetcher(\"something\")\n assert val == 1\n val = fixture_fetcher(\"something\")\n assert val == 1\n val2 = fixture_fetcher(\"other\")\n assert val2 == 2\n val2 = fixture_fetcher(\"other\") # see about caching\n assert val2 == 2\n pytest._fillfuncargs(item)\n assert item.funcargs[\"something\"] == 1\n assert len(get_public_names(item.funcargs)) == 2\n assert \"request\" in item.funcargs"},{"fileName":"helpconfig.py","filePath":"src/_pytest","id":2201,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\" version info, help messages, tracing configuration. \"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\nfrom argparse import Action\n\nimport py\n\nimport pytest\nfrom _pytest.config import PrintHelp\n\n\nclass HelpAction(Action):\n \"\"\"This is an argparse Action that will raise an exception in\n order to skip the rest of the argument parsing when --help is passed.\n This prevents argparse from quitting due to missing required arguments\n when any are defined, for example by ``pytest_addoption``.\n This is similar to the way that the builtin argparse --help option is\n implemented by raising SystemExit.\n \"\"\"\n\n def __init__(self, option_strings, dest=None, default=False, help=None):\n super(HelpAction, self).__init__(\n option_strings=option_strings,\n dest=dest,\n const=True,\n default=default,\n nargs=0,\n help=help,\n )\n\n def __call__(self, parser, namespace, values, option_string=None):\n setattr(namespace, self.dest, self.const)\n\n # We should only skip the rest of the parsing after preparse is done\n if getattr(parser._parser, \"after_preparse\", False):\n raise PrintHelp\n\n\ndef pytest_addoption(parser):\n group = parser.getgroup(\"debugconfig\")\n group.addoption(\n \"--version\",\n action=\"store_true\",\n help=\"display pytest lib version and import information.\",\n )\n group._addoption(\n \"-h\",\n \"--help\",\n action=HelpAction,\n dest=\"help\",\n help=\"show help message and configuration info\",\n )\n group._addoption(\n \"-p\",\n action=\"append\",\n dest=\"plugins\",\n default=[],\n metavar=\"name\",\n help=\"early-load given plugin module name or entry point (multi-allowed). \"\n \"To avoid loading of plugins, use the `no:` prefix, e.g. \"\n \"`no:doctest`.\",\n )\n group.addoption(\n \"--traceconfig\",\n \"--trace-config\",\n action=\"store_true\",\n default=False,\n help=\"trace considerations of conftest.py files.\",\n ),\n group.addoption(\n \"--debug\",\n action=\"store_true\",\n dest=\"debug\",\n default=False,\n help=\"store internal tracing debug information in 'pytestdebug.log'.\",\n )\n group._addoption(\n \"-o\",\n \"--override-ini\",\n dest=\"override_ini\",\n action=\"append\",\n help='override ini option with \"option=value\" style, e.g. `-o xfail_strict=True -o cache_dir=cache`.',\n )\n\n\n@pytest.hookimpl(hookwrapper=True)\ndef pytest_cmdline_parse():\n outcome = yield\n config = outcome.get_result()\n if config.option.debug:\n path = os.path.abspath(\"pytestdebug.log\")\n debugfile = open(path, \"w\")\n debugfile.write(\n \"versions pytest-%s, py-%s, \"\n \"python-%s\\ncwd=%s\\nargs=%s\\n\\n\"\n % (\n pytest.__version__,\n py.__version__,\n \".\".join(map(str, sys.version_info)),\n os.getcwd(),\n config._origargs,\n )\n )\n config.trace.root.setwriter(debugfile.write)\n undo_tracing = config.pluginmanager.enable_tracing()\n sys.stderr.write(\"writing pytestdebug information to %s\\n\" % path)\n\n def unset_tracing():\n debugfile.close()\n sys.stderr.write(\"wrote pytestdebug information to %s\\n\" % debugfile.name)\n config.trace.root.setwriter(None)\n undo_tracing()\n\n config.add_cleanup(unset_tracing)\n\n\ndef showversion(config):\n p = py.path.local(pytest.__file__)\n sys.stderr.write(\n \"This is pytest version %s, imported from %s\\n\" % (pytest.__version__, p)\n )\n plugininfo = getpluginversioninfo(config)\n if plugininfo:\n for line in plugininfo:\n sys.stderr.write(line + \"\\n\")\n\n\ndef pytest_cmdline_main(config):\n if config.option.version:\n showversion(config)\n return 0\n elif config.option.help:\n config._do_configure()\n showhelp(config)\n config._ensure_unconfigure()\n return 0\n\n\ndef showhelp(config):\n import textwrap\n\n reporter = config.pluginmanager.get_plugin(\"terminalreporter\")\n tw = reporter._tw\n tw.write(config._parser.optparser.format_help())\n tw.line()\n tw.line(\n \"[pytest] ini-options in the first pytest.ini|tox.ini|setup.cfg file found:\"\n )\n tw.line()\n\n columns = tw.fullwidth # costly call\n indent_len = 24 # based on argparse's max_help_position=24\n indent = \" \" * indent_len\n for name in config._parser._ininames:\n help, type, default = config._parser._inidict[name]\n if type is None:\n type = \"string\"\n spec = \"%s (%s):\" % (name, type)\n tw.write(\" %s\" % spec)\n spec_len = len(spec)\n if spec_len > (indent_len - 3):\n # Display help starting at a new line.\n tw.line()\n helplines = textwrap.wrap(\n help,\n columns,\n initial_indent=indent,\n subsequent_indent=indent,\n break_on_hyphens=False,\n )\n\n for line in helplines:\n tw.line(line)\n else:\n # Display help starting after the spec, following lines indented.\n tw.write(\" \" * (indent_len - spec_len - 2))\n wrapped = textwrap.wrap(help, columns - indent_len, break_on_hyphens=False)\n\n tw.line(wrapped[0])\n for line in wrapped[1:]:\n tw.line(indent + line)\n\n tw.line()\n tw.line(\"environment variables:\")\n vars = [\n (\"PYTEST_ADDOPTS\", \"extra command line options\"),\n (\"PYTEST_PLUGINS\", \"comma-separated plugins to load during startup\"),\n (\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", \"set to disable plugin auto-loading\"),\n (\"PYTEST_DEBUG\", \"set to enable debug tracing of pytest's internals\"),\n ]\n for name, help in vars:\n tw.line(\" %-24s %s\" % (name, help))\n tw.line()\n tw.line()\n\n tw.line(\"to see available markers type: pytest --markers\")\n tw.line(\"to see available fixtures type: pytest --fixtures\")\n tw.line(\n \"(shown according to specified file_or_dir or current dir \"\n \"if not specified; fixtures with leading '_' are only shown \"\n \"with the '-v' option\"\n )\n\n for warningreport in reporter.stats.get(\"warnings\", []):\n tw.line(\"warning : \" + warningreport.message, red=True)\n return\n\n\nconftest_options = [(\"pytest_plugins\", \"list of plugin names to load\")]\n\n\ndef getpluginversioninfo(config):\n lines = []\n plugininfo = config.pluginmanager.list_plugin_distinfo()\n if plugininfo:\n lines.append(\"setuptools registered plugins:\")\n for plugin, dist in plugininfo:\n loc = getattr(plugin, \"__file__\", repr(plugin))\n content = \"%s-%s at %s\" % (dist.project_name, dist.version, loc)\n lines.append(\" \" + content)\n return lines\n\n\ndef pytest_report_header(config):\n lines = []\n if config.option.debug or config.option.traceconfig:\n lines.append(\"using: pytest-%s pylib-%s\" % (pytest.__version__, py.__version__))\n\n verinfo = getpluginversioninfo(config)\n if verinfo:\n lines.extend(verinfo)\n\n if config.option.traceconfig:\n lines.append(\"active plugins:\")\n items = config.pluginmanager.list_name_plugin()\n for name, plugin in items:\n if hasattr(plugin, \"__file__\"):\n r = plugin.__file__\n else:\n r = repr(plugin)\n lines.append(\" %-20s: %s\" % (name, r))\n return lines\n"},{"fileName":"test_helpconfig.py","filePath":"testing","id":2203,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pytest\nfrom _pytest.main import EXIT_NOTESTSCOLLECTED\n\n\ndef test_version(testdir, pytestconfig):\n result = testdir.runpytest(\"--version\")\n assert result.ret == 0\n # p = py.path.local(py.__file__).dirpath()\n result.stderr.fnmatch_lines(\n [\"*pytest*{}*imported from*\".format(pytest.__version__)]\n )\n if pytestconfig.pluginmanager.list_plugin_distinfo():\n result.stderr.fnmatch_lines([\"*setuptools registered plugins:\", \"*at*\"])\n\n\ndef test_help(testdir):\n result = testdir.runpytest(\"--help\")\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n \"\"\"\n *-v*verbose*\n *setup.cfg*\n *minversion*\n *to see*markers*pytest --markers*\n *to see*fixtures*pytest --fixtures*\n \"\"\"\n )\n\n\ndef test_hookvalidation_unknown(testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_hello(xyz):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret != 0\n result.stdout.fnmatch_lines([\"*unknown hook*pytest_hello*\"])\n\n\ndef test_hookvalidation_optional(testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.hookimpl(optionalhook=True)\n def pytest_hello(xyz):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n\n\ndef test_traceconfig(testdir):\n result = testdir.runpytest(\"--traceconfig\")\n result.stdout.fnmatch_lines([\"*using*pytest*py*\", \"*active plugins*\"])\n\n\ndef test_debug(testdir, monkeypatch):\n result = testdir.runpytest_subprocess(\"--debug\")\n assert result.ret == EXIT_NOTESTSCOLLECTED\n p = testdir.tmpdir.join(\"pytestdebug.log\")\n assert \"pytest_sessionstart\" in p.read()\n\n\ndef test_PYTEST_DEBUG(testdir, monkeypatch):\n monkeypatch.setenv(\"PYTEST_DEBUG\", \"1\")\n result = testdir.runpytest_subprocess()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result.stderr.fnmatch_lines(\n [\"*pytest_plugin_registered*\", \"*manager*PluginManager*\"]\n )\n"},{"id":2204,"name":"release-3.6.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.6.1\n=======================================\n\npytest 3.6.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Jeffrey Rackauckas\n* Miro Hrončok\n* Niklas Meinzer\n* Oliver Bestwalter\n* Ronny Pfannschmidt\n\n\nHappy testing,\nThe pytest Development Team\n"},{"col":0,"comment":"null","endLoc":18,"header":"def test_version(testdir, pytestconfig)","id":2205,"name":"test_version","nodeType":"Function","startLoc":10,"text":"def test_version(testdir, pytestconfig):\n result = testdir.runpytest(\"--version\")\n assert result.ret == 0\n # p = py.path.local(py.__file__).dirpath()\n result.stderr.fnmatch_lines(\n [\"*pytest*{}*imported from*\".format(pytest.__version__)]\n )\n if pytestconfig.pluginmanager.list_plugin_distinfo():\n result.stderr.fnmatch_lines([\"*setuptools registered plugins:\", \"*at*\"])"},{"fileName":"warnings.py","filePath":"src/_pytest","id":2206,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nimport warnings\nfrom contextlib import contextmanager\n\nimport pytest\nfrom _pytest import compat\n\nSHOW_PYTEST_WARNINGS_ARG = \"-Walways::pytest.RemovedInPytest4Warning\"\n\n\ndef _setoption(wmod, arg):\n \"\"\"\n Copy of the warning._setoption function but does not escape arguments.\n \"\"\"\n parts = arg.split(\":\")\n if len(parts) > 5:\n raise wmod._OptionError(\"too many fields (max 5): %r\" % (arg,))\n while len(parts) < 5:\n parts.append(\"\")\n action, message, category, module, lineno = [s.strip() for s in parts]\n action = wmod._getaction(action)\n category = wmod._getcategory(category)\n if lineno:\n try:\n lineno = int(lineno)\n if lineno < 0:\n raise ValueError\n except (ValueError, OverflowError):\n raise wmod._OptionError(\"invalid lineno %r\" % (lineno,))\n else:\n lineno = 0\n wmod.filterwarnings(action, message, category, module, lineno)\n\n\ndef pytest_addoption(parser):\n group = parser.getgroup(\"pytest-warnings\")\n group.addoption(\n \"-W\",\n \"--pythonwarnings\",\n action=\"append\",\n help=\"set which warnings to report, see -W option of python itself.\",\n )\n parser.addini(\n \"filterwarnings\",\n type=\"linelist\",\n help=\"Each line specifies a pattern for \"\n \"warnings.filterwarnings. \"\n \"Processed after -W and --pythonwarnings.\",\n )\n\n\ndef pytest_configure(config):\n config.addinivalue_line(\n \"markers\",\n \"filterwarnings(warning): add a warning filter to the given test. \"\n \"see https://docs.pytest.org/en/latest/warnings.html#pytest-mark-filterwarnings \",\n )\n\n\n@contextmanager\ndef catch_warnings_for_item(config, ihook, when, item):\n \"\"\"\n Context manager that catches warnings generated in the contained execution block.\n\n ``item`` can be None if we are not in the context of an item execution.\n\n Each warning captured triggers the ``pytest_warning_captured`` hook.\n \"\"\"\n cmdline_filters = config.getoption(\"pythonwarnings\") or []\n inifilters = config.getini(\"filterwarnings\")\n with warnings.catch_warnings(record=True) as log:\n\n if not sys.warnoptions:\n # if user is not explicitly configuring warning filters, show deprecation warnings by default (#2908)\n warnings.filterwarnings(\"always\", category=DeprecationWarning)\n warnings.filterwarnings(\"always\", category=PendingDeprecationWarning)\n\n warnings.filterwarnings(\"error\", category=pytest.RemovedInPytest4Warning)\n\n # filters should have this precedence: mark, cmdline options, ini\n # filters should be applied in the inverse order of precedence\n for arg in inifilters:\n _setoption(warnings, arg)\n\n for arg in cmdline_filters:\n warnings._setoption(arg)\n\n if item is not None:\n for mark in item.iter_markers(name=\"filterwarnings\"):\n for arg in mark.args:\n _setoption(warnings, arg)\n\n yield\n\n for warning_message in log:\n ihook.pytest_warning_captured.call_historic(\n kwargs=dict(warning_message=warning_message, when=when, item=item)\n )\n\n\ndef warning_record_to_str(warning_message):\n \"\"\"Convert a warnings.WarningMessage to a string.\n\n This takes lot of unicode shenaningans into account for Python 2.\n When Python 2 support is dropped this function can be greatly simplified.\n \"\"\"\n warn_msg = warning_message.message\n unicode_warning = False\n if compat._PY2 and any(isinstance(m, compat.UNICODE_TYPES) for m in warn_msg.args):\n new_args = []\n for m in warn_msg.args:\n new_args.append(\n compat.ascii_escaped(m) if isinstance(m, compat.UNICODE_TYPES) else m\n )\n unicode_warning = list(warn_msg.args) != new_args\n warn_msg.args = new_args\n\n msg = warnings.formatwarning(\n warn_msg,\n warning_message.category,\n warning_message.filename,\n warning_message.lineno,\n warning_message.line,\n )\n if unicode_warning:\n warnings.warn(\n \"Warning is using unicode non convertible to ascii, \"\n \"converting to a safe representation:\\n {!r}\".format(compat.safe_str(msg)),\n UnicodeWarning,\n )\n return msg\n\n\n@pytest.hookimpl(hookwrapper=True, tryfirst=True)\ndef pytest_runtest_protocol(item):\n with catch_warnings_for_item(\n config=item.config, ihook=item.ihook, when=\"runtest\", item=item\n ):\n yield\n\n\n@pytest.hookimpl(hookwrapper=True, tryfirst=True)\ndef pytest_collection(session):\n config = session.config\n with catch_warnings_for_item(\n config=config, ihook=config.hook, when=\"collect\", item=None\n ):\n yield\n\n\n@pytest.hookimpl(hookwrapper=True)\ndef pytest_terminal_summary(terminalreporter):\n config = terminalreporter.config\n with catch_warnings_for_item(\n config=config, ihook=config.hook, when=\"config\", item=None\n ):\n yield\n\n\ndef _issue_warning_captured(warning, hook, stacklevel):\n \"\"\"\n This function should be used instead of calling ``warnings.warn`` directly when we are in the \"configure\" stage:\n at this point the actual options might not have been set, so we manually trigger the pytest_warning_captured\n hook so we can display this warnings in the terminal. This is a hack until we can sort out #2891.\n\n :param warning: the warning instance.\n :param hook: the hook caller\n :param stacklevel: stacklevel forwarded to warnings.warn\n \"\"\"\n with warnings.catch_warnings(record=True) as records:\n warnings.simplefilter(\"always\", type(warning))\n warnings.warn(warning, stacklevel=stacklevel)\n hook.pytest_warning_captured.call_historic(\n kwargs=dict(warning_message=records[0], when=\"config\", item=None)\n )\n"},{"col":0,"comment":"null","endLoc":77,"header":"def contextmanager(func: Callable[_P, Iterator[_T_co]]) -> Callable[_P, _GeneratorContextManager[_T_co]]","id":2207,"name":"contextmanager","nodeType":"Function","startLoc":77,"text":"def contextmanager(func: Callable[_P, Iterator[_T_co]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ..."},{"id":2208,"name":"release-2.9.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.9.0\n============\n\npytest is a mature Python testing tool with more than a 1100 tests\nagainst itself, passing on many different interpreters and platforms.\n\nSee below for the changes and see docs at:\n\n http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n Anatoly Bubenkov\n Bruno Oliveira\n Buck Golemon\n David Vierra\n Florian Bruhin\n Galaczi Endre\n Georgy Dyuldin\n Lukas Bednar\n Luke Murphy\n Marcin Biernat\n Matt Williams\n Michael Aquilina\n Raphael Pierzina\n Ronny Pfannschmidt\n Ryan Wooden\n Tiemo Kieft\n TomV\n holger krekel\n jab\n\n\nHappy testing,\nThe py.test Development Team\n\n\n2.9.0 (compared to 2.8.7)\n-------------------------\n\n**New Features**\n\n* New ``pytest.mark.skip`` mark, which unconditionally skips marked tests.\n Thanks `@MichaelAquilina`_ for the complete PR (`#1040`_).\n\n* ``--doctest-glob`` may now be passed multiple times in the command-line.\n Thanks `@jab`_ and `@nicoddemus`_ for the PR.\n\n* New ``-rp`` and ``-rP`` reporting options give the summary and full output\n of passing tests, respectively. Thanks to `@codewarrior0`_ for the PR.\n\n* ``pytest.mark.xfail`` now has a ``strict`` option which makes ``XPASS``\n tests to fail the test suite, defaulting to ``False``. There's also a\n ``xfail_strict`` ini option that can be used to configure it project-wise.\n Thanks `@rabbbit`_ for the request and `@nicoddemus`_ for the PR (`#1355`_).\n\n* ``Parser.addini`` now supports options of type ``bool``. Thanks\n `@nicoddemus`_ for the PR.\n\n* New ``ALLOW_BYTES`` doctest option strips ``b`` prefixes from byte strings\n in doctest output (similar to ``ALLOW_UNICODE``).\n Thanks `@jaraco`_ for the request and `@nicoddemus`_ for the PR (`#1287`_).\n\n* give a hint on KeyboardInterrupt to use the --fulltrace option to show the errors,\n this fixes `#1366`_.\n Thanks to `@hpk42`_ for the report and `@RonnyPfannschmidt`_ for the PR.\n\n* catch IndexError exceptions when getting exception source location. This fixes\n pytest internal error for dynamically generated code (fixtures and tests)\n where source lines are fake by intention\n\n**Changes**\n\n* **Important**: `py.code `_ has been\n merged into the ``pytest`` repository as ``pytest._code``. This decision\n was made because ``py.code`` had very few uses outside ``pytest`` and the\n fact that it was in a different repository made it difficult to fix bugs on\n its code in a timely manner. The team hopes with this to be able to better\n refactor out and improve that code.\n This change shouldn't affect users, but it is useful to let users aware\n if they encounter any strange behavior.\n\n Keep in mind that the code for ``pytest._code`` is **private** and\n **experimental**, so you definitely should not import it explicitly!\n\n Please note that the original ``py.code`` is still available in\n `pylib `_.\n\n* ``pytest_enter_pdb`` now optionally receives the pytest config object.\n Thanks `@nicoddemus`_ for the PR.\n\n* Removed code and documentation for Python 2.5 or lower versions,\n including removal of the obsolete ``_pytest.assertion.oldinterpret`` module.\n Thanks `@nicoddemus`_ for the PR (`#1226`_).\n\n* Comparisons now always show up in full when ``CI`` or ``BUILD_NUMBER`` is\n found in the environment, even when -vv isn't used.\n Thanks `@The-Compiler`_ for the PR.\n\n* ``--lf`` and ``--ff`` now support long names: ``--last-failed`` and\n ``--failed-first`` respectively.\n Thanks `@MichaelAquilina`_ for the PR.\n\n* Added expected exceptions to pytest.raises fail message\n\n* Collection only displays progress (\"collecting X items\") when in a terminal.\n This avoids cluttering the output when using ``--color=yes`` to obtain\n colors in CI integrations systems (`#1397`_).\n\n**Bug Fixes**\n\n* The ``-s`` and ``-c`` options should now work under ``xdist``;\n ``Config.fromdictargs`` now represents its input much more faithfully.\n Thanks to `@bukzor`_ for the complete PR (`#680`_).\n\n* Fix (`#1290`_): support Python 3.5's ``@`` operator in assertion rewriting.\n Thanks `@Shinkenjoe`_ for report with test case and `@tomviner`_ for the PR.\n\n* Fix formatting utf-8 explanation messages (`#1379`_).\n Thanks `@biern`_ for the PR.\n\n* Fix `traceback style docs`_ to describe all of the available options\n (auto/long/short/line/native/no), with ``auto`` being the default since v2.6.\n Thanks `@hackebrot`_ for the PR.\n\n* Fix (`#1422`_): junit record_xml_property doesn't allow multiple records\n with same name.\n\n\n.. _`traceback style docs`: https://pytest.org/latest/usage.html#modifying-python-traceback-printing\n\n.. _#1422: https://github.com/pytest-dev/pytest/issues/1422\n.. _#1379: https://github.com/pytest-dev/pytest/issues/1379\n.. _#1366: https://github.com/pytest-dev/pytest/issues/1366\n.. _#1040: https://github.com/pytest-dev/pytest/pull/1040\n.. _#680: https://github.com/pytest-dev/pytest/issues/680\n.. _#1287: https://github.com/pytest-dev/pytest/pull/1287\n.. _#1226: https://github.com/pytest-dev/pytest/pull/1226\n.. _#1290: https://github.com/pytest-dev/pytest/pull/1290\n.. _#1355: https://github.com/pytest-dev/pytest/pull/1355\n.. _#1397: https://github.com/pytest-dev/pytest/issues/1397\n.. _@biern: https://github.com/biern\n.. _@MichaelAquilina: https://github.com/MichaelAquilina\n.. _@bukzor: https://github.com/bukzor\n.. _@hpk42: https://github.com/hpk42\n.. _@nicoddemus: https://github.com/nicoddemus\n.. _@jab: https://github.com/jab\n.. _@codewarrior0: https://github.com/codewarrior0\n.. _@jaraco: https://github.com/jaraco\n.. _@The-Compiler: https://github.com/The-Compiler\n.. _@Shinkenjoe: https://github.com/Shinkenjoe\n.. _@tomviner: https://github.com/tomviner\n.. _@RonnyPfannschmidt: https://github.com/RonnyPfannschmidt\n.. _@rabbbit: https://github.com/rabbbit\n.. _@hackebrot: https://github.com/hackebrot\n"},{"id":2209,"name":"release-3.9.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.9.2\n=======================================\n\npytest 3.9.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Ankit Goel\n* Anthony Sottile\n* Bruno Oliveira\n* Ronny Pfannschmidt\n* Vincent Barbaresi\n* ykantor\n\n\nHappy testing,\nThe pytest Development Team\n"},{"id":2210,"name":"testing/example_scripts/fixtures/fill_fixtures/test_conftest_funcargs_only_available_in_subdir/sub2","nodeType":"Package"},{"fileName":"__init__.py","filePath":"testing/example_scripts/fixtures/fill_fixtures/test_conftest_funcargs_only_available_in_subdir/sub2","id":2211,"nodeType":"File","text":""},{"className":"Action","col":0,"comment":"null","endLoc":356,"id":2212,"nodeType":"Class","startLoc":311,"text":"class Action(_AttributeHolder):\n option_strings: Sequence[str]\n dest: str\n nargs: int | str | None\n const: Any\n default: Any\n type: _ActionType | None\n choices: Iterable[Any] | None\n required: bool\n help: str | None\n metavar: str | tuple[str, ...] | None\n if sys.version_info >= (3, 13):\n def __init__(\n self,\n option_strings: Sequence[str],\n dest: str,\n nargs: int | str | None = None,\n const: _T | None = None,\n default: _T | str | None = None,\n type: Callable[[str], _T] | FileType | None = None,\n choices: Iterable[_T] | None = None,\n required: bool = False,\n help: str | None = None,\n metavar: str | tuple[str, ...] | None = None,\n deprecated: bool = False,\n ) -> None: ...\n else:\n def __init__(\n self,\n option_strings: Sequence[str],\n dest: str,\n nargs: int | str | None = None,\n const: _T | None = None,\n default: _T | str | None = None,\n type: Callable[[str], _T] | FileType | None = None,\n choices: Iterable[_T] | None = None,\n required: bool = False,\n help: str | None = None,\n metavar: str | tuple[str, ...] | None = None,\n ) -> None: ...\n\n def __call__(\n self, parser: ArgumentParser, namespace: Namespace, values: str | Sequence[Any] | None, option_string: str | None = None\n ) -> None: ...\n if sys.version_info >= (3, 9):\n def format_usage(self) -> str: ..."},{"className":"_AttributeHolder","col":0,"comment":"null","endLoc":64,"id":2213,"nodeType":"Class","startLoc":62,"text":"class _AttributeHolder:\n def _get_kwargs(self) -> list[tuple[str, Any]]: ...\n def _get_args(self) -> list[Any]: ..."},{"col":4,"comment":"null","endLoc":63,"header":"def _get_kwargs(self) -> list[tuple[str, Any]]","id":2214,"name":"_get_kwargs","nodeType":"Function","startLoc":63,"text":"def _get_kwargs(self) -> list[tuple[str, Any]]: ..."},{"col":4,"comment":"null","endLoc":64,"header":"def _get_args(self) -> list[Any]","id":2215,"name":"_get_args","nodeType":"Function","startLoc":64,"text":"def _get_args(self) -> list[Any]: ..."},{"col":8,"comment":"null","endLoc":350,"header":"def __init__(\n self,\n option_strings: Sequence[str],\n dest: str,\n nargs: int | str | None = None,\n const: _T | None = None,\n default: _T | str | None = None,\n type: Callable[[str], _T] | FileType | None = None,\n choices: Iterable[_T] | None = None,\n required: bool = False,\n help: str | None = None,\n metavar: str | tuple[str, ...] | None = None,\n ) -> None","id":2216,"name":"__init__","nodeType":"Function","startLoc":338,"text":"def __init__(\n self,\n option_strings: Sequence[str],\n dest: str,\n nargs: int | str | None = None,\n const: _T | None = None,\n default: _T | str | None = None,\n type: Callable[[str], _T] | FileType | None = None,\n choices: Iterable[_T] | None = None,\n required: bool = False,\n help: str | None = None,\n metavar: str | tuple[str, ...] | None = None,\n ) -> None: ..."},{"id":2217,"name":"release-3.10.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.10.0\n=======================================\n\nThe pytest team is proud to announce the 3.10.0 release!\n\npytest is a mature Python testing tool with more than a 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n https://docs.pytest.org/en/latest/changelog.html\n\nFor complete documentation, please visit:\n\n https://docs.pytest.org/en/latest/\n\nAs usual, you can upgrade from pypi via:\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Anders Hovmöller\n* Andreu Vallbona Plazas\n* Ankit Goel\n* Anthony Sottile\n* Bernardo Gomes\n* Brianna Laugher\n* Bruno Oliveira\n* Daniel Hahler\n* David Szotten\n* Mick Koch\n* Niclas Olofsson\n* Palash Chatterjee\n* Ronny Pfannschmidt\n* Sven-Hendrik Haase\n* Ville Skyttä\n* William Jamir Silva\n\n\nHappy testing,\nThe Pytest Development Team\n"},{"col":4,"comment":"null","endLoc":354,"header":"def __call__(\n self, parser: ArgumentParser, namespace: Namespace, values: str | Sequence[Any] | None, option_string: str | None = None\n ) -> None","id":2218,"name":"__call__","nodeType":"Function","startLoc":352,"text":"def __call__(\n self, parser: ArgumentParser, namespace: Namespace, values: str | Sequence[Any] | None, option_string: str | None = None\n ) -> None: ..."},{"col":8,"comment":"null","endLoc":356,"header":"def format_usage(self) -> str","id":2219,"name":"format_usage","nodeType":"Function","startLoc":356,"text":"def format_usage(self) -> str: ..."},{"attributeType":"Sequence","col":4,"comment":"null","endLoc":312,"id":2220,"name":"option_strings","nodeType":"Attribute","startLoc":312,"text":"option_strings"},{"id":2221,"name":"contents.rst","nodeType":"TextFile","path":"doc/en","text":".. _toc:\n\nFull pytest documentation\n===========================\n\n`Download latest version as PDF `_\n\n.. `Download latest version as EPUB `_\n\n.. toctree::\n :maxdepth: 2\n\n getting-started\n usage\n existingtestsuite\n assert\n fixture\n mark\n monkeypatch\n tmpdir\n capture\n warnings\n doctest\n skipping\n parametrize\n cache\n unittest\n nose\n xunit_setup\n plugins\n writing_plugins\n logging\n reference\n\n goodpractices\n flaky\n pythonpath\n customize\n example/index\n bash-completion\n\n backwards-compatibility\n deprecations\n py27-py34-deprecation\n historical-notes\n license\n contributing\n development_guide\n talks\n projects\n faq\n contact\n tidelift\n\n.. only:: html\n\n .. toctree::\n :maxdepth: 1\n\n announce/index\n\n.. only:: html\n\n .. toctree::\n :hidden:\n :maxdepth: 1\n\n changelog\n"},{"id":2222,"name":"testing/examples","nodeType":"Package"},{"fileName":"test_issue519.py","filePath":"testing/examples","id":2223,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ndef test_510(testdir):\n testdir.copy_example(\"issue_519.py\")\n testdir.runpytest(\"issue_519.py\")\n"},{"col":0,"comment":"null","endLoc":4,"header":"def test_510(testdir)","id":2224,"name":"test_510","nodeType":"Function","startLoc":2,"text":"def test_510(testdir):\n testdir.copy_example(\"issue_519.py\")\n testdir.runpytest(\"issue_519.py\")"},{"col":0,"comment":"finds all elements in root that begin with the prefix, case insensitive","endLoc":104,"header":"def find_prefixed(root, prefix)","id":2225,"name":"find_prefixed","nodeType":"Function","startLoc":99,"text":"def find_prefixed(root, prefix):\n \"\"\"finds all elements in root that begin with the prefix, case insensitive\"\"\"\n l_prefix = prefix.lower()\n for x in root.iterdir():\n if x.name.lower().startswith(l_prefix):\n yield x"},{"col":0,"comment":"\n :param iter: iterator over path names\n :param prefix: expected prefix of the path names\n :returns: the parts of the paths following the prefix\n ","endLoc":115,"header":"def extract_suffixes(iter, prefix)","id":2226,"name":"extract_suffixes","nodeType":"Function","startLoc":107,"text":"def extract_suffixes(iter, prefix):\n \"\"\"\n :param iter: iterator over path names\n :param prefix: expected prefix of the path names\n :returns: the parts of the paths following the prefix\n \"\"\"\n p_len = len(prefix)\n for p in iter:\n yield p.name[p_len:]"},{"col":0,"comment":"combines find_prefixes and extract_suffixes\n ","endLoc":121,"header":"def find_suffixes(root, prefix)","id":2227,"name":"find_suffixes","nodeType":"Function","startLoc":118,"text":"def find_suffixes(root, prefix):\n \"\"\"combines find_prefixes and extract_suffixes\n \"\"\"\n return extract_suffixes(find_prefixed(root, prefix), prefix)"},{"col":0,"comment":"parses number path suffixes, returns -1 on error","endLoc":129,"header":"def parse_num(maybe_num)","id":2228,"name":"parse_num","nodeType":"Function","startLoc":124,"text":"def parse_num(maybe_num):\n \"\"\"parses number path suffixes, returns -1 on error\"\"\"\n try:\n return int(maybe_num)\n except ValueError:\n return -1"},{"col":0,"comment":"null","endLoc":32,"header":"def test_help(testdir)","id":2229,"name":"test_help","nodeType":"Function","startLoc":21,"text":"def test_help(testdir):\n result = testdir.runpytest(\"--help\")\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n \"\"\"\n *-v*verbose*\n *setup.cfg*\n *minversion*\n *to see*markers*pytest --markers*\n *to see*fixtures*pytest --fixtures*\n \"\"\"\n )"},{"col":0,"comment":"null","endLoc":44,"header":"def test_hookvalidation_unknown(testdir)","id":2230,"name":"test_hookvalidation_unknown","nodeType":"Function","startLoc":35,"text":"def test_hookvalidation_unknown(testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_hello(xyz):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret != 0\n result.stdout.fnmatch_lines([\"*unknown hook*pytest_hello*\"])"},{"attributeType":"str","col":4,"comment":"null","endLoc":313,"id":2231,"name":"dest","nodeType":"Attribute","startLoc":313,"text":"dest"},{"col":0,"comment":"null","endLoc":57,"header":"def test_hookvalidation_optional(testdir)","id":2232,"name":"test_hookvalidation_optional","nodeType":"Function","startLoc":47,"text":"def test_hookvalidation_optional(testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.hookimpl(optionalhook=True)\n def pytest_hello(xyz):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED"},{"attributeType":"int | str | None","col":4,"comment":"null","endLoc":314,"id":2233,"name":"nargs","nodeType":"Attribute","startLoc":314,"text":"nargs"},{"col":0,"comment":"null","endLoc":62,"header":"def test_traceconfig(testdir)","id":2234,"name":"test_traceconfig","nodeType":"Function","startLoc":60,"text":"def test_traceconfig(testdir):\n result = testdir.runpytest(\"--traceconfig\")\n result.stdout.fnmatch_lines([\"*using*pytest*py*\", \"*active plugins*\"])"},{"attributeType":"null","col":4,"comment":"null","endLoc":315,"id":2235,"name":"const","nodeType":"Attribute","startLoc":315,"text":"const"},{"col":0,"comment":"null","endLoc":69,"header":"def test_debug(testdir, monkeypatch)","id":2236,"name":"test_debug","nodeType":"Function","startLoc":65,"text":"def test_debug(testdir, monkeypatch):\n result = testdir.runpytest_subprocess(\"--debug\")\n assert result.ret == EXIT_NOTESTSCOLLECTED\n p = testdir.tmpdir.join(\"pytestdebug.log\")\n assert \"pytest_sessionstart\" in p.read()"},{"fileName":"test_nose.py","filePath":"testing","id":2237,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pytest\n\n\ndef setup_module(mod):\n mod.nose = pytest.importorskip(\"nose\")\n\n\ndef test_nose_setup(testdir):\n p = testdir.makepyfile(\n \"\"\"\n values = []\n from nose.tools import with_setup\n\n @with_setup(lambda: values.append(1), lambda: values.append(2))\n def test_hello():\n assert values == [1]\n\n def test_world():\n assert values == [1,2]\n\n test_hello.setup = lambda: values.append(1)\n test_hello.teardown = lambda: values.append(2)\n \"\"\"\n )\n result = testdir.runpytest(p, \"-p\", \"nose\")\n result.assert_outcomes(passed=2)\n\n\ndef test_setup_func_with_setup_decorator():\n from _pytest.nose import call_optional\n\n values = []\n\n class A(object):\n @pytest.fixture(autouse=True)\n def f(self):\n values.append(1)\n\n call_optional(A(), \"f\")\n assert not values\n\n\ndef test_setup_func_not_callable():\n from _pytest.nose import call_optional\n\n class A(object):\n f = 1\n\n call_optional(A(), \"f\")\n\n\ndef test_nose_setup_func(testdir):\n p = testdir.makepyfile(\n \"\"\"\n from nose.tools import with_setup\n\n values = []\n\n def my_setup():\n a = 1\n values.append(a)\n\n def my_teardown():\n b = 2\n values.append(b)\n\n @with_setup(my_setup, my_teardown)\n def test_hello():\n print(values)\n assert values == [1]\n\n def test_world():\n print(values)\n assert values == [1,2]\n\n \"\"\"\n )\n result = testdir.runpytest(p, \"-p\", \"nose\")\n result.assert_outcomes(passed=2)\n\n\ndef test_nose_setup_func_failure(testdir):\n p = testdir.makepyfile(\n \"\"\"\n from nose.tools import with_setup\n\n values = []\n my_setup = lambda x: 1\n my_teardown = lambda x: 2\n\n @with_setup(my_setup, my_teardown)\n def test_hello():\n print(values)\n assert values == [1]\n\n def test_world():\n print(values)\n assert values == [1,2]\n\n \"\"\"\n )\n result = testdir.runpytest(p, \"-p\", \"nose\")\n result.stdout.fnmatch_lines([\"*TypeError: ()*\"])\n\n\ndef test_nose_setup_func_failure_2(testdir):\n testdir.makepyfile(\n \"\"\"\n values = []\n\n my_setup = 1\n my_teardown = 2\n\n def test_hello():\n assert values == []\n\n test_hello.setup = my_setup\n test_hello.teardown = my_teardown\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n\ndef test_nose_setup_partial(testdir):\n pytest.importorskip(\"functools\")\n p = testdir.makepyfile(\n \"\"\"\n from functools import partial\n\n values = []\n\n def my_setup(x):\n a = x\n values.append(a)\n\n def my_teardown(x):\n b = x\n values.append(b)\n\n my_setup_partial = partial(my_setup, 1)\n my_teardown_partial = partial(my_teardown, 2)\n\n def test_hello():\n print(values)\n assert values == [1]\n\n def test_world():\n print(values)\n assert values == [1,2]\n\n test_hello.setup = my_setup_partial\n test_hello.teardown = my_teardown_partial\n \"\"\"\n )\n result = testdir.runpytest(p, \"-p\", \"nose\")\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n\ndef test_module_level_setup(testdir):\n testdir.makepyfile(\n \"\"\"\n from nose.tools import with_setup\n items = {}\n\n def setup():\n items[1]=1\n\n def teardown():\n del items[1]\n\n def setup2():\n items[2] = 2\n\n def teardown2():\n del items[2]\n\n def test_setup_module_setup():\n assert items[1] == 1\n\n @with_setup(setup2, teardown2)\n def test_local_setup():\n assert items[2] == 2\n assert 1 not in items\n \"\"\"\n )\n result = testdir.runpytest(\"-p\", \"nose\")\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n\ndef test_nose_style_setup_teardown(testdir):\n testdir.makepyfile(\n \"\"\"\n values = []\n\n def setup_module():\n values.append(1)\n\n def teardown_module():\n del values[0]\n\n def test_hello():\n assert values == [1]\n\n def test_world():\n assert values == [1]\n \"\"\"\n )\n result = testdir.runpytest(\"-p\", \"nose\")\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n\ndef test_nose_setup_ordering(testdir):\n testdir.makepyfile(\n \"\"\"\n def setup_module(mod):\n mod.visited = True\n\n class TestClass(object):\n def setup(self):\n assert visited\n def test_first(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_apiwrapper_problem_issue260(testdir):\n # this would end up trying a call an optional teardown on the class\n # for plain unittests we dont want nose behaviour\n testdir.makepyfile(\n \"\"\"\n import unittest\n class TestCase(unittest.TestCase):\n def setup(self):\n #should not be called in unittest testcases\n assert 0, 'setup'\n def teardown(self):\n #should not be called in unittest testcases\n assert 0, 'teardown'\n def setUp(self):\n print('setup')\n def tearDown(self):\n print('teardown')\n def test_fun(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.assert_outcomes(passed=1)\n\n\ndef test_setup_teardown_linking_issue265(testdir):\n # we accidentally didnt integrate nose setupstate with normal setupstate\n # this test ensures that won't happen again\n testdir.makepyfile(\n '''\n import pytest\n\n class TestGeneric(object):\n def test_nothing(self):\n \"\"\"Tests the API of the implementation (for generic and specialized).\"\"\"\n\n @pytest.mark.skipif(\"True\", reason=\n \"Skip tests to check if teardown is skipped as well.\")\n class TestSkipTeardown(TestGeneric):\n\n def setup(self):\n \"\"\"Sets up my specialized implementation for $COOL_PLATFORM.\"\"\"\n raise Exception(\"should not call setup for skipped tests\")\n\n def teardown(self):\n \"\"\"Undoes the setup.\"\"\"\n raise Exception(\"should not call teardown for skipped tests\")\n '''\n )\n reprec = testdir.runpytest()\n reprec.assert_outcomes(passed=1, skipped=1)\n\n\ndef test_SkipTest_during_collection(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import nose\n raise nose.SkipTest(\"during collection\")\n def test_failing():\n assert False\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.assert_outcomes(skipped=1)\n\n\ndef test_SkipTest_in_test(testdir):\n testdir.makepyfile(\n \"\"\"\n import nose\n\n def test_skipping():\n raise nose.SkipTest(\"in test\")\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(skipped=1)\n\n\ndef test_istest_function_decorator(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import nose.tools\n @nose.tools.istest\n def not_test_prefix():\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.assert_outcomes(passed=1)\n\n\ndef test_nottest_function_decorator(testdir):\n testdir.makepyfile(\n \"\"\"\n import nose.tools\n @nose.tools.nottest\n def test_prefix():\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n assert not reprec.getfailedcollections()\n calls = reprec.getreports(\"pytest_runtest_logreport\")\n assert not calls\n\n\ndef test_istest_class_decorator(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import nose.tools\n @nose.tools.istest\n class NotTestPrefix(object):\n def test_method(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.assert_outcomes(passed=1)\n\n\ndef test_nottest_class_decorator(testdir):\n testdir.makepyfile(\n \"\"\"\n import nose.tools\n @nose.tools.nottest\n class TestPrefix(object):\n def test_method(self):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n assert not reprec.getfailedcollections()\n calls = reprec.getreports(\"pytest_runtest_logreport\")\n assert not calls\n\n\ndef test_skip_test_with_unicode(testdir):\n testdir.makepyfile(\n \"\"\"\n # -*- coding: utf-8 -*-\n import unittest\n class TestClass():\n def test_io(self):\n raise unittest.SkipTest(u'😊')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 skipped *\"])\n"},{"col":0,"comment":"null","endLoc":10,"header":"def setup_module(mod)","id":2238,"name":"setup_module","nodeType":"Function","startLoc":9,"text":"def setup_module(mod):\n mod.nose = pytest.importorskip(\"nose\")"},{"attributeType":"null","col":4,"comment":"null","endLoc":316,"id":2239,"name":"default","nodeType":"Attribute","startLoc":316,"text":"default"},{"attributeType":"(str) -> Any | FileType | str | None","col":4,"comment":"null","endLoc":317,"id":2240,"name":"type","nodeType":"Attribute","startLoc":317,"text":"type"},{"col":0,"comment":"null","endLoc":78,"header":"def test_PYTEST_DEBUG(testdir, monkeypatch)","id":2241,"name":"test_PYTEST_DEBUG","nodeType":"Function","startLoc":72,"text":"def test_PYTEST_DEBUG(testdir, monkeypatch):\n monkeypatch.setenv(\"PYTEST_DEBUG\", \"1\")\n result = testdir.runpytest_subprocess()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result.stderr.fnmatch_lines(\n [\"*pytest_plugin_registered*\", \"*manager*PluginManager*\"]\n )"},{"col":0,"comment":"null","endLoc":31,"header":"def test_nose_setup(testdir)","id":2242,"name":"test_nose_setup","nodeType":"Function","startLoc":13,"text":"def test_nose_setup(testdir):\n p = testdir.makepyfile(\n \"\"\"\n values = []\n from nose.tools import with_setup\n\n @with_setup(lambda: values.append(1), lambda: values.append(2))\n def test_hello():\n assert values == [1]\n\n def test_world():\n assert values == [1,2]\n\n test_hello.setup = lambda: values.append(1)\n test_hello.teardown = lambda: values.append(2)\n \"\"\"\n )\n result = testdir.runpytest(p, \"-p\", \"nose\")\n result.assert_outcomes(passed=2)"},{"attributeType":"Iterable | None","col":4,"comment":"null","endLoc":318,"id":2243,"name":"choices","nodeType":"Attribute","startLoc":318,"text":"choices"},{"className":"CwdSnapshot","col":0,"comment":"null","endLoc":438,"id":2244,"nodeType":"Class","startLoc":433,"text":"class CwdSnapshot(object):\n def __init__(self):\n self.__saved = os.getcwd()\n\n def restore(self):\n os.chdir(self.__saved)"},{"attributeType":"bool","col":4,"comment":"null","endLoc":319,"id":2245,"name":"required","nodeType":"Attribute","startLoc":319,"text":"required"},{"col":0,"comment":"null","endLoc":281,"header":"@hookimpl(hookwrapper=True)\ndef pytest_runtest_protocol(item)","id":2246,"name":"pytest_runtest_protocol","nodeType":"Function","startLoc":254,"text":"@hookimpl(hookwrapper=True)\ndef pytest_runtest_protocol(item):\n if isinstance(item, TestCaseFunction) and \"twisted.trial.unittest\" in sys.modules:\n ut = sys.modules[\"twisted.python.failure\"]\n Failure__init__ = ut.Failure.__init__\n check_testcase_implements_trial_reporter()\n\n def excstore(\n self, exc_value=None, exc_type=None, exc_tb=None, captureVars=None\n ):\n if exc_value is None:\n self._rawexcinfo = sys.exc_info()\n else:\n if exc_type is None:\n exc_type = type(exc_value)\n self._rawexcinfo = (exc_type, exc_value, exc_tb)\n try:\n Failure__init__(\n self, exc_value, exc_type, exc_tb, captureVars=captureVars\n )\n except TypeError:\n Failure__init__(self, exc_value, exc_type, exc_tb)\n\n ut.Failure.__init__ = excstore\n yield\n ut.Failure.__init__ = Failure__init__\n else:\n yield"},{"attributeType":"str | None","col":4,"comment":"null","endLoc":320,"id":2247,"name":"help","nodeType":"Attribute","startLoc":320,"text":"help"},{"col":0,"comment":"Validate syntax of --pdbcls option.","endLoc":25,"header":"def _validate_usepdb_cls(value)","id":2248,"name":"_validate_usepdb_cls","nodeType":"Function","startLoc":17,"text":"def _validate_usepdb_cls(value):\n \"\"\"Validate syntax of --pdbcls option.\"\"\"\n try:\n modname, classname = value.split(\":\")\n except ValueError:\n raise argparse.ArgumentTypeError(\n \"{!r} is not in the format 'modname:classname'\".format(value)\n )\n return (modname, classname)"},{"attributeType":"str | (str, ...) | None","col":4,"comment":"null","endLoc":321,"id":2249,"name":"metavar","nodeType":"Attribute","startLoc":321,"text":"metavar"},{"col":0,"comment":"null","endLoc":49,"header":"def pytest_addoption(parser)","id":2250,"name":"pytest_addoption","nodeType":"Function","startLoc":28,"text":"def pytest_addoption(parser):\n group = parser.getgroup(\"general\")\n group._addoption(\n \"--pdb\",\n dest=\"usepdb\",\n action=\"store_true\",\n help=\"start the interactive Python debugger on errors or KeyboardInterrupt.\",\n )\n group._addoption(\n \"--pdbcls\",\n dest=\"usepdb_cls\",\n metavar=\"modulename:classname\",\n type=_validate_usepdb_cls,\n help=\"start a custom interactive Python debugger on errors. \"\n \"For example: --pdbcls=IPython.terminal.debugger:TerminalPdb\",\n )\n group._addoption(\n \"--trace\",\n dest=\"trace\",\n action=\"store_true\",\n help=\"Immediately break when running each test.\",\n )"},{"col":0,"comment":"null","endLoc":291,"header":"def check_testcase_implements_trial_reporter(done=[])","id":2251,"name":"check_testcase_implements_trial_reporter","nodeType":"Function","startLoc":284,"text":"def check_testcase_implements_trial_reporter(done=[]):\n if done:\n return\n from zope.interface import classImplements\n from twisted.trial.itrial import IReporter\n\n classImplements(TestCaseFunction, IReporter)\n done.append(1)"},{"col":0,"comment":"null","endLoc":45,"header":"def test_setup_func_with_setup_decorator()","id":2252,"name":"test_setup_func_with_setup_decorator","nodeType":"Function","startLoc":34,"text":"def test_setup_func_with_setup_decorator():\n from _pytest.nose import call_optional\n\n values = []\n\n class A(object):\n @pytest.fixture(autouse=True)\n def f(self):\n values.append(1)\n\n call_optional(A(), \"f\")\n assert not values"},{"col":0,"comment":"null","endLoc":74,"header":"def pytest_configure(config)","id":2253,"name":"pytest_configure","nodeType":"Function","startLoc":52,"text":"def pytest_configure(config):\n if config.getvalue(\"trace\"):\n config.pluginmanager.register(PdbTrace(), \"pdbtrace\")\n if config.getvalue(\"usepdb\"):\n config.pluginmanager.register(PdbInvoke(), \"pdbinvoke\")\n\n pytestPDB._saved.append(\n (pdb.set_trace, pytestPDB._pluginmanager, pytestPDB._config)\n )\n pdb.set_trace = pytestPDB.set_trace\n pytestPDB._pluginmanager = config.pluginmanager\n pytestPDB._config = config\n\n # NOTE: not using pytest_unconfigure, since it might get called although\n # pytest_configure was not (if another plugin raises UsageError).\n def fin():\n (\n pdb.set_trace,\n pytestPDB._pluginmanager,\n pytestPDB._config,\n ) = pytestPDB._saved.pop()\n\n config._cleanup.append(fin)"},{"className":"PrintHelp","col":0,"comment":"Raised when pytest should print it's help to skip the rest of the\n argument parsing and validation.","endLoc":10,"id":2254,"nodeType":"Class","startLoc":6,"text":"class PrintHelp(Exception):\n \"\"\"Raised when pytest should print it's help to skip the rest of the\n argument parsing and validation.\"\"\"\n\n pass"},{"className":"HelpAction","col":0,"comment":"This is an argparse Action that will raise an exception in\n order to skip the rest of the argument parsing when --help is passed.\n This prevents argparse from quitting due to missing required arguments\n when any are defined, for example by ``pytest_addoption``.\n This is similar to the way that the builtin argparse --help option is\n implemented by raising SystemExit.\n ","endLoc":41,"id":2255,"nodeType":"Class","startLoc":17,"text":"class HelpAction(Action):\n \"\"\"This is an argparse Action that will raise an exception in\n order to skip the rest of the argument parsing when --help is passed.\n This prevents argparse from quitting due to missing required arguments\n when any are defined, for example by ``pytest_addoption``.\n This is similar to the way that the builtin argparse --help option is\n implemented by raising SystemExit.\n \"\"\"\n\n def __init__(self, option_strings, dest=None, default=False, help=None):\n super(HelpAction, self).__init__(\n option_strings=option_strings,\n dest=dest,\n const=True,\n default=default,\n nargs=0,\n help=help,\n )\n\n def __call__(self, parser, namespace, values, option_string=None):\n setattr(namespace, self.dest, self.const)\n\n # We should only skip the rest of the parsing after preparse is done\n if getattr(parser._parser, \"after_preparse\", False):\n raise PrintHelp"},{"col":4,"comment":"null","endLoc":34,"header":"def __init__(self, option_strings, dest=None, default=False, help=None)","id":2256,"name":"__init__","nodeType":"Function","startLoc":26,"text":"def __init__(self, option_strings, dest=None, default=False, help=None):\n super(HelpAction, self).__init__(\n option_strings=option_strings,\n dest=dest,\n const=True,\n default=default,\n nargs=0,\n help=help,\n )"},{"col":4,"comment":"needed due to python2.7 lacking the default argument for max","endLoc":136,"header":"def _max(iterable, default)","id":2259,"name":"_max","nodeType":"Function","startLoc":134,"text":"def _max(iterable, default):\n \"\"\"needed due to python2.7 lacking the default argument for max\"\"\"\n return reduce(max, iterable, default)"},{"col":0,"comment":"null","endLoc":62,"header":"def pytest_sessionstart(session)","id":2260,"name":"pytest_sessionstart","nodeType":"Function","startLoc":49,"text":"def pytest_sessionstart(session):\n import _pytest.python\n import _pytest.nodes\n\n scopename2class.update(\n {\n \"package\": _pytest.python.Package,\n \"class\": _pytest.python.Class,\n \"module\": _pytest.python.Module,\n \"function\": _pytest.nodes.Item,\n \"session\": _pytest.main.Session,\n }\n )\n session._fixturemanager = FixtureManager(session)"},{"col":0,"comment":"\n Copy of the warning._setoption function but does not escape arguments.\n ","endLoc":37,"header":"def _setoption(wmod, arg)","id":2261,"name":"_setoption","nodeType":"Function","startLoc":16,"text":"def _setoption(wmod, arg):\n \"\"\"\n Copy of the warning._setoption function but does not escape arguments.\n \"\"\"\n parts = arg.split(\":\")\n if len(parts) > 5:\n raise wmod._OptionError(\"too many fields (max 5): %r\" % (arg,))\n while len(parts) < 5:\n parts.append(\"\")\n action, message, category, module, lineno = [s.strip() for s in parts]\n action = wmod._getaction(action)\n category = wmod._getcategory(category)\n if lineno:\n try:\n lineno = int(lineno)\n if lineno < 0:\n raise ValueError\n except (ValueError, OverflowError):\n raise wmod._OptionError(\"invalid lineno %r\" % (lineno,))\n else:\n lineno = 0\n wmod.filterwarnings(action, message, category, module, lineno)"},{"col":0,"comment":"helper to create the current symlink\n\n it's full of race conditions that are reasonably ok to ignore\n for the context of best effort linking to the latest testrun\n\n the presumption being thatin case of much parallelism\n the inaccuracy is going to be acceptable\n ","endLoc":160,"header":"def _force_symlink(root, target, link_to)","id":2262,"name":"_force_symlink","nodeType":"Function","startLoc":143,"text":"def _force_symlink(root, target, link_to):\n \"\"\"helper to create the current symlink\n\n it's full of race conditions that are reasonably ok to ignore\n for the context of best effort linking to the latest testrun\n\n the presumption being thatin case of much parallelism\n the inaccuracy is going to be acceptable\n \"\"\"\n current_symlink = root.joinpath(target)\n try:\n current_symlink.unlink()\n except OSError:\n pass\n try:\n current_symlink.symlink_to(link_to)\n except Exception:\n pass"},{"className":"TestKeywordSelection","col":0,"comment":"null","endLoc":835,"id":2263,"nodeType":"Class","startLoc":707,"text":"class TestKeywordSelection(object):\n def test_select_simple(self, testdir):\n file_test = testdir.makepyfile(\n \"\"\"\n def test_one():\n assert 0\n class TestClass(object):\n def test_method_one(self):\n assert 42 == 43\n \"\"\"\n )\n\n def check(keyword, name):\n reprec = testdir.inline_run(\"-s\", \"-k\", keyword, file_test)\n passed, skipped, failed = reprec.listoutcomes()\n assert len(failed) == 1\n assert failed[0].nodeid.split(\"::\")[-1] == name\n assert len(reprec.getcalls(\"pytest_deselected\")) == 1\n\n for keyword in [\"test_one\", \"est_on\"]:\n check(keyword, \"test_one\")\n check(\"TestClass and test\", \"test_method_one\")\n\n @pytest.mark.parametrize(\n \"keyword\",\n [\n \"xxx\",\n \"xxx and test_2\",\n \"TestClass\",\n \"xxx and not test_1\",\n \"TestClass and test_2\",\n \"xxx and TestClass and test_2\",\n ],\n )\n def test_select_extra_keywords(self, testdir, keyword):\n p = testdir.makepyfile(\n test_select=\"\"\"\n def test_1():\n pass\n class TestClass(object):\n def test_2(self):\n pass\n \"\"\"\n )\n testdir.makepyfile(\n conftest=\"\"\"\n import pytest\n @pytest.hookimpl(hookwrapper=True)\n def pytest_pycollect_makeitem(name):\n outcome = yield\n if name == \"TestClass\":\n item = outcome.get_result()\n item.extra_keyword_matches.add(\"xxx\")\n \"\"\"\n )\n reprec = testdir.inline_run(p.dirpath(), \"-s\", \"-k\", keyword)\n print(\"keyword\", repr(keyword))\n passed, skipped, failed = reprec.listoutcomes()\n assert len(passed) == 1\n assert passed[0].nodeid.endswith(\"test_2\")\n dlist = reprec.getcalls(\"pytest_deselected\")\n assert len(dlist) == 1\n assert dlist[0].items[0].name == \"test_1\"\n\n def test_select_starton(self, testdir):\n threepass = testdir.makepyfile(\n test_threepass=\"\"\"\n def test_one(): assert 1\n def test_two(): assert 1\n def test_three(): assert 1\n \"\"\"\n )\n reprec = testdir.inline_run(\"-k\", \"test_two:\", threepass)\n passed, skipped, failed = reprec.listoutcomes()\n assert len(passed) == 2\n assert not failed\n dlist = reprec.getcalls(\"pytest_deselected\")\n assert len(dlist) == 1\n item = dlist[0].items[0]\n assert item.name == \"test_one\"\n\n def test_keyword_extra(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_one():\n assert 0\n test_one.mykeyword = True\n \"\"\"\n )\n reprec = testdir.inline_run(\"-k\", \"mykeyword\", p)\n passed, skipped, failed = reprec.countoutcomes()\n assert failed == 1\n\n @pytest.mark.xfail\n def test_keyword_extra_dash(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_one():\n assert 0\n test_one.mykeyword = True\n \"\"\"\n )\n # with argparse the argument to an option cannot\n # start with '-'\n reprec = testdir.inline_run(\"-k\", \"-mykeyword\", p)\n passed, skipped, failed = reprec.countoutcomes()\n assert passed + skipped + failed == 0\n\n def test_no_magic_values(self, testdir):\n \"\"\"Make sure the tests do not match on magic values,\n no double underscored values, like '__dict__',\n and no instance values, like '()'.\n \"\"\"\n p = testdir.makepyfile(\n \"\"\"\n def test_one(): assert 1\n \"\"\"\n )\n\n def assert_test_is_not_selected(keyword):\n reprec = testdir.inline_run(\"-k\", keyword, p)\n passed, skipped, failed = reprec.countoutcomes()\n dlist = reprec.getcalls(\"pytest_deselected\")\n assert passed + skipped + failed == 0\n deselected_tests = dlist[0].items\n assert len(deselected_tests) == 1\n\n assert_test_is_not_selected(\"__\")\n assert_test_is_not_selected(\"()\")"},{"col":4,"comment":"null","endLoc":728,"header":"def test_select_simple(self, testdir)","id":2264,"name":"test_select_simple","nodeType":"Function","startLoc":708,"text":"def test_select_simple(self, testdir):\n file_test = testdir.makepyfile(\n \"\"\"\n def test_one():\n assert 0\n class TestClass(object):\n def test_method_one(self):\n assert 42 == 43\n \"\"\"\n )\n\n def check(keyword, name):\n reprec = testdir.inline_run(\"-s\", \"-k\", keyword, file_test)\n passed, skipped, failed = reprec.listoutcomes()\n assert len(failed) == 1\n assert failed[0].nodeid.split(\"::\")[-1] == name\n assert len(reprec.getcalls(\"pytest_deselected\")) == 1\n\n for keyword in [\"test_one\", \"est_on\"]:\n check(keyword, \"test_one\")\n check(\"TestClass and test\", \"test_method_one\")"},{"col":0,"comment":"create a directory with an increased number as suffix for the given prefix","endLoc":181,"header":"def make_numbered_dir(root, prefix)","id":2265,"name":"make_numbered_dir","nodeType":"Function","startLoc":163,"text":"def make_numbered_dir(root, prefix):\n \"\"\"create a directory with an increased number as suffix for the given prefix\"\"\"\n for i in range(10):\n # try up to 10 times to create the folder\n max_existing = _max(map(parse_num, find_suffixes(root, prefix)), default=-1)\n new_number = max_existing + 1\n new_path = root.joinpath(\"{}{}\".format(prefix, new_number))\n try:\n new_path.mkdir()\n except Exception:\n pass\n else:\n _force_symlink(root, prefix + \"current\", new_path)\n return new_path\n else:\n raise EnvironmentError(\n \"could not create numbered dir with prefix \"\n \"{prefix} in {root} after 10 tries\".format(prefix=prefix, root=root)\n )"},{"className":"TestRequestMarking","col":0,"comment":"null","endLoc":972,"id":2266,"nodeType":"Class","startLoc":905,"text":"class TestRequestMarking(object):\n def test_applymarker(self, testdir):\n item1, item2 = testdir.getitems(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def something(request):\n pass\n class TestClass(object):\n def test_func1(self, something):\n pass\n def test_func2(self, something):\n pass\n \"\"\"\n )\n req1 = fixtures.FixtureRequest(item1)\n assert \"xfail\" not in item1.keywords\n req1.applymarker(pytest.mark.xfail)\n assert \"xfail\" in item1.keywords\n assert \"skipif\" not in item1.keywords\n req1.applymarker(pytest.mark.skipif)\n assert \"skipif\" in item1.keywords\n with pytest.raises(ValueError):\n req1.applymarker(42)\n\n def test_accesskeywords(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture()\n def keywords(request):\n return request.keywords\n @pytest.mark.XYZ\n def test_function(keywords):\n assert keywords[\"XYZ\"]\n assert \"abc\" not in keywords\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_accessmarker_dynamic(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture()\n def keywords(request):\n return request.keywords\n\n @pytest.fixture(scope=\"class\", autouse=True)\n def marking(request):\n request.applymarker(pytest.mark.XYZ(\"hello\"))\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_fun1(keywords):\n assert keywords[\"XYZ\"] is not None\n assert \"abc\" not in keywords\n def test_fun2(keywords):\n assert keywords[\"XYZ\"] is not None\n assert \"abc\" not in keywords\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)"},{"col":4,"comment":"null","endLoc":929,"header":"def test_applymarker(self, testdir)","id":2268,"name":"test_applymarker","nodeType":"Function","startLoc":906,"text":"def test_applymarker(self, testdir):\n item1, item2 = testdir.getitems(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def something(request):\n pass\n class TestClass(object):\n def test_func1(self, something):\n pass\n def test_func2(self, something):\n pass\n \"\"\"\n )\n req1 = fixtures.FixtureRequest(item1)\n assert \"xfail\" not in item1.keywords\n req1.applymarker(pytest.mark.xfail)\n assert \"xfail\" in item1.keywords\n assert \"skipif\" not in item1.keywords\n req1.applymarker(pytest.mark.skipif)\n assert \"skipif\" in item1.keywords\n with pytest.raises(ValueError):\n req1.applymarker(42)"},{"col":4,"comment":"null","endLoc":769,"header":"@pytest.mark.parametrize(\n \"keyword\",\n [\n \"xxx\",\n \"xxx and test_2\",\n \"TestClass\",\n \"xxx and not test_1\",\n \"TestClass and test_2\",\n \"xxx and TestClass and test_2\",\n ],\n )\n def test_select_extra_keywords(self, testdir, keyword)","id":2269,"name":"test_select_extra_keywords","nodeType":"Function","startLoc":730,"text":"@pytest.mark.parametrize(\n \"keyword\",\n [\n \"xxx\",\n \"xxx and test_2\",\n \"TestClass\",\n \"xxx and not test_1\",\n \"TestClass and test_2\",\n \"xxx and TestClass and test_2\",\n ],\n )\n def test_select_extra_keywords(self, testdir, keyword):\n p = testdir.makepyfile(\n test_select=\"\"\"\n def test_1():\n pass\n class TestClass(object):\n def test_2(self):\n pass\n \"\"\"\n )\n testdir.makepyfile(\n conftest=\"\"\"\n import pytest\n @pytest.hookimpl(hookwrapper=True)\n def pytest_pycollect_makeitem(name):\n outcome = yield\n if name == \"TestClass\":\n item = outcome.get_result()\n item.extra_keyword_matches.add(\"xxx\")\n \"\"\"\n )\n reprec = testdir.inline_run(p.dirpath(), \"-s\", \"-k\", keyword)\n print(\"keyword\", repr(keyword))\n passed, skipped, failed = reprec.listoutcomes()\n assert len(passed) == 1\n assert passed[0].nodeid.endswith(\"test_2\")\n dlist = reprec.getcalls(\"pytest_deselected\")\n assert len(dlist) == 1\n assert dlist[0].items[0].name == \"test_1\""},{"col":4,"comment":"null","endLoc":786,"header":"def test_select_starton(self, testdir)","id":2270,"name":"test_select_starton","nodeType":"Function","startLoc":771,"text":"def test_select_starton(self, testdir):\n threepass = testdir.makepyfile(\n test_threepass=\"\"\"\n def test_one(): assert 1\n def test_two(): assert 1\n def test_three(): assert 1\n \"\"\"\n )\n reprec = testdir.inline_run(\"-k\", \"test_two:\", threepass)\n passed, skipped, failed = reprec.listoutcomes()\n assert len(passed) == 2\n assert not failed\n dlist = reprec.getcalls(\"pytest_deselected\")\n assert len(dlist) == 1\n item = dlist[0].items[0]\n assert item.name == \"test_one\""},{"col":4,"comment":"null","endLoc":945,"header":"def test_accesskeywords(self, testdir)","id":2271,"name":"test_accesskeywords","nodeType":"Function","startLoc":931,"text":"def test_accesskeywords(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture()\n def keywords(request):\n return request.keywords\n @pytest.mark.XYZ\n def test_function(keywords):\n assert keywords[\"XYZ\"]\n assert \"abc\" not in keywords\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":"null","endLoc":798,"header":"def test_keyword_extra(self, testdir)","id":2272,"name":"test_keyword_extra","nodeType":"Function","startLoc":788,"text":"def test_keyword_extra(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_one():\n assert 0\n test_one.mykeyword = True\n \"\"\"\n )\n reprec = testdir.inline_run(\"-k\", \"mykeyword\", p)\n passed, skipped, failed = reprec.countoutcomes()\n assert failed == 1"},{"col":4,"comment":"null","endLoc":972,"header":"def test_accessmarker_dynamic(self, testdir)","id":2273,"name":"test_accessmarker_dynamic","nodeType":"Function","startLoc":947,"text":"def test_accessmarker_dynamic(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture()\n def keywords(request):\n return request.keywords\n\n @pytest.fixture(scope=\"class\", autouse=True)\n def marking(request):\n request.applymarker(pytest.mark.XYZ(\"hello\"))\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_fun1(keywords):\n assert keywords[\"XYZ\"] is not None\n assert \"abc\" not in keywords\n def test_fun2(keywords):\n assert keywords[\"XYZ\"] is not None\n assert \"abc\" not in keywords\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)"},{"col":4,"comment":"null","endLoc":813,"header":"@pytest.mark.xfail\n def test_keyword_extra_dash(self, testdir)","id":2274,"name":"test_keyword_extra_dash","nodeType":"Function","startLoc":800,"text":"@pytest.mark.xfail\n def test_keyword_extra_dash(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_one():\n assert 0\n test_one.mykeyword = True\n \"\"\"\n )\n # with argparse the argument to an option cannot\n # start with '-'\n reprec = testdir.inline_run(\"-k\", \"-mykeyword\", p)\n passed, skipped, failed = reprec.countoutcomes()\n assert passed + skipped + failed == 0"},{"className":"TestFixtureUsages","col":0,"comment":"null","endLoc":1303,"id":2275,"nodeType":"Class","startLoc":975,"text":"class TestFixtureUsages(object):\n def test_noargfixturedec(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def arg1():\n return 1\n\n def test_func(arg1):\n assert arg1 == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_receives_funcargs(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture()\n def arg1():\n return 1\n\n @pytest.fixture()\n def arg2(arg1):\n return arg1 + 1\n\n def test_add(arg2):\n assert arg2 == 2\n def test_all(arg1, arg2):\n assert arg1 == 1\n assert arg2 == 2\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_receives_funcargs_scope_mismatch(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=\"function\")\n def arg1():\n return 1\n\n @pytest.fixture(scope=\"module\")\n def arg2(arg1):\n return arg1 + 1\n\n def test_add(arg2):\n assert arg2 == 2\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*ScopeMismatch*involved factories*\",\n \"test_receives_funcargs_scope_mismatch.py:6: def arg2(arg1)\",\n \"test_receives_funcargs_scope_mismatch.py:2: def arg1()\",\n \"*1 error*\",\n ]\n )\n\n def test_receives_funcargs_scope_mismatch_issue660(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=\"function\")\n def arg1():\n return 1\n\n @pytest.fixture(scope=\"module\")\n def arg2(arg1):\n return arg1 + 1\n\n def test_add(arg1, arg2):\n assert arg2 == 2\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"*ScopeMismatch*involved factories*\", \"* def arg2*\", \"*1 error*\"]\n )\n\n def test_invalid_scope(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=\"functions\")\n def badscope():\n pass\n\n def test_nothing(badscope):\n pass\n \"\"\"\n )\n result = testdir.runpytest_inprocess()\n result.stdout.fnmatch_lines(\n \"*Fixture 'badscope' from test_invalid_scope.py got an unexpected scope value 'functions'\"\n )\n\n def test_funcarg_parametrized_and_used_twice(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(params=[1,2])\n def arg1(request):\n values.append(1)\n return request.param\n\n @pytest.fixture()\n def arg2(arg1):\n return arg1 + 1\n\n def test_add(arg1, arg2):\n assert arg2 == arg1 + 1\n assert len(values) == arg1\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n def test_factory_uses_unknown_funcarg_as_dependency_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture()\n def fail(missing):\n return\n\n @pytest.fixture()\n def call_fail(fail):\n return\n\n def test_missing(call_fail):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n \"\"\"\n *pytest.fixture()*\n *def call_fail(fail)*\n *pytest.fixture()*\n *def fail*\n *fixture*'missing'*not found*\n \"\"\"\n )\n\n def test_factory_setup_as_classes_fails(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n class arg1(object):\n def __init__(self, request):\n self.x = 1\n arg1 = pytest.fixture()(arg1)\n\n \"\"\"\n )\n reprec = testdir.inline_run()\n values = reprec.getfailedcollections()\n assert len(values) == 1\n\n @pytest.mark.filterwarnings(\"ignore::pytest.PytestDeprecationWarning\")\n def test_request_can_be_overridden(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture()\n def request(request):\n request.a = 1\n return request\n def test_request(request):\n assert request.a == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_usefixtures_marker(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n values = []\n\n @pytest.fixture(scope=\"class\")\n def myfix(request):\n request.cls.hello = \"world\"\n values.append(1)\n\n class TestClass(object):\n def test_one(self):\n assert self.hello == \"world\"\n assert len(values) == 1\n def test_two(self):\n assert self.hello == \"world\"\n assert len(values) == 1\n pytest.mark.usefixtures(\"myfix\")(TestClass)\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_usefixtures_ini(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n usefixtures = myfix\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"class\")\n def myfix(request):\n request.cls.hello = \"world\"\n\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n class TestClass(object):\n def test_one(self):\n assert self.hello == \"world\"\n def test_two(self):\n assert self.hello == \"world\"\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_usefixtures_seen_in_showmarkers(self, testdir):\n result = testdir.runpytest(\"--markers\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *usefixtures(fixturename1*mark tests*fixtures*\n \"\"\"\n )\n\n def test_request_instance_issue203(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n class TestClass(object):\n @pytest.fixture\n def setup1(self, request):\n assert self == request.instance\n self.arg1 = 1\n def test_hello(self, setup1):\n assert self.arg1 == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_fixture_parametrized_with_iterator(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n values = []\n def f():\n yield 1\n yield 2\n dec = pytest.fixture(scope=\"module\", params=f())\n\n @dec\n def arg(request):\n return request.param\n @dec\n def arg2(request):\n return request.param\n\n def test_1(arg):\n values.append(arg)\n def test_2(arg2):\n values.append(arg2*10)\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\")\n reprec.assertoutcome(passed=4)\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n assert values == [1, 2, 10, 20]\n\n def test_setup_functions_as_fixtures(self, testdir):\n \"\"\"Ensure setup_* methods obey fixture scope rules (#517, #3094).\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n DB_INITIALIZED = None\n\n @pytest.yield_fixture(scope=\"session\", autouse=True)\n def db():\n global DB_INITIALIZED\n DB_INITIALIZED = True\n yield\n DB_INITIALIZED = False\n\n def setup_module():\n assert DB_INITIALIZED\n\n def teardown_module():\n assert DB_INITIALIZED\n\n class TestClass(object):\n\n def setup_method(self, method):\n assert DB_INITIALIZED\n\n def teardown_method(self, method):\n assert DB_INITIALIZED\n\n def test_printer_1(self):\n pass\n\n def test_printer_2(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed in *\"])"},{"col":4,"comment":"null","endLoc":989,"header":"def test_noargfixturedec(self, testdir)","id":2276,"name":"test_noargfixturedec","nodeType":"Function","startLoc":976,"text":"def test_noargfixturedec(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def arg1():\n return 1\n\n def test_func(arg1):\n assert arg1 == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":0,"comment":"","endLoc":2,"header":"unittest.py#","id":2278,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" discovery and running of std-library \"unittest\" style tests. \"\"\""},{"col":4,"comment":"Make sure the tests do not match on magic values,\n no double underscored values, like '__dict__',\n and no instance values, like '()'.\n ","endLoc":835,"header":"def test_no_magic_values(self, testdir)","id":2279,"name":"test_no_magic_values","nodeType":"Function","startLoc":815,"text":"def test_no_magic_values(self, testdir):\n \"\"\"Make sure the tests do not match on magic values,\n no double underscored values, like '__dict__',\n and no instance values, like '()'.\n \"\"\"\n p = testdir.makepyfile(\n \"\"\"\n def test_one(): assert 1\n \"\"\"\n )\n\n def assert_test_is_not_selected(keyword):\n reprec = testdir.inline_run(\"-k\", keyword, p)\n passed, skipped, failed = reprec.countoutcomes()\n dlist = reprec.getcalls(\"pytest_deselected\")\n assert passed + skipped + failed == 0\n deselected_tests = dlist[0].items\n assert len(deselected_tests) == 1\n\n assert_test_is_not_selected(\"__\")\n assert_test_is_not_selected(\"()\")"},{"col":4,"comment":"null","endLoc":1011,"header":"def test_receives_funcargs(self, testdir)","id":2280,"name":"test_receives_funcargs","nodeType":"Function","startLoc":991,"text":"def test_receives_funcargs(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture()\n def arg1():\n return 1\n\n @pytest.fixture()\n def arg2(arg1):\n return arg1 + 1\n\n def test_add(arg2):\n assert arg2 == 2\n def test_all(arg1, arg2):\n assert arg1 == 1\n assert arg2 == 2\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)"},{"col":0,"comment":"","endLoc":2,"header":"debugging.py#","id":2281,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" interactive debugging with PDB, the Python Debugger. \"\"\""},{"col":4,"comment":"null","endLoc":1037,"header":"def test_receives_funcargs_scope_mismatch(self, testdir)","id":2282,"name":"test_receives_funcargs_scope_mismatch","nodeType":"Function","startLoc":1013,"text":"def test_receives_funcargs_scope_mismatch(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=\"function\")\n def arg1():\n return 1\n\n @pytest.fixture(scope=\"module\")\n def arg2(arg1):\n return arg1 + 1\n\n def test_add(arg2):\n assert arg2 == 2\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*ScopeMismatch*involved factories*\",\n \"test_receives_funcargs_scope_mismatch.py:6: def arg2(arg1)\",\n \"test_receives_funcargs_scope_mismatch.py:2: def arg1()\",\n \"*1 error*\",\n ]\n )"},{"id":2284,"name":"release-3.4.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.4.2\n=======================================\n\npytest 3.4.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Allan Feldman\n* Bruno Oliveira\n* Florian Bruhin\n* Jason R. Coombs\n* Kyle Altendorf\n* Maik Figura\n* Ronny Pfannschmidt\n* codetriage-readme-bot\n* feuillemorte\n* joshm91\n* mike\n\n\nHappy testing,\nThe pytest Development Team\n"},{"id":2285,"name":"release-2.2.4.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.2.4: bug fixes, better junitxml/unittest/python3 compat\n===========================================================================\n\npytest-2.2.4 is a minor backward-compatible release of the versatile\npy.test testing tool. It contains bug fixes and a few refinements\nto junitxml reporting, better unittest- and python3 compatibility.\n\nFor general information see here:\n\n http://pytest.org/\n\nTo install or upgrade pytest:\n\n pip install -U pytest # or\n easy_install -U pytest\n\nSpecial thanks for helping on this release to Ronny Pfannschmidt\nand Benjamin Peterson and the contributors of issues.\n\nbest,\nholger krekel\n\nChanges between 2.2.3 and 2.2.4\n-----------------------------------\n\n- fix error message for rewritten assertions involving the % operator\n- fix issue 126: correctly match all invalid xml characters for junitxml\n binary escape\n- fix issue with unittest: now @unittest.expectedFailure markers should\n be processed correctly (you can also use @pytest.mark markers)\n- document integration with the extended distribute/setuptools test commands\n- fix issue 140: properly get the real functions\n of bound classmethods for setup/teardown_class\n- fix issue #141: switch from the deceased paste.pocoo.org to bpaste.net\n- fix issue #143: call unconfigure/sessionfinish always when\n configure/sessionstart where called\n- fix issue #144: better mangle test ids to junitxml classnames\n- upgrade distribute_setup.py to 0.6.27\n"},{"className":"TestMarkDecorator","col":0,"comment":"null","endLoc":849,"id":2286,"nodeType":"Class","startLoc":838,"text":"class TestMarkDecorator(object):\n @pytest.mark.parametrize(\n \"lhs, rhs, expected\",\n [\n (pytest.mark.foo(), pytest.mark.foo(), True),\n (pytest.mark.foo(), pytest.mark.bar(), False),\n (pytest.mark.foo(), \"bar\", False),\n (\"foo\", pytest.mark.bar(), False),\n ],\n )\n def test__eq__(self, lhs, rhs, expected):\n assert (lhs == rhs) == expected"},{"col":4,"comment":"null","endLoc":1058,"header":"def test_receives_funcargs_scope_mismatch_issue660(self, testdir)","id":2287,"name":"test_receives_funcargs_scope_mismatch_issue660","nodeType":"Function","startLoc":1039,"text":"def test_receives_funcargs_scope_mismatch_issue660(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=\"function\")\n def arg1():\n return 1\n\n @pytest.fixture(scope=\"module\")\n def arg2(arg1):\n return arg1 + 1\n\n def test_add(arg1, arg2):\n assert arg2 == 2\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"*ScopeMismatch*involved factories*\", \"* def arg2*\", \"*1 error*\"]\n )"},{"col":4,"comment":"null","endLoc":849,"header":"@pytest.mark.parametrize(\n \"lhs, rhs, expected\",\n [\n (pytest.mark.foo(), pytest.mark.foo(), True),\n (pytest.mark.foo(), pytest.mark.bar(), False),\n (pytest.mark.foo(), \"bar\", False),\n (\"foo\", pytest.mark.bar(), False),\n ],\n )\n def test__eq__(self, lhs, rhs, expected)","id":2288,"name":"test__eq__","nodeType":"Function","startLoc":839,"text":"@pytest.mark.parametrize(\n \"lhs, rhs, expected\",\n [\n (pytest.mark.foo(), pytest.mark.foo(), True),\n (pytest.mark.foo(), pytest.mark.bar(), False),\n (pytest.mark.foo(), \"bar\", False),\n (\"foo\", pytest.mark.bar(), False),\n ],\n )\n def test__eq__(self, lhs, rhs, expected):\n assert (lhs == rhs) == expected"},{"id":2289,"name":"monkeypatch.rst","nodeType":"TextFile","path":"doc/en","text":"\nMonkeypatching/mocking modules and environments\n================================================================\n\n.. currentmodule:: _pytest.monkeypatch\n\nSometimes tests need to invoke functionality which depends\non global settings or which invokes code which cannot be easily\ntested such as network access. The ``monkeypatch`` fixture\nhelps you to safely set/delete an attribute, dictionary item or\nenvironment variable or to modify ``sys.path`` for importing.\nSee the `monkeypatch blog post`_ for some introduction material\nand a discussion of its motivation.\n\n.. _`monkeypatch blog post`: http://tetamap.wordpress.com/2009/03/03/monkeypatching-in-unit-tests-done-right/\n\n\nSimple example: monkeypatching functions\n----------------------------------------\n\nIf you want to pretend that ``os.expanduser`` returns a certain\ndirectory, you can use the :py:meth:`monkeypatch.setattr` method to\npatch this function before calling into a function which uses it::\n\n # content of test_module.py\n import os.path\n def getssh(): # pseudo application code\n return os.path.join(os.path.expanduser(\"~admin\"), '.ssh')\n\n def test_mytest(monkeypatch):\n def mockreturn(path):\n return '/abc'\n monkeypatch.setattr(os.path, 'expanduser', mockreturn)\n x = getssh()\n assert x == '/abc/.ssh'\n\nHere our test function monkeypatches ``os.path.expanduser`` and\nthen calls into a function that calls it. After the test function\nfinishes the ``os.path.expanduser`` modification will be undone.\n\nGlobal patch example: preventing \"requests\" from remote operations\n------------------------------------------------------------------\n\nIf you want to prevent the \"requests\" library from performing http\nrequests in all your tests, you can do::\n\n # content of conftest.py\n import pytest\n @pytest.fixture(autouse=True)\n def no_requests(monkeypatch):\n monkeypatch.delattr(\"requests.sessions.Session.request\")\n\nThis autouse fixture will be executed for each test function and it\nwill delete the method ``request.session.Session.request``\nso that any attempts within tests to create http requests will fail.\n\n\n.. note::\n\n Be advised that it is not recommended to patch builtin functions such as ``open``,\n ``compile``, etc., because it might break pytest's internals. If that's\n unavoidable, passing ``--tb=native``, ``--assert=plain`` and ``--capture=no`` might\n help although there's no guarantee.\n\n.. note::\n\n Mind that patching ``stdlib`` functions and some third-party libraries used by pytest\n might break pytest itself, therefore in those cases it is recommended to use\n :meth:`MonkeyPatch.context` to limit the patching to the block you want tested:\n\n .. code-block:: python\n\n import functools\n\n\n def test_partial(monkeypatch):\n with monkeypatch.context() as m:\n m.setattr(functools, \"partial\", 3)\n assert functools.partial == 3\n\n See issue `#3290 `_ for details.\n\n\nMonkeypatching environment variables\n------------------------------------\n\nIf you are working with environment variables you often need to safely change the values\nor delete them from the system for testing purposes. ``Monkeypatch`` provides a mechanism\nto do this using the ``setenv`` and ``delenv`` method. Our example code to test:\n\n.. code-block:: python\n\n # contents of our original code file e.g. code.py\n import os\n\n\n def get_os_user_lower():\n \"\"\"Simple retrieval function.\n Returns lowercase USER or raises EnvironmentError.\"\"\"\n username = os.getenv(\"USER\")\n\n if username is None:\n raise EnvironmentError(\"USER environment is not set.\")\n\n return username.lower()\n\nThere are two potential paths. First, the ``USER`` environment variable is set to a\nvalue. Second, the ``USER`` environment variable does not exist. Using ``monkeypatch``\nboth paths can be safely tested without impacting the running environment:\n\n.. code-block:: python\n\n # contents of our test file e.g. test_code.py\n import pytest\n\n\n def test_upper_to_lower(monkeypatch):\n \"\"\"Set the USER env var to assert the behavior.\"\"\"\n monkeypatch.setenv(\"USER\", \"TestingUser\")\n assert get_os_user_lower() == \"testinguser\"\n\n\n def test_raise_exception(monkeypatch):\n \"\"\"Remove the USER env var and assert EnvironmentError is raised.\"\"\"\n monkeypatch.delenv(\"USER\", raising=False)\n\n with pytest.raises(EnvironmentError):\n _ = get_os_user_lower()\n\nThis behavior can be moved into ``fixture`` structures and shared across tests:\n\n.. code-block:: python\n\n import pytest\n\n\n @pytest.fixture\n def mock_env_user(monkeypatch):\n monkeypatch.setenv(\"USER\", \"TestingUser\")\n\n\n @pytest.fixture\n def mock_env_missing(monkeypatch):\n monkeypatch.delenv(\"USER\", raising=False)\n\n\n # Notice the tests reference the fixtures for mocks\n def test_upper_to_lower(mock_env_user):\n assert get_os_user_lower() == \"testinguser\"\n\n\n def test_raise_exception(mock_env_missing):\n with pytest.raises(EnvironmentError):\n _ = get_os_user_lower()\n\n\n\n.. currentmodule:: _pytest.monkeypatch\n\nAPI Reference\n-------------\n\nConsult the docs for the :class:`MonkeyPatch` class.\n"},{"col":4,"comment":"null","endLoc":1075,"header":"def test_invalid_scope(self, testdir)","id":2290,"name":"test_invalid_scope","nodeType":"Function","startLoc":1060,"text":"def test_invalid_scope(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=\"functions\")\n def badscope():\n pass\n\n def test_nothing(badscope):\n pass\n \"\"\"\n )\n result = testdir.runpytest_inprocess()\n result.stdout.fnmatch_lines(\n \"*Fixture 'badscope' from test_invalid_scope.py got an unexpected scope value 'functions'\"\n )"},{"id":2291,"name":"release-3.6.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.6.2\n=======================================\n\npytest 3.6.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Alan Velasco\n* Alex Barbato\n* Anthony Sottile\n* Bartosz Cierocki\n* Bruno Oliveira\n* Daniel Hahler\n* Guoqiang Zhang\n* Hynek Schlawack\n* John T. Wodder II\n* Michael Käufl\n* Ronny Pfannschmidt\n* Samuel Dion-Girardeau\n\n\nHappy testing,\nThe pytest Development Team\n"},{"col":4,"comment":"null","endLoc":1097,"header":"def test_funcarg_parametrized_and_used_twice(self, testdir)","id":2292,"name":"test_funcarg_parametrized_and_used_twice","nodeType":"Function","startLoc":1077,"text":"def test_funcarg_parametrized_and_used_twice(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(params=[1,2])\n def arg1(request):\n values.append(1)\n return request.param\n\n @pytest.fixture()\n def arg2(arg1):\n return arg1 + 1\n\n def test_add(arg1, arg2):\n assert arg2 == arg1 + 1\n assert len(values) == arg1\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 passed*\"])"},{"col":0,"comment":"Test fails file is run twice that contains marked class.\n See issue#683.\n ","endLoc":75,"header":"def test_marked_class_run_twice(testdir, request)","id":2293,"name":"test_marked_class_run_twice","nodeType":"Function","startLoc":60,"text":"def test_marked_class_run_twice(testdir, request):\n \"\"\"Test fails file is run twice that contains marked class.\n See issue#683.\n \"\"\"\n py_file = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('abc', [1, 2, 3])\n class Test1(object):\n def test_1(self, abc):\n assert abc in [1, 2, 3]\n \"\"\"\n )\n file_name = os.path.basename(py_file.strpath)\n rec = testdir.inline_run(file_name, file_name)\n rec.assertoutcome(passed=6)"},{"col":4,"comment":"null","endLoc":1125,"header":"def test_factory_uses_unknown_funcarg_as_dependency_error(self, testdir)","id":2294,"name":"test_factory_uses_unknown_funcarg_as_dependency_error","nodeType":"Function","startLoc":1099,"text":"def test_factory_uses_unknown_funcarg_as_dependency_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture()\n def fail(missing):\n return\n\n @pytest.fixture()\n def call_fail(fail):\n return\n\n def test_missing(call_fail):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n \"\"\"\n *pytest.fixture()*\n *def call_fail(fail)*\n *pytest.fixture()*\n *def fail*\n *fixture*'missing'*not found*\n \"\"\"\n )"},{"col":4,"comment":"null","endLoc":41,"header":"def __call__(self, parser, namespace, values, option_string=None)","id":2295,"name":"__call__","nodeType":"Function","startLoc":36,"text":"def __call__(self, parser, namespace, values, option_string=None):\n setattr(namespace, self.dest, self.const)\n\n # We should only skip the rest of the parsing after preparse is done\n if getattr(parser._parser, \"after_preparse\", False):\n raise PrintHelp"},{"id":2296,"name":"release-4.4.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-4.4.1\n=======================================\n\npytest 4.4.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n\n\nHappy testing,\nThe pytest Development Team\n"},{"col":4,"comment":"null","endLoc":1140,"header":"def test_factory_setup_as_classes_fails(self, testdir)","id":2297,"name":"test_factory_setup_as_classes_fails","nodeType":"Function","startLoc":1127,"text":"def test_factory_setup_as_classes_fails(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n class arg1(object):\n def __init__(self, request):\n self.x = 1\n arg1 = pytest.fixture()(arg1)\n\n \"\"\"\n )\n reprec = testdir.inline_run()\n values = reprec.getfailedcollections()\n assert len(values) == 1"},{"col":0,"comment":"null","endLoc":70,"header":"def call_optional(obj, name)","id":2298,"name":"call_optional","nodeType":"Function","startLoc":63,"text":"def call_optional(obj, name):\n method = getattr(obj, name, None)\n isfixture = hasattr(method, \"_pytestfixturefunction\")\n if method is not None and not isfixture and callable(method):\n # If there's any problems allow the exception to raise rather than\n # silently ignoring them\n method()\n return True"},{"fileName":"conftest.py","filePath":"testing/example_scripts/fixtures/fill_fixtures/test_conftest_funcargs_only_available_in_subdir/sub2","id":2299,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\n@pytest.fixture\ndef arg2(request):\n pytest.raises(Exception, request.getfixturevalue, \"arg1\")\n"},{"col":0,"comment":"null","endLoc":7,"header":"@pytest.fixture\ndef arg2(request)","id":2301,"name":"arg2","nodeType":"Function","startLoc":5,"text":"@pytest.fixture\ndef arg2(request):\n pytest.raises(Exception, request.getfixturevalue, \"arg1\")"},{"col":4,"comment":"null","endLoc":1156,"header":"@pytest.mark.filterwarnings(\"ignore::pytest.PytestDeprecationWarning\")\n def test_request_can_be_overridden(self, testdir)","id":2302,"name":"test_request_can_be_overridden","nodeType":"Function","startLoc":1142,"text":"@pytest.mark.filterwarnings(\"ignore::pytest.PytestDeprecationWarning\")\n def test_request_can_be_overridden(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture()\n def request(request):\n request.a = 1\n return request\n def test_request(request):\n assert request.a == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":0,"comment":"null","endLoc":88,"header":"def pytest_addoption(parser)","id":2303,"name":"pytest_addoption","nodeType":"Function","startLoc":44,"text":"def pytest_addoption(parser):\n group = parser.getgroup(\"debugconfig\")\n group.addoption(\n \"--version\",\n action=\"store_true\",\n help=\"display pytest lib version and import information.\",\n )\n group._addoption(\n \"-h\",\n \"--help\",\n action=HelpAction,\n dest=\"help\",\n help=\"show help message and configuration info\",\n )\n group._addoption(\n \"-p\",\n action=\"append\",\n dest=\"plugins\",\n default=[],\n metavar=\"name\",\n help=\"early-load given plugin module name or entry point (multi-allowed). \"\n \"To avoid loading of plugins, use the `no:` prefix, e.g. \"\n \"`no:doctest`.\",\n )\n group.addoption(\n \"--traceconfig\",\n \"--trace-config\",\n action=\"store_true\",\n default=False,\n help=\"trace considerations of conftest.py files.\",\n ),\n group.addoption(\n \"--debug\",\n action=\"store_true\",\n dest=\"debug\",\n default=False,\n help=\"store internal tracing debug information in 'pytestdebug.log'.\",\n )\n group._addoption(\n \"-o\",\n \"--override-ini\",\n dest=\"override_ini\",\n action=\"append\",\n help='override ini option with \"option=value\" style, e.g. `-o xfail_strict=True -o cache_dir=cache`.',\n )"},{"col":4,"comment":"null","endLoc":1181,"header":"def test_usefixtures_marker(self, testdir)","id":2304,"name":"test_usefixtures_marker","nodeType":"Function","startLoc":1158,"text":"def test_usefixtures_marker(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n values = []\n\n @pytest.fixture(scope=\"class\")\n def myfix(request):\n request.cls.hello = \"world\"\n values.append(1)\n\n class TestClass(object):\n def test_one(self):\n assert self.hello == \"world\"\n assert len(values) == 1\n def test_two(self):\n assert self.hello == \"world\"\n assert len(values) == 1\n pytest.mark.usefixtures(\"myfix\")(TestClass)\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)"},{"col":0,"comment":"null","endLoc":119,"header":"@pytest.hookimpl(hookwrapper=True)\ndef pytest_cmdline_parse()","id":2305,"name":"pytest_cmdline_parse","nodeType":"Function","startLoc":91,"text":"@pytest.hookimpl(hookwrapper=True)\ndef pytest_cmdline_parse():\n outcome = yield\n config = outcome.get_result()\n if config.option.debug:\n path = os.path.abspath(\"pytestdebug.log\")\n debugfile = open(path, \"w\")\n debugfile.write(\n \"versions pytest-%s, py-%s, \"\n \"python-%s\\ncwd=%s\\nargs=%s\\n\\n\"\n % (\n pytest.__version__,\n py.__version__,\n \".\".join(map(str, sys.version_info)),\n os.getcwd(),\n config._origargs,\n )\n )\n config.trace.root.setwriter(debugfile.write)\n undo_tracing = config.pluginmanager.enable_tracing()\n sys.stderr.write(\"writing pytestdebug information to %s\\n\" % path)\n\n def unset_tracing():\n debugfile.close()\n sys.stderr.write(\"wrote pytestdebug information to %s\\n\" % debugfile.name)\n config.trace.root.setwriter(None)\n undo_tracing()\n\n config.add_cleanup(unset_tracing)"},{"col":4,"comment":"null","endLoc":1210,"header":"def test_usefixtures_ini(self, testdir)","id":2306,"name":"test_usefixtures_ini","nodeType":"Function","startLoc":1183,"text":"def test_usefixtures_ini(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n usefixtures = myfix\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"class\")\n def myfix(request):\n request.cls.hello = \"world\"\n\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n class TestClass(object):\n def test_one(self):\n assert self.hello == \"world\"\n def test_two(self):\n assert self.hello == \"world\"\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)"},{"col":0,"comment":" return list of keys for all parametrized arguments which match\n the specified scope. ","endLoc":206,"header":"def get_parametrized_fixture_keys(item, scopenum)","id":2307,"name":"get_parametrized_fixture_keys","nodeType":"Function","startLoc":183,"text":"def get_parametrized_fixture_keys(item, scopenum):\n \"\"\" return list of keys for all parametrized arguments which match\n the specified scope. \"\"\"\n assert scopenum < scopenum_function # function\n try:\n cs = item.callspec\n except AttributeError:\n pass\n else:\n # cs.indices.items() is random order of argnames. Need to\n # sort this so that different calls to\n # get_parametrized_fixture_keys will be deterministic.\n for argname, param_index in sorted(cs.indices.items()):\n if cs._arg2scopenum[argname] != scopenum:\n continue\n if scopenum == 0: # session\n key = (argname, param_index)\n elif scopenum == 1: # package\n key = (argname, param_index, item.fspath.dirpath())\n elif scopenum == 2: # module\n key = (argname, param_index, item.fspath)\n elif scopenum == 3: # class\n key = (argname, param_index, item.fspath, item.cls)\n yield key"},{"col":0,"comment":"null","endLoc":54,"header":"def test_setup_func_not_callable()","id":2308,"name":"test_setup_func_not_callable","nodeType":"Function","startLoc":48,"text":"def test_setup_func_not_callable():\n from _pytest.nose import call_optional\n\n class A(object):\n f = 1\n\n call_optional(A(), \"f\")"},{"col":4,"comment":"null","endLoc":1218,"header":"def test_usefixtures_seen_in_showmarkers(self, testdir)","id":2309,"name":"test_usefixtures_seen_in_showmarkers","nodeType":"Function","startLoc":1212,"text":"def test_usefixtures_seen_in_showmarkers(self, testdir):\n result = testdir.runpytest(\"--markers\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *usefixtures(fixturename1*mark tests*fixtures*\n \"\"\"\n )"},{"col":4,"comment":"null","endLoc":1235,"header":"def test_request_instance_issue203(self, testdir)","id":2310,"name":"test_request_instance_issue203","nodeType":"Function","startLoc":1220,"text":"def test_request_instance_issue203(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n class TestClass(object):\n @pytest.fixture\n def setup1(self, request):\n assert self == request.instance\n self.arg1 = 1\n def test_hello(self, setup1):\n assert self.arg1 == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"id":2311,"name":"testing/example_scripts/unittest","nodeType":"Package"},{"fileName":"test_setup_skip_class.py","filePath":"testing/example_scripts/unittest","id":2312,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"Skipping an entire subclass with unittest.skip() should *not* call setUpClass from a base class.\"\"\"\nimport unittest\n\n\nclass Base(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n assert 0\n\n\n@unittest.skip(\"skip all tests\")\nclass Test(Base):\n def test_foo(self):\n assert 0\n"},{"col":4,"comment":"null","endLoc":435,"header":"def __init__(self)","id":2313,"name":"__init__","nodeType":"Function","startLoc":434,"text":"def __init__(self):\n self.__saved = os.getcwd()"},{"id":2314,"name":"src/_pytest/_code","nodeType":"Package"},{"fileName":"_py2traceback.py","filePath":"src/_pytest/_code","id":2315,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n# copied from python-2.7.3's traceback.py\n# CHANGES:\n# - some_str is replaced, trying to create unicode strings\n#\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport types\n\nfrom six import text_type\n\n\ndef format_exception_only(etype, value):\n \"\"\"Format the exception part of a traceback.\n\n The arguments are the exception type and value such as given by\n sys.last_type and sys.last_value. The return value is a list of\n strings, each ending in a newline.\n\n Normally, the list contains a single string; however, for\n SyntaxError exceptions, it contains several lines that (when\n printed) display detailed information about where the syntax\n error occurred.\n\n The message indicating which exception occurred is always the last\n string in the list.\n\n \"\"\"\n\n # An instance should not have a meaningful value parameter, but\n # sometimes does, particularly for string exceptions, such as\n # >>> raise string1, string2 # deprecated\n #\n # Clear these out first because issubtype(string1, SyntaxError)\n # would throw another exception and mask the original problem.\n if (\n isinstance(etype, BaseException)\n or isinstance(etype, types.InstanceType)\n or etype is None\n or type(etype) is str\n ):\n return [_format_final_exc_line(etype, value)]\n\n stype = etype.__name__\n\n if not issubclass(etype, SyntaxError):\n return [_format_final_exc_line(stype, value)]\n\n # It was a syntax error; show exactly where the problem was found.\n lines = []\n try:\n msg, (filename, lineno, offset, badline) = value.args\n except Exception:\n pass\n else:\n filename = filename or \"\"\n lines.append(' File \"{}\", line {}\\n'.format(filename, lineno))\n if badline is not None:\n if isinstance(badline, bytes): # python 2 only\n badline = badline.decode(\"utf-8\", \"replace\")\n lines.append(\" {}\\n\".format(badline.strip()))\n if offset is not None:\n caretspace = badline.rstrip(\"\\n\")[:offset].lstrip()\n # non-space whitespace (likes tabs) must be kept for alignment\n caretspace = ((c.isspace() and c or \" \") for c in caretspace)\n # only three spaces to account for offset1 == pos 0\n lines.append(\" {}^\\n\".format(\"\".join(caretspace)))\n value = msg\n\n lines.append(_format_final_exc_line(stype, value))\n return lines\n\n\ndef _format_final_exc_line(etype, value):\n \"\"\"Return a list of a single line -- normal case for format_exception_only\"\"\"\n valuestr = _some_str(value)\n if value is None or not valuestr:\n line = \"{}\\n\".format(etype)\n else:\n line = \"{}: {}\\n\".format(etype, valuestr)\n return line\n\n\ndef _some_str(value):\n try:\n return text_type(value)\n except Exception:\n try:\n return bytes(value).decode(\"UTF-8\", \"replace\")\n except Exception:\n pass\n return \"\".format(type(value).__name__)\n"},{"className":"Base","col":0,"comment":"null","endLoc":9,"id":2316,"nodeType":"Class","startLoc":6,"text":"class Base(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n assert 0"},{"col":0,"comment":"null","endLoc":84,"header":"def test_nose_setup_func(testdir)","id":2317,"name":"test_nose_setup_func","nodeType":"Function","startLoc":57,"text":"def test_nose_setup_func(testdir):\n p = testdir.makepyfile(\n \"\"\"\n from nose.tools import with_setup\n\n values = []\n\n def my_setup():\n a = 1\n values.append(a)\n\n def my_teardown():\n b = 2\n values.append(b)\n\n @with_setup(my_setup, my_teardown)\n def test_hello():\n print(values)\n assert values == [1]\n\n def test_world():\n print(values)\n assert values == [1,2]\n\n \"\"\"\n )\n result = testdir.runpytest(p, \"-p\", \"nose\")\n result.assert_outcomes(passed=2)"},{"col":4,"comment":"null","endLoc":1264,"header":"def test_fixture_parametrized_with_iterator(self, testdir)","id":2318,"name":"test_fixture_parametrized_with_iterator","nodeType":"Function","startLoc":1237,"text":"def test_fixture_parametrized_with_iterator(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n values = []\n def f():\n yield 1\n yield 2\n dec = pytest.fixture(scope=\"module\", params=f())\n\n @dec\n def arg(request):\n return request.param\n @dec\n def arg2(request):\n return request.param\n\n def test_1(arg):\n values.append(arg)\n def test_2(arg2):\n values.append(arg2*10)\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\")\n reprec.assertoutcome(passed=4)\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n assert values == [1, 2, 10, 20]"},{"attributeType":"_Feature","col":0,"comment":"null","endLoc":16,"id":2319,"name":"unicode_literals","nodeType":"Attribute","startLoc":16,"text":"unicode_literals"},{"col":4,"comment":"null","endLoc":438,"header":"def restore(self)","id":2320,"name":"restore","nodeType":"Function","startLoc":437,"text":"def restore(self):\n os.chdir(self.__saved)"},{"col":0,"comment":"null","endLoc":108,"header":"def test_nose_setup_func_failure(testdir)","id":2322,"name":"test_nose_setup_func_failure","nodeType":"Function","startLoc":87,"text":"def test_nose_setup_func_failure(testdir):\n p = testdir.makepyfile(\n \"\"\"\n from nose.tools import with_setup\n\n values = []\n my_setup = lambda x: 1\n my_teardown = lambda x: 2\n\n @with_setup(my_setup, my_teardown)\n def test_hello():\n print(values)\n assert values == [1]\n\n def test_world():\n print(values)\n assert values == [1,2]\n\n \"\"\"\n )\n result = testdir.runpytest(p, \"-p\", \"nose\")\n result.stdout.fnmatch_lines([\"*TypeError: ()*\"])"},{"attributeType":"null","col":8,"comment":"null","endLoc":435,"id":2324,"name":"__saved","nodeType":"Attribute","startLoc":435,"text":"self.__saved"},{"col":4,"comment":"Ensure setup_* methods obey fixture scope rules (#517, #3094).","endLoc":1303,"header":"def test_setup_functions_as_fixtures(self, testdir)","id":2325,"name":"test_setup_functions_as_fixtures","nodeType":"Function","startLoc":1266,"text":"def test_setup_functions_as_fixtures(self, testdir):\n \"\"\"Ensure setup_* methods obey fixture scope rules (#517, #3094).\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n DB_INITIALIZED = None\n\n @pytest.yield_fixture(scope=\"session\", autouse=True)\n def db():\n global DB_INITIALIZED\n DB_INITIALIZED = True\n yield\n DB_INITIALIZED = False\n\n def setup_module():\n assert DB_INITIALIZED\n\n def teardown_module():\n assert DB_INITIALIZED\n\n class TestClass(object):\n\n def setup_method(self, method):\n assert DB_INITIALIZED\n\n def teardown_method(self, method):\n assert DB_INITIALIZED\n\n def test_printer_1(self):\n pass\n\n def test_printer_2(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed in *\"])"},{"col":0,"comment":"null","endLoc":228,"header":"def reorder_items(items)","id":2326,"name":"reorder_items","nodeType":"Function","startLoc":215,"text":"def reorder_items(items):\n argkeys_cache = {}\n items_by_argkey = {}\n for scopenum in range(0, scopenum_function):\n argkeys_cache[scopenum] = d = {}\n items_by_argkey[scopenum] = item_d = defaultdict(deque)\n for item in items:\n keys = OrderedDict.fromkeys(get_parametrized_fixture_keys(item, scopenum))\n if keys:\n d[item] = keys\n for key in keys:\n item_d[key].append(item)\n items = OrderedDict.fromkeys(items)\n return list(reorder_items_atscope(items, argkeys_cache, items_by_argkey, 0))"},{"col":0,"comment":"null","endLoc":127,"header":"def test_nose_setup_func_failure_2(testdir)","id":2327,"name":"test_nose_setup_func_failure_2","nodeType":"Function","startLoc":111,"text":"def test_nose_setup_func_failure_2(testdir):\n testdir.makepyfile(\n \"\"\"\n values = []\n\n my_setup = 1\n my_teardown = 2\n\n def test_hello():\n assert values == []\n\n test_hello.setup = my_setup\n test_hello.teardown = my_teardown\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":0,"comment":"null","endLoc":98,"header":"def test_ini_markers(testdir)","id":2328,"name":"test_ini_markers","nodeType":"Function","startLoc":78,"text":"def test_ini_markers(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n markers =\n a1: this is a webtest marker\n a2: this is a smoke marker\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_markers(pytestconfig):\n markers = pytestconfig.getini(\"markers\")\n print(markers)\n assert len(markers) >= 2\n assert markers[0].startswith(\"a1:\")\n assert markers[1].startswith(\"a2:\")\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(passed=1)"},{"col":0,"comment":"Format the exception part of a traceback.\n\n The arguments are the exception type and value such as given by\n sys.last_type and sys.last_value. The return value is a list of\n strings, each ending in a newline.\n\n Normally, the list contains a single string; however, for\n SyntaxError exceptions, it contains several lines that (when\n printed) display detailed information about where the syntax\n error occurred.\n\n The message indicating which exception occurred is always the last\n string in the list.\n\n ","endLoc":74,"header":"def format_exception_only(etype, value)","id":2329,"name":"format_exception_only","nodeType":"Function","startLoc":16,"text":"def format_exception_only(etype, value):\n \"\"\"Format the exception part of a traceback.\n\n The arguments are the exception type and value such as given by\n sys.last_type and sys.last_value. The return value is a list of\n strings, each ending in a newline.\n\n Normally, the list contains a single string; however, for\n SyntaxError exceptions, it contains several lines that (when\n printed) display detailed information about where the syntax\n error occurred.\n\n The message indicating which exception occurred is always the last\n string in the list.\n\n \"\"\"\n\n # An instance should not have a meaningful value parameter, but\n # sometimes does, particularly for string exceptions, such as\n # >>> raise string1, string2 # deprecated\n #\n # Clear these out first because issubtype(string1, SyntaxError)\n # would throw another exception and mask the original problem.\n if (\n isinstance(etype, BaseException)\n or isinstance(etype, types.InstanceType)\n or etype is None\n or type(etype) is str\n ):\n return [_format_final_exc_line(etype, value)]\n\n stype = etype.__name__\n\n if not issubclass(etype, SyntaxError):\n return [_format_final_exc_line(stype, value)]\n\n # It was a syntax error; show exactly where the problem was found.\n lines = []\n try:\n msg, (filename, lineno, offset, badline) = value.args\n except Exception:\n pass\n else:\n filename = filename or \"\"\n lines.append(' File \"{}\", line {}\\n'.format(filename, lineno))\n if badline is not None:\n if isinstance(badline, bytes): # python 2 only\n badline = badline.decode(\"utf-8\", \"replace\")\n lines.append(\" {}\\n\".format(badline.strip()))\n if offset is not None:\n caretspace = badline.rstrip(\"\\n\")[:offset].lstrip()\n # non-space whitespace (likes tabs) must be kept for alignment\n caretspace = ((c.isspace() and c or \" \") for c in caretspace)\n # only three spaces to account for offset1 == pos 0\n lines.append(\" {}^\\n\".format(\"\".join(caretspace)))\n value = msg\n\n lines.append(_format_final_exc_line(stype, value))\n return lines"},{"className":"HookRecorder","col":0,"comment":"Record all hooks called in a plugin manager.\n\n This wraps all the hook calls in the plugin manager, recording each call\n before propagating the normal calls.\n\n ","endLoc":322,"id":2330,"nodeType":"Class","startLoc":195,"text":"class HookRecorder(object):\n \"\"\"Record all hooks called in a plugin manager.\n\n This wraps all the hook calls in the plugin manager, recording each call\n before propagating the normal calls.\n\n \"\"\"\n\n def __init__(self, pluginmanager):\n self._pluginmanager = pluginmanager\n self.calls = []\n\n def before(hook_name, hook_impls, kwargs):\n self.calls.append(ParsedCall(hook_name, kwargs))\n\n def after(outcome, hook_name, hook_impls, kwargs):\n pass\n\n self._undo_wrapping = pluginmanager.add_hookcall_monitoring(before, after)\n\n def finish_recording(self):\n self._undo_wrapping()\n\n def getcalls(self, names):\n if isinstance(names, str):\n names = names.split()\n return [call for call in self.calls if call._name in names]\n\n def assert_contains(self, entries):\n __tracebackhide__ = True\n i = 0\n entries = list(entries)\n backlocals = sys._getframe(1).f_locals\n while entries:\n name, check = entries.pop(0)\n for ind, call in enumerate(self.calls[i:]):\n if call._name == name:\n print(\"NAMEMATCH\", name, call)\n if eval(check, backlocals, call.__dict__):\n print(\"CHECKERMATCH\", repr(check), \"->\", call)\n else:\n print(\"NOCHECKERMATCH\", repr(check), \"-\", call)\n continue\n i += ind + 1\n break\n print(\"NONAMEMATCH\", name, \"with\", call)\n else:\n pytest.fail(\"could not find %r check %r\" % (name, check))\n\n def popcall(self, name):\n __tracebackhide__ = True\n for i, call in enumerate(self.calls):\n if call._name == name:\n del self.calls[i]\n return call\n lines = [\"could not find call %r, in:\" % (name,)]\n lines.extend([\" %s\" % x for x in self.calls])\n pytest.fail(\"\\n\".join(lines))\n\n def getcall(self, name):\n values = self.getcalls(name)\n assert len(values) == 1, (name, values)\n return values[0]\n\n # functionality for test reports\n\n def getreports(self, names=\"pytest_runtest_logreport pytest_collectreport\"):\n return [x.report for x in self.getcalls(names)]\n\n def matchreport(\n self,\n inamepart=\"\",\n names=\"pytest_runtest_logreport pytest_collectreport\",\n when=None,\n ):\n \"\"\"return a testreport whose dotted import path matches\"\"\"\n values = []\n for rep in self.getreports(names=names):\n if not when and rep.when != \"call\" and rep.passed:\n # setup/teardown passing reports - let's ignore those\n continue\n if when and rep.when != when:\n continue\n if not inamepart or inamepart in rep.nodeid.split(\"::\"):\n values.append(rep)\n if not values:\n raise ValueError(\n \"could not find test report matching %r: \"\n \"no test reports at all!\" % (inamepart,)\n )\n if len(values) > 1:\n raise ValueError(\n \"found 2 or more testreports matching %r: %s\" % (inamepart, values)\n )\n return values[0]\n\n def getfailures(self, names=\"pytest_runtest_logreport pytest_collectreport\"):\n return [rep for rep in self.getreports(names) if rep.failed]\n\n def getfailedcollections(self):\n return self.getfailures(\"pytest_collectreport\")\n\n def listoutcomes(self):\n passed = []\n skipped = []\n failed = []\n for rep in self.getreports(\"pytest_collectreport pytest_runtest_logreport\"):\n if rep.passed:\n if rep.when == \"call\":\n passed.append(rep)\n elif rep.skipped:\n skipped.append(rep)\n else:\n assert rep.failed, \"Unexpected outcome: {!r}\".format(rep)\n failed.append(rep)\n return passed, skipped, failed\n\n def countoutcomes(self):\n return [len(x) for x in self.listoutcomes()]\n\n def assertoutcome(self, passed=0, skipped=0, failed=0):\n realpassed, realskipped, realfailed = self.listoutcomes()\n assert passed == len(realpassed)\n assert skipped == len(realskipped)\n assert failed == len(realfailed)\n\n def clear(self):\n self.calls[:] = []"},{"className":"TestFixtureManagerParseFactories","col":0,"comment":"null","endLoc":1529,"id":2331,"nodeType":"Class","startLoc":1306,"text":"class TestFixtureManagerParseFactories(object):\n @pytest.fixture\n def testdir(self, request):\n testdir = request.getfixturevalue(\"testdir\")\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def hello(request):\n return \"conftest\"\n\n @pytest.fixture\n def fm(request):\n return request._fixturemanager\n\n @pytest.fixture\n def item(request):\n return request._pyfuncitem\n \"\"\"\n )\n return testdir\n\n def test_parsefactories_evil_objects_issue214(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class A(object):\n def __call__(self):\n pass\n def __getattr__(self, name):\n raise RuntimeError()\n a = A()\n def test_hello():\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1, failed=0)\n\n def test_parsefactories_conftest(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_hello(item, fm):\n for name in (\"fm\", \"hello\", \"item\"):\n faclist = fm.getfixturedefs(name, item.nodeid)\n assert len(faclist) == 1\n fac = faclist[0]\n assert fac.func.__name__ == name\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=1)\n\n def test_parsefactories_conftest_and_module_and_class(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n import six\n\n @pytest.fixture\n def hello(request):\n return \"module\"\n class TestClass(object):\n @pytest.fixture\n def hello(self, request):\n return \"class\"\n def test_hello(self, item, fm):\n faclist = fm.getfixturedefs(\"hello\", item.nodeid)\n print(faclist)\n assert len(faclist) == 3\n\n assert faclist[0].func(item._request) == \"conftest\"\n assert faclist[1].func(item._request) == \"module\"\n assert faclist[2].func(item._request) == \"class\"\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=1)\n\n def test_parsefactories_relative_node_ids(self, testdir):\n # example mostly taken from:\n # https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html\n runner = testdir.mkdir(\"runner\")\n package = testdir.mkdir(\"package\")\n package.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def one():\n return 1\n \"\"\"\n )\n )\n package.join(\"test_x.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_x(one):\n assert one == 1\n \"\"\"\n )\n )\n sub = package.mkdir(\"sub\")\n sub.join(\"__init__.py\").ensure()\n sub.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def one():\n return 2\n \"\"\"\n )\n )\n sub.join(\"test_y.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_x(one):\n assert one == 2\n \"\"\"\n )\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n with runner.as_cwd():\n reprec = testdir.inline_run(\"..\")\n reprec.assertoutcome(passed=2)\n\n def test_package_xunit_fixture(self, testdir):\n testdir.makepyfile(\n __init__=\"\"\"\\\n values = []\n \"\"\"\n )\n package = testdir.mkdir(\"package\")\n package.join(\"__init__.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def setup_module():\n values.append(\"package\")\n def teardown_module():\n values[:] = []\n \"\"\"\n )\n )\n package.join(\"test_x.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def test_x():\n assert values == [\"package\"]\n \"\"\"\n )\n )\n package = testdir.mkdir(\"package2\")\n package.join(\"__init__.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def setup_module():\n values.append(\"package2\")\n def teardown_module():\n values[:] = []\n \"\"\"\n )\n )\n package.join(\"test_x.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def test_x():\n assert values == [\"package2\"]\n \"\"\"\n )\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_package_fixture_complex(self, testdir):\n testdir.makepyfile(\n __init__=\"\"\"\\\n values = []\n \"\"\"\n )\n testdir.syspathinsert(testdir.tmpdir.dirname)\n package = testdir.mkdir(\"package\")\n package.join(\"__init__.py\").write(\"\")\n package.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n from .. import values\n @pytest.fixture(scope=\"package\")\n def one():\n values.append(\"package\")\n yield values\n values.pop()\n @pytest.fixture(scope=\"package\", autouse=True)\n def two():\n values.append(\"package-auto\")\n yield values\n values.pop()\n \"\"\"\n )\n )\n package.join(\"test_x.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def test_package_autouse():\n assert values == [\"package-auto\"]\n def test_package(one):\n assert values == [\"package-auto\", \"package\"]\n \"\"\"\n )\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_collect_custom_items(self, testdir):\n testdir.copy_example(\"fixtures/custom_item\")\n result = testdir.runpytest(\"foo\")\n result.stdout.fnmatch_lines([\"*passed*\"])"},{"col":0,"comment":"null","endLoc":162,"header":"def test_nose_setup_partial(testdir)","id":2332,"name":"test_nose_setup_partial","nodeType":"Function","startLoc":130,"text":"def test_nose_setup_partial(testdir):\n pytest.importorskip(\"functools\")\n p = testdir.makepyfile(\n \"\"\"\n from functools import partial\n\n values = []\n\n def my_setup(x):\n a = x\n values.append(a)\n\n def my_teardown(x):\n b = x\n values.append(b)\n\n my_setup_partial = partial(my_setup, 1)\n my_teardown_partial = partial(my_teardown, 2)\n\n def test_hello():\n print(values)\n assert values == [1]\n\n def test_world():\n print(values)\n assert values == [1,2]\n\n test_hello.setup = my_setup_partial\n test_hello.teardown = my_teardown_partial\n \"\"\"\n )\n result = testdir.runpytest(p, \"-p\", \"nose\")\n result.stdout.fnmatch_lines([\"*2 passed*\"])"},{"col":4,"comment":"null","endLoc":213,"header":"def __init__(self, pluginmanager)","id":2333,"name":"__init__","nodeType":"Function","startLoc":203,"text":"def __init__(self, pluginmanager):\n self._pluginmanager = pluginmanager\n self.calls = []\n\n def before(hook_name, hook_impls, kwargs):\n self.calls.append(ParsedCall(hook_name, kwargs))\n\n def after(outcome, hook_name, hook_impls, kwargs):\n pass\n\n self._undo_wrapping = pluginmanager.add_hookcall_monitoring(before, after)"},{"col":4,"comment":"null","endLoc":1327,"header":"@pytest.fixture\n def testdir(self, request)","id":2334,"name":"testdir","nodeType":"Function","startLoc":1307,"text":"@pytest.fixture\n def testdir(self, request):\n testdir = request.getfixturevalue(\"testdir\")\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def hello(request):\n return \"conftest\"\n\n @pytest.fixture\n def fm(request):\n return request._fixturemanager\n\n @pytest.fixture\n def item(request):\n return request._pyfuncitem\n \"\"\"\n )\n return testdir"},{"col":0,"comment":"null","endLoc":193,"header":"def test_module_level_setup(testdir)","id":2335,"name":"test_module_level_setup","nodeType":"Function","startLoc":165,"text":"def test_module_level_setup(testdir):\n testdir.makepyfile(\n \"\"\"\n from nose.tools import with_setup\n items = {}\n\n def setup():\n items[1]=1\n\n def teardown():\n del items[1]\n\n def setup2():\n items[2] = 2\n\n def teardown2():\n del items[2]\n\n def test_setup_module_setup():\n assert items[1] == 1\n\n @with_setup(setup2, teardown2)\n def test_local_setup():\n assert items[2] == 2\n assert 1 not in items\n \"\"\"\n )\n result = testdir.runpytest(\"-p\", \"nose\")\n result.stdout.fnmatch_lines([\"*2 passed*\"])"},{"col":4,"comment":"null","endLoc":187,"header":"def __init__(self, name, kwargs)","id":2336,"name":"__init__","nodeType":"Function","startLoc":185,"text":"def __init__(self, name, kwargs):\n self.__dict__.update(kwargs)\n self._name = name"},{"col":0,"comment":"null","endLoc":114,"header":"def test_markers_option(testdir)","id":2337,"name":"test_markers_option","nodeType":"Function","startLoc":101,"text":"def test_markers_option(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n markers =\n a1: this is a webtest marker\n a1some: another marker\n nodescription\n \"\"\"\n )\n result = testdir.runpytest(\"--markers\")\n result.stdout.fnmatch_lines(\n [\"*a1*this is a webtest*\", \"*a1some*another marker\", \"*nodescription*\"]\n )"},{"col":0,"comment":"null","endLoc":215,"header":"def test_nose_style_setup_teardown(testdir)","id":2338,"name":"test_nose_style_setup_teardown","nodeType":"Function","startLoc":196,"text":"def test_nose_style_setup_teardown(testdir):\n testdir.makepyfile(\n \"\"\"\n values = []\n\n def setup_module():\n values.append(1)\n\n def teardown_module():\n del values[0]\n\n def test_hello():\n assert values == [1]\n\n def test_world():\n assert values == [1]\n \"\"\"\n )\n result = testdir.runpytest(\"-p\", \"nose\")\n result.stdout.fnmatch_lines([\"*2 passed*\"])"},{"col":0,"comment":"null","endLoc":232,"header":"def test_nose_setup_ordering(testdir)","id":2339,"name":"test_nose_setup_ordering","nodeType":"Function","startLoc":218,"text":"def test_nose_setup_ordering(testdir):\n testdir.makepyfile(\n \"\"\"\n def setup_module(mod):\n mod.visited = True\n\n class TestClass(object):\n def setup(self):\n assert visited\n def test_first(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":0,"comment":"null","endLoc":257,"header":"def test_apiwrapper_problem_issue260(testdir)","id":2340,"name":"test_apiwrapper_problem_issue260","nodeType":"Function","startLoc":235,"text":"def test_apiwrapper_problem_issue260(testdir):\n # this would end up trying a call an optional teardown on the class\n # for plain unittests we dont want nose behaviour\n testdir.makepyfile(\n \"\"\"\n import unittest\n class TestCase(unittest.TestCase):\n def setup(self):\n #should not be called in unittest testcases\n assert 0, 'setup'\n def teardown(self):\n #should not be called in unittest testcases\n assert 0, 'teardown'\n def setUp(self):\n print('setup')\n def tearDown(self):\n print('teardown')\n def test_fun(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.assert_outcomes(passed=1)"},{"col":0,"comment":"null","endLoc":135,"header":"def test_ini_markers_whitespace(testdir)","id":2348,"name":"test_ini_markers_whitespace","nodeType":"Function","startLoc":117,"text":"def test_ini_markers_whitespace(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n markers =\n a1 : this is a whitespace marker\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.a1\n def test_markers():\n assert True\n \"\"\"\n )\n rec = testdir.inline_run(\"--strict-markers\", \"-m\", \"a1\")\n rec.assertoutcome(passed=1)"},{"col":0,"comment":"null","endLoc":285,"header":"def test_setup_teardown_linking_issue265(testdir)","id":2349,"name":"test_setup_teardown_linking_issue265","nodeType":"Function","startLoc":260,"text":"def test_setup_teardown_linking_issue265(testdir):\n # we accidentally didnt integrate nose setupstate with normal setupstate\n # this test ensures that won't happen again\n testdir.makepyfile(\n '''\n import pytest\n\n class TestGeneric(object):\n def test_nothing(self):\n \"\"\"Tests the API of the implementation (for generic and specialized).\"\"\"\n\n @pytest.mark.skipif(\"True\", reason=\n \"Skip tests to check if teardown is skipped as well.\")\n class TestSkipTeardown(TestGeneric):\n\n def setup(self):\n \"\"\"Sets up my specialized implementation for $COOL_PLATFORM.\"\"\"\n raise Exception(\"should not call setup for skipped tests\")\n\n def teardown(self):\n \"\"\"Undoes the setup.\"\"\"\n raise Exception(\"should not call teardown for skipped tests\")\n '''\n )\n reprec = testdir.runpytest()\n reprec.assert_outcomes(passed=1, skipped=1)"},{"col":0,"comment":"null","endLoc":298,"header":"def test_SkipTest_during_collection(testdir)","id":2350,"name":"test_SkipTest_during_collection","nodeType":"Function","startLoc":288,"text":"def test_SkipTest_during_collection(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import nose\n raise nose.SkipTest(\"during collection\")\n def test_failing():\n assert False\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.assert_outcomes(skipped=1)"},{"col":4,"comment":"null","endLoc":1343,"header":"def test_parsefactories_evil_objects_issue214(self, testdir)","id":2351,"name":"test_parsefactories_evil_objects_issue214","nodeType":"Function","startLoc":1329,"text":"def test_parsefactories_evil_objects_issue214(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class A(object):\n def __call__(self):\n pass\n def __getattr__(self, name):\n raise RuntimeError()\n a = A()\n def test_hello():\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1, failed=0)"},{"col":0,"comment":"null","endLoc":311,"header":"def test_SkipTest_in_test(testdir)","id":2352,"name":"test_SkipTest_in_test","nodeType":"Function","startLoc":301,"text":"def test_SkipTest_in_test(testdir):\n testdir.makepyfile(\n \"\"\"\n import nose\n\n def test_skipping():\n raise nose.SkipTest(\"in test\")\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(skipped=1)"},{"col":0,"comment":"null","endLoc":324,"header":"def test_istest_function_decorator(testdir)","id":2353,"name":"test_istest_function_decorator","nodeType":"Function","startLoc":314,"text":"def test_istest_function_decorator(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import nose.tools\n @nose.tools.istest\n def not_test_prefix():\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.assert_outcomes(passed=1)"},{"col":4,"comment":"null","endLoc":1357,"header":"def test_parsefactories_conftest(self, testdir)","id":2354,"name":"test_parsefactories_conftest","nodeType":"Function","startLoc":1345,"text":"def test_parsefactories_conftest(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_hello(item, fm):\n for name in (\"fm\", \"hello\", \"item\"):\n faclist = fm.getfixturedefs(name, item.nodeid)\n assert len(faclist) == 1\n fac = faclist[0]\n assert fac.func.__name__ == name\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=1)"},{"col":0,"comment":"null","endLoc":339,"header":"def test_nottest_function_decorator(testdir)","id":2355,"name":"test_nottest_function_decorator","nodeType":"Function","startLoc":327,"text":"def test_nottest_function_decorator(testdir):\n testdir.makepyfile(\n \"\"\"\n import nose.tools\n @nose.tools.nottest\n def test_prefix():\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n assert not reprec.getfailedcollections()\n calls = reprec.getreports(\"pytest_runtest_logreport\")\n assert not calls"},{"col":4,"comment":"null","endLoc":1383,"header":"def test_parsefactories_conftest_and_module_and_class(self, testdir)","id":2356,"name":"test_parsefactories_conftest_and_module_and_class","nodeType":"Function","startLoc":1359,"text":"def test_parsefactories_conftest_and_module_and_class(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n import six\n\n @pytest.fixture\n def hello(request):\n return \"module\"\n class TestClass(object):\n @pytest.fixture\n def hello(self, request):\n return \"class\"\n def test_hello(self, item, fm):\n faclist = fm.getfixturedefs(\"hello\", item.nodeid)\n print(faclist)\n assert len(faclist) == 3\n\n assert faclist[0].func(item._request) == \"conftest\"\n assert faclist[1].func(item._request) == \"module\"\n assert faclist[2].func(item._request) == \"class\"\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=1)"},{"col":0,"comment":"null","endLoc":353,"header":"def test_istest_class_decorator(testdir)","id":2357,"name":"test_istest_class_decorator","nodeType":"Function","startLoc":342,"text":"def test_istest_class_decorator(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import nose.tools\n @nose.tools.istest\n class NotTestPrefix(object):\n def test_method(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.assert_outcomes(passed=1)"},{"col":0,"comment":"null","endLoc":155,"header":"def test_marker_without_description(testdir)","id":2358,"name":"test_marker_without_description","nodeType":"Function","startLoc":138,"text":"def test_marker_without_description(testdir):\n testdir.makefile(\n \".cfg\",\n setup=\"\"\"\n [tool:pytest]\n markers=slow\n \"\"\",\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n pytest.mark.xfail('FAIL')\n \"\"\"\n )\n ftdir = testdir.mkdir(\"ft1_dummy\")\n testdir.tmpdir.join(\"conftest.py\").move(ftdir.join(\"conftest.py\"))\n rec = testdir.runpytest(\"--strict-markers\")\n rec.assert_outcomes()"},{"className":"TestCase","col":0,"comment":"null","endLoc":324,"id":2359,"nodeType":"Class","startLoc":108,"text":"class TestCase:\n failureException: type[BaseException]\n longMessage: bool\n maxDiff: int | None\n # undocumented\n _testMethodName: str\n # undocumented\n _testMethodDoc: str\n def __init__(self, methodName: str = \"runTest\") -> None: ...\n def __eq__(self, other: object) -> bool: ...\n def __hash__(self) -> int: ...\n def setUp(self) -> None: ...\n def tearDown(self) -> None: ...\n @classmethod\n def setUpClass(cls) -> None: ...\n @classmethod\n def tearDownClass(cls) -> None: ...\n def run(self, result: unittest.result.TestResult | None = None) -> unittest.result.TestResult | None: ...\n def __call__(self, result: unittest.result.TestResult | None = ...) -> unittest.result.TestResult | None: ...\n def skipTest(self, reason: Any) -> NoReturn: ...\n def subTest(self, msg: Any = ..., **params: Any) -> AbstractContextManager[None]: ...\n def debug(self) -> None: ...\n if sys.version_info < (3, 11):\n def _addSkip(self, result: unittest.result.TestResult, test_case: TestCase, reason: str) -> None: ...\n\n def assertEqual(self, first: Any, second: Any, msg: Any = None) -> None: ...\n def assertNotEqual(self, first: Any, second: Any, msg: Any = None) -> None: ...\n def assertTrue(self, expr: Any, msg: Any = None) -> None: ...\n def assertFalse(self, expr: Any, msg: Any = None) -> None: ...\n def assertIs(self, expr1: object, expr2: object, msg: Any = None) -> None: ...\n def assertIsNot(self, expr1: object, expr2: object, msg: Any = None) -> None: ...\n def assertIsNone(self, obj: object, msg: Any = None) -> None: ...\n def assertIsNotNone(self, obj: object, msg: Any = None) -> None: ...\n def assertIn(self, member: Any, container: Iterable[Any] | Container[Any], msg: Any = None) -> None: ...\n def assertNotIn(self, member: Any, container: Iterable[Any] | Container[Any], msg: Any = None) -> None: ...\n def assertIsInstance(self, obj: object, cls: _ClassInfo, msg: Any = None) -> None: ...\n def assertNotIsInstance(self, obj: object, cls: _ClassInfo, msg: Any = None) -> None: ...\n @overload\n def assertGreater(self, a: SupportsDunderGT[_T], b: _T, msg: Any = None) -> None: ...\n @overload\n def assertGreater(self, a: _T, b: SupportsDunderLT[_T], msg: Any = None) -> None: ...\n @overload\n def assertGreaterEqual(self, a: SupportsDunderGE[_T], b: _T, msg: Any = None) -> None: ...\n @overload\n def assertGreaterEqual(self, a: _T, b: SupportsDunderLE[_T], msg: Any = None) -> None: ...\n @overload\n def assertLess(self, a: SupportsDunderLT[_T], b: _T, msg: Any = None) -> None: ...\n @overload\n def assertLess(self, a: _T, b: SupportsDunderGT[_T], msg: Any = None) -> None: ...\n @overload\n def assertLessEqual(self, a: SupportsDunderLE[_T], b: _T, msg: Any = None) -> None: ...\n @overload\n def assertLessEqual(self, a: _T, b: SupportsDunderGE[_T], msg: Any = None) -> None: ...\n # `assertRaises`, `assertRaisesRegex`, and `assertRaisesRegexp`\n # are not using `ParamSpec` intentionally,\n # because they might be used with explicitly wrong arg types to raise some error in tests.\n @overload\n def assertRaises(\n self,\n expected_exception: type[BaseException] | tuple[type[BaseException], ...],\n callable: Callable[..., object],\n *args: Any,\n **kwargs: Any,\n ) -> None: ...\n @overload\n def assertRaises(\n self, expected_exception: type[_E] | tuple[type[_E], ...], *, msg: Any = ...\n ) -> _AssertRaisesContext[_E]: ...\n @overload\n def assertRaisesRegex(\n self,\n expected_exception: type[BaseException] | tuple[type[BaseException], ...],\n expected_regex: str | Pattern[str],\n callable: Callable[..., object],\n *args: Any,\n **kwargs: Any,\n ) -> None: ...\n @overload\n def assertRaisesRegex(\n self, expected_exception: type[_E] | tuple[type[_E], ...], expected_regex: str | Pattern[str], *, msg: Any = ...\n ) -> _AssertRaisesContext[_E]: ...\n @overload\n def assertWarns(\n self,\n expected_warning: type[Warning] | tuple[type[Warning], ...],\n callable: Callable[_P, object],\n *args: _P.args,\n **kwargs: _P.kwargs,\n ) -> None: ...\n @overload\n def assertWarns(\n self, expected_warning: type[Warning] | tuple[type[Warning], ...], *, msg: Any = ...\n ) -> _AssertWarnsContext: ...\n @overload\n def assertWarnsRegex(\n self,\n expected_warning: type[Warning] | tuple[type[Warning], ...],\n expected_regex: str | Pattern[str],\n callable: Callable[_P, object],\n *args: _P.args,\n **kwargs: _P.kwargs,\n ) -> None: ...\n @overload\n def assertWarnsRegex(\n self, expected_warning: type[Warning] | tuple[type[Warning], ...], expected_regex: str | Pattern[str], *, msg: Any = ...\n ) -> _AssertWarnsContext: ...\n def assertLogs(\n self, logger: str | logging.Logger | None = None, level: int | str | None = None\n ) -> _AssertLogsContext[_LoggingWatcher]: ...\n if sys.version_info >= (3, 10):\n def assertNoLogs(\n self, logger: str | logging.Logger | None = None, level: int | str | None = None\n ) -> _AssertLogsContext[None]: ...\n\n @overload\n def assertAlmostEqual(self, first: _S, second: _S, places: None, msg: Any, delta: _SupportsAbsAndDunderGE) -> None: ...\n @overload\n def assertAlmostEqual(\n self, first: _S, second: _S, places: None = None, msg: Any = None, *, delta: _SupportsAbsAndDunderGE\n ) -> None: ...\n @overload\n def assertAlmostEqual(\n self,\n first: SupportsSub[_T, SupportsAbs[SupportsRound[object]]],\n second: _T,\n places: int | None = None,\n msg: Any = None,\n delta: None = None,\n ) -> None: ...\n @overload\n def assertAlmostEqual(\n self,\n first: _T,\n second: SupportsRSub[_T, SupportsAbs[SupportsRound[object]]],\n places: int | None = None,\n msg: Any = None,\n delta: None = None,\n ) -> None: ...\n @overload\n def assertNotAlmostEqual(self, first: _S, second: _S, places: None, msg: Any, delta: _SupportsAbsAndDunderGE) -> None: ...\n @overload\n def assertNotAlmostEqual(\n self, first: _S, second: _S, places: None = None, msg: Any = None, *, delta: _SupportsAbsAndDunderGE\n ) -> None: ...\n @overload\n def assertNotAlmostEqual(\n self,\n first: SupportsSub[_T, SupportsAbs[SupportsRound[object]]],\n second: _T,\n places: int | None = None,\n msg: Any = None,\n delta: None = None,\n ) -> None: ...\n @overload\n def assertNotAlmostEqual(\n self,\n first: _T,\n second: SupportsRSub[_T, SupportsAbs[SupportsRound[object]]],\n places: int | None = None,\n msg: Any = None,\n delta: None = None,\n ) -> None: ...\n def assertRegex(self, text: AnyStr, expected_regex: AnyStr | Pattern[AnyStr], msg: Any = None) -> None: ...\n def assertNotRegex(self, text: AnyStr, unexpected_regex: AnyStr | Pattern[AnyStr], msg: Any = None) -> None: ...\n def assertCountEqual(self, first: Iterable[Any], second: Iterable[Any], msg: Any = None) -> None: ...\n def addTypeEqualityFunc(self, typeobj: type[Any], function: Callable[..., None]) -> None: ...\n def assertMultiLineEqual(self, first: str, second: str, msg: Any = None) -> None: ...\n def assertSequenceEqual(\n self, seq1: Sequence[Any], seq2: Sequence[Any], msg: Any = None, seq_type: type[Sequence[Any]] | None = None\n ) -> None: ...\n def assertListEqual(self, list1: list[Any], list2: list[Any], msg: Any = None) -> None: ...\n def assertTupleEqual(self, tuple1: tuple[Any, ...], tuple2: tuple[Any, ...], msg: Any = None) -> None: ...\n def assertSetEqual(self, set1: AbstractSet[object], set2: AbstractSet[object], msg: Any = None) -> None: ...\n # assertDictEqual accepts only true dict instances. We can't use that here, since that would make\n # assertDictEqual incompatible with TypedDict.\n def assertDictEqual(self, d1: Mapping[Any, object], d2: Mapping[Any, object], msg: Any = None) -> None: ...\n def fail(self, msg: Any = None) -> NoReturn: ...\n def countTestCases(self) -> int: ...\n def defaultTestResult(self) -> unittest.result.TestResult: ...\n def id(self) -> str: ...\n def shortDescription(self) -> str | None: ...\n def addCleanup(self, function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ...\n\n if sys.version_info >= (3, 11):\n def enterContext(self, cm: AbstractContextManager[_T]) -> _T: ...\n\n def doCleanups(self) -> None: ...\n @classmethod\n def addClassCleanup(cls, function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ...\n @classmethod\n def doClassCleanups(cls) -> None: ...\n\n if sys.version_info >= (3, 11):\n @classmethod\n def enterClassContext(cls, cm: AbstractContextManager[_T]) -> _T: ...\n\n def _formatMessage(self, msg: str | None, standardMsg: str) -> str: ... # undocumented\n def _getAssertEqualityFunc(self, first: Any, second: Any) -> Callable[..., None]: ... # undocumented\n if sys.version_info < (3, 12):\n failUnlessEqual = assertEqual\n assertEquals = assertEqual\n failIfEqual = assertNotEqual\n assertNotEquals = assertNotEqual\n failUnless = assertTrue\n assert_ = assertTrue\n failIf = assertFalse\n failUnlessRaises = assertRaises\n failUnlessAlmostEqual = assertAlmostEqual\n assertAlmostEquals = assertAlmostEqual\n failIfAlmostEqual = assertNotAlmostEqual\n assertNotAlmostEquals = assertNotAlmostEqual\n assertRegexpMatches = assertRegex\n assertNotRegexpMatches = assertNotRegex\n assertRaisesRegexp = assertRaisesRegex\n def assertDictContainsSubset(\n self, subset: Mapping[Any, Any], dictionary: Mapping[Any, Any], msg: object = None\n ) -> None: ..."},{"col":0,"comment":"null","endLoc":369,"header":"def test_nottest_class_decorator(testdir)","id":2360,"name":"test_nottest_class_decorator","nodeType":"Function","startLoc":356,"text":"def test_nottest_class_decorator(testdir):\n testdir.makepyfile(\n \"\"\"\n import nose.tools\n @nose.tools.nottest\n class TestPrefix(object):\n def test_method(self):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n assert not reprec.getfailedcollections()\n calls = reprec.getreports(\"pytest_runtest_logreport\")\n assert not calls"},{"col":4,"comment":"null","endLoc":1432,"header":"def test_parsefactories_relative_node_ids(self, testdir)","id":2361,"name":"test_parsefactories_relative_node_ids","nodeType":"Function","startLoc":1385,"text":"def test_parsefactories_relative_node_ids(self, testdir):\n # example mostly taken from:\n # https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html\n runner = testdir.mkdir(\"runner\")\n package = testdir.mkdir(\"package\")\n package.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def one():\n return 1\n \"\"\"\n )\n )\n package.join(\"test_x.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_x(one):\n assert one == 1\n \"\"\"\n )\n )\n sub = package.mkdir(\"sub\")\n sub.join(\"__init__.py\").ensure()\n sub.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def one():\n return 2\n \"\"\"\n )\n )\n sub.join(\"test_y.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_x(one):\n assert one == 2\n \"\"\"\n )\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n with runner.as_cwd():\n reprec = testdir.inline_run(\"..\")\n reprec.assertoutcome(passed=2)"},{"col":0,"comment":"null","endLoc":181,"header":"def test_markers_option_with_plugin_in_current_dir(testdir)","id":2362,"name":"test_markers_option_with_plugin_in_current_dir","nodeType":"Function","startLoc":158,"text":"def test_markers_option_with_plugin_in_current_dir(testdir):\n testdir.makeconftest('pytest_plugins = \"flip_flop\"')\n testdir.makepyfile(\n flip_flop=\"\"\"\\\n def pytest_configure(config):\n config.addinivalue_line(\"markers\", \"flip:flop\")\n\n def pytest_generate_tests(metafunc):\n try:\n mark = metafunc.function.flipper\n except AttributeError:\n return\n metafunc.parametrize(\"x\", (10, 20))\"\"\"\n )\n testdir.makepyfile(\n \"\"\"\\\n import pytest\n @pytest.mark.flipper\n def test_example(x):\n assert x\"\"\"\n )\n\n result = testdir.runpytest(\"--markers\")\n result.stdout.fnmatch_lines([\"*flip*flop*\"])"},{"col":0,"comment":"null","endLoc":383,"header":"def test_skip_test_with_unicode(testdir)","id":2363,"name":"test_skip_test_with_unicode","nodeType":"Function","startLoc":372,"text":"def test_skip_test_with_unicode(testdir):\n testdir.makepyfile(\n \"\"\"\n # -*- coding: utf-8 -*-\n import unittest\n class TestClass():\n def test_io(self):\n raise unittest.SkipTest(u'😊')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 skipped *\"])"},{"col":0,"comment":"null","endLoc":195,"header":"def test_mark_on_pseudo_function(testdir)","id":2364,"name":"test_mark_on_pseudo_function","nodeType":"Function","startLoc":184,"text":"def test_mark_on_pseudo_function(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.r(lambda x: 0/0)\n def test_hello():\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":0,"comment":"null","endLoc":212,"header":"@pytest.mark.parametrize(\"option_name\", [\"--strict-markers\", \"--strict\"])\ndef test_strict_prohibits_unregistered_markers(testdir, option_name)","id":2365,"name":"test_strict_prohibits_unregistered_markers","nodeType":"Function","startLoc":198,"text":"@pytest.mark.parametrize(\"option_name\", [\"--strict-markers\", \"--strict\"])\ndef test_strict_prohibits_unregistered_markers(testdir, option_name):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.unregisteredmark\n def test_hello():\n pass\n \"\"\"\n )\n result = testdir.runpytest(option_name)\n assert result.ret != 0\n result.stdout.fnmatch_lines(\n [\"'unregisteredmark' not found in `markers` configuration option\"]\n )"},{"col":0,"comment":"null","endLoc":241,"header":"@pytest.mark.parametrize(\n \"spec\",\n [\n (\"xyz\", (\"test_one\",)),\n (\"xyz and xyz2\", ()),\n (\"xyz2\", (\"test_two\",)),\n (\"xyz or xyz2\", (\"test_one\", \"test_two\")),\n ],\n)\ndef test_mark_option(spec, testdir)","id":2366,"name":"test_mark_option","nodeType":"Function","startLoc":215,"text":"@pytest.mark.parametrize(\n \"spec\",\n [\n (\"xyz\", (\"test_one\",)),\n (\"xyz and xyz2\", ()),\n (\"xyz2\", (\"test_two\",)),\n (\"xyz or xyz2\", (\"test_one\", \"test_two\")),\n ],\n)\ndef test_mark_option(spec, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xyz\n def test_one():\n pass\n @pytest.mark.xyz2\n def test_two():\n pass\n \"\"\"\n )\n opt, passed_result = spec\n rec = testdir.inline_run(\"-m\", opt)\n passed, skipped, fail = rec.listoutcomes()\n passed = [x.nodeid.split(\"::\")[-1] for x in passed]\n assert len(passed) == len(passed_result)\n assert list(passed) == list(passed_result)"},{"id":2367,"name":"release-4.6.4.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-4.6.4\n=======================================\n\npytest 4.6.4 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Thomas Grainger\n* Zac Hatfield-Dodds\n\n\nHappy testing,\nThe pytest Development Team\n"},{"col":4,"comment":"null","endLoc":216,"header":"def finish_recording(self)","id":2368,"name":"finish_recording","nodeType":"Function","startLoc":215,"text":"def finish_recording(self):\n self._undo_wrapping()"},{"col":4,"comment":"null","endLoc":221,"header":"def getcalls(self, names)","id":2369,"name":"getcalls","nodeType":"Function","startLoc":218,"text":"def getcalls(self, names):\n if isinstance(names, str):\n names = names.split()\n return [call for call in self.calls if call._name in names]"},{"col":4,"comment":"null","endLoc":242,"header":"def assert_contains(self, entries)","id":2370,"name":"assert_contains","nodeType":"Function","startLoc":223,"text":"def assert_contains(self, entries):\n __tracebackhide__ = True\n i = 0\n entries = list(entries)\n backlocals = sys._getframe(1).f_locals\n while entries:\n name, check = entries.pop(0)\n for ind, call in enumerate(self.calls[i:]):\n if call._name == name:\n print(\"NAMEMATCH\", name, call)\n if eval(check, backlocals, call.__dict__):\n print(\"CHECKERMATCH\", repr(check), \"->\", call)\n else:\n print(\"NOCHECKERMATCH\", repr(check), \"-\", call)\n continue\n i += ind + 1\n break\n print(\"NONAMEMATCH\", name, \"with\", call)\n else:\n pytest.fail(\"could not find %r check %r\" % (name, check))"},{"col":4,"comment":"null","endLoc":1483,"header":"def test_package_xunit_fixture(self, testdir)","id":2371,"name":"test_package_xunit_fixture","nodeType":"Function","startLoc":1434,"text":"def test_package_xunit_fixture(self, testdir):\n testdir.makepyfile(\n __init__=\"\"\"\\\n values = []\n \"\"\"\n )\n package = testdir.mkdir(\"package\")\n package.join(\"__init__.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def setup_module():\n values.append(\"package\")\n def teardown_module():\n values[:] = []\n \"\"\"\n )\n )\n package.join(\"test_x.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def test_x():\n assert values == [\"package\"]\n \"\"\"\n )\n )\n package = testdir.mkdir(\"package2\")\n package.join(\"__init__.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def setup_module():\n values.append(\"package2\")\n def teardown_module():\n values[:] = []\n \"\"\"\n )\n )\n package.join(\"test_x.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def test_x():\n assert values == [\"package2\"]\n \"\"\"\n )\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)"},{"col":0,"comment":"Return a list of a single line -- normal case for format_exception_only","endLoc":84,"header":"def _format_final_exc_line(etype, value)","id":2372,"name":"_format_final_exc_line","nodeType":"Function","startLoc":77,"text":"def _format_final_exc_line(etype, value):\n \"\"\"Return a list of a single line -- normal case for format_exception_only\"\"\"\n valuestr = _some_str(value)\n if value is None or not valuestr:\n line = \"{}\\n\".format(etype)\n else:\n line = \"{}: {}\\n\".format(etype, valuestr)\n return line"},{"col":0,"comment":"null","endLoc":95,"header":"def _some_str(value)","id":2373,"name":"_some_str","nodeType":"Function","startLoc":87,"text":"def _some_str(value):\n try:\n return text_type(value)\n except Exception:\n try:\n return bytes(value).decode(\"UTF-8\", \"replace\")\n except Exception:\n pass\n return \"\".format(type(value).__name__)"},{"col":4,"comment":"null","endLoc":1524,"header":"def test_package_fixture_complex(self, testdir)","id":2374,"name":"test_package_fixture_complex","nodeType":"Function","startLoc":1485,"text":"def test_package_fixture_complex(self, testdir):\n testdir.makepyfile(\n __init__=\"\"\"\\\n values = []\n \"\"\"\n )\n testdir.syspathinsert(testdir.tmpdir.dirname)\n package = testdir.mkdir(\"package\")\n package.join(\"__init__.py\").write(\"\")\n package.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n from .. import values\n @pytest.fixture(scope=\"package\")\n def one():\n values.append(\"package\")\n yield values\n values.pop()\n @pytest.fixture(scope=\"package\", autouse=True)\n def two():\n values.append(\"package-auto\")\n yield values\n values.pop()\n \"\"\"\n )\n )\n package.join(\"test_x.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def test_package_autouse():\n assert values == [\"package-auto\"]\n def test_package(one):\n assert values == [\"package-auto\", \"package\"]\n \"\"\"\n )\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)"},{"col":4,"comment":"null","endLoc":1529,"header":"def test_collect_custom_items(self, testdir)","id":2375,"name":"test_collect_custom_items","nodeType":"Function","startLoc":1526,"text":"def test_collect_custom_items(self, testdir):\n testdir.copy_example(\"fixtures/custom_item\")\n result = testdir.runpytest(\"foo\")\n result.stdout.fnmatch_lines([\"*passed*\"])"},{"className":"TestAutouseDiscovery","col":0,"comment":"null","endLoc":1705,"id":2376,"nodeType":"Class","startLoc":1532,"text":"class TestAutouseDiscovery(object):\n @pytest.fixture\n def testdir(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture(autouse=True)\n def perfunction(request, tmpdir):\n pass\n\n @pytest.fixture()\n def arg1(tmpdir):\n pass\n @pytest.fixture(autouse=True)\n def perfunction2(arg1):\n pass\n\n @pytest.fixture\n def fm(request):\n return request._fixturemanager\n\n @pytest.fixture\n def item(request):\n return request._pyfuncitem\n \"\"\"\n )\n return testdir\n\n def test_parsefactories_conftest(self, testdir):\n testdir.makepyfile(\n \"\"\"\n from _pytest.pytester import get_public_names\n def test_check_setup(item, fm):\n autousenames = fm._getautousenames(item.nodeid)\n assert len(get_public_names(autousenames)) == 2\n assert \"perfunction2\" in autousenames\n assert \"perfunction\" in autousenames\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=1)\n\n def test_two_classes_separated_autouse(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n class TestA(object):\n values = []\n @pytest.fixture(autouse=True)\n def setup1(self):\n self.values.append(1)\n def test_setup1(self):\n assert self.values == [1]\n class TestB(object):\n values = []\n @pytest.fixture(autouse=True)\n def setup2(self):\n self.values.append(1)\n def test_setup2(self):\n assert self.values == [1]\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_setup_at_classlevel(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n class TestClass(object):\n @pytest.fixture(autouse=True)\n def permethod(self, request):\n request.instance.funcname = request.function.__name__\n def test_method1(self):\n assert self.funcname == \"test_method1\"\n def test_method2(self):\n assert self.funcname == \"test_method2\"\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=2)\n\n @pytest.mark.xfail(reason=\"'enabled' feature not implemented\")\n def test_setup_enabled_functionnode(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n def enabled(parentnode, markers):\n return \"needsdb\" in markers\n\n @pytest.fixture(params=[1,2])\n def db(request):\n return request.param\n\n @pytest.fixture(enabled=enabled, autouse=True)\n def createdb(db):\n pass\n\n def test_func1(request):\n assert \"db\" not in request.fixturenames\n\n @pytest.mark.needsdb\n def test_func2(request):\n assert \"db\" in request.fixturenames\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=2)\n\n def test_callables_nocode(self, testdir):\n \"\"\"\n an imported mock.call would break setup/factory discovery\n due to it being callable and __code__ not being a code object\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n class _call(tuple):\n def __call__(self, *k, **kw):\n pass\n def __getattr__(self, k):\n return self\n\n call = _call()\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(failed=0, passed=0)\n\n def test_autouse_in_conftests(self, testdir):\n a = testdir.mkdir(\"a\")\n b = testdir.mkdir(\"a1\")\n conftest = testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture(autouse=True)\n def hello():\n xxx\n \"\"\"\n )\n conftest.move(a.join(conftest.basename))\n a.join(\"test_something.py\").write(\"def test_func(): pass\")\n b.join(\"test_otherthing.py\").write(\"def test_func(): pass\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n \"\"\"\n *1 passed*1 error*\n \"\"\"\n )\n\n def test_autouse_in_module_and_two_classes(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(autouse=True)\n def append1():\n values.append(\"module\")\n def test_x():\n assert values == [\"module\"]\n\n class TestA(object):\n @pytest.fixture(autouse=True)\n def append2(self):\n values.append(\"A\")\n def test_hello(self):\n assert values == [\"module\", \"module\", \"A\"], values\n class TestA2(object):\n def test_world(self):\n assert values == [\"module\", \"module\", \"A\", \"module\"], values\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=3)"},{"col":4,"comment":"null","endLoc":116,"header":"def __init__(self, methodName: str = \"runTest\") -> None","id":2377,"name":"__init__","nodeType":"Function","startLoc":116,"text":"def __init__(self, methodName: str = \"runTest\") -> None: ..."},{"col":4,"comment":"null","endLoc":117,"header":"def __eq__(self, other: object) -> bool","id":2378,"name":"__eq__","nodeType":"Function","startLoc":117,"text":"def __eq__(self, other: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":118,"header":"def __hash__(self) -> int","id":2379,"name":"__hash__","nodeType":"Function","startLoc":118,"text":"def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":119,"header":"def setUp(self) -> None","id":2380,"name":"setUp","nodeType":"Function","startLoc":119,"text":"def setUp(self) -> None: ..."},{"col":4,"comment":"null","endLoc":120,"header":"def tearDown(self) -> None","id":2381,"name":"tearDown","nodeType":"Function","startLoc":120,"text":"def tearDown(self) -> None: ..."},{"col":4,"comment":"null","endLoc":122,"header":"@classmethod\n def setUpClass(cls) -> None","id":2382,"name":"setUpClass","nodeType":"Function","startLoc":121,"text":"@classmethod\n def setUpClass(cls) -> None: ..."},{"col":4,"comment":"null","endLoc":124,"header":"@classmethod\n def tearDownClass(cls) -> None","id":2383,"name":"tearDownClass","nodeType":"Function","startLoc":123,"text":"@classmethod\n def tearDownClass(cls) -> None: ..."},{"col":4,"comment":"null","endLoc":125,"header":"def run(self, result: unittest.result.TestResult | None = None) -> unittest.result.TestResult | None","id":2384,"name":"run","nodeType":"Function","startLoc":125,"text":"def run(self, result: unittest.result.TestResult | None = None) -> unittest.result.TestResult | None: ..."},{"col":4,"comment":"null","endLoc":126,"header":"def __call__(self, result: unittest.result.TestResult | None = ...) -> unittest.result.TestResult | None","id":2385,"name":"__call__","nodeType":"Function","startLoc":126,"text":"def __call__(self, result: unittest.result.TestResult | None = ...) -> unittest.result.TestResult | None: ..."},{"col":4,"comment":"null","endLoc":1558,"header":"@pytest.fixture\n def testdir(self, testdir)","id":2386,"name":"testdir","nodeType":"Function","startLoc":1533,"text":"@pytest.fixture\n def testdir(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture(autouse=True)\n def perfunction(request, tmpdir):\n pass\n\n @pytest.fixture()\n def arg1(tmpdir):\n pass\n @pytest.fixture(autouse=True)\n def perfunction2(arg1):\n pass\n\n @pytest.fixture\n def fm(request):\n return request._fixturemanager\n\n @pytest.fixture\n def item(request):\n return request._pyfuncitem\n \"\"\"\n )\n return testdir"},{"col":4,"comment":"null","endLoc":127,"header":"def skipTest(self, reason: Any) -> NoReturn","id":2387,"name":"skipTest","nodeType":"Function","startLoc":127,"text":"def skipTest(self, reason: Any) -> NoReturn: ..."},{"col":4,"comment":"null","endLoc":128,"header":"def subTest(self, msg: Any = ..., **params: Any) -> AbstractContextManager[None]","id":2388,"name":"subTest","nodeType":"Function","startLoc":128,"text":"def subTest(self, msg: Any = ..., **params: Any) -> AbstractContextManager[None]: ..."},{"col":4,"comment":"null","endLoc":129,"header":"def debug(self) -> None","id":2389,"name":"debug","nodeType":"Function","startLoc":129,"text":"def debug(self) -> None: ..."},{"col":8,"comment":"null","endLoc":131,"header":"def _addSkip(self, result: unittest.result.TestResult, test_case: TestCase, reason: str) -> None","id":2390,"name":"_addSkip","nodeType":"Function","startLoc":131,"text":"def _addSkip(self, result: unittest.result.TestResult, test_case: TestCase, reason: str) -> None: ..."},{"col":4,"comment":"null","endLoc":133,"header":"def assertEqual(self, first: Any, second: Any, msg: Any = None) -> None","id":2391,"name":"assertEqual","nodeType":"Function","startLoc":133,"text":"def assertEqual(self, first: Any, second: Any, msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":134,"header":"def assertNotEqual(self, first: Any, second: Any, msg: Any = None) -> None","id":2392,"name":"assertNotEqual","nodeType":"Function","startLoc":134,"text":"def assertNotEqual(self, first: Any, second: Any, msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":135,"header":"def assertTrue(self, expr: Any, msg: Any = None) -> None","id":2393,"name":"assertTrue","nodeType":"Function","startLoc":135,"text":"def assertTrue(self, expr: Any, msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":136,"header":"def assertFalse(self, expr: Any, msg: Any = None) -> None","id":2394,"name":"assertFalse","nodeType":"Function","startLoc":136,"text":"def assertFalse(self, expr: Any, msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":137,"header":"def assertIs(self, expr1: object, expr2: object, msg: Any = None) -> None","id":2395,"name":"assertIs","nodeType":"Function","startLoc":137,"text":"def assertIs(self, expr1: object, expr2: object, msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":138,"header":"def assertIsNot(self, expr1: object, expr2: object, msg: Any = None) -> None","id":2396,"name":"assertIsNot","nodeType":"Function","startLoc":138,"text":"def assertIsNot(self, expr1: object, expr2: object, msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":139,"header":"def assertIsNone(self, obj: object, msg: Any = None) -> None","id":2397,"name":"assertIsNone","nodeType":"Function","startLoc":139,"text":"def assertIsNone(self, obj: object, msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":140,"header":"def assertIsNotNone(self, obj: object, msg: Any = None) -> None","id":2398,"name":"assertIsNotNone","nodeType":"Function","startLoc":140,"text":"def assertIsNotNone(self, obj: object, msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":141,"header":"def assertIn(self, member: Any, container: Iterable[Any] | Container[Any], msg: Any = None) -> None","id":2399,"name":"assertIn","nodeType":"Function","startLoc":141,"text":"def assertIn(self, member: Any, container: Iterable[Any] | Container[Any], msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":142,"header":"def assertNotIn(self, member: Any, container: Iterable[Any] | Container[Any], msg: Any = None) -> None","id":2400,"name":"assertNotIn","nodeType":"Function","startLoc":142,"text":"def assertNotIn(self, member: Any, container: Iterable[Any] | Container[Any], msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":143,"header":"def assertIsInstance(self, obj: object, cls: _ClassInfo, msg: Any = None) -> None","id":2401,"name":"assertIsInstance","nodeType":"Function","startLoc":143,"text":"def assertIsInstance(self, obj: object, cls: _ClassInfo, msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":144,"header":"def assertNotIsInstance(self, obj: object, cls: _ClassInfo, msg: Any = None) -> None","id":2402,"name":"assertNotIsInstance","nodeType":"Function","startLoc":144,"text":"def assertNotIsInstance(self, obj: object, cls: _ClassInfo, msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":146,"header":"@overload\n def assertGreater(self, a: SupportsDunderGT[_T], b: _T, msg: Any = None) -> None","id":2403,"name":"assertGreater","nodeType":"Function","startLoc":145,"text":"@overload\n def assertGreater(self, a: SupportsDunderGT[_T], b: _T, msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":148,"header":"@overload\n def assertGreater(self, a: _T, b: SupportsDunderLT[_T], msg: Any = None) -> None","id":2404,"name":"assertGreater","nodeType":"Function","startLoc":147,"text":"@overload\n def assertGreater(self, a: _T, b: SupportsDunderLT[_T], msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":150,"header":"@overload\n def assertGreaterEqual(self, a: SupportsDunderGE[_T], b: _T, msg: Any = None) -> None","id":2405,"name":"assertGreaterEqual","nodeType":"Function","startLoc":149,"text":"@overload\n def assertGreaterEqual(self, a: SupportsDunderGE[_T], b: _T, msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":152,"header":"@overload\n def assertGreaterEqual(self, a: _T, b: SupportsDunderLE[_T], msg: Any = None) -> None","id":2406,"name":"assertGreaterEqual","nodeType":"Function","startLoc":151,"text":"@overload\n def assertGreaterEqual(self, a: _T, b: SupportsDunderLE[_T], msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":154,"header":"@overload\n def assertLess(self, a: SupportsDunderLT[_T], b: _T, msg: Any = None) -> None","id":2407,"name":"assertLess","nodeType":"Function","startLoc":153,"text":"@overload\n def assertLess(self, a: SupportsDunderLT[_T], b: _T, msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":156,"header":"@overload\n def assertLess(self, a: _T, b: SupportsDunderGT[_T], msg: Any = None) -> None","id":2408,"name":"assertLess","nodeType":"Function","startLoc":155,"text":"@overload\n def assertLess(self, a: _T, b: SupportsDunderGT[_T], msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":158,"header":"@overload\n def assertLessEqual(self, a: SupportsDunderLE[_T], b: _T, msg: Any = None) -> None","id":2409,"name":"assertLessEqual","nodeType":"Function","startLoc":157,"text":"@overload\n def assertLessEqual(self, a: SupportsDunderLE[_T], b: _T, msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":160,"header":"@overload\n def assertLessEqual(self, a: _T, b: SupportsDunderGE[_T], msg: Any = None) -> None","id":2410,"name":"assertLessEqual","nodeType":"Function","startLoc":159,"text":"@overload\n def assertLessEqual(self, a: _T, b: SupportsDunderGE[_T], msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":171,"header":"@overload\n def assertRaises(\n self,\n expected_exception: type[BaseException] | tuple[type[BaseException], ...],\n callable: Callable[..., object],\n *args: Any,\n **kwargs: Any,\n ) -> None","id":2411,"name":"assertRaises","nodeType":"Function","startLoc":164,"text":"@overload\n def assertRaises(\n self,\n expected_exception: type[BaseException] | tuple[type[BaseException], ...],\n callable: Callable[..., object],\n *args: Any,\n **kwargs: Any,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":175,"header":"@overload\n def assertRaises(\n self, expected_exception: type[_E] | tuple[type[_E], ...], *, msg: Any = ...\n ) -> _AssertRaisesContext[_E]","id":2412,"name":"assertRaises","nodeType":"Function","startLoc":172,"text":"@overload\n def assertRaises(\n self, expected_exception: type[_E] | tuple[type[_E], ...], *, msg: Any = ...\n ) -> _AssertRaisesContext[_E]: ..."},{"col":4,"comment":"null","endLoc":184,"header":"@overload\n def assertRaisesRegex(\n self,\n expected_exception: type[BaseException] | tuple[type[BaseException], ...],\n expected_regex: str | Pattern[str],\n callable: Callable[..., object],\n *args: Any,\n **kwargs: Any,\n ) -> None","id":2413,"name":"assertRaisesRegex","nodeType":"Function","startLoc":176,"text":"@overload\n def assertRaisesRegex(\n self,\n expected_exception: type[BaseException] | tuple[type[BaseException], ...],\n expected_regex: str | Pattern[str],\n callable: Callable[..., object],\n *args: Any,\n **kwargs: Any,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":188,"header":"@overload\n def assertRaisesRegex(\n self, expected_exception: type[_E] | tuple[type[_E], ...], expected_regex: str | Pattern[str], *, msg: Any = ...\n ) -> _AssertRaisesContext[_E]","id":2414,"name":"assertRaisesRegex","nodeType":"Function","startLoc":185,"text":"@overload\n def assertRaisesRegex(\n self, expected_exception: type[_E] | tuple[type[_E], ...], expected_regex: str | Pattern[str], *, msg: Any = ...\n ) -> _AssertRaisesContext[_E]: ..."},{"col":4,"comment":"null","endLoc":196,"header":"@overload\n def assertWarns(\n self,\n expected_warning: type[Warning] | tuple[type[Warning], ...],\n callable: Callable[_P, object],\n *args: _P.args,\n **kwargs: _P.kwargs,\n ) -> None","id":2415,"name":"assertWarns","nodeType":"Function","startLoc":189,"text":"@overload\n def assertWarns(\n self,\n expected_warning: type[Warning] | tuple[type[Warning], ...],\n callable: Callable[_P, object],\n *args: _P.args,\n **kwargs: _P.kwargs,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":200,"header":"@overload\n def assertWarns(\n self, expected_warning: type[Warning] | tuple[type[Warning], ...], *, msg: Any = ...\n ) -> _AssertWarnsContext","id":2416,"name":"assertWarns","nodeType":"Function","startLoc":197,"text":"@overload\n def assertWarns(\n self, expected_warning: type[Warning] | tuple[type[Warning], ...], *, msg: Any = ...\n ) -> _AssertWarnsContext: ..."},{"col":4,"comment":"null","endLoc":209,"header":"@overload\n def assertWarnsRegex(\n self,\n expected_warning: type[Warning] | tuple[type[Warning], ...],\n expected_regex: str | Pattern[str],\n callable: Callable[_P, object],\n *args: _P.args,\n **kwargs: _P.kwargs,\n ) -> None","id":2417,"name":"assertWarnsRegex","nodeType":"Function","startLoc":201,"text":"@overload\n def assertWarnsRegex(\n self,\n expected_warning: type[Warning] | tuple[type[Warning], ...],\n expected_regex: str | Pattern[str],\n callable: Callable[_P, object],\n *args: _P.args,\n **kwargs: _P.kwargs,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":213,"header":"@overload\n def assertWarnsRegex(\n self, expected_warning: type[Warning] | tuple[type[Warning], ...], expected_regex: str | Pattern[str], *, msg: Any = ...\n ) -> _AssertWarnsContext","id":2418,"name":"assertWarnsRegex","nodeType":"Function","startLoc":210,"text":"@overload\n def assertWarnsRegex(\n self, expected_warning: type[Warning] | tuple[type[Warning], ...], expected_regex: str | Pattern[str], *, msg: Any = ...\n ) -> _AssertWarnsContext: ..."},{"col":4,"comment":"null","endLoc":216,"header":"def assertLogs(\n self, logger: str | logging.Logger | None = None, level: int | str | None = None\n ) -> _AssertLogsContext[_LoggingWatcher]","id":2419,"name":"assertLogs","nodeType":"Function","startLoc":214,"text":"def assertLogs(\n self, logger: str | logging.Logger | None = None, level: int | str | None = None\n ) -> _AssertLogsContext[_LoggingWatcher]: ..."},{"col":4,"comment":"null","endLoc":223,"header":"@overload\n def assertAlmostEqual(self, first: _S, second: _S, places: None, msg: Any, delta: _SupportsAbsAndDunderGE) -> None","id":2420,"name":"assertAlmostEqual","nodeType":"Function","startLoc":222,"text":"@overload\n def assertAlmostEqual(self, first: _S, second: _S, places: None, msg: Any, delta: _SupportsAbsAndDunderGE) -> None: ..."},{"col":4,"comment":"null","endLoc":227,"header":"@overload\n def assertAlmostEqual(\n self, first: _S, second: _S, places: None = None, msg: Any = None, *, delta: _SupportsAbsAndDunderGE\n ) -> None","id":2421,"name":"assertAlmostEqual","nodeType":"Function","startLoc":224,"text":"@overload\n def assertAlmostEqual(\n self, first: _S, second: _S, places: None = None, msg: Any = None, *, delta: _SupportsAbsAndDunderGE\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":236,"header":"@overload\n def assertAlmostEqual(\n self,\n first: SupportsSub[_T, SupportsAbs[SupportsRound[object]]],\n second: _T,\n places: int | None = None,\n msg: Any = None,\n delta: None = None,\n ) -> None","id":2422,"name":"assertAlmostEqual","nodeType":"Function","startLoc":228,"text":"@overload\n def assertAlmostEqual(\n self,\n first: SupportsSub[_T, SupportsAbs[SupportsRound[object]]],\n second: _T,\n places: int | None = None,\n msg: Any = None,\n delta: None = None,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":245,"header":"@overload\n def assertAlmostEqual(\n self,\n first: _T,\n second: SupportsRSub[_T, SupportsAbs[SupportsRound[object]]],\n places: int | None = None,\n msg: Any = None,\n delta: None = None,\n ) -> None","id":2423,"name":"assertAlmostEqual","nodeType":"Function","startLoc":237,"text":"@overload\n def assertAlmostEqual(\n self,\n first: _T,\n second: SupportsRSub[_T, SupportsAbs[SupportsRound[object]]],\n places: int | None = None,\n msg: Any = None,\n delta: None = None,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":247,"header":"@overload\n def assertNotAlmostEqual(self, first: _S, second: _S, places: None, msg: Any, delta: _SupportsAbsAndDunderGE) -> None","id":2424,"name":"assertNotAlmostEqual","nodeType":"Function","startLoc":246,"text":"@overload\n def assertNotAlmostEqual(self, first: _S, second: _S, places: None, msg: Any, delta: _SupportsAbsAndDunderGE) -> None: ..."},{"col":4,"comment":"null","endLoc":251,"header":"@overload\n def assertNotAlmostEqual(\n self, first: _S, second: _S, places: None = None, msg: Any = None, *, delta: _SupportsAbsAndDunderGE\n ) -> None","id":2425,"name":"assertNotAlmostEqual","nodeType":"Function","startLoc":248,"text":"@overload\n def assertNotAlmostEqual(\n self, first: _S, second: _S, places: None = None, msg: Any = None, *, delta: _SupportsAbsAndDunderGE\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":260,"header":"@overload\n def assertNotAlmostEqual(\n self,\n first: SupportsSub[_T, SupportsAbs[SupportsRound[object]]],\n second: _T,\n places: int | None = None,\n msg: Any = None,\n delta: None = None,\n ) -> None","id":2426,"name":"assertNotAlmostEqual","nodeType":"Function","startLoc":252,"text":"@overload\n def assertNotAlmostEqual(\n self,\n first: SupportsSub[_T, SupportsAbs[SupportsRound[object]]],\n second: _T,\n places: int | None = None,\n msg: Any = None,\n delta: None = None,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":269,"header":"@overload\n def assertNotAlmostEqual(\n self,\n first: _T,\n second: SupportsRSub[_T, SupportsAbs[SupportsRound[object]]],\n places: int | None = None,\n msg: Any = None,\n delta: None = None,\n ) -> None","id":2427,"name":"assertNotAlmostEqual","nodeType":"Function","startLoc":261,"text":"@overload\n def assertNotAlmostEqual(\n self,\n first: _T,\n second: SupportsRSub[_T, SupportsAbs[SupportsRound[object]]],\n places: int | None = None,\n msg: Any = None,\n delta: None = None,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":270,"header":"def assertRegex(self, text: AnyStr, expected_regex: AnyStr | Pattern[AnyStr], msg: Any = None) -> None","id":2428,"name":"assertRegex","nodeType":"Function","startLoc":270,"text":"def assertRegex(self, text: AnyStr, expected_regex: AnyStr | Pattern[AnyStr], msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":271,"header":"def assertNotRegex(self, text: AnyStr, unexpected_regex: AnyStr | Pattern[AnyStr], msg: Any = None) -> None","id":2429,"name":"assertNotRegex","nodeType":"Function","startLoc":271,"text":"def assertNotRegex(self, text: AnyStr, unexpected_regex: AnyStr | Pattern[AnyStr], msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":272,"header":"def assertCountEqual(self, first: Iterable[Any], second: Iterable[Any], msg: Any = None) -> None","id":2430,"name":"assertCountEqual","nodeType":"Function","startLoc":272,"text":"def assertCountEqual(self, first: Iterable[Any], second: Iterable[Any], msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":273,"header":"def addTypeEqualityFunc(self, typeobj: type[Any], function: Callable[..., None]) -> None","id":2431,"name":"addTypeEqualityFunc","nodeType":"Function","startLoc":273,"text":"def addTypeEqualityFunc(self, typeobj: type[Any], function: Callable[..., None]) -> None: ..."},{"col":4,"comment":"null","endLoc":274,"header":"def assertMultiLineEqual(self, first: str, second: str, msg: Any = None) -> None","id":2432,"name":"assertMultiLineEqual","nodeType":"Function","startLoc":274,"text":"def assertMultiLineEqual(self, first: str, second: str, msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":277,"header":"def assertSequenceEqual(\n self, seq1: Sequence[Any], seq2: Sequence[Any], msg: Any = None, seq_type: type[Sequence[Any]] | None = None\n ) -> None","id":2433,"name":"assertSequenceEqual","nodeType":"Function","startLoc":275,"text":"def assertSequenceEqual(\n self, seq1: Sequence[Any], seq2: Sequence[Any], msg: Any = None, seq_type: type[Sequence[Any]] | None = None\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":278,"header":"def assertListEqual(self, list1: list[Any], list2: list[Any], msg: Any = None) -> None","id":2434,"name":"assertListEqual","nodeType":"Function","startLoc":278,"text":"def assertListEqual(self, list1: list[Any], list2: list[Any], msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":279,"header":"def assertTupleEqual(self, tuple1: tuple[Any, ...], tuple2: tuple[Any, ...], msg: Any = None) -> None","id":2435,"name":"assertTupleEqual","nodeType":"Function","startLoc":279,"text":"def assertTupleEqual(self, tuple1: tuple[Any, ...], tuple2: tuple[Any, ...], msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":280,"header":"def assertSetEqual(self, set1: AbstractSet[object], set2: AbstractSet[object], msg: Any = None) -> None","id":2436,"name":"assertSetEqual","nodeType":"Function","startLoc":280,"text":"def assertSetEqual(self, set1: AbstractSet[object], set2: AbstractSet[object], msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":283,"header":"def assertDictEqual(self, d1: Mapping[Any, object], d2: Mapping[Any, object], msg: Any = None) -> None","id":2437,"name":"assertDictEqual","nodeType":"Function","startLoc":283,"text":"def assertDictEqual(self, d1: Mapping[Any, object], d2: Mapping[Any, object], msg: Any = None) -> None: ..."},{"col":4,"comment":"null","endLoc":284,"header":"def fail(self, msg: Any = None) -> NoReturn","id":2438,"name":"fail","nodeType":"Function","startLoc":284,"text":"def fail(self, msg: Any = None) -> NoReturn: ..."},{"col":4,"comment":"null","endLoc":285,"header":"def countTestCases(self) -> int","id":2439,"name":"countTestCases","nodeType":"Function","startLoc":285,"text":"def countTestCases(self) -> int: ..."},{"col":4,"comment":"null","endLoc":286,"header":"def defaultTestResult(self) -> unittest.result.TestResult","id":2440,"name":"defaultTestResult","nodeType":"Function","startLoc":286,"text":"def defaultTestResult(self) -> unittest.result.TestResult: ..."},{"col":4,"comment":"null","endLoc":287,"header":"def id(self) -> str","id":2441,"name":"id","nodeType":"Function","startLoc":287,"text":"def id(self) -> str: ..."},{"col":4,"comment":"null","endLoc":288,"header":"def shortDescription(self) -> str | None","id":2442,"name":"shortDescription","nodeType":"Function","startLoc":288,"text":"def shortDescription(self) -> str | None: ..."},{"col":4,"comment":"null","endLoc":289,"header":"def addCleanup(self, function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None","id":2443,"name":"addCleanup","nodeType":"Function","startLoc":289,"text":"def addCleanup(self, function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ..."},{"col":4,"comment":"null","endLoc":294,"header":"def doCleanups(self) -> None","id":2444,"name":"doCleanups","nodeType":"Function","startLoc":294,"text":"def doCleanups(self) -> None: ..."},{"col":4,"comment":"null","endLoc":296,"header":"@classmethod\n def addClassCleanup(cls, function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None","id":2445,"name":"addClassCleanup","nodeType":"Function","startLoc":295,"text":"@classmethod\n def addClassCleanup(cls, function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ..."},{"col":4,"comment":"null","endLoc":298,"header":"@classmethod\n def doClassCleanups(cls) -> None","id":2446,"name":"doClassCleanups","nodeType":"Function","startLoc":297,"text":"@classmethod\n def doClassCleanups(cls) -> None: ..."},{"col":4,"comment":"null","endLoc":304,"header":"def _formatMessage(self, msg: str | None, standardMsg: str) -> str","id":2447,"name":"_formatMessage","nodeType":"Function","startLoc":304,"text":"def _formatMessage(self, msg: str | None, standardMsg: str) -> str: ... # undocumented"},{"col":4,"comment":"null","endLoc":305,"header":"def _getAssertEqualityFunc(self, first: Any, second: Any) -> Callable[..., None]","id":2448,"name":"_getAssertEqualityFunc","nodeType":"Function","startLoc":305,"text":"def _getAssertEqualityFunc(self, first: Any, second: Any) -> Callable[..., None]: ... # undocumented"},{"col":8,"comment":"null","endLoc":324,"header":"def assertDictContainsSubset(\n self, subset: Mapping[Any, Any], dictionary: Mapping[Any, Any], msg: object = None\n ) -> None","id":2449,"name":"assertDictContainsSubset","nodeType":"Function","startLoc":322,"text":"def assertDictContainsSubset(\n self, subset: Mapping[Any, Any], dictionary: Mapping[Any, Any], msg: object = None\n ) -> None: ..."},{"attributeType":"BaseException","col":4,"comment":"null","endLoc":109,"id":2450,"name":"failureException","nodeType":"Attribute","startLoc":109,"text":"failureException"},{"col":4,"comment":"null","endLoc":1572,"header":"def test_parsefactories_conftest(self, testdir)","id":2451,"name":"test_parsefactories_conftest","nodeType":"Function","startLoc":1560,"text":"def test_parsefactories_conftest(self, testdir):\n testdir.makepyfile(\n \"\"\"\n from _pytest.pytester import get_public_names\n def test_check_setup(item, fm):\n autousenames = fm._getautousenames(item.nodeid)\n assert len(get_public_names(autousenames)) == 2\n assert \"perfunction2\" in autousenames\n assert \"perfunction\" in autousenames\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":"null","endLoc":1595,"header":"def test_two_classes_separated_autouse(self, testdir)","id":2452,"name":"test_two_classes_separated_autouse","nodeType":"Function","startLoc":1574,"text":"def test_two_classes_separated_autouse(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n class TestA(object):\n values = []\n @pytest.fixture(autouse=True)\n def setup1(self):\n self.values.append(1)\n def test_setup1(self):\n assert self.values == [1]\n class TestB(object):\n values = []\n @pytest.fixture(autouse=True)\n def setup2(self):\n self.values.append(1)\n def test_setup2(self):\n assert self.values == [1]\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)"},{"col":0,"comment":"null","endLoc":54,"header":"def pytest_addoption(parser)","id":2453,"name":"pytest_addoption","nodeType":"Function","startLoc":40,"text":"def pytest_addoption(parser):\n group = parser.getgroup(\"pytest-warnings\")\n group.addoption(\n \"-W\",\n \"--pythonwarnings\",\n action=\"append\",\n help=\"set which warnings to report, see -W option of python itself.\",\n )\n parser.addini(\n \"filterwarnings\",\n type=\"linelist\",\n help=\"Each line specifies a pattern for \"\n \"warnings.filterwarnings. \"\n \"Processed after -W and --pythonwarnings.\",\n )"},{"col":4,"comment":"null","endLoc":1612,"header":"def test_setup_at_classlevel(self, testdir)","id":2454,"name":"test_setup_at_classlevel","nodeType":"Function","startLoc":1597,"text":"def test_setup_at_classlevel(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n class TestClass(object):\n @pytest.fixture(autouse=True)\n def permethod(self, request):\n request.instance.funcname = request.function.__name__\n def test_method1(self):\n assert self.funcname == \"test_method1\"\n def test_method2(self):\n assert self.funcname == \"test_method2\"\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=2)"},{"col":0,"comment":"null","endLoc":62,"header":"def pytest_configure(config)","id":2455,"name":"pytest_configure","nodeType":"Function","startLoc":57,"text":"def pytest_configure(config):\n config.addinivalue_line(\n \"markers\",\n \"filterwarnings(warning): add a warning filter to the given test. \"\n \"see https://docs.pytest.org/en/latest/warnings.html#pytest-mark-filterwarnings \",\n )"},{"col":0,"comment":"\n Context manager that catches warnings generated in the contained execution block.\n\n ``item`` can be None if we are not in the context of an item execution.\n\n Each warning captured triggers the ``pytest_warning_captured`` hook.\n ","endLoc":103,"header":"@contextmanager\ndef catch_warnings_for_item(config, ihook, when, item)","id":2456,"name":"catch_warnings_for_item","nodeType":"Function","startLoc":65,"text":"@contextmanager\ndef catch_warnings_for_item(config, ihook, when, item):\n \"\"\"\n Context manager that catches warnings generated in the contained execution block.\n\n ``item`` can be None if we are not in the context of an item execution.\n\n Each warning captured triggers the ``pytest_warning_captured`` hook.\n \"\"\"\n cmdline_filters = config.getoption(\"pythonwarnings\") or []\n inifilters = config.getini(\"filterwarnings\")\n with warnings.catch_warnings(record=True) as log:\n\n if not sys.warnoptions:\n # if user is not explicitly configuring warning filters, show deprecation warnings by default (#2908)\n warnings.filterwarnings(\"always\", category=DeprecationWarning)\n warnings.filterwarnings(\"always\", category=PendingDeprecationWarning)\n\n warnings.filterwarnings(\"error\", category=pytest.RemovedInPytest4Warning)\n\n # filters should have this precedence: mark, cmdline options, ini\n # filters should be applied in the inverse order of precedence\n for arg in inifilters:\n _setoption(warnings, arg)\n\n for arg in cmdline_filters:\n warnings._setoption(arg)\n\n if item is not None:\n for mark in item.iter_markers(name=\"filterwarnings\"):\n for arg in mark.args:\n _setoption(warnings, arg)\n\n yield\n\n for warning_message in log:\n ihook.pytest_warning_captured.call_historic(\n kwargs=dict(warning_message=warning_message, when=when, item=item)\n )"},{"attributeType":"bool","col":4,"comment":"null","endLoc":110,"id":2457,"name":"longMessage","nodeType":"Attribute","startLoc":110,"text":"longMessage"},{"col":4,"comment":"null","endLoc":1640,"header":"@pytest.mark.xfail(reason=\"'enabled' feature not implemented\")\n def test_setup_enabled_functionnode(self, testdir)","id":2458,"name":"test_setup_enabled_functionnode","nodeType":"Function","startLoc":1614,"text":"@pytest.mark.xfail(reason=\"'enabled' feature not implemented\")\n def test_setup_enabled_functionnode(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n def enabled(parentnode, markers):\n return \"needsdb\" in markers\n\n @pytest.fixture(params=[1,2])\n def db(request):\n return request.param\n\n @pytest.fixture(enabled=enabled, autouse=True)\n def createdb(db):\n pass\n\n def test_func1(request):\n assert \"db\" not in request.fixturenames\n\n @pytest.mark.needsdb\n def test_func2(request):\n assert \"db\" in request.fixturenames\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=2)"},{"attributeType":"int | None","col":4,"comment":"null","endLoc":111,"id":2459,"name":"maxDiff","nodeType":"Attribute","startLoc":111,"text":"maxDiff"},{"col":4,"comment":"\n an imported mock.call would break setup/factory discovery\n due to it being callable and __code__ not being a code object\n ","endLoc":1659,"header":"def test_callables_nocode(self, testdir)","id":2460,"name":"test_callables_nocode","nodeType":"Function","startLoc":1642,"text":"def test_callables_nocode(self, testdir):\n \"\"\"\n an imported mock.call would break setup/factory discovery\n due to it being callable and __code__ not being a code object\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n class _call(tuple):\n def __call__(self, *k, **kw):\n pass\n def __getattr__(self, k):\n return self\n\n call = _call()\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(failed=0, passed=0)"},{"attributeType":"str","col":4,"comment":"null","endLoc":113,"id":2461,"name":"_testMethodName","nodeType":"Attribute","startLoc":113,"text":"_testMethodName"},{"col":4,"comment":"null","endLoc":1680,"header":"def test_autouse_in_conftests(self, testdir)","id":2462,"name":"test_autouse_in_conftests","nodeType":"Function","startLoc":1661,"text":"def test_autouse_in_conftests(self, testdir):\n a = testdir.mkdir(\"a\")\n b = testdir.mkdir(\"a1\")\n conftest = testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture(autouse=True)\n def hello():\n xxx\n \"\"\"\n )\n conftest.move(a.join(conftest.basename))\n a.join(\"test_something.py\").write(\"def test_func(): pass\")\n b.join(\"test_otherthing.py\").write(\"def test_func(): pass\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n \"\"\"\n *1 passed*1 error*\n \"\"\"\n )"},{"attributeType":"str","col":4,"comment":"null","endLoc":115,"id":2463,"name":"_testMethodDoc","nodeType":"Attribute","startLoc":115,"text":"_testMethodDoc"},{"attributeType":"function","col":8,"comment":"null","endLoc":307,"id":2464,"name":"failUnlessEqual","nodeType":"Attribute","startLoc":307,"text":"failUnlessEqual"},{"col":4,"comment":"null","endLoc":1705,"header":"def test_autouse_in_module_and_two_classes(self, testdir)","id":2465,"name":"test_autouse_in_module_and_two_classes","nodeType":"Function","startLoc":1682,"text":"def test_autouse_in_module_and_two_classes(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(autouse=True)\n def append1():\n values.append(\"module\")\n def test_x():\n assert values == [\"module\"]\n\n class TestA(object):\n @pytest.fixture(autouse=True)\n def append2(self):\n values.append(\"A\")\n def test_hello(self):\n assert values == [\"module\", \"module\", \"A\"], values\n class TestA2(object):\n def test_world(self):\n assert values == [\"module\", \"module\", \"A\", \"module\"], values\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=3)"},{"attributeType":"function","col":8,"comment":"null","endLoc":308,"id":2466,"name":"assertEquals","nodeType":"Attribute","startLoc":308,"text":"assertEquals"},{"attributeType":"function","col":8,"comment":"null","endLoc":309,"id":2467,"name":"failIfEqual","nodeType":"Attribute","startLoc":309,"text":"failIfEqual"},{"className":"TestAutouseManagement","col":0,"comment":"null","endLoc":1953,"id":2468,"nodeType":"Class","startLoc":1708,"text":"class TestAutouseManagement(object):\n def test_autouse_conftest_mid_directory(self, testdir):\n pkgdir = testdir.mkpydir(\"xyz123\")\n pkgdir.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture(autouse=True)\n def app():\n import sys\n sys._myapp = \"hello\"\n \"\"\"\n )\n )\n t = pkgdir.ensure(\"tests\", \"test_app.py\")\n t.write(\n textwrap.dedent(\n \"\"\"\\\n import sys\n def test_app():\n assert sys._myapp == \"hello\"\n \"\"\"\n )\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=1)\n\n def test_funcarg_and_setup(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(scope=\"module\")\n def arg():\n values.append(1)\n return 0\n @pytest.fixture(scope=\"module\", autouse=True)\n def something(arg):\n values.append(2)\n\n def test_hello(arg):\n assert len(values) == 2\n assert values == [1,2]\n assert arg == 0\n\n def test_hello2(arg):\n assert len(values) == 2\n assert values == [1,2]\n assert arg == 0\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_uses_parametrized_resource(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(params=[1,2])\n def arg(request):\n return request.param\n\n @pytest.fixture(autouse=True)\n def something(arg):\n values.append(arg)\n\n def test_hello():\n if len(values) == 1:\n assert values == [1]\n elif len(values) == 2:\n assert values == [1, 2]\n else:\n 0/0\n\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=2)\n\n def test_session_parametrized_function(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n values = []\n\n @pytest.fixture(scope=\"session\", params=[1,2])\n def arg(request):\n return request.param\n\n @pytest.fixture(scope=\"function\", autouse=True)\n def append(request, arg):\n if request.function.__name__ == \"test_some\":\n values.append(arg)\n\n def test_some():\n pass\n\n def test_result(arg):\n assert len(values) == arg\n assert values[:arg] == [1,2][:arg]\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\", \"-s\")\n reprec.assertoutcome(passed=4)\n\n def test_class_function_parametrization_finalization(self, testdir):\n p = testdir.makeconftest(\n \"\"\"\n import pytest\n import pprint\n\n values = []\n\n @pytest.fixture(scope=\"function\", params=[1,2])\n def farg(request):\n return request.param\n\n @pytest.fixture(scope=\"class\", params=list(\"ab\"))\n def carg(request):\n return request.param\n\n @pytest.fixture(scope=\"function\", autouse=True)\n def append(request, farg, carg):\n def fin():\n values.append(\"fin_%s%s\" % (carg, farg))\n request.addfinalizer(fin)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n class TestClass(object):\n def test_1(self):\n pass\n class TestClass2(object):\n def test_2(self):\n pass\n \"\"\"\n )\n confcut = \"--confcutdir={}\".format(testdir.tmpdir)\n reprec = testdir.inline_run(\"-v\", \"-s\", confcut)\n reprec.assertoutcome(passed=8)\n config = reprec.getcalls(\"pytest_unconfigure\")[0].config\n values = config.pluginmanager._getconftestmodules(p)[0].values\n assert values == [\"fin_a1\", \"fin_a2\", \"fin_b1\", \"fin_b2\"] * 2\n\n def test_scope_ordering(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(scope=\"function\", autouse=True)\n def fappend2():\n values.append(2)\n @pytest.fixture(scope=\"class\", autouse=True)\n def classappend3():\n values.append(3)\n @pytest.fixture(scope=\"module\", autouse=True)\n def mappend():\n values.append(1)\n\n class TestHallo(object):\n def test_method(self):\n assert values == [1,3,2]\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_parametrization_setup_teardown_ordering(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n def pytest_generate_tests(metafunc):\n if metafunc.cls is None:\n assert metafunc.function is test_finish\n if metafunc.cls is not None:\n metafunc.parametrize(\"item\", [1,2], scope=\"class\")\n class TestClass(object):\n @pytest.fixture(scope=\"class\", autouse=True)\n def addteardown(self, item, request):\n values.append(\"setup-%d\" % item)\n request.addfinalizer(lambda: values.append(\"teardown-%d\" % item))\n def test_step1(self, item):\n values.append(\"step1-%d\" % item)\n def test_step2(self, item):\n values.append(\"step2-%d\" % item)\n\n def test_finish():\n print(values)\n assert values == [\"setup-1\", \"step1-1\", \"step2-1\", \"teardown-1\",\n \"setup-2\", \"step1-2\", \"step2-2\", \"teardown-2\",]\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=5)\n\n def test_ordering_autouse_before_explicit(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n values = []\n @pytest.fixture(autouse=True)\n def fix1():\n values.append(1)\n @pytest.fixture()\n def arg1():\n values.append(2)\n def test_hello(arg1):\n assert values == [1,2]\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n @pytest.mark.parametrize(\"param1\", [\"\", \"params=[1]\"], ids=[\"p00\", \"p01\"])\n @pytest.mark.parametrize(\"param2\", [\"\", \"params=[1]\"], ids=[\"p10\", \"p11\"])\n def test_ordering_dependencies_torndown_first(self, testdir, param1, param2):\n \"\"\"#226\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(%(param1)s)\n def arg1(request):\n request.addfinalizer(lambda: values.append(\"fin1\"))\n values.append(\"new1\")\n @pytest.fixture(%(param2)s)\n def arg2(request, arg1):\n request.addfinalizer(lambda: values.append(\"fin2\"))\n values.append(\"new2\")\n\n def test_arg(arg2):\n pass\n def test_check():\n assert values == [\"new1\", \"new2\", \"fin2\", \"fin1\"]\n \"\"\"\n % locals()\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=2)"},{"attributeType":"function","col":8,"comment":"null","endLoc":310,"id":2469,"name":"assertNotEquals","nodeType":"Attribute","startLoc":310,"text":"assertNotEquals"},{"attributeType":"function","col":8,"comment":"null","endLoc":311,"id":2470,"name":"failUnless","nodeType":"Attribute","startLoc":311,"text":"failUnless"},{"col":4,"comment":"null","endLoc":1733,"header":"def test_autouse_conftest_mid_directory(self, testdir)","id":2471,"name":"test_autouse_conftest_mid_directory","nodeType":"Function","startLoc":1709,"text":"def test_autouse_conftest_mid_directory(self, testdir):\n pkgdir = testdir.mkpydir(\"xyz123\")\n pkgdir.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture(autouse=True)\n def app():\n import sys\n sys._myapp = \"hello\"\n \"\"\"\n )\n )\n t = pkgdir.ensure(\"tests\", \"test_app.py\")\n t.write(\n textwrap.dedent(\n \"\"\"\\\n import sys\n def test_app():\n assert sys._myapp == \"hello\"\n \"\"\"\n )\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=1)"},{"attributeType":"function","col":8,"comment":"null","endLoc":312,"id":2472,"name":"assert_","nodeType":"Attribute","startLoc":312,"text":"assert_"},{"attributeType":"function","col":8,"comment":"null","endLoc":313,"id":2473,"name":"failIf","nodeType":"Attribute","startLoc":313,"text":"failIf"},{"attributeType":"function | function","col":8,"comment":"null","endLoc":314,"id":2474,"name":"failUnlessRaises","nodeType":"Attribute","startLoc":314,"text":"failUnlessRaises"},{"col":4,"comment":"null","endLoc":1760,"header":"def test_funcarg_and_setup(self, testdir)","id":2475,"name":"test_funcarg_and_setup","nodeType":"Function","startLoc":1735,"text":"def test_funcarg_and_setup(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(scope=\"module\")\n def arg():\n values.append(1)\n return 0\n @pytest.fixture(scope=\"module\", autouse=True)\n def something(arg):\n values.append(2)\n\n def test_hello(arg):\n assert len(values) == 2\n assert values == [1,2]\n assert arg == 0\n\n def test_hello2(arg):\n assert len(values) == 2\n assert values == [1,2]\n assert arg == 0\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)"},{"col":4,"comment":"null","endLoc":1786,"header":"def test_uses_parametrized_resource(self, testdir)","id":2476,"name":"test_uses_parametrized_resource","nodeType":"Function","startLoc":1762,"text":"def test_uses_parametrized_resource(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(params=[1,2])\n def arg(request):\n return request.param\n\n @pytest.fixture(autouse=True)\n def something(arg):\n values.append(arg)\n\n def test_hello():\n if len(values) == 1:\n assert values == [1]\n elif len(values) == 2:\n assert values == [1, 2]\n else:\n 0/0\n\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=2)"},{"attributeType":"function | function | function | function","col":8,"comment":"null","endLoc":315,"id":2477,"name":"failUnlessAlmostEqual","nodeType":"Attribute","startLoc":315,"text":"failUnlessAlmostEqual"},{"col":4,"comment":"null","endLoc":1813,"header":"def test_session_parametrized_function(self, testdir)","id":2478,"name":"test_session_parametrized_function","nodeType":"Function","startLoc":1788,"text":"def test_session_parametrized_function(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n values = []\n\n @pytest.fixture(scope=\"session\", params=[1,2])\n def arg(request):\n return request.param\n\n @pytest.fixture(scope=\"function\", autouse=True)\n def append(request, arg):\n if request.function.__name__ == \"test_some\":\n values.append(arg)\n\n def test_some():\n pass\n\n def test_result(arg):\n assert len(values) == arg\n assert values[:arg] == [1,2][:arg]\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\", \"-s\")\n reprec.assertoutcome(passed=4)"},{"attributeType":"function | function | function | function","col":8,"comment":"null","endLoc":316,"id":2479,"name":"assertAlmostEquals","nodeType":"Attribute","startLoc":316,"text":"assertAlmostEquals"},{"attributeType":"function | function | function | function","col":8,"comment":"null","endLoc":317,"id":2480,"name":"failIfAlmostEqual","nodeType":"Attribute","startLoc":317,"text":"failIfAlmostEqual"},{"col":4,"comment":"null","endLoc":1855,"header":"def test_class_function_parametrization_finalization(self, testdir)","id":2481,"name":"test_class_function_parametrization_finalization","nodeType":"Function","startLoc":1815,"text":"def test_class_function_parametrization_finalization(self, testdir):\n p = testdir.makeconftest(\n \"\"\"\n import pytest\n import pprint\n\n values = []\n\n @pytest.fixture(scope=\"function\", params=[1,2])\n def farg(request):\n return request.param\n\n @pytest.fixture(scope=\"class\", params=list(\"ab\"))\n def carg(request):\n return request.param\n\n @pytest.fixture(scope=\"function\", autouse=True)\n def append(request, farg, carg):\n def fin():\n values.append(\"fin_%s%s\" % (carg, farg))\n request.addfinalizer(fin)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n class TestClass(object):\n def test_1(self):\n pass\n class TestClass2(object):\n def test_2(self):\n pass\n \"\"\"\n )\n confcut = \"--confcutdir={}\".format(testdir.tmpdir)\n reprec = testdir.inline_run(\"-v\", \"-s\", confcut)\n reprec.assertoutcome(passed=8)\n config = reprec.getcalls(\"pytest_unconfigure\")[0].config\n values = config.pluginmanager._getconftestmodules(p)[0].values\n assert values == [\"fin_a1\", \"fin_a2\", \"fin_b1\", \"fin_b2\"] * 2"},{"attributeType":"function | function | function | function","col":8,"comment":"null","endLoc":318,"id":2482,"name":"assertNotAlmostEquals","nodeType":"Attribute","startLoc":318,"text":"assertNotAlmostEquals"},{"attributeType":"function","col":8,"comment":"null","endLoc":319,"id":2483,"name":"assertRegexpMatches","nodeType":"Attribute","startLoc":319,"text":"assertRegexpMatches"},{"attributeType":"function","col":8,"comment":"null","endLoc":320,"id":2484,"name":"assertNotRegexpMatches","nodeType":"Attribute","startLoc":320,"text":"assertNotRegexpMatches"},{"col":0,"comment":"null","endLoc":270,"header":"@pytest.mark.parametrize(\n \"spec\", [(\"interface\", (\"test_interface\",)), (\"not interface\", (\"test_nointer\",))]\n)\ndef test_mark_option_custom(spec, testdir)","id":2485,"name":"test_mark_option_custom","nodeType":"Function","startLoc":244,"text":"@pytest.mark.parametrize(\n \"spec\", [(\"interface\", (\"test_interface\",)), (\"not interface\", (\"test_nointer\",))]\n)\ndef test_mark_option_custom(spec, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_collection_modifyitems(items):\n for item in items:\n if \"interface\" in item.nodeid:\n item.add_marker(pytest.mark.interface)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_interface():\n pass\n def test_nointer():\n pass\n \"\"\"\n )\n opt, passed_result = spec\n rec = testdir.inline_run(\"-m\", opt)\n passed, skipped, fail = rec.listoutcomes()\n passed = [x.nodeid.split(\"::\")[-1] for x in passed]\n assert len(passed) == len(passed_result)\n assert list(passed) == list(passed_result)"},{"attributeType":"function | function","col":8,"comment":"null","endLoc":321,"id":2486,"name":"assertRaisesRegexp","nodeType":"Attribute","startLoc":321,"text":"assertRaisesRegexp"},{"col":4,"comment":"null","endLoc":1878,"header":"def test_scope_ordering(self, testdir)","id":2487,"name":"test_scope_ordering","nodeType":"Function","startLoc":1857,"text":"def test_scope_ordering(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(scope=\"function\", autouse=True)\n def fappend2():\n values.append(2)\n @pytest.fixture(scope=\"class\", autouse=True)\n def classappend3():\n values.append(3)\n @pytest.fixture(scope=\"module\", autouse=True)\n def mappend():\n values.append(1)\n\n class TestHallo(object):\n def test_method(self):\n assert values == [1,3,2]\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":"null","endLoc":1907,"header":"def test_parametrization_setup_teardown_ordering(self, testdir)","id":2488,"name":"test_parametrization_setup_teardown_ordering","nodeType":"Function","startLoc":1880,"text":"def test_parametrization_setup_teardown_ordering(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n def pytest_generate_tests(metafunc):\n if metafunc.cls is None:\n assert metafunc.function is test_finish\n if metafunc.cls is not None:\n metafunc.parametrize(\"item\", [1,2], scope=\"class\")\n class TestClass(object):\n @pytest.fixture(scope=\"class\", autouse=True)\n def addteardown(self, item, request):\n values.append(\"setup-%d\" % item)\n request.addfinalizer(lambda: values.append(\"teardown-%d\" % item))\n def test_step1(self, item):\n values.append(\"step1-%d\" % item)\n def test_step2(self, item):\n values.append(\"step2-%d\" % item)\n\n def test_finish():\n print(values)\n assert values == [\"setup-1\", \"step1-1\", \"step2-1\", \"teardown-1\",\n \"setup-2\", \"step1-2\", \"step2-2\", \"teardown-2\",]\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=5)"},{"col":4,"comment":"null","endLoc":9,"header":"@classmethod\n def setUpClass(cls)","id":2489,"name":"setUpClass","nodeType":"Function","startLoc":7,"text":"@classmethod\n def setUpClass(cls):\n assert 0"},{"className":"Test","col":0,"comment":"null","endLoc":15,"id":2490,"nodeType":"Class","startLoc":12,"text":"@unittest.skip(\"skip all tests\")\nclass Test(Base):\n def test_foo(self):\n assert 0"},{"col":4,"comment":"null","endLoc":15,"header":"def test_foo(self)","id":2491,"name":"test_foo","nodeType":"Function","startLoc":14,"text":"def test_foo(self):\n assert 0"},{"col":0,"comment":"","endLoc":2,"header":"test_setup_skip_class.py#","id":2492,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"Skipping an entire subclass with unittest.skip() should *not* call setUpClass from a base class.\"\"\""},{"col":4,"comment":"null","endLoc":1926,"header":"def test_ordering_autouse_before_explicit(self, testdir)","id":2493,"name":"test_ordering_autouse_before_explicit","nodeType":"Function","startLoc":1909,"text":"def test_ordering_autouse_before_explicit(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n values = []\n @pytest.fixture(autouse=True)\n def fix1():\n values.append(1)\n @pytest.fixture()\n def arg1():\n values.append(2)\n def test_hello(arg1):\n assert values == [1,2]\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"fileName":"__init__.py","filePath":"src/_pytest/_code","id":2494,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\" python inspection/code generation API \"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom .code import Code # noqa\nfrom .code import ExceptionInfo # noqa\nfrom .code import filter_traceback # noqa\nfrom .code import Frame # noqa\nfrom .code import getrawcode # noqa\nfrom .code import Traceback # noqa\nfrom .source import compile_ as compile # noqa\nfrom .source import getfslineno # noqa\nfrom .source import Source # noqa\n"},{"className":"Code","col":0,"comment":" wrapper around Python code objects ","endLoc":100,"id":2495,"nodeType":"Class","startLoc":33,"text":"class Code(object):\n \"\"\" wrapper around Python code objects \"\"\"\n\n def __init__(self, rawcode):\n if not hasattr(rawcode, \"co_filename\"):\n rawcode = getrawcode(rawcode)\n try:\n self.filename = rawcode.co_filename\n self.firstlineno = rawcode.co_firstlineno - 1\n self.name = rawcode.co_name\n except AttributeError:\n raise TypeError(\"not a code object: %r\" % (rawcode,))\n self.raw = rawcode\n\n def __eq__(self, other):\n return self.raw == other.raw\n\n __hash__ = None\n\n def __ne__(self, other):\n return not self == other\n\n @property\n def path(self):\n \"\"\" return a path object pointing to source code (note that it\n might not point to an actually existing file). \"\"\"\n try:\n p = py.path.local(self.raw.co_filename)\n # maybe don't try this checking\n if not p.check():\n raise OSError(\"py.path check failed.\")\n except OSError:\n # XXX maybe try harder like the weird logic\n # in the standard lib [linecache.updatecache] does?\n p = self.raw.co_filename\n\n return p\n\n @property\n def fullsource(self):\n \"\"\" return a _pytest._code.Source object for the full source file of the code\n \"\"\"\n from _pytest._code import source\n\n full, _ = source.findsource(self.raw)\n return full\n\n def source(self):\n \"\"\" return a _pytest._code.Source object for the code object's source only\n \"\"\"\n # return source only for that part of code\n import _pytest._code\n\n return _pytest._code.Source(self.raw)\n\n def getargs(self, var=False):\n \"\"\" return a tuple with the argument names for the code object\n\n if 'var' is set True also return the names of the variable and\n keyword arguments when present\n \"\"\"\n # handfull shortcut for getting args\n raw = self.raw\n argcount = raw.co_argcount\n if var:\n argcount += raw.co_flags & CO_VARARGS\n argcount += raw.co_flags & CO_VARKEYWORDS\n return raw.co_varnames[:argcount]"},{"col":4,"comment":"null","endLoc":48,"header":"def __eq__(self, other)","id":2496,"name":"__eq__","nodeType":"Function","startLoc":47,"text":"def __eq__(self, other):\n return self.raw == other.raw"},{"col":4,"comment":"null","endLoc":53,"header":"def __ne__(self, other)","id":2497,"name":"__ne__","nodeType":"Function","startLoc":52,"text":"def __ne__(self, other):\n return not self == other"},{"col":4,"comment":" return a path object pointing to source code (note that it\n might not point to an actually existing file). ","endLoc":69,"header":"@property\n def path(self)","id":2498,"name":"path","nodeType":"Function","startLoc":55,"text":"@property\n def path(self):\n \"\"\" return a path object pointing to source code (note that it\n might not point to an actually existing file). \"\"\"\n try:\n p = py.path.local(self.raw.co_filename)\n # maybe don't try this checking\n if not p.check():\n raise OSError(\"py.path check failed.\")\n except OSError:\n # XXX maybe try harder like the weird logic\n # in the standard lib [linecache.updatecache] does?\n p = self.raw.co_filename\n\n return p"},{"col":4,"comment":"#226","endLoc":1953,"header":"@pytest.mark.parametrize(\"param1\", [\"\", \"params=[1]\"], ids=[\"p00\", \"p01\"])\n @pytest.mark.parametrize(\"param2\", [\"\", \"params=[1]\"], ids=[\"p10\", \"p11\"])\n def test_ordering_dependencies_torndown_first(self, testdir, param1, param2)","id":2499,"name":"test_ordering_dependencies_torndown_first","nodeType":"Function","startLoc":1928,"text":"@pytest.mark.parametrize(\"param1\", [\"\", \"params=[1]\"], ids=[\"p00\", \"p01\"])\n @pytest.mark.parametrize(\"param2\", [\"\", \"params=[1]\"], ids=[\"p10\", \"p11\"])\n def test_ordering_dependencies_torndown_first(self, testdir, param1, param2):\n \"\"\"#226\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(%(param1)s)\n def arg1(request):\n request.addfinalizer(lambda: values.append(\"fin1\"))\n values.append(\"new1\")\n @pytest.fixture(%(param2)s)\n def arg2(request, arg1):\n request.addfinalizer(lambda: values.append(\"fin2\"))\n values.append(\"new2\")\n\n def test_arg(arg2):\n pass\n def test_check():\n assert values == [\"new1\", \"new2\", \"fin2\", \"fin1\"]\n \"\"\"\n % locals()\n )\n reprec = testdir.inline_run(\"-s\")\n reprec.assertoutcome(passed=2)"},{"col":0,"comment":"null","endLoc":298,"header":"@pytest.mark.parametrize(\n \"spec\",\n [\n (\"interface\", (\"test_interface\",)),\n (\"not interface\", (\"test_nointer\", \"test_pass\")),\n (\"pass\", (\"test_pass\",)),\n (\"not pass\", (\"test_interface\", \"test_nointer\")),\n ],\n)\ndef test_keyword_option_custom(spec, testdir)","id":2501,"name":"test_keyword_option_custom","nodeType":"Function","startLoc":273,"text":"@pytest.mark.parametrize(\n \"spec\",\n [\n (\"interface\", (\"test_interface\",)),\n (\"not interface\", (\"test_nointer\", \"test_pass\")),\n (\"pass\", (\"test_pass\",)),\n (\"not pass\", (\"test_interface\", \"test_nointer\")),\n ],\n)\ndef test_keyword_option_custom(spec, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_interface():\n pass\n def test_nointer():\n pass\n def test_pass():\n pass\n \"\"\"\n )\n opt, passed_result = spec\n rec = testdir.inline_run(\"-k\", opt)\n passed, skipped, fail = rec.listoutcomes()\n passed = [x.nodeid.split(\"::\")[-1] for x in passed]\n assert len(passed) == len(passed_result)\n assert list(passed) == list(passed_result)"},{"className":"TestFixtureMarker","col":0,"comment":"null","endLoc":2909,"id":2502,"nodeType":"Class","startLoc":1956,"text":"class TestFixtureMarker(object):\n def test_parametrize(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(params=[\"a\", \"b\", \"c\"])\n def arg(request):\n return request.param\n values = []\n def test_param(arg):\n values.append(arg)\n def test_result():\n assert values == list(\"abc\")\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=4)\n\n def test_multiple_parametrization_issue_736(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[1,2,3])\n def foo(request):\n return request.param\n\n @pytest.mark.parametrize('foobar', [4,5,6])\n def test_issue(foo, foobar):\n assert foo in [1,2,3]\n assert foobar in [4,5,6]\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=9)\n\n @pytest.mark.parametrize(\n \"param_args\",\n [\"'fixt, val'\", \"'fixt,val'\", \"['fixt', 'val']\", \"('fixt', 'val')\"],\n )\n def test_override_parametrized_fixture_issue_979(self, testdir, param_args):\n \"\"\"Make sure a parametrized argument can override a parametrized fixture.\n\n This was a regression introduced in the fix for #736.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[1, 2])\n def fixt(request):\n return request.param\n\n @pytest.mark.parametrize(%s, [(3, 'x'), (4, 'x')])\n def test_foo(fixt, val):\n pass\n \"\"\"\n % param_args\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_scope_session(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(scope=\"module\")\n def arg():\n values.append(1)\n return 1\n\n def test_1(arg):\n assert arg == 1\n def test_2(arg):\n assert arg == 1\n assert len(values) == 1\n class TestClass(object):\n def test3(self, arg):\n assert arg == 1\n assert len(values) == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=3)\n\n def test_scope_session_exc(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(scope=\"session\")\n def fix():\n values.append(1)\n pytest.skip('skipping')\n\n def test_1(fix):\n pass\n def test_2(fix):\n pass\n def test_last():\n assert values == [1]\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(skipped=2, passed=1)\n\n def test_scope_session_exc_two_fix(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n m = []\n @pytest.fixture(scope=\"session\")\n def a():\n values.append(1)\n pytest.skip('skipping')\n @pytest.fixture(scope=\"session\")\n def b(a):\n m.append(1)\n\n def test_1(b):\n pass\n def test_2(b):\n pass\n def test_last():\n assert values == [1]\n assert m == []\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(skipped=2, passed=1)\n\n def test_scope_exc(self, testdir):\n testdir.makepyfile(\n test_foo=\"\"\"\n def test_foo(fix):\n pass\n \"\"\",\n test_bar=\"\"\"\n def test_bar(fix):\n pass\n \"\"\",\n conftest=\"\"\"\n import pytest\n reqs = []\n @pytest.fixture(scope=\"session\")\n def fix(request):\n reqs.append(1)\n pytest.skip()\n @pytest.fixture\n def req_list():\n return reqs\n \"\"\",\n test_real=\"\"\"\n def test_last(req_list):\n assert req_list == [1]\n \"\"\",\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(skipped=2, passed=1)\n\n def test_scope_module_uses_session(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(scope=\"module\")\n def arg():\n values.append(1)\n return 1\n\n def test_1(arg):\n assert arg == 1\n def test_2(arg):\n assert arg == 1\n assert len(values) == 1\n class TestClass(object):\n def test3(self, arg):\n assert arg == 1\n assert len(values) == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=3)\n\n def test_scope_module_and_finalizer(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n finalized_list = []\n created_list = []\n @pytest.fixture(scope=\"module\")\n def arg(request):\n created_list.append(1)\n assert request.scope == \"module\"\n request.addfinalizer(lambda: finalized_list.append(1))\n @pytest.fixture\n def created(request):\n return len(created_list)\n @pytest.fixture\n def finalized(request):\n return len(finalized_list)\n \"\"\"\n )\n testdir.makepyfile(\n test_mod1=\"\"\"\n def test_1(arg, created, finalized):\n assert created == 1\n assert finalized == 0\n def test_2(arg, created, finalized):\n assert created == 1\n assert finalized == 0\"\"\",\n test_mod2=\"\"\"\n def test_3(arg, created, finalized):\n assert created == 2\n assert finalized == 1\"\"\",\n test_mode3=\"\"\"\n def test_4(arg, created, finalized):\n assert created == 3\n assert finalized == 2\n \"\"\",\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=4)\n\n def test_scope_mismatch_various(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n finalized = []\n created = []\n @pytest.fixture(scope=\"function\")\n def arg(request):\n pass\n \"\"\"\n )\n testdir.makepyfile(\n test_mod1=\"\"\"\n import pytest\n @pytest.fixture(scope=\"session\")\n def arg(request):\n request.getfixturevalue(\"arg\")\n def test_1(arg):\n pass\n \"\"\"\n )\n result = testdir.runpytest(SHOW_PYTEST_WARNINGS_ARG)\n assert result.ret != 0\n result.stdout.fnmatch_lines(\n [\"*ScopeMismatch*You tried*function*session*request*\"]\n )\n\n def test_register_only_with_mark(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture()\n def arg():\n return 1\n \"\"\"\n )\n testdir.makepyfile(\n test_mod1=\"\"\"\n import pytest\n @pytest.fixture()\n def arg(arg):\n return arg + 1\n def test_1(arg):\n assert arg == 2\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_parametrize_and_scope(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=\"module\", params=[\"a\", \"b\", \"c\"])\n def arg(request):\n return request.param\n values = []\n def test_param(arg):\n values.append(arg)\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\")\n reprec.assertoutcome(passed=3)\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n assert len(values) == 3\n assert \"a\" in values\n assert \"b\" in values\n assert \"c\" in values\n\n def test_scope_mismatch(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture(scope=\"function\")\n def arg(request):\n pass\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=\"session\")\n def arg(arg):\n pass\n def test_mismatch(arg):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*ScopeMismatch*\", \"*1 error*\"])\n\n def test_parametrize_separated_order(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"module\", params=[1, 2])\n def arg(request):\n return request.param\n\n values = []\n def test_1(arg):\n values.append(arg)\n def test_2(arg):\n values.append(arg)\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\")\n reprec.assertoutcome(passed=4)\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n assert values == [1, 1, 2, 2]\n\n def test_module_parametrized_ordering(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style=classic\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"session\", params=\"s1 s2\".split())\n def sarg():\n pass\n @pytest.fixture(scope=\"module\", params=\"m1 m2\".split())\n def marg():\n pass\n \"\"\"\n )\n testdir.makepyfile(\n test_mod1=\"\"\"\n def test_func(sarg):\n pass\n def test_func1(marg):\n pass\n \"\"\",\n test_mod2=\"\"\"\n def test_func2(sarg):\n pass\n def test_func3(sarg, marg):\n pass\n def test_func3b(sarg, marg):\n pass\n def test_func4(marg):\n pass\n \"\"\",\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n \"\"\"\n test_mod1.py::test_func[s1] PASSED\n test_mod2.py::test_func2[s1] PASSED\n test_mod2.py::test_func3[s1-m1] PASSED\n test_mod2.py::test_func3b[s1-m1] PASSED\n test_mod2.py::test_func3[s1-m2] PASSED\n test_mod2.py::test_func3b[s1-m2] PASSED\n test_mod1.py::test_func[s2] PASSED\n test_mod2.py::test_func2[s2] PASSED\n test_mod2.py::test_func3[s2-m1] PASSED\n test_mod2.py::test_func3b[s2-m1] PASSED\n test_mod2.py::test_func4[m1] PASSED\n test_mod2.py::test_func3[s2-m2] PASSED\n test_mod2.py::test_func3b[s2-m2] PASSED\n test_mod2.py::test_func4[m2] PASSED\n test_mod1.py::test_func1[m1] PASSED\n test_mod1.py::test_func1[m2] PASSED\n \"\"\"\n )\n\n def test_dynamic_parametrized_ordering(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style=classic\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n def pytest_configure(config):\n class DynamicFixturePlugin(object):\n @pytest.fixture(scope='session', params=['flavor1', 'flavor2'])\n def flavor(self, request):\n return request.param\n config.pluginmanager.register(DynamicFixturePlugin(), 'flavor-fixture')\n\n @pytest.fixture(scope='session', params=['vxlan', 'vlan'])\n def encap(request):\n return request.param\n\n @pytest.fixture(scope='session', autouse='True')\n def reprovision(request, flavor, encap):\n pass\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test(reprovision):\n pass\n def test2(reprovision):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n \"\"\"\n test_dynamic_parametrized_ordering.py::test[flavor1-vxlan] PASSED\n test_dynamic_parametrized_ordering.py::test2[flavor1-vxlan] PASSED\n test_dynamic_parametrized_ordering.py::test[flavor2-vxlan] PASSED\n test_dynamic_parametrized_ordering.py::test2[flavor2-vxlan] PASSED\n test_dynamic_parametrized_ordering.py::test[flavor2-vlan] PASSED\n test_dynamic_parametrized_ordering.py::test2[flavor2-vlan] PASSED\n test_dynamic_parametrized_ordering.py::test[flavor1-vlan] PASSED\n test_dynamic_parametrized_ordering.py::test2[flavor1-vlan] PASSED\n \"\"\"\n )\n\n def test_class_ordering(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style=classic\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n values = []\n\n @pytest.fixture(scope=\"function\", params=[1,2])\n def farg(request):\n return request.param\n\n @pytest.fixture(scope=\"class\", params=list(\"ab\"))\n def carg(request):\n return request.param\n\n @pytest.fixture(scope=\"function\", autouse=True)\n def append(request, farg, carg):\n def fin():\n values.append(\"fin_%s%s\" % (carg, farg))\n request.addfinalizer(fin)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n class TestClass2(object):\n def test_1(self):\n pass\n def test_2(self):\n pass\n class TestClass(object):\n def test_3(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-vs\")\n result.stdout.re_match_lines(\n r\"\"\"\n test_class_ordering.py::TestClass2::test_1\\[a-1\\] PASSED\n test_class_ordering.py::TestClass2::test_1\\[a-2\\] PASSED\n test_class_ordering.py::TestClass2::test_2\\[a-1\\] PASSED\n test_class_ordering.py::TestClass2::test_2\\[a-2\\] PASSED\n test_class_ordering.py::TestClass2::test_1\\[b-1\\] PASSED\n test_class_ordering.py::TestClass2::test_1\\[b-2\\] PASSED\n test_class_ordering.py::TestClass2::test_2\\[b-1\\] PASSED\n test_class_ordering.py::TestClass2::test_2\\[b-2\\] PASSED\n test_class_ordering.py::TestClass::test_3\\[a-1\\] PASSED\n test_class_ordering.py::TestClass::test_3\\[a-2\\] PASSED\n test_class_ordering.py::TestClass::test_3\\[b-1\\] PASSED\n test_class_ordering.py::TestClass::test_3\\[b-2\\] PASSED\n \"\"\"\n )\n\n def test_parametrize_separated_order_higher_scope_first(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"function\", params=[1, 2])\n def arg(request):\n param = request.param\n request.addfinalizer(lambda: values.append(\"fin:%s\" % param))\n values.append(\"create:%s\" % param)\n return request.param\n\n @pytest.fixture(scope=\"module\", params=[\"mod1\", \"mod2\"])\n def modarg(request):\n param = request.param\n request.addfinalizer(lambda: values.append(\"fin:%s\" % param))\n values.append(\"create:%s\" % param)\n return request.param\n\n values = []\n def test_1(arg):\n values.append(\"test1\")\n def test_2(modarg):\n values.append(\"test2\")\n def test_3(arg, modarg):\n values.append(\"test3\")\n def test_4(modarg, arg):\n values.append(\"test4\")\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\")\n reprec.assertoutcome(passed=12)\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n expected = [\n \"create:1\",\n \"test1\",\n \"fin:1\",\n \"create:2\",\n \"test1\",\n \"fin:2\",\n \"create:mod1\",\n \"test2\",\n \"create:1\",\n \"test3\",\n \"fin:1\",\n \"create:2\",\n \"test3\",\n \"fin:2\",\n \"create:1\",\n \"test4\",\n \"fin:1\",\n \"create:2\",\n \"test4\",\n \"fin:2\",\n \"fin:mod1\",\n \"create:mod2\",\n \"test2\",\n \"create:1\",\n \"test3\",\n \"fin:1\",\n \"create:2\",\n \"test3\",\n \"fin:2\",\n \"create:1\",\n \"test4\",\n \"fin:1\",\n \"create:2\",\n \"test4\",\n \"fin:2\",\n \"fin:mod2\",\n ]\n import pprint\n\n pprint.pprint(list(zip(values, expected)))\n assert values == expected\n\n def test_parametrized_fixture_teardown_order(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(params=[1,2], scope=\"class\")\n def param1(request):\n return request.param\n\n values = []\n\n class TestClass(object):\n @classmethod\n @pytest.fixture(scope=\"class\", autouse=True)\n def setup1(self, request, param1):\n values.append(1)\n request.addfinalizer(self.teardown1)\n @classmethod\n def teardown1(self):\n assert values.pop() == 1\n @pytest.fixture(scope=\"class\", autouse=True)\n def setup2(self, request, param1):\n values.append(2)\n request.addfinalizer(self.teardown2)\n @classmethod\n def teardown2(self):\n assert values.pop() == 2\n def test(self):\n pass\n\n def test_finish():\n assert not values\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *3 passed*\n \"\"\"\n )\n assert \"error\" not in result.stdout.str()\n\n def test_fixture_finalizer(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n import sys\n\n @pytest.fixture\n def browser(request):\n\n def finalize():\n sys.stdout.write('Finalized')\n request.addfinalizer(finalize)\n return {}\n \"\"\"\n )\n b = testdir.mkdir(\"subdir\")\n b.join(\"test_overridden_fixture_finalizer.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def browser(browser):\n browser['visited'] = True\n return browser\n\n def test_browser(browser):\n assert browser['visited'] is True\n \"\"\"\n )\n )\n reprec = testdir.runpytest(\"-s\")\n for test in [\"test_browser\"]:\n reprec.stdout.fnmatch_lines([\"*Finalized*\"])\n\n def test_class_scope_with_normal_tests(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import pytest\n\n class Box(object):\n value = 0\n\n @pytest.fixture(scope='class')\n def a(request):\n Box.value += 1\n return Box.value\n\n def test_a(a):\n assert a == 1\n\n class Test1(object):\n def test_b(self, a):\n assert a == 2\n\n class Test2(object):\n def test_c(self, a):\n assert a == 3\"\"\"\n )\n reprec = testdir.inline_run(testpath)\n for test in [\"test_a\", \"test_b\", \"test_c\"]:\n assert reprec.matchreport(test).passed\n\n def test_request_is_clean(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(params=[1, 2])\n def fix(request):\n request.addfinalizer(lambda: values.append(request.param))\n def test_fix(fix):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n assert values == [1, 2]\n\n def test_parametrize_separated_lifecycle(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n values = []\n @pytest.fixture(scope=\"module\", params=[1, 2])\n def arg(request):\n x = request.param\n request.addfinalizer(lambda: values.append(\"fin%s\" % x))\n return request.param\n def test_1(arg):\n values.append(arg)\n def test_2(arg):\n values.append(arg)\n \"\"\"\n )\n reprec = testdir.inline_run(\"-vs\")\n reprec.assertoutcome(passed=4)\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n import pprint\n\n pprint.pprint(values)\n # assert len(values) == 6\n assert values[0] == values[1] == 1\n assert values[2] == \"fin1\"\n assert values[3] == values[4] == 2\n assert values[5] == \"fin2\"\n\n def test_parametrize_function_scoped_finalizers_called(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"function\", params=[1, 2])\n def arg(request):\n x = request.param\n request.addfinalizer(lambda: values.append(\"fin%s\" % x))\n return request.param\n\n values = []\n def test_1(arg):\n values.append(arg)\n def test_2(arg):\n values.append(arg)\n def test_3():\n assert len(values) == 8\n assert values == [1, \"fin1\", 2, \"fin2\", 1, \"fin1\", 2, \"fin2\"]\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\")\n reprec.assertoutcome(passed=5)\n\n @pytest.mark.parametrize(\"scope\", [\"session\", \"function\", \"module\"])\n def test_finalizer_order_on_parametrization(self, scope, testdir):\n \"\"\"#246\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n\n @pytest.fixture(scope=%(scope)r, params=[\"1\"])\n def fix1(request):\n return request.param\n\n @pytest.fixture(scope=%(scope)r)\n def fix2(request, base):\n def cleanup_fix2():\n assert not values, \"base should not have been finalized\"\n request.addfinalizer(cleanup_fix2)\n\n @pytest.fixture(scope=%(scope)r)\n def base(request, fix1):\n def cleanup_base():\n values.append(\"fin_base\")\n print(\"finalizing base\")\n request.addfinalizer(cleanup_base)\n\n def test_begin():\n pass\n def test_baz(base, fix2):\n pass\n def test_other():\n pass\n \"\"\"\n % {\"scope\": scope}\n )\n reprec = testdir.inline_run(\"-lvs\")\n reprec.assertoutcome(passed=3)\n\n def test_class_scope_parametrization_ordering(self, testdir):\n \"\"\"#396\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(params=[\"John\", \"Doe\"], scope=\"class\")\n def human(request):\n request.addfinalizer(lambda: values.append(\"fin %s\" % request.param))\n return request.param\n\n class TestGreetings(object):\n def test_hello(self, human):\n values.append(\"test_hello\")\n\n class TestMetrics(object):\n def test_name(self, human):\n values.append(\"test_name\")\n\n def test_population(self, human):\n values.append(\"test_population\")\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=6)\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n assert values == [\n \"test_hello\",\n \"fin John\",\n \"test_hello\",\n \"fin Doe\",\n \"test_name\",\n \"test_population\",\n \"fin John\",\n \"test_name\",\n \"test_population\",\n \"fin Doe\",\n ]\n\n def test_parametrize_setup_function(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"module\", params=[1, 2])\n def arg(request):\n return request.param\n\n @pytest.fixture(scope=\"module\", autouse=True)\n def mysetup(request, arg):\n request.addfinalizer(lambda: values.append(\"fin%s\" % arg))\n values.append(\"setup%s\" % arg)\n\n values = []\n def test_1(arg):\n values.append(arg)\n def test_2(arg):\n values.append(arg)\n def test_3():\n import pprint\n pprint.pprint(values)\n if arg == 1:\n assert values == [\"setup1\", 1, 1, ]\n elif arg == 2:\n assert values == [\"setup1\", 1, 1, \"fin1\",\n \"setup2\", 2, 2, ]\n\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\")\n reprec.assertoutcome(passed=6)\n\n def test_fixture_marked_function_not_collected_as_test(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def test_app():\n return 1\n\n def test_something(test_app):\n assert test_app == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_params_and_ids(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[object(), object()],\n ids=['alpha', 'beta'])\n def fix(request):\n return request.param\n\n def test_foo(fix):\n assert 1\n \"\"\"\n )\n res = testdir.runpytest(\"-v\")\n res.stdout.fnmatch_lines([\"*test_foo*alpha*\", \"*test_foo*beta*\"])\n\n def test_params_and_ids_yieldfixture(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.yield_fixture(params=[object(), object()],\n ids=['alpha', 'beta'])\n def fix(request):\n yield request.param\n\n def test_foo(fix):\n assert 1\n \"\"\"\n )\n res = testdir.runpytest(\"-v\")\n res.stdout.fnmatch_lines([\"*test_foo*alpha*\", \"*test_foo*beta*\"])\n\n def test_deterministic_fixture_collection(self, testdir, monkeypatch):\n \"\"\"#920\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"module\",\n params=[\"A\",\n \"B\",\n \"C\"])\n def A(request):\n return request.param\n\n @pytest.fixture(scope=\"module\",\n params=[\"DDDDDDDDD\", \"EEEEEEEEEEEE\", \"FFFFFFFFFFF\", \"banansda\"])\n def B(request, A):\n return request.param\n\n def test_foo(B):\n # Something funky is going on here.\n # Despite specified seeds, on what is collected,\n # sometimes we get unexpected passes. hashing B seems\n # to help?\n assert hash(B) or True\n \"\"\"\n )\n monkeypatch.setenv(\"PYTHONHASHSEED\", \"1\")\n out1 = testdir.runpytest_subprocess(\"-v\")\n monkeypatch.setenv(\"PYTHONHASHSEED\", \"2\")\n out2 = testdir.runpytest_subprocess(\"-v\")\n out1 = [\n line\n for line in out1.outlines\n if line.startswith(\"test_deterministic_fixture_collection.py::test_foo\")\n ]\n out2 = [\n line\n for line in out2.outlines\n if line.startswith(\"test_deterministic_fixture_collection.py::test_foo\")\n ]\n assert len(out1) == 12\n assert out1 == out2"},{"col":4,"comment":"null","endLoc":1972,"header":"def test_parametrize(self, testdir)","id":2503,"name":"test_parametrize","nodeType":"Function","startLoc":1957,"text":"def test_parametrize(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(params=[\"a\", \"b\", \"c\"])\n def arg(request):\n return request.param\n values = []\n def test_param(arg):\n values.append(arg)\n def test_result():\n assert values == list(\"abc\")\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=4)"},{"col":4,"comment":" return a _pytest._code.Source object for the full source file of the code\n ","endLoc":78,"header":"@property\n def fullsource(self)","id":2504,"name":"fullsource","nodeType":"Function","startLoc":71,"text":"@property\n def fullsource(self):\n \"\"\" return a _pytest._code.Source object for the full source file of the code\n \"\"\"\n from _pytest._code import source\n\n full, _ = source.findsource(self.raw)\n return full"},{"col":4,"comment":"null","endLoc":1990,"header":"def test_multiple_parametrization_issue_736(self, testdir)","id":2505,"name":"test_multiple_parametrization_issue_736","nodeType":"Function","startLoc":1974,"text":"def test_multiple_parametrization_issue_736(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[1,2,3])\n def foo(request):\n return request.param\n\n @pytest.mark.parametrize('foobar', [4,5,6])\n def test_issue(foo, foobar):\n assert foo in [1,2,3]\n assert foobar in [4,5,6]\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=9)"},{"col":4,"comment":"null","endLoc":252,"header":"def popcall(self, name)","id":2506,"name":"popcall","nodeType":"Function","startLoc":244,"text":"def popcall(self, name):\n __tracebackhide__ = True\n for i, call in enumerate(self.calls):\n if call._name == name:\n del self.calls[i]\n return call\n lines = [\"could not find call %r, in:\" % (name,)]\n lines.extend([\" %s\" % x for x in self.calls])\n pytest.fail(\"\\n\".join(lines))"},{"col":4,"comment":"Make sure a parametrized argument can override a parametrized fixture.\n\n This was a regression introduced in the fix for #736.\n ","endLoc":2016,"header":"@pytest.mark.parametrize(\n \"param_args\",\n [\"'fixt, val'\", \"'fixt,val'\", \"['fixt', 'val']\", \"('fixt', 'val')\"],\n )\n def test_override_parametrized_fixture_issue_979(self, testdir, param_args)","id":2507,"name":"test_override_parametrized_fixture_issue_979","nodeType":"Function","startLoc":1992,"text":"@pytest.mark.parametrize(\n \"param_args\",\n [\"'fixt, val'\", \"'fixt,val'\", \"['fixt', 'val']\", \"('fixt', 'val')\"],\n )\n def test_override_parametrized_fixture_issue_979(self, testdir, param_args):\n \"\"\"Make sure a parametrized argument can override a parametrized fixture.\n\n This was a regression introduced in the fix for #736.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[1, 2])\n def fixt(request):\n return request.param\n\n @pytest.mark.parametrize(%s, [(3, 'x'), (4, 'x')])\n def test_foo(fixt, val):\n pass\n \"\"\"\n % param_args\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)"},{"col":4,"comment":"null","endLoc":2040,"header":"def test_scope_session(self, testdir)","id":2508,"name":"test_scope_session","nodeType":"Function","startLoc":2018,"text":"def test_scope_session(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(scope=\"module\")\n def arg():\n values.append(1)\n return 1\n\n def test_1(arg):\n assert arg == 1\n def test_2(arg):\n assert arg == 1\n assert len(values) == 1\n class TestClass(object):\n def test3(self, arg):\n assert arg == 1\n assert len(values) == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=3)"},{"col":4,"comment":"null","endLoc":257,"header":"def getcall(self, name)","id":2509,"name":"getcall","nodeType":"Function","startLoc":254,"text":"def getcall(self, name):\n values = self.getcalls(name)\n assert len(values) == 1, (name, values)\n return values[0]"},{"col":4,"comment":"null","endLoc":2061,"header":"def test_scope_session_exc(self, testdir)","id":2510,"name":"test_scope_session_exc","nodeType":"Function","startLoc":2042,"text":"def test_scope_session_exc(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(scope=\"session\")\n def fix():\n values.append(1)\n pytest.skip('skipping')\n\n def test_1(fix):\n pass\n def test_2(fix):\n pass\n def test_last():\n assert values == [1]\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(skipped=2, passed=1)"},{"col":0,"comment":"null","endLoc":247,"header":"def findsource(obj)","id":2511,"name":"findsource","nodeType":"Function","startLoc":240,"text":"def findsource(obj):\n try:\n sourcelines, lineno = inspect.findsource(obj)\n except Exception:\n return None, -1\n source = Source()\n source.lines = [line.rstrip() for line in sourcelines]\n return source, lineno"},{"col":4,"comment":"null","endLoc":2087,"header":"def test_scope_session_exc_two_fix(self, testdir)","id":2512,"name":"test_scope_session_exc_two_fix","nodeType":"Function","startLoc":2063,"text":"def test_scope_session_exc_two_fix(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n m = []\n @pytest.fixture(scope=\"session\")\n def a():\n values.append(1)\n pytest.skip('skipping')\n @pytest.fixture(scope=\"session\")\n def b(a):\n m.append(1)\n\n def test_1(b):\n pass\n def test_2(b):\n pass\n def test_last():\n assert values == [1]\n assert m == []\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(skipped=2, passed=1)"},{"col":4,"comment":"null","endLoc":262,"header":"def getreports(self, names=\"pytest_runtest_logreport pytest_collectreport\")","id":2513,"name":"getreports","nodeType":"Function","startLoc":261,"text":"def getreports(self, names=\"pytest_runtest_logreport pytest_collectreport\"):\n return [x.report for x in self.getcalls(names)]"},{"col":4,"comment":"return a testreport whose dotted import path matches","endLoc":289,"header":"def matchreport(\n self,\n inamepart=\"\",\n names=\"pytest_runtest_logreport pytest_collectreport\",\n when=None,\n )","id":2514,"name":"matchreport","nodeType":"Function","startLoc":264,"text":"def matchreport(\n self,\n inamepart=\"\",\n names=\"pytest_runtest_logreport pytest_collectreport\",\n when=None,\n ):\n \"\"\"return a testreport whose dotted import path matches\"\"\"\n values = []\n for rep in self.getreports(names=names):\n if not when and rep.when != \"call\" and rep.passed:\n # setup/teardown passing reports - let's ignore those\n continue\n if when and rep.when != when:\n continue\n if not inamepart or inamepart in rep.nodeid.split(\"::\"):\n values.append(rep)\n if not values:\n raise ValueError(\n \"could not find test report matching %r: \"\n \"no test reports at all!\" % (inamepart,)\n )\n if len(values) > 1:\n raise ValueError(\n \"found 2 or more testreports matching %r: %s\" % (inamepart, values)\n )\n return values[0]"},{"col":4,"comment":"null","endLoc":2116,"header":"def test_scope_exc(self, testdir)","id":2515,"name":"test_scope_exc","nodeType":"Function","startLoc":2089,"text":"def test_scope_exc(self, testdir):\n testdir.makepyfile(\n test_foo=\"\"\"\n def test_foo(fix):\n pass\n \"\"\",\n test_bar=\"\"\"\n def test_bar(fix):\n pass\n \"\"\",\n conftest=\"\"\"\n import pytest\n reqs = []\n @pytest.fixture(scope=\"session\")\n def fix(request):\n reqs.append(1)\n pytest.skip()\n @pytest.fixture\n def req_list():\n return reqs\n \"\"\",\n test_real=\"\"\"\n def test_last(req_list):\n assert req_list == [1]\n \"\"\",\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(skipped=2, passed=1)"},{"col":4,"comment":"null","endLoc":2140,"header":"def test_scope_module_uses_session(self, testdir)","id":2517,"name":"test_scope_module_uses_session","nodeType":"Function","startLoc":2118,"text":"def test_scope_module_uses_session(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(scope=\"module\")\n def arg():\n values.append(1)\n return 1\n\n def test_1(arg):\n assert arg == 1\n def test_2(arg):\n assert arg == 1\n assert len(values) == 1\n class TestClass(object):\n def test3(self, arg):\n assert arg == 1\n assert len(values) == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=3)"},{"col":4,"comment":"null","endLoc":2180,"header":"def test_scope_module_and_finalizer(self, testdir)","id":2518,"name":"test_scope_module_and_finalizer","nodeType":"Function","startLoc":2142,"text":"def test_scope_module_and_finalizer(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n finalized_list = []\n created_list = []\n @pytest.fixture(scope=\"module\")\n def arg(request):\n created_list.append(1)\n assert request.scope == \"module\"\n request.addfinalizer(lambda: finalized_list.append(1))\n @pytest.fixture\n def created(request):\n return len(created_list)\n @pytest.fixture\n def finalized(request):\n return len(finalized_list)\n \"\"\"\n )\n testdir.makepyfile(\n test_mod1=\"\"\"\n def test_1(arg, created, finalized):\n assert created == 1\n assert finalized == 0\n def test_2(arg, created, finalized):\n assert created == 1\n assert finalized == 0\"\"\",\n test_mod2=\"\"\"\n def test_3(arg, created, finalized):\n assert created == 2\n assert finalized == 1\"\"\",\n test_mode3=\"\"\"\n def test_4(arg, created, finalized):\n assert created == 3\n assert finalized == 2\n \"\"\",\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=4)"},{"col":4,"comment":"null","endLoc":2207,"header":"def test_scope_mismatch_various(self, testdir)","id":2519,"name":"test_scope_mismatch_various","nodeType":"Function","startLoc":2182,"text":"def test_scope_mismatch_various(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n finalized = []\n created = []\n @pytest.fixture(scope=\"function\")\n def arg(request):\n pass\n \"\"\"\n )\n testdir.makepyfile(\n test_mod1=\"\"\"\n import pytest\n @pytest.fixture(scope=\"session\")\n def arg(request):\n request.getfixturevalue(\"arg\")\n def test_1(arg):\n pass\n \"\"\"\n )\n result = testdir.runpytest(SHOW_PYTEST_WARNINGS_ARG)\n assert result.ret != 0\n result.stdout.fnmatch_lines(\n [\"*ScopeMismatch*You tried*function*session*request*\"]\n )"},{"attributeType":"null","col":4,"comment":"null","endLoc":50,"id":2520,"name":"__hash__","nodeType":"Attribute","startLoc":50,"text":"__hash__"},{"attributeType":"null","col":12,"comment":"null","endLoc":40,"id":2521,"name":"filename","nodeType":"Attribute","startLoc":40,"text":"self.filename"},{"col":4,"comment":"null","endLoc":2229,"header":"def test_register_only_with_mark(self, testdir)","id":2522,"name":"test_register_only_with_mark","nodeType":"Function","startLoc":2209,"text":"def test_register_only_with_mark(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture()\n def arg():\n return 1\n \"\"\"\n )\n testdir.makepyfile(\n test_mod1=\"\"\"\n import pytest\n @pytest.fixture()\n def arg(arg):\n return arg + 1\n def test_1(arg):\n assert arg == 2\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":"null","endLoc":2249,"header":"def test_parametrize_and_scope(self, testdir)","id":2523,"name":"test_parametrize_and_scope","nodeType":"Function","startLoc":2231,"text":"def test_parametrize_and_scope(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=\"module\", params=[\"a\", \"b\", \"c\"])\n def arg(request):\n return request.param\n values = []\n def test_param(arg):\n values.append(arg)\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\")\n reprec.assertoutcome(passed=3)\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n assert len(values) == 3\n assert \"a\" in values\n assert \"b\" in values\n assert \"c\" in values"},{"col":0,"comment":"null","endLoc":305,"header":"def test_keyword_option_considers_mark(testdir)","id":2524,"name":"test_keyword_option_considers_mark","nodeType":"Function","startLoc":301,"text":"def test_keyword_option_considers_mark(testdir):\n testdir.copy_example(\"marks/marks_considered_keywords\")\n rec = testdir.inline_run(\"-k\", \"foo\")\n passed = rec.listoutcomes()[0]\n assert len(passed) == 1"},{"col":4,"comment":"null","endLoc":292,"header":"def getfailures(self, names=\"pytest_runtest_logreport pytest_collectreport\")","id":2525,"name":"getfailures","nodeType":"Function","startLoc":291,"text":"def getfailures(self, names=\"pytest_runtest_logreport pytest_collectreport\"):\n return [rep for rep in self.getreports(names) if rep.failed]"},{"col":4,"comment":"null","endLoc":2271,"header":"def test_scope_mismatch(self, testdir)","id":2526,"name":"test_scope_mismatch","nodeType":"Function","startLoc":2251,"text":"def test_scope_mismatch(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture(scope=\"function\")\n def arg(request):\n pass\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=\"session\")\n def arg(arg):\n pass\n def test_mismatch(arg):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*ScopeMismatch*\", \"*1 error*\"])"},{"col":4,"comment":"null","endLoc":295,"header":"def getfailedcollections(self)","id":2527,"name":"getfailedcollections","nodeType":"Function","startLoc":294,"text":"def getfailedcollections(self):\n return self.getfailures(\"pytest_collectreport\")"},{"col":4,"comment":"null","endLoc":2292,"header":"def test_parametrize_separated_order(self, testdir)","id":2528,"name":"test_parametrize_separated_order","nodeType":"Function","startLoc":2273,"text":"def test_parametrize_separated_order(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"module\", params=[1, 2])\n def arg(request):\n return request.param\n\n values = []\n def test_1(arg):\n values.append(arg)\n def test_2(arg):\n values.append(arg)\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\")\n reprec.assertoutcome(passed=4)\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n assert values == [1, 1, 2, 2]"},{"attributeType":"null","col":12,"comment":"null","endLoc":42,"id":2529,"name":"name","nodeType":"Attribute","startLoc":42,"text":"self.name"},{"col":0,"comment":"null","endLoc":330,"header":"@pytest.mark.parametrize(\n \"spec\",\n [\n (\"None\", (\"test_func[None]\",)),\n (\"1.3\", (\"test_func[1.3]\",)),\n (\"2-3\", (\"test_func[2-3]\",)),\n ],\n)\ndef test_keyword_option_parametrize(spec, testdir)","id":2530,"name":"test_keyword_option_parametrize","nodeType":"Function","startLoc":308,"text":"@pytest.mark.parametrize(\n \"spec\",\n [\n (\"None\", (\"test_func[None]\",)),\n (\"1.3\", (\"test_func[1.3]\",)),\n (\"2-3\", (\"test_func[2-3]\",)),\n ],\n)\ndef test_keyword_option_parametrize(spec, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize(\"arg\", [None, 1.3, \"2-3\"])\n def test_func(arg):\n pass\n \"\"\"\n )\n opt, passed_result = spec\n rec = testdir.inline_run(\"-k\", opt)\n passed, skipped, fail = rec.listoutcomes()\n passed = [x.nodeid.split(\"::\")[-1] for x in passed]\n assert len(passed) == len(passed_result)\n assert list(passed) == list(passed_result)"},{"col":4,"comment":"null","endLoc":310,"header":"def listoutcomes(self)","id":2531,"name":"listoutcomes","nodeType":"Function","startLoc":297,"text":"def listoutcomes(self):\n passed = []\n skipped = []\n failed = []\n for rep in self.getreports(\"pytest_collectreport pytest_runtest_logreport\"):\n if rep.passed:\n if rep.when == \"call\":\n passed.append(rep)\n elif rep.skipped:\n skipped.append(rep)\n else:\n assert rep.failed, \"Unexpected outcome: {!r}\".format(rep)\n failed.append(rep)\n return passed, skipped, failed"},{"col":4,"comment":"null","endLoc":2351,"header":"def test_module_parametrized_ordering(self, testdir)","id":2532,"name":"test_module_parametrized_ordering","nodeType":"Function","startLoc":2294,"text":"def test_module_parametrized_ordering(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style=classic\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"session\", params=\"s1 s2\".split())\n def sarg():\n pass\n @pytest.fixture(scope=\"module\", params=\"m1 m2\".split())\n def marg():\n pass\n \"\"\"\n )\n testdir.makepyfile(\n test_mod1=\"\"\"\n def test_func(sarg):\n pass\n def test_func1(marg):\n pass\n \"\"\",\n test_mod2=\"\"\"\n def test_func2(sarg):\n pass\n def test_func3(sarg, marg):\n pass\n def test_func3b(sarg, marg):\n pass\n def test_func4(marg):\n pass\n \"\"\",\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n \"\"\"\n test_mod1.py::test_func[s1] PASSED\n test_mod2.py::test_func2[s1] PASSED\n test_mod2.py::test_func3[s1-m1] PASSED\n test_mod2.py::test_func3b[s1-m1] PASSED\n test_mod2.py::test_func3[s1-m2] PASSED\n test_mod2.py::test_func3b[s1-m2] PASSED\n test_mod1.py::test_func[s2] PASSED\n test_mod2.py::test_func2[s2] PASSED\n test_mod2.py::test_func3[s2-m1] PASSED\n test_mod2.py::test_func3b[s2-m1] PASSED\n test_mod2.py::test_func4[m1] PASSED\n test_mod2.py::test_func3[s2-m2] PASSED\n test_mod2.py::test_func3b[s2-m2] PASSED\n test_mod2.py::test_func4[m2] PASSED\n test_mod1.py::test_func1[m1] PASSED\n test_mod1.py::test_func1[m2] PASSED\n \"\"\"\n )"},{"col":0,"comment":"crates a lock to prevent premature folder cleanup","endLoc":205,"header":"def create_cleanup_lock(p)","id":2533,"name":"create_cleanup_lock","nodeType":"Function","startLoc":184,"text":"def create_cleanup_lock(p):\n \"\"\"crates a lock to prevent premature folder cleanup\"\"\"\n lock_path = get_lock_path(p)\n try:\n fd = os.open(str(lock_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)\n except OSError as e:\n if e.errno == errno.EEXIST:\n six.raise_from(\n EnvironmentError(\"cannot create lockfile in {path}\".format(path=p)), e\n )\n else:\n raise\n else:\n pid = os.getpid()\n spid = str(pid)\n if not isinstance(spid, bytes):\n spid = spid.encode(\"ascii\")\n os.write(fd, spid)\n os.close(fd)\n if not lock_path.is_file():\n raise EnvironmentError(\"lock path got renamed after successful creation\")\n return lock_path"},{"col":4,"comment":"null","endLoc":2400,"header":"def test_dynamic_parametrized_ordering(self, testdir)","id":2534,"name":"test_dynamic_parametrized_ordering","nodeType":"Function","startLoc":2353,"text":"def test_dynamic_parametrized_ordering(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style=classic\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n def pytest_configure(config):\n class DynamicFixturePlugin(object):\n @pytest.fixture(scope='session', params=['flavor1', 'flavor2'])\n def flavor(self, request):\n return request.param\n config.pluginmanager.register(DynamicFixturePlugin(), 'flavor-fixture')\n\n @pytest.fixture(scope='session', params=['vxlan', 'vlan'])\n def encap(request):\n return request.param\n\n @pytest.fixture(scope='session', autouse='True')\n def reprovision(request, flavor, encap):\n pass\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test(reprovision):\n pass\n def test2(reprovision):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n \"\"\"\n test_dynamic_parametrized_ordering.py::test[flavor1-vxlan] PASSED\n test_dynamic_parametrized_ordering.py::test2[flavor1-vxlan] PASSED\n test_dynamic_parametrized_ordering.py::test[flavor2-vxlan] PASSED\n test_dynamic_parametrized_ordering.py::test2[flavor2-vxlan] PASSED\n test_dynamic_parametrized_ordering.py::test[flavor2-vlan] PASSED\n test_dynamic_parametrized_ordering.py::test2[flavor2-vlan] PASSED\n test_dynamic_parametrized_ordering.py::test[flavor1-vlan] PASSED\n test_dynamic_parametrized_ordering.py::test2[flavor1-vlan] PASSED\n \"\"\"\n )"},{"attributeType":"null","col":8,"comment":"null","endLoc":45,"id":2535,"name":"raw","nodeType":"Attribute","startLoc":45,"text":"self.raw"},{"col":4,"comment":"null","endLoc":2460,"header":"def test_class_ordering(self, testdir)","id":2536,"name":"test_class_ordering","nodeType":"Function","startLoc":2402,"text":"def test_class_ordering(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style=classic\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n values = []\n\n @pytest.fixture(scope=\"function\", params=[1,2])\n def farg(request):\n return request.param\n\n @pytest.fixture(scope=\"class\", params=list(\"ab\"))\n def carg(request):\n return request.param\n\n @pytest.fixture(scope=\"function\", autouse=True)\n def append(request, farg, carg):\n def fin():\n values.append(\"fin_%s%s\" % (carg, farg))\n request.addfinalizer(fin)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n class TestClass2(object):\n def test_1(self):\n pass\n def test_2(self):\n pass\n class TestClass(object):\n def test_3(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-vs\")\n result.stdout.re_match_lines(\n r\"\"\"\n test_class_ordering.py::TestClass2::test_1\\[a-1\\] PASSED\n test_class_ordering.py::TestClass2::test_1\\[a-2\\] PASSED\n test_class_ordering.py::TestClass2::test_2\\[a-1\\] PASSED\n test_class_ordering.py::TestClass2::test_2\\[a-2\\] PASSED\n test_class_ordering.py::TestClass2::test_1\\[b-1\\] PASSED\n test_class_ordering.py::TestClass2::test_1\\[b-2\\] PASSED\n test_class_ordering.py::TestClass2::test_2\\[b-1\\] PASSED\n test_class_ordering.py::TestClass2::test_2\\[b-2\\] PASSED\n test_class_ordering.py::TestClass::test_3\\[a-1\\] PASSED\n test_class_ordering.py::TestClass::test_3\\[a-2\\] PASSED\n test_class_ordering.py::TestClass::test_3\\[b-1\\] PASSED\n test_class_ordering.py::TestClass::test_3\\[b-2\\] PASSED\n \"\"\"\n )"},{"col":4,"comment":"null","endLoc":2536,"header":"def test_parametrize_separated_order_higher_scope_first(self, testdir)","id":2537,"name":"test_parametrize_separated_order_higher_scope_first","nodeType":"Function","startLoc":2462,"text":"def test_parametrize_separated_order_higher_scope_first(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"function\", params=[1, 2])\n def arg(request):\n param = request.param\n request.addfinalizer(lambda: values.append(\"fin:%s\" % param))\n values.append(\"create:%s\" % param)\n return request.param\n\n @pytest.fixture(scope=\"module\", params=[\"mod1\", \"mod2\"])\n def modarg(request):\n param = request.param\n request.addfinalizer(lambda: values.append(\"fin:%s\" % param))\n values.append(\"create:%s\" % param)\n return request.param\n\n values = []\n def test_1(arg):\n values.append(\"test1\")\n def test_2(modarg):\n values.append(\"test2\")\n def test_3(arg, modarg):\n values.append(\"test3\")\n def test_4(modarg, arg):\n values.append(\"test4\")\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\")\n reprec.assertoutcome(passed=12)\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n expected = [\n \"create:1\",\n \"test1\",\n \"fin:1\",\n \"create:2\",\n \"test1\",\n \"fin:2\",\n \"create:mod1\",\n \"test2\",\n \"create:1\",\n \"test3\",\n \"fin:1\",\n \"create:2\",\n \"test3\",\n \"fin:2\",\n \"create:1\",\n \"test4\",\n \"fin:1\",\n \"create:2\",\n \"test4\",\n \"fin:2\",\n \"fin:mod1\",\n \"create:mod2\",\n \"test2\",\n \"create:1\",\n \"test3\",\n \"fin:1\",\n \"create:2\",\n \"test3\",\n \"fin:2\",\n \"create:1\",\n \"test4\",\n \"fin:1\",\n \"create:2\",\n \"test4\",\n \"fin:2\",\n \"fin:mod2\",\n ]\n import pprint\n\n pprint.pprint(list(zip(values, expected)))\n assert values == expected"},{"attributeType":"null","col":12,"comment":"null","endLoc":41,"id":2538,"name":"firstlineno","nodeType":"Attribute","startLoc":41,"text":"self.firstlineno"},{"className":"ExceptionInfo","col":0,"comment":" wraps sys.exc_info() objects and offers\n help for navigating the traceback.\n ","endLoc":582,"id":2540,"nodeType":"Class","startLoc":388,"text":"@attr.s(repr=False)\nclass ExceptionInfo(object):\n \"\"\" wraps sys.exc_info() objects and offers\n help for navigating the traceback.\n \"\"\"\n\n _assert_start_repr = (\n \"AssertionError(u'assert \" if _PY2 else \"AssertionError('assert \"\n )\n\n _excinfo = attr.ib()\n _striptext = attr.ib(default=\"\")\n _traceback = attr.ib(default=None)\n\n @classmethod\n def from_current(cls, exprinfo=None):\n \"\"\"returns an ExceptionInfo matching the current traceback\n\n .. warning::\n\n Experimental API\n\n\n :param exprinfo: a text string helping to determine if we should\n strip ``AssertionError`` from the output, defaults\n to the exception message/``__str__()``\n \"\"\"\n tup = sys.exc_info()\n assert tup[0] is not None, \"no current exception\"\n _striptext = \"\"\n if exprinfo is None and isinstance(tup[1], AssertionError):\n exprinfo = getattr(tup[1], \"msg\", None)\n if exprinfo is None:\n exprinfo = saferepr(tup[1])\n if exprinfo and exprinfo.startswith(cls._assert_start_repr):\n _striptext = \"AssertionError: \"\n\n return cls(tup, _striptext)\n\n @classmethod\n def for_later(cls):\n \"\"\"return an unfilled ExceptionInfo\n \"\"\"\n return cls(None)\n\n @property\n def type(self):\n \"\"\"the exception class\"\"\"\n return self._excinfo[0]\n\n @property\n def value(self):\n \"\"\"the exception value\"\"\"\n return self._excinfo[1]\n\n @property\n def tb(self):\n \"\"\"the exception raw traceback\"\"\"\n return self._excinfo[2]\n\n @property\n def typename(self):\n \"\"\"the type name of the exception\"\"\"\n return self.type.__name__\n\n @property\n def traceback(self):\n \"\"\"the traceback\"\"\"\n if self._traceback is None:\n self._traceback = Traceback(self.tb, excinfo=ref(self))\n return self._traceback\n\n @traceback.setter\n def traceback(self, value):\n self._traceback = value\n\n def __repr__(self):\n if self._excinfo is None:\n return \"\"\n return \"\" % (self.typename, len(self.traceback))\n\n def exconly(self, tryshort=False):\n \"\"\" return the exception as a string\n\n when 'tryshort' resolves to True, and the exception is a\n _pytest._code._AssertionError, only the actual exception part of\n the exception representation is returned (so 'AssertionError: ' is\n removed from the beginning)\n \"\"\"\n lines = format_exception_only(self.type, self.value)\n text = \"\".join(lines)\n text = text.rstrip()\n if tryshort:\n if text.startswith(self._striptext):\n text = text[len(self._striptext) :]\n return text\n\n def errisinstance(self, exc):\n \"\"\" return True if the exception is an instance of exc \"\"\"\n return isinstance(self.value, exc)\n\n def _getreprcrash(self):\n exconly = self.exconly(tryshort=True)\n entry = self.traceback.getcrashentry()\n path, lineno = entry.frame.code.raw.co_filename, entry.lineno\n return ReprFileLocation(path, lineno + 1, exconly)\n\n def getrepr(\n self,\n showlocals=False,\n style=\"long\",\n abspath=False,\n tbfilter=True,\n funcargs=False,\n truncate_locals=True,\n chain=True,\n ):\n \"\"\"\n Return str()able representation of this exception info.\n\n :param bool showlocals:\n Show locals per traceback entry.\n Ignored if ``style==\"native\"``.\n\n :param str style: long|short|no|native traceback style\n\n :param bool abspath:\n If paths should be changed to absolute or left unchanged.\n\n :param bool tbfilter:\n Hide entries that contain a local variable ``__tracebackhide__==True``.\n Ignored if ``style==\"native\"``.\n\n :param bool funcargs:\n Show fixtures (\"funcargs\" for legacy purposes) per traceback entry.\n\n :param bool truncate_locals:\n With ``showlocals==True``, make sure locals can be safely represented as strings.\n\n :param bool chain: if chained exceptions in Python 3 should be shown.\n\n .. versionchanged:: 3.9\n\n Added the ``chain`` parameter.\n \"\"\"\n if style == \"native\":\n return ReprExceptionInfo(\n ReprTracebackNative(\n traceback.format_exception(\n self.type, self.value, self.traceback[0]._rawentry\n )\n ),\n self._getreprcrash(),\n )\n\n fmt = FormattedExcinfo(\n showlocals=showlocals,\n style=style,\n abspath=abspath,\n tbfilter=tbfilter,\n funcargs=funcargs,\n truncate_locals=truncate_locals,\n chain=chain,\n )\n return fmt.repr_excinfo(self)\n\n def __str__(self):\n if self._excinfo is None:\n return repr(self)\n entry = self.traceback[-1]\n loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly())\n return str(loc)\n\n def __unicode__(self):\n entry = self.traceback[-1]\n loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly())\n return text_type(loc)\n\n def match(self, regexp):\n \"\"\"\n Check whether the regular expression 'regexp' is found in the string\n representation of the exception using ``re.search``. If it matches\n then True is returned (so that it is possible to write\n ``assert excinfo.match()``). If it doesn't match an AssertionError is\n raised.\n \"\"\"\n __tracebackhide__ = True\n value = (\n text_type(self.value) if isinstance(regexp, text_type) else str(self.value)\n )\n if not re.search(regexp, value):\n raise AssertionError(\n u\"Pattern {!r} not found in {!r}\".format(regexp, value)\n )\n return True"},{"col":4,"comment":"the exception class","endLoc":436,"header":"@property\n def type(self)","id":2541,"name":"type","nodeType":"Function","startLoc":433,"text":"@property\n def type(self):\n \"\"\"the exception class\"\"\"\n return self._excinfo[0]"},{"col":4,"comment":"the exception value","endLoc":441,"header":"@property\n def value(self)","id":2542,"name":"value","nodeType":"Function","startLoc":438,"text":"@property\n def value(self):\n \"\"\"the exception value\"\"\"\n return self._excinfo[1]"},{"col":4,"comment":"the exception raw traceback","endLoc":446,"header":"@property\n def tb(self)","id":2543,"name":"tb","nodeType":"Function","startLoc":443,"text":"@property\n def tb(self):\n \"\"\"the exception raw traceback\"\"\"\n return self._excinfo[2]"},{"col":4,"comment":"the type name of the exception","endLoc":451,"header":"@property\n def typename(self)","id":2544,"name":"typename","nodeType":"Function","startLoc":448,"text":"@property\n def typename(self):\n \"\"\"the type name of the exception\"\"\"\n return self.type.__name__"},{"col":4,"comment":"the traceback","endLoc":458,"header":"@property\n def traceback(self)","id":2545,"name":"traceback","nodeType":"Function","startLoc":453,"text":"@property\n def traceback(self):\n \"\"\"the traceback\"\"\"\n if self._traceback is None:\n self._traceback = Traceback(self.tb, excinfo=ref(self))\n return self._traceback"},{"col":4,"comment":"null","endLoc":313,"header":"def countoutcomes(self)","id":2546,"name":"countoutcomes","nodeType":"Function","startLoc":312,"text":"def countoutcomes(self):\n return [len(x) for x in self.listoutcomes()]"},{"col":4,"comment":"null","endLoc":319,"header":"def assertoutcome(self, passed=0, skipped=0, failed=0)","id":2547,"name":"assertoutcome","nodeType":"Function","startLoc":315,"text":"def assertoutcome(self, passed=0, skipped=0, failed=0):\n realpassed, realskipped, realfailed = self.listoutcomes()\n assert passed == len(realpassed)\n assert skipped == len(realskipped)\n assert failed == len(realfailed)"},{"col":4,"comment":"null","endLoc":322,"header":"def clear(self)","id":2548,"name":"clear","nodeType":"Function","startLoc":321,"text":"def clear(self):\n self.calls[:] = []"},{"attributeType":"null","col":8,"comment":"null","endLoc":205,"id":2549,"name":"calls","nodeType":"Attribute","startLoc":205,"text":"self.calls"},{"attributeType":"null","col":8,"comment":"null","endLoc":213,"id":2550,"name":"_undo_wrapping","nodeType":"Attribute","startLoc":213,"text":"self._undo_wrapping"},{"attributeType":"null","col":8,"comment":"null","endLoc":204,"id":2551,"name":"_pluginmanager","nodeType":"Attribute","startLoc":204,"text":"self._pluginmanager"},{"className":"LineMatcher","col":0,"comment":"Flexible matching of text.\n\n This is a convenience class to test large texts like the output of\n commands.\n\n The constructor takes a list of lines without their trailing newlines, i.e.\n ``text.splitlines()``.\n\n ","endLoc":1413,"id":2552,"nodeType":"Class","startLoc":1274,"text":"class LineMatcher(object):\n \"\"\"Flexible matching of text.\n\n This is a convenience class to test large texts like the output of\n commands.\n\n The constructor takes a list of lines without their trailing newlines, i.e.\n ``text.splitlines()``.\n\n \"\"\"\n\n def __init__(self, lines):\n self.lines = lines\n self._log_output = []\n\n def str(self):\n \"\"\"Return the entire original text.\"\"\"\n return \"\\n\".join(self.lines)\n\n def _getlines(self, lines2):\n if isinstance(lines2, str):\n lines2 = Source(lines2)\n if isinstance(lines2, Source):\n lines2 = lines2.strip().lines\n return lines2\n\n def fnmatch_lines_random(self, lines2):\n \"\"\"Check lines exist in the output using in any order.\n\n Lines are checked using ``fnmatch.fnmatch``. The argument is a list of\n lines which have to occur in the output, in any order.\n\n \"\"\"\n self._match_lines_random(lines2, fnmatch)\n\n def re_match_lines_random(self, lines2):\n \"\"\"Check lines exist in the output using ``re.match``, in any order.\n\n The argument is a list of lines which have to occur in the output, in\n any order.\n\n \"\"\"\n self._match_lines_random(lines2, lambda name, pat: re.match(pat, name))\n\n def _match_lines_random(self, lines2, match_func):\n \"\"\"Check lines exist in the output.\n\n The argument is a list of lines which have to occur in the output, in\n any order. Each line can contain glob whildcards.\n\n \"\"\"\n lines2 = self._getlines(lines2)\n for line in lines2:\n for x in self.lines:\n if line == x or match_func(x, line):\n self._log(\"matched: \", repr(line))\n break\n else:\n self._log(\"line %r not found in output\" % line)\n raise ValueError(self._log_text)\n\n def get_lines_after(self, fnline):\n \"\"\"Return all lines following the given line in the text.\n\n The given line can contain glob wildcards.\n\n \"\"\"\n for i, line in enumerate(self.lines):\n if fnline == line or fnmatch(line, fnline):\n return self.lines[i + 1 :]\n raise ValueError(\"line %r not found in output\" % fnline)\n\n def _log(self, *args):\n self._log_output.append(\" \".join(str(x) for x in args))\n\n @property\n def _log_text(self):\n return \"\\n\".join(self._log_output)\n\n def fnmatch_lines(self, lines2):\n \"\"\"Search captured text for matching lines using ``fnmatch.fnmatch``.\n\n The argument is a list of lines which have to match and can use glob\n wildcards. If they do not match a pytest.fail() is called. The\n matches and non-matches are also printed on stdout.\n\n \"\"\"\n __tracebackhide__ = True\n self._match_lines(lines2, fnmatch, \"fnmatch\")\n\n def re_match_lines(self, lines2):\n \"\"\"Search captured text for matching lines using ``re.match``.\n\n The argument is a list of lines which have to match using ``re.match``.\n If they do not match a pytest.fail() is called.\n\n The matches and non-matches are also printed on stdout.\n\n \"\"\"\n __tracebackhide__ = True\n self._match_lines(lines2, lambda name, pat: re.match(pat, name), \"re.match\")\n\n def _match_lines(self, lines2, match_func, match_nickname):\n \"\"\"Underlying implementation of ``fnmatch_lines`` and ``re_match_lines``.\n\n :param list[str] lines2: list of string patterns to match. The actual\n format depends on ``match_func``\n :param match_func: a callable ``match_func(line, pattern)`` where line\n is the captured line from stdout/stderr and pattern is the matching\n pattern\n :param str match_nickname: the nickname for the match function that\n will be logged to stdout when a match occurs\n\n \"\"\"\n assert isinstance(lines2, Sequence)\n lines2 = self._getlines(lines2)\n lines1 = self.lines[:]\n nextline = None\n extralines = []\n __tracebackhide__ = True\n for line in lines2:\n nomatchprinted = False\n while lines1:\n nextline = lines1.pop(0)\n if line == nextline:\n self._log(\"exact match:\", repr(line))\n break\n elif match_func(nextline, line):\n self._log(\"%s:\" % match_nickname, repr(line))\n self._log(\" with:\", repr(nextline))\n break\n else:\n if not nomatchprinted:\n self._log(\"nomatch:\", repr(line))\n nomatchprinted = True\n self._log(\" and:\", repr(nextline))\n extralines.append(nextline)\n else:\n self._log(\"remains unmatched: %r\" % (line,))\n pytest.fail(self._log_text)"},{"col":4,"comment":"null","endLoc":1287,"header":"def __init__(self, lines)","id":2553,"name":"__init__","nodeType":"Function","startLoc":1285,"text":"def __init__(self, lines):\n self.lines = lines\n self._log_output = []"},{"col":4,"comment":"Return the entire original text.","endLoc":1291,"header":"def str(self)","id":2554,"name":"str","nodeType":"Function","startLoc":1289,"text":"def str(self):\n \"\"\"Return the entire original text.\"\"\"\n return \"\\n\".join(self.lines)"},{"col":4,"comment":"null","endLoc":1298,"header":"def _getlines(self, lines2)","id":2555,"name":"_getlines","nodeType":"Function","startLoc":1293,"text":"def _getlines(self, lines2):\n if isinstance(lines2, str):\n lines2 = Source(lines2)\n if isinstance(lines2, Source):\n lines2 = lines2.strip().lines\n return lines2"},{"col":0,"comment":"null","endLoc":353,"header":"@pytest.mark.parametrize(\n \"spec\",\n [\n (\n \"foo or import\",\n \"ERROR: Python keyword 'import' not accepted in expressions passed to '-k'\",\n ),\n (\"foo or\", \"ERROR","id":2557,"name":"test_keyword_option_wrong_arguments","nodeType":"Function","startLoc":333,"text":"@pytest.mark.parametrize(\n \"spec\",\n [\n (\n \"foo or import\",\n \"ERROR: Python keyword 'import' not accepted in expressions passed to '-k'\",\n ),\n (\"foo or\", \"ERROR: Wrong expression passed to '-k': foo or\"),\n ],\n)\ndef test_keyword_option_wrong_arguments(spec, testdir, capsys):\n testdir.makepyfile(\n \"\"\"\n def test_func(arg):\n pass\n \"\"\"\n )\n opt, expected_result = spec\n testdir.inline_run(\"-k\", opt)\n out = capsys.readouterr().err\n assert expected_result in out"},{"col":4,"comment":"Check lines exist in the output using in any order.\n\n Lines are checked using ``fnmatch.fnmatch``. The argument is a list of\n lines which have to occur in the output, in any order.\n\n ","endLoc":1307,"header":"def fnmatch_lines_random(self, lines2)","id":2558,"name":"fnmatch_lines_random","nodeType":"Function","startLoc":1300,"text":"def fnmatch_lines_random(self, lines2):\n \"\"\"Check lines exist in the output using in any order.\n\n Lines are checked using ``fnmatch.fnmatch``. The argument is a list of\n lines which have to occur in the output, in any order.\n\n \"\"\"\n self._match_lines_random(lines2, fnmatch)"},{"col":4,"comment":"Check lines exist in the output.\n\n The argument is a list of lines which have to occur in the output, in\n any order. Each line can contain glob whildcards.\n\n ","endLoc":1333,"header":"def _match_lines_random(self, lines2, match_func)","id":2559,"name":"_match_lines_random","nodeType":"Function","startLoc":1318,"text":"def _match_lines_random(self, lines2, match_func):\n \"\"\"Check lines exist in the output.\n\n The argument is a list of lines which have to occur in the output, in\n any order. Each line can contain glob whildcards.\n\n \"\"\"\n lines2 = self._getlines(lines2)\n for line in lines2:\n for x in self.lines:\n if line == x or match_func(x, line):\n self._log(\"matched: \", repr(line))\n break\n else:\n self._log(\"line %r not found in output\" % line)\n raise ValueError(self._log_text)"},{"col":4,"comment":"null","endLoc":1347,"header":"def _log(self, *args)","id":2560,"name":"_log","nodeType":"Function","startLoc":1346,"text":"def _log(self, *args):\n self._log_output.append(\" \".join(str(x) for x in args))"},{"col":0,"comment":"Parametrized test not collected if test named specified\n in command line issue#649.\n ","endLoc":370,"header":"def test_parametrized_collected_from_command_line(testdir)","id":2561,"name":"test_parametrized_collected_from_command_line","nodeType":"Function","startLoc":356,"text":"def test_parametrized_collected_from_command_line(testdir):\n \"\"\"Parametrized test not collected if test named specified\n in command line issue#649.\n \"\"\"\n py_file = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize(\"arg\", [None, 1.3, \"2-3\"])\n def test_func(arg):\n pass\n \"\"\"\n )\n file_name = os.path.basename(py_file.strpath)\n rec = testdir.inline_run(file_name + \"::\" + \"test_func\")\n rec.assertoutcome(passed=3)"},{"col":4,"comment":"Check lines exist in the output using ``re.match``, in any order.\n\n The argument is a list of lines which have to occur in the output, in\n any order.\n\n ","endLoc":1316,"header":"def re_match_lines_random(self, lines2)","id":2562,"name":"re_match_lines_random","nodeType":"Function","startLoc":1309,"text":"def re_match_lines_random(self, lines2):\n \"\"\"Check lines exist in the output using ``re.match``, in any order.\n\n The argument is a list of lines which have to occur in the output, in\n any order.\n\n \"\"\"\n self._match_lines_random(lines2, lambda name, pat: re.match(pat, name))"},{"col":0,"comment":"null","endLoc":252,"header":"@overload\ndef match(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Match[str] | None","id":2563,"name":"match","nodeType":"Function","startLoc":251,"text":"@overload\ndef match(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Match[str] | None: ..."},{"col":0,"comment":"null","endLoc":254,"header":"@overload\ndef match(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None","id":2564,"name":"match","nodeType":"Function","startLoc":253,"text":"@overload\ndef match(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None: ..."},{"col":41,"endLoc":1316,"id":2565,"nodeType":"Lambda","startLoc":1316,"text":"lambda name, pat: re.match(pat, name)"},{"col":4,"comment":"Return all lines following the given line in the text.\n\n The given line can contain glob wildcards.\n\n ","endLoc":1344,"header":"def get_lines_after(self, fnline)","id":2566,"name":"get_lines_after","nodeType":"Function","startLoc":1335,"text":"def get_lines_after(self, fnline):\n \"\"\"Return all lines following the given line in the text.\n\n The given line can contain glob wildcards.\n\n \"\"\"\n for i, line in enumerate(self.lines):\n if fnline == line or fnmatch(line, fnline):\n return self.lines[i + 1 :]\n raise ValueError(\"line %r not found in output\" % fnline)"},{"col":0,"comment":"Test collect parametrized func with wrong number of args.","endLoc":393,"header":"def test_parametrized_collect_with_wrong_args(testdir)","id":2567,"name":"test_parametrized_collect_with_wrong_args","nodeType":"Function","startLoc":373,"text":"def test_parametrized_collect_with_wrong_args(testdir):\n \"\"\"Test collect parametrized func with wrong number of args.\"\"\"\n py_file = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize('foo, bar', [(1, 2, 3)])\n def test_func(foo, bar):\n pass\n \"\"\"\n )\n\n result = testdir.runpytest(py_file)\n result.stdout.fnmatch_lines(\n [\n 'test_parametrized_collect_with_wrong_args.py::test_func: in \"parametrize\" the number of names (2):',\n \" ['foo', 'bar']\",\n \"must be equal to the number of values (3):\",\n \" (1, 2, 3)\",\n ]\n )"},{"col":0,"comment":"Test collect parametrized func with wrong number of args.","endLoc":413,"header":"def test_parametrized_with_kwargs(testdir)","id":2568,"name":"test_parametrized_with_kwargs","nodeType":"Function","startLoc":396,"text":"def test_parametrized_with_kwargs(testdir):\n \"\"\"Test collect parametrized func with wrong number of args.\"\"\"\n py_file = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[1,2])\n def a(request):\n return request.param\n\n @pytest.mark.parametrize(argnames='b', argvalues=[1, 2])\n def test_func(a, b):\n pass\n \"\"\"\n )\n\n result = testdir.runpytest(py_file)\n assert result.ret == 0"},{"col":4,"comment":"null","endLoc":1351,"header":"@property\n def _log_text(self)","id":2569,"name":"_log_text","nodeType":"Function","startLoc":1349,"text":"@property\n def _log_text(self):\n return \"\\n\".join(self._log_output)"},{"col":4,"comment":"Search captured text for matching lines using ``fnmatch.fnmatch``.\n\n The argument is a list of lines which have to match and can use glob\n wildcards. If they do not match a pytest.fail() is called. The\n matches and non-matches are also printed on stdout.\n\n ","endLoc":1362,"header":"def fnmatch_lines(self, lines2)","id":2570,"name":"fnmatch_lines","nodeType":"Function","startLoc":1353,"text":"def fnmatch_lines(self, lines2):\n \"\"\"Search captured text for matching lines using ``fnmatch.fnmatch``.\n\n The argument is a list of lines which have to match and can use glob\n wildcards. If they do not match a pytest.fail() is called. The\n matches and non-matches are also printed on stdout.\n\n \"\"\"\n __tracebackhide__ = True\n self._match_lines(lines2, fnmatch, \"fnmatch\")"},{"col":4,"comment":"Underlying implementation of ``fnmatch_lines`` and ``re_match_lines``.\n\n :param list[str] lines2: list of string patterns to match. The actual\n format depends on ``match_func``\n :param match_func: a callable ``match_func(line, pattern)`` where line\n is the captured line from stdout/stderr and pattern is the matching\n pattern\n :param str match_nickname: the nickname for the match function that\n will be logged to stdout when a match occurs\n\n ","endLoc":1413,"header":"def _match_lines(self, lines2, match_func, match_nickname)","id":2572,"name":"_match_lines","nodeType":"Function","startLoc":1376,"text":"def _match_lines(self, lines2, match_func, match_nickname):\n \"\"\"Underlying implementation of ``fnmatch_lines`` and ``re_match_lines``.\n\n :param list[str] lines2: list of string patterns to match. The actual\n format depends on ``match_func``\n :param match_func: a callable ``match_func(line, pattern)`` where line\n is the captured line from stdout/stderr and pattern is the matching\n pattern\n :param str match_nickname: the nickname for the match function that\n will be logged to stdout when a match occurs\n\n \"\"\"\n assert isinstance(lines2, Sequence)\n lines2 = self._getlines(lines2)\n lines1 = self.lines[:]\n nextline = None\n extralines = []\n __tracebackhide__ = True\n for line in lines2:\n nomatchprinted = False\n while lines1:\n nextline = lines1.pop(0)\n if line == nextline:\n self._log(\"exact match:\", repr(line))\n break\n elif match_func(nextline, line):\n self._log(\"%s:\" % match_nickname, repr(line))\n self._log(\" with:\", repr(nextline))\n break\n else:\n if not nomatchprinted:\n self._log(\"nomatch:\", repr(line))\n nomatchprinted = True\n self._log(\" and:\", repr(nextline))\n extralines.append(nextline)\n else:\n self._log(\"remains unmatched: %r\" % (line,))\n pytest.fail(self._log_text)"},{"col":0,"comment":"parametrize should work with generators (#5354).","endLoc":435,"header":"def test_parametrize_iterator(testdir)","id":2574,"name":"test_parametrize_iterator","nodeType":"Function","startLoc":416,"text":"def test_parametrize_iterator(testdir):\n \"\"\"parametrize should work with generators (#5354).\"\"\"\n py_file = testdir.makepyfile(\n \"\"\"\\\n import pytest\n\n def gen():\n yield 1\n yield 2\n yield 3\n\n @pytest.mark.parametrize('a', gen())\n def test(a):\n assert a >= 1\n \"\"\"\n )\n result = testdir.runpytest(py_file)\n assert result.ret == 0\n # should not skip any tests\n result.stdout.fnmatch_lines([\"*3 passed*\"])"},{"col":0,"comment":"null","endLoc":875,"header":"@pytest.mark.parametrize(\"mark\", [None, \"\", \"skip\", \"xfail\"])\ndef test_parameterset_for_parametrize_marks(testdir, mark)","id":2575,"name":"test_parameterset_for_parametrize_marks","nodeType":"Function","startLoc":852,"text":"@pytest.mark.parametrize(\"mark\", [None, \"\", \"skip\", \"xfail\"])\ndef test_parameterset_for_parametrize_marks(testdir, mark):\n if mark is not None:\n testdir.makeini(\n \"\"\"\n [pytest]\n {}={}\n \"\"\".format(\n EMPTY_PARAMETERSET_OPTION, mark\n )\n )\n\n config = testdir.parseconfig()\n from _pytest.mark import pytest_configure, get_empty_parameterset_mark\n\n pytest_configure(config)\n result_mark = get_empty_parameterset_mark(config, [\"a\"], all)\n if mark in (None, \"\"):\n # normalize to the requested name\n mark = \"skip\"\n assert result_mark.name == mark\n assert result_mark.kwargs[\"reason\"].startswith(\"got empty parameter set \")\n if mark == \"xfail\":\n assert result_mark.kwargs.get(\"run\") is False"},{"col":4,"comment":"null","endLoc":462,"header":"@traceback.setter\n def traceback(self, value)","id":2576,"name":"traceback","nodeType":"Function","startLoc":460,"text":"@traceback.setter\n def traceback(self, value):\n self._traceback = value"},{"col":4,"comment":"null","endLoc":467,"header":"def __repr__(self)","id":2577,"name":"__repr__","nodeType":"Function","startLoc":464,"text":"def __repr__(self):\n if self._excinfo is None:\n return \"\"\n return \"\" % (self.typename, len(self.traceback))"},{"col":0,"comment":"null","endLoc":162,"header":"def pytest_configure(config)","id":2578,"name":"pytest_configure","nodeType":"Function","startLoc":152,"text":"def pytest_configure(config):\n config._old_mark_config = MARK_GEN._config\n MARK_GEN._config = config\n\n empty_parameterset = config.getini(EMPTY_PARAMETERSET_OPTION)\n\n if empty_parameterset not in (\"skip\", \"xfail\", \"fail_at_collect\", None, \"\"):\n raise UsageError(\n \"{!s} must be one of skip, xfail or fail_at_collect\"\n \" but it is {!r}\".format(EMPTY_PARAMETERSET_OPTION, empty_parameterset)\n )"},{"col":4,"comment":" return the exception as a string\n\n when 'tryshort' resolves to True, and the exception is a\n _pytest._code._AssertionError, only the actual exception part of\n the exception representation is returned (so 'AssertionError: ' is\n removed from the beginning)\n ","endLoc":483,"header":"def exconly(self, tryshort=False)","id":2579,"name":"exconly","nodeType":"Function","startLoc":469,"text":"def exconly(self, tryshort=False):\n \"\"\" return the exception as a string\n\n when 'tryshort' resolves to True, and the exception is a\n _pytest._code._AssertionError, only the actual exception part of\n the exception representation is returned (so 'AssertionError: ' is\n removed from the beginning)\n \"\"\"\n lines = format_exception_only(self.type, self.value)\n text = \"\".join(lines)\n text = text.rstrip()\n if tryshort:\n if text.startswith(self._striptext):\n text = text[len(self._striptext) :]\n return text"},{"col":4,"comment":"null","endLoc":101,"header":"def format_exception_only(etype: type[BaseException] | None, value: BaseException | None) -> list[str]","id":2580,"name":"format_exception_only","nodeType":"Function","startLoc":101,"text":"def format_exception_only(etype: type[BaseException] | None, value: BaseException | None) -> list[str]: ..."},{"fileName":"__init__.py","filePath":"src/_pytest/config","id":2581,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\" command line options, ini-file and conftest.py processing. \"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport copy\nimport inspect\nimport os\nimport shlex\nimport sys\nimport types\nimport warnings\n\nimport importlib_metadata\nimport py\nimport six\nfrom packaging.version import Version\nfrom pluggy import HookimplMarker\nfrom pluggy import HookspecMarker\nfrom pluggy import PluginManager\n\nimport _pytest._code\nimport _pytest.assertion\nimport _pytest.hookspec # the extension point definitions\nfrom .exceptions import PrintHelp\nfrom .exceptions import UsageError\nfrom .findpaths import determine_setup\nfrom .findpaths import exists\nfrom _pytest import deprecated\nfrom _pytest._code import ExceptionInfo\nfrom _pytest._code import filter_traceback\nfrom _pytest.compat import lru_cache\nfrom _pytest.compat import safe_str\nfrom _pytest.outcomes import fail\nfrom _pytest.outcomes import Skipped\nfrom _pytest.warning_types import PytestConfigWarning\n\nhookimpl = HookimplMarker(\"pytest\")\nhookspec = HookspecMarker(\"pytest\")\n\n\nclass ConftestImportFailure(Exception):\n def __init__(self, path, excinfo):\n Exception.__init__(self, path, excinfo)\n self.path = path\n self.excinfo = excinfo\n\n\ndef main(args=None, plugins=None):\n \"\"\" return exit code, after performing an in-process test run.\n\n :arg args: list of command line arguments.\n\n :arg plugins: list of plugin objects to be auto-registered during\n initialization.\n \"\"\"\n from _pytest.main import EXIT_USAGEERROR\n\n try:\n try:\n config = _prepareconfig(args, plugins)\n except ConftestImportFailure as e:\n exc_info = ExceptionInfo(e.excinfo)\n tw = py.io.TerminalWriter(sys.stderr)\n tw.line(\n \"ImportError while loading conftest '{e.path}'.\".format(e=e), red=True\n )\n exc_info.traceback = exc_info.traceback.filter(filter_traceback)\n exc_repr = (\n exc_info.getrepr(style=\"short\", chain=False)\n if exc_info.traceback\n else exc_info.exconly()\n )\n formatted_tb = safe_str(exc_repr)\n for line in formatted_tb.splitlines():\n tw.line(line.rstrip(), red=True)\n return 4\n else:\n try:\n return config.hook.pytest_cmdline_main(config=config)\n finally:\n config._ensure_unconfigure()\n except UsageError as e:\n tw = py.io.TerminalWriter(sys.stderr)\n for msg in e.args:\n tw.line(\"ERROR: {}\\n\".format(msg), red=True)\n return EXIT_USAGEERROR\n\n\nclass cmdline(object): # compatibility namespace\n main = staticmethod(main)\n\n\ndef filename_arg(path, optname):\n \"\"\" Argparse type validator for filename arguments.\n\n :path: path of filename\n :optname: name of the option\n \"\"\"\n if os.path.isdir(path):\n raise UsageError(\"{} must be a filename, given: {}\".format(optname, path))\n return path\n\n\ndef directory_arg(path, optname):\n \"\"\"Argparse type validator for directory arguments.\n\n :path: path of directory\n :optname: name of the option\n \"\"\"\n if not os.path.isdir(path):\n raise UsageError(\"{} must be a directory, given: {}\".format(optname, path))\n return path\n\n\n# Plugins that cannot be disabled via \"-p no:X\" currently.\nessential_plugins = ( # fmt: off\n \"mark\",\n \"main\",\n \"runner\",\n \"fixtures\",\n \"helpconfig\", # Provides -p.\n) # fmt: on\n\ndefault_plugins = essential_plugins + (\n \"python\",\n \"terminal\",\n \"debugging\",\n \"unittest\",\n \"capture\",\n \"skipping\",\n \"tmpdir\",\n \"monkeypatch\",\n \"recwarn\",\n \"pastebin\",\n \"nose\",\n \"assertion\",\n \"junitxml\",\n \"resultlog\",\n \"doctest\",\n \"cacheprovider\",\n \"freeze_support\",\n \"setuponly\",\n \"setupplan\",\n \"stepwise\",\n \"warnings\",\n \"logging\",\n \"reports\",\n)\n\nbuiltin_plugins = set(default_plugins)\nbuiltin_plugins.add(\"pytester\")\n\n\ndef get_config(args=None):\n # subsequent calls to main will create a fresh instance\n pluginmanager = PytestPluginManager()\n config = Config(pluginmanager)\n\n if args is not None:\n # Handle any \"-p no:plugin\" args.\n pluginmanager.consider_preparse(args)\n\n for spec in default_plugins:\n pluginmanager.import_plugin(spec)\n return config\n\n\ndef get_plugin_manager():\n \"\"\"\n Obtain a new instance of the\n :py:class:`_pytest.config.PytestPluginManager`, with default plugins\n already loaded.\n\n This function can be used by integration with other tools, like hooking\n into pytest to run tests into an IDE.\n \"\"\"\n return get_config().pluginmanager\n\n\ndef _prepareconfig(args=None, plugins=None):\n warning = None\n if args is None:\n args = sys.argv[1:]\n elif isinstance(args, py.path.local):\n args = [str(args)]\n elif not isinstance(args, (tuple, list)):\n msg = \"`args` parameter expected to be a list or tuple of strings, got: {!r} (type: {})\"\n raise TypeError(msg.format(args, type(args)))\n\n config = get_config(args)\n pluginmanager = config.pluginmanager\n try:\n if plugins:\n for plugin in plugins:\n if isinstance(plugin, six.string_types):\n pluginmanager.consider_pluginarg(plugin)\n else:\n pluginmanager.register(plugin)\n if warning:\n from _pytest.warnings import _issue_warning_captured\n\n _issue_warning_captured(warning, hook=config.hook, stacklevel=4)\n return pluginmanager.hook.pytest_cmdline_parse(\n pluginmanager=pluginmanager, args=args\n )\n except BaseException:\n config._ensure_unconfigure()\n raise\n\n\nclass PytestPluginManager(PluginManager):\n \"\"\"\n Overwrites :py:class:`pluggy.PluginManager ` to add pytest-specific\n functionality:\n\n * loading plugins from the command line, ``PYTEST_PLUGINS`` env variable and\n ``pytest_plugins`` global variables found in plugins being loaded;\n * ``conftest.py`` loading during start-up;\n \"\"\"\n\n def __init__(self):\n super(PytestPluginManager, self).__init__(\"pytest\")\n self._conftest_plugins = set()\n\n # state related to local conftest plugins\n self._dirpath2confmods = {}\n self._conftestpath2mod = {}\n self._confcutdir = None\n self._noconftest = False\n self._duplicatepaths = set()\n\n self.add_hookspecs(_pytest.hookspec)\n self.register(self)\n if os.environ.get(\"PYTEST_DEBUG\"):\n err = sys.stderr\n encoding = getattr(err, \"encoding\", \"utf8\")\n try:\n err = py.io.dupfile(err, encoding=encoding)\n except Exception:\n pass\n self.trace.root.setwriter(err.write)\n self.enable_tracing()\n\n # Config._consider_importhook will set a real object if required.\n self.rewrite_hook = _pytest.assertion.DummyRewriteHook()\n # Used to know when we are importing conftests after the pytest_configure stage\n self._configured = False\n\n def addhooks(self, module_or_class):\n \"\"\"\n .. deprecated:: 2.8\n\n Use :py:meth:`pluggy.PluginManager.add_hookspecs `\n instead.\n \"\"\"\n warnings.warn(deprecated.PLUGIN_MANAGER_ADDHOOKS, stacklevel=2)\n return self.add_hookspecs(module_or_class)\n\n def parse_hookimpl_opts(self, plugin, name):\n # pytest hooks are always prefixed with pytest_\n # so we avoid accessing possibly non-readable attributes\n # (see issue #1073)\n if not name.startswith(\"pytest_\"):\n return\n # ignore names which can not be hooks\n if name == \"pytest_plugins\":\n return\n\n method = getattr(plugin, name)\n opts = super(PytestPluginManager, self).parse_hookimpl_opts(plugin, name)\n\n # consider only actual functions for hooks (#3775)\n if not inspect.isroutine(method):\n return\n\n # collect unmarked hooks as long as they have the `pytest_' prefix\n if opts is None and name.startswith(\"pytest_\"):\n opts = {}\n if opts is not None:\n # TODO: DeprecationWarning, people should use hookimpl\n # https://github.com/pytest-dev/pytest/issues/4562\n known_marks = {m.name for m in getattr(method, \"pytestmark\", [])}\n\n for name in (\"tryfirst\", \"trylast\", \"optionalhook\", \"hookwrapper\"):\n opts.setdefault(name, hasattr(method, name) or name in known_marks)\n return opts\n\n def parse_hookspec_opts(self, module_or_class, name):\n opts = super(PytestPluginManager, self).parse_hookspec_opts(\n module_or_class, name\n )\n if opts is None:\n method = getattr(module_or_class, name)\n\n if name.startswith(\"pytest_\"):\n # todo: deprecate hookspec hacks\n # https://github.com/pytest-dev/pytest/issues/4562\n known_marks = {m.name for m in getattr(method, \"pytestmark\", [])}\n opts = {\n \"firstresult\": hasattr(method, \"firstresult\")\n or \"firstresult\" in known_marks,\n \"historic\": hasattr(method, \"historic\")\n or \"historic\" in known_marks,\n }\n return opts\n\n def register(self, plugin, name=None):\n if name in [\"pytest_catchlog\", \"pytest_capturelog\"]:\n warnings.warn(\n PytestConfigWarning(\n \"{} plugin has been merged into the core, \"\n \"please remove it from your requirements.\".format(\n name.replace(\"_\", \"-\")\n )\n )\n )\n return\n ret = super(PytestPluginManager, self).register(plugin, name)\n if ret:\n self.hook.pytest_plugin_registered.call_historic(\n kwargs=dict(plugin=plugin, manager=self)\n )\n\n if isinstance(plugin, types.ModuleType):\n self.consider_module(plugin)\n return ret\n\n def getplugin(self, name):\n # support deprecated naming because plugins (xdist e.g.) use it\n return self.get_plugin(name)\n\n def hasplugin(self, name):\n \"\"\"Return True if the plugin with the given name is registered.\"\"\"\n return bool(self.get_plugin(name))\n\n def pytest_configure(self, config):\n # XXX now that the pluginmanager exposes hookimpl(tryfirst...)\n # we should remove tryfirst/trylast as markers\n config.addinivalue_line(\n \"markers\",\n \"tryfirst: mark a hook implementation function such that the \"\n \"plugin machinery will try to call it first/as early as possible.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"trylast: mark a hook implementation function such that the \"\n \"plugin machinery will try to call it last/as late as possible.\",\n )\n self._configured = True\n\n #\n # internal API for local conftest plugin handling\n #\n def _set_initial_conftests(self, namespace):\n \"\"\" load initial conftest files given a preparsed \"namespace\".\n As conftest files may add their own command line options\n which have arguments ('--my-opt somepath') we might get some\n false positives. All builtin and 3rd party plugins will have\n been loaded, however, so common options will not confuse our logic\n here.\n \"\"\"\n current = py.path.local()\n self._confcutdir = (\n current.join(namespace.confcutdir, abs=True)\n if namespace.confcutdir\n else None\n )\n self._noconftest = namespace.noconftest\n self._using_pyargs = namespace.pyargs\n testpaths = namespace.file_or_dir\n foundanchor = False\n for path in testpaths:\n path = str(path)\n # remove node-id syntax\n i = path.find(\"::\")\n if i != -1:\n path = path[:i]\n anchor = current.join(path, abs=1)\n if exists(anchor): # we found some file object\n self._try_load_conftest(anchor)\n foundanchor = True\n if not foundanchor:\n self._try_load_conftest(current)\n\n def _try_load_conftest(self, anchor):\n self._getconftestmodules(anchor)\n # let's also consider test* subdirs\n if anchor.check(dir=1):\n for x in anchor.listdir(\"test*\"):\n if x.check(dir=1):\n self._getconftestmodules(x)\n\n @lru_cache(maxsize=128)\n def _getconftestmodules(self, path):\n if self._noconftest:\n return []\n\n if path.isfile():\n directory = path.dirpath()\n else:\n directory = path\n\n if six.PY2: # py2 is not using lru_cache.\n try:\n return self._dirpath2confmods[directory]\n except KeyError:\n pass\n\n # XXX these days we may rather want to use config.rootdir\n # and allow users to opt into looking into the rootdir parent\n # directories instead of requiring to specify confcutdir\n clist = []\n for parent in directory.realpath().parts():\n if self._confcutdir and self._confcutdir.relto(parent):\n continue\n conftestpath = parent.join(\"conftest.py\")\n if conftestpath.isfile():\n # Use realpath to avoid loading the same conftest twice\n # with build systems that create build directories containing\n # symlinks to actual files.\n mod = self._importconftest(conftestpath.realpath())\n clist.append(mod)\n self._dirpath2confmods[directory] = clist\n return clist\n\n def _rget_with_confmod(self, name, path):\n modules = self._getconftestmodules(path)\n for mod in reversed(modules):\n try:\n return mod, getattr(mod, name)\n except AttributeError:\n continue\n raise KeyError(name)\n\n def _importconftest(self, conftestpath):\n try:\n return self._conftestpath2mod[conftestpath]\n except KeyError:\n pkgpath = conftestpath.pypkgpath()\n if pkgpath is None:\n _ensure_removed_sysmodule(conftestpath.purebasename)\n try:\n mod = conftestpath.pyimport()\n if (\n hasattr(mod, \"pytest_plugins\")\n and self._configured\n and not self._using_pyargs\n ):\n from _pytest.deprecated import (\n PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST,\n )\n\n fail(\n PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST.format(\n conftestpath, self._confcutdir\n ),\n pytrace=False,\n )\n except Exception:\n raise ConftestImportFailure(conftestpath, sys.exc_info())\n\n self._conftest_plugins.add(mod)\n self._conftestpath2mod[conftestpath] = mod\n dirpath = conftestpath.dirpath()\n if dirpath in self._dirpath2confmods:\n for path, mods in self._dirpath2confmods.items():\n if path and path.relto(dirpath) or path == dirpath:\n assert mod not in mods\n mods.append(mod)\n self.trace(\"loaded conftestmodule %r\" % (mod))\n self.consider_conftest(mod)\n return mod\n\n #\n # API for bootstrapping plugin loading\n #\n #\n\n def consider_preparse(self, args):\n i = 0\n n = len(args)\n while i < n:\n opt = args[i]\n i += 1\n if isinstance(opt, six.string_types):\n if opt == \"-p\":\n try:\n parg = args[i]\n except IndexError:\n return\n i += 1\n elif opt.startswith(\"-p\"):\n parg = opt[2:]\n else:\n continue\n self.consider_pluginarg(parg)\n\n def consider_pluginarg(self, arg):\n if arg.startswith(\"no:\"):\n name = arg[3:]\n if name in essential_plugins:\n raise UsageError(\"plugin %s cannot be disabled\" % name)\n\n # PR #4304 : remove stepwise if cacheprovider is blocked\n if name == \"cacheprovider\":\n self.set_blocked(\"stepwise\")\n self.set_blocked(\"pytest_stepwise\")\n\n self.set_blocked(name)\n if not name.startswith(\"pytest_\"):\n self.set_blocked(\"pytest_\" + name)\n else:\n name = arg\n # Unblock the plugin. None indicates that it has been blocked.\n # There is no interface with pluggy for this.\n if self._name2plugin.get(name, -1) is None:\n del self._name2plugin[name]\n if not name.startswith(\"pytest_\"):\n if self._name2plugin.get(\"pytest_\" + name, -1) is None:\n del self._name2plugin[\"pytest_\" + name]\n self.import_plugin(arg, consider_entry_points=True)\n\n def consider_conftest(self, conftestmodule):\n self.register(conftestmodule, name=conftestmodule.__file__)\n\n def consider_env(self):\n self._import_plugin_specs(os.environ.get(\"PYTEST_PLUGINS\"))\n\n def consider_module(self, mod):\n self._import_plugin_specs(getattr(mod, \"pytest_plugins\", []))\n\n def _import_plugin_specs(self, spec):\n plugins = _get_plugin_specs_as_list(spec)\n for import_spec in plugins:\n self.import_plugin(import_spec)\n\n def import_plugin(self, modname, consider_entry_points=False):\n \"\"\"\n Imports a plugin with ``modname``. If ``consider_entry_points`` is True, entry point\n names are also considered to find a plugin.\n \"\"\"\n # most often modname refers to builtin modules, e.g. \"pytester\",\n # \"terminal\" or \"capture\". Those plugins are registered under their\n # basename for historic purposes but must be imported with the\n # _pytest prefix.\n assert isinstance(modname, six.string_types), (\n \"module name as text required, got %r\" % modname\n )\n modname = str(modname)\n if self.is_blocked(modname) or self.get_plugin(modname) is not None:\n return\n\n importspec = \"_pytest.\" + modname if modname in builtin_plugins else modname\n self.rewrite_hook.mark_rewrite(importspec)\n\n if consider_entry_points:\n loaded = self.load_setuptools_entrypoints(\"pytest11\", name=modname)\n if loaded:\n return\n\n try:\n __import__(importspec)\n except ImportError as e:\n new_exc_message = 'Error importing plugin \"%s\": %s' % (\n modname,\n safe_str(e.args[0]),\n )\n new_exc = ImportError(new_exc_message)\n tb = sys.exc_info()[2]\n\n six.reraise(ImportError, new_exc, tb)\n\n except Skipped as e:\n from _pytest.warnings import _issue_warning_captured\n\n _issue_warning_captured(\n PytestConfigWarning(\"skipped plugin %r: %s\" % (modname, e.msg)),\n self.hook,\n stacklevel=1,\n )\n else:\n mod = sys.modules[importspec]\n self.register(mod, modname)\n\n\ndef _get_plugin_specs_as_list(specs):\n \"\"\"\n Parses a list of \"plugin specs\" and returns a list of plugin names.\n\n Plugin specs can be given as a list of strings separated by \",\" or already as a list/tuple in\n which case it is returned as a list. Specs can also be `None` in which case an\n empty list is returned.\n \"\"\"\n if specs is not None and not isinstance(specs, types.ModuleType):\n if isinstance(specs, six.string_types):\n specs = specs.split(\",\") if specs else []\n if not isinstance(specs, (list, tuple)):\n raise UsageError(\n \"Plugin specs must be a ','-separated string or a \"\n \"list/tuple of strings for plugin names. Given: %r\" % specs\n )\n return list(specs)\n return []\n\n\ndef _ensure_removed_sysmodule(modname):\n try:\n del sys.modules[modname]\n except KeyError:\n pass\n\n\nclass Notset(object):\n def __repr__(self):\n return \"\"\n\n\nnotset = Notset()\n\n\ndef _iter_rewritable_modules(package_files):\n for fn in package_files:\n is_simple_module = \"/\" not in fn and fn.endswith(\".py\")\n is_package = fn.count(\"/\") == 1 and fn.endswith(\"__init__.py\")\n if is_simple_module:\n module_name, _ = os.path.splitext(fn)\n yield module_name\n elif is_package:\n package_name = os.path.dirname(fn)\n yield package_name\n\n\nclass Config(object):\n \"\"\" access to configuration values, pluginmanager and plugin hooks. \"\"\"\n\n def __init__(self, pluginmanager):\n #: access to command line option as attributes.\n #: (deprecated), use :py:func:`getoption() <_pytest.config.Config.getoption>` instead\n self.option = argparse.Namespace()\n from .argparsing import Parser, FILE_OR_DIR\n\n _a = FILE_OR_DIR\n self._parser = Parser(\n usage=\"%%(prog)s [options] [%s] [%s] [...]\" % (_a, _a),\n processopt=self._processopt,\n )\n #: a pluginmanager instance\n self.pluginmanager = pluginmanager\n self.trace = self.pluginmanager.trace.root.get(\"config\")\n self.hook = self.pluginmanager.hook\n self._inicache = {}\n self._override_ini = ()\n self._opt2dest = {}\n self._cleanup = []\n self.pluginmanager.register(self, \"pytestconfig\")\n self._configured = False\n self.invocation_dir = py.path.local()\n self.hook.pytest_addoption.call_historic(kwargs=dict(parser=self._parser))\n\n def add_cleanup(self, func):\n \"\"\" Add a function to be called when the config object gets out of\n use (usually coninciding with pytest_unconfigure).\"\"\"\n self._cleanup.append(func)\n\n def _do_configure(self):\n assert not self._configured\n self._configured = True\n self.hook.pytest_configure.call_historic(kwargs=dict(config=self))\n\n def _ensure_unconfigure(self):\n if self._configured:\n self._configured = False\n self.hook.pytest_unconfigure(config=self)\n self.hook.pytest_configure._call_history = []\n while self._cleanup:\n fin = self._cleanup.pop()\n fin()\n\n def get_terminal_writer(self):\n return self.pluginmanager.get_plugin(\"terminalreporter\")._tw\n\n def pytest_cmdline_parse(self, pluginmanager, args):\n try:\n self.parse(args)\n except UsageError:\n\n # Handle --version and --help here in a minimal fashion.\n # This gets done via helpconfig normally, but its\n # pytest_cmdline_main is not called in case of errors.\n if getattr(self.option, \"version\", False) or \"--version\" in args:\n from _pytest.helpconfig import showversion\n\n showversion(self)\n elif (\n getattr(self.option, \"help\", False) or \"--help\" in args or \"-h\" in args\n ):\n self._parser._getparser().print_help()\n sys.stdout.write(\n \"\\nNOTE: displaying only minimal help due to UsageError.\\n\\n\"\n )\n\n raise\n\n return self\n\n def notify_exception(self, excinfo, option=None):\n if option and getattr(option, \"fulltrace\", False):\n style = \"long\"\n else:\n style = \"native\"\n excrepr = excinfo.getrepr(\n funcargs=True, showlocals=getattr(option, \"showlocals\", False), style=style\n )\n res = self.hook.pytest_internalerror(excrepr=excrepr, excinfo=excinfo)\n if not any(res):\n for line in str(excrepr).split(\"\\n\"):\n sys.stderr.write(\"INTERNALERROR> %s\\n\" % line)\n sys.stderr.flush()\n\n def cwd_relative_nodeid(self, nodeid):\n # nodeid's are relative to the rootpath, compute relative to cwd\n if self.invocation_dir != self.rootdir:\n fullpath = self.rootdir.join(nodeid)\n nodeid = self.invocation_dir.bestrelpath(fullpath)\n return nodeid\n\n @classmethod\n def fromdictargs(cls, option_dict, args):\n \"\"\" constructor useable for subprocesses. \"\"\"\n config = get_config(args)\n config.option.__dict__.update(option_dict)\n config.parse(args, addopts=False)\n for x in config.option.plugins:\n config.pluginmanager.consider_pluginarg(x)\n return config\n\n def _processopt(self, opt):\n for name in opt._short_opts + opt._long_opts:\n self._opt2dest[name] = opt.dest\n\n if hasattr(opt, \"default\") and opt.dest:\n if not hasattr(self.option, opt.dest):\n setattr(self.option, opt.dest, opt.default)\n\n @hookimpl(trylast=True)\n def pytest_load_initial_conftests(self, early_config):\n self.pluginmanager._set_initial_conftests(early_config.known_args_namespace)\n\n def _initini(self, args):\n ns, unknown_args = self._parser.parse_known_and_unknown_args(\n args, namespace=copy.copy(self.option)\n )\n r = determine_setup(\n ns.inifilename,\n ns.file_or_dir + unknown_args,\n rootdir_cmd_arg=ns.rootdir or None,\n config=self,\n )\n self.rootdir, self.inifile, self.inicfg = r\n self._parser.extra_info[\"rootdir\"] = self.rootdir\n self._parser.extra_info[\"inifile\"] = self.inifile\n self._parser.addini(\"addopts\", \"extra command line options\", \"args\")\n self._parser.addini(\"minversion\", \"minimally required pytest version\")\n self._override_ini = ns.override_ini or ()\n\n def _consider_importhook(self, args):\n \"\"\"Install the PEP 302 import hook if using assertion rewriting.\n\n Needs to parse the --assert= option from the commandline\n and find all the installed plugins to mark them for rewriting\n by the importhook.\n \"\"\"\n ns, unknown_args = self._parser.parse_known_and_unknown_args(args)\n mode = getattr(ns, \"assertmode\", \"plain\")\n if mode == \"rewrite\":\n try:\n hook = _pytest.assertion.install_importhook(self)\n except SystemError:\n mode = \"plain\"\n else:\n self._mark_plugins_for_rewrite(hook)\n _warn_about_missing_assertion(mode)\n\n def _mark_plugins_for_rewrite(self, hook):\n \"\"\"\n Given an importhook, mark for rewrite any top-level\n modules or packages in the distribution package for\n all pytest plugins.\n \"\"\"\n self.pluginmanager.rewrite_hook = hook\n\n if os.environ.get(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\"):\n # We don't autoload from setuptools entry points, no need to continue.\n return\n\n package_files = (\n str(file)\n for dist in importlib_metadata.distributions()\n if any(ep.group == \"pytest11\" for ep in dist.entry_points)\n for file in dist.files or []\n )\n\n for name in _iter_rewritable_modules(package_files):\n hook.mark_rewrite(name)\n\n def _validate_args(self, args, via):\n \"\"\"Validate known args.\"\"\"\n self._parser._config_source_hint = via\n try:\n self._parser.parse_known_and_unknown_args(\n args, namespace=copy.copy(self.option)\n )\n finally:\n del self._parser._config_source_hint\n\n return args\n\n def _preparse(self, args, addopts=True):\n if addopts:\n env_addopts = os.environ.get(\"PYTEST_ADDOPTS\", \"\")\n if len(env_addopts):\n args[:] = (\n self._validate_args(shlex.split(env_addopts), \"via PYTEST_ADDOPTS\")\n + args\n )\n self._initini(args)\n if addopts:\n args[:] = (\n self._validate_args(self.getini(\"addopts\"), \"via addopts config\") + args\n )\n\n self._checkversion()\n self._consider_importhook(args)\n self.pluginmanager.consider_preparse(args)\n if not os.environ.get(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\"):\n # Don't autoload from setuptools entry point. Only explicitly specified\n # plugins are going to be loaded.\n self.pluginmanager.load_setuptools_entrypoints(\"pytest11\")\n self.pluginmanager.consider_env()\n self.known_args_namespace = ns = self._parser.parse_known_args(\n args, namespace=copy.copy(self.option)\n )\n if self.known_args_namespace.confcutdir is None and self.inifile:\n confcutdir = py.path.local(self.inifile).dirname\n self.known_args_namespace.confcutdir = confcutdir\n try:\n self.hook.pytest_load_initial_conftests(\n early_config=self, args=args, parser=self._parser\n )\n except ConftestImportFailure:\n e = sys.exc_info()[1]\n if ns.help or ns.version:\n # we don't want to prevent --help/--version to work\n # so just let is pass and print a warning at the end\n from _pytest.warnings import _issue_warning_captured\n\n _issue_warning_captured(\n PytestConfigWarning(\n \"could not load initial conftests: {}\".format(e.path)\n ),\n self.hook,\n stacklevel=2,\n )\n else:\n raise\n\n def _checkversion(self):\n import pytest\n\n minver = self.inicfg.get(\"minversion\", None)\n if minver:\n if Version(minver) > Version(pytest.__version__):\n raise pytest.UsageError(\n \"%s:%d: requires pytest-%s, actual pytest-%s'\"\n % (\n self.inicfg.config.path,\n self.inicfg.lineof(\"minversion\"),\n minver,\n pytest.__version__,\n )\n )\n\n def parse(self, args, addopts=True):\n # parse given cmdline arguments into this config object.\n assert not hasattr(\n self, \"args\"\n ), \"can only parse cmdline args at most once per Config object\"\n self._origargs = args\n self.hook.pytest_addhooks.call_historic(\n kwargs=dict(pluginmanager=self.pluginmanager)\n )\n self._preparse(args, addopts=addopts)\n # XXX deprecated hook:\n self.hook.pytest_cmdline_preparse(config=self, args=args)\n self._parser.after_preparse = True\n try:\n args = self._parser.parse_setoption(\n args, self.option, namespace=self.option\n )\n if not args:\n if self.invocation_dir == self.rootdir:\n args = self.getini(\"testpaths\")\n if not args:\n args = [str(self.invocation_dir)]\n self.args = args\n except PrintHelp:\n pass\n\n def addinivalue_line(self, name, line):\n \"\"\" add a line to an ini-file option. The option must have been\n declared but might not yet be set in which case the line becomes the\n the first line in its value. \"\"\"\n x = self.getini(name)\n assert isinstance(x, list)\n x.append(line) # modifies the cached list inline\n\n def getini(self, name):\n \"\"\" return configuration value from an :ref:`ini file `. If the\n specified name hasn't been registered through a prior\n :py:func:`parser.addini <_pytest.config.Parser.addini>`\n call (usually from a plugin), a ValueError is raised. \"\"\"\n try:\n return self._inicache[name]\n except KeyError:\n self._inicache[name] = val = self._getini(name)\n return val\n\n def _getini(self, name):\n try:\n description, type, default = self._parser._inidict[name]\n except KeyError:\n raise ValueError(\"unknown configuration value: %r\" % (name,))\n value = self._get_override_ini_value(name)\n if value is None:\n try:\n value = self.inicfg[name]\n except KeyError:\n if default is not None:\n return default\n if type is None:\n return \"\"\n return []\n if type == \"pathlist\":\n dp = py.path.local(self.inicfg.config.path).dirpath()\n values = []\n for relpath in shlex.split(value):\n values.append(dp.join(relpath, abs=True))\n return values\n elif type == \"args\":\n return shlex.split(value)\n elif type == \"linelist\":\n return [t for t in map(lambda x: x.strip(), value.split(\"\\n\")) if t]\n elif type == \"bool\":\n return bool(_strtobool(value.strip()))\n else:\n assert type is None\n return value\n\n def _getconftest_pathlist(self, name, path):\n try:\n mod, relroots = self.pluginmanager._rget_with_confmod(name, path)\n except KeyError:\n return None\n modpath = py.path.local(mod.__file__).dirpath()\n values = []\n for relroot in relroots:\n if not isinstance(relroot, py.path.local):\n relroot = relroot.replace(\"/\", py.path.local.sep)\n relroot = modpath.join(relroot, abs=True)\n values.append(relroot)\n return values\n\n def _get_override_ini_value(self, name):\n value = None\n # override_ini is a list of \"ini=value\" options\n # always use the last item if multiple values are set for same ini-name,\n # e.g. -o foo=bar1 -o foo=bar2 will set foo to bar2\n for ini_config in self._override_ini:\n try:\n key, user_ini_value = ini_config.split(\"=\", 1)\n except ValueError:\n raise UsageError(\"-o/--override-ini expects option=value style.\")\n else:\n if key == name:\n value = user_ini_value\n return value\n\n def getoption(self, name, default=notset, skip=False):\n \"\"\" return command line option value.\n\n :arg name: name of the option. You may also specify\n the literal ``--OPT`` option instead of the \"dest\" option name.\n :arg default: default value if no option of that name exists.\n :arg skip: if True raise pytest.skip if option does not exists\n or has a None value.\n \"\"\"\n name = self._opt2dest.get(name, name)\n try:\n val = getattr(self.option, name)\n if val is None and skip:\n raise AttributeError(name)\n return val\n except AttributeError:\n if default is not notset:\n return default\n if skip:\n import pytest\n\n pytest.skip(\"no %r option found\" % (name,))\n raise ValueError(\"no option named %r\" % (name,))\n\n def getvalue(self, name, path=None):\n \"\"\" (deprecated, use getoption()) \"\"\"\n return self.getoption(name)\n\n def getvalueorskip(self, name, path=None):\n \"\"\" (deprecated, use getoption(skip=True)) \"\"\"\n return self.getoption(name, skip=True)\n\n\ndef _assertion_supported():\n try:\n assert False\n except AssertionError:\n return True\n else:\n return False\n\n\ndef _warn_about_missing_assertion(mode):\n if not _assertion_supported():\n if mode == \"plain\":\n sys.stderr.write(\n \"WARNING: ASSERTIONS ARE NOT EXECUTED\"\n \" and FAILING TESTS WILL PASS. Are you\"\n \" using python -O?\"\n )\n else:\n sys.stderr.write(\n \"WARNING: assertions not in test modules or\"\n \" plugins will be ignored\"\n \" because assert statements are not executed \"\n \"by the underlying Python interpreter \"\n \"(are you using python -O?)\\n\"\n )\n\n\ndef setns(obj, dic):\n import pytest\n\n for name, value in dic.items():\n if isinstance(value, dict):\n mod = getattr(obj, name, None)\n if mod is None:\n modname = \"pytest.%s\" % name\n mod = types.ModuleType(modname)\n sys.modules[modname] = mod\n mod.__all__ = []\n setattr(obj, name, mod)\n obj.__all__.append(name)\n setns(mod, value)\n else:\n setattr(obj, name, value)\n obj.__all__.append(name)\n # if obj != pytest:\n # pytest.__all__.append(name)\n setattr(pytest, name, value)\n\n\ndef create_terminal_writer(config, *args, **kwargs):\n \"\"\"Create a TerminalWriter instance configured according to the options\n in the config object. Every code which requires a TerminalWriter object\n and has access to a config object should use this function.\n \"\"\"\n tw = py.io.TerminalWriter(*args, **kwargs)\n if config.option.color == \"yes\":\n tw.hasmarkup = True\n if config.option.color == \"no\":\n tw.hasmarkup = False\n return tw\n\n\ndef _strtobool(val):\n \"\"\"Convert a string representation of truth to true (1) or false (0).\n\n True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values\n are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if\n 'val' is anything else.\n\n .. note:: copied from distutils.util\n \"\"\"\n val = val.lower()\n if val in (\"y\", \"yes\", \"t\", \"true\", \"on\", \"1\"):\n return 1\n elif val in (\"n\", \"no\", \"f\", \"false\", \"off\", \"0\"):\n return 0\n else:\n raise ValueError(\"invalid truth value %r\" % (val,))\n"},{"col":0,"comment":"Return True if a TracebackEntry instance should be removed from tracebacks:\n * dynamically generated code (no code to show up for it);\n * internal traceback from pytest or its internal libraries, py and pluggy.\n ","endLoc":1093,"header":"def filter_traceback(entry)","id":2582,"name":"filter_traceback","nodeType":"Function","startLoc":1076,"text":"def filter_traceback(entry):\n \"\"\"Return True if a TracebackEntry instance should be removed from tracebacks:\n * dynamically generated code (no code to show up for it);\n * internal traceback from pytest or its internal libraries, py and pluggy.\n \"\"\"\n # entry.path might sometimes return a str object when the entry\n # points to dynamically generated code\n # see https://bitbucket.org/pytest-dev/py/issues/71\n raw_filename = entry.frame.code.raw.co_filename\n is_generated = \"<\" in raw_filename and \">\" in raw_filename\n if is_generated:\n return False\n # entry.path might point to a non-existing file, in which case it will\n # also return a str object. see #1133\n p = py.path.local(entry.path)\n return (\n not p.relto(_PLUGGY_DIR) and not p.relto(_PYTEST_DIR) and not p.relto(_PY_DIR)\n )"},{"col":4,"comment":"Search captured text for matching lines using ``re.match``.\n\n The argument is a list of lines which have to match using ``re.match``.\n If they do not match a pytest.fail() is called.\n\n The matches and non-matches are also printed on stdout.\n\n ","endLoc":1374,"header":"def re_match_lines(self, lines2)","id":2584,"name":"re_match_lines","nodeType":"Function","startLoc":1364,"text":"def re_match_lines(self, lines2):\n \"\"\"Search captured text for matching lines using ``re.match``.\n\n The argument is a list of lines which have to match using ``re.match``.\n If they do not match a pytest.fail() is called.\n\n The matches and non-matches are also printed on stdout.\n\n \"\"\"\n __tracebackhide__ = True\n self._match_lines(lines2, lambda name, pat: re.match(pat, name), \"re.match\")"},{"col":34,"endLoc":1374,"id":2585,"nodeType":"Lambda","startLoc":1374,"text":"lambda name, pat: re.match(pat, name)"},{"className":"ConftestImportFailure","col":0,"comment":"null","endLoc":48,"id":2586,"nodeType":"Class","startLoc":44,"text":"class ConftestImportFailure(Exception):\n def __init__(self, path, excinfo):\n Exception.__init__(self, path, excinfo)\n self.path = path\n self.excinfo = excinfo"},{"attributeType":"null","col":8,"comment":"null","endLoc":47,"id":2588,"name":"path","nodeType":"Attribute","startLoc":47,"text":"self.path"},{"attributeType":"null","col":8,"comment":"null","endLoc":1287,"id":2589,"name":"_log_output","nodeType":"Attribute","startLoc":1287,"text":"self._log_output"},{"attributeType":"null","col":8,"comment":"null","endLoc":1286,"id":2590,"name":"lines","nodeType":"Attribute","startLoc":1286,"text":"self.lines"},{"className":"SysModulesSnapshot","col":0,"comment":"null","endLoc":452,"id":2591,"nodeType":"Class","startLoc":441,"text":"class SysModulesSnapshot(object):\n def __init__(self, preserve=None):\n self.__preserve = preserve\n self.__saved = dict(sys.modules)\n\n def restore(self):\n if self.__preserve:\n self.__saved.update(\n (k, m) for k, m in sys.modules.items() if self.__preserve(k)\n )\n sys.modules.clear()\n sys.modules.update(self.__saved)"},{"col":4,"comment":"null","endLoc":444,"header":"def __init__(self, preserve=None)","id":2592,"name":"__init__","nodeType":"Function","startLoc":442,"text":"def __init__(self, preserve=None):\n self.__preserve = preserve\n self.__saved = dict(sys.modules)"},{"col":0,"comment":"registers a cleanup function for removing a lock, by default on atexit","endLoc":222,"header":"def register_cleanup_lock_removal(lock_path, register=atexit.register)","id":2593,"name":"register_cleanup_lock_removal","nodeType":"Function","startLoc":208,"text":"def register_cleanup_lock_removal(lock_path, register=atexit.register):\n \"\"\"registers a cleanup function for removing a lock, by default on atexit\"\"\"\n pid = os.getpid()\n\n def cleanup_on_exit(lock_path=lock_path, original_pid=pid):\n current_pid = os.getpid()\n if current_pid != original_pid:\n # fork\n return\n try:\n lock_path.unlink()\n except (OSError, IOError):\n pass\n\n return register(cleanup_on_exit)"},{"col":4,"comment":" return True if the exception is an instance of exc ","endLoc":487,"header":"def errisinstance(self, exc)","id":2594,"name":"errisinstance","nodeType":"Function","startLoc":485,"text":"def errisinstance(self, exc):\n \"\"\" return True if the exception is an instance of exc \"\"\"\n return isinstance(self.value, exc)"},{"col":4,"comment":"null","endLoc":493,"header":"def _getreprcrash(self)","id":2595,"name":"_getreprcrash","nodeType":"Function","startLoc":489,"text":"def _getreprcrash(self):\n exconly = self.exconly(tryshort=True)\n entry = self.traceback.getcrashentry()\n path, lineno = entry.frame.code.raw.co_filename, entry.lineno\n return ReprFileLocation(path, lineno + 1, exconly)"},{"attributeType":"null","col":8,"comment":"null","endLoc":48,"id":2596,"name":"excinfo","nodeType":"Attribute","startLoc":48,"text":"self.excinfo"},{"className":"Notset","col":0,"comment":"null","endLoc":618,"id":2597,"nodeType":"Class","startLoc":616,"text":"class Notset(object):\n def __repr__(self):\n return \"\""},{"col":4,"comment":"null","endLoc":618,"header":"def __repr__(self)","id":2598,"name":"__repr__","nodeType":"Function","startLoc":617,"text":"def __repr__(self):\n return \"\""},{"className":"Config","col":0,"comment":" access to configuration values, pluginmanager and plugin hooks. ","endLoc":1021,"id":2599,"nodeType":"Class","startLoc":636,"text":"class Config(object):\n \"\"\" access to configuration values, pluginmanager and plugin hooks. \"\"\"\n\n def __init__(self, pluginmanager):\n #: access to command line option as attributes.\n #: (deprecated), use :py:func:`getoption() <_pytest.config.Config.getoption>` instead\n self.option = argparse.Namespace()\n from .argparsing import Parser, FILE_OR_DIR\n\n _a = FILE_OR_DIR\n self._parser = Parser(\n usage=\"%%(prog)s [options] [%s] [%s] [...]\" % (_a, _a),\n processopt=self._processopt,\n )\n #: a pluginmanager instance\n self.pluginmanager = pluginmanager\n self.trace = self.pluginmanager.trace.root.get(\"config\")\n self.hook = self.pluginmanager.hook\n self._inicache = {}\n self._override_ini = ()\n self._opt2dest = {}\n self._cleanup = []\n self.pluginmanager.register(self, \"pytestconfig\")\n self._configured = False\n self.invocation_dir = py.path.local()\n self.hook.pytest_addoption.call_historic(kwargs=dict(parser=self._parser))\n\n def add_cleanup(self, func):\n \"\"\" Add a function to be called when the config object gets out of\n use (usually coninciding with pytest_unconfigure).\"\"\"\n self._cleanup.append(func)\n\n def _do_configure(self):\n assert not self._configured\n self._configured = True\n self.hook.pytest_configure.call_historic(kwargs=dict(config=self))\n\n def _ensure_unconfigure(self):\n if self._configured:\n self._configured = False\n self.hook.pytest_unconfigure(config=self)\n self.hook.pytest_configure._call_history = []\n while self._cleanup:\n fin = self._cleanup.pop()\n fin()\n\n def get_terminal_writer(self):\n return self.pluginmanager.get_plugin(\"terminalreporter\")._tw\n\n def pytest_cmdline_parse(self, pluginmanager, args):\n try:\n self.parse(args)\n except UsageError:\n\n # Handle --version and --help here in a minimal fashion.\n # This gets done via helpconfig normally, but its\n # pytest_cmdline_main is not called in case of errors.\n if getattr(self.option, \"version\", False) or \"--version\" in args:\n from _pytest.helpconfig import showversion\n\n showversion(self)\n elif (\n getattr(self.option, \"help\", False) or \"--help\" in args or \"-h\" in args\n ):\n self._parser._getparser().print_help()\n sys.stdout.write(\n \"\\nNOTE: displaying only minimal help due to UsageError.\\n\\n\"\n )\n\n raise\n\n return self\n\n def notify_exception(self, excinfo, option=None):\n if option and getattr(option, \"fulltrace\", False):\n style = \"long\"\n else:\n style = \"native\"\n excrepr = excinfo.getrepr(\n funcargs=True, showlocals=getattr(option, \"showlocals\", False), style=style\n )\n res = self.hook.pytest_internalerror(excrepr=excrepr, excinfo=excinfo)\n if not any(res):\n for line in str(excrepr).split(\"\\n\"):\n sys.stderr.write(\"INTERNALERROR> %s\\n\" % line)\n sys.stderr.flush()\n\n def cwd_relative_nodeid(self, nodeid):\n # nodeid's are relative to the rootpath, compute relative to cwd\n if self.invocation_dir != self.rootdir:\n fullpath = self.rootdir.join(nodeid)\n nodeid = self.invocation_dir.bestrelpath(fullpath)\n return nodeid\n\n @classmethod\n def fromdictargs(cls, option_dict, args):\n \"\"\" constructor useable for subprocesses. \"\"\"\n config = get_config(args)\n config.option.__dict__.update(option_dict)\n config.parse(args, addopts=False)\n for x in config.option.plugins:\n config.pluginmanager.consider_pluginarg(x)\n return config\n\n def _processopt(self, opt):\n for name in opt._short_opts + opt._long_opts:\n self._opt2dest[name] = opt.dest\n\n if hasattr(opt, \"default\") and opt.dest:\n if not hasattr(self.option, opt.dest):\n setattr(self.option, opt.dest, opt.default)\n\n @hookimpl(trylast=True)\n def pytest_load_initial_conftests(self, early_config):\n self.pluginmanager._set_initial_conftests(early_config.known_args_namespace)\n\n def _initini(self, args):\n ns, unknown_args = self._parser.parse_known_and_unknown_args(\n args, namespace=copy.copy(self.option)\n )\n r = determine_setup(\n ns.inifilename,\n ns.file_or_dir + unknown_args,\n rootdir_cmd_arg=ns.rootdir or None,\n config=self,\n )\n self.rootdir, self.inifile, self.inicfg = r\n self._parser.extra_info[\"rootdir\"] = self.rootdir\n self._parser.extra_info[\"inifile\"] = self.inifile\n self._parser.addini(\"addopts\", \"extra command line options\", \"args\")\n self._parser.addini(\"minversion\", \"minimally required pytest version\")\n self._override_ini = ns.override_ini or ()\n\n def _consider_importhook(self, args):\n \"\"\"Install the PEP 302 import hook if using assertion rewriting.\n\n Needs to parse the --assert= option from the commandline\n and find all the installed plugins to mark them for rewriting\n by the importhook.\n \"\"\"\n ns, unknown_args = self._parser.parse_known_and_unknown_args(args)\n mode = getattr(ns, \"assertmode\", \"plain\")\n if mode == \"rewrite\":\n try:\n hook = _pytest.assertion.install_importhook(self)\n except SystemError:\n mode = \"plain\"\n else:\n self._mark_plugins_for_rewrite(hook)\n _warn_about_missing_assertion(mode)\n\n def _mark_plugins_for_rewrite(self, hook):\n \"\"\"\n Given an importhook, mark for rewrite any top-level\n modules or packages in the distribution package for\n all pytest plugins.\n \"\"\"\n self.pluginmanager.rewrite_hook = hook\n\n if os.environ.get(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\"):\n # We don't autoload from setuptools entry points, no need to continue.\n return\n\n package_files = (\n str(file)\n for dist in importlib_metadata.distributions()\n if any(ep.group == \"pytest11\" for ep in dist.entry_points)\n for file in dist.files or []\n )\n\n for name in _iter_rewritable_modules(package_files):\n hook.mark_rewrite(name)\n\n def _validate_args(self, args, via):\n \"\"\"Validate known args.\"\"\"\n self._parser._config_source_hint = via\n try:\n self._parser.parse_known_and_unknown_args(\n args, namespace=copy.copy(self.option)\n )\n finally:\n del self._parser._config_source_hint\n\n return args\n\n def _preparse(self, args, addopts=True):\n if addopts:\n env_addopts = os.environ.get(\"PYTEST_ADDOPTS\", \"\")\n if len(env_addopts):\n args[:] = (\n self._validate_args(shlex.split(env_addopts), \"via PYTEST_ADDOPTS\")\n + args\n )\n self._initini(args)\n if addopts:\n args[:] = (\n self._validate_args(self.getini(\"addopts\"), \"via addopts config\") + args\n )\n\n self._checkversion()\n self._consider_importhook(args)\n self.pluginmanager.consider_preparse(args)\n if not os.environ.get(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\"):\n # Don't autoload from setuptools entry point. Only explicitly specified\n # plugins are going to be loaded.\n self.pluginmanager.load_setuptools_entrypoints(\"pytest11\")\n self.pluginmanager.consider_env()\n self.known_args_namespace = ns = self._parser.parse_known_args(\n args, namespace=copy.copy(self.option)\n )\n if self.known_args_namespace.confcutdir is None and self.inifile:\n confcutdir = py.path.local(self.inifile).dirname\n self.known_args_namespace.confcutdir = confcutdir\n try:\n self.hook.pytest_load_initial_conftests(\n early_config=self, args=args, parser=self._parser\n )\n except ConftestImportFailure:\n e = sys.exc_info()[1]\n if ns.help or ns.version:\n # we don't want to prevent --help/--version to work\n # so just let is pass and print a warning at the end\n from _pytest.warnings import _issue_warning_captured\n\n _issue_warning_captured(\n PytestConfigWarning(\n \"could not load initial conftests: {}\".format(e.path)\n ),\n self.hook,\n stacklevel=2,\n )\n else:\n raise\n\n def _checkversion(self):\n import pytest\n\n minver = self.inicfg.get(\"minversion\", None)\n if minver:\n if Version(minver) > Version(pytest.__version__):\n raise pytest.UsageError(\n \"%s:%d: requires pytest-%s, actual pytest-%s'\"\n % (\n self.inicfg.config.path,\n self.inicfg.lineof(\"minversion\"),\n minver,\n pytest.__version__,\n )\n )\n\n def parse(self, args, addopts=True):\n # parse given cmdline arguments into this config object.\n assert not hasattr(\n self, \"args\"\n ), \"can only parse cmdline args at most once per Config object\"\n self._origargs = args\n self.hook.pytest_addhooks.call_historic(\n kwargs=dict(pluginmanager=self.pluginmanager)\n )\n self._preparse(args, addopts=addopts)\n # XXX deprecated hook:\n self.hook.pytest_cmdline_preparse(config=self, args=args)\n self._parser.after_preparse = True\n try:\n args = self._parser.parse_setoption(\n args, self.option, namespace=self.option\n )\n if not args:\n if self.invocation_dir == self.rootdir:\n args = self.getini(\"testpaths\")\n if not args:\n args = [str(self.invocation_dir)]\n self.args = args\n except PrintHelp:\n pass\n\n def addinivalue_line(self, name, line):\n \"\"\" add a line to an ini-file option. The option must have been\n declared but might not yet be set in which case the line becomes the\n the first line in its value. \"\"\"\n x = self.getini(name)\n assert isinstance(x, list)\n x.append(line) # modifies the cached list inline\n\n def getini(self, name):\n \"\"\" return configuration value from an :ref:`ini file `. If the\n specified name hasn't been registered through a prior\n :py:func:`parser.addini <_pytest.config.Parser.addini>`\n call (usually from a plugin), a ValueError is raised. \"\"\"\n try:\n return self._inicache[name]\n except KeyError:\n self._inicache[name] = val = self._getini(name)\n return val\n\n def _getini(self, name):\n try:\n description, type, default = self._parser._inidict[name]\n except KeyError:\n raise ValueError(\"unknown configuration value: %r\" % (name,))\n value = self._get_override_ini_value(name)\n if value is None:\n try:\n value = self.inicfg[name]\n except KeyError:\n if default is not None:\n return default\n if type is None:\n return \"\"\n return []\n if type == \"pathlist\":\n dp = py.path.local(self.inicfg.config.path).dirpath()\n values = []\n for relpath in shlex.split(value):\n values.append(dp.join(relpath, abs=True))\n return values\n elif type == \"args\":\n return shlex.split(value)\n elif type == \"linelist\":\n return [t for t in map(lambda x: x.strip(), value.split(\"\\n\")) if t]\n elif type == \"bool\":\n return bool(_strtobool(value.strip()))\n else:\n assert type is None\n return value\n\n def _getconftest_pathlist(self, name, path):\n try:\n mod, relroots = self.pluginmanager._rget_with_confmod(name, path)\n except KeyError:\n return None\n modpath = py.path.local(mod.__file__).dirpath()\n values = []\n for relroot in relroots:\n if not isinstance(relroot, py.path.local):\n relroot = relroot.replace(\"/\", py.path.local.sep)\n relroot = modpath.join(relroot, abs=True)\n values.append(relroot)\n return values\n\n def _get_override_ini_value(self, name):\n value = None\n # override_ini is a list of \"ini=value\" options\n # always use the last item if multiple values are set for same ini-name,\n # e.g. -o foo=bar1 -o foo=bar2 will set foo to bar2\n for ini_config in self._override_ini:\n try:\n key, user_ini_value = ini_config.split(\"=\", 1)\n except ValueError:\n raise UsageError(\"-o/--override-ini expects option=value style.\")\n else:\n if key == name:\n value = user_ini_value\n return value\n\n def getoption(self, name, default=notset, skip=False):\n \"\"\" return command line option value.\n\n :arg name: name of the option. You may also specify\n the literal ``--OPT`` option instead of the \"dest\" option name.\n :arg default: default value if no option of that name exists.\n :arg skip: if True raise pytest.skip if option does not exists\n or has a None value.\n \"\"\"\n name = self._opt2dest.get(name, name)\n try:\n val = getattr(self.option, name)\n if val is None and skip:\n raise AttributeError(name)\n return val\n except AttributeError:\n if default is not notset:\n return default\n if skip:\n import pytest\n\n pytest.skip(\"no %r option found\" % (name,))\n raise ValueError(\"no option named %r\" % (name,))\n\n def getvalue(self, name, path=None):\n \"\"\" (deprecated, use getoption()) \"\"\"\n return self.getoption(name)\n\n def getvalueorskip(self, name, path=None):\n \"\"\" (deprecated, use getoption(skip=True)) \"\"\"\n return self.getoption(name, skip=True)"},{"col":4,"comment":" Add a function to be called when the config object gets out of\n use (usually coninciding with pytest_unconfigure).","endLoc":666,"header":"def add_cleanup(self, func)","id":2600,"name":"add_cleanup","nodeType":"Function","startLoc":663,"text":"def add_cleanup(self, func):\n \"\"\" Add a function to be called when the config object gets out of\n use (usually coninciding with pytest_unconfigure).\"\"\"\n self._cleanup.append(func)"},{"col":0,"comment":"null","endLoc":917,"header":"def test_parameterset_for_fail_at_collect(testdir)","id":2601,"name":"test_parameterset_for_fail_at_collect","nodeType":"Function","startLoc":878,"text":"def test_parameterset_for_fail_at_collect(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n {}=fail_at_collect\n \"\"\".format(\n EMPTY_PARAMETERSET_OPTION\n )\n )\n\n config = testdir.parseconfig()\n from _pytest.mark import pytest_configure, get_empty_parameterset_mark\n\n pytest_configure(config)\n\n with pytest.raises(\n Collector.CollectError,\n match=r\"Empty parameter set in 'pytest_configure' at line \\d\\d+\",\n ):\n get_empty_parameterset_mark(config, [\"a\"], pytest_configure)\n\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.parametrize(\"empty\", [])\n def test():\n pass\n \"\"\"\n )\n result = testdir.runpytest(str(p1))\n result.stdout.fnmatch_lines(\n [\n \"collected 0 items / 1 errors\",\n \"* ERROR collecting test_parameterset_for_fail_at_collect.py *\",\n \"Empty parameter set in 'test' at line 3\",\n \"*= 1 error in *\",\n ]\n )\n assert result.ret == EXIT_INTERRUPTED"},{"col":4,"comment":"\n Return str()able representation of this exception info.\n\n :param bool showlocals:\n Show locals per traceback entry.\n Ignored if ``style==\"native\"``.\n\n :param str style: long|short|no|native traceback style\n\n :param bool abspath:\n If paths should be changed to absolute or left unchanged.\n\n :param bool tbfilter:\n Hide entries that contain a local variable ``__tracebackhide__==True``.\n Ignored if ``style==\"native\"``.\n\n :param bool funcargs:\n Show fixtures (\"funcargs\" for legacy purposes) per traceback entry.\n\n :param bool truncate_locals:\n With ``showlocals==True``, make sure locals can be safely represented as strings.\n\n :param bool chain: if chained exceptions in Python 3 should be shown.\n\n .. versionchanged:: 3.9\n\n Added the ``chain`` parameter.\n ","endLoc":552,"header":"def getrepr(\n self,\n showlocals=False,\n style=\"long\",\n abspath=False,\n tbfilter=True,\n funcargs=False,\n truncate_locals=True,\n chain=True,\n )","id":2602,"name":"getrepr","nodeType":"Function","startLoc":495,"text":"def getrepr(\n self,\n showlocals=False,\n style=\"long\",\n abspath=False,\n tbfilter=True,\n funcargs=False,\n truncate_locals=True,\n chain=True,\n ):\n \"\"\"\n Return str()able representation of this exception info.\n\n :param bool showlocals:\n Show locals per traceback entry.\n Ignored if ``style==\"native\"``.\n\n :param str style: long|short|no|native traceback style\n\n :param bool abspath:\n If paths should be changed to absolute or left unchanged.\n\n :param bool tbfilter:\n Hide entries that contain a local variable ``__tracebackhide__==True``.\n Ignored if ``style==\"native\"``.\n\n :param bool funcargs:\n Show fixtures (\"funcargs\" for legacy purposes) per traceback entry.\n\n :param bool truncate_locals:\n With ``showlocals==True``, make sure locals can be safely represented as strings.\n\n :param bool chain: if chained exceptions in Python 3 should be shown.\n\n .. versionchanged:: 3.9\n\n Added the ``chain`` parameter.\n \"\"\"\n if style == \"native\":\n return ReprExceptionInfo(\n ReprTracebackNative(\n traceback.format_exception(\n self.type, self.value, self.traceback[0]._rawentry\n )\n ),\n self._getreprcrash(),\n )\n\n fmt = FormattedExcinfo(\n showlocals=showlocals,\n style=style,\n abspath=abspath,\n tbfilter=tbfilter,\n funcargs=funcargs,\n truncate_locals=truncate_locals,\n chain=chain,\n )\n return fmt.repr_excinfo(self)"},{"col":0,"comment":"removes a numbered directory if its lock can be obtained and it does not seem to be in use","endLoc":248,"header":"def maybe_delete_a_numbered_dir(path)","id":2604,"name":"maybe_delete_a_numbered_dir","nodeType":"Function","startLoc":225,"text":"def maybe_delete_a_numbered_dir(path):\n \"\"\"removes a numbered directory if its lock can be obtained and it does not seem to be in use\"\"\"\n lock_path = None\n try:\n lock_path = create_cleanup_lock(path)\n parent = path.parent\n\n garbage = parent.joinpath(\"garbage-{}\".format(uuid.uuid4()))\n path.rename(garbage)\n rm_rf(garbage)\n except (OSError, EnvironmentError):\n # known races:\n # * other process did a cleanup at the same time\n # * deletable folder was found\n # * process cwd (Windows)\n return\n finally:\n # if we created the lock, ensure we remove it even if we failed\n # to properly remove the numbered dir\n if lock_path is not None:\n try:\n lock_path.unlink()\n except (OSError, IOError):\n pass"},{"col":4,"comment":"null","endLoc":559,"header":"def __str__(self)","id":2606,"name":"__str__","nodeType":"Function","startLoc":554,"text":"def __str__(self):\n if self._excinfo is None:\n return repr(self)\n entry = self.traceback[-1]\n loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly())\n return str(loc)"},{"col":4,"comment":"null","endLoc":671,"header":"def _do_configure(self)","id":2607,"name":"_do_configure","nodeType":"Function","startLoc":668,"text":"def _do_configure(self):\n assert not self._configured\n self._configured = True\n self.hook.pytest_configure.call_historic(kwargs=dict(config=self))"},{"col":0,"comment":"checks if a lock exists and breaks it if its considered dead","endLoc":267,"header":"def ensure_deletable(path, consider_lock_dead_if_created_before)","id":2608,"name":"ensure_deletable","nodeType":"Function","startLoc":251,"text":"def ensure_deletable(path, consider_lock_dead_if_created_before):\n \"\"\"checks if a lock exists and breaks it if its considered dead\"\"\"\n if path.is_symlink():\n return False\n lock = get_lock_path(path)\n if not lock.exists():\n return True\n try:\n lock_time = lock.stat().st_mtime\n except Exception:\n return False\n else:\n if lock_time < consider_lock_dead_if_created_before:\n lock.unlink()\n return True\n else:\n return False"},{"col":0,"comment":"tries to cleanup a folder if we can ensure it's deletable","endLoc":273,"header":"def try_cleanup(path, consider_lock_dead_if_created_before)","id":2609,"name":"try_cleanup","nodeType":"Function","startLoc":270,"text":"def try_cleanup(path, consider_lock_dead_if_created_before):\n \"\"\"tries to cleanup a folder if we can ensure it's deletable\"\"\"\n if ensure_deletable(path, consider_lock_dead_if_created_before):\n maybe_delete_a_numbered_dir(path)"},{"col":0,"comment":"lists candidates for numbered directories to be removed - follows py.path","endLoc":285,"header":"def cleanup_candidates(root, prefix, keep)","id":2610,"name":"cleanup_candidates","nodeType":"Function","startLoc":276,"text":"def cleanup_candidates(root, prefix, keep):\n \"\"\"lists candidates for numbered directories to be removed - follows py.path\"\"\"\n max_existing = _max(map(parse_num, find_suffixes(root, prefix)), default=-1)\n max_delete = max_existing - keep\n paths = find_prefixed(root, prefix)\n paths, paths2 = itertools.tee(paths)\n numbers = map(parse_num, extract_suffixes(paths2, prefix))\n for path, number in zip(paths, numbers):\n if number <= max_delete:\n yield path"},{"col":0,"comment":"null","endLoc":922,"header":"def test_parameterset_for_parametrize_bad_markname(testdir)","id":2612,"name":"test_parameterset_for_parametrize_bad_markname","nodeType":"Function","startLoc":920,"text":"def test_parameterset_for_parametrize_bad_markname(testdir):\n with pytest.raises(pytest.UsageError):\n test_parameterset_for_parametrize_marks(testdir, \"bad\")"},{"col":0,"comment":"null","endLoc":957,"header":"def test_mark_expressions_no_smear(testdir)","id":2613,"name":"test_mark_expressions_no_smear","nodeType":"Function","startLoc":925,"text":"def test_mark_expressions_no_smear(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n class BaseTests(object):\n def test_something(self):\n pass\n\n @pytest.mark.FOO\n class TestFooClass(BaseTests):\n pass\n\n @pytest.mark.BAR\n class TestBarClass(BaseTests):\n pass\n \"\"\"\n )\n\n reprec = testdir.inline_run(\"-m\", \"FOO\")\n passed, skipped, failed = reprec.countoutcomes()\n dlist = reprec.getcalls(\"pytest_deselected\")\n assert passed == 1\n assert skipped == failed == 0\n deselected_tests = dlist[0].items\n assert len(deselected_tests) == 1\n\n # todo: fixed\n # keywords smear - expected behaviour\n # reprec_keywords = testdir.inline_run(\"-k\", \"FOO\")\n # passed_k, skipped_k, failed_k = reprec_keywords.countoutcomes()\n # assert passed_k == 2\n # assert skipped_k == failed_k == 0"},{"col":0,"comment":"null","endLoc":966,"header":"def test_addmarker_order()","id":2614,"name":"test_addmarker_order","nodeType":"Function","startLoc":960,"text":"def test_addmarker_order():\n node = Node(\"Test\", config=mock.Mock(), session=mock.Mock(), nodeid=\"Test\")\n node.add_marker(\"foo\")\n node.add_marker(\"bar\")\n node.add_marker(\"baz\", append=False)\n extracted = [x.name for x in node.iter_markers()]\n assert extracted == [\"baz\", \"foo\", \"bar\"]"},{"col":4,"comment":"null","endLoc":564,"header":"def __unicode__(self)","id":2615,"name":"__unicode__","nodeType":"Function","startLoc":561,"text":"def __unicode__(self):\n entry = self.traceback[-1]\n loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly())\n return text_type(loc)"},{"col":4,"comment":"\n Check whether the regular expression 'regexp' is found in the string\n representation of the exception using ``re.search``. If it matches\n then True is returned (so that it is possible to write\n ``assert excinfo.match()``). If it doesn't match an AssertionError is\n raised.\n ","endLoc":582,"header":"def match(self, regexp)","id":2616,"name":"match","nodeType":"Function","startLoc":566,"text":"def match(self, regexp):\n \"\"\"\n Check whether the regular expression 'regexp' is found in the string\n representation of the exception using ``re.search``. If it matches\n then True is returned (so that it is possible to write\n ``assert excinfo.match()``). If it doesn't match an AssertionError is\n raised.\n \"\"\"\n __tracebackhide__ = True\n value = (\n text_type(self.value) if isinstance(regexp, text_type) else str(self.value)\n )\n if not re.search(regexp, value):\n raise AssertionError(\n u\"Pattern {!r} not found in {!r}\".format(regexp, value)\n )\n return True"},{"col":4,"comment":"null","endLoc":77,"header":"def pprint(\n object: object,\n stream: IO[str] | None = None,\n indent: int = 1,\n width: int = 80,\n depth: int | None = None,\n *,\n compact: bool = False,\n sort_dicts: bool = True,\n ) -> None","id":2618,"name":"pprint","nodeType":"Function","startLoc":68,"text":"def pprint(\n object: object,\n stream: IO[str] | None = None,\n indent: int = 1,\n width: int = 80,\n depth: int | None = None,\n *,\n compact: bool = False,\n sort_dicts: bool = True,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":2577,"header":"def test_parametrized_fixture_teardown_order(self, testdir)","id":2619,"name":"test_parametrized_fixture_teardown_order","nodeType":"Function","startLoc":2538,"text":"def test_parametrized_fixture_teardown_order(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(params=[1,2], scope=\"class\")\n def param1(request):\n return request.param\n\n values = []\n\n class TestClass(object):\n @classmethod\n @pytest.fixture(scope=\"class\", autouse=True)\n def setup1(self, request, param1):\n values.append(1)\n request.addfinalizer(self.teardown1)\n @classmethod\n def teardown1(self):\n assert values.pop() == 1\n @pytest.fixture(scope=\"class\", autouse=True)\n def setup2(self, request, param1):\n values.append(2)\n request.addfinalizer(self.teardown2)\n @classmethod\n def teardown2(self):\n assert values.pop() == 2\n def test(self):\n pass\n\n def test_finish():\n assert not values\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *3 passed*\n \"\"\"\n )\n assert \"error\" not in result.stdout.str()"},{"col":4,"comment":"null","endLoc":2611,"header":"def test_fixture_finalizer(self, testdir)","id":2620,"name":"test_fixture_finalizer","nodeType":"Function","startLoc":2579,"text":"def test_fixture_finalizer(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n import sys\n\n @pytest.fixture\n def browser(request):\n\n def finalize():\n sys.stdout.write('Finalized')\n request.addfinalizer(finalize)\n return {}\n \"\"\"\n )\n b = testdir.mkdir(\"subdir\")\n b.join(\"test_overridden_fixture_finalizer.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def browser(browser):\n browser['visited'] = True\n return browser\n\n def test_browser(browser):\n assert browser['visited'] is True\n \"\"\"\n )\n )\n reprec = testdir.runpytest(\"-s\")\n for test in [\"test_browser\"]:\n reprec.stdout.fnmatch_lines([\"*Finalized*\"])"},{"col":4,"comment":"null","endLoc":2639,"header":"def test_class_scope_with_normal_tests(self, testdir)","id":2621,"name":"test_class_scope_with_normal_tests","nodeType":"Function","startLoc":2613,"text":"def test_class_scope_with_normal_tests(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import pytest\n\n class Box(object):\n value = 0\n\n @pytest.fixture(scope='class')\n def a(request):\n Box.value += 1\n return Box.value\n\n def test_a(a):\n assert a == 1\n\n class Test1(object):\n def test_b(self, a):\n assert a == 2\n\n class Test2(object):\n def test_c(self, a):\n assert a == 3\"\"\"\n )\n reprec = testdir.inline_run(testpath)\n for test in [\"test_a\", \"test_b\", \"test_c\"]:\n assert reprec.matchreport(test).passed"},{"col":4,"comment":"null","endLoc":2655,"header":"def test_request_is_clean(self, testdir)","id":2622,"name":"test_request_is_clean","nodeType":"Function","startLoc":2641,"text":"def test_request_is_clean(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(params=[1, 2])\n def fix(request):\n request.addfinalizer(lambda: values.append(request.param))\n def test_fix(fix):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\")\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n assert values == [1, 2]"},{"col":4,"comment":"null","endLoc":2684,"header":"def test_parametrize_separated_lifecycle(self, testdir)","id":2623,"name":"test_parametrize_separated_lifecycle","nodeType":"Function","startLoc":2657,"text":"def test_parametrize_separated_lifecycle(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n values = []\n @pytest.fixture(scope=\"module\", params=[1, 2])\n def arg(request):\n x = request.param\n request.addfinalizer(lambda: values.append(\"fin%s\" % x))\n return request.param\n def test_1(arg):\n values.append(arg)\n def test_2(arg):\n values.append(arg)\n \"\"\"\n )\n reprec = testdir.inline_run(\"-vs\")\n reprec.assertoutcome(passed=4)\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n import pprint\n\n pprint.pprint(values)\n # assert len(values) == 6\n assert values[0] == values[1] == 1\n assert values[2] == \"fin1\"\n assert values[3] == values[4] == 2\n assert values[5] == \"fin2\""},{"col":4,"comment":"null","endLoc":2708,"header":"def test_parametrize_function_scoped_finalizers_called(self, testdir)","id":2624,"name":"test_parametrize_function_scoped_finalizers_called","nodeType":"Function","startLoc":2686,"text":"def test_parametrize_function_scoped_finalizers_called(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"function\", params=[1, 2])\n def arg(request):\n x = request.param\n request.addfinalizer(lambda: values.append(\"fin%s\" % x))\n return request.param\n\n values = []\n def test_1(arg):\n values.append(arg)\n def test_2(arg):\n values.append(arg)\n def test_3():\n assert len(values) == 8\n assert values == [1, \"fin1\", 2, \"fin2\", 1, \"fin1\", 2, \"fin2\"]\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\")\n reprec.assertoutcome(passed=5)"},{"col":4,"comment":"#246","endLoc":2745,"header":"@pytest.mark.parametrize(\"scope\", [\"session\", \"function\", \"module\"])\n def test_finalizer_order_on_parametrization(self, scope, testdir)","id":2625,"name":"test_finalizer_order_on_parametrization","nodeType":"Function","startLoc":2710,"text":"@pytest.mark.parametrize(\"scope\", [\"session\", \"function\", \"module\"])\n def test_finalizer_order_on_parametrization(self, scope, testdir):\n \"\"\"#246\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n\n @pytest.fixture(scope=%(scope)r, params=[\"1\"])\n def fix1(request):\n return request.param\n\n @pytest.fixture(scope=%(scope)r)\n def fix2(request, base):\n def cleanup_fix2():\n assert not values, \"base should not have been finalized\"\n request.addfinalizer(cleanup_fix2)\n\n @pytest.fixture(scope=%(scope)r)\n def base(request, fix1):\n def cleanup_base():\n values.append(\"fin_base\")\n print(\"finalizing base\")\n request.addfinalizer(cleanup_base)\n\n def test_begin():\n pass\n def test_baz(base, fix2):\n pass\n def test_other():\n pass\n \"\"\"\n % {\"scope\": scope}\n )\n reprec = testdir.inline_run(\"-lvs\")\n reprec.assertoutcome(passed=3)"},{"col":0,"comment":"null","endLoc":274,"header":"def reorder_items_atscope(items, argkeys_cache, items_by_argkey, scopenum)","id":2626,"name":"reorder_items_atscope","nodeType":"Function","startLoc":237,"text":"def reorder_items_atscope(items, argkeys_cache, items_by_argkey, scopenum):\n if scopenum >= scopenum_function or len(items) < 3:\n return items\n ignore = set()\n items_deque = deque(items)\n items_done = OrderedDict()\n scoped_items_by_argkey = items_by_argkey[scopenum]\n scoped_argkeys_cache = argkeys_cache[scopenum]\n while items_deque:\n no_argkey_group = OrderedDict()\n slicing_argkey = None\n while items_deque:\n item = items_deque.popleft()\n if item in items_done or item in no_argkey_group:\n continue\n argkeys = OrderedDict.fromkeys(\n k for k in scoped_argkeys_cache.get(item, []) if k not in ignore\n )\n if not argkeys:\n no_argkey_group[item] = None\n else:\n slicing_argkey, _ = argkeys.popitem()\n # we don't have to remove relevant items from later in the deque because they'll just be ignored\n matching_items = [\n i for i in scoped_items_by_argkey[slicing_argkey] if i in items\n ]\n for i in reversed(matching_items):\n fix_cache_order(i, argkeys_cache, items_by_argkey)\n items_deque.appendleft(i)\n break\n if no_argkey_group:\n no_argkey_group = reorder_items_atscope(\n no_argkey_group, argkeys_cache, items_by_argkey, scopenum + 1\n )\n for item in no_argkey_group:\n items_done[item] = None\n ignore.add(slicing_argkey)\n return items_done"},{"col":4,"comment":"#396","endLoc":2784,"header":"def test_class_scope_parametrization_ordering(self, testdir)","id":2627,"name":"test_class_scope_parametrization_ordering","nodeType":"Function","startLoc":2747,"text":"def test_class_scope_parametrization_ordering(self, testdir):\n \"\"\"#396\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n values = []\n @pytest.fixture(params=[\"John\", \"Doe\"], scope=\"class\")\n def human(request):\n request.addfinalizer(lambda: values.append(\"fin %s\" % request.param))\n return request.param\n\n class TestGreetings(object):\n def test_hello(self, human):\n values.append(\"test_hello\")\n\n class TestMetrics(object):\n def test_name(self, human):\n values.append(\"test_name\")\n\n def test_population(self, human):\n values.append(\"test_population\")\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=6)\n values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n assert values == [\n \"test_hello\",\n \"fin John\",\n \"test_hello\",\n \"fin Doe\",\n \"test_name\",\n \"test_population\",\n \"fin John\",\n \"test_name\",\n \"test_population\",\n \"fin Doe\",\n ]"},{"col":4,"comment":"null","endLoc":2817,"header":"def test_parametrize_setup_function(self, testdir)","id":2628,"name":"test_parametrize_setup_function","nodeType":"Function","startLoc":2786,"text":"def test_parametrize_setup_function(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"module\", params=[1, 2])\n def arg(request):\n return request.param\n\n @pytest.fixture(scope=\"module\", autouse=True)\n def mysetup(request, arg):\n request.addfinalizer(lambda: values.append(\"fin%s\" % arg))\n values.append(\"setup%s\" % arg)\n\n values = []\n def test_1(arg):\n values.append(arg)\n def test_2(arg):\n values.append(arg)\n def test_3():\n import pprint\n pprint.pprint(values)\n if arg == 1:\n assert values == [\"setup1\", 1, 1, ]\n elif arg == 2:\n assert values == [\"setup1\", 1, 1, \"fin1\",\n \"setup2\", 2, 2, ]\n\n \"\"\"\n )\n reprec = testdir.inline_run(\"-v\")\n reprec.assertoutcome(passed=6)"},{"col":4,"comment":"null","endLoc":2832,"header":"def test_fixture_marked_function_not_collected_as_test(self, testdir)","id":2629,"name":"test_fixture_marked_function_not_collected_as_test","nodeType":"Function","startLoc":2819,"text":"def test_fixture_marked_function_not_collected_as_test(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def test_app():\n return 1\n\n def test_something(test_app):\n assert test_app == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":"null","endLoc":2849,"header":"def test_params_and_ids(self, testdir)","id":2630,"name":"test_params_and_ids","nodeType":"Function","startLoc":2834,"text":"def test_params_and_ids(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[object(), object()],\n ids=['alpha', 'beta'])\n def fix(request):\n return request.param\n\n def test_foo(fix):\n assert 1\n \"\"\"\n )\n res = testdir.runpytest(\"-v\")\n res.stdout.fnmatch_lines([\"*test_foo*alpha*\", \"*test_foo*beta*\"])"},{"col":4,"comment":"null","endLoc":2866,"header":"def test_params_and_ids_yieldfixture(self, testdir)","id":2633,"name":"test_params_and_ids_yieldfixture","nodeType":"Function","startLoc":2851,"text":"def test_params_and_ids_yieldfixture(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.yield_fixture(params=[object(), object()],\n ids=['alpha', 'beta'])\n def fix(request):\n yield request.param\n\n def test_foo(fix):\n assert 1\n \"\"\"\n )\n res = testdir.runpytest(\"-v\")\n res.stdout.fnmatch_lines([\"*test_foo*alpha*\", \"*test_foo*beta*\"])"},{"col":4,"comment":"#920","endLoc":2909,"header":"def test_deterministic_fixture_collection(self, testdir, monkeypatch)","id":2634,"name":"test_deterministic_fixture_collection","nodeType":"Function","startLoc":2868,"text":"def test_deterministic_fixture_collection(self, testdir, monkeypatch):\n \"\"\"#920\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope=\"module\",\n params=[\"A\",\n \"B\",\n \"C\"])\n def A(request):\n return request.param\n\n @pytest.fixture(scope=\"module\",\n params=[\"DDDDDDDDD\", \"EEEEEEEEEEEE\", \"FFFFFFFFFFF\", \"banansda\"])\n def B(request, A):\n return request.param\n\n def test_foo(B):\n # Something funky is going on here.\n # Despite specified seeds, on what is collected,\n # sometimes we get unexpected passes. hashing B seems\n # to help?\n assert hash(B) or True\n \"\"\"\n )\n monkeypatch.setenv(\"PYTHONHASHSEED\", \"1\")\n out1 = testdir.runpytest_subprocess(\"-v\")\n monkeypatch.setenv(\"PYTHONHASHSEED\", \"2\")\n out2 = testdir.runpytest_subprocess(\"-v\")\n out1 = [\n line\n for line in out1.outlines\n if line.startswith(\"test_deterministic_fixture_collection.py::test_foo\")\n ]\n out2 = [\n line\n for line in out2.outlines\n if line.startswith(\"test_deterministic_fixture_collection.py::test_foo\")\n ]\n assert len(out1) == 12\n assert out1 == out2"},{"attributeType":"null","col":4,"comment":"null","endLoc":394,"id":2635,"name":"_assert_start_repr","nodeType":"Attribute","startLoc":394,"text":"_assert_start_repr"},{"attributeType":"null","col":4,"comment":"null","endLoc":398,"id":2636,"name":"_excinfo","nodeType":"Attribute","startLoc":398,"text":"_excinfo"},{"attributeType":"null","col":4,"comment":"null","endLoc":399,"id":2637,"name":"_striptext","nodeType":"Attribute","startLoc":399,"text":"_striptext"},{"attributeType":"null","col":4,"comment":"null","endLoc":400,"id":2638,"name":"_traceback","nodeType":"Attribute","startLoc":400,"text":"_traceback"},{"attributeType":"null","col":12,"comment":"null","endLoc":457,"id":2639,"name":"_traceback","nodeType":"Attribute","startLoc":457,"text":"self._traceback"},{"className":"TestRequestScopeAccess","col":0,"comment":"null","endLoc":2963,"id":2640,"nodeType":"Class","startLoc":2912,"text":"class TestRequestScopeAccess(object):\n pytestmark = pytest.mark.parametrize(\n (\"scope\", \"ok\", \"error\"),\n [\n [\"session\", \"\", \"fspath class function module\"],\n [\"module\", \"module fspath\", \"cls function\"],\n [\"class\", \"module fspath cls\", \"function\"],\n [\"function\", \"module fspath cls function\", \"\"],\n ],\n )\n\n def test_setup(self, testdir, scope, ok, error):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=%r, autouse=True)\n def myscoped(request):\n for x in %r:\n assert hasattr(request, x)\n for x in %r:\n pytest.raises(AttributeError, lambda:\n getattr(request, x))\n assert request.session\n assert request.config\n def test_func():\n pass\n \"\"\"\n % (scope, ok.split(), error.split())\n )\n reprec = testdir.inline_run(\"-l\")\n reprec.assertoutcome(passed=1)\n\n def test_funcarg(self, testdir, scope, ok, error):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=%r)\n def arg(request):\n for x in %r:\n assert hasattr(request, x)\n for x in %r:\n pytest.raises(AttributeError, lambda:\n getattr(request, x))\n assert request.session\n assert request.config\n def test_func(arg):\n pass\n \"\"\"\n % (scope, ok.split(), error.split())\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"className":"Frame","col":0,"comment":"Wrapper around a Python frame holding f_locals and f_globals\n in which expressions can be evaluated.","endLoc":163,"id":2641,"nodeType":"Class","startLoc":103,"text":"class Frame(object):\n \"\"\"Wrapper around a Python frame holding f_locals and f_globals\n in which expressions can be evaluated.\"\"\"\n\n def __init__(self, frame):\n self.lineno = frame.f_lineno - 1\n self.f_globals = frame.f_globals\n self.f_locals = frame.f_locals\n self.raw = frame\n self.code = Code(frame.f_code)\n\n @property\n def statement(self):\n \"\"\" statement this frame is at \"\"\"\n import _pytest._code\n\n if self.code.fullsource is None:\n return _pytest._code.Source(\"\")\n return self.code.fullsource.getstatement(self.lineno)\n\n def eval(self, code, **vars):\n \"\"\" evaluate 'code' in the frame\n\n 'vars' are optional additional local variables\n\n returns the result of the evaluation\n \"\"\"\n f_locals = self.f_locals.copy()\n f_locals.update(vars)\n return eval(code, self.f_globals, f_locals)\n\n def exec_(self, code, **vars):\n \"\"\" exec 'code' in the frame\n\n 'vars' are optiona; additional local variables\n \"\"\"\n f_locals = self.f_locals.copy()\n f_locals.update(vars)\n exec(code, self.f_globals, f_locals)\n\n def repr(self, object):\n \"\"\" return a 'safe' (non-recursive, one-line) string repr for 'object'\n \"\"\"\n return saferepr(object)\n\n def is_true(self, object):\n return object\n\n def getargs(self, var=False):\n \"\"\" return a list of tuples (name, value) for all arguments\n\n if 'var' is set True also include the variable and keyword\n arguments when present\n \"\"\"\n retval = []\n for arg in self.code.getargs(var):\n try:\n retval.append((arg, self.f_locals[arg]))\n except KeyError:\n pass # this can occur when using Psyco\n return retval"},{"col":4,"comment":"null","endLoc":2942,"header":"def test_setup(self, testdir, scope, ok, error)","id":2642,"name":"test_setup","nodeType":"Function","startLoc":2923,"text":"def test_setup(self, testdir, scope, ok, error):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=%r, autouse=True)\n def myscoped(request):\n for x in %r:\n assert hasattr(request, x)\n for x in %r:\n pytest.raises(AttributeError, lambda:\n getattr(request, x))\n assert request.session\n assert request.config\n def test_func():\n pass\n \"\"\"\n % (scope, ok.split(), error.split())\n )\n reprec = testdir.inline_run(\"-l\")\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":" statement this frame is at ","endLoc":121,"header":"@property\n def statement(self)","id":2643,"name":"statement","nodeType":"Function","startLoc":114,"text":"@property\n def statement(self):\n \"\"\" statement this frame is at \"\"\"\n import _pytest._code\n\n if self.code.fullsource is None:\n return _pytest._code.Source(\"\")\n return self.code.fullsource.getstatement(self.lineno)"},{"col":4,"comment":"null","endLoc":2963,"header":"def test_funcarg(self, testdir, scope, ok, error)","id":2644,"name":"test_funcarg","nodeType":"Function","startLoc":2944,"text":"def test_funcarg(self, testdir, scope, ok, error):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope=%r)\n def arg(request):\n for x in %r:\n assert hasattr(request, x)\n for x in %r:\n pytest.raises(AttributeError, lambda:\n getattr(request, x))\n assert request.session\n assert request.config\n def test_func(arg):\n pass\n \"\"\"\n % (scope, ok.split(), error.split())\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":" evaluate 'code' in the frame\n\n 'vars' are optional additional local variables\n\n returns the result of the evaluation\n ","endLoc":132,"header":"def eval(self, code, **vars)","id":2645,"name":"eval","nodeType":"Function","startLoc":123,"text":"def eval(self, code, **vars):\n \"\"\" evaluate 'code' in the frame\n\n 'vars' are optional additional local variables\n\n returns the result of the evaluation\n \"\"\"\n f_locals = self.f_locals.copy()\n f_locals.update(vars)\n return eval(code, self.f_globals, f_locals)"},{"attributeType":"null","col":4,"comment":"null","endLoc":2913,"id":2646,"name":"pytestmark","nodeType":"Attribute","startLoc":2913,"text":"pytestmark"},{"col":0,"comment":"#3605","endLoc":1005,"header":"@pytest.mark.filterwarnings(\"ignore\")\ndef test_markers_from_parametrize(testdir)","id":2647,"name":"test_markers_from_parametrize","nodeType":"Function","startLoc":969,"text":"@pytest.mark.filterwarnings(\"ignore\")\ndef test_markers_from_parametrize(testdir):\n \"\"\"#3605\"\"\"\n testdir.makepyfile(\n \"\"\"\n from __future__ import print_function\n import pytest\n\n first_custom_mark = pytest.mark.custom_marker\n custom_mark = pytest.mark.custom_mark\n @pytest.fixture(autouse=True)\n def trigger(request):\n custom_mark = list(request.node.iter_markers('custom_mark'))\n print(\"Custom mark %s\" % custom_mark)\n\n @custom_mark(\"custom mark non parametrized\")\n def test_custom_mark_non_parametrized():\n print(\"Hey from test\")\n\n @pytest.mark.parametrize(\n \"obj_type\",\n [\n first_custom_mark(\"first custom mark\")(\"template\"),\n pytest.param( # Think this should be recommended way?\n \"disk\",\n marks=custom_mark('custom mark1')\n ),\n custom_mark(\"custom mark2\")(\"vm\"), # Tried also this\n ]\n )\n def test_custom_mark_parametrized(obj_type):\n print(\"obj_type is:\", obj_type)\n \"\"\"\n )\n\n result = testdir.runpytest(SHOW_PYTEST_WARNINGS_ARG)\n result.assert_outcomes(passed=4)"},{"className":"TestErrors","col":0,"comment":"null","endLoc":3030,"id":2648,"nodeType":"Class","startLoc":2966,"text":"class TestErrors(object):\n def test_subfactory_missing_funcarg(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture()\n def gen(qwe123):\n return 1\n def test_something(gen):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret != 0\n result.stdout.fnmatch_lines(\n [\"*def gen(qwe123):*\", \"*fixture*qwe123*not found*\", \"*1 error*\"]\n )\n\n def test_issue498_fixture_finalizer_failing(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def fix1(request):\n def f():\n raise KeyError\n request.addfinalizer(f)\n return object()\n\n values = []\n def test_1(fix1):\n values.append(fix1)\n def test_2(fix1):\n values.append(fix1)\n def test_3():\n assert values[0] != values[1]\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n \"\"\"\n *ERROR*teardown*test_1*\n *KeyError*\n *ERROR*teardown*test_2*\n *KeyError*\n *3 pass*2 error*\n \"\"\"\n )\n\n def test_setupfunc_missing_funcarg(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(autouse=True)\n def gen(qwe123):\n return 1\n def test_something():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret != 0\n result.stdout.fnmatch_lines(\n [\"*def gen(qwe123):*\", \"*fixture*qwe123*not found*\", \"*1 error*\"]\n )"},{"col":4,"comment":"null","endLoc":2982,"header":"def test_subfactory_missing_funcarg(self, testdir)","id":2649,"name":"test_subfactory_missing_funcarg","nodeType":"Function","startLoc":2967,"text":"def test_subfactory_missing_funcarg(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture()\n def gen(qwe123):\n return 1\n def test_something(gen):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret != 0\n result.stdout.fnmatch_lines(\n [\"*def gen(qwe123):*\", \"*fixture*qwe123*not found*\", \"*1 error*\"]\n )"},{"col":4,"comment":" exec 'code' in the frame\n\n 'vars' are optiona; additional local variables\n ","endLoc":141,"header":"def exec_(self, code, **vars)","id":2650,"name":"exec_","nodeType":"Function","startLoc":134,"text":"def exec_(self, code, **vars):\n \"\"\" exec 'code' in the frame\n\n 'vars' are optiona; additional local variables\n \"\"\"\n f_locals = self.f_locals.copy()\n f_locals.update(vars)\n exec(code, self.f_globals, f_locals)"},{"col":4,"comment":"null","endLoc":3013,"header":"def test_issue498_fixture_finalizer_failing(self, testdir)","id":2651,"name":"test_issue498_fixture_finalizer_failing","nodeType":"Function","startLoc":2984,"text":"def test_issue498_fixture_finalizer_failing(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def fix1(request):\n def f():\n raise KeyError\n request.addfinalizer(f)\n return object()\n\n values = []\n def test_1(fix1):\n values.append(fix1)\n def test_2(fix1):\n values.append(fix1)\n def test_3():\n assert values[0] != values[1]\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n \"\"\"\n *ERROR*teardown*test_1*\n *KeyError*\n *ERROR*teardown*test_2*\n *KeyError*\n *3 pass*2 error*\n \"\"\"\n )"},{"col":4,"comment":"null","endLoc":3030,"header":"def test_setupfunc_missing_funcarg(self, testdir)","id":2657,"name":"test_setupfunc_missing_funcarg","nodeType":"Function","startLoc":3015,"text":"def test_setupfunc_missing_funcarg(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(autouse=True)\n def gen(qwe123):\n return 1\n def test_something():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret != 0\n result.stdout.fnmatch_lines(\n [\"*def gen(qwe123):*\", \"*fixture*qwe123*not found*\", \"*1 error*\"]\n )"},{"col":4,"comment":" return a 'safe' (non-recursive, one-line) string repr for 'object'\n ","endLoc":146,"header":"def repr(self, object)","id":2658,"name":"repr","nodeType":"Function","startLoc":143,"text":"def repr(self, object):\n \"\"\" return a 'safe' (non-recursive, one-line) string repr for 'object'\n \"\"\"\n return saferepr(object)"},{"col":4,"comment":"null","endLoc":149,"header":"def is_true(self, object)","id":2659,"name":"is_true","nodeType":"Function","startLoc":148,"text":"def is_true(self, object):\n return object"},{"attributeType":"null","col":8,"comment":"null","endLoc":108,"id":2660,"name":"lineno","nodeType":"Attribute","startLoc":108,"text":"self.lineno"},{"col":0,"comment":"null","endLoc":1015,"header":"def test_pytest_param_id_requires_string()","id":2661,"name":"test_pytest_param_id_requires_string","nodeType":"Function","startLoc":1008,"text":"def test_pytest_param_id_requires_string():\n with pytest.raises(TypeError) as excinfo:\n pytest.param(id=True)\n msg, = excinfo.value.args\n if six.PY2:\n assert msg == \"Expected id to be a string, got : True\"\n else:\n assert msg == \"Expected id to be a string, got : True\""},{"className":"TestShowFixtures","col":0,"comment":"null","endLoc":3318,"id":2662,"nodeType":"Class","startLoc":3033,"text":"class TestShowFixtures(object):\n def test_funcarg_compat(self, testdir):\n config = testdir.parseconfigure(\"--funcargs\")\n assert config.option.showfixtures\n\n def test_show_fixtures(self, testdir):\n result = testdir.runpytest(\"--fixtures\")\n result.stdout.fnmatch_lines(\n [\n \"tmpdir_factory [[]session scope[]]\",\n \"*for the test session*\",\n \"tmpdir\",\n \"*temporary directory*\",\n ]\n )\n\n def test_show_fixtures_verbose(self, testdir):\n result = testdir.runpytest(\"--fixtures\", \"-v\")\n result.stdout.fnmatch_lines(\n [\n \"tmpdir_factory [[]session scope[]] -- *tmpdir.py*\",\n \"*for the test session*\",\n \"tmpdir -- *tmpdir.py*\",\n \"*temporary directory*\",\n ]\n )\n\n def test_show_fixtures_testmodule(self, testdir):\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture\n def _arg0():\n \"\"\" hidden \"\"\"\n @pytest.fixture\n def arg1():\n \"\"\" hello world \"\"\"\n '''\n )\n result = testdir.runpytest(\"--fixtures\", p)\n result.stdout.fnmatch_lines(\n \"\"\"\n *tmpdir\n *fixtures defined from*\n *arg1*\n *hello world*\n \"\"\"\n )\n assert \"arg0\" not in result.stdout.str()\n\n @pytest.mark.parametrize(\"testmod\", [True, False])\n def test_show_fixtures_conftest(self, testdir, testmod):\n testdir.makeconftest(\n '''\n import pytest\n @pytest.fixture\n def arg1():\n \"\"\" hello world \"\"\"\n '''\n )\n if testmod:\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--fixtures\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *tmpdir*\n *fixtures defined from*conftest*\n *arg1*\n *hello world*\n \"\"\"\n )\n\n def test_show_fixtures_trimmed_doc(self, testdir):\n p = testdir.makepyfile(\n textwrap.dedent(\n '''\\\n import pytest\n @pytest.fixture\n def arg1():\n \"\"\"\n line1\n line2\n\n \"\"\"\n @pytest.fixture\n def arg2():\n \"\"\"\n line1\n line2\n\n \"\"\"\n '''\n )\n )\n result = testdir.runpytest(\"--fixtures\", p)\n result.stdout.fnmatch_lines(\n textwrap.dedent(\n \"\"\"\\\n * fixtures defined from test_show_fixtures_trimmed_doc *\n arg2\n line1\n line2\n arg1\n line1\n line2\n \"\"\"\n )\n )\n\n def test_show_fixtures_indented_doc(self, testdir):\n p = testdir.makepyfile(\n textwrap.dedent(\n '''\\\n import pytest\n @pytest.fixture\n def fixture1():\n \"\"\"\n line1\n indented line\n \"\"\"\n '''\n )\n )\n result = testdir.runpytest(\"--fixtures\", p)\n result.stdout.fnmatch_lines(\n textwrap.dedent(\n \"\"\"\\\n * fixtures defined from test_show_fixtures_indented_doc *\n fixture1\n line1\n indented line\n \"\"\"\n )\n )\n\n def test_show_fixtures_indented_doc_first_line_unindented(self, testdir):\n p = testdir.makepyfile(\n textwrap.dedent(\n '''\\\n import pytest\n @pytest.fixture\n def fixture1():\n \"\"\"line1\n line2\n indented line\n \"\"\"\n '''\n )\n )\n result = testdir.runpytest(\"--fixtures\", p)\n result.stdout.fnmatch_lines(\n textwrap.dedent(\n \"\"\"\\\n * fixtures defined from test_show_fixtures_indented_doc_first_line_unindented *\n fixture1\n line1\n line2\n indented line\n \"\"\"\n )\n )\n\n def test_show_fixtures_indented_in_class(self, testdir):\n p = testdir.makepyfile(\n textwrap.dedent(\n '''\\\n import pytest\n class TestClass(object):\n @pytest.fixture\n def fixture1(self):\n \"\"\"line1\n line2\n indented line\n \"\"\"\n '''\n )\n )\n result = testdir.runpytest(\"--fixtures\", p)\n result.stdout.fnmatch_lines(\n textwrap.dedent(\n \"\"\"\\\n * fixtures defined from test_show_fixtures_indented_in_class *\n fixture1\n line1\n line2\n indented line\n \"\"\"\n )\n )\n\n def test_show_fixtures_different_files(self, testdir):\n \"\"\"\n #833: --fixtures only shows fixtures from first file\n \"\"\"\n testdir.makepyfile(\n test_a='''\n import pytest\n\n @pytest.fixture\n def fix_a():\n \"\"\"Fixture A\"\"\"\n pass\n\n def test_a(fix_a):\n pass\n '''\n )\n testdir.makepyfile(\n test_b='''\n import pytest\n\n @pytest.fixture\n def fix_b():\n \"\"\"Fixture B\"\"\"\n pass\n\n def test_b(fix_b):\n pass\n '''\n )\n result = testdir.runpytest(\"--fixtures\")\n result.stdout.fnmatch_lines(\n \"\"\"\n * fixtures defined from test_a *\n fix_a\n Fixture A\n\n * fixtures defined from test_b *\n fix_b\n Fixture B\n \"\"\"\n )\n\n def test_show_fixtures_with_same_name(self, testdir):\n testdir.makeconftest(\n '''\n import pytest\n @pytest.fixture\n def arg1():\n \"\"\"Hello World in conftest.py\"\"\"\n return \"Hello World\"\n '''\n )\n testdir.makepyfile(\n \"\"\"\n def test_foo(arg1):\n assert arg1 == \"Hello World\"\n \"\"\"\n )\n testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture\n def arg1():\n \"\"\"Hi from test module\"\"\"\n return \"Hi\"\n def test_bar(arg1):\n assert arg1 == \"Hi\"\n '''\n )\n result = testdir.runpytest(\"--fixtures\")\n result.stdout.fnmatch_lines(\n \"\"\"\n * fixtures defined from conftest *\n arg1\n Hello World in conftest.py\n\n * fixtures defined from test_show_fixtures_with_same_name *\n arg1\n Hi from test module\n \"\"\"\n )\n\n def test_fixture_disallow_twice(self):\n \"\"\"Test that applying @pytest.fixture twice generates an error (#2334).\"\"\"\n with pytest.raises(ValueError):\n\n @pytest.fixture\n @pytest.fixture\n def foo():\n pass"},{"attributeType":"null","col":8,"comment":"null","endLoc":112,"id":2663,"name":"code","nodeType":"Attribute","startLoc":112,"text":"self.code"},{"attributeType":"null","col":8,"comment":"null","endLoc":111,"id":2664,"name":"raw","nodeType":"Attribute","startLoc":111,"text":"self.raw"},{"col":4,"comment":"null","endLoc":3036,"header":"def test_funcarg_compat(self, testdir)","id":2665,"name":"test_funcarg_compat","nodeType":"Function","startLoc":3034,"text":"def test_funcarg_compat(self, testdir):\n config = testdir.parseconfigure(\"--funcargs\")\n assert config.option.showfixtures"},{"col":4,"comment":"null","endLoc":3047,"header":"def test_show_fixtures(self, testdir)","id":2666,"name":"test_show_fixtures","nodeType":"Function","startLoc":3038,"text":"def test_show_fixtures(self, testdir):\n result = testdir.runpytest(\"--fixtures\")\n result.stdout.fnmatch_lines(\n [\n \"tmpdir_factory [[]session scope[]]\",\n \"*for the test session*\",\n \"tmpdir\",\n \"*temporary directory*\",\n ]\n )"},{"col":0,"comment":"null","endLoc":1020,"header":"@pytest.mark.parametrize(\"s\", (None, \"hello world\"))\ndef test_pytest_param_id_allows_none_or_string(s)","id":2667,"name":"test_pytest_param_id_allows_none_or_string","nodeType":"Function","startLoc":1018,"text":"@pytest.mark.parametrize(\"s\", (None, \"hello world\"))\ndef test_pytest_param_id_allows_none_or_string(s):\n assert pytest.param(id=s)"},{"attributeType":"null","col":8,"comment":"null","endLoc":109,"id":2668,"name":"f_globals","nodeType":"Attribute","startLoc":109,"text":"self.f_globals"},{"col":4,"comment":"null","endLoc":3058,"header":"def test_show_fixtures_verbose(self, testdir)","id":2670,"name":"test_show_fixtures_verbose","nodeType":"Function","startLoc":3049,"text":"def test_show_fixtures_verbose(self, testdir):\n result = testdir.runpytest(\"--fixtures\", \"-v\")\n result.stdout.fnmatch_lines(\n [\n \"tmpdir_factory [[]session scope[]] -- *tmpdir.py*\",\n \"*for the test session*\",\n \"tmpdir -- *tmpdir.py*\",\n \"*temporary directory*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":3081,"header":"def test_show_fixtures_testmodule(self, testdir)","id":2671,"name":"test_show_fixtures_testmodule","nodeType":"Function","startLoc":3060,"text":"def test_show_fixtures_testmodule(self, testdir):\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture\n def _arg0():\n \"\"\" hidden \"\"\"\n @pytest.fixture\n def arg1():\n \"\"\" hello world \"\"\"\n '''\n )\n result = testdir.runpytest(\"--fixtures\", p)\n result.stdout.fnmatch_lines(\n \"\"\"\n *tmpdir\n *fixtures defined from*\n *arg1*\n *hello world*\n \"\"\"\n )\n assert \"arg0\" not in result.stdout.str()"},{"col":4,"comment":"null","endLoc":3108,"header":"@pytest.mark.parametrize(\"testmod\", [True, False])\n def test_show_fixtures_conftest(self, testdir, testmod)","id":2672,"name":"test_show_fixtures_conftest","nodeType":"Function","startLoc":3083,"text":"@pytest.mark.parametrize(\"testmod\", [True, False])\n def test_show_fixtures_conftest(self, testdir, testmod):\n testdir.makeconftest(\n '''\n import pytest\n @pytest.fixture\n def arg1():\n \"\"\" hello world \"\"\"\n '''\n )\n if testmod:\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--fixtures\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *tmpdir*\n *fixtures defined from*conftest*\n *arg1*\n *hello world*\n \"\"\"\n )"},{"id":2673,"name":"testing/example_scripts/collect/package_init_given_as_arg/pkg","nodeType":"Package"},{"fileName":"test_foo.py","filePath":"testing/example_scripts/collect/package_init_given_as_arg/pkg","id":2674,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ndef test():\n pass\n"},{"col":0,"comment":"null","endLoc":3,"header":"def test()","id":2675,"name":"test","nodeType":"Function","startLoc":2,"text":"def test():\n pass"},{"col":4,"comment":"null","endLoc":680,"header":"def _ensure_unconfigure(self)","id":2676,"name":"_ensure_unconfigure","nodeType":"Function","startLoc":673,"text":"def _ensure_unconfigure(self):\n if self._configured:\n self._configured = False\n self.hook.pytest_unconfigure(config=self)\n self.hook.pytest_configure._call_history = []\n while self._cleanup:\n fin = self._cleanup.pop()\n fin()"},{"id":2677,"name":"doc/en/example/costlysetup/sub_a","nodeType":"Package"},{"fileName":"__init__.py","filePath":"doc/en/example/costlysetup/sub_a","id":2678,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n#\n"},{"col":0,"comment":"null","endLoc":1032,"header":"def test_pytest_param_warning_on_unknown_kwargs()","id":2679,"name":"test_pytest_param_warning_on_unknown_kwargs","nodeType":"Function","startLoc":1023,"text":"def test_pytest_param_warning_on_unknown_kwargs():\n with pytest.warns(PytestDeprecationWarning) as warninfo:\n # typo, should be marks=\n pytest.param(1, 2, mark=pytest.mark.xfail())\n assert warninfo[0].filename == __file__\n msg, = warninfo[0].message.args\n assert msg == (\n \"pytest.param() got unexpected keyword arguments: ['mark'].\\n\"\n \"This will be an error in future versions.\"\n )"},{"id":2680,"name":"testing/example_scripts/warnings","nodeType":"Package"},{"fileName":"test_group_warnings_by_message.py","filePath":"testing/example_scripts/warnings","id":2681,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport warnings\n\nimport pytest\n\n\ndef func():\n warnings.warn(UserWarning(\"foo\"))\n\n\n@pytest.mark.parametrize(\"i\", range(5))\ndef test_foo(i):\n func()\n\n\ndef test_bar():\n func()\n"},{"col":4,"comment":"null","endLoc":3145,"header":"def test_show_fixtures_trimmed_doc(self, testdir)","id":2682,"name":"test_show_fixtures_trimmed_doc","nodeType":"Function","startLoc":3110,"text":"def test_show_fixtures_trimmed_doc(self, testdir):\n p = testdir.makepyfile(\n textwrap.dedent(\n '''\\\n import pytest\n @pytest.fixture\n def arg1():\n \"\"\"\n line1\n line2\n\n \"\"\"\n @pytest.fixture\n def arg2():\n \"\"\"\n line1\n line2\n\n \"\"\"\n '''\n )\n )\n result = testdir.runpytest(\"--fixtures\", p)\n result.stdout.fnmatch_lines(\n textwrap.dedent(\n \"\"\"\\\n * fixtures defined from test_show_fixtures_trimmed_doc *\n arg2\n line1\n line2\n arg1\n line1\n line2\n \"\"\"\n )\n )"},{"col":0,"comment":"null","endLoc":8,"header":"def func()","id":2683,"name":"func","nodeType":"Function","startLoc":7,"text":"def func():\n warnings.warn(UserWarning(\"foo\"))"},{"col":4,"comment":"null","endLoc":3171,"header":"def test_show_fixtures_indented_doc(self, testdir)","id":2684,"name":"test_show_fixtures_indented_doc","nodeType":"Function","startLoc":3147,"text":"def test_show_fixtures_indented_doc(self, testdir):\n p = testdir.makepyfile(\n textwrap.dedent(\n '''\\\n import pytest\n @pytest.fixture\n def fixture1():\n \"\"\"\n line1\n indented line\n \"\"\"\n '''\n )\n )\n result = testdir.runpytest(\"--fixtures\", p)\n result.stdout.fnmatch_lines(\n textwrap.dedent(\n \"\"\"\\\n * fixtures defined from test_show_fixtures_indented_doc *\n fixture1\n line1\n indented line\n \"\"\"\n )\n )"},{"attributeType":"null","col":8,"comment":"null","endLoc":110,"id":2685,"name":"f_locals","nodeType":"Attribute","startLoc":110,"text":"self.f_locals"},{"className":"Traceback","col":0,"comment":" Traceback objects encapsulate and offer higher level\n access to Traceback entries.\n ","endLoc":380,"id":2686,"nodeType":"Class","startLoc":279,"text":"class Traceback(list):\n \"\"\" Traceback objects encapsulate and offer higher level\n access to Traceback entries.\n \"\"\"\n\n Entry = TracebackEntry\n\n def __init__(self, tb, excinfo=None):\n \"\"\" initialize from given python traceback object and ExceptionInfo \"\"\"\n self._excinfo = excinfo\n if hasattr(tb, \"tb_next\"):\n\n def f(cur):\n while cur is not None:\n yield self.Entry(cur, excinfo=excinfo)\n cur = cur.tb_next\n\n list.__init__(self, f(tb))\n else:\n list.__init__(self, tb)\n\n def cut(self, path=None, lineno=None, firstlineno=None, excludepath=None):\n \"\"\" return a Traceback instance wrapping part of this Traceback\n\n by provding any combination of path, lineno and firstlineno, the\n first frame to start the to-be-returned traceback is determined\n\n this allows cutting the first part of a Traceback instance e.g.\n for formatting reasons (removing some uninteresting bits that deal\n with handling of the exception/traceback)\n \"\"\"\n for x in self:\n code = x.frame.code\n codepath = code.path\n if (\n (path is None or codepath == path)\n and (\n excludepath is None\n or not hasattr(codepath, \"relto\")\n or not codepath.relto(excludepath)\n )\n and (lineno is None or x.lineno == lineno)\n and (firstlineno is None or x.frame.code.firstlineno == firstlineno)\n ):\n return Traceback(x._rawentry, self._excinfo)\n return self\n\n def __getitem__(self, key):\n val = super(Traceback, self).__getitem__(key)\n if isinstance(key, type(slice(0))):\n val = self.__class__(val)\n return val\n\n def filter(self, fn=lambda x: not x.ishidden()):\n \"\"\" return a Traceback instance with certain items removed\n\n fn is a function that gets a single argument, a TracebackEntry\n instance, and should return True when the item should be added\n to the Traceback, False when not\n\n by default this removes all the TracebackEntries which are hidden\n (see ishidden() above)\n \"\"\"\n return Traceback(filter(fn, self), self._excinfo)\n\n def getcrashentry(self):\n \"\"\" return last non-hidden traceback entry that lead\n to the exception of a traceback.\n \"\"\"\n for i in range(-1, -len(self) - 1, -1):\n entry = self[i]\n if not entry.ishidden():\n return entry\n return self[-1]\n\n def recursionindex(self):\n \"\"\" return the index of the frame/TracebackEntry where recursion\n originates if appropriate, None if no recursion occurred\n \"\"\"\n cache = {}\n for i, entry in enumerate(self):\n # id for the code.raw is needed to work around\n # the strange metaprogramming in the decorator lib from pypi\n # which generates code objects that have hash/value equality\n # XXX needs a test\n key = entry.frame.code.path, id(entry.frame.code.raw), entry.lineno\n # print \"checking for recursion at\", key\n values = cache.setdefault(key, [])\n if values:\n f = entry.frame\n loc = f.f_locals\n for otherloc in values:\n if f.is_true(\n f.eval(\n co_equal,\n __recursioncache_locals_1=loc,\n __recursioncache_locals_2=otherloc,\n )\n ):\n return i\n values.append(entry.frame.f_locals)\n return None"},{"col":4,"comment":"null","endLoc":3198,"header":"def test_show_fixtures_indented_doc_first_line_unindented(self, testdir)","id":2687,"name":"test_show_fixtures_indented_doc_first_line_unindented","nodeType":"Function","startLoc":3173,"text":"def test_show_fixtures_indented_doc_first_line_unindented(self, testdir):\n p = testdir.makepyfile(\n textwrap.dedent(\n '''\\\n import pytest\n @pytest.fixture\n def fixture1():\n \"\"\"line1\n line2\n indented line\n \"\"\"\n '''\n )\n )\n result = testdir.runpytest(\"--fixtures\", p)\n result.stdout.fnmatch_lines(\n textwrap.dedent(\n \"\"\"\\\n * fixtures defined from test_show_fixtures_indented_doc_first_line_unindented *\n fixture1\n line1\n line2\n indented line\n \"\"\"\n )\n )"},{"className":"list","col":0,"comment":"null","endLoc":1061,"id":2688,"nodeType":"Class","startLoc":1008,"text":"class list(MutableSequence[_T], Generic[_T]):\n @overload\n def __init__(self) -> None: ...\n @overload\n def __init__(self, __iterable: Iterable[_T]) -> None: ...\n def copy(self) -> list[_T]: ...\n def append(self, __object: _T) -> None: ...\n def extend(self, __iterable: Iterable[_T]) -> None: ...\n def pop(self, __index: SupportsIndex = -1) -> _T: ...\n # Signature of `list.index` should be kept in line with `collections.UserList.index()`\n # and multiprocessing.managers.ListProxy.index()\n def index(self, __value: _T, __start: SupportsIndex = 0, __stop: SupportsIndex = sys.maxsize) -> int: ...\n def count(self, __value: _T) -> int: ...\n def insert(self, __index: SupportsIndex, __object: _T) -> None: ...\n def remove(self, __value: _T) -> None: ...\n # Signature of `list.sort` should be kept inline with `collections.UserList.sort()`\n # and multiprocessing.managers.ListProxy.sort()\n #\n # Use list[SupportsRichComparisonT] for the first overload rather than [SupportsRichComparison]\n # to work around invariance\n @overload\n def sort(self: list[SupportsRichComparisonT], *, key: None = None, reverse: bool = False) -> None: ...\n @overload\n def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> None: ...\n def __len__(self) -> int: ...\n def __iter__(self) -> Iterator[_T]: ...\n __hash__: ClassVar[None] # type: ignore[assignment]\n @overload\n def __getitem__(self, __i: SupportsIndex) -> _T: ...\n @overload\n def __getitem__(self, __s: slice) -> list[_T]: ...\n @overload\n def __setitem__(self, __key: SupportsIndex, __value: _T) -> None: ...\n @overload\n def __setitem__(self, __key: slice, __value: Iterable[_T]) -> None: ...\n def __delitem__(self, __key: SupportsIndex | slice) -> None: ...\n # Overloading looks unnecessary, but is needed to work around complex mypy problems\n @overload\n def __add__(self, __value: list[_T]) -> list[_T]: ...\n @overload\n def __add__(self, __value: list[_S]) -> list[_S | _T]: ...\n def __iadd__(self, __value: Iterable[_T]) -> Self: ... # type: ignore[misc]\n def __mul__(self, __value: SupportsIndex) -> list[_T]: ...\n def __rmul__(self, __value: SupportsIndex) -> list[_T]: ...\n def __imul__(self, __value: SupportsIndex) -> Self: ...\n def __contains__(self, __key: object) -> bool: ...\n def __reversed__(self) -> Iterator[_T]: ...\n def __gt__(self, __value: list[_T]) -> bool: ...\n def __ge__(self, __value: list[_T]) -> bool: ...\n def __lt__(self, __value: list[_T]) -> bool: ...\n def __le__(self, __value: list[_T]) -> bool: ...\n def __eq__(self, __value: object) -> bool: ...\n if sys.version_info >= (3, 9):\n def __class_getitem__(cls, __item: Any) -> GenericAlias: ..."},{"col":0,"comment":"null","endLoc":13,"header":"@pytest.mark.parametrize(\"i\", range(5))\ndef test_foo(i)","id":2689,"name":"test_foo","nodeType":"Function","startLoc":11,"text":"@pytest.mark.parametrize(\"i\", range(5))\ndef test_foo(i):\n func()"},{"attributeType":"null","col":42,"comment":"null","endLoc":14,"id":2690,"name":"Mark","nodeType":"Attribute","startLoc":14,"text":"Mark"},{"col":4,"comment":"null","endLoc":3226,"header":"def test_show_fixtures_indented_in_class(self, testdir)","id":2691,"name":"test_show_fixtures_indented_in_class","nodeType":"Function","startLoc":3200,"text":"def test_show_fixtures_indented_in_class(self, testdir):\n p = testdir.makepyfile(\n textwrap.dedent(\n '''\\\n import pytest\n class TestClass(object):\n @pytest.fixture\n def fixture1(self):\n \"\"\"line1\n line2\n indented line\n \"\"\"\n '''\n )\n )\n result = testdir.runpytest(\"--fixtures\", p)\n result.stdout.fnmatch_lines(\n textwrap.dedent(\n \"\"\"\\\n * fixtures defined from test_show_fixtures_indented_in_class *\n fixture1\n line1\n line2\n indented line\n \"\"\"\n )\n )"},{"attributeType":"null","col":28,"comment":"null","endLoc":23,"id":2692,"name":"mock","nodeType":"Attribute","startLoc":23,"text":"mock"},{"attributeType":"null","col":0,"comment":"null","endLoc":25,"id":2693,"name":"ignore_markinfo","nodeType":"Attribute","startLoc":25,"text":"ignore_markinfo"},{"col":0,"comment":"","endLoc":2,"header":"test_mark.py#","id":2694,"name":"","nodeType":"Function","startLoc":2,"text":"try:\n import mock\nexcept ImportError:\n import unittest.mock as mock\n\nignore_markinfo = pytest.mark.filterwarnings(\n \"ignore:MarkInfo objects:pytest.RemovedInPytest4Warning\"\n)"},{"col":4,"comment":"\n #833: --fixtures only shows fixtures from first file\n ","endLoc":3269,"header":"def test_show_fixtures_different_files(self, testdir)","id":2695,"name":"test_show_fixtures_different_files","nodeType":"Function","startLoc":3228,"text":"def test_show_fixtures_different_files(self, testdir):\n \"\"\"\n #833: --fixtures only shows fixtures from first file\n \"\"\"\n testdir.makepyfile(\n test_a='''\n import pytest\n\n @pytest.fixture\n def fix_a():\n \"\"\"Fixture A\"\"\"\n pass\n\n def test_a(fix_a):\n pass\n '''\n )\n testdir.makepyfile(\n test_b='''\n import pytest\n\n @pytest.fixture\n def fix_b():\n \"\"\"Fixture B\"\"\"\n pass\n\n def test_b(fix_b):\n pass\n '''\n )\n result = testdir.runpytest(\"--fixtures\")\n result.stdout.fnmatch_lines(\n \"\"\"\n * fixtures defined from test_a *\n fix_a\n Fixture A\n\n * fixtures defined from test_b *\n fix_b\n Fixture B\n \"\"\"\n )"},{"col":4,"comment":"null","endLoc":3309,"header":"def test_show_fixtures_with_same_name(self, testdir)","id":2696,"name":"test_show_fixtures_with_same_name","nodeType":"Function","startLoc":3271,"text":"def test_show_fixtures_with_same_name(self, testdir):\n testdir.makeconftest(\n '''\n import pytest\n @pytest.fixture\n def arg1():\n \"\"\"Hello World in conftest.py\"\"\"\n return \"Hello World\"\n '''\n )\n testdir.makepyfile(\n \"\"\"\n def test_foo(arg1):\n assert arg1 == \"Hello World\"\n \"\"\"\n )\n testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture\n def arg1():\n \"\"\"Hi from test module\"\"\"\n return \"Hi\"\n def test_bar(arg1):\n assert arg1 == \"Hi\"\n '''\n )\n result = testdir.runpytest(\"--fixtures\")\n result.stdout.fnmatch_lines(\n \"\"\"\n * fixtures defined from conftest *\n arg1\n Hello World in conftest.py\n\n * fixtures defined from test_show_fixtures_with_same_name *\n arg1\n Hi from test module\n \"\"\"\n )"},{"id":2697,"name":"links.inc","nodeType":"TextFile","path":"doc/en","text":"\n.. _`skipping plugin`: plugin/skipping.html\n.. _`funcargs mechanism`: funcargs.html\n.. _`doctest.py`: http://docs.python.org/library/doctest.html\n.. _`xUnit style setup`: xunit_setup.html\n.. _`pytest_nose`: plugin/nose.html\n.. _`reStructured Text`: http://docutils.sourceforge.net\n.. _`Python debugger`: http://docs.python.org/lib/module-pdb.html\n.. _nose: https://nose.readthedocs.io/en/latest/\n.. _pytest: https://pypi.org/project/pytest/\n.. _mercurial: http://mercurial.selenic.com/wiki/\n.. _`setuptools`: https://pypi.org/project/setuptools/\n.. _`easy_install`:\n.. _`distribute docs`:\n.. _`distribute`: https://pypi.org/project/distribute/\n.. _`pip`: https://pypi.org/project/pip/\n.. _`venv`: https://docs.python.org/3/library/venv.html/\n.. _`virtualenv`: https://pypi.org/project/virtualenv/\n.. _hudson: http://hudson-ci.org/\n.. _jenkins: http://jenkins-ci.org/\n.. _tox: http://testrun.org/tox\n.. _pylib: https://py.readthedocs.io/en/latest/\n"},{"col":4,"comment":"Test that applying @pytest.fixture twice generates an error (#2334).","endLoc":3318,"header":"def test_fixture_disallow_twice(self)","id":2699,"name":"test_fixture_disallow_twice","nodeType":"Function","startLoc":3311,"text":"def test_fixture_disallow_twice(self):\n \"\"\"Test that applying @pytest.fixture twice generates an error (#2334).\"\"\"\n with pytest.raises(ValueError):\n\n @pytest.fixture\n @pytest.fixture\n def foo():\n pass"},{"col":4,"comment":"null","endLoc":683,"header":"def get_terminal_writer(self)","id":2700,"name":"get_terminal_writer","nodeType":"Function","startLoc":682,"text":"def get_terminal_writer(self):\n return self.pluginmanager.get_plugin(\"terminalreporter\")._tw"},{"id":2701,"name":"cache.rst","nodeType":"TextFile","path":"doc/en","text":".. _`cache_provider`:\n.. _cache:\n\n\nCache: working with cross-testrun state\n=======================================\n\n\n\nUsage\n---------\n\nThe plugin provides two command line options to rerun failures from the\nlast ``pytest`` invocation:\n\n* ``--lf``, ``--last-failed`` - to only re-run the failures.\n* ``--ff``, ``--failed-first`` - to run the failures first and then the rest of\n the tests.\n\nFor cleanup (usually not needed), a ``--cache-clear`` option allows to remove\nall cross-session cache contents ahead of a test run.\n\nOther plugins may access the `config.cache`_ object to set/get\n**json encodable** values between ``pytest`` invocations.\n\n.. note::\n\n This plugin is enabled by default, but can be disabled if needed: see\n :ref:`cmdunregister` (the internal name for this plugin is\n ``cacheprovider``).\n\n\nRerunning only failures or failures first\n-----------------------------------------------\n\nFirst, let's create 50 test invocation of which only 2 fail::\n\n # content of test_50.py\n import pytest\n\n @pytest.mark.parametrize(\"i\", range(50))\n def test_num(i):\n if i in (17, 25):\n pytest.fail(\"bad luck\")\n\nIf you run this for the first time you will see two failures:\n\n.. code-block:: pytest\n\n $ pytest -q\n .................F.......F........................ [100%]\n ================================= FAILURES =================================\n _______________________________ test_num[17] _______________________________\n\n i = 17\n\n @pytest.mark.parametrize(\"i\", range(50))\n def test_num(i):\n if i in (17, 25):\n > pytest.fail(\"bad luck\")\n E Failed: bad luck\n\n test_50.py:6: Failed\n _______________________________ test_num[25] _______________________________\n\n i = 25\n\n @pytest.mark.parametrize(\"i\", range(50))\n def test_num(i):\n if i in (17, 25):\n > pytest.fail(\"bad luck\")\n E Failed: bad luck\n\n test_50.py:6: Failed\n 2 failed, 48 passed in 0.12 seconds\n\nIf you then run it with ``--lf``:\n\n.. code-block:: pytest\n\n $ pytest --lf\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 50 items / 48 deselected / 2 selected\n run-last-failure: rerun previous 2 failures\n\n test_50.py FF [100%]\n\n ================================= FAILURES =================================\n _______________________________ test_num[17] _______________________________\n\n i = 17\n\n @pytest.mark.parametrize(\"i\", range(50))\n def test_num(i):\n if i in (17, 25):\n > pytest.fail(\"bad luck\")\n E Failed: bad luck\n\n test_50.py:6: Failed\n _______________________________ test_num[25] _______________________________\n\n i = 25\n\n @pytest.mark.parametrize(\"i\", range(50))\n def test_num(i):\n if i in (17, 25):\n > pytest.fail(\"bad luck\")\n E Failed: bad luck\n\n test_50.py:6: Failed\n ================= 2 failed, 48 deselected in 0.12 seconds ==================\n\nYou have run only the two failing test from the last run, while 48 tests have\nnot been run (\"deselected\").\n\nNow, if you run with the ``--ff`` option, all tests will be run but the first\nprevious failures will be executed first (as can be seen from the series\nof ``FF`` and dots):\n\n.. code-block:: pytest\n\n $ pytest --ff\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 50 items\n run-last-failure: rerun previous 2 failures first\n\n test_50.py FF................................................ [100%]\n\n ================================= FAILURES =================================\n _______________________________ test_num[17] _______________________________\n\n i = 17\n\n @pytest.mark.parametrize(\"i\", range(50))\n def test_num(i):\n if i in (17, 25):\n > pytest.fail(\"bad luck\")\n E Failed: bad luck\n\n test_50.py:6: Failed\n _______________________________ test_num[25] _______________________________\n\n i = 25\n\n @pytest.mark.parametrize(\"i\", range(50))\n def test_num(i):\n if i in (17, 25):\n > pytest.fail(\"bad luck\")\n E Failed: bad luck\n\n test_50.py:6: Failed\n =================== 2 failed, 48 passed in 0.12 seconds ====================\n\n.. _`config.cache`:\n\nNew ``--nf``, ``--new-first`` options: run new tests first followed by the rest\nof the tests, in both cases tests are also sorted by the file modified time,\nwith more recent files coming first.\n\nBehavior when no tests failed in the last run\n---------------------------------------------\n\nWhen no tests failed in the last run, or when no cached ``lastfailed`` data was\nfound, ``pytest`` can be configured either to run all of the tests or no tests,\nusing the ``--last-failed-no-failures`` option, which takes one of the following values:\n\n.. code-block:: bash\n\n pytest --last-failed --last-failed-no-failures all # run all tests (default behavior)\n pytest --last-failed --last-failed-no-failures none # run no tests and exit\n\nThe new config.cache object\n--------------------------------\n\n.. regendoc:wipe\n\nPlugins or conftest.py support code can get a cached value using the\npytest ``config`` object. Here is a basic example plugin which\nimplements a :ref:`fixture` which re-uses previously created state\nacross pytest invocations::\n\n # content of test_caching.py\n import pytest\n import time\n\n def expensive_computation():\n print(\"running expensive computation...\")\n\n @pytest.fixture\n def mydata(request):\n val = request.config.cache.get(\"example/value\", None)\n if val is None:\n expensive_computation()\n val = 42\n request.config.cache.set(\"example/value\", val)\n return val\n\n def test_function(mydata):\n assert mydata == 23\n\nIf you run this command for the first time, you can see the print statement:\n\n.. code-block:: pytest\n\n $ pytest -q\n F [100%]\n ================================= FAILURES =================================\n ______________________________ test_function _______________________________\n\n mydata = 42\n\n def test_function(mydata):\n > assert mydata == 23\n E assert 42 == 23\n\n test_caching.py:17: AssertionError\n -------------------------- Captured stdout setup ---------------------------\n running expensive computation...\n 1 failed in 0.12 seconds\n\nIf you run it a second time the value will be retrieved from\nthe cache and nothing will be printed:\n\n.. code-block:: pytest\n\n $ pytest -q\n F [100%]\n ================================= FAILURES =================================\n ______________________________ test_function _______________________________\n\n mydata = 42\n\n def test_function(mydata):\n > assert mydata == 23\n E assert 42 == 23\n\n test_caching.py:17: AssertionError\n 1 failed in 0.12 seconds\n\nSee the :ref:`cache-api` for more details.\n\n\nInspecting Cache content\n------------------------\n\nYou can always peek at the content of the cache using the\n``--cache-show`` command line option:\n\n.. code-block:: pytest\n\n $ pytest --cache-show\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n cachedir: $PYTHON_PREFIX/.pytest_cache\n --------------------------- cache values for '*' ---------------------------\n cache/lastfailed contains:\n {'test_50.py::test_num[17]': True,\n 'test_50.py::test_num[25]': True,\n 'test_assert1.py::test_function': True,\n 'test_assert2.py::test_set_comparison': True,\n 'test_caching.py::test_function': True,\n 'test_foocompare.py::test_compare': True}\n cache/nodeids contains:\n ['test_caching.py::test_function']\n cache/stepwise contains:\n []\n example/value contains:\n 42\n\n ======================= no tests ran in 0.12 seconds =======================\n\n``--cache-show`` takes an optional argument to specify a glob pattern for\nfiltering:\n\n.. code-block:: pytest\n\n $ pytest --cache-show example/*\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n cachedir: $PYTHON_PREFIX/.pytest_cache\n ----------------------- cache values for 'example/*' -----------------------\n example/value contains:\n 42\n\n ======================= no tests ran in 0.12 seconds =======================\n\nClearing Cache content\n----------------------\n\nYou can instruct pytest to clear all cache files and values\nby adding the ``--cache-clear`` option like this:\n\n.. code-block:: bash\n\n pytest --cache-clear\n\nThis is recommended for invocations from Continuous Integration\nservers where isolation and correctness is more important\nthan speed.\n\n\nStepwise\n--------\n\nAs an alternative to ``--lf -x``, especially for cases where you expect a large part of the test suite will fail, ``--sw``, ``--stepwise`` allows you to fix them one at a time. The test suite will run until the first failure and then stop. At the next invocation, tests will continue from the last failing test and then run until the next failing test. You may use the ``--stepwise-skip`` option to ignore one failing test and stop the test execution on the second failing test instead. This is useful if you get stuck on a failing test and just want to ignore it until later.\n"},{"className":"TestContextManagerFixtureFuncs","col":0,"comment":"null","endLoc":3466,"id":2702,"nodeType":"Class","startLoc":3321,"text":"class TestContextManagerFixtureFuncs(object):\n @pytest.fixture(params=[\"fixture\", \"yield_fixture\"])\n def flavor(self, request, testdir, monkeypatch):\n monkeypatch.setenv(\"PYTEST_FIXTURE_FLAVOR\", request.param)\n testdir.makepyfile(\n test_context=\"\"\"\n import os\n import pytest\n import warnings\n VAR = \"PYTEST_FIXTURE_FLAVOR\"\n if VAR not in os.environ:\n warnings.warn(\"PYTEST_FIXTURE_FLAVOR was not set, assuming fixture\")\n fixture = pytest.fixture\n else:\n fixture = getattr(pytest, os.environ[VAR])\n \"\"\"\n )\n\n def test_simple(self, testdir, flavor):\n testdir.makepyfile(\n \"\"\"\n from __future__ import print_function\n from test_context import fixture\n @fixture\n def arg1():\n print(\"setup\")\n yield 1\n print(\"teardown\")\n def test_1(arg1):\n print(\"test1\", arg1)\n def test_2(arg1):\n print(\"test2\", arg1)\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *setup*\n *test1 1*\n *teardown*\n *setup*\n *test2 1*\n *teardown*\n \"\"\"\n )\n\n def test_scoped(self, testdir, flavor):\n testdir.makepyfile(\n \"\"\"\n from __future__ import print_function\n from test_context import fixture\n @fixture(scope=\"module\")\n def arg1():\n print(\"setup\")\n yield 1\n print(\"teardown\")\n def test_1(arg1):\n print(\"test1\", arg1)\n def test_2(arg1):\n print(\"test2\", arg1)\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *setup*\n *test1 1*\n *test2 1*\n *teardown*\n \"\"\"\n )\n\n def test_setup_exception(self, testdir, flavor):\n testdir.makepyfile(\n \"\"\"\n from test_context import fixture\n @fixture(scope=\"module\")\n def arg1():\n pytest.fail(\"setup\")\n yield 1\n def test_1(arg1):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *pytest.fail*setup*\n *1 error*\n \"\"\"\n )\n\n def test_teardown_exception(self, testdir, flavor):\n testdir.makepyfile(\n \"\"\"\n from test_context import fixture\n @fixture(scope=\"module\")\n def arg1():\n yield 1\n pytest.fail(\"teardown\")\n def test_1(arg1):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *pytest.fail*teardown*\n *1 passed*1 error*\n \"\"\"\n )\n\n def test_yields_more_than_one(self, testdir, flavor):\n testdir.makepyfile(\n \"\"\"\n from test_context import fixture\n @fixture(scope=\"module\")\n def arg1():\n yield 1\n yield 2\n def test_1(arg1):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *fixture function*\n *test_yields*:2*\n \"\"\"\n )\n\n def test_custom_name(self, testdir, flavor):\n testdir.makepyfile(\n \"\"\"\n from test_context import fixture\n @fixture(name='meow')\n def arg1():\n return 'mew'\n def test_1(meow):\n print(meow)\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines([\"*mew*\"])"},{"col":4,"comment":"null","endLoc":3337,"header":"@pytest.fixture(params=[\"fixture\", \"yield_fixture\"])\n def flavor(self, request, testdir, monkeypatch)","id":2703,"name":"flavor","nodeType":"Function","startLoc":3322,"text":"@pytest.fixture(params=[\"fixture\", \"yield_fixture\"])\n def flavor(self, request, testdir, monkeypatch):\n monkeypatch.setenv(\"PYTEST_FIXTURE_FLAVOR\", request.param)\n testdir.makepyfile(\n test_context=\"\"\"\n import os\n import pytest\n import warnings\n VAR = \"PYTEST_FIXTURE_FLAVOR\"\n if VAR not in os.environ:\n warnings.warn(\"PYTEST_FIXTURE_FLAVOR was not set, assuming fixture\")\n fixture = pytest.fixture\n else:\n fixture = getattr(pytest, os.environ[VAR])\n \"\"\"\n )"},{"col":4,"comment":"null","endLoc":707,"header":"def pytest_cmdline_parse(self, pluginmanager, args)","id":2704,"name":"pytest_cmdline_parse","nodeType":"Function","startLoc":685,"text":"def pytest_cmdline_parse(self, pluginmanager, args):\n try:\n self.parse(args)\n except UsageError:\n\n # Handle --version and --help here in a minimal fashion.\n # This gets done via helpconfig normally, but its\n # pytest_cmdline_main is not called in case of errors.\n if getattr(self.option, \"version\", False) or \"--version\" in args:\n from _pytest.helpconfig import showversion\n\n showversion(self)\n elif (\n getattr(self.option, \"help\", False) or \"--help\" in args or \"-h\" in args\n ):\n self._parser._getparser().print_help()\n sys.stdout.write(\n \"\\nNOTE: displaying only minimal help due to UsageError.\\n\\n\"\n )\n\n raise\n\n return self"},{"col":0,"comment":"null","endLoc":130,"header":"def showversion(config)","id":2705,"name":"showversion","nodeType":"Function","startLoc":122,"text":"def showversion(config):\n p = py.path.local(pytest.__file__)\n sys.stderr.write(\n \"This is pytest version %s, imported from %s\\n\" % (pytest.__version__, p)\n )\n plugininfo = getpluginversioninfo(config)\n if plugininfo:\n for line in plugininfo:\n sys.stderr.write(line + \"\\n\")"},{"col":4,"comment":"null","endLoc":1013,"header":"def copy(self) -> list[_T]","id":2706,"name":"copy","nodeType":"Function","startLoc":1013,"text":"def copy(self) -> list[_T]: ..."},{"col":4,"comment":"null","endLoc":1020,"header":"def count(self, __value: _T) -> int","id":2707,"name":"count","nodeType":"Function","startLoc":1020,"text":"def count(self, __value: _T) -> int: ..."},{"col":4,"comment":"null","endLoc":1032,"header":"def __len__(self) -> int","id":2708,"name":"__len__","nodeType":"Function","startLoc":1032,"text":"def __len__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":1033,"header":"def __iter__(self) -> Iterator[_T]","id":2709,"name":"__iter__","nodeType":"Function","startLoc":1033,"text":"def __iter__(self) -> Iterator[_T]: ..."},{"col":4,"comment":"null","endLoc":1036,"header":"@overload\n def __getitem__(self, __i: SupportsIndex) -> _T","id":2710,"name":"__getitem__","nodeType":"Function","startLoc":1035,"text":"@overload\n def __getitem__(self, __i: SupportsIndex) -> _T: ..."},{"col":4,"comment":"null","endLoc":1038,"header":"@overload\n def __getitem__(self, __s: slice) -> list[_T]","id":2711,"name":"__getitem__","nodeType":"Function","startLoc":1037,"text":"@overload\n def __getitem__(self, __s: slice) -> list[_T]: ..."},{"col":4,"comment":"null","endLoc":1040,"header":"@overload\n def __setitem__(self, __key: SupportsIndex, __value: _T) -> None","id":2712,"name":"__setitem__","nodeType":"Function","startLoc":1039,"text":"@overload\n def __setitem__(self, __key: SupportsIndex, __value: _T) -> None: ..."},{"col":4,"comment":"null","endLoc":1042,"header":"@overload\n def __setitem__(self, __key: slice, __value: Iterable[_T]) -> None","id":2713,"name":"__setitem__","nodeType":"Function","startLoc":1041,"text":"@overload\n def __setitem__(self, __key: slice, __value: Iterable[_T]) -> None: ..."},{"col":4,"comment":"null","endLoc":1043,"header":"def __delitem__(self, __key: SupportsIndex | slice) -> None","id":2714,"name":"__delitem__","nodeType":"Function","startLoc":1043,"text":"def __delitem__(self, __key: SupportsIndex | slice) -> None: ..."},{"col":4,"comment":"null","endLoc":1046,"header":"@overload\n def __add__(self, __value: list[_T]) -> list[_T]","id":2715,"name":"__add__","nodeType":"Function","startLoc":1045,"text":"@overload\n def __add__(self, __value: list[_T]) -> list[_T]: ..."},{"col":4,"comment":"null","endLoc":1048,"header":"@overload\n def __add__(self, __value: list[_S]) -> list[_S | _T]","id":2716,"name":"__add__","nodeType":"Function","startLoc":1047,"text":"@overload\n def __add__(self, __value: list[_S]) -> list[_S | _T]: ..."},{"col":4,"comment":"null","endLoc":1049,"header":"def __iadd__(self, __value: Iterable[_T]) -> Self","id":2717,"name":"__iadd__","nodeType":"Function","startLoc":1049,"text":"def __iadd__(self, __value: Iterable[_T]) -> Self: ... # type: ignore[misc]"},{"col":4,"comment":"null","endLoc":1050,"header":"def __mul__(self, __value: SupportsIndex) -> list[_T]","id":2718,"name":"__mul__","nodeType":"Function","startLoc":1050,"text":"def __mul__(self, __value: SupportsIndex) -> list[_T]: ..."},{"col":4,"comment":"null","endLoc":1051,"header":"def __rmul__(self, __value: SupportsIndex) -> list[_T]","id":2719,"name":"__rmul__","nodeType":"Function","startLoc":1051,"text":"def __rmul__(self, __value: SupportsIndex) -> list[_T]: ..."},{"col":4,"comment":"null","endLoc":1052,"header":"def __imul__(self, __value: SupportsIndex) -> Self","id":2720,"name":"__imul__","nodeType":"Function","startLoc":1052,"text":"def __imul__(self, __value: SupportsIndex) -> Self: ..."},{"col":4,"comment":"null","endLoc":1053,"header":"def __contains__(self, __key: object) -> bool","id":2721,"name":"__contains__","nodeType":"Function","startLoc":1053,"text":"def __contains__(self, __key: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":1054,"header":"def __reversed__(self) -> Iterator[_T]","id":2722,"name":"__reversed__","nodeType":"Function","startLoc":1054,"text":"def __reversed__(self) -> Iterator[_T]: ..."},{"col":4,"comment":"null","endLoc":1055,"header":"def __gt__(self, __value: list[_T]) -> bool","id":2723,"name":"__gt__","nodeType":"Function","startLoc":1055,"text":"def __gt__(self, __value: list[_T]) -> bool: ..."},{"col":4,"comment":"null","endLoc":1056,"header":"def __ge__(self, __value: list[_T]) -> bool","id":2724,"name":"__ge__","nodeType":"Function","startLoc":1056,"text":"def __ge__(self, __value: list[_T]) -> bool: ..."},{"col":4,"comment":"null","endLoc":1057,"header":"def __lt__(self, __value: list[_T]) -> bool","id":2725,"name":"__lt__","nodeType":"Function","startLoc":1057,"text":"def __lt__(self, __value: list[_T]) -> bool: ..."},{"col":4,"comment":"null","endLoc":1058,"header":"def __le__(self, __value: list[_T]) -> bool","id":2726,"name":"__le__","nodeType":"Function","startLoc":1058,"text":"def __le__(self, __value: list[_T]) -> bool: ..."},{"col":4,"comment":"null","endLoc":1059,"header":"def __eq__(self, __value: object) -> bool","id":2727,"name":"__eq__","nodeType":"Function","startLoc":1059,"text":"def __eq__(self, __value: object) -> bool: ..."},{"col":8,"comment":"null","endLoc":1061,"header":"def __class_getitem__(cls, __item: Any) -> GenericAlias","id":2728,"name":"__class_getitem__","nodeType":"Function","startLoc":1061,"text":"def __class_getitem__(cls, __item: Any) -> GenericAlias: ..."},{"attributeType":"None","col":4,"comment":"null","endLoc":1034,"id":2729,"name":"__hash__","nodeType":"Attribute","startLoc":1034,"text":"__hash__"},{"col":0,"comment":"null","endLoc":226,"header":"def getpluginversioninfo(config)","id":2730,"name":"getpluginversioninfo","nodeType":"Function","startLoc":217,"text":"def getpluginversioninfo(config):\n lines = []\n plugininfo = config.pluginmanager.list_plugin_distinfo()\n if plugininfo:\n lines.append(\"setuptools registered plugins:\")\n for plugin, dist in plugininfo:\n loc = getattr(plugin, \"__file__\", repr(plugin))\n content = \"%s-%s at %s\" % (dist.project_name, dist.version, loc)\n lines.append(\" \" + content)\n return lines"},{"col":4,"comment":" return a Traceback instance wrapping part of this Traceback\n\n by provding any combination of path, lineno and firstlineno, the\n first frame to start the to-be-returned traceback is determined\n\n this allows cutting the first part of a Traceback instance e.g.\n for formatting reasons (removing some uninteresting bits that deal\n with handling of the exception/traceback)\n ","endLoc":324,"header":"def cut(self, path=None, lineno=None, firstlineno=None, excludepath=None)","id":2731,"name":"cut","nodeType":"Function","startLoc":300,"text":"def cut(self, path=None, lineno=None, firstlineno=None, excludepath=None):\n \"\"\" return a Traceback instance wrapping part of this Traceback\n\n by provding any combination of path, lineno and firstlineno, the\n first frame to start the to-be-returned traceback is determined\n\n this allows cutting the first part of a Traceback instance e.g.\n for formatting reasons (removing some uninteresting bits that deal\n with handling of the exception/traceback)\n \"\"\"\n for x in self:\n code = x.frame.code\n codepath = code.path\n if (\n (path is None or codepath == path)\n and (\n excludepath is None\n or not hasattr(codepath, \"relto\")\n or not codepath.relto(excludepath)\n )\n and (lineno is None or x.lineno == lineno)\n and (firstlineno is None or x.frame.code.firstlineno == firstlineno)\n ):\n return Traceback(x._rawentry, self._excinfo)\n return self"},{"col":4,"comment":"null","endLoc":452,"header":"def restore(self)","id":2732,"name":"restore","nodeType":"Function","startLoc":446,"text":"def restore(self):\n if self.__preserve:\n self.__saved.update(\n (k, m) for k, m in sys.modules.items() if self.__preserve(k)\n )\n sys.modules.clear()\n sys.modules.update(self.__saved)"},{"col":4,"comment":"null","endLoc":1088,"header":"def items(self) -> dict_items[_KT, _VT]","id":2733,"name":"items","nodeType":"Function","startLoc":1088,"text":"def items(self) -> dict_items[_KT, _VT]: ..."},{"col":0,"comment":"null","endLoc":17,"header":"def test_bar()","id":2734,"name":"test_bar","nodeType":"Function","startLoc":16,"text":"def test_bar():\n func()"},{"col":4,"comment":"null","endLoc":330,"header":"def __getitem__(self, key)","id":2735,"name":"__getitem__","nodeType":"Function","startLoc":326,"text":"def __getitem__(self, key):\n val = super(Traceback, self).__getitem__(key)\n if isinstance(key, type(slice(0))):\n val = self.__class__(val)\n return val"},{"fileName":"test_conftest.py","filePath":"testing","id":2736,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport textwrap\n\nimport py\n\nimport pytest\nfrom _pytest.config import PytestPluginManager\nfrom _pytest.main import EXIT_NOTESTSCOLLECTED\nfrom _pytest.main import EXIT_OK\nfrom _pytest.main import EXIT_USAGEERROR\n\n\ndef ConftestWithSetinitial(path):\n conftest = PytestPluginManager()\n conftest_setinitial(conftest, [path])\n return conftest\n\n\ndef conftest_setinitial(conftest, args, confcutdir=None):\n class Namespace(object):\n def __init__(self):\n self.file_or_dir = args\n self.confcutdir = str(confcutdir)\n self.noconftest = False\n self.pyargs = False\n\n conftest._set_initial_conftests(Namespace())\n\n\n@pytest.mark.usefixtures(\"_sys_snapshot\")\nclass TestConftestValueAccessGlobal(object):\n @pytest.fixture(scope=\"module\", params=[\"global\", \"inpackage\"])\n def basedir(self, request, tmpdir_factory):\n tmpdir = tmpdir_factory.mktemp(\"basedir\", numbered=True)\n tmpdir.ensure(\"adir/conftest.py\").write(\"a=1 ; Directory = 3\")\n tmpdir.ensure(\"adir/b/conftest.py\").write(\"b=2 ; a = 1.5\")\n if request.param == \"inpackage\":\n tmpdir.ensure(\"adir/__init__.py\")\n tmpdir.ensure(\"adir/b/__init__.py\")\n\n yield tmpdir\n\n def test_basic_init(self, basedir):\n conftest = PytestPluginManager()\n p = basedir.join(\"adir\")\n assert conftest._rget_with_confmod(\"a\", p)[1] == 1\n\n def test_immediate_initialiation_and_incremental_are_the_same(self, basedir):\n conftest = PytestPluginManager()\n assert not len(conftest._dirpath2confmods)\n conftest._getconftestmodules(basedir)\n snap1 = len(conftest._dirpath2confmods)\n assert snap1 == 1\n conftest._getconftestmodules(basedir.join(\"adir\"))\n assert len(conftest._dirpath2confmods) == snap1 + 1\n conftest._getconftestmodules(basedir.join(\"b\"))\n assert len(conftest._dirpath2confmods) == snap1 + 2\n\n def test_value_access_not_existing(self, basedir):\n conftest = ConftestWithSetinitial(basedir)\n with pytest.raises(KeyError):\n conftest._rget_with_confmod(\"a\", basedir)\n\n def test_value_access_by_path(self, basedir):\n conftest = ConftestWithSetinitial(basedir)\n adir = basedir.join(\"adir\")\n assert conftest._rget_with_confmod(\"a\", adir)[1] == 1\n assert conftest._rget_with_confmod(\"a\", adir.join(\"b\"))[1] == 1.5\n\n def test_value_access_with_confmod(self, basedir):\n startdir = basedir.join(\"adir\", \"b\")\n startdir.ensure(\"xx\", dir=True)\n conftest = ConftestWithSetinitial(startdir)\n mod, value = conftest._rget_with_confmod(\"a\", startdir)\n assert value == 1.5\n path = py.path.local(mod.__file__)\n assert path.dirpath() == basedir.join(\"adir\", \"b\")\n assert path.purebasename.startswith(\"conftest\")\n\n\ndef test_conftest_in_nonpkg_with_init(tmpdir, _sys_snapshot):\n tmpdir.ensure(\"adir-1.0/conftest.py\").write(\"a=1 ; Directory = 3\")\n tmpdir.ensure(\"adir-1.0/b/conftest.py\").write(\"b=2 ; a = 1.5\")\n tmpdir.ensure(\"adir-1.0/b/__init__.py\")\n tmpdir.ensure(\"adir-1.0/__init__.py\")\n ConftestWithSetinitial(tmpdir.join(\"adir-1.0\", \"b\"))\n\n\ndef test_doubledash_considered(testdir):\n conf = testdir.mkdir(\"--option\")\n conf.ensure(\"conftest.py\")\n conftest = PytestPluginManager()\n conftest_setinitial(conftest, [conf.basename, conf.basename])\n values = conftest._getconftestmodules(conf)\n assert len(values) == 1\n\n\ndef test_issue151_load_all_conftests(testdir):\n names = \"code proj src\".split()\n for name in names:\n p = testdir.mkdir(name)\n p.ensure(\"conftest.py\")\n\n conftest = PytestPluginManager()\n conftest_setinitial(conftest, names)\n d = list(conftest._conftestpath2mod.values())\n assert len(d) == len(names)\n\n\ndef test_conftest_global_import(testdir):\n testdir.makeconftest(\"x=3\")\n p = testdir.makepyfile(\n \"\"\"\n import py, pytest\n from _pytest.config import PytestPluginManager\n conf = PytestPluginManager()\n mod = conf._importconftest(py.path.local(\"conftest.py\"))\n assert mod.x == 3\n import conftest\n assert conftest is mod, (conftest, mod)\n subconf = py.path.local().ensure(\"sub\", \"conftest.py\")\n subconf.write(\"y=4\")\n mod2 = conf._importconftest(subconf)\n assert mod != mod2\n assert mod2.y == 4\n import conftest\n assert conftest is mod2, (conftest, mod)\n \"\"\"\n )\n res = testdir.runpython(p)\n assert res.ret == 0\n\n\ndef test_conftestcutdir(testdir):\n conf = testdir.makeconftest(\"\")\n p = testdir.mkdir(\"x\")\n conftest = PytestPluginManager()\n conftest_setinitial(conftest, [testdir.tmpdir], confcutdir=p)\n values = conftest._getconftestmodules(p)\n assert len(values) == 0\n values = conftest._getconftestmodules(conf.dirpath())\n assert len(values) == 0\n assert conf not in conftest._conftestpath2mod\n # but we can still import a conftest directly\n conftest._importconftest(conf)\n values = conftest._getconftestmodules(conf.dirpath())\n assert values[0].__file__.startswith(str(conf))\n # and all sub paths get updated properly\n values = conftest._getconftestmodules(p)\n assert len(values) == 1\n assert values[0].__file__.startswith(str(conf))\n\n\ndef test_conftestcutdir_inplace_considered(testdir):\n conf = testdir.makeconftest(\"\")\n conftest = PytestPluginManager()\n conftest_setinitial(conftest, [conf.dirpath()], confcutdir=conf.dirpath())\n values = conftest._getconftestmodules(conf.dirpath())\n assert len(values) == 1\n assert values[0].__file__.startswith(str(conf))\n\n\n@pytest.mark.parametrize(\"name\", \"test tests whatever .dotdir\".split())\ndef test_setinitial_conftest_subdirs(testdir, name):\n sub = testdir.mkdir(name)\n subconftest = sub.ensure(\"conftest.py\")\n conftest = PytestPluginManager()\n conftest_setinitial(conftest, [sub.dirpath()], confcutdir=testdir.tmpdir)\n if name not in (\"whatever\", \".dotdir\"):\n assert subconftest in conftest._conftestpath2mod\n assert len(conftest._conftestpath2mod) == 1\n else:\n assert subconftest not in conftest._conftestpath2mod\n assert len(conftest._conftestpath2mod) == 0\n\n\ndef test_conftest_confcutdir(testdir):\n testdir.makeconftest(\"assert 0\")\n x = testdir.mkdir(\"x\")\n x.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def pytest_addoption(parser):\n parser.addoption(\"--xyz\", action=\"store_true\")\n \"\"\"\n )\n )\n result = testdir.runpytest(\"-h\", \"--confcutdir=%s\" % x, x)\n result.stdout.fnmatch_lines([\"*--xyz*\"])\n assert \"warning: could not load initial\" not in result.stdout.str()\n\n\n@pytest.mark.skipif(\n not hasattr(py.path.local, \"mksymlinkto\"),\n reason=\"symlink not available on this platform\",\n)\ndef test_conftest_symlink(testdir):\n \"\"\"Ensure that conftest.py is used for resolved symlinks.\"\"\"\n real = testdir.tmpdir.mkdir(\"real\")\n realtests = real.mkdir(\"app\").mkdir(\"tests\")\n testdir.tmpdir.join(\"symlinktests\").mksymlinkto(realtests)\n testdir.tmpdir.join(\"symlink\").mksymlinkto(real)\n testdir.makepyfile(\n **{\n \"real/app/tests/test_foo.py\": \"def test1(fixture): pass\",\n \"real/conftest.py\": textwrap.dedent(\n \"\"\"\n import pytest\n\n print(\"conftest_loaded\")\n\n @pytest.fixture\n def fixture():\n print(\"fixture_used\")\n \"\"\"\n ),\n }\n )\n result = testdir.runpytest(\"-vs\", \"symlinktests\")\n result.stdout.fnmatch_lines(\n [\n \"*conftest_loaded*\",\n \"real/app/tests/test_foo.py::test1 fixture_used\",\n \"PASSED\",\n ]\n )\n assert result.ret == EXIT_OK\n\n # Should not cause \"ValueError: Plugin already registered\" (#4174).\n result = testdir.runpytest(\"-vs\", \"symlink\")\n assert result.ret == EXIT_OK\n\n realtests.ensure(\"__init__.py\")\n result = testdir.runpytest(\"-vs\", \"symlinktests/test_foo.py::test1\")\n result.stdout.fnmatch_lines(\n [\n \"*conftest_loaded*\",\n \"real/app/tests/test_foo.py::test1 fixture_used\",\n \"PASSED\",\n ]\n )\n assert result.ret == EXIT_OK\n\n\n@pytest.mark.skipif(\n not hasattr(py.path.local, \"mksymlinkto\"),\n reason=\"symlink not available on this platform\",\n)\ndef test_conftest_symlink_files(testdir):\n \"\"\"Check conftest.py loading when running in directory with symlinks.\"\"\"\n real = testdir.tmpdir.mkdir(\"real\")\n source = {\n \"app/test_foo.py\": \"def test1(fixture): pass\",\n \"app/__init__.py\": \"\",\n \"app/conftest.py\": textwrap.dedent(\n \"\"\"\n import pytest\n\n print(\"conftest_loaded\")\n\n @pytest.fixture\n def fixture():\n print(\"fixture_used\")\n \"\"\"\n ),\n }\n testdir.makepyfile(**{\"real/%s\" % k: v for k, v in source.items()})\n\n # Create a build directory that contains symlinks to actual files\n # but doesn't symlink actual directories.\n build = testdir.tmpdir.mkdir(\"build\")\n build.mkdir(\"app\")\n for f in source:\n build.join(f).mksymlinkto(real.join(f))\n build.chdir()\n result = testdir.runpytest(\"-vs\", \"app/test_foo.py\")\n result.stdout.fnmatch_lines([\"*conftest_loaded*\", \"PASSED\"])\n assert result.ret == EXIT_OK\n\n\ndef test_no_conftest(testdir):\n testdir.makeconftest(\"assert 0\")\n result = testdir.runpytest(\"--noconftest\")\n assert result.ret == EXIT_NOTESTSCOLLECTED\n\n result = testdir.runpytest()\n assert result.ret == EXIT_USAGEERROR\n\n\ndef test_conftest_existing_resultlog(testdir):\n x = testdir.mkdir(\"tests\")\n x.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def pytest_addoption(parser):\n parser.addoption(\"--xyz\", action=\"store_true\")\n \"\"\"\n )\n )\n testdir.makefile(ext=\".log\", result=\"\") # Writes result.log\n result = testdir.runpytest(\"-h\", \"--resultlog\", \"result.log\")\n result.stdout.fnmatch_lines([\"*--xyz*\"])\n\n\ndef test_conftest_existing_junitxml(testdir):\n x = testdir.mkdir(\"tests\")\n x.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def pytest_addoption(parser):\n parser.addoption(\"--xyz\", action=\"store_true\")\n \"\"\"\n )\n )\n testdir.makefile(ext=\".xml\", junit=\"\") # Writes junit.xml\n result = testdir.runpytest(\"-h\", \"--junitxml\", \"junit.xml\")\n result.stdout.fnmatch_lines([\"*--xyz*\"])\n\n\ndef test_conftest_import_order(testdir, monkeypatch):\n ct1 = testdir.makeconftest(\"\")\n sub = testdir.mkdir(\"sub\")\n ct2 = sub.join(\"conftest.py\")\n ct2.write(\"\")\n\n def impct(p):\n return p\n\n conftest = PytestPluginManager()\n conftest._confcutdir = testdir.tmpdir\n monkeypatch.setattr(conftest, \"_importconftest\", impct)\n assert conftest._getconftestmodules(sub) == [ct1, ct2]\n\n\ndef test_fixture_dependency(testdir, monkeypatch):\n ct1 = testdir.makeconftest(\"\")\n ct1 = testdir.makepyfile(\"__init__.py\")\n ct1.write(\"\")\n sub = testdir.mkdir(\"sub\")\n sub.join(\"__init__.py\").write(\"\")\n sub.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n\n @pytest.fixture\n def not_needed():\n assert False, \"Should not be called!\"\n\n @pytest.fixture\n def foo():\n assert False, \"Should not be called!\"\n\n @pytest.fixture\n def bar(foo):\n return 'bar'\n \"\"\"\n )\n )\n subsub = sub.mkdir(\"subsub\")\n subsub.join(\"__init__.py\").write(\"\")\n subsub.join(\"test_bar.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n\n @pytest.fixture\n def bar():\n return 'sub bar'\n\n def test_event_fixture(bar):\n assert bar == 'sub bar'\n \"\"\"\n )\n )\n result = testdir.runpytest(\"sub\")\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_conftest_found_with_double_dash(testdir):\n sub = testdir.mkdir(\"sub\")\n sub.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def pytest_addoption(parser):\n parser.addoption(\"--hello-world\", action=\"store_true\")\n \"\"\"\n )\n )\n p = sub.join(\"test_hello.py\")\n p.write(\"def test_hello(): pass\")\n result = testdir.runpytest(str(p) + \"::test_hello\", \"-h\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *--hello-world*\n \"\"\"\n )\n\n\nclass TestConftestVisibility(object):\n def _setup_tree(self, testdir): # for issue616\n # example mostly taken from:\n # https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html\n runner = testdir.mkdir(\"empty\")\n package = testdir.mkdir(\"package\")\n\n package.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def fxtr():\n return \"from-package\"\n \"\"\"\n )\n )\n package.join(\"test_pkgroot.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_pkgroot(fxtr):\n assert fxtr == \"from-package\"\n \"\"\"\n )\n )\n\n swc = package.mkdir(\"swc\")\n swc.join(\"__init__.py\").ensure()\n swc.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def fxtr():\n return \"from-swc\"\n \"\"\"\n )\n )\n swc.join(\"test_with_conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_with_conftest(fxtr):\n assert fxtr == \"from-swc\"\n \"\"\"\n )\n )\n\n snc = package.mkdir(\"snc\")\n snc.join(\"__init__.py\").ensure()\n snc.join(\"test_no_conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_no_conftest(fxtr):\n assert fxtr == \"from-package\" # No local conftest.py, so should\n # use value from parent dir's\n \"\"\"\n )\n )\n print(\"created directory structure:\")\n for x in testdir.tmpdir.visit():\n print(\" \" + x.relto(testdir.tmpdir))\n\n return {\"runner\": runner, \"package\": package, \"swc\": swc, \"snc\": snc}\n\n # N.B.: \"swc\" stands for \"subdir with conftest.py\"\n # \"snc\" stands for \"subdir no [i.e. without] conftest.py\"\n @pytest.mark.parametrize(\n \"chdir,testarg,expect_ntests_passed\",\n [\n # Effective target: package/..\n (\"runner\", \"..\", 3),\n (\"package\", \"..\", 3),\n (\"swc\", \"../..\", 3),\n (\"snc\", \"../..\", 3),\n # Effective target: package\n (\"runner\", \"../package\", 3),\n (\"package\", \".\", 3),\n (\"swc\", \"..\", 3),\n (\"snc\", \"..\", 3),\n # Effective target: package/swc\n (\"runner\", \"../package/swc\", 1),\n (\"package\", \"./swc\", 1),\n (\"swc\", \".\", 1),\n (\"snc\", \"../swc\", 1),\n # Effective target: package/snc\n (\"runner\", \"../package/snc\", 1),\n (\"package\", \"./snc\", 1),\n (\"swc\", \"../snc\", 1),\n (\"snc\", \".\", 1),\n ],\n )\n def test_parsefactories_relative_node_ids(\n self, testdir, chdir, testarg, expect_ntests_passed\n ):\n \"\"\"#616\"\"\"\n dirs = self._setup_tree(testdir)\n print(\"pytest run in cwd: %s\" % (dirs[chdir].relto(testdir.tmpdir)))\n print(\"pytestarg : %s\" % (testarg))\n print(\"expected pass : %s\" % (expect_ntests_passed))\n with dirs[chdir].as_cwd():\n reprec = testdir.inline_run(testarg, \"-q\", \"--traceconfig\")\n reprec.assertoutcome(passed=expect_ntests_passed)\n\n\n@pytest.mark.parametrize(\n \"confcutdir,passed,error\", [(\".\", 2, 0), (\"src\", 1, 1), (None, 1, 1)]\n)\ndef test_search_conftest_up_to_inifile(testdir, confcutdir, passed, error):\n \"\"\"Test that conftest files are detected only up to an ini file, unless\n an explicit --confcutdir option is given.\n \"\"\"\n root = testdir.tmpdir\n src = root.join(\"src\").ensure(dir=1)\n src.join(\"pytest.ini\").write(\"[pytest]\")\n src.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def fix1(): pass\n \"\"\"\n )\n )\n src.join(\"test_foo.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_1(fix1):\n pass\n def test_2(out_of_reach):\n pass\n \"\"\"\n )\n )\n root.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def out_of_reach(): pass\n \"\"\"\n )\n )\n\n args = [str(src)]\n if confcutdir:\n args = [\"--confcutdir=%s\" % root.join(confcutdir)]\n result = testdir.runpytest(*args)\n match = \"\"\n if passed:\n match += \"*%d passed*\" % passed\n if error:\n match += \"*%d error*\" % error\n result.stdout.fnmatch_lines(match)\n\n\ndef test_issue1073_conftest_special_objects(testdir):\n testdir.makeconftest(\n \"\"\"\\\n class DontTouchMe(object):\n def __getattr__(self, x):\n raise Exception('cant touch me')\n\n x = DontTouchMe()\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\\\n def test_some():\n pass\n \"\"\"\n )\n res = testdir.runpytest()\n assert res.ret == 0\n\n\ndef test_conftest_exception_handling(testdir):\n testdir.makeconftest(\n \"\"\"\\\n raise ValueError()\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\\\n def test_some():\n pass\n \"\"\"\n )\n res = testdir.runpytest()\n assert res.ret == 4\n assert \"raise ValueError()\" in [line.strip() for line in res.errlines]\n\n\ndef test_hook_proxy(testdir):\n \"\"\"Session's gethookproxy() would cache conftests incorrectly (#2016).\n It was decided to remove the cache altogether.\n \"\"\"\n testdir.makepyfile(\n **{\n \"root/demo-0/test_foo1.py\": \"def test1(): pass\",\n \"root/demo-a/test_foo2.py\": \"def test1(): pass\",\n \"root/demo-a/conftest.py\": \"\"\"\\\n def pytest_ignore_collect(path, config):\n return True\n \"\"\",\n \"root/demo-b/test_foo3.py\": \"def test1(): pass\",\n \"root/demo-c/test_foo4.py\": \"def test1(): pass\",\n }\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"*test_foo1.py*\", \"*test_foo3.py*\", \"*test_foo4.py*\", \"*3 passed*\"]\n )\n\n\ndef test_required_option_help(testdir):\n testdir.makeconftest(\"assert 0\")\n x = testdir.mkdir(\"x\")\n x.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def pytest_addoption(parser):\n parser.addoption(\"--xyz\", action=\"store_true\", required=True)\n \"\"\"\n )\n )\n result = testdir.runpytest(\"-h\", x)\n assert \"argument --xyz is required\" not in result.stdout.str()\n assert \"general:\" in result.stdout.str()\n"},{"attributeType":"null","col":8,"comment":"null","endLoc":443,"id":2737,"name":"__preserve","nodeType":"Attribute","startLoc":443,"text":"self.__preserve"},{"attributeType":"null","col":8,"comment":"null","endLoc":444,"id":2738,"name":"__saved","nodeType":"Attribute","startLoc":444,"text":"self.__saved"},{"className":"SysPathsSnapshot","col":0,"comment":"null","endLoc":460,"id":2739,"nodeType":"Class","startLoc":455,"text":"class SysPathsSnapshot(object):\n def __init__(self):\n self.__saved = list(sys.path), list(sys.meta_path)\n\n def restore(self):\n sys.path[:], sys.meta_path[:] = self.__saved"},{"col":4,"comment":"null","endLoc":457,"header":"def __init__(self)","id":2740,"name":"__init__","nodeType":"Function","startLoc":456,"text":"def __init__(self):\n self.__saved = list(sys.path), list(sys.meta_path)"},{"attributeType":"null","col":0,"comment":"null","endLoc":33,"id":2741,"name":"EXIT_USAGEERROR","nodeType":"Attribute","startLoc":33,"text":"EXIT_USAGEERROR"},{"className":"TestConftestValueAccessGlobal","col":0,"comment":"null","endLoc":82,"id":2742,"nodeType":"Class","startLoc":34,"text":"@pytest.mark.usefixtures(\"_sys_snapshot\")\nclass TestConftestValueAccessGlobal(object):\n @pytest.fixture(scope=\"module\", params=[\"global\", \"inpackage\"])\n def basedir(self, request, tmpdir_factory):\n tmpdir = tmpdir_factory.mktemp(\"basedir\", numbered=True)\n tmpdir.ensure(\"adir/conftest.py\").write(\"a=1 ; Directory = 3\")\n tmpdir.ensure(\"adir/b/conftest.py\").write(\"b=2 ; a = 1.5\")\n if request.param == \"inpackage\":\n tmpdir.ensure(\"adir/__init__.py\")\n tmpdir.ensure(\"adir/b/__init__.py\")\n\n yield tmpdir\n\n def test_basic_init(self, basedir):\n conftest = PytestPluginManager()\n p = basedir.join(\"adir\")\n assert conftest._rget_with_confmod(\"a\", p)[1] == 1\n\n def test_immediate_initialiation_and_incremental_are_the_same(self, basedir):\n conftest = PytestPluginManager()\n assert not len(conftest._dirpath2confmods)\n conftest._getconftestmodules(basedir)\n snap1 = len(conftest._dirpath2confmods)\n assert snap1 == 1\n conftest._getconftestmodules(basedir.join(\"adir\"))\n assert len(conftest._dirpath2confmods) == snap1 + 1\n conftest._getconftestmodules(basedir.join(\"b\"))\n assert len(conftest._dirpath2confmods) == snap1 + 2\n\n def test_value_access_not_existing(self, basedir):\n conftest = ConftestWithSetinitial(basedir)\n with pytest.raises(KeyError):\n conftest._rget_with_confmod(\"a\", basedir)\n\n def test_value_access_by_path(self, basedir):\n conftest = ConftestWithSetinitial(basedir)\n adir = basedir.join(\"adir\")\n assert conftest._rget_with_confmod(\"a\", adir)[1] == 1\n assert conftest._rget_with_confmod(\"a\", adir.join(\"b\"))[1] == 1.5\n\n def test_value_access_with_confmod(self, basedir):\n startdir = basedir.join(\"adir\", \"b\")\n startdir.ensure(\"xx\", dir=True)\n conftest = ConftestWithSetinitial(startdir)\n mod, value = conftest._rget_with_confmod(\"a\", startdir)\n assert value == 1.5\n path = py.path.local(mod.__file__)\n assert path.dirpath() == basedir.join(\"adir\", \"b\")\n assert path.purebasename.startswith(\"conftest\")"},{"id":2743,"name":"release-3.0.3.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.0.3\n============\n\npytest 3.0.3 has just been released to PyPI.\n\nThis release fixes some regressions and bugs reported in the last version,\nbeing a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n* Florian Bruhin\n* Floris Bruynooghe\n* Huayi Zhang\n* Lev Maximov\n* Raquel Alegre\n* Ronny Pfannschmidt\n* Roy Williams\n* Tyler Goodlet\n* mbyt\n\nHappy testing,\nThe pytest Development Team\n"},{"id":2744,"name":"doc/en/_themes/flask/static","nodeType":"Package"},{"id":2745,"name":"flasky.css_t","nodeType":"TextFile","path":"doc/en/_themes/flask/static","text":"/*\n * flasky.css_t\n * ~~~~~~~~~~~~\n *\n * :copyright: Copyright 2010 by Armin Ronacher.\n * :license: Flask Design License, see LICENSE for details.\n */\n\n{% set page_width = '1020px' %}\n{% set sidebar_width = '220px' %}\n/* orange of logo is #d67c29 but we use black for links for now */\n{% set link_color = '#000' %}\n{% set link_hover_color = '#000' %}\n{% set base_font = 'sans-serif' %}\n{% set header_font = 'serif' %}\n\n@import url(\"basic.css\");\n\n/* -- page layout ----------------------------------------------------------- */\n\nbody {\n font-family: {{ base_font }};\n font-size: 17px;\n background-color: white;\n color: #000;\n margin: 0;\n padding: 0;\n}\n\ndiv.document {\n width: {{ page_width }};\n margin: 30px auto 0 auto;\n}\n\ndiv.documentwrapper {\n float: left;\n width: 100%;\n}\n\ndiv.bodywrapper {\n margin: 0 0 0 {{ sidebar_width }};\n}\n\ndiv.sphinxsidebar {\n width: {{ sidebar_width }};\n}\n\nhr {\n border: 0;\n border-top: 1px solid #B1B4B6;\n}\n\ndiv.body {\n background-color: #ffffff;\n color: #3E4349;\n padding: 0 30px 0 30px;\n}\n\nimg.floatingflask {\n padding: 0 0 10px 10px;\n float: right;\n}\n\ndiv.footer {\n width: {{ page_width }};\n margin: 20px auto 30px auto;\n font-size: 14px;\n color: #888;\n text-align: right;\n}\n\ndiv.footer a {\n color: #888;\n}\n\ndiv.related {\n display: none;\n}\n\ndiv.sphinxsidebar a {\n color: #444;\n text-decoration: none;\n border-bottom: 1px dotted #999;\n}\n\ndiv.sphinxsidebar a:hover {\n border-bottom: 1px solid #999;\n}\n\ndiv.sphinxsidebar {\n font-size: 14px;\n line-height: 1.5;\n}\n\ndiv.sphinxsidebarwrapper {\n padding: 18px 10px;\n}\n\ndiv.sphinxsidebarwrapper p.logo {\n padding: 0 0 20px 0;\n margin: 0;\n text-align: center;\n}\n\ndiv.sphinxsidebar h3,\ndiv.sphinxsidebar h4 {\n font-family: {{ header_font }};\n color: #444;\n font-size: 24px;\n font-weight: normal;\n margin: 0 0 5px 0;\n padding: 0;\n}\n\ndiv.sphinxsidebar h4 {\n font-size: 20px;\n}\n\ndiv.sphinxsidebar h3 a {\n color: #444;\n}\n\ndiv.sphinxsidebar p.logo a,\ndiv.sphinxsidebar h3 a,\ndiv.sphinxsidebar p.logo a:hover,\ndiv.sphinxsidebar h3 a:hover {\n border: none;\n}\n\ndiv.sphinxsidebar p {\n color: #555;\n margin: 10px 0;\n}\n\ndiv.sphinxsidebar ul {\n margin: 10px 0;\n padding: 0;\n color: #000;\n}\n\ndiv.sphinxsidebar input {\n border: 1px solid #ccc;\n font-family: {{ base_font }};\n font-size: 1em;\n}\n\n/* -- body styles ----------------------------------------------------------- */\n\na {\n color: {{ link_color }};\n text-decoration: underline;\n}\n\na:hover {\n color: {{ link_hover_color }};\n text-decoration: underline;\n}\n\na.reference.internal em {\n font-style: normal;\n}\n\ndiv.body h1,\ndiv.body h2,\ndiv.body h3,\ndiv.body h4,\ndiv.body h5,\ndiv.body h6 {\n font-family: {{ header_font }};\n font-weight: normal;\n margin: 30px 0px 10px 0px;\n padding: 0;\n}\n\n{% if theme_index_logo %}\ndiv.indexwrapper h1 {\n text-indent: -999999px;\n background: url({{ theme_index_logo }}) no-repeat center center;\n height: {{ theme_index_logo_height }};\n}\n{% else %}\ndiv.indexwrapper div.body h1 {\n font-size: 200%;\n}\n{% endif %}\ndiv.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; }\ndiv.body h2 { font-size: 180%; }\ndiv.body h3 { font-size: 150%; }\ndiv.body h4 { font-size: 130%; }\ndiv.body h5 { font-size: 100%; }\ndiv.body h6 { font-size: 100%; }\n\na.headerlink {\n color: #ddd;\n padding: 0 4px;\n text-decoration: none;\n}\n\na.headerlink:hover {\n color: #444;\n background: #eaeaea;\n}\n\ndiv.body p, div.body dd, div.body li {\n line-height: 1.4em;\n}\n\ndiv.admonition {\n background: #fafafa;\n margin: 20px -30px;\n padding: 10px 30px;\n border-top: 1px solid #ccc;\n border-bottom: 1px solid #ccc;\n}\n\ndiv.admonition tt.xref, div.admonition a tt {\n border-bottom: 1px solid #fafafa;\n}\n\ndd div.admonition {\n margin-left: -60px;\n padding-left: 60px;\n}\n\ndiv.admonition p.admonition-title {\n font-family: {{ header_font }};\n font-weight: normal;\n font-size: 24px;\n margin: 0 0 10px 0;\n padding: 0;\n line-height: 1;\n}\n\ndiv.admonition p.last {\n margin-bottom: 0;\n}\n\ndiv.highlight {\n background-color: white;\n}\n\ndt:target, .highlight {\n background: #FAF3E8;\n}\n\ndiv.note {\n background-color: #eee;\n border: 1px solid #ccc;\n}\n\ndiv.seealso {\n background-color: #ffc;\n border: 1px solid #ff6;\n}\n\ndiv.topic {\n background-color: #eee;\n}\n\np.admonition-title {\n display: inline;\n}\n\np.admonition-title:after {\n content: \":\";\n}\n\npre, tt, code {\n font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace;\n font-size: 0.9em;\n background: #eee;\n}\n\nimg.screenshot {\n}\n\ntt.descname, tt.descclassname {\n font-size: 0.95em;\n}\n\ntt.descname {\n padding-right: 0.08em;\n}\n\nimg.screenshot {\n -moz-box-shadow: 2px 2px 4px #eee;\n -webkit-box-shadow: 2px 2px 4px #eee;\n box-shadow: 2px 2px 4px #eee;\n}\n\ntable.docutils {\n border: 1px solid #888;\n -moz-box-shadow: 2px 2px 4px #eee;\n -webkit-box-shadow: 2px 2px 4px #eee;\n box-shadow: 2px 2px 4px #eee;\n}\n\ntable.docutils td, table.docutils th {\n border: 1px solid #888;\n padding: 0.25em 0.7em;\n}\n\ntable.field-list, table.footnote {\n border: none;\n -moz-box-shadow: none;\n -webkit-box-shadow: none;\n box-shadow: none;\n}\n\ntable.footnote {\n margin: 15px 0;\n width: 100%;\n border: 1px solid #eee;\n background: #fdfdfd;\n font-size: 0.9em;\n}\n\ntable.footnote + table.footnote {\n margin-top: -15px;\n border-top: none;\n}\n\ntable.field-list th {\n padding: 0 0.8em 0 0;\n}\n\ntable.field-list td {\n padding: 0;\n}\n\ntable.footnote td.label {\n width: 0px;\n padding: 0.3em 0 0.3em 0.5em;\n}\n\ntable.footnote td {\n padding: 0.3em 0.5em;\n}\n\ndl {\n margin: 0;\n padding: 0;\n}\n\ndl dd {\n margin-left: 30px;\n}\n\nblockquote {\n margin: 0 0 0 30px;\n padding: 0;\n}\n\nul, ol {\n margin: 10px 0 10px 30px;\n padding: 0;\n}\n\npre {\n background: #eee;\n padding: 7px 30px;\n margin: 15px -30px;\n line-height: 1.3em;\n}\n\ndl pre, blockquote pre, li pre {\n margin-left: -60px;\n padding-left: 60px;\n}\n\ndl dl pre {\n margin-left: -90px;\n padding-left: 90px;\n}\n\ntt {\n background-color: #ecf0f3;\n color: #222;\n /* padding: 1px 2px; */\n}\n\ntt.xref, a tt {\n background-color: #FBFBFB;\n border-bottom: 1px solid white;\n}\n\na.reference {\n text-decoration: none;\n border-bottom: 1px dotted {{ link_color }};\n}\n\na.reference:hover {\n border-bottom: 1px solid {{ link_hover_color }};\n}\n\na.footnote-reference {\n text-decoration: none;\n font-size: 0.7em;\n vertical-align: top;\n border-bottom: 1px dotted {{ link_color }};\n}\n\na.footnote-reference:hover {\n border-bottom: 1px solid {{ link_hover_color }};\n}\n\na:hover tt {\n background: #EEE;\n}\n\n\n@media screen and (max-width: 870px) {\n\n div.sphinxsidebar {\n display: none;\n }\n\n div.document {\n width: 100%;\n\n }\n\n div.documentwrapper {\n margin-left: 0;\n margin-top: 0;\n margin-right: 0;\n margin-bottom: 0;\n }\n\n div.bodywrapper {\n margin-top: 0;\n margin-right: 0;\n margin-bottom: 0;\n margin-left: 0;\n }\n\n ul {\n margin-left: 0;\n }\n\n .document {\n width: auto;\n }\n\n .footer {\n width: auto;\n }\n\n .bodywrapper {\n margin: 0;\n }\n\n .footer {\n width: auto;\n }\n\n .github {\n display: none;\n }\n\n\n\n}\n\n\n\n@media screen and (max-width: 875px) {\n\n body {\n margin: 0;\n padding: 20px 30px;\n }\n\n div.documentwrapper {\n float: none;\n background: white;\n }\n\n div.sphinxsidebar {\n display: block;\n float: none;\n width: 102.5%;\n margin: 50px -30px -20px -30px;\n padding: 10px 20px;\n background: #333;\n color: white;\n }\n\n div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p,\n div.sphinxsidebar h3 a, div.sphinxsidebar ul {\n color: white;\n }\n\n div.sphinxsidebar a {\n color: #aaa;\n }\n\n div.sphinxsidebar p.logo {\n display: none;\n }\n\n div.document {\n width: 100%;\n margin: 0;\n }\n\n div.related {\n display: block;\n margin: 0;\n padding: 10px 0 20px 0;\n }\n\n div.related ul,\n div.related ul li {\n margin: 0;\n padding: 0;\n }\n\n div.footer {\n display: none;\n }\n\n div.bodywrapper {\n margin: 0;\n }\n\n div.body {\n min-height: 0;\n padding: 0;\n }\n\n .rtd_doc_footer {\n display: none;\n }\n\n .document {\n width: auto;\n }\n\n .footer {\n width: auto;\n }\n\n .footer {\n width: auto;\n }\n\n .github {\n display: none;\n }\n}\n\n/* misc. */\n\n.revsys-inline {\n display: none!important;\n}\n"},{"col":4,"comment":"null","endLoc":45,"header":"@pytest.fixture(scope=\"module\", params=[\"global\", \"inpackage\"])\n def basedir(self, request, tmpdir_factory)","id":2746,"name":"basedir","nodeType":"Function","startLoc":36,"text":"@pytest.fixture(scope=\"module\", params=[\"global\", \"inpackage\"])\n def basedir(self, request, tmpdir_factory):\n tmpdir = tmpdir_factory.mktemp(\"basedir\", numbered=True)\n tmpdir.ensure(\"adir/conftest.py\").write(\"a=1 ; Directory = 3\")\n tmpdir.ensure(\"adir/b/conftest.py\").write(\"b=2 ; a = 1.5\")\n if request.param == \"inpackage\":\n tmpdir.ensure(\"adir/__init__.py\")\n tmpdir.ensure(\"adir/b/__init__.py\")\n\n yield tmpdir"},{"col":4,"comment":"null","endLoc":3366,"header":"def test_simple(self, testdir, flavor)","id":2747,"name":"test_simple","nodeType":"Function","startLoc":3339,"text":"def test_simple(self, testdir, flavor):\n testdir.makepyfile(\n \"\"\"\n from __future__ import print_function\n from test_context import fixture\n @fixture\n def arg1():\n print(\"setup\")\n yield 1\n print(\"teardown\")\n def test_1(arg1):\n print(\"test1\", arg1)\n def test_2(arg1):\n print(\"test2\", arg1)\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *setup*\n *test1 1*\n *teardown*\n *setup*\n *test2 1*\n *teardown*\n \"\"\"\n )"},{"col":4,"comment":"null","endLoc":3392,"header":"def test_scoped(self, testdir, flavor)","id":2748,"name":"test_scoped","nodeType":"Function","startLoc":3368,"text":"def test_scoped(self, testdir, flavor):\n testdir.makepyfile(\n \"\"\"\n from __future__ import print_function\n from test_context import fixture\n @fixture(scope=\"module\")\n def arg1():\n print(\"setup\")\n yield 1\n print(\"teardown\")\n def test_1(arg1):\n print(\"test1\", arg1)\n def test_2(arg1):\n print(\"test2\", arg1)\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *setup*\n *test1 1*\n *test2 1*\n *teardown*\n \"\"\"\n )"},{"col":4,"comment":"null","endLoc":3412,"header":"def test_setup_exception(self, testdir, flavor)","id":2749,"name":"test_setup_exception","nodeType":"Function","startLoc":3394,"text":"def test_setup_exception(self, testdir, flavor):\n testdir.makepyfile(\n \"\"\"\n from test_context import fixture\n @fixture(scope=\"module\")\n def arg1():\n pytest.fail(\"setup\")\n yield 1\n def test_1(arg1):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *pytest.fail*setup*\n *1 error*\n \"\"\"\n )"},{"fileName":"test_formatter.py","filePath":"testing/logging","id":2750,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport logging\n\nimport py.io\nimport six\n\nimport pytest\nfrom _pytest.logging import ColoredLevelFormatter\n\n\ndef test_coloredlogformatter():\n logfmt = \"%(filename)-25s %(lineno)4d %(levelname)-8s %(message)s\"\n\n record = logging.LogRecord(\n name=\"dummy\",\n level=logging.INFO,\n pathname=\"dummypath\",\n lineno=10,\n msg=\"Test Message\",\n args=(),\n exc_info=False,\n )\n\n class ColorConfig(object):\n class option(object):\n pass\n\n tw = py.io.TerminalWriter()\n tw.hasmarkup = True\n formatter = ColoredLevelFormatter(tw, logfmt)\n output = formatter.format(record)\n assert output == (\n \"dummypath 10 \\x1b[32mINFO \\x1b[0m Test Message\"\n )\n\n tw.hasmarkup = False\n formatter = ColoredLevelFormatter(tw, logfmt)\n output = formatter.format(record)\n assert output == (\"dummypath 10 INFO Test Message\")\n\n\n@pytest.mark.skipif(\n six.PY2, reason=\"Formatter classes don't support format styles in PY2\"\n)\ndef test_multiline_message():\n from _pytest.logging import PercentStyleMultiline\n\n logfmt = \"%(filename)-25s %(lineno)4d %(levelname)-8s %(message)s\"\n\n record = logging.LogRecord(\n name=\"dummy\",\n level=logging.INFO,\n pathname=\"dummypath\",\n lineno=10,\n msg=\"Test Message line1\\nline2\",\n args=(),\n exc_info=False,\n )\n # this is called by logging.Formatter.format\n record.message = record.getMessage()\n\n style = PercentStyleMultiline(logfmt)\n output = style.format(record)\n assert output == (\n \"dummypath 10 INFO Test Message line1\\n\"\n \" line2\"\n )\n"},{"col":4,"comment":"null","endLoc":3432,"header":"def test_teardown_exception(self, testdir, flavor)","id":2751,"name":"test_teardown_exception","nodeType":"Function","startLoc":3414,"text":"def test_teardown_exception(self, testdir, flavor):\n testdir.makepyfile(\n \"\"\"\n from test_context import fixture\n @fixture(scope=\"module\")\n def arg1():\n yield 1\n pytest.fail(\"teardown\")\n def test_1(arg1):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *pytest.fail*teardown*\n *1 passed*1 error*\n \"\"\"\n )"},{"className":"ColoredLevelFormatter","col":0,"comment":"\n Colorize the %(levelname)..s part of the log format passed to __init__.\n ","endLoc":77,"id":2752,"nodeType":"Class","startLoc":28,"text":"class ColoredLevelFormatter(logging.Formatter):\n \"\"\"\n Colorize the %(levelname)..s part of the log format passed to __init__.\n \"\"\"\n\n LOGLEVEL_COLOROPTS = {\n logging.CRITICAL: {\"red\"},\n logging.ERROR: {\"red\", \"bold\"},\n logging.WARNING: {\"yellow\"},\n logging.WARN: {\"yellow\"},\n logging.INFO: {\"green\"},\n logging.DEBUG: {\"purple\"},\n logging.NOTSET: set(),\n }\n LEVELNAME_FMT_REGEX = re.compile(r\"%\\(levelname\\)([+-]?\\d*s)\")\n\n def __init__(self, terminalwriter, *args, **kwargs):\n super(ColoredLevelFormatter, self).__init__(*args, **kwargs)\n if six.PY2:\n self._original_fmt = self._fmt\n else:\n self._original_fmt = self._style._fmt\n self._level_to_fmt_mapping = {}\n\n levelname_fmt_match = self.LEVELNAME_FMT_REGEX.search(self._fmt)\n if not levelname_fmt_match:\n return\n levelname_fmt = levelname_fmt_match.group()\n\n for level, color_opts in self.LOGLEVEL_COLOROPTS.items():\n formatted_levelname = levelname_fmt % {\n \"levelname\": logging.getLevelName(level)\n }\n\n # add ANSI escape sequences around the formatted levelname\n color_kwargs = {name: True for name in color_opts}\n colorized_formatted_levelname = terminalwriter.markup(\n formatted_levelname, **color_kwargs\n )\n self._level_to_fmt_mapping[level] = self.LEVELNAME_FMT_REGEX.sub(\n colorized_formatted_levelname, self._fmt\n )\n\n def format(self, record):\n fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt)\n if six.PY2:\n self._fmt = fmt\n else:\n self._style._fmt = fmt\n return super(ColoredLevelFormatter, self).format(record)"},{"col":4,"comment":"null","endLoc":3452,"header":"def test_yields_more_than_one(self, testdir, flavor)","id":2753,"name":"test_yields_more_than_one","nodeType":"Function","startLoc":3434,"text":"def test_yields_more_than_one(self, testdir, flavor):\n testdir.makepyfile(\n \"\"\"\n from test_context import fixture\n @fixture(scope=\"module\")\n def arg1():\n yield 1\n yield 2\n def test_1(arg1):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *fixture function*\n *test_yields*:2*\n \"\"\"\n )"},{"col":4,"comment":"null","endLoc":3466,"header":"def test_custom_name(self, testdir, flavor)","id":2754,"name":"test_custom_name","nodeType":"Function","startLoc":3454,"text":"def test_custom_name(self, testdir, flavor):\n testdir.makepyfile(\n \"\"\"\n from test_context import fixture\n @fixture(name='meow')\n def arg1():\n return 'mew'\n def test_1(meow):\n print(meow)\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines([\"*mew*\"])"},{"col":4,"comment":"null","endLoc":460,"header":"def restore(self)","id":2755,"name":"restore","nodeType":"Function","startLoc":459,"text":"def restore(self):\n sys.path[:], sys.meta_path[:] = self.__saved"},{"className":"TestParameterizedSubRequest","col":0,"comment":"null","endLoc":3599,"id":2756,"nodeType":"Class","startLoc":3469,"text":"class TestParameterizedSubRequest(object):\n def test_call_from_fixture(self, testdir):\n testdir.makepyfile(\n test_call_from_fixture=\"\"\"\n import pytest\n\n @pytest.fixture(params=[0, 1, 2])\n def fix_with_param(request):\n return request.param\n\n @pytest.fixture\n def get_named_fixture(request):\n return request.getfixturevalue('fix_with_param')\n\n def test_foo(request, get_named_fixture):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"The requested fixture has no parameter defined for test:\",\n \" test_call_from_fixture.py::test_foo\",\n \"Requested fixture 'fix_with_param' defined in:\",\n \"test_call_from_fixture.py:4\",\n \"Requested here:\",\n \"test_call_from_fixture.py:9\",\n \"*1 error in*\",\n ]\n )\n\n def test_call_from_test(self, testdir):\n testdir.makepyfile(\n test_call_from_test=\"\"\"\n import pytest\n\n @pytest.fixture(params=[0, 1, 2])\n def fix_with_param(request):\n return request.param\n\n def test_foo(request):\n request.getfixturevalue('fix_with_param')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"The requested fixture has no parameter defined for test:\",\n \" test_call_from_test.py::test_foo\",\n \"Requested fixture 'fix_with_param' defined in:\",\n \"test_call_from_test.py:4\",\n \"Requested here:\",\n \"test_call_from_test.py:8\",\n \"*1 failed*\",\n ]\n )\n\n def test_external_fixture(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[0, 1, 2])\n def fix_with_param(request):\n return request.param\n \"\"\"\n )\n\n testdir.makepyfile(\n test_external_fixture=\"\"\"\n def test_foo(request):\n request.getfixturevalue('fix_with_param')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"The requested fixture has no parameter defined for test:\",\n \" test_external_fixture.py::test_foo\",\n \"\",\n \"Requested fixture 'fix_with_param' defined in:\",\n \"conftest.py:4\",\n \"Requested here:\",\n \"test_external_fixture.py:2\",\n \"*1 failed*\",\n ]\n )\n\n def test_non_relative_path(self, testdir):\n tests_dir = testdir.mkdir(\"tests\")\n fixdir = testdir.mkdir(\"fixtures\")\n fixfile = fixdir.join(\"fix.py\")\n fixfile.write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n\n @pytest.fixture(params=[0, 1, 2])\n def fix_with_param(request):\n return request.param\n \"\"\"\n )\n )\n\n testfile = tests_dir.join(\"test_foos.py\")\n testfile.write(\n textwrap.dedent(\n \"\"\"\\\n from fix import fix_with_param\n\n def test_foo(request):\n request.getfixturevalue('fix_with_param')\n \"\"\"\n )\n )\n\n tests_dir.chdir()\n testdir.syspathinsert(fixdir)\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"The requested fixture has no parameter defined for test:\",\n \" test_foos.py::test_foo\",\n \"\",\n \"Requested fixture 'fix_with_param' defined in:\",\n \"*fix.py:4\",\n \"Requested here:\",\n \"test_foos.py:4\",\n \"*1 failed*\",\n ]\n )"},{"attributeType":"null","col":8,"comment":"null","endLoc":457,"id":2757,"name":"__saved","nodeType":"Attribute","startLoc":457,"text":"self.__saved"},{"col":4,"comment":"null","endLoc":3498,"header":"def test_call_from_fixture(self, testdir)","id":2758,"name":"test_call_from_fixture","nodeType":"Function","startLoc":3470,"text":"def test_call_from_fixture(self, testdir):\n testdir.makepyfile(\n test_call_from_fixture=\"\"\"\n import pytest\n\n @pytest.fixture(params=[0, 1, 2])\n def fix_with_param(request):\n return request.param\n\n @pytest.fixture\n def get_named_fixture(request):\n return request.getfixturevalue('fix_with_param')\n\n def test_foo(request, get_named_fixture):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"The requested fixture has no parameter defined for test:\",\n \" test_call_from_fixture.py::test_foo\",\n \"Requested fixture 'fix_with_param' defined in:\",\n \"test_call_from_fixture.py:4\",\n \"Requested here:\",\n \"test_call_from_fixture.py:9\",\n \"*1 error in*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":3524,"header":"def test_call_from_test(self, testdir)","id":2759,"name":"test_call_from_test","nodeType":"Function","startLoc":3500,"text":"def test_call_from_test(self, testdir):\n testdir.makepyfile(\n test_call_from_test=\"\"\"\n import pytest\n\n @pytest.fixture(params=[0, 1, 2])\n def fix_with_param(request):\n return request.param\n\n def test_foo(request):\n request.getfixturevalue('fix_with_param')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"The requested fixture has no parameter defined for test:\",\n \" test_call_from_test.py::test_foo\",\n \"Requested fixture 'fix_with_param' defined in:\",\n \"test_call_from_test.py:4\",\n \"Requested here:\",\n \"test_call_from_test.py:8\",\n \"*1 failed*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":3555,"header":"def test_external_fixture(self, testdir)","id":2760,"name":"test_external_fixture","nodeType":"Function","startLoc":3526,"text":"def test_external_fixture(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[0, 1, 2])\n def fix_with_param(request):\n return request.param\n \"\"\"\n )\n\n testdir.makepyfile(\n test_external_fixture=\"\"\"\n def test_foo(request):\n request.getfixturevalue('fix_with_param')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"The requested fixture has no parameter defined for test:\",\n \" test_external_fixture.py::test_foo\",\n \"\",\n \"Requested fixture 'fix_with_param' defined in:\",\n \"conftest.py:4\",\n \"Requested here:\",\n \"test_external_fixture.py:2\",\n \"*1 failed*\",\n ]\n )"},{"className":"TestInlineRunModulesCleanup","col":0,"comment":"null","endLoc":289,"id":2761,"nodeType":"Class","startLoc":217,"text":"class TestInlineRunModulesCleanup(object):\n def test_inline_run_test_module_not_cleaned_up(self, testdir):\n test_mod = testdir.makepyfile(\"def test_foo(): assert True\")\n result = testdir.inline_run(str(test_mod))\n assert result.ret == EXIT_OK\n # rewrite module, now test should fail if module was re-imported\n test_mod.write(\"def test_foo(): assert False\")\n result2 = testdir.inline_run(str(test_mod))\n assert result2.ret == EXIT_TESTSFAILED\n\n def spy_factory(self):\n class SysModulesSnapshotSpy(object):\n instances = []\n\n def __init__(self, preserve=None):\n SysModulesSnapshotSpy.instances.append(self)\n self._spy_restore_count = 0\n self._spy_preserve = preserve\n self.__snapshot = SysModulesSnapshot(preserve=preserve)\n\n def restore(self):\n self._spy_restore_count += 1\n return self.__snapshot.restore()\n\n return SysModulesSnapshotSpy\n\n def test_inline_run_taking_and_restoring_a_sys_modules_snapshot(\n self, testdir, monkeypatch\n ):\n spy_factory = self.spy_factory()\n monkeypatch.setattr(pytester, \"SysModulesSnapshot\", spy_factory)\n testdir.syspathinsert()\n original = dict(sys.modules)\n testdir.makepyfile(import1=\"# you son of a silly person\")\n testdir.makepyfile(import2=\"# my hovercraft is full of eels\")\n test_mod = testdir.makepyfile(\n \"\"\"\n import import1\n def test_foo(): import import2\"\"\"\n )\n testdir.inline_run(str(test_mod))\n assert len(spy_factory.instances) == 1\n spy = spy_factory.instances[0]\n assert spy._spy_restore_count == 1\n assert sys.modules == original\n assert all(sys.modules[x] is original[x] for x in sys.modules)\n\n def test_inline_run_sys_modules_snapshot_restore_preserving_modules(\n self, testdir, monkeypatch\n ):\n spy_factory = self.spy_factory()\n monkeypatch.setattr(pytester, \"SysModulesSnapshot\", spy_factory)\n test_mod = testdir.makepyfile(\"def test_foo(): pass\")\n testdir.inline_run(str(test_mod))\n spy = spy_factory.instances[0]\n assert not spy._spy_preserve(\"black_knight\")\n assert spy._spy_preserve(\"zope\")\n assert spy._spy_preserve(\"zope.interface\")\n assert spy._spy_preserve(\"zopelicious\")\n\n def test_external_test_module_imports_not_cleaned_up(self, testdir):\n testdir.syspathinsert()\n testdir.makepyfile(imported=\"data = 'you son of a silly person'\")\n import imported\n\n test_mod = testdir.makepyfile(\n \"\"\"\n def test_foo():\n import imported\n imported.data = 42\"\"\"\n )\n testdir.inline_run(str(test_mod))\n assert imported.data == 42"},{"col":4,"comment":"null","endLoc":225,"header":"def test_inline_run_test_module_not_cleaned_up(self, testdir)","id":2762,"name":"test_inline_run_test_module_not_cleaned_up","nodeType":"Function","startLoc":218,"text":"def test_inline_run_test_module_not_cleaned_up(self, testdir):\n test_mod = testdir.makepyfile(\"def test_foo(): assert True\")\n result = testdir.inline_run(str(test_mod))\n assert result.ret == EXIT_OK\n # rewrite module, now test should fail if module was re-imported\n test_mod.write(\"def test_foo(): assert False\")\n result2 = testdir.inline_run(str(test_mod))\n assert result2.ret == EXIT_TESTSFAILED"},{"col":4,"comment":"null","endLoc":3599,"header":"def test_non_relative_path(self, testdir)","id":2763,"name":"test_non_relative_path","nodeType":"Function","startLoc":3557,"text":"def test_non_relative_path(self, testdir):\n tests_dir = testdir.mkdir(\"tests\")\n fixdir = testdir.mkdir(\"fixtures\")\n fixfile = fixdir.join(\"fix.py\")\n fixfile.write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n\n @pytest.fixture(params=[0, 1, 2])\n def fix_with_param(request):\n return request.param\n \"\"\"\n )\n )\n\n testfile = tests_dir.join(\"test_foos.py\")\n testfile.write(\n textwrap.dedent(\n \"\"\"\\\n from fix import fix_with_param\n\n def test_foo(request):\n request.getfixturevalue('fix_with_param')\n \"\"\"\n )\n )\n\n tests_dir.chdir()\n testdir.syspathinsert(fixdir)\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"The requested fixture has no parameter defined for test:\",\n \" test_foos.py::test_foo\",\n \"\",\n \"Requested fixture 'fix_with_param' defined in:\",\n \"*fix.py:4\",\n \"Requested here:\",\n \"test_foos.py:4\",\n \"*1 failed*\",\n ]\n )"},{"className":"TestScopeOrdering","col":0,"comment":"Class of tests that ensure fixtures are ordered based on their scopes (#2405)","endLoc":3941,"id":2764,"nodeType":"Class","startLoc":3648,"text":"class TestScopeOrdering(object):\n \"\"\"Class of tests that ensure fixtures are ordered based on their scopes (#2405)\"\"\"\n\n @pytest.mark.parametrize(\"variant\", [\"mark\", \"autouse\"])\n def test_func_closure_module_auto(self, testdir, variant, monkeypatch):\n \"\"\"Semantically identical to the example posted in #2405 when ``use_mark=True``\"\"\"\n monkeypatch.setenv(\"FIXTURE_ACTIVATION_VARIANT\", variant)\n testdir.makepyfile(\n \"\"\"\n import warnings\n import os\n import pytest\n VAR = 'FIXTURE_ACTIVATION_VARIANT'\n VALID_VARS = ('autouse', 'mark')\n\n VARIANT = os.environ.get(VAR)\n if VARIANT is None or VARIANT not in VALID_VARS:\n warnings.warn(\"{!r} is not in {}, assuming autouse\".format(VARIANT, VALID_VARS) )\n variant = 'mark'\n\n @pytest.fixture(scope='module', autouse=VARIANT == 'autouse')\n def m1(): pass\n\n if VARIANT=='mark':\n pytestmark = pytest.mark.usefixtures('m1')\n\n @pytest.fixture(scope='function', autouse=True)\n def f1(): pass\n\n def test_func(m1):\n pass\n \"\"\"\n )\n items, _ = testdir.inline_genitems()\n request = FixtureRequest(items[0])\n assert request.fixturenames == \"m1 f1\".split()\n\n def test_func_closure_with_native_fixtures(self, testdir, monkeypatch):\n \"\"\"Sanity check that verifies the order returned by the closures and the actual fixture execution order:\n The execution order may differ because of fixture inter-dependencies.\n \"\"\"\n monkeypatch.setattr(pytest, \"FIXTURE_ORDER\", [], raising=False)\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n FIXTURE_ORDER = pytest.FIXTURE_ORDER\n\n @pytest.fixture(scope=\"session\")\n def s1():\n FIXTURE_ORDER.append('s1')\n\n @pytest.fixture(scope=\"package\")\n def p1():\n FIXTURE_ORDER.append('p1')\n\n @pytest.fixture(scope=\"module\")\n def m1():\n FIXTURE_ORDER.append('m1')\n\n @pytest.fixture(scope='session')\n def my_tmpdir_factory():\n FIXTURE_ORDER.append('my_tmpdir_factory')\n\n @pytest.fixture\n def my_tmpdir(my_tmpdir_factory):\n FIXTURE_ORDER.append('my_tmpdir')\n\n @pytest.fixture\n def f1(my_tmpdir):\n FIXTURE_ORDER.append('f1')\n\n @pytest.fixture\n def f2():\n FIXTURE_ORDER.append('f2')\n\n def test_foo(f1, p1, m1, f2, s1): pass\n \"\"\"\n )\n items, _ = testdir.inline_genitems()\n request = FixtureRequest(items[0])\n # order of fixtures based on their scope and position in the parameter list\n assert (\n request.fixturenames == \"s1 my_tmpdir_factory p1 m1 f1 f2 my_tmpdir\".split()\n )\n testdir.runpytest()\n # actual fixture execution differs: dependent fixtures must be created first (\"my_tmpdir\")\n assert (\n pytest.FIXTURE_ORDER == \"s1 my_tmpdir_factory p1 m1 my_tmpdir f1 f2\".split()\n )\n\n def test_func_closure_module(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='module')\n def m1(): pass\n\n @pytest.fixture(scope='function')\n def f1(): pass\n\n def test_func(f1, m1):\n pass\n \"\"\"\n )\n items, _ = testdir.inline_genitems()\n request = FixtureRequest(items[0])\n assert request.fixturenames == \"m1 f1\".split()\n\n def test_func_closure_scopes_reordered(self, testdir):\n \"\"\"Test ensures that fixtures are ordered by scope regardless of the order of the parameters, although\n fixtures of same scope keep the declared order\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='session')\n def s1(): pass\n\n @pytest.fixture(scope='module')\n def m1(): pass\n\n @pytest.fixture(scope='function')\n def f1(): pass\n\n @pytest.fixture(scope='function')\n def f2(): pass\n\n class Test:\n\n @pytest.fixture(scope='class')\n def c1(cls): pass\n\n def test_func(self, f2, f1, c1, m1, s1):\n pass\n \"\"\"\n )\n items, _ = testdir.inline_genitems()\n request = FixtureRequest(items[0])\n assert request.fixturenames == \"s1 m1 c1 f2 f1\".split()\n\n def test_func_closure_same_scope_closer_root_first(self, testdir):\n \"\"\"Auto-use fixtures of same scope are ordered by closer-to-root first\"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='module', autouse=True)\n def m_conf(): pass\n \"\"\"\n )\n testdir.makepyfile(\n **{\n \"sub/conftest.py\": \"\"\"\n import pytest\n\n @pytest.fixture(scope='package', autouse=True)\n def p_sub(): pass\n\n @pytest.fixture(scope='module', autouse=True)\n def m_sub(): pass\n \"\"\",\n \"sub/__init__.py\": \"\",\n \"sub/test_func.py\": \"\"\"\n import pytest\n\n @pytest.fixture(scope='module', autouse=True)\n def m_test(): pass\n\n @pytest.fixture(scope='function')\n def f1(): pass\n\n def test_func(m_test, f1):\n pass\n \"\"\",\n }\n )\n items, _ = testdir.inline_genitems()\n request = FixtureRequest(items[0])\n assert request.fixturenames == \"p_sub m_conf m_sub m_test f1\".split()\n\n def test_func_closure_all_scopes_complex(self, testdir):\n \"\"\"Complex test involving all scopes and mixing autouse with normal fixtures\"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='session')\n def s1(): pass\n\n @pytest.fixture(scope='package', autouse=True)\n def p1(): pass\n \"\"\"\n )\n testdir.makepyfile(**{\"__init__.py\": \"\"})\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='module', autouse=True)\n def m1(): pass\n\n @pytest.fixture(scope='module')\n def m2(s1): pass\n\n @pytest.fixture(scope='function')\n def f1(): pass\n\n @pytest.fixture(scope='function')\n def f2(): pass\n\n class Test:\n\n @pytest.fixture(scope='class', autouse=True)\n def c1(self):\n pass\n\n def test_func(self, f2, f1, m2):\n pass\n \"\"\"\n )\n items, _ = testdir.inline_genitems()\n request = FixtureRequest(items[0])\n assert request.fixturenames == \"s1 p1 m1 m2 c1 f2 f1\".split()\n\n def test_multiple_packages(self, testdir):\n \"\"\"Complex test involving multiple package fixtures. Make sure teardowns\n are executed in order.\n .\n └── root\n ├── __init__.py\n ├── sub1\n │ ├── __init__.py\n │ ├── conftest.py\n │ └── test_1.py\n └── sub2\n ├── __init__.py\n ├── conftest.py\n └── test_2.py\n \"\"\"\n root = testdir.mkdir(\"root\")\n root.join(\"__init__.py\").write(\"values = []\")\n sub1 = root.mkdir(\"sub1\")\n sub1.ensure(\"__init__.py\")\n sub1.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n from .. import values\n @pytest.fixture(scope=\"package\")\n def fix():\n values.append(\"pre-sub1\")\n yield values\n assert values.pop() == \"pre-sub1\"\n \"\"\"\n )\n )\n sub1.join(\"test_1.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def test_1(fix):\n assert values == [\"pre-sub1\"]\n \"\"\"\n )\n )\n sub2 = root.mkdir(\"sub2\")\n sub2.ensure(\"__init__.py\")\n sub2.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n from .. import values\n @pytest.fixture(scope=\"package\")\n def fix():\n values.append(\"pre-sub2\")\n yield values\n assert values.pop() == \"pre-sub2\"\n \"\"\"\n )\n )\n sub2.join(\"test_2.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def test_2(fix):\n assert values == [\"pre-sub2\"]\n \"\"\"\n )\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)"},{"col":4,"comment":"Semantically identical to the example posted in #2405 when ``use_mark=True``","endLoc":3683,"header":"@pytest.mark.parametrize(\"variant\", [\"mark\", \"autouse\"])\n def test_func_closure_module_auto(self, testdir, variant, monkeypatch)","id":2765,"name":"test_func_closure_module_auto","nodeType":"Function","startLoc":3651,"text":"@pytest.mark.parametrize(\"variant\", [\"mark\", \"autouse\"])\n def test_func_closure_module_auto(self, testdir, variant, monkeypatch):\n \"\"\"Semantically identical to the example posted in #2405 when ``use_mark=True``\"\"\"\n monkeypatch.setenv(\"FIXTURE_ACTIVATION_VARIANT\", variant)\n testdir.makepyfile(\n \"\"\"\n import warnings\n import os\n import pytest\n VAR = 'FIXTURE_ACTIVATION_VARIANT'\n VALID_VARS = ('autouse', 'mark')\n\n VARIANT = os.environ.get(VAR)\n if VARIANT is None or VARIANT not in VALID_VARS:\n warnings.warn(\"{!r} is not in {}, assuming autouse\".format(VARIANT, VALID_VARS) )\n variant = 'mark'\n\n @pytest.fixture(scope='module', autouse=VARIANT == 'autouse')\n def m1(): pass\n\n if VARIANT=='mark':\n pytestmark = pytest.mark.usefixtures('m1')\n\n @pytest.fixture(scope='function', autouse=True)\n def f1(): pass\n\n def test_func(m1):\n pass\n \"\"\"\n )\n items, _ = testdir.inline_genitems()\n request = FixtureRequest(items[0])\n assert request.fixturenames == \"m1 f1\".split()"},{"className":"Formatter","col":0,"comment":"null","endLoc":303,"id":2768,"nodeType":"Class","startLoc":272,"text":"class Formatter:\n converter: Callable[[float | None], struct_time]\n _fmt: str | None # undocumented\n datefmt: str | None # undocumented\n _style: PercentStyle # undocumented\n default_time_format: str\n if sys.version_info >= (3, 9):\n default_msec_format: str | None\n else:\n default_msec_format: str\n\n if sys.version_info >= (3, 10):\n def __init__(\n self,\n fmt: str | None = None,\n datefmt: str | None = None,\n style: _FormatStyle = \"%\",\n validate: bool = True,\n *,\n defaults: Mapping[str, Any] | None = None,\n ) -> None: ...\n else:\n def __init__(\n self, fmt: str | None = None, datefmt: str | None = None, style: _FormatStyle = \"%\", validate: bool = True\n ) -> None: ...\n\n def format(self, record: LogRecord) -> str: ...\n def formatTime(self, record: LogRecord, datefmt: str | None = None) -> str: ...\n def formatException(self, ei: _SysExcInfoType) -> str: ...\n def formatMessage(self, record: LogRecord) -> str: ... # undocumented\n def formatStack(self, stack_info: str) -> str: ...\n def usesTime(self) -> bool: ... # undocumented"},{"col":8,"comment":"null","endLoc":296,"header":"def __init__(\n self, fmt: str | None = None, datefmt: str | None = None, style: _FormatStyle = \"%\", validate: bool = True\n ) -> None","id":2769,"name":"__init__","nodeType":"Function","startLoc":294,"text":"def __init__(\n self, fmt: str | None = None, datefmt: str | None = None, style: _FormatStyle = \"%\", validate: bool = True\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":298,"header":"def format(self, record: LogRecord) -> str","id":2770,"name":"format","nodeType":"Function","startLoc":298,"text":"def format(self, record: LogRecord) -> str: ..."},{"col":4,"comment":"null","endLoc":299,"header":"def formatTime(self, record: LogRecord, datefmt: str | None = None) -> str","id":2771,"name":"formatTime","nodeType":"Function","startLoc":299,"text":"def formatTime(self, record: LogRecord, datefmt: str | None = None) -> str: ..."},{"col":4,"comment":"null","endLoc":300,"header":"def formatException(self, ei: _SysExcInfoType) -> str","id":2772,"name":"formatException","nodeType":"Function","startLoc":300,"text":"def formatException(self, ei: _SysExcInfoType) -> str: ..."},{"col":4,"comment":"null","endLoc":301,"header":"def formatMessage(self, record: LogRecord) -> str","id":2773,"name":"formatMessage","nodeType":"Function","startLoc":301,"text":"def formatMessage(self, record: LogRecord) -> str: ... # undocumented"},{"col":4,"comment":"null","endLoc":302,"header":"def formatStack(self, stack_info: str) -> str","id":2774,"name":"formatStack","nodeType":"Function","startLoc":302,"text":"def formatStack(self, stack_info: str) -> str: ..."},{"col":4,"comment":"null","endLoc":303,"header":"def usesTime(self) -> bool","id":2775,"name":"usesTime","nodeType":"Function","startLoc":303,"text":"def usesTime(self) -> bool: ... # undocumented"},{"attributeType":"(float | None) -> struct_time","col":4,"comment":"null","endLoc":273,"id":2776,"name":"converter","nodeType":"Attribute","startLoc":273,"text":"converter"},{"col":4,"comment":"null","endLoc":50,"header":"def test_basic_init(self, basedir)","id":2777,"name":"test_basic_init","nodeType":"Function","startLoc":47,"text":"def test_basic_init(self, basedir):\n conftest = PytestPluginManager()\n p = basedir.join(\"adir\")\n assert conftest._rget_with_confmod(\"a\", p)[1] == 1"},{"col":4,"comment":"null","endLoc":241,"header":"def spy_factory(self)","id":2778,"name":"spy_factory","nodeType":"Function","startLoc":227,"text":"def spy_factory(self):\n class SysModulesSnapshotSpy(object):\n instances = []\n\n def __init__(self, preserve=None):\n SysModulesSnapshotSpy.instances.append(self)\n self._spy_restore_count = 0\n self._spy_preserve = preserve\n self.__snapshot = SysModulesSnapshot(preserve=preserve)\n\n def restore(self):\n self._spy_restore_count += 1\n return self.__snapshot.restore()\n\n return SysModulesSnapshotSpy"},{"col":4,"comment":"null","endLoc":61,"header":"def test_immediate_initialiation_and_incremental_are_the_same(self, basedir)","id":2779,"name":"test_immediate_initialiation_and_incremental_are_the_same","nodeType":"Function","startLoc":52,"text":"def test_immediate_initialiation_and_incremental_are_the_same(self, basedir):\n conftest = PytestPluginManager()\n assert not len(conftest._dirpath2confmods)\n conftest._getconftestmodules(basedir)\n snap1 = len(conftest._dirpath2confmods)\n assert snap1 == 1\n conftest._getconftestmodules(basedir.join(\"adir\"))\n assert len(conftest._dirpath2confmods) == snap1 + 1\n conftest._getconftestmodules(basedir.join(\"b\"))\n assert len(conftest._dirpath2confmods) == snap1 + 2"},{"col":4,"comment":"null","endLoc":66,"header":"def test_value_access_not_existing(self, basedir)","id":2780,"name":"test_value_access_not_existing","nodeType":"Function","startLoc":63,"text":"def test_value_access_not_existing(self, basedir):\n conftest = ConftestWithSetinitial(basedir)\n with pytest.raises(KeyError):\n conftest._rget_with_confmod(\"a\", basedir)"},{"col":0,"comment":"null","endLoc":20,"header":"def ConftestWithSetinitial(path)","id":2781,"name":"ConftestWithSetinitial","nodeType":"Function","startLoc":17,"text":"def ConftestWithSetinitial(path):\n conftest = PytestPluginManager()\n conftest_setinitial(conftest, [path])\n return conftest"},{"col":0,"comment":"null","endLoc":31,"header":"def conftest_setinitial(conftest, args, confcutdir=None)","id":2782,"name":"conftest_setinitial","nodeType":"Function","startLoc":23,"text":"def conftest_setinitial(conftest, args, confcutdir=None):\n class Namespace(object):\n def __init__(self):\n self.file_or_dir = args\n self.confcutdir = str(confcutdir)\n self.noconftest = False\n self.pyargs = False\n\n conftest._set_initial_conftests(Namespace())"},{"col":0,"comment":"cleanup for lock driven numbered directories","endLoc":293,"header":"def cleanup_numbered_dir(root, prefix, keep, consider_lock_dead_if_created_before)","id":2783,"name":"cleanup_numbered_dir","nodeType":"Function","startLoc":288,"text":"def cleanup_numbered_dir(root, prefix, keep, consider_lock_dead_if_created_before):\n \"\"\"cleanup for lock driven numbered directories\"\"\"\n for path in cleanup_candidates(root, prefix, keep):\n try_cleanup(path, consider_lock_dead_if_created_before)\n for path in root.glob(\"garbage-*\"):\n try_cleanup(path, consider_lock_dead_if_created_before)"},{"col":0,"comment":"creates a numbered dir with a cleanup lock and removes old ones","endLoc":316,"header":"def make_numbered_dir_with_cleanup(root, prefix, keep, lock_timeout)","id":2784,"name":"make_numbered_dir_with_cleanup","nodeType":"Function","startLoc":296,"text":"def make_numbered_dir_with_cleanup(root, prefix, keep, lock_timeout):\n \"\"\"creates a numbered dir with a cleanup lock and removes old ones\"\"\"\n e = None\n for i in range(10):\n try:\n p = make_numbered_dir(root, prefix)\n lock_path = create_cleanup_lock(p)\n register_cleanup_lock_removal(lock_path)\n except Exception as exc:\n e = exc\n else:\n consider_lock_dead_if_created_before = p.stat().st_mtime - lock_timeout\n cleanup_numbered_dir(\n root=root,\n prefix=prefix,\n keep=keep,\n consider_lock_dead_if_created_before=consider_lock_dead_if_created_before,\n )\n return p\n assert e is not None\n raise e"},{"attributeType":"str | None","col":4,"comment":"null","endLoc":274,"id":2785,"name":"_fmt","nodeType":"Attribute","startLoc":274,"text":"_fmt"},{"col":0,"comment":"null","endLoc":141,"header":"def pytest_cmdline_main(config)","id":2786,"name":"pytest_cmdline_main","nodeType":"Function","startLoc":133,"text":"def pytest_cmdline_main(config):\n if config.option.version:\n showversion(config)\n return 0\n elif config.option.help:\n config._do_configure()\n showhelp(config)\n config._ensure_unconfigure()\n return 0"},{"col":0,"comment":"null","endLoc":327,"header":"def resolve_from_str(input, root)","id":2787,"name":"resolve_from_str","nodeType":"Function","startLoc":319,"text":"def resolve_from_str(input, root):\n assert not isinstance(input, Path), \"would break on py2\"\n root = Path(root)\n input = expanduser(input)\n input = expandvars(input)\n if isabs(input):\n return Path(input)\n else:\n return root.joinpath(input)"},{"attributeType":"str | None","col":4,"comment":"null","endLoc":275,"id":2788,"name":"datefmt","nodeType":"Attribute","startLoc":275,"text":"datefmt"},{"col":0,"comment":"null","endLoc":211,"header":"def showhelp(config)","id":2789,"name":"showhelp","nodeType":"Function","startLoc":144,"text":"def showhelp(config):\n import textwrap\n\n reporter = config.pluginmanager.get_plugin(\"terminalreporter\")\n tw = reporter._tw\n tw.write(config._parser.optparser.format_help())\n tw.line()\n tw.line(\n \"[pytest] ini-options in the first pytest.ini|tox.ini|setup.cfg file found:\"\n )\n tw.line()\n\n columns = tw.fullwidth # costly call\n indent_len = 24 # based on argparse's max_help_position=24\n indent = \" \" * indent_len\n for name in config._parser._ininames:\n help, type, default = config._parser._inidict[name]\n if type is None:\n type = \"string\"\n spec = \"%s (%s):\" % (name, type)\n tw.write(\" %s\" % spec)\n spec_len = len(spec)\n if spec_len > (indent_len - 3):\n # Display help starting at a new line.\n tw.line()\n helplines = textwrap.wrap(\n help,\n columns,\n initial_indent=indent,\n subsequent_indent=indent,\n break_on_hyphens=False,\n )\n\n for line in helplines:\n tw.line(line)\n else:\n # Display help starting after the spec, following lines indented.\n tw.write(\" \" * (indent_len - spec_len - 2))\n wrapped = textwrap.wrap(help, columns - indent_len, break_on_hyphens=False)\n\n tw.line(wrapped[0])\n for line in wrapped[1:]:\n tw.line(indent + line)\n\n tw.line()\n tw.line(\"environment variables:\")\n vars = [\n (\"PYTEST_ADDOPTS\", \"extra command line options\"),\n (\"PYTEST_PLUGINS\", \"comma-separated plugins to load during startup\"),\n (\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", \"set to disable plugin auto-loading\"),\n (\"PYTEST_DEBUG\", \"set to enable debug tracing of pytest's internals\"),\n ]\n for name, help in vars:\n tw.line(\" %-24s %s\" % (name, help))\n tw.line()\n tw.line()\n\n tw.line(\"to see available markers type: pytest --markers\")\n tw.line(\"to see available fixtures type: pytest --fixtures\")\n tw.line(\n \"(shown according to specified file_or_dir or current dir \"\n \"if not specified; fixtures with leading '_' are only shown \"\n \"with the '-v' option\"\n )\n\n for warningreport in reporter.stats.get(\"warnings\", []):\n tw.line(\"warning : \" + warningreport.message, red=True)\n return"},{"attributeType":"PercentStyle","col":4,"comment":"null","endLoc":276,"id":2790,"name":"_style","nodeType":"Attribute","startLoc":276,"text":"_style"},{"attributeType":"str","col":4,"comment":"null","endLoc":277,"id":2791,"name":"default_time_format","nodeType":"Attribute","startLoc":277,"text":"default_time_format"},{"attributeType":"str | None","col":8,"comment":"null","endLoc":279,"id":2792,"name":"default_msec_format","nodeType":"Attribute","startLoc":279,"text":"default_msec_format"},{"col":4,"comment":"Sanity check that verifies the order returned by the closures and the actual fixture execution order:\n The execution order may differ because of fixture inter-dependencies.\n ","endLoc":3737,"header":"def test_func_closure_with_native_fixtures(self, testdir, monkeypatch)","id":2793,"name":"test_func_closure_with_native_fixtures","nodeType":"Function","startLoc":3685,"text":"def test_func_closure_with_native_fixtures(self, testdir, monkeypatch):\n \"\"\"Sanity check that verifies the order returned by the closures and the actual fixture execution order:\n The execution order may differ because of fixture inter-dependencies.\n \"\"\"\n monkeypatch.setattr(pytest, \"FIXTURE_ORDER\", [], raising=False)\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n FIXTURE_ORDER = pytest.FIXTURE_ORDER\n\n @pytest.fixture(scope=\"session\")\n def s1():\n FIXTURE_ORDER.append('s1')\n\n @pytest.fixture(scope=\"package\")\n def p1():\n FIXTURE_ORDER.append('p1')\n\n @pytest.fixture(scope=\"module\")\n def m1():\n FIXTURE_ORDER.append('m1')\n\n @pytest.fixture(scope='session')\n def my_tmpdir_factory():\n FIXTURE_ORDER.append('my_tmpdir_factory')\n\n @pytest.fixture\n def my_tmpdir(my_tmpdir_factory):\n FIXTURE_ORDER.append('my_tmpdir')\n\n @pytest.fixture\n def f1(my_tmpdir):\n FIXTURE_ORDER.append('f1')\n\n @pytest.fixture\n def f2():\n FIXTURE_ORDER.append('f2')\n\n def test_foo(f1, p1, m1, f2, s1): pass\n \"\"\"\n )\n items, _ = testdir.inline_genitems()\n request = FixtureRequest(items[0])\n # order of fixtures based on their scope and position in the parameter list\n assert (\n request.fixturenames == \"s1 my_tmpdir_factory p1 m1 f1 f2 my_tmpdir\".split()\n )\n testdir.runpytest()\n # actual fixture execution differs: dependent fixtures must be created first (\"my_tmpdir\")\n assert (\n pytest.FIXTURE_ORDER == \"s1 my_tmpdir_factory p1 m1 my_tmpdir f1 f2\".split()\n )"},{"col":4,"comment":"null","endLoc":69,"header":"def __init__(self, terminalwriter, *args, **kwargs)","id":2794,"name":"__init__","nodeType":"Function","startLoc":44,"text":"def __init__(self, terminalwriter, *args, **kwargs):\n super(ColoredLevelFormatter, self).__init__(*args, **kwargs)\n if six.PY2:\n self._original_fmt = self._fmt\n else:\n self._original_fmt = self._style._fmt\n self._level_to_fmt_mapping = {}\n\n levelname_fmt_match = self.LEVELNAME_FMT_REGEX.search(self._fmt)\n if not levelname_fmt_match:\n return\n levelname_fmt = levelname_fmt_match.group()\n\n for level, color_opts in self.LOGLEVEL_COLOROPTS.items():\n formatted_levelname = levelname_fmt % {\n \"levelname\": logging.getLevelName(level)\n }\n\n # add ANSI escape sequences around the formatted levelname\n color_kwargs = {name: True for name in color_opts}\n colorized_formatted_levelname = terminalwriter.markup(\n formatted_levelname, **color_kwargs\n )\n self._level_to_fmt_mapping[level] = self.LEVELNAME_FMT_REGEX.sub(\n colorized_formatted_levelname, self._fmt\n )"},{"col":4,"comment":"null","endLoc":262,"header":"def test_inline_run_taking_and_restoring_a_sys_modules_snapshot(\n self, testdir, monkeypatch\n )","id":2795,"name":"test_inline_run_taking_and_restoring_a_sys_modules_snapshot","nodeType":"Function","startLoc":243,"text":"def test_inline_run_taking_and_restoring_a_sys_modules_snapshot(\n self, testdir, monkeypatch\n ):\n spy_factory = self.spy_factory()\n monkeypatch.setattr(pytester, \"SysModulesSnapshot\", spy_factory)\n testdir.syspathinsert()\n original = dict(sys.modules)\n testdir.makepyfile(import1=\"# you son of a silly person\")\n testdir.makepyfile(import2=\"# my hovercraft is full of eels\")\n test_mod = testdir.makepyfile(\n \"\"\"\n import import1\n def test_foo(): import import2\"\"\"\n )\n testdir.inline_run(str(test_mod))\n assert len(spy_factory.instances) == 1\n spy = spy_factory.instances[0]\n assert spy._spy_restore_count == 1\n assert sys.modules == original\n assert all(sys.modules[x] is original[x] for x in sys.modules)"},{"col":4,"comment":"null","endLoc":3756,"header":"def test_func_closure_module(self, testdir)","id":2796,"name":"test_func_closure_module","nodeType":"Function","startLoc":3739,"text":"def test_func_closure_module(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='module')\n def m1(): pass\n\n @pytest.fixture(scope='function')\n def f1(): pass\n\n def test_func(f1, m1):\n pass\n \"\"\"\n )\n items, _ = testdir.inline_genitems()\n request = FixtureRequest(items[0])\n assert request.fixturenames == \"m1 f1\".split()"},{"col":4,"comment":" return a Traceback instance with certain items removed\n\n fn is a function that gets a single argument, a TracebackEntry\n instance, and should return True when the item should be added\n to the Traceback, False when not\n\n by default this removes all the TracebackEntries which are hidden\n (see ishidden() above)\n ","endLoc":342,"header":"def filter(self, fn=lambda x: not x.ishidden())","id":2797,"name":"filter","nodeType":"Function","startLoc":332,"text":"def filter(self, fn=lambda x: not x.ishidden()):\n \"\"\" return a Traceback instance with certain items removed\n\n fn is a function that gets a single argument, a TracebackEntry\n instance, and should return True when the item should be added\n to the Traceback, False when not\n\n by default this removes all the TracebackEntries which are hidden\n (see ishidden() above)\n \"\"\"\n return Traceback(filter(fn, self), self._excinfo)"},{"col":24,"endLoc":332,"id":2798,"nodeType":"Lambda","startLoc":332,"text":"lambda x: not x.ishidden()"},{"col":4,"comment":"Test ensures that fixtures are ordered by scope regardless of the order of the parameters, although\n fixtures of same scope keep the declared order\n ","endLoc":3789,"header":"def test_func_closure_scopes_reordered(self, testdir)","id":2799,"name":"test_func_closure_scopes_reordered","nodeType":"Function","startLoc":3758,"text":"def test_func_closure_scopes_reordered(self, testdir):\n \"\"\"Test ensures that fixtures are ordered by scope regardless of the order of the parameters, although\n fixtures of same scope keep the declared order\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='session')\n def s1(): pass\n\n @pytest.fixture(scope='module')\n def m1(): pass\n\n @pytest.fixture(scope='function')\n def f1(): pass\n\n @pytest.fixture(scope='function')\n def f2(): pass\n\n class Test:\n\n @pytest.fixture(scope='class')\n def c1(cls): pass\n\n def test_func(self, f2, f1, c1, m1, s1):\n pass\n \"\"\"\n )\n items, _ = testdir.inline_genitems()\n request = FixtureRequest(items[0])\n assert request.fixturenames == \"s1 m1 c1 f2 f1\".split()"},{"col":0,"comment":"FNMatcher port from py.path.common which works with PurePath() instances.\n\n The difference between this algorithm and PurePath.match() is that the latter matches \"**\" glob expressions\n for each part of the path, while this algorithm uses the whole path instead.\n\n For example:\n \"tests/foo/bar/doc/test_foo.py\" matches pattern \"tests/**/doc/test*.py\" with this algorithm, but not with\n PurePath.match().\n\n This algorithm was ported to keep backward-compatibility with existing settings which assume paths match according\n this logic.\n\n References:\n * https://bugs.python.org/issue29249\n * https://bugs.python.org/issue34731\n ","endLoc":360,"header":"def fnmatch_ex(pattern, path)","id":2801,"name":"fnmatch_ex","nodeType":"Function","startLoc":330,"text":"def fnmatch_ex(pattern, path):\n \"\"\"FNMatcher port from py.path.common which works with PurePath() instances.\n\n The difference between this algorithm and PurePath.match() is that the latter matches \"**\" glob expressions\n for each part of the path, while this algorithm uses the whole path instead.\n\n For example:\n \"tests/foo/bar/doc/test_foo.py\" matches pattern \"tests/**/doc/test*.py\" with this algorithm, but not with\n PurePath.match().\n\n This algorithm was ported to keep backward-compatibility with existing settings which assume paths match according\n this logic.\n\n References:\n * https://bugs.python.org/issue29249\n * https://bugs.python.org/issue34731\n \"\"\"\n path = PurePath(path)\n iswin32 = sys.platform.startswith(\"win\")\n\n if iswin32 and sep not in pattern and posix_sep in pattern:\n # Running on Windows, the pattern has no Windows path separators,\n # and the pattern has one or more Posix path separators. Replace\n # the Posix path separators with the Windows path separator.\n pattern = pattern.replace(posix_sep, sep)\n\n if sep not in pattern:\n name = path.name\n else:\n name = six.text_type(path)\n return fnmatch.fnmatch(name, pattern)"},{"col":4,"comment":"Auto-use fixtures of same scope are ordered by closer-to-root first","endLoc":3829,"header":"def test_func_closure_same_scope_closer_root_first(self, testdir)","id":2802,"name":"test_func_closure_same_scope_closer_root_first","nodeType":"Function","startLoc":3791,"text":"def test_func_closure_same_scope_closer_root_first(self, testdir):\n \"\"\"Auto-use fixtures of same scope are ordered by closer-to-root first\"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='module', autouse=True)\n def m_conf(): pass\n \"\"\"\n )\n testdir.makepyfile(\n **{\n \"sub/conftest.py\": \"\"\"\n import pytest\n\n @pytest.fixture(scope='package', autouse=True)\n def p_sub(): pass\n\n @pytest.fixture(scope='module', autouse=True)\n def m_sub(): pass\n \"\"\",\n \"sub/__init__.py\": \"\",\n \"sub/test_func.py\": \"\"\"\n import pytest\n\n @pytest.fixture(scope='module', autouse=True)\n def m_test(): pass\n\n @pytest.fixture(scope='function')\n def f1(): pass\n\n def test_func(m_test, f1):\n pass\n \"\"\",\n }\n )\n items, _ = testdir.inline_genitems()\n request = FixtureRequest(items[0])\n assert request.fixturenames == \"p_sub m_conf m_sub m_test f1\".split()"},{"col":4,"comment":"null","endLoc":72,"header":"def test_value_access_by_path(self, basedir)","id":2803,"name":"test_value_access_by_path","nodeType":"Function","startLoc":68,"text":"def test_value_access_by_path(self, basedir):\n conftest = ConftestWithSetinitial(basedir)\n adir = basedir.join(\"adir\")\n assert conftest._rget_with_confmod(\"a\", adir)[1] == 1\n assert conftest._rget_with_confmod(\"a\", adir.join(\"b\"))[1] == 1.5"},{"col":4,"comment":"null","endLoc":82,"header":"def test_value_access_with_confmod(self, basedir)","id":2806,"name":"test_value_access_with_confmod","nodeType":"Function","startLoc":74,"text":"def test_value_access_with_confmod(self, basedir):\n startdir = basedir.join(\"adir\", \"b\")\n startdir.ensure(\"xx\", dir=True)\n conftest = ConftestWithSetinitial(startdir)\n mod, value = conftest._rget_with_confmod(\"a\", startdir)\n assert value == 1.5\n path = py.path.local(mod.__file__)\n assert path.dirpath() == basedir.join(\"adir\", \"b\")\n assert path.purebasename.startswith(\"conftest\")"},{"col":4,"comment":"null","endLoc":77,"header":"def format(self, record)","id":2808,"name":"format","nodeType":"Function","startLoc":71,"text":"def format(self, record):\n fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt)\n if six.PY2:\n self._fmt = fmt\n else:\n self._style._fmt = fmt\n return super(ColoredLevelFormatter, self).format(record)"},{"col":4,"comment":"Complex test involving all scopes and mixing autouse with normal fixtures","endLoc":3873,"header":"def test_func_closure_all_scopes_complex(self, testdir)","id":2809,"name":"test_func_closure_all_scopes_complex","nodeType":"Function","startLoc":3831,"text":"def test_func_closure_all_scopes_complex(self, testdir):\n \"\"\"Complex test involving all scopes and mixing autouse with normal fixtures\"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='session')\n def s1(): pass\n\n @pytest.fixture(scope='package', autouse=True)\n def p1(): pass\n \"\"\"\n )\n testdir.makepyfile(**{\"__init__.py\": \"\"})\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(scope='module', autouse=True)\n def m1(): pass\n\n @pytest.fixture(scope='module')\n def m2(s1): pass\n\n @pytest.fixture(scope='function')\n def f1(): pass\n\n @pytest.fixture(scope='function')\n def f2(): pass\n\n class Test:\n\n @pytest.fixture(scope='class', autouse=True)\n def c1(self):\n pass\n\n def test_func(self, f2, f1, m2):\n pass\n \"\"\"\n )\n items, _ = testdir.inline_genitems()\n request = FixtureRequest(items[0])\n assert request.fixturenames == \"s1 p1 m1 m2 c1 f2 f1\".split()"},{"attributeType":"null","col":4,"comment":"null","endLoc":33,"id":2810,"name":"LOGLEVEL_COLOROPTS","nodeType":"Attribute","startLoc":33,"text":"LOGLEVEL_COLOROPTS"},{"attributeType":"null","col":4,"comment":"null","endLoc":42,"id":2811,"name":"LEVELNAME_FMT_REGEX","nodeType":"Attribute","startLoc":42,"text":"LEVELNAME_FMT_REGEX"},{"attributeType":"str | None","col":12,"comment":"null","endLoc":74,"id":2812,"name":"_fmt","nodeType":"Attribute","startLoc":74,"text":"self._fmt"},{"className":"TestConftestVisibility","col":0,"comment":"null","endLoc":505,"id":2813,"nodeType":"Class","startLoc":404,"text":"class TestConftestVisibility(object):\n def _setup_tree(self, testdir): # for issue616\n # example mostly taken from:\n # https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html\n runner = testdir.mkdir(\"empty\")\n package = testdir.mkdir(\"package\")\n\n package.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def fxtr():\n return \"from-package\"\n \"\"\"\n )\n )\n package.join(\"test_pkgroot.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_pkgroot(fxtr):\n assert fxtr == \"from-package\"\n \"\"\"\n )\n )\n\n swc = package.mkdir(\"swc\")\n swc.join(\"__init__.py\").ensure()\n swc.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def fxtr():\n return \"from-swc\"\n \"\"\"\n )\n )\n swc.join(\"test_with_conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_with_conftest(fxtr):\n assert fxtr == \"from-swc\"\n \"\"\"\n )\n )\n\n snc = package.mkdir(\"snc\")\n snc.join(\"__init__.py\").ensure()\n snc.join(\"test_no_conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_no_conftest(fxtr):\n assert fxtr == \"from-package\" # No local conftest.py, so should\n # use value from parent dir's\n \"\"\"\n )\n )\n print(\"created directory structure:\")\n for x in testdir.tmpdir.visit():\n print(\" \" + x.relto(testdir.tmpdir))\n\n return {\"runner\": runner, \"package\": package, \"swc\": swc, \"snc\": snc}\n\n # N.B.: \"swc\" stands for \"subdir with conftest.py\"\n # \"snc\" stands for \"subdir no [i.e. without] conftest.py\"\n @pytest.mark.parametrize(\n \"chdir,testarg,expect_ntests_passed\",\n [\n # Effective target: package/..\n (\"runner\", \"..\", 3),\n (\"package\", \"..\", 3),\n (\"swc\", \"../..\", 3),\n (\"snc\", \"../..\", 3),\n # Effective target: package\n (\"runner\", \"../package\", 3),\n (\"package\", \".\", 3),\n (\"swc\", \"..\", 3),\n (\"snc\", \"..\", 3),\n # Effective target: package/swc\n (\"runner\", \"../package/swc\", 1),\n (\"package\", \"./swc\", 1),\n (\"swc\", \".\", 1),\n (\"snc\", \"../swc\", 1),\n # Effective target: package/snc\n (\"runner\", \"../package/snc\", 1),\n (\"package\", \"./snc\", 1),\n (\"swc\", \"../snc\", 1),\n (\"snc\", \".\", 1),\n ],\n )\n def test_parsefactories_relative_node_ids(\n self, testdir, chdir, testarg, expect_ntests_passed\n ):\n \"\"\"#616\"\"\"\n dirs = self._setup_tree(testdir)\n print(\"pytest run in cwd: %s\" % (dirs[chdir].relto(testdir.tmpdir)))\n print(\"pytestarg : %s\" % (testarg))\n print(\"expected pass : %s\" % (expect_ntests_passed))\n with dirs[chdir].as_cwd():\n reprec = testdir.inline_run(testarg, \"-q\", \"--traceconfig\")\n reprec.assertoutcome(passed=expect_ntests_passed)"},{"col":4,"comment":" return last non-hidden traceback entry that lead\n to the exception of a traceback.\n ","endLoc":352,"header":"def getcrashentry(self)","id":2817,"name":"getcrashentry","nodeType":"Function","startLoc":344,"text":"def getcrashentry(self):\n \"\"\" return last non-hidden traceback entry that lead\n to the exception of a traceback.\n \"\"\"\n for i in range(-1, -len(self) - 1, -1):\n entry = self[i]\n if not entry.ishidden():\n return entry\n return self[-1]"},{"attributeType":"null","col":8,"comment":"null","endLoc":50,"id":2818,"name":"_level_to_fmt_mapping","nodeType":"Attribute","startLoc":50,"text":"self._level_to_fmt_mapping"},{"attributeType":"str","col":12,"comment":"null","endLoc":49,"id":2819,"name":"_original_fmt","nodeType":"Attribute","startLoc":49,"text":"self._original_fmt"},{"col":4,"comment":"Complex test involving multiple package fixtures. Make sure teardowns\n are executed in order.\n .\n └── root\n ├── __init__.py\n ├── sub1\n │ ├── __init__.py\n │ ├── conftest.py\n │ └── test_1.py\n └── sub2\n ├── __init__.py\n ├── conftest.py\n └── test_2.py\n ","endLoc":3941,"header":"def test_multiple_packages(self, testdir)","id":2820,"name":"test_multiple_packages","nodeType":"Function","startLoc":3875,"text":"def test_multiple_packages(self, testdir):\n \"\"\"Complex test involving multiple package fixtures. Make sure teardowns\n are executed in order.\n .\n └── root\n ├── __init__.py\n ├── sub1\n │ ├── __init__.py\n │ ├── conftest.py\n │ └── test_1.py\n └── sub2\n ├── __init__.py\n ├── conftest.py\n └── test_2.py\n \"\"\"\n root = testdir.mkdir(\"root\")\n root.join(\"__init__.py\").write(\"values = []\")\n sub1 = root.mkdir(\"sub1\")\n sub1.ensure(\"__init__.py\")\n sub1.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n from .. import values\n @pytest.fixture(scope=\"package\")\n def fix():\n values.append(\"pre-sub1\")\n yield values\n assert values.pop() == \"pre-sub1\"\n \"\"\"\n )\n )\n sub1.join(\"test_1.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def test_1(fix):\n assert values == [\"pre-sub1\"]\n \"\"\"\n )\n )\n sub2 = root.mkdir(\"sub2\")\n sub2.ensure(\"__init__.py\")\n sub2.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n from .. import values\n @pytest.fixture(scope=\"package\")\n def fix():\n values.append(\"pre-sub2\")\n yield values\n assert values.pop() == \"pre-sub2\"\n \"\"\"\n )\n )\n sub2.join(\"test_2.py\").write(\n textwrap.dedent(\n \"\"\"\\\n from .. import values\n def test_2(fix):\n assert values == [\"pre-sub2\"]\n \"\"\"\n )\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)"},{"col":4,"comment":"null","endLoc":275,"header":"def test_inline_run_sys_modules_snapshot_restore_preserving_modules(\n self, testdir, monkeypatch\n )","id":2821,"name":"test_inline_run_sys_modules_snapshot_restore_preserving_modules","nodeType":"Function","startLoc":264,"text":"def test_inline_run_sys_modules_snapshot_restore_preserving_modules(\n self, testdir, monkeypatch\n ):\n spy_factory = self.spy_factory()\n monkeypatch.setattr(pytester, \"SysModulesSnapshot\", spy_factory)\n test_mod = testdir.makepyfile(\"def test_foo(): pass\")\n testdir.inline_run(str(test_mod))\n spy = spy_factory.instances[0]\n assert not spy._spy_preserve(\"black_knight\")\n assert spy._spy_preserve(\"zope\")\n assert spy._spy_preserve(\"zope.interface\")\n assert spy._spy_preserve(\"zopelicious\")"},{"col":4,"comment":"null","endLoc":466,"header":"def _setup_tree(self, testdir)","id":2822,"name":"_setup_tree","nodeType":"Function","startLoc":405,"text":"def _setup_tree(self, testdir): # for issue616\n # example mostly taken from:\n # https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html\n runner = testdir.mkdir(\"empty\")\n package = testdir.mkdir(\"package\")\n\n package.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def fxtr():\n return \"from-package\"\n \"\"\"\n )\n )\n package.join(\"test_pkgroot.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_pkgroot(fxtr):\n assert fxtr == \"from-package\"\n \"\"\"\n )\n )\n\n swc = package.mkdir(\"swc\")\n swc.join(\"__init__.py\").ensure()\n swc.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def fxtr():\n return \"from-swc\"\n \"\"\"\n )\n )\n swc.join(\"test_with_conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_with_conftest(fxtr):\n assert fxtr == \"from-swc\"\n \"\"\"\n )\n )\n\n snc = package.mkdir(\"snc\")\n snc.join(\"__init__.py\").ensure()\n snc.join(\"test_no_conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_no_conftest(fxtr):\n assert fxtr == \"from-package\" # No local conftest.py, so should\n # use value from parent dir's\n \"\"\"\n )\n )\n print(\"created directory structure:\")\n for x in testdir.tmpdir.visit():\n print(\" \" + x.relto(testdir.tmpdir))\n\n return {\"runner\": runner, \"package\": package, \"swc\": swc, \"snc\": snc}"},{"col":0,"comment":"null","endLoc":39,"header":"def test_coloredlogformatter()","id":2823,"name":"test_coloredlogformatter","nodeType":"Function","startLoc":11,"text":"def test_coloredlogformatter():\n logfmt = \"%(filename)-25s %(lineno)4d %(levelname)-8s %(message)s\"\n\n record = logging.LogRecord(\n name=\"dummy\",\n level=logging.INFO,\n pathname=\"dummypath\",\n lineno=10,\n msg=\"Test Message\",\n args=(),\n exc_info=False,\n )\n\n class ColorConfig(object):\n class option(object):\n pass\n\n tw = py.io.TerminalWriter()\n tw.hasmarkup = True\n formatter = ColoredLevelFormatter(tw, logfmt)\n output = formatter.format(record)\n assert output == (\n \"dummypath 10 \\x1b[32mINFO \\x1b[0m Test Message\"\n )\n\n tw.hasmarkup = False\n formatter = ColoredLevelFormatter(tw, logfmt)\n output = formatter.format(record)\n assert output == (\"dummypath 10 INFO Test Message\")"},{"col":4,"comment":"#616","endLoc":505,"header":"@pytest.mark.parametrize(\n \"chdir,testarg,expect_ntests_passed\",\n [\n # Effective target: package/..\n (\"runner\", \"..\", 3),\n (\"package\", \"..\", 3),\n (\"swc\", \"../..\", 3),\n (\"snc\", \"../..\", 3),\n # Effective target","id":2824,"name":"test_parsefactories_relative_node_ids","nodeType":"Function","startLoc":470,"text":"@pytest.mark.parametrize(\n \"chdir,testarg,expect_ntests_passed\",\n [\n # Effective target: package/..\n (\"runner\", \"..\", 3),\n (\"package\", \"..\", 3),\n (\"swc\", \"../..\", 3),\n (\"snc\", \"../..\", 3),\n # Effective target: package\n (\"runner\", \"../package\", 3),\n (\"package\", \".\", 3),\n (\"swc\", \"..\", 3),\n (\"snc\", \"..\", 3),\n # Effective target: package/swc\n (\"runner\", \"../package/swc\", 1),\n (\"package\", \"./swc\", 1),\n (\"swc\", \".\", 1),\n (\"snc\", \"../swc\", 1),\n # Effective target: package/snc\n (\"runner\", \"../package/snc\", 1),\n (\"package\", \"./snc\", 1),\n (\"swc\", \"../snc\", 1),\n (\"snc\", \".\", 1),\n ],\n )\n def test_parsefactories_relative_node_ids(\n self, testdir, chdir, testarg, expect_ntests_passed\n ):\n \"\"\"#616\"\"\"\n dirs = self._setup_tree(testdir)\n print(\"pytest run in cwd: %s\" % (dirs[chdir].relto(testdir.tmpdir)))\n print(\"pytestarg : %s\" % (testarg))\n print(\"expected pass : %s\" % (expect_ntests_passed))\n with dirs[chdir].as_cwd():\n reprec = testdir.inline_run(testarg, \"-q\", \"--traceconfig\")\n reprec.assertoutcome(passed=expect_ntests_passed)"},{"col":0,"comment":"null","endLoc":44,"header":"def test_getfuncargnames()","id":2825,"name":"test_getfuncargnames","nodeType":"Function","startLoc":14,"text":"def test_getfuncargnames():\n def f():\n pass\n\n assert not fixtures.getfuncargnames(f)\n\n def g(arg):\n pass\n\n assert fixtures.getfuncargnames(g) == (\"arg\",)\n\n def h(arg1, arg2=\"hello\"):\n pass\n\n assert fixtures.getfuncargnames(h) == (\"arg1\",)\n\n def h(arg1, arg2, arg3=\"hello\"):\n pass\n\n assert fixtures.getfuncargnames(h) == (\"arg1\", \"arg2\")\n\n class A(object):\n def f(self, arg1, arg2=\"hello\"):\n pass\n\n @staticmethod\n def static(arg1, arg2):\n pass\n\n assert fixtures.getfuncargnames(A().f) == (\"arg1\",)\n assert fixtures.getfuncargnames(A.static, cls=A) == (\"arg1\", \"arg2\")"},{"col":0,"comment":"null","endLoc":247,"header":"def pytest_report_header(config)","id":2826,"name":"pytest_report_header","nodeType":"Function","startLoc":229,"text":"def pytest_report_header(config):\n lines = []\n if config.option.debug or config.option.traceconfig:\n lines.append(\"using: pytest-%s pylib-%s\" % (pytest.__version__, py.__version__))\n\n verinfo = getpluginversioninfo(config)\n if verinfo:\n lines.extend(verinfo)\n\n if config.option.traceconfig:\n lines.append(\"active plugins:\")\n items = config.pluginmanager.list_name_plugin()\n for name, plugin in items:\n if hasattr(plugin, \"__file__\"):\n r = plugin.__file__\n else:\n r = repr(plugin)\n lines.append(\" %-20s: %s\" % (name, r))\n return lines"},{"col":0,"comment":"null","endLoc":234,"header":"def fix_cache_order(item, argkeys_cache, items_by_argkey)","id":2827,"name":"fix_cache_order","nodeType":"Function","startLoc":231,"text":"def fix_cache_order(item, argkeys_cache, items_by_argkey):\n for scopenum in range(0, scopenum_function):\n for key in argkeys_cache[scopenum].get(item, []):\n items_by_argkey[scopenum][key].appendleft(item)"},{"attributeType":"null","col":0,"comment":"null","endLoc":33,"id":2828,"name":"__all__","nodeType":"Attribute","startLoc":33,"text":"__all__"},{"attributeType":"int","col":0,"comment":"null","endLoc":36,"id":2829,"name":"LOCK_TIMEOUT","nodeType":"Attribute","startLoc":36,"text":"LOCK_TIMEOUT"},{"col":0,"comment":"null","endLoc":90,"header":"def test_conftest_in_nonpkg_with_init(tmpdir, _sys_snapshot)","id":2830,"name":"test_conftest_in_nonpkg_with_init","nodeType":"Function","startLoc":85,"text":"def test_conftest_in_nonpkg_with_init(tmpdir, _sys_snapshot):\n tmpdir.ensure(\"adir-1.0/conftest.py\").write(\"a=1 ; Directory = 3\")\n tmpdir.ensure(\"adir-1.0/b/conftest.py\").write(\"b=2 ; a = 1.5\")\n tmpdir.ensure(\"adir-1.0/b/__init__.py\")\n tmpdir.ensure(\"adir-1.0/__init__.py\")\n ConftestWithSetinitial(tmpdir.join(\"adir-1.0\", \"b\"))"},{"col":0,"comment":"null","endLoc":3645,"header":"def test_pytest_fixture_setup_and_post_finalizer_hook(testdir)","id":2831,"name":"test_pytest_fixture_setup_and_post_finalizer_hook","nodeType":"Function","startLoc":3602,"text":"def test_pytest_fixture_setup_and_post_finalizer_hook(testdir):\n testdir.makeconftest(\n \"\"\"\n from __future__ import print_function\n def pytest_fixture_setup(fixturedef, request):\n print('ROOT setup hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))\n def pytest_fixture_post_finalizer(fixturedef, request):\n print('ROOT finalizer hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))\n \"\"\"\n )\n testdir.makepyfile(\n **{\n \"tests/conftest.py\": \"\"\"\n from __future__ import print_function\n def pytest_fixture_setup(fixturedef, request):\n print('TESTS setup hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))\n def pytest_fixture_post_finalizer(fixturedef, request):\n print('TESTS finalizer hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))\n \"\"\",\n \"tests/test_hooks.py\": \"\"\"\n from __future__ import print_function\n import pytest\n\n @pytest.fixture()\n def my_fixture():\n return 'some'\n\n def test_func(my_fixture):\n print('TEST test_func')\n assert my_fixture == 'some'\n \"\"\",\n }\n )\n result = testdir.runpytest(\"-s\")\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n [\n \"*TESTS setup hook called for my_fixture from test_func*\",\n \"*ROOT setup hook called for my_fixture from test_func*\",\n \"*TEST test_func*\",\n \"*TESTS finalizer hook called for my_fixture from test_func*\",\n \"*ROOT finalizer hook called for my_fixture from test_func*\",\n ]\n )"},{"col":4,"comment":" return the index of the frame/TracebackEntry where recursion\n originates if appropriate, None if no recursion occurred\n ","endLoc":380,"header":"def recursionindex(self)","id":2832,"name":"recursionindex","nodeType":"Function","startLoc":354,"text":"def recursionindex(self):\n \"\"\" return the index of the frame/TracebackEntry where recursion\n originates if appropriate, None if no recursion occurred\n \"\"\"\n cache = {}\n for i, entry in enumerate(self):\n # id for the code.raw is needed to work around\n # the strange metaprogramming in the decorator lib from pypi\n # which generates code objects that have hash/value equality\n # XXX needs a test\n key = entry.frame.code.path, id(entry.frame.code.raw), entry.lineno\n # print \"checking for recursion at\", key\n values = cache.setdefault(key, [])\n if values:\n f = entry.frame\n loc = f.f_locals\n for otherloc in values:\n if f.is_true(\n f.eval(\n co_equal,\n __recursioncache_locals_1=loc,\n __recursioncache_locals_2=otherloc,\n )\n ):\n return i\n values.append(entry.frame.f_locals)\n return None"},{"col":0,"comment":"null","endLoc":99,"header":"def test_doubledash_considered(testdir)","id":2833,"name":"test_doubledash_considered","nodeType":"Function","startLoc":93,"text":"def test_doubledash_considered(testdir):\n conf = testdir.mkdir(\"--option\")\n conf.ensure(\"conftest.py\")\n conftest = PytestPluginManager()\n conftest_setinitial(conftest, [conf.basename, conf.basename])\n values = conftest._getconftestmodules(conf)\n assert len(values) == 1"},{"col":0,"comment":"Check if an error is raised if a fixture function is called directly (#4545)","endLoc":3952,"header":"def test_call_fixture_function_error()","id":2834,"name":"test_call_fixture_function_error","nodeType":"Function","startLoc":3944,"text":"def test_call_fixture_function_error():\n \"\"\"Check if an error is raised if a fixture function is called directly (#4545)\"\"\"\n\n @pytest.fixture\n def fix():\n return 1\n\n with pytest.raises(pytest.fail.Exception):\n assert fix() == 1"},{"col":0,"comment":"Parametrized arguments would be shadowed if a fixture with the same name also exists (#5036)","endLoc":3995,"header":"def test_fixture_param_shadowing(testdir)","id":2836,"name":"test_fixture_param_shadowing","nodeType":"Function","startLoc":3955,"text":"def test_fixture_param_shadowing(testdir):\n \"\"\"Parametrized arguments would be shadowed if a fixture with the same name also exists (#5036)\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=['a', 'b'])\n def argroot(request):\n return request.param\n\n @pytest.fixture\n def arg(argroot):\n return argroot\n\n # This should only be parametrized directly\n @pytest.mark.parametrize(\"arg\", [1])\n def test_direct(arg):\n assert arg == 1\n\n # This should be parametrized based on the fixtures\n def test_normal_fixture(arg):\n assert isinstance(arg, str)\n\n # Indirect should still work:\n\n @pytest.fixture\n def arg2(request):\n return 2*request.param\n\n @pytest.mark.parametrize(\"arg2\", [1], indirect=True)\n def test_indirect(arg2):\n assert arg2 == 2\n \"\"\"\n )\n # Only one test should have run\n result = testdir.runpytest(\"-v\")\n result.assert_outcomes(passed=4)\n result.stdout.fnmatch_lines([\"*::test_direct[[]1[]]*\"])\n result.stdout.fnmatch_lines([\"*::test_normal_fixture[[]a[]]*\"])\n result.stdout.fnmatch_lines([\"*::test_normal_fixture[[]b[]]*\"])\n result.stdout.fnmatch_lines([\"*::test_indirect[[]1[]]*\"])"},{"col":0,"comment":"Convert a warnings.WarningMessage to a string.\n\n This takes lot of unicode shenaningans into account for Python 2.\n When Python 2 support is dropped this function can be greatly simplified.\n ","endLoc":136,"header":"def warning_record_to_str(warning_message)","id":2837,"name":"warning_record_to_str","nodeType":"Function","startLoc":106,"text":"def warning_record_to_str(warning_message):\n \"\"\"Convert a warnings.WarningMessage to a string.\n\n This takes lot of unicode shenaningans into account for Python 2.\n When Python 2 support is dropped this function can be greatly simplified.\n \"\"\"\n warn_msg = warning_message.message\n unicode_warning = False\n if compat._PY2 and any(isinstance(m, compat.UNICODE_TYPES) for m in warn_msg.args):\n new_args = []\n for m in warn_msg.args:\n new_args.append(\n compat.ascii_escaped(m) if isinstance(m, compat.UNICODE_TYPES) else m\n )\n unicode_warning = list(warn_msg.args) != new_args\n warn_msg.args = new_args\n\n msg = warnings.formatwarning(\n warn_msg,\n warning_message.category,\n warning_message.filename,\n warning_message.lineno,\n warning_message.line,\n )\n if unicode_warning:\n warnings.warn(\n \"Warning is using unicode non convertible to ascii, \"\n \"converting to a safe representation:\\n {!r}\".format(compat.safe_str(msg)),\n UnicodeWarning,\n )\n return msg"},{"col":4,"comment":"null","endLoc":289,"header":"def test_external_test_module_imports_not_cleaned_up(self, testdir)","id":2838,"name":"test_external_test_module_imports_not_cleaned_up","nodeType":"Function","startLoc":277,"text":"def test_external_test_module_imports_not_cleaned_up(self, testdir):\n testdir.syspathinsert()\n testdir.makepyfile(imported=\"data = 'you son of a silly person'\")\n import imported\n\n test_mod = testdir.makepyfile(\n \"\"\"\n def test_foo():\n import imported\n imported.data = 42\"\"\"\n )\n testdir.inline_run(str(test_mod))\n assert imported.data == 42"},{"attributeType":"methodcaller","col":0,"comment":"null","endLoc":38,"id":2839,"name":"get_lock_path","nodeType":"Attribute","startLoc":38,"text":"get_lock_path"},{"attributeType":"function | function | function | function | function | function","col":4,"comment":"null","endLoc":140,"id":2840,"name":"_max","nodeType":"Attribute","startLoc":140,"text":"_max"},{"col":0,"comment":"","endLoc":2,"header":"pathlib.py#","id":2841,"name":"","nodeType":"Function","startLoc":2,"text":"if PY36:\n from pathlib import Path, PurePath\nelse:\n from pathlib2 import Path, PurePath\n\n__all__ = [\"Path\", \"PurePath\"]\n\nLOCK_TIMEOUT = 60 * 60 * 3\n\nget_lock_path = operator.methodcaller(\"joinpath\", \".lock\")\n\nif six.PY2:\n\n def _max(iterable, default):\n \"\"\"needed due to python2.7 lacking the default argument for max\"\"\"\n return reduce(max, iterable, default)\n\n\nelse:\n _max = max"},{"fileName":"test_pathlib.py","filePath":"testing","id":2843,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport sys\n\nimport py\n\nimport pytest\nfrom _pytest.pathlib import fnmatch_ex\nfrom _pytest.pathlib import get_lock_path\nfrom _pytest.pathlib import maybe_delete_a_numbered_dir\nfrom _pytest.pathlib import Path\n\n\nclass TestPort:\n \"\"\"Test that our port of py.common.FNMatcher (fnmatch_ex) produces the same results as the\n original py.path.local.fnmatch method.\n \"\"\"\n\n @pytest.fixture(params=[\"pathlib\", \"py.path\"])\n def match(self, request):\n if request.param == \"py.path\":\n\n def match_(pattern, path):\n return py.path.local(path).fnmatch(pattern)\n\n else:\n assert request.param == \"pathlib\"\n\n def match_(pattern, path):\n return fnmatch_ex(pattern, path)\n\n return match_\n\n if sys.platform == \"win32\":\n drv1 = \"c:\"\n drv2 = \"d:\"\n else:\n drv1 = \"/c\"\n drv2 = \"/d\"\n\n @pytest.mark.parametrize(\n \"pattern, path\",\n [\n (\"*.py\", \"foo.py\"),\n (\"*.py\", \"bar/foo.py\"),\n (\"test_*.py\", \"foo/test_foo.py\"),\n (\"tests/*.py\", \"tests/foo.py\"),\n (drv1 + \"/*.py\", drv1 + \"/foo.py\"),\n (drv1 + \"/foo/*.py\", drv1 + \"/foo/foo.py\"),\n (\"tests/**/test*.py\", \"tests/foo/test_foo.py\"),\n (\"tests/**/doc/test*.py\", \"tests/foo/bar/doc/test_foo.py\"),\n (\"tests/**/doc/**/test*.py\", \"tests/foo/doc/bar/test_foo.py\"),\n ],\n )\n def test_matching(self, match, pattern, path):\n assert match(pattern, path)\n\n @pytest.mark.parametrize(\n \"pattern, path\",\n [\n (\"*.py\", \"foo.pyc\"),\n (\"*.py\", \"foo/foo.pyc\"),\n (\"tests/*.py\", \"foo/foo.py\"),\n (drv1 + \"/*.py\", drv2 + \"/foo.py\"),\n (drv1 + \"/foo/*.py\", drv2 + \"/foo/foo.py\"),\n (\"tests/**/test*.py\", \"tests/foo.py\"),\n (\"tests/**/test*.py\", \"foo/test_foo.py\"),\n (\"tests/**/doc/test*.py\", \"tests/foo/bar/doc/foo.py\"),\n (\"tests/**/doc/test*.py\", \"tests/foo/bar/test_foo.py\"),\n ],\n )\n def test_not_matching(self, match, pattern, path):\n assert not match(pattern, path)\n\n\ndef test_access_denied_during_cleanup(tmp_path, monkeypatch):\n \"\"\"Ensure that deleting a numbered dir does not fail because of OSErrors (#4262).\"\"\"\n path = tmp_path / \"temp-1\"\n path.mkdir()\n\n def renamed_failed(*args):\n raise OSError(\"access denied\")\n\n monkeypatch.setattr(Path, \"rename\", renamed_failed)\n\n lock_path = get_lock_path(path)\n maybe_delete_a_numbered_dir(path)\n assert not lock_path.is_file()\n"},{"className":"TestPort","col":0,"comment":"Test that our port of py.common.FNMatcher (fnmatch_ex) produces the same results as the\n original py.path.local.fnmatch method.\n ","endLoc":72,"id":2844,"nodeType":"Class","startLoc":13,"text":"class TestPort:\n \"\"\"Test that our port of py.common.FNMatcher (fnmatch_ex) produces the same results as the\n original py.path.local.fnmatch method.\n \"\"\"\n\n @pytest.fixture(params=[\"pathlib\", \"py.path\"])\n def match(self, request):\n if request.param == \"py.path\":\n\n def match_(pattern, path):\n return py.path.local(path).fnmatch(pattern)\n\n else:\n assert request.param == \"pathlib\"\n\n def match_(pattern, path):\n return fnmatch_ex(pattern, path)\n\n return match_\n\n if sys.platform == \"win32\":\n drv1 = \"c:\"\n drv2 = \"d:\"\n else:\n drv1 = \"/c\"\n drv2 = \"/d\"\n\n @pytest.mark.parametrize(\n \"pattern, path\",\n [\n (\"*.py\", \"foo.py\"),\n (\"*.py\", \"bar/foo.py\"),\n (\"test_*.py\", \"foo/test_foo.py\"),\n (\"tests/*.py\", \"tests/foo.py\"),\n (drv1 + \"/*.py\", drv1 + \"/foo.py\"),\n (drv1 + \"/foo/*.py\", drv1 + \"/foo/foo.py\"),\n (\"tests/**/test*.py\", \"tests/foo/test_foo.py\"),\n (\"tests/**/doc/test*.py\", \"tests/foo/bar/doc/test_foo.py\"),\n (\"tests/**/doc/**/test*.py\", \"tests/foo/doc/bar/test_foo.py\"),\n ],\n )\n def test_matching(self, match, pattern, path):\n assert match(pattern, path)\n\n @pytest.mark.parametrize(\n \"pattern, path\",\n [\n (\"*.py\", \"foo.pyc\"),\n (\"*.py\", \"foo/foo.pyc\"),\n (\"tests/*.py\", \"foo/foo.py\"),\n (drv1 + \"/*.py\", drv2 + \"/foo.py\"),\n (drv1 + \"/foo/*.py\", drv2 + \"/foo/foo.py\"),\n (\"tests/**/test*.py\", \"tests/foo.py\"),\n (\"tests/**/test*.py\", \"foo/test_foo.py\"),\n (\"tests/**/doc/test*.py\", \"tests/foo/bar/doc/foo.py\"),\n (\"tests/**/doc/test*.py\", \"tests/foo/bar/test_foo.py\"),\n ],\n )\n def test_not_matching(self, match, pattern, path):\n assert not match(pattern, path)"},{"col":4,"comment":"null","endLoc":31,"header":"@pytest.fixture(params=[\"pathlib\", \"py.path\"])\n def match(self, request)","id":2845,"name":"match","nodeType":"Function","startLoc":18,"text":"@pytest.fixture(params=[\"pathlib\", \"py.path\"])\n def match(self, request):\n if request.param == \"py.path\":\n\n def match_(pattern, path):\n return py.path.local(path).fnmatch(pattern)\n\n else:\n assert request.param == \"pathlib\"\n\n def match_(pattern, path):\n return fnmatch_ex(pattern, path)\n\n return match_"},{"attributeType":"list","col":0,"comment":"null","endLoc":214,"id":2846,"name":"conftest_options","nodeType":"Attribute","startLoc":214,"text":"conftest_options"},{"col":0,"comment":"","endLoc":2,"header":"helpconfig.py#","id":2847,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" version info, help messages, tracing configuration. \"\"\"\n\nconftest_options = [(\"pytest_plugins\", \"list of plugin names to load\")]"},{"col":0,"comment":"null","endLoc":111,"header":"def test_issue151_load_all_conftests(testdir)","id":2848,"name":"test_issue151_load_all_conftests","nodeType":"Function","startLoc":102,"text":"def test_issue151_load_all_conftests(testdir):\n names = \"code proj src\".split()\n for name in names:\n p = testdir.mkdir(name)\n p.ensure(\"conftest.py\")\n\n conftest = PytestPluginManager()\n conftest_setinitial(conftest, names)\n d = list(conftest._conftestpath2mod.values())\n assert len(d) == len(names)"},{"col":4,"comment":"null","endLoc":55,"header":"@pytest.mark.parametrize(\n \"pattern, path\",\n [\n (\"*.py\", \"foo.py\"),\n (\"*.py\", \"bar/foo.py\"),\n (\"test_*.py\", \"foo/test_foo.py\"),\n (\"tests/*.py\", \"tests/foo.py\"),\n (drv1 + \"/*.py\", drv1 + \"/foo.py\"),\n (drv1 + \"/foo/*.py\", drv1 + \"/foo/foo.py\"),\n (\"tests/**/test*.py\", \"tests/foo/test_foo.py\"),\n (\"tests/**/doc/test*.py\", \"tests/foo/bar/doc/test_foo.py\"),\n (\"tests/**/doc/**/test*.py\", \"tests/foo/doc/bar/test_foo.py\"),\n ],\n )\n def test_matching(self, match, pattern, path)","id":2849,"name":"test_matching","nodeType":"Function","startLoc":40,"text":"@pytest.mark.parametrize(\n \"pattern, path\",\n [\n (\"*.py\", \"foo.py\"),\n (\"*.py\", \"bar/foo.py\"),\n (\"test_*.py\", \"foo/test_foo.py\"),\n (\"tests/*.py\", \"tests/foo.py\"),\n (drv1 + \"/*.py\", drv1 + \"/foo.py\"),\n (drv1 + \"/foo/*.py\", drv1 + \"/foo/foo.py\"),\n (\"tests/**/test*.py\", \"tests/foo/test_foo.py\"),\n (\"tests/**/doc/test*.py\", \"tests/foo/bar/doc/test_foo.py\"),\n (\"tests/**/doc/**/test*.py\", \"tests/foo/doc/bar/test_foo.py\"),\n ],\n )\n def test_matching(self, match, pattern, path):\n assert match(pattern, path)"},{"id":2850,"name":"xunit_setup.rst","nodeType":"TextFile","path":"doc/en","text":"\n.. _`classic xunit`:\n.. _xunitsetup:\n\nclassic xunit-style setup\n========================================\n\nThis section describes a classic and popular way how you can implement\nfixtures (setup and teardown test state) on a per-module/class/function basis.\n\n\n.. note::\n\n While these setup/teardown methods are simple and familiar to those\n coming from a ``unittest`` or nose ``background``, you may also consider\n using pytest's more powerful :ref:`fixture mechanism\n ` which leverages the concept of dependency injection, allowing\n for a more modular and more scalable approach for managing test state,\n especially for larger projects and for functional testing. You can\n mix both fixture mechanisms in the same file but\n test methods of ``unittest.TestCase`` subclasses\n cannot receive fixture arguments.\n\n\nModule level setup/teardown\n--------------------------------------\n\nIf you have multiple test functions and test classes in a single\nmodule you can optionally implement the following fixture methods\nwhich will usually be called once for all the functions::\n\n def setup_module(module):\n \"\"\" setup any state specific to the execution of the given module.\"\"\"\n\n def teardown_module(module):\n \"\"\" teardown any state that was previously setup with a setup_module\n method.\n \"\"\"\n\nAs of pytest-3.0, the ``module`` parameter is optional.\n\nClass level setup/teardown\n----------------------------------\n\nSimilarly, the following methods are called at class level before\nand after all test methods of the class are called::\n\n @classmethod\n def setup_class(cls):\n \"\"\" setup any state specific to the execution of the given class (which\n usually contains tests).\n \"\"\"\n\n @classmethod\n def teardown_class(cls):\n \"\"\" teardown any state that was previously setup with a call to\n setup_class.\n \"\"\"\n\nMethod and function level setup/teardown\n-----------------------------------------------\n\nSimilarly, the following methods are called around each method invocation::\n\n def setup_method(self, method):\n \"\"\" setup any state tied to the execution of the given method in a\n class. setup_method is invoked for every test method of a class.\n \"\"\"\n\n def teardown_method(self, method):\n \"\"\" teardown any state that was previously setup with a setup_method\n call.\n \"\"\"\n\nAs of pytest-3.0, the ``method`` parameter is optional.\n\nIf you would rather define test functions directly at module level\nyou can also use the following functions to implement fixtures::\n\n def setup_function(function):\n \"\"\" setup any state tied to the execution of the given function.\n Invoked for every test function in the module.\n \"\"\"\n\n def teardown_function(function):\n \"\"\" teardown any state that was previously setup with a setup_function\n call.\n \"\"\"\n\nAs of pytest-3.0, the ``function`` parameter is optional.\n\nRemarks:\n\n* It is possible for setup/teardown pairs to be invoked multiple times\n per testing process.\n\n* teardown functions are not called if the corresponding setup function existed\n and failed/was skipped.\n\n* Prior to pytest-4.2, xunit-style functions did not obey the scope rules of fixtures, so\n it was possible, for example, for a ``setup_method`` to be called before a\n session-scoped autouse fixture.\n\n Now the xunit-style functions are integrated with the fixture mechanism and obey the proper\n scope rules of fixtures involved in the call.\n\n.. _`unittest.py module`: http://docs.python.org/library/unittest.html\n"},{"id":2851,"name":"backwards-compatibility.rst","nodeType":"TextFile","path":"doc/en","text":".. _backwards-compatibility:\n\nBackwards Compatibility Policy\n==============================\n\nKeeping backwards compatibility has a very high priority in the pytest project. Although we have deprecated functionality over the years, most of it is still supported. All deprecations in pytest were done because simpler or more efficient ways of accomplishing the same tasks have emerged, making the old way of doing things unnecessary.\n\nWith the pytest 3.0 release we introduced a clear communication scheme for when we will actually remove the old busted joint and politely ask you to use the new hotness instead, while giving you enough time to adjust your tests or raise concerns if there are valid reasons to keep deprecated functionality around.\n\nTo communicate changes we issue deprecation warnings using a custom warning hierarchy (see :ref:`internal-warnings`). These warnings may be suppressed using the standard means: ``-W`` command-line flag or ``filterwarnings`` ini options (see :ref:`warnings`), but we suggest to use these sparingly and temporarily, and heed the warnings when possible.\n\nWe will only start the removal of deprecated functionality in major releases (e.g. if we deprecate something in 3.0 we will start to remove it in 4.0), and keep it around for at least two minor releases (e.g. if we deprecate something in 3.9 and 4.0 is the next release, we start to remove it in 5.0, not in 4.0).\n\nWhen the deprecation expires (e.g. 4.0 is released), we won't remove the deprecated functionality immediately, but will use the standard warning filters to turn them into **errors** by default. This approach makes it explicit that removal is imminent, and still gives you time to turn the deprecated feature into a warning instead of an error so it can be dealt with in your own time. In the next minor release (e.g. 4.1), the feature will be effectively removed.\n\n\nDeprecation Roadmap\n-------------------\n\nFeatures currently deprecated and removed in previous releases can be found in :ref:`deprecations`.\n\nWe track future deprecation and removal of features using milestones and the `deprecation `_ and `removal `_ labels on GitHub.\n"},{"attributeType":"TracebackEntry","col":4,"comment":"null","endLoc":284,"id":2852,"name":"Entry","nodeType":"Attribute","startLoc":284,"text":"Entry"},{"id":2853,"name":"getting-started.rst","nodeType":"TextFile","path":"doc/en","text":"Installation and Getting Started\n===================================\n\n**Pythons**: Python 2.7, 3.4, 3.5, 3.6, 3.7, Jython, PyPy-2.3\n\n**Platforms**: Unix/Posix and Windows\n\n**PyPI package name**: `pytest `_\n\n**Documentation as PDF**: `download latest `_\n\n``pytest`` is a framework that makes building simple and scalable tests easy. Tests are expressive and readable—no boilerplate code required. Get started in minutes with a small unit test or complex functional test for your application or library.\n\n.. _`getstarted`:\n.. _`installation`:\n\nInstall ``pytest``\n----------------------------------------\n\n1. Run the following command in your command line:\n\n.. code-block:: bash\n\n pip install -U pytest\n\n2. Check that you installed the correct version:\n\n.. code-block:: bash\n\n $ pytest --version\n This is pytest version 4.x.y, imported from $PYTHON_PREFIX/lib/python3.6/site-packages/pytest.py\n\n.. _`simpletest`:\n\nCreate your first test\n----------------------------------------------------------\n\nCreate a simple test function with just four lines of code::\n\n # content of test_sample.py\n def func(x):\n return x + 1\n\n def test_answer():\n assert func(3) == 5\n\nThat’s it. You can now execute the test function:\n\n.. code-block:: pytest\n\n $ pytest\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 1 item\n\n test_sample.py F [100%]\n\n ================================= FAILURES =================================\n _______________________________ test_answer ________________________________\n\n def test_answer():\n > assert func(3) == 5\n E assert 4 == 5\n E + where 4 = func(3)\n\n test_sample.py:5: AssertionError\n ========================= 1 failed in 0.12 seconds =========================\n\nThis test returns a failure report because ``func(3)`` does not return ``5``.\n\n.. note::\n\n You can use the ``assert`` statement to verify test expectations. pytest’s `Advanced assertion introspection `_ will intelligently report intermediate values of the assert expression so you can avoid the many names `of JUnit legacy methods `_.\n\nRun multiple tests\n----------------------------------------------------------\n\n``pytest`` will run all files of the form test_*.py or \\*_test.py in the current directory and its subdirectories. More generally, it follows :ref:`standard test discovery rules `.\n\n\nAssert that a certain exception is raised\n--------------------------------------------------------------\n\nUse the :ref:`raises ` helper to assert that some code raises an exception::\n\n # content of test_sysexit.py\n import pytest\n def f():\n raise SystemExit(1)\n\n def test_mytest():\n with pytest.raises(SystemExit):\n f()\n\nExecute the test function with “quiet” reporting mode:\n\n.. code-block:: pytest\n\n $ pytest -q test_sysexit.py\n . [100%]\n 1 passed in 0.12 seconds\n\nGroup multiple tests in a class\n--------------------------------------------------------------\n\nOnce you develop multiple tests, you may want to group them into a class. pytest makes it easy to create a class containing more than one test::\n\n # content of test_class.py\n class TestClass(object):\n def test_one(self):\n x = \"this\"\n assert 'h' in x\n\n def test_two(self):\n x = \"hello\"\n assert hasattr(x, 'check')\n\n``pytest`` discovers all tests following its :ref:`Conventions for Python test discovery `, so it finds both ``test_`` prefixed functions. There is no need to subclass anything. We can simply run the module by passing its filename:\n\n.. code-block:: pytest\n\n $ pytest -q test_class.py\n .F [100%]\n ================================= FAILURES =================================\n ____________________________ TestClass.test_two ____________________________\n\n self = \n\n def test_two(self):\n x = \"hello\"\n > assert hasattr(x, 'check')\n E AssertionError: assert False\n E + where False = hasattr('hello', 'check')\n\n test_class.py:8: AssertionError\n 1 failed, 1 passed in 0.12 seconds\n\nThe first test passed and the second failed. You can easily see the intermediate values in the assertion to help you understand the reason for the failure.\n\nRequest a unique temporary directory for functional tests\n--------------------------------------------------------------\n\n``pytest`` provides `Builtin fixtures/function arguments `_ to request arbitrary resources, like a unique temporary directory::\n\n # content of test_tmpdir.py\n def test_needsfiles(tmpdir):\n print(tmpdir)\n assert 0\n\nList the name ``tmpdir`` in the test function signature and ``pytest`` will lookup and call a fixture factory to create the resource before performing the test function call. Before the test runs, ``pytest`` creates a unique-per-test-invocation temporary directory:\n\n.. code-block:: pytest\n\n $ pytest -q test_tmpdir.py\n F [100%]\n ================================= FAILURES =================================\n _____________________________ test_needsfiles ______________________________\n\n tmpdir = local('PYTEST_TMPDIR/test_needsfiles0')\n\n def test_needsfiles(tmpdir):\n print(tmpdir)\n > assert 0\n E assert 0\n\n test_tmpdir.py:3: AssertionError\n --------------------------- Captured stdout call ---------------------------\n PYTEST_TMPDIR/test_needsfiles0\n 1 failed in 0.12 seconds\n\nMore info on tmpdir handling is available at :ref:`Temporary directories and files `.\n\nFind out what kind of builtin :ref:`pytest fixtures ` exist with the command:\n\n.. code-block:: bash\n\n pytest --fixtures # shows builtin and custom fixtures\n\nNote that this command omits fixtures with leading ``_`` unless the ``-v`` option is added.\n\nContinue reading\n-------------------------------------\n\nCheck out additional pytest resources to help you customize tests for your unique workflow:\n\n* \":ref:`cmdline`\" for command line invocation examples\n* \":ref:`existingtestsuite`\" for working with pre-existing tests\n* \":ref:`mark`\" for information on the ``pytest.mark`` mechanism\n* \":ref:`fixtures`\" for providing a functional baseline to your tests\n* \":ref:`plugins`\" for managing and writing plugins\n* \":ref:`goodpractices`\" for virtualenv and test layouts\n\n.. include:: links.inc\n"},{"id":2854,"name":"simple.rst","nodeType":"TextFile","path":"doc/en/example","text":"\n\nBasic patterns and examples\n==========================================================\n\n.. _request example:\n\nPass different values to a test function, depending on command line options\n----------------------------------------------------------------------------\n\n.. regendoc:wipe\n\nSuppose we want to write a test that depends on a command line option.\nHere is a basic pattern to achieve this:\n\n.. code-block:: python\n\n # content of test_sample.py\n def test_answer(cmdopt):\n if cmdopt == \"type1\":\n print(\"first\")\n elif cmdopt == \"type2\":\n print(\"second\")\n assert 0 # to see what was printed\n\n\nFor this to work we need to add a command line option and\nprovide the ``cmdopt`` through a :ref:`fixture function `:\n\n.. code-block:: python\n\n # content of conftest.py\n import pytest\n\n\n def pytest_addoption(parser):\n parser.addoption(\n \"--cmdopt\", action=\"store\", default=\"type1\", help=\"my option: type1 or type2\"\n )\n\n\n @pytest.fixture\n def cmdopt(request):\n return request.config.getoption(\"--cmdopt\")\n\nLet's run this without supplying our new option:\n\n.. code-block:: pytest\n\n $ pytest -q test_sample.py\n F [100%]\n ================================= FAILURES =================================\n _______________________________ test_answer ________________________________\n\n cmdopt = 'type1'\n\n def test_answer(cmdopt):\n if cmdopt == \"type1\":\n print(\"first\")\n elif cmdopt == \"type2\":\n print(\"second\")\n > assert 0 # to see what was printed\n E assert 0\n\n test_sample.py:6: AssertionError\n --------------------------- Captured stdout call ---------------------------\n first\n 1 failed in 0.12 seconds\n\nAnd now with supplying a command line option:\n\n.. code-block:: pytest\n\n $ pytest -q --cmdopt=type2\n F [100%]\n ================================= FAILURES =================================\n _______________________________ test_answer ________________________________\n\n cmdopt = 'type2'\n\n def test_answer(cmdopt):\n if cmdopt == \"type1\":\n print(\"first\")\n elif cmdopt == \"type2\":\n print(\"second\")\n > assert 0 # to see what was printed\n E assert 0\n\n test_sample.py:6: AssertionError\n --------------------------- Captured stdout call ---------------------------\n second\n 1 failed in 0.12 seconds\n\nYou can see that the command line option arrived in our test. This\ncompletes the basic pattern. However, one often rather wants to process\ncommand line options outside of the test and rather pass in different or\nmore complex objects.\n\nDynamically adding command line options\n--------------------------------------------------------------\n\n.. regendoc:wipe\n\nThrough :confval:`addopts` you can statically add command line\noptions for your project. You can also dynamically modify\nthe command line arguments before they get processed:\n\n.. code-block:: python\n\n # setuptools plugin\n import sys\n\n\n def pytest_load_initial_conftests(args):\n if \"xdist\" in sys.modules: # pytest-xdist plugin\n import multiprocessing\n\n num = max(multiprocessing.cpu_count() / 2, 1)\n args[:] = [\"-n\", str(num)] + args\n\nIf you have the `xdist plugin `_ installed\nyou will now always perform test runs using a number\nof subprocesses close to your CPU. Running in an empty\ndirectory with the above conftest.py:\n\n.. code-block:: pytest\n\n $ pytest\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 0 items\n\n ======================= no tests ran in 0.12 seconds =======================\n\n.. _`excontrolskip`:\n\nControl skipping of tests according to command line option\n--------------------------------------------------------------\n\n.. regendoc:wipe\n\nHere is a ``conftest.py`` file adding a ``--runslow`` command\nline option to control skipping of ``pytest.mark.slow`` marked tests:\n\n.. code-block:: python\n\n # content of conftest.py\n\n import pytest\n\n\n def pytest_addoption(parser):\n parser.addoption(\n \"--runslow\", action=\"store_true\", default=False, help=\"run slow tests\"\n )\n\n\n def pytest_collection_modifyitems(config, items):\n if config.getoption(\"--runslow\"):\n # --runslow given in cli: do not skip slow tests\n return\n skip_slow = pytest.mark.skip(reason=\"need --runslow option to run\")\n for item in items:\n if \"slow\" in item.keywords:\n item.add_marker(skip_slow)\n\nWe can now write a test module like this:\n\n.. code-block:: python\n\n # content of test_module.py\n import pytest\n\n\n def test_func_fast():\n pass\n\n\n @pytest.mark.slow\n def test_func_slow():\n pass\n\nand when running it will see a skipped \"slow\" test:\n\n.. code-block:: pytest\n\n $ pytest -rs # \"-rs\" means report details on the little 's'\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 2 items\n\n test_module.py .s [100%]\n\n ========================= short test summary info ==========================\n SKIPPED [1] test_module.py:8: need --runslow option to run\n =================== 1 passed, 1 skipped in 0.12 seconds ====================\n\nOr run it including the ``slow`` marked test:\n\n.. code-block:: pytest\n\n $ pytest --runslow\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 2 items\n\n test_module.py .. [100%]\n\n ========================= 2 passed in 0.12 seconds =========================\n\nWriting well integrated assertion helpers\n--------------------------------------------------\n\n.. regendoc:wipe\n\nIf you have a test helper function called from a test you can\nuse the ``pytest.fail`` marker to fail a test with a certain message.\nThe test support function will not show up in the traceback if you\nset the ``__tracebackhide__`` option somewhere in the helper function.\nExample:\n\n.. code-block:: python\n\n # content of test_checkconfig.py\n import pytest\n\n\n def checkconfig(x):\n __tracebackhide__ = True\n if not hasattr(x, \"config\"):\n pytest.fail(\"not configured: %s\" % (x,))\n\n\n def test_something():\n checkconfig(42)\n\nThe ``__tracebackhide__`` setting influences ``pytest`` showing\nof tracebacks: the ``checkconfig`` function will not be shown\nunless the ``--full-trace`` command line option is specified.\nLet's run our little function:\n\n.. code-block:: pytest\n\n $ pytest -q test_checkconfig.py\n F [100%]\n ================================= FAILURES =================================\n ______________________________ test_something ______________________________\n\n def test_something():\n > checkconfig(42)\n E Failed: not configured: 42\n\n test_checkconfig.py:11: Failed\n 1 failed in 0.12 seconds\n\nIf you only want to hide certain exceptions, you can set ``__tracebackhide__``\nto a callable which gets the ``ExceptionInfo`` object. You can for example use\nthis to make sure unexpected exception types aren't hidden:\n\n.. code-block:: python\n\n import operator\n import pytest\n\n\n class ConfigException(Exception):\n pass\n\n\n def checkconfig(x):\n __tracebackhide__ = operator.methodcaller(\"errisinstance\", ConfigException)\n if not hasattr(x, \"config\"):\n raise ConfigException(\"not configured: %s\" % (x,))\n\n\n def test_something():\n checkconfig(42)\n\nThis will avoid hiding the exception traceback on unrelated exceptions (i.e.\nbugs in assertion helpers).\n\n\nDetect if running from within a pytest run\n--------------------------------------------------------------\n\n.. regendoc:wipe\n\nUsually it is a bad idea to make application code\nbehave differently if called from a test. But if you\nabsolutely must find out if your application code is\nrunning from a test you can do something like this:\n\n.. code-block:: python\n\n # content of conftest.py\n\n\n def pytest_configure(config):\n import sys\n\n sys._called_from_test = True\n\n\n def pytest_unconfigure(config):\n import sys\n\n del sys._called_from_test\n\nand then check for the ``sys._called_from_test`` flag:\n\n.. code-block:: python\n\n if hasattr(sys, \"_called_from_test\"):\n # called from within a test run\n ...\n else:\n # called \"normally\"\n ...\n\naccordingly in your application. It's also a good idea\nto use your own application module rather than ``sys``\nfor handling flag.\n\nAdding info to test report header\n--------------------------------------------------------------\n\n.. regendoc:wipe\n\nIt's easy to present extra information in a ``pytest`` run:\n\n.. code-block:: python\n\n # content of conftest.py\n\n\n def pytest_report_header(config):\n return \"project deps: mylib-1.1\"\n\nwhich will add the string to the test header accordingly:\n\n.. code-block:: pytest\n\n $ pytest\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n project deps: mylib-1.1\n rootdir: $REGENDOC_TMPDIR\n collected 0 items\n\n ======================= no tests ran in 0.12 seconds =======================\n\n.. regendoc:wipe\n\nIt is also possible to return a list of strings which will be considered as several\nlines of information. You may consider ``config.getoption('verbose')`` in order to\ndisplay more information if applicable:\n\n.. code-block:: python\n\n # content of conftest.py\n\n\n def pytest_report_header(config):\n if config.getoption(\"verbose\") > 0:\n return [\"info1: did you know that ...\", \"did you?\"]\n\nwhich will add info only when run with \"--v\":\n\n.. code-block:: pytest\n\n $ pytest -v\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python\n cachedir: $PYTHON_PREFIX/.pytest_cache\n info1: did you know that ...\n did you?\n rootdir: $REGENDOC_TMPDIR\n collecting ... collected 0 items\n\n ======================= no tests ran in 0.12 seconds =======================\n\nand nothing when run plainly:\n\n.. code-block:: pytest\n\n $ pytest\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 0 items\n\n ======================= no tests ran in 0.12 seconds =======================\n\nprofiling test duration\n--------------------------\n\n.. regendoc:wipe\n\n.. versionadded: 2.2\n\nIf you have a slow running large test suite you might want to find\nout which tests are the slowest. Let's make an artificial test suite:\n\n.. code-block:: python\n\n # content of test_some_are_slow.py\n import time\n\n\n def test_funcfast():\n time.sleep(0.1)\n\n\n def test_funcslow1():\n time.sleep(0.2)\n\n\n def test_funcslow2():\n time.sleep(0.3)\n\nNow we can profile which test functions execute the slowest:\n\n.. code-block:: pytest\n\n $ pytest --durations=3\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 3 items\n\n test_some_are_slow.py ... [100%]\n\n ========================= slowest 3 test durations =========================\n 0.31s call test_some_are_slow.py::test_funcslow2\n 0.20s call test_some_are_slow.py::test_funcslow1\n 0.10s call test_some_are_slow.py::test_funcfast\n ========================= 3 passed in 0.12 seconds =========================\n\nincremental testing - test steps\n---------------------------------------------------\n\n.. regendoc:wipe\n\nSometimes you may have a testing situation which consists of a series\nof test steps. If one step fails it makes no sense to execute further\nsteps as they are all expected to fail anyway and their tracebacks\nadd no insight. Here is a simple ``conftest.py`` file which introduces\nan ``incremental`` marker which is to be used on classes:\n\n.. code-block:: python\n\n # content of conftest.py\n\n import pytest\n\n\n def pytest_runtest_makereport(item, call):\n if \"incremental\" in item.keywords:\n if call.excinfo is not None:\n parent = item.parent\n parent._previousfailed = item\n\n\n def pytest_runtest_setup(item):\n if \"incremental\" in item.keywords:\n previousfailed = getattr(item.parent, \"_previousfailed\", None)\n if previousfailed is not None:\n pytest.xfail(\"previous test failed (%s)\" % previousfailed.name)\n\nThese two hook implementations work together to abort incremental-marked\ntests in a class. Here is a test module example:\n\n.. code-block:: python\n\n # content of test_step.py\n\n import pytest\n\n\n @pytest.mark.incremental\n class TestUserHandling(object):\n def test_login(self):\n pass\n\n def test_modification(self):\n assert 0\n\n def test_deletion(self):\n pass\n\n\n def test_normal():\n pass\n\nIf we run this:\n\n.. code-block:: pytest\n\n $ pytest -rx\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 4 items\n\n test_step.py .Fx. [100%]\n\n ================================= FAILURES =================================\n ____________________ TestUserHandling.test_modification ____________________\n\n self = \n\n def test_modification(self):\n > assert 0\n E assert 0\n\n test_step.py:11: AssertionError\n ========================= short test summary info ==========================\n XFAIL test_step.py::TestUserHandling::test_deletion\n reason: previous test failed (test_modification)\n ============== 1 failed, 2 passed, 1 xfailed in 0.12 seconds ===============\n\nWe'll see that ``test_deletion`` was not executed because ``test_modification``\nfailed. It is reported as an \"expected failure\".\n\n\nPackage/Directory-level fixtures (setups)\n-------------------------------------------------------\n\nIf you have nested test directories, you can have per-directory fixture scopes\nby placing fixture functions in a ``conftest.py`` file in that directory\nYou can use all types of fixtures including :ref:`autouse fixtures\n` which are the equivalent of xUnit's setup/teardown\nconcept. It's however recommended to have explicit fixture references in your\ntests or test classes rather than relying on implicitly executing\nsetup/teardown functions, especially if they are far away from the actual tests.\n\nHere is an example for making a ``db`` fixture available in a directory:\n\n.. code-block:: python\n\n # content of a/conftest.py\n import pytest\n\n\n class DB(object):\n pass\n\n\n @pytest.fixture(scope=\"session\")\n def db():\n return DB()\n\nand then a test module in that directory:\n\n.. code-block:: python\n\n # content of a/test_db.py\n def test_a1(db):\n assert 0, db # to show value\n\nanother test module:\n\n.. code-block:: python\n\n # content of a/test_db2.py\n def test_a2(db):\n assert 0, db # to show value\n\nand then a module in a sister directory which will not see\nthe ``db`` fixture:\n\n.. code-block:: python\n\n # content of b/test_error.py\n def test_root(db): # no db here, will error out\n pass\n\nWe can run this:\n\n.. code-block:: pytest\n\n $ pytest\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 7 items\n\n test_step.py .Fx. [ 57%]\n a/test_db.py F [ 71%]\n a/test_db2.py F [ 85%]\n b/test_error.py E [100%]\n\n ================================== ERRORS ==================================\n _______________________ ERROR at setup of test_root ________________________\n file $REGENDOC_TMPDIR/b/test_error.py, line 1\n def test_root(db): # no db here, will error out\n E fixture 'db' not found\n > available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n > use 'pytest --fixtures [testpath]' for help on them.\n\n $REGENDOC_TMPDIR/b/test_error.py:1\n ================================= FAILURES =================================\n ____________________ TestUserHandling.test_modification ____________________\n\n self = \n\n def test_modification(self):\n > assert 0\n E assert 0\n\n test_step.py:11: AssertionError\n _________________________________ test_a1 __________________________________\n\n db = \n\n def test_a1(db):\n > assert 0, db # to show value\n E AssertionError: \n E assert 0\n\n a/test_db.py:2: AssertionError\n _________________________________ test_a2 __________________________________\n\n db = \n\n def test_a2(db):\n > assert 0, db # to show value\n E AssertionError: \n E assert 0\n\n a/test_db2.py:2: AssertionError\n ========== 3 failed, 2 passed, 1 xfailed, 1 error in 0.12 seconds ==========\n\nThe two test modules in the ``a`` directory see the same ``db`` fixture instance\nwhile the one test in the sister-directory ``b`` doesn't see it. We could of course\nalso define a ``db`` fixture in that sister directory's ``conftest.py`` file.\nNote that each fixture is only instantiated if there is a test actually needing\nit (unless you use \"autouse\" fixture which are always executed ahead of the first test\nexecuting).\n\n\npost-process test reports / failures\n---------------------------------------\n\nIf you want to postprocess test reports and need access to the executing\nenvironment you can implement a hook that gets called when the test\n\"report\" object is about to be created. Here we write out all failing\ntest calls and also access a fixture (if it was used by the test) in\ncase you want to query/look at it during your post processing. In our\ncase we just write some information out to a ``failures`` file:\n\n.. code-block:: python\n\n # content of conftest.py\n\n import pytest\n import os.path\n\n\n @pytest.hookimpl(tryfirst=True, hookwrapper=True)\n def pytest_runtest_makereport(item, call):\n # execute all other hooks to obtain the report object\n outcome = yield\n rep = outcome.get_result()\n\n # we only look at actual failing test calls, not setup/teardown\n if rep.when == \"call\" and rep.failed:\n mode = \"a\" if os.path.exists(\"failures\") else \"w\"\n with open(\"failures\", mode) as f:\n # let's also access a fixture for the fun of it\n if \"tmpdir\" in item.fixturenames:\n extra = \" (%s)\" % item.funcargs[\"tmpdir\"]\n else:\n extra = \"\"\n\n f.write(rep.nodeid + extra + \"\\n\")\n\n\nif you then have failing tests:\n\n.. code-block:: python\n\n # content of test_module.py\n def test_fail1(tmpdir):\n assert 0\n\n\n def test_fail2():\n assert 0\n\nand run them:\n\n.. code-block:: pytest\n\n $ pytest test_module.py\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 2 items\n\n test_module.py FF [100%]\n\n ================================= FAILURES =================================\n ________________________________ test_fail1 ________________________________\n\n tmpdir = local('PYTEST_TMPDIR/test_fail10')\n\n def test_fail1(tmpdir):\n > assert 0\n E assert 0\n\n test_module.py:2: AssertionError\n ________________________________ test_fail2 ________________________________\n\n def test_fail2():\n > assert 0\n E assert 0\n\n test_module.py:6: AssertionError\n ========================= 2 failed in 0.12 seconds =========================\n\nyou will have a \"failures\" file which contains the failing test ids:\n\n.. code-block:: bash\n\n $ cat failures\n test_module.py::test_fail1 (PYTEST_TMPDIR/test_fail10)\n test_module.py::test_fail2\n\nMaking test result information available in fixtures\n-----------------------------------------------------------\n\n.. regendoc:wipe\n\nIf you want to make test result reports available in fixture finalizers\nhere is a little example implemented via a local plugin:\n\n.. code-block:: python\n\n # content of conftest.py\n\n import pytest\n\n\n @pytest.hookimpl(tryfirst=True, hookwrapper=True)\n def pytest_runtest_makereport(item, call):\n # execute all other hooks to obtain the report object\n outcome = yield\n rep = outcome.get_result()\n\n # set a report attribute for each phase of a call, which can\n # be \"setup\", \"call\", \"teardown\"\n\n setattr(item, \"rep_\" + rep.when, rep)\n\n\n @pytest.fixture\n def something(request):\n yield\n # request.node is an \"item\" because we use the default\n # \"function\" scope\n if request.node.rep_setup.failed:\n print(\"setting up a test failed!\", request.node.nodeid)\n elif request.node.rep_setup.passed:\n if request.node.rep_call.failed:\n print(\"executing test failed\", request.node.nodeid)\n\n\nif you then have failing tests:\n\n.. code-block:: python\n\n # content of test_module.py\n\n import pytest\n\n\n @pytest.fixture\n def other():\n assert 0\n\n\n def test_setup_fails(something, other):\n pass\n\n\n def test_call_fails(something):\n assert 0\n\n\n def test_fail2():\n assert 0\n\nand run it:\n\n.. code-block:: pytest\n\n $ pytest -s test_module.py\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 3 items\n\n test_module.py Esetting up a test failed! test_module.py::test_setup_fails\n Fexecuting test failed test_module.py::test_call_fails\n F\n\n ================================== ERRORS ==================================\n ____________________ ERROR at setup of test_setup_fails ____________________\n\n @pytest.fixture\n def other():\n > assert 0\n E assert 0\n\n test_module.py:7: AssertionError\n ================================= FAILURES =================================\n _____________________________ test_call_fails ______________________________\n\n something = None\n\n def test_call_fails(something):\n > assert 0\n E assert 0\n\n test_module.py:15: AssertionError\n ________________________________ test_fail2 ________________________________\n\n def test_fail2():\n > assert 0\n E assert 0\n\n test_module.py:19: AssertionError\n ==================== 2 failed, 1 error in 0.12 seconds =====================\n\nYou'll see that the fixture finalizers could use the precise reporting\ninformation.\n\n.. _pytest current test env:\n\n``PYTEST_CURRENT_TEST`` environment variable\n--------------------------------------------\n\n\n\nSometimes a test session might get stuck and there might be no easy way to figure out\nwhich test got stuck, for example if pytest was run in quiet mode (``-q``) or you don't have access to the console\noutput. This is particularly a problem if the problem helps only sporadically, the famous \"flaky\" kind of tests.\n\n``pytest`` sets a ``PYTEST_CURRENT_TEST`` environment variable when running tests, which can be inspected\nby process monitoring utilities or libraries like `psutil `_ to discover which\ntest got stuck if necessary:\n\n.. code-block:: python\n\n import psutil\n\n for pid in psutil.pids():\n environ = psutil.Process(pid).environ()\n if \"PYTEST_CURRENT_TEST\" in environ:\n print(f'pytest process {pid} running: {environ[\"PYTEST_CURRENT_TEST\"]}')\n\nDuring the test session pytest will set ``PYTEST_CURRENT_TEST`` to the current test\n:ref:`nodeid ` and the current stage, which can be ``setup``, ``call``\nand ``teardown``.\n\nFor example, when running a single test function named ``test_foo`` from ``foo_module.py``,\n``PYTEST_CURRENT_TEST`` will be set to:\n\n#. ``foo_module.py::test_foo (setup)``\n#. ``foo_module.py::test_foo (call)``\n#. ``foo_module.py::test_foo (teardown)``\n\nIn that order.\n\n.. note::\n\n The contents of ``PYTEST_CURRENT_TEST`` is meant to be human readable and the actual format\n can be changed between releases (even bug fixes) so it shouldn't be relied on for scripting\n or automation.\n\n.. _freezing-pytest:\n\nFreezing pytest\n---------------\n\nIf you freeze your application using a tool like\n`PyInstaller `_\nin order to distribute it to your end-users, it is a good idea to also package\nyour test runner and run your tests using the frozen application. This way packaging\nerrors such as dependencies not being included into the executable can be detected early\nwhile also allowing you to send test files to users so they can run them in their\nmachines, which can be useful to obtain more information about a hard to reproduce bug.\n\nFortunately recent ``PyInstaller`` releases already have a custom hook\nfor pytest, but if you are using another tool to freeze executables\nsuch as ``cx_freeze`` or ``py2exe``, you can use ``pytest.freeze_includes()``\nto obtain the full list of internal pytest modules. How to configure the tools\nto find the internal modules varies from tool to tool, however.\n\nInstead of freezing the pytest runner as a separate executable, you can make\nyour frozen program work as the pytest runner by some clever\nargument handling during program startup. This allows you to\nhave a single executable, which is usually more convenient.\nPlease note that the mechanism for plugin discovery used by pytest\n(setupttools entry points) doesn't work with frozen executables so pytest\ncan't find any third party plugins automatically. To include third party plugins\nlike ``pytest-timeout`` they must be imported explicitly and passed on to pytest.main.\n\n.. code-block:: python\n\n # contents of app_main.py\n import sys\n import pytest_timeout # Third party plugin\n\n if len(sys.argv) > 1 and sys.argv[1] == \"--pytest\":\n import pytest\n\n sys.exit(pytest.main(sys.argv[2:], plugins=[pytest_timeout]))\n else:\n # normal application execution: at this point argv can be parsed\n # by your argument-parsing library of choice as usual\n ...\n\n\nThis allows you to execute tests using the frozen\napplication with standard ``pytest`` command-line options:\n\n.. code-block:: bash\n\n ./app_main --pytest --verbose --tb=long --junitxml=results.xml test-suite/\n"},{"id":2855,"name":"requirements.txt","nodeType":"TextFile","path":"doc/en","text":"pygments-pytest>=1.1.0\nsphinx>=1.8.2,<2.1\nsphinxcontrib-trio\nsphinx-removed-in>=0.2.0\n"},{"attributeType":"null","col":8,"comment":"null","endLoc":288,"id":2856,"name":"_excinfo","nodeType":"Attribute","startLoc":288,"text":"self._excinfo"},{"col":0,"comment":" Return source location (path, lineno) for the given object.\n If the source cannot be determined return (\"\", -1).\n\n The line number is 0-based.\n ","endLoc":232,"header":"def getfslineno(obj)","id":2859,"name":"getfslineno","nodeType":"Function","startLoc":205,"text":"def getfslineno(obj):\n \"\"\" Return source location (path, lineno) for the given object.\n If the source cannot be determined return (\"\", -1).\n\n The line number is 0-based.\n \"\"\"\n from .code import Code\n\n try:\n code = Code(obj)\n except TypeError:\n try:\n fn = inspect.getsourcefile(obj) or inspect.getfile(obj)\n except TypeError:\n return \"\", -1\n\n fspath = fn and py.path.local(fn) or None\n lineno = -1\n if fspath:\n try:\n _, lineno = findsource(obj)\n except IOError:\n pass\n else:\n fspath = code.path\n lineno = code.firstlineno\n assert isinstance(lineno, int)\n return fspath, lineno"},{"className":"TestSysModulesSnapshot","col":0,"comment":"null","endLoc":370,"id":2860,"nodeType":"Class","startLoc":311,"text":"class TestSysModulesSnapshot(object):\n key = \"my-test-module\"\n\n def test_remove_added(self):\n original = dict(sys.modules)\n assert self.key not in sys.modules\n snapshot = SysModulesSnapshot()\n sys.modules[self.key] = \"something\"\n assert self.key in sys.modules\n snapshot.restore()\n assert sys.modules == original\n\n def test_add_removed(self, monkeypatch):\n assert self.key not in sys.modules\n monkeypatch.setitem(sys.modules, self.key, \"something\")\n assert self.key in sys.modules\n original = dict(sys.modules)\n snapshot = SysModulesSnapshot()\n del sys.modules[self.key]\n assert self.key not in sys.modules\n snapshot.restore()\n assert sys.modules == original\n\n def test_restore_reloaded(self, monkeypatch):\n assert self.key not in sys.modules\n monkeypatch.setitem(sys.modules, self.key, \"something\")\n assert self.key in sys.modules\n original = dict(sys.modules)\n snapshot = SysModulesSnapshot()\n sys.modules[self.key] = \"something else\"\n snapshot.restore()\n assert sys.modules == original\n\n def test_preserve_modules(self, monkeypatch):\n key = [self.key + str(i) for i in range(3)]\n assert not any(k in sys.modules for k in key)\n for i, k in enumerate(key):\n monkeypatch.setitem(sys.modules, k, \"something\" + str(i))\n original = dict(sys.modules)\n\n def preserve(name):\n return name in (key[0], key[1], \"some-other-key\")\n\n snapshot = SysModulesSnapshot(preserve=preserve)\n sys.modules[key[0]] = original[key[0]] = \"something else0\"\n sys.modules[key[1]] = original[key[1]] = \"something else1\"\n sys.modules[key[2]] = \"something else2\"\n snapshot.restore()\n assert sys.modules == original\n\n def test_preserve_container(self, monkeypatch):\n original = dict(sys.modules)\n assert self.key not in original\n replacement = dict(sys.modules)\n replacement[self.key] = \"life of brian\"\n snapshot = SysModulesSnapshot()\n monkeypatch.setattr(sys, \"modules\", replacement)\n snapshot.restore()\n assert sys.modules is replacement\n assert sys.modules == original"},{"col":4,"comment":"null","endLoc":321,"header":"def test_remove_added(self)","id":2861,"name":"test_remove_added","nodeType":"Function","startLoc":314,"text":"def test_remove_added(self):\n original = dict(sys.modules)\n assert self.key not in sys.modules\n snapshot = SysModulesSnapshot()\n sys.modules[self.key] = \"something\"\n assert self.key in sys.modules\n snapshot.restore()\n assert sys.modules == original"},{"col":0,"comment":"null","endLoc":67,"header":"@pytest.mark.skipif(\n six.PY2, reason=\"Formatter classes don't support format styles in PY2\"\n)\ndef test_multiline_message()","id":2862,"name":"test_multiline_message","nodeType":"Function","startLoc":42,"text":"@pytest.mark.skipif(\n six.PY2, reason=\"Formatter classes don't support format styles in PY2\"\n)\ndef test_multiline_message():\n from _pytest.logging import PercentStyleMultiline\n\n logfmt = \"%(filename)-25s %(lineno)4d %(levelname)-8s %(message)s\"\n\n record = logging.LogRecord(\n name=\"dummy\",\n level=logging.INFO,\n pathname=\"dummypath\",\n lineno=10,\n msg=\"Test Message line1\\nline2\",\n args=(),\n exc_info=False,\n )\n # this is called by logging.Formatter.format\n record.message = record.getMessage()\n\n style = PercentStyleMultiline(logfmt)\n output = style.format(record)\n assert output == (\n \"dummypath 10 INFO Test Message line1\\n\"\n \" line2\"\n )"},{"id":2863,"name":"doc/en/_themes/flask","nodeType":"Package"},{"id":2864,"name":"layout.html","nodeType":"TextFile","path":"doc/en/_themes/flask","text":"{%- extends \"basic/layout.html\" %}\n{%- block extrahead %}\n {{ super() }}\n {% if theme_touch_icon %}\n \n {% endif %}\n \n{% endblock %}\n{%- block relbar2 %}{% endblock %}\n{% block header %}\n {{ super() }}\n {% if pagename == 'index' %}\n
\n {% endif %}\n{% endblock %}\n{%- block footer %}\n
\n © Copyright {{ copyright }}.\n Created using Sphinx.\n
\n {% if pagename == 'index' %}\n
\n {% endif %}\n{%- endblock %}\n"},{"id":2865,"name":"attic.rst","nodeType":"TextFile","path":"doc/en/example","text":"\n.. _`accept example`:\n\nexample: specifying and selecting acceptance tests\n--------------------------------------------------------------\n\n.. sourcecode:: python\n\n # ./conftest.py\n def pytest_option(parser):\n group = parser.getgroup(\"myproject\")\n group.addoption(\n \"-A\", dest=\"acceptance\", action=\"store_true\", help=\"run (slow) acceptance tests\"\n )\n\n\n def pytest_funcarg__accept(request):\n return AcceptFixture(request)\n\n\n class AcceptFixture(object):\n def __init__(self, request):\n if not request.config.getoption(\"acceptance\"):\n pytest.skip(\"specify -A to run acceptance tests\")\n self.tmpdir = request.config.mktemp(request.function.__name__, numbered=True)\n\n def run(self, *cmd):\n \"\"\" called by test code to execute an acceptance test. \"\"\"\n self.tmpdir.chdir()\n return subprocess.check_output(cmd).decode()\n\n\nand the actual test function example:\n\n.. sourcecode:: python\n\n def test_some_acceptance_aspect(accept):\n accept.tmpdir.mkdir(\"somesub\")\n result = accept.run(\"ls\", \"-la\")\n assert \"somesub\" in result\n\nIf you run this test without specifying a command line option\nthe test will get skipped with an appropriate message. Otherwise\nyou can start to add convenience and test support methods\nto your AcceptFixture and drive running of tools or\napplications and provide ways to do assertions about\nthe output.\n\n.. _`decorate a funcarg`:\n\nexample: decorating a funcarg in a test module\n--------------------------------------------------------------\n\nFor larger scale setups it's sometimes useful to decorate\na funcarg just for a particular test module. We can\nextend the `accept example`_ by putting this in our test module:\n\n.. sourcecode:: python\n\n def pytest_funcarg__accept(request):\n # call the next factory (living in our conftest.py)\n arg = request.getfuncargvalue(\"accept\")\n # create a special layout in our tempdir\n arg.tmpdir.mkdir(\"special\")\n return arg\n\n\n class TestSpecialAcceptance(object):\n def test_sometest(self, accept):\n assert accept.tmpdir.join(\"special\").check()\n\nOur module level factory will be invoked first and it can\nask its request object to call the next factory and then\ndecorate its result. This mechanism allows us to stay\nignorant of how/where the function argument is provided -\nin our example from a `conftest plugin`_.\n\nsidenote: the temporary directory used here are instances of\nthe `py.path.local`_ class which provides many of the os.path\nmethods in a convenient way.\n\n.. _`py.path.local`: ../path.html#local\n.. _`conftest plugin`: customize.html#conftestplugin\n"},{"col":8,"comment":"null","endLoc":674,"header":"def __init__(self, fmt: str) -> None","id":2868,"name":"__init__","nodeType":"Function","startLoc":674,"text":"def __init__(self, fmt: str) -> None: ..."},{"col":0,"comment":"null","endLoc":300,"header":"def get_direct_param_fixture_func(request)","id":2869,"name":"get_direct_param_fixture_func","nodeType":"Function","startLoc":299,"text":"def get_direct_param_fixture_func(request):\n return request.param"},{"col":0,"comment":"null","endLoc":784,"header":"def fail_fixturefunc(fixturefunc, msg)","id":2870,"name":"fail_fixturefunc","nodeType":"Function","startLoc":780,"text":"def fail_fixturefunc(fixturefunc, msg):\n fs, lineno = getfslineno(fixturefunc)\n location = \"%s:%s\" % (fs, lineno + 1)\n source = _pytest._code.Source(fixturefunc)\n fail(msg + \":\\n\\n\" + str(source.indent()) + \"\\n\" + location, pytrace=False)"},{"col":8,"comment":"null","endLoc":107,"header":"def format(self, record)","id":2871,"name":"format","nodeType":"Function","startLoc":96,"text":"def format(self, record):\n if \"\\n\" in record.message:\n lines = record.message.splitlines()\n formatted = self._fmt % self._update_message(record.__dict__, lines[0])\n # TODO optimize this by introducing an option that tells the\n # logging framework that the indentation doesn't\n # change. This allows to compute the indentation only once.\n indentation = _remove_ansi_escape_sequences(formatted).find(lines[0])\n lines[0] = formatted\n return (\"\\n\" + \" \" * indentation).join(lines)\n else:\n return self._fmt % record.__dict__"},{"className":"Source","col":0,"comment":" an immutable object holding a source code fragment,\n possibly deindenting it.\n ","endLoc":182,"id":2872,"nodeType":"Class","startLoc":20,"text":"class Source(object):\n \"\"\" an immutable object holding a source code fragment,\n possibly deindenting it.\n \"\"\"\n\n _compilecounter = 0\n\n def __init__(self, *parts, **kwargs):\n self.lines = lines = []\n de = kwargs.get(\"deindent\", True)\n for part in parts:\n if not part:\n partlines = []\n elif isinstance(part, Source):\n partlines = part.lines\n elif isinstance(part, (tuple, list)):\n partlines = [x.rstrip(\"\\n\") for x in part]\n elif isinstance(part, six.string_types):\n partlines = part.split(\"\\n\")\n else:\n partlines = getsource(part, deindent=de).lines\n if de:\n partlines = deindent(partlines)\n lines.extend(partlines)\n\n def __eq__(self, other):\n try:\n return self.lines == other.lines\n except AttributeError:\n if isinstance(other, str):\n return str(self) == other\n return False\n\n __hash__ = None\n\n def __getitem__(self, key):\n if isinstance(key, int):\n return self.lines[key]\n else:\n if key.step not in (None, 1):\n raise IndexError(\"cannot slice a Source with a step\")\n newsource = Source()\n newsource.lines = self.lines[key.start : key.stop]\n return newsource\n\n def __len__(self):\n return len(self.lines)\n\n def strip(self):\n \"\"\" return new source object with trailing\n and leading blank lines removed.\n \"\"\"\n start, end = 0, len(self)\n while start < end and not self.lines[start].strip():\n start += 1\n while end > start and not self.lines[end - 1].strip():\n end -= 1\n source = Source()\n source.lines[:] = self.lines[start:end]\n return source\n\n def putaround(self, before=\"\", after=\"\", indent=\" \" * 4):\n \"\"\" return a copy of the source object with\n 'before' and 'after' wrapped around it.\n \"\"\"\n before = Source(before)\n after = Source(after)\n newsource = Source()\n lines = [(indent + line) for line in self.lines]\n newsource.lines = before.lines + lines + after.lines\n return newsource\n\n def indent(self, indent=\" \" * 4):\n \"\"\" return a copy of the source object with\n all lines indented by the given indent-string.\n \"\"\"\n newsource = Source()\n newsource.lines = [(indent + line) for line in self.lines]\n return newsource\n\n def getstatement(self, lineno):\n \"\"\" return Source statement which contains the\n given linenumber (counted from 0).\n \"\"\"\n start, end = self.getstatementrange(lineno)\n return self[start:end]\n\n def getstatementrange(self, lineno):\n \"\"\" return (start, end) tuple which spans the minimal\n statement region which containing the given lineno.\n \"\"\"\n if not (0 <= lineno < len(self)):\n raise IndexError(\"lineno out of range\")\n ast, start, end = getstatementrange_ast(lineno, self)\n return start, end\n\n def deindent(self):\n \"\"\"return a new source object deindented.\"\"\"\n newsource = Source()\n newsource.lines[:] = deindent(self.lines)\n return newsource\n\n def isparseable(self, deindent=True):\n \"\"\" return True if source is parseable, heuristically\n deindenting it by default.\n \"\"\"\n from parser import suite as syntax_checker\n\n if deindent:\n source = str(self.deindent())\n else:\n source = str(self)\n try:\n # compile(source+'\\n', \"x\", \"exec\")\n syntax_checker(source + \"\\n\")\n except KeyboardInterrupt:\n raise\n except Exception:\n return False\n else:\n return True\n\n def __str__(self):\n return \"\\n\".join(self.lines)\n\n def compile(\n self, filename=None, mode=\"exec\", flag=0, dont_inherit=0, _genframe=None\n ):\n \"\"\" return compiled code object. if filename is None\n invent an artificial filename which displays\n the source/line position of the caller frame.\n \"\"\"\n if not filename or py.path.local(filename).check(file=0):\n if _genframe is None:\n _genframe = sys._getframe(1) # the caller\n fn, lineno = _genframe.f_code.co_filename, _genframe.f_lineno\n base = \"<%d-codegen \" % self._compilecounter\n self.__class__._compilecounter += 1\n if not filename:\n filename = base + \"%s:%d>\" % (fn, lineno)\n else:\n filename = base + \"%r %s:%d>\" % (filename, fn, lineno)\n source = \"\\n\".join(self.lines) + \"\\n\"\n try:\n co = compile(source, filename, mode, flag)\n except SyntaxError:\n ex = sys.exc_info()[1]\n # re-represent syntax errors from parsing python strings\n msglines = self.lines[: ex.lineno]\n if ex.offset:\n msglines.append(\" \" * ex.offset + \"^\")\n msglines.append(\"(code was compiled probably from here: %s)\" % filename)\n newex = SyntaxError(\"\\n\".join(msglines))\n newex.offset = ex.offset\n newex.lineno = ex.lineno\n newex.text = ex.text\n raise newex\n else:\n if flag & _AST_FLAG:\n return co\n lines = [(x + \"\\n\") for x in self.lines]\n linecache.cache[filename] = (1, None, lines, filename)\n return co"},{"col":4,"comment":" return a copy of the source object with\n all lines indented by the given indent-string.\n ","endLoc":98,"header":"def indent(self, indent=\" \" * 4)","id":2873,"name":"indent","nodeType":"Function","startLoc":92,"text":"def indent(self, indent=\" \" * 4):\n \"\"\" return a copy of the source object with\n all lines indented by the given indent-string.\n \"\"\"\n newsource = Source()\n newsource.lines = [(indent + line) for line in self.lines]\n return newsource"},{"col":4,"comment":"null","endLoc":51,"header":"def __eq__(self, other)","id":2874,"name":"__eq__","nodeType":"Function","startLoc":45,"text":"def __eq__(self, other):\n try:\n return self.lines == other.lines\n except AttributeError:\n if isinstance(other, str):\n return str(self) == other\n return False"},{"col":8,"comment":"null","endLoc":94,"header":"@staticmethod\n def _update_message(record_dict, message)","id":2875,"name":"_update_message","nodeType":"Function","startLoc":90,"text":"@staticmethod\n def _update_message(record_dict, message):\n tmp = record_dict.copy()\n tmp[\"message\"] = message\n return tmp"},{"col":0,"comment":"null","endLoc":25,"header":"def _remove_ansi_escape_sequences(text)","id":2876,"name":"_remove_ansi_escape_sequences","nodeType":"Function","startLoc":24,"text":"def _remove_ansi_escape_sequences(text):\n return _ANSI_ESCAPE_SEQ.sub(\"\", text)"},{"col":0,"comment":"null","endLoc":796,"header":"def call_fixture_func(fixturefunc, request, kwargs)","id":2877,"name":"call_fixture_func","nodeType":"Function","startLoc":787,"text":"def call_fixture_func(fixturefunc, request, kwargs):\n yieldctx = is_generator(fixturefunc)\n if yieldctx:\n it = fixturefunc(**kwargs)\n res = next(it)\n finalizer = functools.partial(_teardown_yield_fixture, fixturefunc, it)\n request.addfinalizer(finalizer)\n else:\n res = fixturefunc(**kwargs)\n return res"},{"col":4,"comment":"null","endLoc":63,"header":"def __getitem__(self, key)","id":2878,"name":"__getitem__","nodeType":"Function","startLoc":55,"text":"def __getitem__(self, key):\n if isinstance(key, int):\n return self.lines[key]\n else:\n if key.step not in (None, 1):\n raise IndexError(\"cannot slice a Source with a step\")\n newsource = Source()\n newsource.lines = self.lines[key.start : key.stop]\n return newsource"},{"fileName":"test_doctest.py","filePath":"testing","id":2879,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport inspect\nimport sys\nimport textwrap\n\nimport pytest\nfrom _pytest.compat import MODULE_NOT_FOUND_ERROR\nfrom _pytest.doctest import _is_mocked\nfrom _pytest.doctest import _patch_unwrap_mock_aware\nfrom _pytest.doctest import DoctestItem\nfrom _pytest.doctest import DoctestModule\nfrom _pytest.doctest import DoctestTextfile\n\n\nclass TestDoctests(object):\n def test_collect_testtextfile(self, testdir):\n w = testdir.maketxtfile(whatever=\"\")\n checkfile = testdir.maketxtfile(\n test_something=\"\"\"\n alskdjalsdk\n >>> i = 5\n >>> i-1\n 4\n \"\"\"\n )\n\n for x in (testdir.tmpdir, checkfile):\n # print \"checking that %s returns custom items\" % (x,)\n items, reprec = testdir.inline_genitems(x)\n assert len(items) == 1\n assert isinstance(items[0], DoctestItem)\n assert isinstance(items[0].parent, DoctestTextfile)\n # Empty file has no items.\n items, reprec = testdir.inline_genitems(w)\n assert len(items) == 0\n\n def test_collect_module_empty(self, testdir):\n path = testdir.makepyfile(whatever=\"#\")\n for p in (path, testdir.tmpdir):\n items, reprec = testdir.inline_genitems(p, \"--doctest-modules\")\n assert len(items) == 0\n\n def test_collect_module_single_modulelevel_doctest(self, testdir):\n path = testdir.makepyfile(whatever='\"\"\">>> pass\"\"\"')\n for p in (path, testdir.tmpdir):\n items, reprec = testdir.inline_genitems(p, \"--doctest-modules\")\n assert len(items) == 1\n assert isinstance(items[0], DoctestItem)\n assert isinstance(items[0].parent, DoctestModule)\n\n def test_collect_module_two_doctest_one_modulelevel(self, testdir):\n path = testdir.makepyfile(\n whatever=\"\"\"\n '>>> x = None'\n def my_func():\n \">>> magic = 42 \"\n \"\"\"\n )\n for p in (path, testdir.tmpdir):\n items, reprec = testdir.inline_genitems(p, \"--doctest-modules\")\n assert len(items) == 2\n assert isinstance(items[0], DoctestItem)\n assert isinstance(items[1], DoctestItem)\n assert isinstance(items[0].parent, DoctestModule)\n assert items[0].parent is items[1].parent\n\n def test_collect_module_two_doctest_no_modulelevel(self, testdir):\n path = testdir.makepyfile(\n whatever=\"\"\"\n '# Empty'\n def my_func():\n \">>> magic = 42 \"\n def unuseful():\n '''\n # This is a function\n # >>> # it doesn't have any doctest\n '''\n def another():\n '''\n # This is another function\n >>> import os # this one does have a doctest\n '''\n \"\"\"\n )\n for p in (path, testdir.tmpdir):\n items, reprec = testdir.inline_genitems(p, \"--doctest-modules\")\n assert len(items) == 2\n assert isinstance(items[0], DoctestItem)\n assert isinstance(items[1], DoctestItem)\n assert isinstance(items[0].parent, DoctestModule)\n assert items[0].parent is items[1].parent\n\n def test_simple_doctestfile(self, testdir):\n p = testdir.maketxtfile(\n test_doc=\"\"\"\n >>> x = 1\n >>> x == 1\n False\n \"\"\"\n )\n reprec = testdir.inline_run(p)\n reprec.assertoutcome(failed=1)\n\n def test_new_pattern(self, testdir):\n p = testdir.maketxtfile(\n xdoc=\"\"\"\n >>> x = 1\n >>> x == 1\n False\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-glob=x*.txt\")\n reprec.assertoutcome(failed=1)\n\n def test_multiple_patterns(self, testdir):\n \"\"\"Test support for multiple --doctest-glob arguments (#1255).\n \"\"\"\n testdir.maketxtfile(\n xdoc=\"\"\"\n >>> 1\n 1\n \"\"\"\n )\n testdir.makefile(\n \".foo\",\n test=\"\"\"\n >>> 1\n 1\n \"\"\",\n )\n testdir.maketxtfile(\n test_normal=\"\"\"\n >>> 1\n 1\n \"\"\"\n )\n expected = {\"xdoc.txt\", \"test.foo\", \"test_normal.txt\"}\n assert {x.basename for x in testdir.tmpdir.listdir()} == expected\n args = [\"--doctest-glob=xdoc*.txt\", \"--doctest-glob=*.foo\"]\n result = testdir.runpytest(*args)\n result.stdout.fnmatch_lines([\"*test.foo *\", \"*xdoc.txt *\", \"*2 passed*\"])\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*test_normal.txt *\", \"*1 passed*\"])\n\n @pytest.mark.parametrize(\n \" test_string, encoding\",\n [(u\"foo\", \"ascii\"), (u\"öäü\", \"latin1\"), (u\"öäü\", \"utf-8\")],\n )\n def test_encoding(self, testdir, test_string, encoding):\n \"\"\"Test support for doctest_encoding ini option.\n \"\"\"\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_encoding={}\n \"\"\".format(\n encoding\n )\n )\n doctest = u\"\"\"\n >>> u\"{}\"\n {}\n \"\"\".format(\n test_string, repr(test_string)\n )\n testdir._makefile(\".txt\", [doctest], {}, encoding=encoding)\n\n result = testdir.runpytest()\n\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_doctest_unexpected_exception(self, testdir):\n testdir.maketxtfile(\n \"\"\"\n >>> i = 0\n >>> 0 / i\n 2\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines(\n [\n \"*unexpected_exception*\",\n \"*>>> i = 0*\",\n \"*>>> 0 / i*\",\n \"*UNEXPECTED*ZeroDivision*\",\n ]\n )\n\n def test_doctest_skip(self, testdir):\n testdir.maketxtfile(\n \"\"\"\n >>> 1\n 1\n >>> import pytest\n >>> pytest.skip(\"\")\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines([\"*1 skipped*\"])\n\n def test_docstring_partial_context_around_error(self, testdir):\n \"\"\"Test that we show some context before the actual line of a failing\n doctest.\n \"\"\"\n testdir.makepyfile(\n '''\n def foo():\n \"\"\"\n text-line-1\n text-line-2\n text-line-3\n text-line-4\n text-line-5\n text-line-6\n text-line-7\n text-line-8\n text-line-9\n text-line-10\n text-line-11\n >>> 1 + 1\n 3\n\n text-line-after\n \"\"\"\n '''\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines(\n [\n \"*docstring_partial_context_around_error*\",\n \"005*text-line-3\",\n \"006*text-line-4\",\n \"013*text-line-11\",\n \"014*>>> 1 + 1\",\n \"Expected:\",\n \" 3\",\n \"Got:\",\n \" 2\",\n ]\n )\n # lines below should be trimmed out\n assert \"text-line-2\" not in result.stdout.str()\n assert \"text-line-after\" not in result.stdout.str()\n\n def test_docstring_full_context_around_error(self, testdir):\n \"\"\"Test that we show the whole context before the actual line of a failing\n doctest, provided that the context is up to 10 lines long.\n \"\"\"\n testdir.makepyfile(\n '''\n def foo():\n \"\"\"\n text-line-1\n text-line-2\n\n >>> 1 + 1\n 3\n \"\"\"\n '''\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines(\n [\n \"*docstring_full_context_around_error*\",\n \"003*text-line-1\",\n \"004*text-line-2\",\n \"006*>>> 1 + 1\",\n \"Expected:\",\n \" 3\",\n \"Got:\",\n \" 2\",\n ]\n )\n\n def test_doctest_linedata_missing(self, testdir):\n testdir.tmpdir.join(\"hello.py\").write(\n textwrap.dedent(\n \"\"\"\\\n class Fun(object):\n @property\n def test(self):\n '''\n >>> a = 1\n >>> 1/0\n '''\n \"\"\"\n )\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines(\n [\n \"*hello*\",\n \"*EXAMPLE LOCATION UNKNOWN, not showing all tests of that example*\",\n \"*1/0*\",\n \"*UNEXPECTED*ZeroDivision*\",\n \"*1 failed*\",\n ]\n )\n\n def test_doctest_unex_importerror_only_txt(self, testdir):\n testdir.maketxtfile(\n \"\"\"\n >>> import asdalsdkjaslkdjasd\n >>>\n \"\"\"\n )\n result = testdir.runpytest()\n # doctest is never executed because of error during hello.py collection\n result.stdout.fnmatch_lines(\n [\n \"*>>> import asdals*\",\n \"*UNEXPECTED*{e}*\".format(e=MODULE_NOT_FOUND_ERROR),\n \"{e}: No module named *asdal*\".format(e=MODULE_NOT_FOUND_ERROR),\n ]\n )\n\n def test_doctest_unex_importerror_with_module(self, testdir):\n testdir.tmpdir.join(\"hello.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import asdalsdkjaslkdjasd\n \"\"\"\n )\n )\n testdir.maketxtfile(\n \"\"\"\n >>> import hello\n >>>\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\")\n # doctest is never executed because of error during hello.py collection\n result.stdout.fnmatch_lines(\n [\n \"*ERROR collecting hello.py*\",\n \"*{e}: No module named *asdals*\".format(e=MODULE_NOT_FOUND_ERROR),\n \"*Interrupted: 1 errors during collection*\",\n ]\n )\n\n def test_doctestmodule(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n '''\n >>> x = 1\n >>> x == 1\n False\n\n '''\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(failed=1)\n\n def test_doctestmodule_external_and_issue116(self, testdir):\n p = testdir.mkpydir(\"hello\")\n p.join(\"__init__.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def somefunc():\n '''\n >>> i = 0\n >>> i + 1\n 2\n '''\n \"\"\"\n )\n )\n result = testdir.runpytest(p, \"--doctest-modules\")\n result.stdout.fnmatch_lines(\n [\n \"003 *>>> i = 0\",\n \"004 *>>> i + 1\",\n \"*Expected:\",\n \"* 2\",\n \"*Got:\",\n \"* 1\",\n \"*:4: DocTestFailure\",\n ]\n )\n\n def test_txtfile_failing(self, testdir):\n p = testdir.maketxtfile(\n \"\"\"\n >>> i = 0\n >>> i + 1\n 2\n \"\"\"\n )\n result = testdir.runpytest(p, \"-s\")\n result.stdout.fnmatch_lines(\n [\n \"001 >>> i = 0\",\n \"002 >>> i + 1\",\n \"Expected:\",\n \" 2\",\n \"Got:\",\n \" 1\",\n \"*test_txtfile_failing.txt:2: DocTestFailure\",\n ]\n )\n\n def test_txtfile_with_fixtures(self, testdir):\n p = testdir.maketxtfile(\n \"\"\"\n >>> dir = getfixture('tmpdir')\n >>> type(dir).__name__\n 'LocalPath'\n \"\"\"\n )\n reprec = testdir.inline_run(p)\n reprec.assertoutcome(passed=1)\n\n def test_txtfile_with_usefixtures_in_ini(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n usefixtures = myfixture\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture\n def myfixture(monkeypatch):\n monkeypatch.setenv(\"HELLO\", \"WORLD\")\n \"\"\"\n )\n\n p = testdir.maketxtfile(\n \"\"\"\n >>> import os\n >>> os.environ[\"HELLO\"]\n 'WORLD'\n \"\"\"\n )\n reprec = testdir.inline_run(p)\n reprec.assertoutcome(passed=1)\n\n def test_doctestmodule_with_fixtures(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n '''\n >>> dir = getfixture('tmpdir')\n >>> type(dir).__name__\n 'LocalPath'\n '''\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(passed=1)\n\n def test_doctestmodule_three_tests(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n '''\n >>> dir = getfixture('tmpdir')\n >>> type(dir).__name__\n 'LocalPath'\n '''\n def my_func():\n '''\n >>> magic = 42\n >>> magic - 42\n 0\n '''\n def unuseful():\n pass\n def another():\n '''\n >>> import os\n >>> os is os\n True\n '''\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(passed=3)\n\n def test_doctestmodule_two_tests_one_fail(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n class MyClass(object):\n def bad_meth(self):\n '''\n >>> magic = 42\n >>> magic\n 0\n '''\n def nice_meth(self):\n '''\n >>> magic = 42\n >>> magic - 42\n 0\n '''\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(failed=1, passed=1)\n\n def test_ignored_whitespace(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_optionflags = ELLIPSIS NORMALIZE_WHITESPACE\n \"\"\"\n )\n p = testdir.makepyfile(\n \"\"\"\n class MyClass(object):\n '''\n >>> a = \"foo \"\n >>> print(a)\n foo\n '''\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(passed=1)\n\n def test_non_ignored_whitespace(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_optionflags = ELLIPSIS\n \"\"\"\n )\n p = testdir.makepyfile(\n \"\"\"\n class MyClass(object):\n '''\n >>> a = \"foo \"\n >>> print(a)\n foo\n '''\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(failed=1, passed=0)\n\n def test_ignored_whitespace_glob(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_optionflags = ELLIPSIS NORMALIZE_WHITESPACE\n \"\"\"\n )\n p = testdir.maketxtfile(\n xdoc=\"\"\"\n >>> a = \"foo \"\n >>> print(a)\n foo\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-glob=x*.txt\")\n reprec.assertoutcome(passed=1)\n\n def test_non_ignored_whitespace_glob(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_optionflags = ELLIPSIS\n \"\"\"\n )\n p = testdir.maketxtfile(\n xdoc=\"\"\"\n >>> a = \"foo \"\n >>> print(a)\n foo\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-glob=x*.txt\")\n reprec.assertoutcome(failed=1, passed=0)\n\n def test_contains_unicode(self, testdir):\n \"\"\"Fix internal error with docstrings containing non-ascii characters.\n \"\"\"\n testdir.makepyfile(\n u'''\n # -*- coding: utf-8 -*-\n def foo():\n \"\"\"\n >>> name = 'с' # not letter 'c' but instead Cyrillic 's'.\n 'anything'\n \"\"\"\n '''\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines([\"Got nothing\", \"* 1 failed in*\"])\n\n def test_ignore_import_errors_on_doctest(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import asdf\n\n def add_one(x):\n '''\n >>> add_one(1)\n 2\n '''\n return x + 1\n \"\"\"\n )\n\n reprec = testdir.inline_run(\n p, \"--doctest-modules\", \"--doctest-ignore-import-errors\"\n )\n reprec.assertoutcome(skipped=1, failed=1, passed=0)\n\n def test_junit_report_for_doctest(self, testdir):\n \"\"\"\n #713: Fix --junit-xml option when used with --doctest-modules.\n \"\"\"\n p = testdir.makepyfile(\n \"\"\"\n def foo():\n '''\n >>> 1 + 1\n 3\n '''\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\", \"--junit-xml=junit.xml\")\n reprec.assertoutcome(failed=1)\n\n def test_unicode_doctest(self, testdir):\n \"\"\"\n Test case for issue 2434: DecodeError on Python 2 when doctest contains non-ascii\n characters.\n \"\"\"\n p = testdir.maketxtfile(\n test_unicode_doctest=\"\"\"\n .. doctest::\n\n >>> print(\n ... \"Hi\\\\n\\\\nByé\")\n Hi\n ...\n Byé\n >>> 1/0 # Byé\n 1\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\"*UNEXPECTED EXCEPTION: ZeroDivisionError*\", \"*1 failed*\"]\n )\n\n def test_unicode_doctest_module(self, testdir):\n \"\"\"\n Test case for issue 2434: DecodeError on Python 2 when doctest docstring\n contains non-ascii characters.\n \"\"\"\n p = testdir.makepyfile(\n test_unicode_doctest_module=\"\"\"\n # -*- coding: utf-8 -*-\n from __future__ import unicode_literals\n\n def fix_bad_unicode(text):\n '''\n >>> print(fix_bad_unicode('único'))\n único\n '''\n return \"único\"\n \"\"\"\n )\n result = testdir.runpytest(p, \"--doctest-modules\")\n result.stdout.fnmatch_lines([\"* 1 passed *\"])\n\n def test_print_unicode_value(self, testdir):\n \"\"\"\n Test case for issue 3583: Printing Unicode in doctest under Python 2.7\n doesn't work\n \"\"\"\n p = testdir.maketxtfile(\n test_print_unicode_value=r\"\"\"\n Here is a doctest::\n\n >>> print(u'\\xE5\\xE9\\xEE\\xF8\\xFC')\n åéîøü\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"* 1 passed *\"])\n\n def test_reportinfo(self, testdir):\n \"\"\"\n Test case to make sure that DoctestItem.reportinfo() returns lineno.\n \"\"\"\n p = testdir.makepyfile(\n test_reportinfo=\"\"\"\n def foo(x):\n '''\n >>> foo('a')\n 'b'\n '''\n return 'c'\n \"\"\"\n )\n items, reprec = testdir.inline_genitems(p, \"--doctest-modules\")\n reportinfo = items[0].reportinfo()\n assert reportinfo[1] == 1\n\n def test_valid_setup_py(self, testdir):\n \"\"\"\n Test to make sure that pytest ignores valid setup.py files when ran\n with --doctest-modules\n \"\"\"\n p = testdir.makepyfile(\n setup=\"\"\"\n from setuptools import setup, find_packages\n setup(name='sample',\n version='0.0',\n description='description',\n packages=find_packages()\n )\n \"\"\"\n )\n result = testdir.runpytest(p, \"--doctest-modules\")\n result.stdout.fnmatch_lines([\"*collected 0 items*\"])\n\n def test_invalid_setup_py(self, testdir):\n \"\"\"\n Test to make sure that pytest reads setup.py files that are not used\n for python packages when ran with --doctest-modules\n \"\"\"\n p = testdir.makepyfile(\n setup=\"\"\"\n def test_foo():\n return 'bar'\n \"\"\"\n )\n result = testdir.runpytest(p, \"--doctest-modules\")\n result.stdout.fnmatch_lines([\"*collected 1 item*\"])\n\n\nclass TestLiterals(object):\n @pytest.mark.parametrize(\"config_mode\", [\"ini\", \"comment\"])\n def test_allow_unicode(self, testdir, config_mode):\n \"\"\"Test that doctests which output unicode work in all python versions\n tested by pytest when the ALLOW_UNICODE option is used (either in\n the ini file or by an inline comment).\n \"\"\"\n if config_mode == \"ini\":\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_optionflags = ALLOW_UNICODE\n \"\"\"\n )\n comment = \"\"\n else:\n comment = \"#doctest: +ALLOW_UNICODE\"\n\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> b'12'.decode('ascii') {comment}\n '12'\n \"\"\".format(\n comment=comment\n )\n )\n testdir.makepyfile(\n foo=\"\"\"\n def foo():\n '''\n >>> b'12'.decode('ascii') {comment}\n '12'\n '''\n \"\"\".format(\n comment=comment\n )\n )\n reprec = testdir.inline_run(\"--doctest-modules\")\n reprec.assertoutcome(passed=2)\n\n @pytest.mark.parametrize(\"config_mode\", [\"ini\", \"comment\"])\n def test_allow_bytes(self, testdir, config_mode):\n \"\"\"Test that doctests which output bytes work in all python versions\n tested by pytest when the ALLOW_BYTES option is used (either in\n the ini file or by an inline comment)(#1287).\n \"\"\"\n if config_mode == \"ini\":\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_optionflags = ALLOW_BYTES\n \"\"\"\n )\n comment = \"\"\n else:\n comment = \"#doctest: +ALLOW_BYTES\"\n\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> b'foo' {comment}\n 'foo'\n \"\"\".format(\n comment=comment\n )\n )\n testdir.makepyfile(\n foo=\"\"\"\n def foo():\n '''\n >>> b'foo' {comment}\n 'foo'\n '''\n \"\"\".format(\n comment=comment\n )\n )\n reprec = testdir.inline_run(\"--doctest-modules\")\n reprec.assertoutcome(passed=2)\n\n def test_unicode_string(self, testdir):\n \"\"\"Test that doctests which output unicode fail in Python 2 when\n the ALLOW_UNICODE option is not used. The same test should pass\n in Python 3.\n \"\"\"\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> b'12'.decode('ascii')\n '12'\n \"\"\"\n )\n reprec = testdir.inline_run()\n passed = int(sys.version_info[0] >= 3)\n reprec.assertoutcome(passed=passed, failed=int(not passed))\n\n def test_bytes_literal(self, testdir):\n \"\"\"Test that doctests which output bytes fail in Python 3 when\n the ALLOW_BYTES option is not used. The same test should pass\n in Python 2 (#1287).\n \"\"\"\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> b'foo'\n 'foo'\n \"\"\"\n )\n reprec = testdir.inline_run()\n passed = int(sys.version_info[0] == 2)\n reprec.assertoutcome(passed=passed, failed=int(not passed))\n\n\nclass TestDoctestSkips(object):\n \"\"\"\n If all examples in a doctest are skipped due to the SKIP option, then\n the tests should be SKIPPED rather than PASSED. (#957)\n \"\"\"\n\n @pytest.fixture(params=[\"text\", \"module\"])\n def makedoctest(self, testdir, request):\n def makeit(doctest):\n mode = request.param\n if mode == \"text\":\n testdir.maketxtfile(doctest)\n else:\n assert mode == \"module\"\n testdir.makepyfile('\"\"\"\\n%s\"\"\"' % doctest)\n\n return makeit\n\n def test_one_skipped(self, testdir, makedoctest):\n makedoctest(\n \"\"\"\n >>> 1 + 1 # doctest: +SKIP\n 2\n >>> 2 + 2\n 4\n \"\"\"\n )\n reprec = testdir.inline_run(\"--doctest-modules\")\n reprec.assertoutcome(passed=1)\n\n def test_one_skipped_failed(self, testdir, makedoctest):\n makedoctest(\n \"\"\"\n >>> 1 + 1 # doctest: +SKIP\n 2\n >>> 2 + 2\n 200\n \"\"\"\n )\n reprec = testdir.inline_run(\"--doctest-modules\")\n reprec.assertoutcome(failed=1)\n\n def test_all_skipped(self, testdir, makedoctest):\n makedoctest(\n \"\"\"\n >>> 1 + 1 # doctest: +SKIP\n 2\n >>> 2 + 2 # doctest: +SKIP\n 200\n \"\"\"\n )\n reprec = testdir.inline_run(\"--doctest-modules\")\n reprec.assertoutcome(skipped=1)\n\n def test_vacuous_all_skipped(self, testdir, makedoctest):\n makedoctest(\"\")\n reprec = testdir.inline_run(\"--doctest-modules\")\n reprec.assertoutcome(passed=0, skipped=0)\n\n def test_continue_on_failure(self, testdir):\n testdir.maketxtfile(\n test_something=\"\"\"\n >>> i = 5\n >>> def foo():\n ... raise ValueError('error1')\n >>> foo()\n >>> i\n >>> i + 2\n 7\n >>> i + 1\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\", \"--doctest-continue-on-failure\")\n result.assert_outcomes(passed=0, failed=1)\n # The lines that contains the failure are 4, 5, and 8. The first one\n # is a stack trace and the other two are mismatches.\n result.stdout.fnmatch_lines(\n [\"*4: UnexpectedException*\", \"*5: DocTestFailure*\", \"*8: DocTestFailure*\"]\n )\n\n\nclass TestDoctestAutoUseFixtures(object):\n\n SCOPES = [\"module\", \"session\", \"class\", \"function\"]\n\n def test_doctest_module_session_fixture(self, testdir):\n \"\"\"Test that session fixtures are initialized for doctest modules (#768)\n \"\"\"\n # session fixture which changes some global data, which will\n # be accessed by doctests in a module\n testdir.makeconftest(\n \"\"\"\n import pytest\n import sys\n\n @pytest.yield_fixture(autouse=True, scope='session')\n def myfixture():\n assert not hasattr(sys, 'pytest_session_data')\n sys.pytest_session_data = 1\n yield\n del sys.pytest_session_data\n \"\"\"\n )\n testdir.makepyfile(\n foo=\"\"\"\n import sys\n\n def foo():\n '''\n >>> assert sys.pytest_session_data == 1\n '''\n\n def bar():\n '''\n >>> assert sys.pytest_session_data == 1\n '''\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n @pytest.mark.parametrize(\"scope\", SCOPES)\n @pytest.mark.parametrize(\"enable_doctest\", [True, False])\n def test_fixture_scopes(self, testdir, scope, enable_doctest):\n \"\"\"Test that auto-use fixtures work properly with doctest modules.\n See #1057 and #1100.\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(autouse=True, scope=\"{scope}\")\n def auto(request):\n return 99\n \"\"\".format(\n scope=scope\n )\n )\n testdir.makepyfile(\n test_1='''\n def test_foo():\n \"\"\"\n >>> getfixture('auto') + 1\n 100\n \"\"\"\n def test_bar():\n assert 1\n '''\n )\n params = (\"--doctest-modules\",) if enable_doctest else ()\n passes = 3 if enable_doctest else 2\n result = testdir.runpytest(*params)\n result.stdout.fnmatch_lines([\"*=== %d passed in *\" % passes])\n\n @pytest.mark.parametrize(\"scope\", SCOPES)\n @pytest.mark.parametrize(\"autouse\", [True, False])\n @pytest.mark.parametrize(\"use_fixture_in_doctest\", [True, False])\n def test_fixture_module_doctest_scopes(\n self, testdir, scope, autouse, use_fixture_in_doctest\n ):\n \"\"\"Test that auto-use fixtures work properly with doctest files.\n See #1057 and #1100.\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(autouse={autouse}, scope=\"{scope}\")\n def auto(request):\n return 99\n \"\"\".format(\n scope=scope, autouse=autouse\n )\n )\n if use_fixture_in_doctest:\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> getfixture('auto')\n 99\n \"\"\"\n )\n else:\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> 1 + 1\n 2\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\")\n assert \"FAILURES\" not in str(result.stdout.str())\n result.stdout.fnmatch_lines([\"*=== 1 passed in *\"])\n\n @pytest.mark.parametrize(\"scope\", SCOPES)\n def test_auto_use_request_attributes(self, testdir, scope):\n \"\"\"Check that all attributes of a request in an autouse fixture\n behave as expected when requested for a doctest item.\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(autouse=True, scope=\"{scope}\")\n def auto(request):\n if \"{scope}\" == 'module':\n assert request.module is None\n if \"{scope}\" == 'class':\n assert request.cls is None\n if \"{scope}\" == 'function':\n assert request.function is None\n return 99\n \"\"\".format(\n scope=scope\n )\n )\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> 1 + 1\n 2\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\")\n assert \"FAILURES\" not in str(result.stdout.str())\n result.stdout.fnmatch_lines([\"*=== 1 passed in *\"])\n\n\nclass TestDoctestNamespaceFixture(object):\n\n SCOPES = [\"module\", \"session\", \"class\", \"function\"]\n\n @pytest.mark.parametrize(\"scope\", SCOPES)\n def test_namespace_doctestfile(self, testdir, scope):\n \"\"\"\n Check that inserting something into the namespace works in a\n simple text file doctest\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n import contextlib\n\n @pytest.fixture(autouse=True, scope=\"{scope}\")\n def add_contextlib(doctest_namespace):\n doctest_namespace['cl'] = contextlib\n \"\"\".format(\n scope=scope\n )\n )\n p = testdir.maketxtfile(\n \"\"\"\n >>> print(cl.__name__)\n contextlib\n \"\"\"\n )\n reprec = testdir.inline_run(p)\n reprec.assertoutcome(passed=1)\n\n @pytest.mark.parametrize(\"scope\", SCOPES)\n def test_namespace_pyfile(self, testdir, scope):\n \"\"\"\n Check that inserting something into the namespace works in a\n simple Python file docstring doctest\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n import contextlib\n\n @pytest.fixture(autouse=True, scope=\"{scope}\")\n def add_contextlib(doctest_namespace):\n doctest_namespace['cl'] = contextlib\n \"\"\".format(\n scope=scope\n )\n )\n p = testdir.makepyfile(\n \"\"\"\n def foo():\n '''\n >>> print(cl.__name__)\n contextlib\n '''\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(passed=1)\n\n\nclass TestDoctestReportingOption(object):\n def _run_doctest_report(self, testdir, format):\n testdir.makepyfile(\n \"\"\"\n def foo():\n '''\n >>> foo()\n a b\n 0 1 4\n 1 2 4\n 2 3 6\n '''\n print(' a b\\\\n'\n '0 1 4\\\\n'\n '1 2 5\\\\n'\n '2 3 6')\n \"\"\"\n )\n return testdir.runpytest(\"--doctest-modules\", \"--doctest-report\", format)\n\n @pytest.mark.parametrize(\"format\", [\"udiff\", \"UDIFF\", \"uDiFf\"])\n def test_doctest_report_udiff(self, testdir, format):\n result = self._run_doctest_report(testdir, format)\n result.stdout.fnmatch_lines(\n [\" 0 1 4\", \" -1 2 4\", \" +1 2 5\", \" 2 3 6\"]\n )\n\n def test_doctest_report_cdiff(self, testdir):\n result = self._run_doctest_report(testdir, \"cdiff\")\n result.stdout.fnmatch_lines(\n [\n \" a b\",\n \" 0 1 4\",\n \" ! 1 2 4\",\n \" 2 3 6\",\n \" --- 1,4 ----\",\n \" a b\",\n \" 0 1 4\",\n \" ! 1 2 5\",\n \" 2 3 6\",\n ]\n )\n\n def test_doctest_report_ndiff(self, testdir):\n result = self._run_doctest_report(testdir, \"ndiff\")\n result.stdout.fnmatch_lines(\n [\n \" a b\",\n \" 0 1 4\",\n \" - 1 2 4\",\n \" ? ^\",\n \" + 1 2 5\",\n \" ? ^\",\n \" 2 3 6\",\n ]\n )\n\n @pytest.mark.parametrize(\"format\", [\"none\", \"only_first_failure\"])\n def test_doctest_report_none_or_only_first_failure(self, testdir, format):\n result = self._run_doctest_report(testdir, format)\n result.stdout.fnmatch_lines(\n [\n \"Expected:\",\n \" a b\",\n \" 0 1 4\",\n \" 1 2 4\",\n \" 2 3 6\",\n \"Got:\",\n \" a b\",\n \" 0 1 4\",\n \" 1 2 5\",\n \" 2 3 6\",\n ]\n )\n\n def test_doctest_report_invalid(self, testdir):\n result = self._run_doctest_report(testdir, \"obviously_invalid_format\")\n result.stderr.fnmatch_lines(\n [\n \"*error: argument --doctest-report: invalid choice: 'obviously_invalid_format' (choose from*\"\n ]\n )\n\n\n@pytest.mark.parametrize(\"mock_module\", [\"mock\", \"unittest.mock\"])\ndef test_doctest_mock_objects_dont_recurse_missbehaved(mock_module, testdir):\n pytest.importorskip(mock_module)\n testdir.makepyfile(\n \"\"\"\n from {mock_module} import call\n class Example(object):\n '''\n >>> 1 + 1\n 2\n '''\n \"\"\".format(\n mock_module=mock_module\n )\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines([\"* 1 passed *\"])\n\n\nclass Broken:\n def __getattr__(self, _):\n raise KeyError(\"This should be an AttributeError\")\n\n\n@pytest.mark.skipif(not hasattr(inspect, \"unwrap\"), reason=\"nothing to patch\")\n@pytest.mark.parametrize( # pragma: no branch (lambdas are not called)\n \"stop\", [None, _is_mocked, lambda f: None, lambda f: False, lambda f: True]\n)\ndef test_warning_on_unwrap_of_broken_object(stop):\n bad_instance = Broken()\n assert inspect.unwrap.__module__ == \"inspect\"\n with _patch_unwrap_mock_aware():\n assert inspect.unwrap.__module__ != \"inspect\"\n with pytest.warns(\n pytest.PytestWarning, match=\"^Got KeyError.* when unwrapping\"\n ):\n with pytest.raises(KeyError):\n inspect.unwrap(bad_instance, stop=stop)\n assert inspect.unwrap.__module__ == \"inspect\"\n"},{"attributeType":"null","col":0,"comment":"null","endLoc":44,"id":2880,"name":"MODULE_NOT_FOUND_ERROR","nodeType":"Attribute","startLoc":44,"text":"MODULE_NOT_FOUND_ERROR"},{"col":4,"comment":"null","endLoc":66,"header":"def __len__(self)","id":2881,"name":"__len__","nodeType":"Function","startLoc":65,"text":"def __len__(self):\n return len(self.lines)"},{"col":4,"comment":" return new source object with trailing\n and leading blank lines removed.\n ","endLoc":79,"header":"def strip(self)","id":2882,"name":"strip","nodeType":"Function","startLoc":68,"text":"def strip(self):\n \"\"\" return new source object with trailing\n and leading blank lines removed.\n \"\"\"\n start, end = 0, len(self)\n while start < end and not self.lines[start].strip():\n start += 1\n while end > start and not self.lines[end - 1].strip():\n end -= 1\n source = Source()\n source.lines[:] = self.lines[start:end]\n return source"},{"col":0,"comment":"Executes the teardown of a fixture function by advancing the iterator after the\n yield and ensure the iteration ends (if not it means there is more than one yield in the function)","endLoc":809,"header":"def _teardown_yield_fixture(fixturefunc, it)","id":2883,"name":"_teardown_yield_fixture","nodeType":"Function","startLoc":799,"text":"def _teardown_yield_fixture(fixturefunc, it):\n \"\"\"Executes the teardown of a fixture function by advancing the iterator after the\n yield and ensure the iteration ends (if not it means there is more than one yield in the function)\"\"\"\n try:\n next(it)\n except StopIteration:\n pass\n else:\n fail_fixturefunc(\n fixturefunc, \"yield_fixture function has more than one 'yield'\"\n )"},{"col":0,"comment":"\n returns if a object is possibly a mock object by checking the existence of a highly improbable attribute\n ","endLoc":364,"header":"def _is_mocked(obj)","id":2884,"name":"_is_mocked","nodeType":"Function","startLoc":357,"text":"def _is_mocked(obj):\n \"\"\"\n returns if a object is possibly a mock object by checking the existence of a highly improbable attribute\n \"\"\"\n return (\n safe_getattr(obj, \"pytest_mock_example_attribute_that_shouldnt_exist\", None)\n is not None\n )"},{"col":0,"comment":"Gets the actual callable that can be called to obtain the fixture value, dealing with unittest-specific\n instances and bound methods.\n ","endLoc":921,"header":"def resolve_fixture_function(fixturedef, request)","id":2885,"name":"resolve_fixture_function","nodeType":"Function","startLoc":904,"text":"def resolve_fixture_function(fixturedef, request):\n \"\"\"Gets the actual callable that can be called to obtain the fixture value, dealing with unittest-specific\n instances and bound methods.\n \"\"\"\n fixturefunc = fixturedef.func\n if fixturedef.unittest:\n if request.instance is not None:\n # bind the unbound method to the TestCase instance\n fixturefunc = fixturedef.func.__get__(request.instance)\n else:\n # the fixture function needs to be bound to the actual\n # request.instance so that code working with \"fixturedef\" behaves\n # as expected.\n if request.instance is not None:\n fixturefunc = getimfunc(fixturedef.func)\n if fixturefunc != fixturedef.func:\n fixturefunc = fixturefunc.__get__(request.instance)\n return fixturefunc"},{"col":0,"comment":" Execution of fixture setup. ","endLoc":941,"header":"def pytest_fixture_setup(fixturedef, request)","id":2886,"name":"pytest_fixture_setup","nodeType":"Function","startLoc":924,"text":"def pytest_fixture_setup(fixturedef, request):\n \"\"\" Execution of fixture setup. \"\"\"\n kwargs = {}\n for argname in fixturedef.argnames:\n fixdef = request._get_active_fixturedef(argname)\n result, arg_cache_key, exc = fixdef.cached_result\n request._check_scope(argname, request.scope, fixdef.scope)\n kwargs[argname] = result\n\n fixturefunc = resolve_fixture_function(fixturedef, request)\n my_cache_key = request.param_index\n try:\n result = call_fixture_func(fixturefunc, request, kwargs)\n except TEST_OUTCOME:\n fixturedef.cached_result = (None, my_cache_key, sys.exc_info())\n raise\n fixturedef.cached_result = (result, my_cache_key, None)\n return result"},{"col":4,"comment":" return a copy of the source object with\n 'before' and 'after' wrapped around it.\n ","endLoc":90,"header":"def putaround(self, before=\"\", after=\"\", indent=\" \" * 4)","id":2887,"name":"putaround","nodeType":"Function","startLoc":81,"text":"def putaround(self, before=\"\", after=\"\", indent=\" \" * 4):\n \"\"\" return a copy of the source object with\n 'before' and 'after' wrapped around it.\n \"\"\"\n before = Source(before)\n after = Source(after)\n newsource = Source()\n lines = [(indent + line) for line in self.lines]\n newsource.lines = before.lines + lines + after.lines\n return newsource"},{"col":0,"comment":"null","endLoc":949,"header":"def _ensure_immutable_ids(ids)","id":2888,"name":"_ensure_immutable_ids","nodeType":"Function","startLoc":944,"text":"def _ensure_immutable_ids(ids):\n if ids is None:\n return\n if callable(ids):\n return ids\n return tuple(ids)"},{"col":4,"comment":"null","endLoc":72,"header":"@pytest.mark.parametrize(\n \"pattern, path\",\n [\n (\"*.py\", \"foo.pyc\"),\n (\"*.py\", \"foo/foo.pyc\"),\n (\"tests/*.py\", \"foo/foo.py\"),\n (drv1 + \"/*.py\", drv2 + \"/foo.py\"),\n (drv1 + \"/foo/*.py\", drv2 + \"/foo/foo.py\"),\n (\"tests/**/test*.py\", \"tests/foo.py\"),\n (\"tests/**/test*.py\", \"foo/test_foo.py\"),\n (\"tests/**/doc/test*.py\", \"tests/foo/bar/doc/foo.py\"),\n (\"tests/**/doc/test*.py\", \"tests/foo/bar/test_foo.py\"),\n ],\n )\n def test_not_matching(self, match, pattern, path)","id":2891,"name":"test_not_matching","nodeType":"Function","startLoc":57,"text":"@pytest.mark.parametrize(\n \"pattern, path\",\n [\n (\"*.py\", \"foo.pyc\"),\n (\"*.py\", \"foo/foo.pyc\"),\n (\"tests/*.py\", \"foo/foo.py\"),\n (drv1 + \"/*.py\", drv2 + \"/foo.py\"),\n (drv1 + \"/foo/*.py\", drv2 + \"/foo/foo.py\"),\n (\"tests/**/test*.py\", \"tests/foo.py\"),\n (\"tests/**/test*.py\", \"foo/test_foo.py\"),\n (\"tests/**/doc/test*.py\", \"tests/foo/bar/doc/foo.py\"),\n (\"tests/**/doc/test*.py\", \"tests/foo/bar/test_foo.py\"),\n ],\n )\n def test_not_matching(self, match, pattern, path):\n assert not match(pattern, path)"},{"col":4,"comment":" return Source statement which contains the\n given linenumber (counted from 0).\n ","endLoc":105,"header":"def getstatement(self, lineno)","id":2892,"name":"getstatement","nodeType":"Function","startLoc":100,"text":"def getstatement(self, lineno):\n \"\"\" return Source statement which contains the\n given linenumber (counted from 0).\n \"\"\"\n start, end = self.getstatementrange(lineno)\n return self[start:end]"},{"col":0,"comment":"Session-scoped fixture that returns the :class:`_pytest.config.Config` object.\n\n Example::\n\n def test_foo(pytestconfig):\n if pytestconfig.getoption(\"verbose\") > 0:\n ...\n\n ","endLoc":1074,"header":"@fixture(scope=\"session\")\ndef pytestconfig(request)","id":2893,"name":"pytestconfig","nodeType":"Function","startLoc":1063,"text":"@fixture(scope=\"session\")\ndef pytestconfig(request):\n \"\"\"Session-scoped fixture that returns the :class:`_pytest.config.Config` object.\n\n Example::\n\n def test_foo(pytestconfig):\n if pytestconfig.getoption(\"verbose\") > 0:\n ...\n\n \"\"\"\n return request.config"},{"col":0,"comment":"null","endLoc":1083,"header":"def pytest_addoption(parser)","id":2894,"name":"pytest_addoption","nodeType":"Function","startLoc":1077,"text":"def pytest_addoption(parser):\n parser.addini(\n \"usefixtures\",\n type=\"args\",\n default=[],\n help=\"list of default fixtures to be used with this project\",\n )"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":65,"id":2895,"name":"scopename2class","nodeType":"Attribute","startLoc":65,"text":"scopename2class"},{"attributeType":"dict","col":0,"comment":"null","endLoc":68,"id":2896,"name":"scope2props","nodeType":"Attribute","startLoc":68,"text":"scope2props"},{"col":4,"comment":" return (start, end) tuple which spans the minimal\n statement region which containing the given lineno.\n ","endLoc":114,"header":"def getstatementrange(self, lineno)","id":2897,"name":"getstatementrange","nodeType":"Function","startLoc":107,"text":"def getstatementrange(self, lineno):\n \"\"\" return (start, end) tuple which spans the minimal\n statement region which containing the given lineno.\n \"\"\"\n if not (0 <= lineno < len(self)):\n raise IndexError(\"lineno out of range\")\n ast, start, end = getstatementrange_ast(lineno, self)\n return start, end"},{"fileName":"logging.py","filePath":"src/_pytest","id":2898,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\" Access and control log capturing. \"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport logging\nimport re\nfrom contextlib import contextmanager\n\nimport py\nimport six\n\nimport pytest\nfrom _pytest.compat import dummy_context_manager\nfrom _pytest.config import create_terminal_writer\nfrom _pytest.pathlib import Path\n\nDEFAULT_LOG_FORMAT = \"%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s\"\nDEFAULT_LOG_DATE_FORMAT = \"%H:%M:%S\"\n_ANSI_ESCAPE_SEQ = re.compile(r\"\\x1b\\[[\\d;]+m\")\n\n\ndef _remove_ansi_escape_sequences(text):\n return _ANSI_ESCAPE_SEQ.sub(\"\", text)\n\n\nclass ColoredLevelFormatter(logging.Formatter):\n \"\"\"\n Colorize the %(levelname)..s part of the log format passed to __init__.\n \"\"\"\n\n LOGLEVEL_COLOROPTS = {\n logging.CRITICAL: {\"red\"},\n logging.ERROR: {\"red\", \"bold\"},\n logging.WARNING: {\"yellow\"},\n logging.WARN: {\"yellow\"},\n logging.INFO: {\"green\"},\n logging.DEBUG: {\"purple\"},\n logging.NOTSET: set(),\n }\n LEVELNAME_FMT_REGEX = re.compile(r\"%\\(levelname\\)([+-]?\\d*s)\")\n\n def __init__(self, terminalwriter, *args, **kwargs):\n super(ColoredLevelFormatter, self).__init__(*args, **kwargs)\n if six.PY2:\n self._original_fmt = self._fmt\n else:\n self._original_fmt = self._style._fmt\n self._level_to_fmt_mapping = {}\n\n levelname_fmt_match = self.LEVELNAME_FMT_REGEX.search(self._fmt)\n if not levelname_fmt_match:\n return\n levelname_fmt = levelname_fmt_match.group()\n\n for level, color_opts in self.LOGLEVEL_COLOROPTS.items():\n formatted_levelname = levelname_fmt % {\n \"levelname\": logging.getLevelName(level)\n }\n\n # add ANSI escape sequences around the formatted levelname\n color_kwargs = {name: True for name in color_opts}\n colorized_formatted_levelname = terminalwriter.markup(\n formatted_levelname, **color_kwargs\n )\n self._level_to_fmt_mapping[level] = self.LEVELNAME_FMT_REGEX.sub(\n colorized_formatted_levelname, self._fmt\n )\n\n def format(self, record):\n fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt)\n if six.PY2:\n self._fmt = fmt\n else:\n self._style._fmt = fmt\n return super(ColoredLevelFormatter, self).format(record)\n\n\nif not six.PY2:\n # Formatter classes don't support format styles in PY2\n\n class PercentStyleMultiline(logging.PercentStyle):\n \"\"\"A logging style with special support for multiline messages.\n\n If the message of a record consists of multiple lines, this style\n formats the message as if each line were logged separately.\n \"\"\"\n\n @staticmethod\n def _update_message(record_dict, message):\n tmp = record_dict.copy()\n tmp[\"message\"] = message\n return tmp\n\n def format(self, record):\n if \"\\n\" in record.message:\n lines = record.message.splitlines()\n formatted = self._fmt % self._update_message(record.__dict__, lines[0])\n # TODO optimize this by introducing an option that tells the\n # logging framework that the indentation doesn't\n # change. This allows to compute the indentation only once.\n indentation = _remove_ansi_escape_sequences(formatted).find(lines[0])\n lines[0] = formatted\n return (\"\\n\" + \" \" * indentation).join(lines)\n else:\n return self._fmt % record.__dict__\n\n\ndef get_option_ini(config, *names):\n for name in names:\n ret = config.getoption(name) # 'default' arg won't work as expected\n if ret is None:\n ret = config.getini(name)\n if ret:\n return ret\n\n\ndef pytest_addoption(parser):\n \"\"\"Add options to control log capturing.\"\"\"\n group = parser.getgroup(\"logging\")\n\n def add_option_ini(option, dest, default=None, type=None, **kwargs):\n parser.addini(\n dest, default=default, type=type, help=\"default value for \" + option\n )\n group.addoption(option, dest=dest, **kwargs)\n\n add_option_ini(\n \"--no-print-logs\",\n dest=\"log_print\",\n action=\"store_const\",\n const=False,\n default=True,\n type=\"bool\",\n help=\"disable printing caught logs on failed tests.\",\n )\n add_option_ini(\n \"--log-level\",\n dest=\"log_level\",\n default=None,\n help=\"logging level used by the logging module\",\n )\n add_option_ini(\n \"--log-format\",\n dest=\"log_format\",\n default=DEFAULT_LOG_FORMAT,\n help=\"log format as used by the logging module.\",\n )\n add_option_ini(\n \"--log-date-format\",\n dest=\"log_date_format\",\n default=DEFAULT_LOG_DATE_FORMAT,\n help=\"log date format as used by the logging module.\",\n )\n parser.addini(\n \"log_cli\",\n default=False,\n type=\"bool\",\n help='enable log display during test run (also known as \"live logging\").',\n )\n add_option_ini(\n \"--log-cli-level\", dest=\"log_cli_level\", default=None, help=\"cli logging level.\"\n )\n add_option_ini(\n \"--log-cli-format\",\n dest=\"log_cli_format\",\n default=None,\n help=\"log format as used by the logging module.\",\n )\n add_option_ini(\n \"--log-cli-date-format\",\n dest=\"log_cli_date_format\",\n default=None,\n help=\"log date format as used by the logging module.\",\n )\n add_option_ini(\n \"--log-file\",\n dest=\"log_file\",\n default=None,\n help=\"path to a file when logging will be written to.\",\n )\n add_option_ini(\n \"--log-file-level\",\n dest=\"log_file_level\",\n default=None,\n help=\"log file logging level.\",\n )\n add_option_ini(\n \"--log-file-format\",\n dest=\"log_file_format\",\n default=DEFAULT_LOG_FORMAT,\n help=\"log format as used by the logging module.\",\n )\n add_option_ini(\n \"--log-file-date-format\",\n dest=\"log_file_date_format\",\n default=DEFAULT_LOG_DATE_FORMAT,\n help=\"log date format as used by the logging module.\",\n )\n\n\n@contextmanager\ndef catching_logs(handler, formatter=None, level=None):\n \"\"\"Context manager that prepares the whole logging machinery properly.\"\"\"\n root_logger = logging.getLogger()\n\n if formatter is not None:\n handler.setFormatter(formatter)\n if level is not None:\n handler.setLevel(level)\n\n # Adding the same handler twice would confuse logging system.\n # Just don't do that.\n add_new_handler = handler not in root_logger.handlers\n\n if add_new_handler:\n root_logger.addHandler(handler)\n if level is not None:\n orig_level = root_logger.level\n root_logger.setLevel(min(orig_level, level))\n try:\n yield handler\n finally:\n if level is not None:\n root_logger.setLevel(orig_level)\n if add_new_handler:\n root_logger.removeHandler(handler)\n\n\nclass LogCaptureHandler(logging.StreamHandler):\n \"\"\"A logging handler that stores log records and the log text.\"\"\"\n\n def __init__(self):\n \"\"\"Creates a new log handler.\"\"\"\n logging.StreamHandler.__init__(self, py.io.TextIO())\n self.records = []\n\n def emit(self, record):\n \"\"\"Keep the log records in a list in addition to the log text.\"\"\"\n self.records.append(record)\n logging.StreamHandler.emit(self, record)\n\n def reset(self):\n self.records = []\n self.stream = py.io.TextIO()\n\n\nclass LogCaptureFixture(object):\n \"\"\"Provides access and control of log capturing.\"\"\"\n\n def __init__(self, item):\n \"\"\"Creates a new funcarg.\"\"\"\n self._item = item\n # dict of log name -> log level\n self._initial_log_levels = {} # Dict[str, int]\n\n def _finalize(self):\n \"\"\"Finalizes the fixture.\n\n This restores the log levels changed by :meth:`set_level`.\n \"\"\"\n # restore log levels\n for logger_name, level in self._initial_log_levels.items():\n logger = logging.getLogger(logger_name)\n logger.setLevel(level)\n\n @property\n def handler(self):\n \"\"\"\n :rtype: LogCaptureHandler\n \"\"\"\n return self._item.catch_log_handler\n\n def get_records(self, when):\n \"\"\"\n Get the logging records for one of the possible test phases.\n\n :param str when:\n Which test phase to obtain the records from. Valid values are: \"setup\", \"call\" and \"teardown\".\n\n :rtype: List[logging.LogRecord]\n :return: the list of captured records at the given stage\n\n .. versionadded:: 3.4\n \"\"\"\n handler = self._item.catch_log_handlers.get(when)\n if handler:\n return handler.records\n else:\n return []\n\n @property\n def text(self):\n \"\"\"Returns the formatted log text.\"\"\"\n return _remove_ansi_escape_sequences(self.handler.stream.getvalue())\n\n @property\n def records(self):\n \"\"\"Returns the list of log records.\"\"\"\n return self.handler.records\n\n @property\n def record_tuples(self):\n \"\"\"Returns a list of a stripped down version of log records intended\n for use in assertion comparison.\n\n The format of the tuple is:\n\n (logger_name, log_level, message)\n \"\"\"\n return [(r.name, r.levelno, r.getMessage()) for r in self.records]\n\n @property\n def messages(self):\n \"\"\"Returns a list of format-interpolated log messages.\n\n Unlike 'records', which contains the format string and parameters for interpolation, log messages in this list\n are all interpolated.\n Unlike 'text', which contains the output from the handler, log messages in this list are unadorned with\n levels, timestamps, etc, making exact comparisons more reliable.\n\n Note that traceback or stack info (from :func:`logging.exception` or the `exc_info` or `stack_info` arguments\n to the logging functions) is not included, as this is added by the formatter in the handler.\n\n .. versionadded:: 3.7\n \"\"\"\n return [r.getMessage() for r in self.records]\n\n def clear(self):\n \"\"\"Reset the list of log records and the captured log text.\"\"\"\n self.handler.reset()\n\n def set_level(self, level, logger=None):\n \"\"\"Sets the level for capturing of logs. The level will be restored to its previous value at the end of\n the test.\n\n :param int level: the logger to level.\n :param str logger: the logger to update the level. If not given, the root logger level is updated.\n\n .. versionchanged:: 3.4\n The levels of the loggers changed by this function will be restored to their initial values at the\n end of the test.\n \"\"\"\n logger_name = logger\n logger = logging.getLogger(logger_name)\n # save the original log-level to restore it during teardown\n self._initial_log_levels.setdefault(logger_name, logger.level)\n logger.setLevel(level)\n\n @contextmanager\n def at_level(self, level, logger=None):\n \"\"\"Context manager that sets the level for capturing of logs. After the end of the 'with' statement the\n level is restored to its original value.\n\n :param int level: the logger to level.\n :param str logger: the logger to update the level. If not given, the root logger level is updated.\n \"\"\"\n logger = logging.getLogger(logger)\n orig_level = logger.level\n logger.setLevel(level)\n try:\n yield\n finally:\n logger.setLevel(orig_level)\n\n\n@pytest.fixture\ndef caplog(request):\n \"\"\"Access and control log capturing.\n\n Captured logs are available through the following properties/methods::\n\n * caplog.text -> string containing formatted log output\n * caplog.records -> list of logging.LogRecord instances\n * caplog.record_tuples -> list of (logger_name, level, message) tuples\n * caplog.clear() -> clear captured records and formatted log output string\n \"\"\"\n result = LogCaptureFixture(request.node)\n yield result\n result._finalize()\n\n\ndef get_actual_log_level(config, *setting_names):\n \"\"\"Return the actual logging level.\"\"\"\n\n for setting_name in setting_names:\n log_level = config.getoption(setting_name)\n if log_level is None:\n log_level = config.getini(setting_name)\n if log_level:\n break\n else:\n return\n\n if isinstance(log_level, six.string_types):\n log_level = log_level.upper()\n try:\n return int(getattr(logging, log_level, log_level))\n except ValueError:\n # Python logging does not recognise this as a logging level\n raise pytest.UsageError(\n \"'{}' is not recognized as a logging level name for \"\n \"'{}'. Please consider passing the \"\n \"logging level num instead.\".format(log_level, setting_name)\n )\n\n\n# run after terminalreporter/capturemanager are configured\n@pytest.hookimpl(trylast=True)\ndef pytest_configure(config):\n config.pluginmanager.register(LoggingPlugin(config), \"logging-plugin\")\n\n\nclass LoggingPlugin(object):\n \"\"\"Attaches to the logging module and captures log messages for each test.\n \"\"\"\n\n def __init__(self, config):\n \"\"\"Creates a new plugin to capture log messages.\n\n The formatter can be safely shared across all handlers so\n create a single one for the entire test session here.\n \"\"\"\n self._config = config\n\n self.print_logs = get_option_ini(config, \"log_print\")\n self.formatter = self._create_formatter(\n get_option_ini(config, \"log_format\"),\n get_option_ini(config, \"log_date_format\"),\n )\n self.log_level = get_actual_log_level(config, \"log_level\")\n\n self.log_file_level = get_actual_log_level(config, \"log_file_level\")\n self.log_file_format = get_option_ini(config, \"log_file_format\", \"log_format\")\n self.log_file_date_format = get_option_ini(\n config, \"log_file_date_format\", \"log_date_format\"\n )\n self.log_file_formatter = logging.Formatter(\n self.log_file_format, datefmt=self.log_file_date_format\n )\n\n log_file = get_option_ini(config, \"log_file\")\n if log_file:\n self.log_file_handler = logging.FileHandler(\n log_file, mode=\"w\", encoding=\"UTF-8\"\n )\n self.log_file_handler.setFormatter(self.log_file_formatter)\n else:\n self.log_file_handler = None\n\n self.log_cli_handler = None\n\n self.live_logs_context = lambda: dummy_context_manager()\n # Note that the lambda for the live_logs_context is needed because\n # live_logs_context can otherwise not be entered multiple times due\n # to limitations of contextlib.contextmanager.\n\n if self._log_cli_enabled():\n self._setup_cli_logging()\n\n def _create_formatter(self, log_format, log_date_format):\n # color option doesn't exist if terminal plugin is disabled\n color = getattr(self._config.option, \"color\", \"no\")\n if color != \"no\" and ColoredLevelFormatter.LEVELNAME_FMT_REGEX.search(\n log_format\n ):\n formatter = ColoredLevelFormatter(\n create_terminal_writer(self._config), log_format, log_date_format\n )\n else:\n formatter = logging.Formatter(log_format, log_date_format)\n\n if not six.PY2:\n formatter._style = PercentStyleMultiline(formatter._style._fmt)\n return formatter\n\n def _setup_cli_logging(self):\n config = self._config\n terminal_reporter = config.pluginmanager.get_plugin(\"terminalreporter\")\n if terminal_reporter is None:\n # terminal reporter is disabled e.g. by pytest-xdist.\n return\n\n capture_manager = config.pluginmanager.get_plugin(\"capturemanager\")\n # if capturemanager plugin is disabled, live logging still works.\n log_cli_handler = _LiveLoggingStreamHandler(terminal_reporter, capture_manager)\n\n log_cli_formatter = self._create_formatter(\n get_option_ini(config, \"log_cli_format\", \"log_format\"),\n get_option_ini(config, \"log_cli_date_format\", \"log_date_format\"),\n )\n\n log_cli_level = get_actual_log_level(config, \"log_cli_level\", \"log_level\")\n self.log_cli_handler = log_cli_handler\n self.live_logs_context = lambda: catching_logs(\n log_cli_handler, formatter=log_cli_formatter, level=log_cli_level\n )\n\n def set_log_path(self, fname):\n \"\"\"Public method, which can set filename parameter for\n Logging.FileHandler(). Also creates parent directory if\n it does not exist.\n\n .. warning::\n Please considered as an experimental API.\n \"\"\"\n fname = Path(fname)\n\n if not fname.is_absolute():\n fname = Path(self._config.rootdir, fname)\n\n if not fname.parent.exists():\n fname.parent.mkdir(exist_ok=True, parents=True)\n\n self.log_file_handler = logging.FileHandler(\n str(fname), mode=\"w\", encoding=\"UTF-8\"\n )\n self.log_file_handler.setFormatter(self.log_file_formatter)\n\n def _log_cli_enabled(self):\n \"\"\"Return True if log_cli should be considered enabled, either explicitly\n or because --log-cli-level was given in the command-line.\n \"\"\"\n return self._config.getoption(\n \"--log-cli-level\"\n ) is not None or self._config.getini(\"log_cli\")\n\n @pytest.hookimpl(hookwrapper=True, tryfirst=True)\n def pytest_collection(self):\n with self.live_logs_context():\n if self.log_cli_handler:\n self.log_cli_handler.set_when(\"collection\")\n\n if self.log_file_handler is not None:\n with catching_logs(self.log_file_handler, level=self.log_file_level):\n yield\n else:\n yield\n\n @contextmanager\n def _runtest_for(self, item, when):\n with self._runtest_for_main(item, when):\n if self.log_file_handler is not None:\n with catching_logs(self.log_file_handler, level=self.log_file_level):\n yield\n else:\n yield\n\n @contextmanager\n def _runtest_for_main(self, item, when):\n \"\"\"Implements the internals of pytest_runtest_xxx() hook.\"\"\"\n with catching_logs(\n LogCaptureHandler(), formatter=self.formatter, level=self.log_level\n ) as log_handler:\n if self.log_cli_handler:\n self.log_cli_handler.set_when(when)\n\n if item is None:\n yield # run the test\n return\n\n if not hasattr(item, \"catch_log_handlers\"):\n item.catch_log_handlers = {}\n item.catch_log_handlers[when] = log_handler\n item.catch_log_handler = log_handler\n try:\n yield # run test\n finally:\n if when == \"teardown\":\n del item.catch_log_handler\n del item.catch_log_handlers\n\n if self.print_logs:\n # Add a captured log section to the report.\n log = log_handler.stream.getvalue().strip()\n item.add_report_section(when, \"log\", log)\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_setup(self, item):\n with self._runtest_for(item, \"setup\"):\n yield\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_call(self, item):\n with self._runtest_for(item, \"call\"):\n yield\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_teardown(self, item):\n with self._runtest_for(item, \"teardown\"):\n yield\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_logstart(self):\n if self.log_cli_handler:\n self.log_cli_handler.reset()\n with self._runtest_for(None, \"start\"):\n yield\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_logfinish(self):\n with self._runtest_for(None, \"finish\"):\n yield\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_logreport(self):\n with self._runtest_for(None, \"logreport\"):\n yield\n\n @pytest.hookimpl(hookwrapper=True, tryfirst=True)\n def pytest_sessionfinish(self):\n with self.live_logs_context():\n if self.log_cli_handler:\n self.log_cli_handler.set_when(\"sessionfinish\")\n if self.log_file_handler is not None:\n try:\n with catching_logs(\n self.log_file_handler, level=self.log_file_level\n ):\n yield\n finally:\n # Close the FileHandler explicitly.\n # (logging.shutdown might have lost the weakref?!)\n self.log_file_handler.close()\n else:\n yield\n\n @pytest.hookimpl(hookwrapper=True, tryfirst=True)\n def pytest_sessionstart(self):\n with self.live_logs_context():\n if self.log_cli_handler:\n self.log_cli_handler.set_when(\"sessionstart\")\n if self.log_file_handler is not None:\n with catching_logs(self.log_file_handler, level=self.log_file_level):\n yield\n else:\n yield\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtestloop(self, session):\n \"\"\"Runs all collected test items.\"\"\"\n\n if session.config.option.collectonly:\n yield\n return\n\n if self._log_cli_enabled() and self._config.getoption(\"verbose\") < 1:\n # setting verbose flag is needed to avoid messy test progress output\n self._config.option.verbose = 1\n\n with self.live_logs_context():\n if self.log_file_handler is not None:\n with catching_logs(self.log_file_handler, level=self.log_file_level):\n yield # run all the tests\n else:\n yield # run all the tests\n\n\nclass _LiveLoggingStreamHandler(logging.StreamHandler):\n \"\"\"\n Custom StreamHandler used by the live logging feature: it will write a newline before the first log message\n in each test.\n\n During live logging we must also explicitly disable stdout/stderr capturing otherwise it will get captured\n and won't appear in the terminal.\n \"\"\"\n\n def __init__(self, terminal_reporter, capture_manager):\n \"\"\"\n :param _pytest.terminal.TerminalReporter terminal_reporter:\n :param _pytest.capture.CaptureManager capture_manager:\n \"\"\"\n logging.StreamHandler.__init__(self, stream=terminal_reporter)\n self.capture_manager = capture_manager\n self.reset()\n self.set_when(None)\n self._test_outcome_written = False\n\n def reset(self):\n \"\"\"Reset the handler; should be called before the start of each test\"\"\"\n self._first_record_emitted = False\n\n def set_when(self, when):\n \"\"\"Prepares for the given test phase (setup/call/teardown)\"\"\"\n self._when = when\n self._section_name_shown = False\n if when == \"start\":\n self._test_outcome_written = False\n\n def emit(self, record):\n ctx_manager = (\n self.capture_manager.global_and_fixture_disabled()\n if self.capture_manager\n else dummy_context_manager()\n )\n with ctx_manager:\n if not self._first_record_emitted:\n self.stream.write(\"\\n\")\n self._first_record_emitted = True\n elif self._when in (\"teardown\", \"finish\"):\n if not self._test_outcome_written:\n self._test_outcome_written = True\n self.stream.write(\"\\n\")\n if not self._section_name_shown and self._when:\n self.stream.section(\"live log \" + self._when, sep=\"-\", bold=True)\n self._section_name_shown = True\n logging.StreamHandler.emit(self, record)\n"},{"col":0,"comment":"null","endLoc":329,"header":"def getstatementrange_ast(lineno, source, assertion=False, astnode=None)","id":2899,"name":"getstatementrange_ast","nodeType":"Function","startLoc":290,"text":"def getstatementrange_ast(lineno, source, assertion=False, astnode=None):\n if astnode is None:\n content = str(source)\n # See #4260:\n # don't produce duplicate warnings when compiling source to find ast\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n astnode = compile(content, \"source\", \"exec\", _AST_FLAG)\n\n start, end = get_statement_startend2(lineno, astnode)\n # we need to correct the end:\n # - ast-parsing strips comments\n # - there might be empty lines\n # - we might have lesser indented code blocks at the end\n if end is None:\n end = len(source.lines)\n\n if end > start + 1:\n # make sure we don't span differently indented code blocks\n # by using the BlockFinder helper used which inspect.getsource() uses itself\n block_finder = inspect.BlockFinder()\n # if we start with an indented line, put blockfinder to \"started\" mode\n block_finder.started = source.lines[start][0].isspace()\n it = ((x + \"\\n\") for x in source.lines[start:end])\n try:\n for tok in tokenize.generate_tokens(lambda: next(it)):\n block_finder.tokeneater(*tok)\n except (inspect.EndOfBlock, IndentationError):\n end = block_finder.last + start\n except Exception:\n pass\n\n # the end might still point to a comment or empty line, correct it\n while end:\n line = source.lines[end - 1].lstrip()\n if line.startswith(\"#\") or not line:\n end -= 1\n else:\n break\n return astnode, start, end"},{"col":0,"comment":"Context manager that does nothing, useful in situations where you might need an actual context manager or not\n depending on some condition. Using this allow to keep the same code","endLoc":172,"header":"@contextmanager\ndef dummy_context_manager()","id":2900,"name":"dummy_context_manager","nodeType":"Function","startLoc":168,"text":"@contextmanager\ndef dummy_context_manager():\n \"\"\"Context manager that does nothing, useful in situations where you might need an actual context manager or not\n depending on some condition. Using this allow to keep the same code\"\"\"\n yield"},{"className":"PercentStyleMultiline","col":4,"comment":"A logging style with special support for multiline messages.\n\n If the message of a record consists of multiple lines, this style\n formats the message as if each line were logged separately.\n ","endLoc":107,"id":2901,"nodeType":"Class","startLoc":83,"text":"class PercentStyleMultiline(logging.PercentStyle):\n \"\"\"A logging style with special support for multiline messages.\n\n If the message of a record consists of multiple lines, this style\n formats the message as if each line were logged separately.\n \"\"\"\n\n @staticmethod\n def _update_message(record_dict, message):\n tmp = record_dict.copy()\n tmp[\"message\"] = message\n return tmp\n\n def format(self, record):\n if \"\\n\" in record.message:\n lines = record.message.splitlines()\n formatted = self._fmt % self._update_message(record.__dict__, lines[0])\n # TODO optimize this by introducing an option that tells the\n # logging framework that the indentation doesn't\n # change. This allows to compute the indentation only once.\n indentation = _remove_ansi_escape_sequences(formatted).find(lines[0])\n lines[0] = formatted\n return (\"\\n\" + \" \" * indentation).join(lines)\n else:\n return self._fmt % record.__dict__"},{"className":"PercentStyle","col":0,"comment":"null","endLoc":678,"id":2902,"nodeType":"Class","startLoc":665,"text":"class PercentStyle: # undocumented\n default_format: str\n asctime_format: str\n asctime_search: str\n validation_pattern: Pattern[str]\n _fmt: str\n if sys.version_info >= (3, 10):\n def __init__(self, fmt: str, *, defaults: Mapping[str, Any] | None = None) -> None: ...\n else:\n def __init__(self, fmt: str) -> None: ...\n\n def usesTime(self) -> bool: ...\n def validate(self) -> None: ...\n def format(self, record: Any) -> str: ..."},{"col":4,"comment":"null","endLoc":676,"header":"def usesTime(self) -> bool","id":2903,"name":"usesTime","nodeType":"Function","startLoc":676,"text":"def usesTime(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":677,"header":"def validate(self) -> None","id":2904,"name":"validate","nodeType":"Function","startLoc":677,"text":"def validate(self) -> None: ..."},{"col":4,"comment":"null","endLoc":678,"header":"def format(self, record: Any) -> str","id":2905,"name":"format","nodeType":"Function","startLoc":678,"text":"def format(self, record: Any) -> str: ..."},{"attributeType":"str","col":4,"comment":"null","endLoc":666,"id":2906,"name":"default_format","nodeType":"Attribute","startLoc":666,"text":"default_format"},{"col":0,"comment":"\n contextmanager which replaces ``inspect.unwrap`` with a version\n that's aware of mock objects and doesn't recurse on them\n ","endLoc":396,"header":"@contextmanager\ndef _patch_unwrap_mock_aware()","id":2907,"name":"_patch_unwrap_mock_aware","nodeType":"Function","startLoc":367,"text":"@contextmanager\ndef _patch_unwrap_mock_aware():\n \"\"\"\n contextmanager which replaces ``inspect.unwrap`` with a version\n that's aware of mock objects and doesn't recurse on them\n \"\"\"\n real_unwrap = getattr(inspect, \"unwrap\", None)\n if real_unwrap is None:\n yield\n else:\n\n def _mock_aware_unwrap(obj, stop=None):\n try:\n if stop is None or stop is _is_mocked:\n return real_unwrap(obj, stop=_is_mocked)\n return real_unwrap(obj, stop=lambda obj: _is_mocked(obj) or stop(obj))\n except Exception as e:\n warnings.warn(\n \"Got %r when unwrapping %r. This is usually caused \"\n \"by a violation of Python's object protocol; see e.g. \"\n \"https://github.com/pytest-dev/pytest/issues/5080\" % (e, obj),\n PytestWarning,\n )\n raise\n\n inspect.unwrap = _mock_aware_unwrap\n try:\n yield\n finally:\n inspect.unwrap = real_unwrap"},{"attributeType":"str","col":4,"comment":"null","endLoc":667,"id":2908,"name":"asctime_format","nodeType":"Attribute","startLoc":667,"text":"asctime_format"},{"attributeType":"str","col":4,"comment":"null","endLoc":668,"id":2909,"name":"asctime_search","nodeType":"Attribute","startLoc":668,"text":"asctime_search"},{"attributeType":"Pattern","col":4,"comment":"null","endLoc":669,"id":2910,"name":"validation_pattern","nodeType":"Attribute","startLoc":669,"text":"validation_pattern"},{"col":0,"comment":"null","endLoc":144,"header":"@pytest.hookimpl(hookwrapper=True, tryfirst=True)\ndef pytest_runtest_protocol(item)","id":2911,"name":"pytest_runtest_protocol","nodeType":"Function","startLoc":139,"text":"@pytest.hookimpl(hookwrapper=True, tryfirst=True)\ndef pytest_runtest_protocol(item):\n with catch_warnings_for_item(\n config=item.config, ihook=item.ihook, when=\"runtest\", item=item\n ):\n yield"},{"col":45,"endLoc":382,"id":2912,"nodeType":"Lambda","startLoc":382,"text":"lambda obj: _is_mocked(obj) or stop(obj)"},{"attributeType":"str","col":4,"comment":"null","endLoc":670,"id":2913,"name":"_fmt","nodeType":"Attribute","startLoc":670,"text":"_fmt"},{"col":4,"comment":"null","endLoc":332,"header":"def test_add_removed(self, monkeypatch)","id":2914,"name":"test_add_removed","nodeType":"Function","startLoc":323,"text":"def test_add_removed(self, monkeypatch):\n assert self.key not in sys.modules\n monkeypatch.setitem(sys.modules, self.key, \"something\")\n assert self.key in sys.modules\n original = dict(sys.modules)\n snapshot = SysModulesSnapshot()\n del sys.modules[self.key]\n assert self.key not in sys.modules\n snapshot.restore()\n assert sys.modules == original"},{"className":"LogCaptureHandler","col":0,"comment":"A logging handler that stores log records and the log text.","endLoc":246,"id":2915,"nodeType":"Class","startLoc":231,"text":"class LogCaptureHandler(logging.StreamHandler):\n \"\"\"A logging handler that stores log records and the log text.\"\"\"\n\n def __init__(self):\n \"\"\"Creates a new log handler.\"\"\"\n logging.StreamHandler.__init__(self, py.io.TextIO())\n self.records = []\n\n def emit(self, record):\n \"\"\"Keep the log records in a list in addition to the log text.\"\"\"\n self.records.append(record)\n logging.StreamHandler.emit(self, record)\n\n def reset(self):\n self.records = []\n self.stream = py.io.TextIO()"},{"className":"StreamHandler","col":0,"comment":"null","endLoc":634,"id":2916,"nodeType":"Class","startLoc":625,"text":"class StreamHandler(Handler, Generic[_StreamT]):\n stream: _StreamT # undocumented\n terminator: str\n @overload\n def __init__(self: StreamHandler[TextIO], stream: None = None) -> None: ...\n @overload\n def __init__(self: StreamHandler[_StreamT], stream: _StreamT) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780\n def setStream(self, stream: _StreamT) -> _StreamT | None: ...\n if sys.version_info >= (3, 11):\n def __class_getitem__(cls, item: Any, /) -> GenericAlias: ..."},{"attributeType":"str","col":8,"comment":"null","endLoc":34,"id":2917,"name":"drv1","nodeType":"Attribute","startLoc":34,"text":"drv1"},{"attributeType":"str","col":8,"comment":"null","endLoc":35,"id":2918,"name":"drv2","nodeType":"Attribute","startLoc":35,"text":"drv2"},{"attributeType":"str","col":8,"comment":"null","endLoc":37,"id":2919,"name":"drv1","nodeType":"Attribute","startLoc":37,"text":"drv1"},{"attributeType":"str","col":8,"comment":"null","endLoc":38,"id":2920,"name":"drv2","nodeType":"Attribute","startLoc":38,"text":"drv2"},{"col":0,"comment":"Ensure that deleting a numbered dir does not fail because of OSErrors (#4262).","endLoc":87,"header":"def test_access_denied_during_cleanup(tmp_path, monkeypatch)","id":2921,"name":"test_access_denied_during_cleanup","nodeType":"Function","startLoc":75,"text":"def test_access_denied_during_cleanup(tmp_path, monkeypatch):\n \"\"\"Ensure that deleting a numbered dir does not fail because of OSErrors (#4262).\"\"\"\n path = tmp_path / \"temp-1\"\n path.mkdir()\n\n def renamed_failed(*args):\n raise OSError(\"access denied\")\n\n monkeypatch.setattr(Path, \"rename\", renamed_failed)\n\n lock_path = get_lock_path(path)\n maybe_delete_a_numbered_dir(path)\n assert not lock_path.is_file()"},{"className":"DoctestItem","col":0,"comment":"null","endLoc":279,"id":2922,"nodeType":"Class","startLoc":184,"text":"class DoctestItem(pytest.Item):\n def __init__(self, name, parent, runner=None, dtest=None):\n super(DoctestItem, self).__init__(name, parent)\n self.runner = runner\n self.dtest = dtest\n self.obj = None\n self.fixture_request = None\n\n def setup(self):\n if self.dtest is not None:\n self.fixture_request = _setup_fixtures(self)\n globs = dict(getfixture=self.fixture_request.getfixturevalue)\n for name, value in self.fixture_request.getfixturevalue(\n \"doctest_namespace\"\n ).items():\n globs[name] = value\n self.dtest.globs.update(globs)\n\n def runtest(self):\n _check_all_skipped(self.dtest)\n self._disable_output_capturing_for_darwin()\n failures = []\n self.runner.run(self.dtest, out=failures)\n if failures:\n raise MultipleDoctestFailures(failures)\n\n def _disable_output_capturing_for_darwin(self):\n \"\"\"\n Disable output capturing. Otherwise, stdout is lost to doctest (#985)\n \"\"\"\n if platform.system() != \"Darwin\":\n return\n capman = self.config.pluginmanager.getplugin(\"capturemanager\")\n if capman:\n capman.suspend_global_capture(in_=True)\n out, err = capman.read_global_capture()\n sys.stdout.write(out)\n sys.stderr.write(err)\n\n def repr_failure(self, excinfo):\n import doctest\n\n failures = None\n if excinfo.errisinstance((doctest.DocTestFailure, doctest.UnexpectedException)):\n failures = [excinfo.value]\n elif excinfo.errisinstance(MultipleDoctestFailures):\n failures = excinfo.value.failures\n\n if failures is not None:\n reprlocation_lines = []\n for failure in failures:\n example = failure.example\n test = failure.test\n filename = test.filename\n if test.lineno is None:\n lineno = None\n else:\n lineno = test.lineno + example.lineno + 1\n message = type(failure).__name__\n reprlocation = ReprFileLocation(filename, lineno, message)\n checker = _get_checker()\n report_choice = _get_report_choice(\n self.config.getoption(\"doctestreport\")\n )\n if lineno is not None:\n lines = failure.test.docstring.splitlines(False)\n # add line numbers to the left of the error message\n lines = [\n \"%03d %s\" % (i + test.lineno + 1, x)\n for (i, x) in enumerate(lines)\n ]\n # trim docstring error lines to 10\n lines = lines[max(example.lineno - 9, 0) : example.lineno + 1]\n else:\n lines = [\n \"EXAMPLE LOCATION UNKNOWN, not showing all tests of that example\"\n ]\n indent = \">>>\"\n for line in example.source.splitlines():\n lines.append(\"??? %s %s\" % (indent, line))\n indent = \"...\"\n if isinstance(failure, doctest.DocTestFailure):\n lines += checker.output_difference(\n example, failure.got, report_choice\n ).split(\"\\n\")\n else:\n inner_excinfo = ExceptionInfo(failure.exc_info)\n lines += [\"UNEXPECTED EXCEPTION: %s\" % repr(inner_excinfo.value)]\n lines += traceback.format_exception(*failure.exc_info)\n reprlocation_lines.append((reprlocation, lines))\n return ReprFailDoctest(reprlocation_lines)\n else:\n return super(DoctestItem, self).repr_failure(excinfo)\n\n def reportinfo(self):\n return self.fspath, self.dtest.lineno, \"[doctest] %s\" % self.name"},{"col":4,"comment":"null","endLoc":190,"header":"def __init__(self, name, parent, runner=None, dtest=None)","id":2923,"name":"__init__","nodeType":"Function","startLoc":185,"text":"def __init__(self, name, parent, runner=None, dtest=None):\n super(DoctestItem, self).__init__(name, parent)\n self.runner = runner\n self.dtest = dtest\n self.obj = None\n self.fixture_request = None"},{"className":"Handler","col":0,"comment":"null","endLoc":266,"id":2924,"nodeType":"Class","startLoc":248,"text":"class Handler(Filterer):\n level: int # undocumented\n formatter: Formatter | None # undocumented\n lock: threading.Lock | None # undocumented\n name: str | None # undocumented\n def __init__(self, level: _Level = 0) -> None: ...\n def get_name(self) -> str: ... # undocumented\n def set_name(self, name: str) -> None: ... # undocumented\n def createLock(self) -> None: ...\n def acquire(self) -> None: ...\n def release(self) -> None: ...\n def setLevel(self, level: _Level) -> None: ...\n def setFormatter(self, fmt: Formatter | None) -> None: ...\n def flush(self) -> None: ...\n def close(self) -> None: ...\n def handle(self, record: LogRecord) -> bool: ...\n def handleError(self, record: LogRecord) -> None: ...\n def format(self, record: LogRecord) -> str: ...\n def emit(self, record: LogRecord) -> None: ..."},{"className":"Filterer","col":0,"comment":"null","endLoc":102,"id":2925,"nodeType":"Class","startLoc":95,"text":"class Filterer:\n filters: list[_FilterType]\n def addFilter(self, filter: _FilterType) -> None: ...\n def removeFilter(self, filter: _FilterType) -> None: ...\n if sys.version_info >= (3, 12):\n def filter(self, record: LogRecord) -> bool | LogRecord: ...\n else:\n def filter(self, record: LogRecord) -> bool: ..."},{"col":4,"comment":"null","endLoc":97,"header":"def addFilter(self, filter: _FilterType) -> None","id":2926,"name":"addFilter","nodeType":"Function","startLoc":97,"text":"def addFilter(self, filter: _FilterType) -> None: ..."},{"col":4,"comment":"null","endLoc":98,"header":"def removeFilter(self, filter: _FilterType) -> None","id":2927,"name":"removeFilter","nodeType":"Function","startLoc":98,"text":"def removeFilter(self, filter: _FilterType) -> None: ..."},{"col":8,"comment":"null","endLoc":102,"header":"def filter(self, record: LogRecord) -> bool","id":2928,"name":"filter","nodeType":"Function","startLoc":102,"text":"def filter(self, record: LogRecord) -> bool: ..."},{"attributeType":"list","col":4,"comment":"null","endLoc":96,"id":2929,"name":"filters","nodeType":"Attribute","startLoc":96,"text":"filters"},{"col":0,"comment":"null","endLoc":135,"header":"def test_conftest_global_import(testdir)","id":2930,"name":"test_conftest_global_import","nodeType":"Function","startLoc":114,"text":"def test_conftest_global_import(testdir):\n testdir.makeconftest(\"x=3\")\n p = testdir.makepyfile(\n \"\"\"\n import py, pytest\n from _pytest.config import PytestPluginManager\n conf = PytestPluginManager()\n mod = conf._importconftest(py.path.local(\"conftest.py\"))\n assert mod.x == 3\n import conftest\n assert conftest is mod, (conftest, mod)\n subconf = py.path.local().ensure(\"sub\", \"conftest.py\")\n subconf.write(\"y=4\")\n mod2 = conf._importconftest(subconf)\n assert mod != mod2\n assert mod2.y == 4\n import conftest\n assert conftest is mod2, (conftest, mod)\n \"\"\"\n )\n res = testdir.runpython(p)\n assert res.ret == 0"},{"col":0,"comment":"null","endLoc":155,"header":"def test_conftestcutdir(testdir)","id":2931,"name":"test_conftestcutdir","nodeType":"Function","startLoc":138,"text":"def test_conftestcutdir(testdir):\n conf = testdir.makeconftest(\"\")\n p = testdir.mkdir(\"x\")\n conftest = PytestPluginManager()\n conftest_setinitial(conftest, [testdir.tmpdir], confcutdir=p)\n values = conftest._getconftestmodules(p)\n assert len(values) == 0\n values = conftest._getconftestmodules(conf.dirpath())\n assert len(values) == 0\n assert conf not in conftest._conftestpath2mod\n # but we can still import a conftest directly\n conftest._importconftest(conf)\n values = conftest._getconftestmodules(conf.dirpath())\n assert values[0].__file__.startswith(str(conf))\n # and all sub paths get updated properly\n values = conftest._getconftestmodules(p)\n assert len(values) == 1\n assert values[0].__file__.startswith(str(conf))"},{"attributeType":"list","col":0,"comment":"null","endLoc":676,"id":2932,"name":"scopes","nodeType":"Attribute","startLoc":676,"text":"scopes"},{"attributeType":"int","col":0,"comment":"null","endLoc":677,"id":2933,"name":"scopenum_function","nodeType":"Attribute","startLoc":677,"text":"scopenum_function"},{"attributeType":"function | FixtureFunctionMarker","col":0,"comment":"null","endLoc":1060,"id":2934,"name":"defaultfuncargprefixmarker","nodeType":"Attribute","startLoc":1060,"text":"defaultfuncargprefixmarker"},{"col":4,"comment":"null","endLoc":253,"header":"def __init__(self, level: _Level = 0) -> None","id":2935,"name":"__init__","nodeType":"Function","startLoc":253,"text":"def __init__(self, level: _Level = 0) -> None: ..."},{"col":4,"comment":"null","endLoc":254,"header":"def get_name(self) -> str","id":2936,"name":"get_name","nodeType":"Function","startLoc":254,"text":"def get_name(self) -> str: ... # undocumented"},{"col":4,"comment":"null","endLoc":255,"header":"def set_name(self, name: str) -> None","id":2937,"name":"set_name","nodeType":"Function","startLoc":255,"text":"def set_name(self, name: str) -> None: ... # undocumented"},{"col":4,"comment":"null","endLoc":256,"header":"def createLock(self) -> None","id":2938,"name":"createLock","nodeType":"Function","startLoc":256,"text":"def createLock(self) -> None: ..."},{"col":4,"comment":"null","endLoc":257,"header":"def acquire(self) -> None","id":2939,"name":"acquire","nodeType":"Function","startLoc":257,"text":"def acquire(self) -> None: ..."},{"col":4,"comment":"null","endLoc":258,"header":"def release(self) -> None","id":2940,"name":"release","nodeType":"Function","startLoc":258,"text":"def release(self) -> None: ..."},{"col":4,"comment":"null","endLoc":259,"header":"def setLevel(self, level: _Level) -> None","id":2941,"name":"setLevel","nodeType":"Function","startLoc":259,"text":"def setLevel(self, level: _Level) -> None: ..."},{"col":4,"comment":"null","endLoc":260,"header":"def setFormatter(self, fmt: Formatter | None) -> None","id":2942,"name":"setFormatter","nodeType":"Function","startLoc":260,"text":"def setFormatter(self, fmt: Formatter | None) -> None: ..."},{"col":4,"comment":"null","endLoc":261,"header":"def flush(self) -> None","id":2943,"name":"flush","nodeType":"Function","startLoc":261,"text":"def flush(self) -> None: ..."},{"col":4,"comment":"null","endLoc":262,"header":"def close(self) -> None","id":2944,"name":"close","nodeType":"Function","startLoc":262,"text":"def close(self) -> None: ..."},{"col":4,"comment":"null","endLoc":263,"header":"def handle(self, record: LogRecord) -> bool","id":2945,"name":"handle","nodeType":"Function","startLoc":263,"text":"def handle(self, record: LogRecord) -> bool: ..."},{"col":4,"comment":"null","endLoc":264,"header":"def handleError(self, record: LogRecord) -> None","id":2946,"name":"handleError","nodeType":"Function","startLoc":264,"text":"def handleError(self, record: LogRecord) -> None: ..."},{"col":4,"comment":"null","endLoc":265,"header":"def format(self, record: LogRecord) -> str","id":2947,"name":"format","nodeType":"Function","startLoc":265,"text":"def format(self, record: LogRecord) -> str: ..."},{"col":4,"comment":"null","endLoc":266,"header":"def emit(self, record: LogRecord) -> None","id":2948,"name":"emit","nodeType":"Function","startLoc":266,"text":"def emit(self, record: LogRecord) -> None: ..."},{"attributeType":"int","col":4,"comment":"null","endLoc":249,"id":2949,"name":"level","nodeType":"Attribute","startLoc":249,"text":"level"},{"attributeType":"Formatter | None","col":4,"comment":"null","endLoc":250,"id":2950,"name":"formatter","nodeType":"Attribute","startLoc":250,"text":"formatter"},{"attributeType":"Lock | None","col":4,"comment":"null","endLoc":251,"id":2951,"name":"lock","nodeType":"Attribute","startLoc":251,"text":"lock"},{"col":4,"comment":"null","endLoc":200,"header":"def setup(self)","id":2952,"name":"setup","nodeType":"Function","startLoc":192,"text":"def setup(self):\n if self.dtest is not None:\n self.fixture_request = _setup_fixtures(self)\n globs = dict(getfixture=self.fixture_request.getfixturevalue)\n for name, value in self.fixture_request.getfixturevalue(\n \"doctest_namespace\"\n ).items():\n globs[name] = value\n self.dtest.globs.update(globs)"},{"id":2953,"name":"release-3.0.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.0.2\n============\n\npytest 3.0.2 has just been released to PyPI.\n\nThis release fixes some regressions and bugs reported in version 3.0.1, being a\ndrop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Ahn Ki-Wook\n* Bruno Oliveira\n* Florian Bruhin\n* Jordan Guymon\n* Raphael Pierzina\n* Ronny Pfannschmidt\n* mbyt\n\nHappy testing,\nThe pytest Development Team\n"},{"id":2954,"name":"azure-pipelines.yml","nodeType":"TextFile","path":"","text":"trigger:\n- master\n- features\n\nvariables:\n PYTEST_ADDOPTS: \"--junitxml=build/test-results/$(tox.env).xml -vv\"\n python.needs_vc: False\n COVERAGE_FILE: \"$(Build.Repository.LocalPath)/.coverage\"\n COVERAGE_PROCESS_START: \"$(Build.Repository.LocalPath)/.coveragerc\"\n PYTEST_COVERAGE: '0'\n\njobs:\n\n- job: 'Test'\n pool:\n vmImage: \"vs2017-win2016\"\n strategy:\n matrix:\n py27:\n python.version: '2.7'\n tox.env: 'py27'\n py27-nobyte-lsof-numpy:\n python.version: '2.7'\n tox.env: 'py27-lsof-nobyte-numpy'\n # Coverage for:\n # - test_supports_breakpoint_module_global\n # - test_terminal_reporter_writer_attr (without xdist)\n # - \"if write\" branch in _pytest.assertion.rewrite\n # - numpy\n # - pytester's LsofFdLeakChecker (being skipped)\n PYTEST_COVERAGE: '1'\n py27-twisted:\n python.version: '2.7'\n tox.env: 'py27-twisted'\n python.needs_vc: True\n py27-pluggymaster-xdist:\n python.version: '2.7'\n tox.env: 'py27-pluggymaster-xdist'\n # Coverage for:\n # - except-IOError in _attempt_to_close_capture_file for py2.\n # Also seen with py27-nobyte (using xdist), and py27-xdist.\n # But no exception with py27-pexpect,py27-twisted,py27-numpy.\n PYTEST_COVERAGE: '1'\n # -- pypy2 and pypy3 are disabled for now: #5279 --\n # pypy:\n # python.version: 'pypy2'\n # tox.env: 'pypy'\n # pypy3:\n # python.version: 'pypy3'\n # tox.env: 'pypy3'\n py34-xdist:\n python.version: '3.4'\n tox.env: 'py34-xdist'\n # Coverage for:\n # - _pytest.compat._bytes_to_ascii\n PYTEST_COVERAGE: '1'\n py35-xdist:\n python.version: '3.5'\n tox.env: 'py35-xdist'\n # Coverage for:\n # - test_supports_breakpoint_module_global\n PYTEST_COVERAGE: '1'\n py36-xdist:\n python.version: '3.6'\n tox.env: 'py36-xdist'\n py37:\n python.version: '3.7'\n tox.env: 'py37'\n # Coverage for:\n # - _py36_windowsconsoleio_workaround (with py36+)\n # - test_request_garbage (no xdist)\n PYTEST_COVERAGE: '1'\n py37-linting/docs/doctesting:\n python.version: '3.7'\n tox.env: 'linting,docs,doctesting'\n py37-twisted/numpy:\n python.version: '3.7'\n tox.env: 'py37-twisted,py37-numpy'\n py37-pluggymaster-xdist:\n python.version: '3.7'\n tox.env: 'py37-pluggymaster-xdist'\n maxParallel: 10\n\n steps:\n - task: UsePythonVersion@0\n inputs:\n versionSpec: '$(python.version)'\n architecture: 'x64'\n\n - script: choco install vcpython27\n condition: eq(variables['python.needs_vc'], True)\n displayName: 'Install VC for py27'\n\n - script: python -m pip install tox\n displayName: 'Install tox'\n\n - script: |\n call scripts/setup-coverage-vars.bat || goto :eof\n python -m tox -e $(tox.env)\n displayName: 'Run tests'\n\n - task: PublishTestResults@2\n inputs:\n testResultsFiles: 'build/test-results/$(tox.env).xml'\n testRunTitle: '$(tox.env)'\n condition: succeededOrFailed()\n\n - script: call scripts\\upload-coverage.bat\n displayName: 'Report and upload coverage'\n condition: eq(variables['PYTEST_COVERAGE'], '1')\n env:\n CODECOV_TOKEN: $(CODECOV_TOKEN)\n PYTEST_CODECOV_NAME: $(tox.env)\n"},{"fileName":"stepwise.py","filePath":"src/_pytest","id":2955,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\ndef pytest_addoption(parser):\n group = parser.getgroup(\"general\")\n group.addoption(\n \"--sw\",\n \"--stepwise\",\n action=\"store_true\",\n dest=\"stepwise\",\n help=\"exit on test failure and continue from last failing test next time\",\n )\n group.addoption(\n \"--stepwise-skip\",\n action=\"store_true\",\n dest=\"stepwise_skip\",\n help=\"ignore the first failing test but stop on the next failing test\",\n )\n\n\n@pytest.hookimpl\ndef pytest_configure(config):\n config.pluginmanager.register(StepwisePlugin(config), \"stepwiseplugin\")\n\n\nclass StepwisePlugin:\n def __init__(self, config):\n self.config = config\n self.active = config.getvalue(\"stepwise\")\n self.session = None\n self.report_status = \"\"\n\n if self.active:\n self.lastfailed = config.cache.get(\"cache/stepwise\", None)\n self.skip = config.getvalue(\"stepwise_skip\")\n\n def pytest_sessionstart(self, session):\n self.session = session\n\n def pytest_collection_modifyitems(self, session, config, items):\n if not self.active:\n return\n if not self.lastfailed:\n self.report_status = \"no previously failed tests, not skipping.\"\n return\n\n already_passed = []\n found = False\n\n # Make a list of all tests that have been run before the last failing one.\n for item in items:\n if item.nodeid == self.lastfailed:\n found = True\n break\n else:\n already_passed.append(item)\n\n # If the previously failed test was not found among the test items,\n # do not skip any tests.\n if not found:\n self.report_status = \"previously failed test not found, not skipping.\"\n already_passed = []\n else:\n self.report_status = \"skipping {} already passed items.\".format(\n len(already_passed)\n )\n\n for item in already_passed:\n items.remove(item)\n\n config.hook.pytest_deselected(items=already_passed)\n\n def pytest_runtest_logreport(self, report):\n if not self.active:\n return\n\n if report.failed:\n if self.skip:\n # Remove test from the failed ones (if it exists) and unset the skip option\n # to make sure the following tests will not be skipped.\n if report.nodeid == self.lastfailed:\n self.lastfailed = None\n\n self.skip = False\n else:\n # Mark test as the last failing and interrupt the test session.\n self.lastfailed = report.nodeid\n self.session.shouldstop = (\n \"Test failed, continuing from this test next run.\"\n )\n\n else:\n # If the test was actually run and did pass.\n if report.when == \"call\":\n # Remove test from the failed ones, if exists.\n if report.nodeid == self.lastfailed:\n self.lastfailed = None\n\n def pytest_report_collectionfinish(self):\n if self.active and self.config.getoption(\"verbose\") >= 0 and self.report_status:\n return \"stepwise: %s\" % self.report_status\n\n def pytest_sessionfinish(self, session):\n if self.active:\n self.config.cache.set(\"cache/stepwise\", self.lastfailed)\n else:\n # Clear the list of failing tests if the plugin is not active.\n self.config.cache.set(\"cache/stepwise\", [])\n"},{"className":"StepwisePlugin","col":0,"comment":"null","endLoc":109,"id":2956,"nodeType":"Class","startLoc":27,"text":"class StepwisePlugin:\n def __init__(self, config):\n self.config = config\n self.active = config.getvalue(\"stepwise\")\n self.session = None\n self.report_status = \"\"\n\n if self.active:\n self.lastfailed = config.cache.get(\"cache/stepwise\", None)\n self.skip = config.getvalue(\"stepwise_skip\")\n\n def pytest_sessionstart(self, session):\n self.session = session\n\n def pytest_collection_modifyitems(self, session, config, items):\n if not self.active:\n return\n if not self.lastfailed:\n self.report_status = \"no previously failed tests, not skipping.\"\n return\n\n already_passed = []\n found = False\n\n # Make a list of all tests that have been run before the last failing one.\n for item in items:\n if item.nodeid == self.lastfailed:\n found = True\n break\n else:\n already_passed.append(item)\n\n # If the previously failed test was not found among the test items,\n # do not skip any tests.\n if not found:\n self.report_status = \"previously failed test not found, not skipping.\"\n already_passed = []\n else:\n self.report_status = \"skipping {} already passed items.\".format(\n len(already_passed)\n )\n\n for item in already_passed:\n items.remove(item)\n\n config.hook.pytest_deselected(items=already_passed)\n\n def pytest_runtest_logreport(self, report):\n if not self.active:\n return\n\n if report.failed:\n if self.skip:\n # Remove test from the failed ones (if it exists) and unset the skip option\n # to make sure the following tests will not be skipped.\n if report.nodeid == self.lastfailed:\n self.lastfailed = None\n\n self.skip = False\n else:\n # Mark test as the last failing and interrupt the test session.\n self.lastfailed = report.nodeid\n self.session.shouldstop = (\n \"Test failed, continuing from this test next run.\"\n )\n\n else:\n # If the test was actually run and did pass.\n if report.when == \"call\":\n # Remove test from the failed ones, if exists.\n if report.nodeid == self.lastfailed:\n self.lastfailed = None\n\n def pytest_report_collectionfinish(self):\n if self.active and self.config.getoption(\"verbose\") >= 0 and self.report_status:\n return \"stepwise: %s\" % self.report_status\n\n def pytest_sessionfinish(self, session):\n if self.active:\n self.config.cache.set(\"cache/stepwise\", self.lastfailed)\n else:\n # Clear the list of failing tests if the plugin is not active.\n self.config.cache.set(\"cache/stepwise\", [])"},{"attributeType":"str | None","col":4,"comment":"null","endLoc":252,"id":2957,"name":"name","nodeType":"Attribute","startLoc":252,"text":"name"},{"col":4,"comment":"null","endLoc":36,"header":"def __init__(self, config)","id":2958,"name":"__init__","nodeType":"Function","startLoc":28,"text":"def __init__(self, config):\n self.config = config\n self.active = config.getvalue(\"stepwise\")\n self.session = None\n self.report_status = \"\"\n\n if self.active:\n self.lastfailed = config.cache.get(\"cache/stepwise\", None)\n self.skip = config.getvalue(\"stepwise_skip\")"},{"col":0,"comment":"\n Used by DoctestTextfile and DoctestItem to setup fixture information.\n ","endLoc":460,"header":"def _setup_fixtures(doctest_item)","id":2959,"name":"_setup_fixtures","nodeType":"Function","startLoc":445,"text":"def _setup_fixtures(doctest_item):\n \"\"\"\n Used by DoctestTextfile and DoctestItem to setup fixture information.\n \"\"\"\n\n def func():\n pass\n\n doctest_item.funcargs = {}\n fm = doctest_item.session._fixturemanager\n doctest_item._fixtureinfo = fm.getfixtureinfo(\n node=doctest_item, func=func, cls=None, funcargs=False\n )\n fixture_request = FixtureRequest(doctest_item)\n fixture_request._fillfixtures()\n return fixture_request"},{"col":0,"comment":"null","endLoc":153,"header":"@pytest.hookimpl(hookwrapper=True, tryfirst=True)\ndef pytest_collection(session)","id":2960,"name":"pytest_collection","nodeType":"Function","startLoc":147,"text":"@pytest.hookimpl(hookwrapper=True, tryfirst=True)\ndef pytest_collection(session):\n config = session.config\n with catch_warnings_for_item(\n config=config, ihook=config.hook, when=\"collect\", item=None\n ):\n yield"},{"fileName":"test_resultlog.py","filePath":"testing","id":2961,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nimport py\n\nimport _pytest._code\nimport pytest\nfrom _pytest.resultlog import pytest_configure\nfrom _pytest.resultlog import pytest_unconfigure\nfrom _pytest.resultlog import ResultLog\n\npytestmark = pytest.mark.filterwarnings(\"ignore:--result-log is deprecated\")\n\n\ndef test_write_log_entry():\n reslog = ResultLog(None, None)\n reslog.logfile = py.io.TextIO()\n reslog.write_log_entry(\"name\", \".\", \"\")\n entry = reslog.logfile.getvalue()\n assert entry[-1] == \"\\n\"\n entry_lines = entry.splitlines()\n assert len(entry_lines) == 1\n assert entry_lines[0] == \". name\"\n\n reslog.logfile = py.io.TextIO()\n reslog.write_log_entry(\"name\", \"s\", \"Skipped\")\n entry = reslog.logfile.getvalue()\n assert entry[-1] == \"\\n\"\n entry_lines = entry.splitlines()\n assert len(entry_lines) == 2\n assert entry_lines[0] == \"s name\"\n assert entry_lines[1] == \" Skipped\"\n\n reslog.logfile = py.io.TextIO()\n reslog.write_log_entry(\"name\", \"s\", \"Skipped\\n\")\n entry = reslog.logfile.getvalue()\n assert entry[-1] == \"\\n\"\n entry_lines = entry.splitlines()\n assert len(entry_lines) == 2\n assert entry_lines[0] == \"s name\"\n assert entry_lines[1] == \" Skipped\"\n\n reslog.logfile = py.io.TextIO()\n longrepr = \" tb1\\n tb 2\\nE tb3\\nSome Error\"\n reslog.write_log_entry(\"name\", \"F\", longrepr)\n entry = reslog.logfile.getvalue()\n assert entry[-1] == \"\\n\"\n entry_lines = entry.splitlines()\n assert len(entry_lines) == 5\n assert entry_lines[0] == \"F name\"\n assert entry_lines[1:] == [\" \" + line for line in longrepr.splitlines()]\n\n\nclass TestWithFunctionIntegration(object):\n # XXX (hpk) i think that the resultlog plugin should\n # provide a Parser object so that one can remain\n # ignorant regarding formatting details.\n def getresultlog(self, testdir, arg):\n resultlog = testdir.tmpdir.join(\"resultlog\")\n testdir.plugins.append(\"resultlog\")\n args = [\"--resultlog=%s\" % resultlog] + [arg]\n testdir.runpytest(*args)\n return [x for x in resultlog.readlines(cr=0) if x]\n\n def test_collection_report(self, testdir):\n ok = testdir.makepyfile(test_collection_ok=\"\")\n fail = testdir.makepyfile(test_collection_fail=\"XXX\")\n lines = self.getresultlog(testdir, ok)\n assert not lines\n\n lines = self.getresultlog(testdir, fail)\n assert lines\n assert lines[0].startswith(\"F \")\n assert lines[0].endswith(\"test_collection_fail.py\"), lines[0]\n for x in lines[1:]:\n assert x.startswith(\" \")\n assert \"XXX\" in \"\".join(lines[1:])\n\n def test_log_test_outcomes(self, testdir):\n mod = testdir.makepyfile(\n test_mod=\"\"\"\n import pytest\n def test_pass(): pass\n def test_skip(): pytest.skip(\"hello\")\n def test_fail(): raise ValueError(\"FAIL\")\n\n @pytest.mark.xfail\n def test_xfail(): raise ValueError(\"XFAIL\")\n @pytest.mark.xfail\n def test_xpass(): pass\n\n \"\"\"\n )\n lines = self.getresultlog(testdir, mod)\n assert len(lines) >= 3\n assert lines[0].startswith(\". \")\n assert lines[0].endswith(\"test_pass\")\n assert lines[1].startswith(\"s \"), lines[1]\n assert lines[1].endswith(\"test_skip\")\n assert lines[2].find(\"hello\") != -1\n\n assert lines[3].startswith(\"F \")\n assert lines[3].endswith(\"test_fail\")\n tb = \"\".join(lines[4:8])\n assert tb.find('raise ValueError(\"FAIL\")') != -1\n\n assert lines[8].startswith(\"x \")\n tb = \"\".join(lines[8:14])\n assert tb.find('raise ValueError(\"XFAIL\")') != -1\n\n assert lines[14].startswith(\"X \")\n assert len(lines) == 15\n\n @pytest.mark.parametrize(\"style\", (\"native\", \"long\", \"short\"))\n def test_internal_exception(self, style):\n # they are produced for example by a teardown failing\n # at the end of the run or a failing hook invocation\n try:\n raise ValueError\n except ValueError:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n reslog = ResultLog(None, py.io.TextIO())\n reslog.pytest_internalerror(excinfo.getrepr(style=style))\n entry = reslog.logfile.getvalue()\n entry_lines = entry.splitlines()\n\n assert entry_lines[0].startswith(\"! \")\n if style != \"native\":\n assert os.path.basename(__file__)[:-9] in entry_lines[0] # .pyc/class\n assert entry_lines[-1][0] == \" \"\n assert \"ValueError\" in entry\n\n\ndef test_generic(testdir, LineMatcher):\n testdir.plugins.append(\"resultlog\")\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_pass():\n pass\n def test_fail():\n assert 0\n def test_skip():\n pytest.skip(\"\")\n @pytest.mark.xfail\n def test_xfail():\n assert 0\n @pytest.mark.xfail(run=False)\n def test_xfail_norun():\n assert 0\n \"\"\"\n )\n testdir.runpytest(\"--resultlog=result.log\")\n lines = testdir.tmpdir.join(\"result.log\").readlines(cr=0)\n LineMatcher(lines).fnmatch_lines(\n [\n \". *:test_pass\",\n \"F *:test_fail\",\n \"s *:test_skip\",\n \"x *:test_xfail\",\n \"x *:test_xfail_norun\",\n ]\n )\n\n\ndef test_makedir_for_resultlog(testdir, LineMatcher):\n \"\"\"--resultlog should automatically create directories for the log file\"\"\"\n testdir.plugins.append(\"resultlog\")\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_pass():\n pass\n \"\"\"\n )\n testdir.runpytest(\"--resultlog=path/to/result.log\")\n lines = testdir.tmpdir.join(\"path/to/result.log\").readlines(cr=0)\n LineMatcher(lines).fnmatch_lines([\". *:test_pass\"])\n\n\ndef test_no_resultlog_on_slaves(testdir):\n config = testdir.parseconfig(\"-p\", \"resultlog\", \"--resultlog=resultlog\")\n\n assert not hasattr(config, \"_resultlog\")\n pytest_configure(config)\n assert hasattr(config, \"_resultlog\")\n pytest_unconfigure(config)\n assert not hasattr(config, \"_resultlog\")\n\n config.slaveinput = {}\n pytest_configure(config)\n assert not hasattr(config, \"_resultlog\")\n pytest_unconfigure(config)\n assert not hasattr(config, \"_resultlog\")\n\n\ndef test_failure_issue380(testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n class MyCollector(pytest.File):\n def collect(self):\n raise ValueError()\n def repr_failure(self, excinfo):\n return \"somestring\"\n def pytest_collect_file(path, parent):\n return MyCollector(parent=parent, fspath=path)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--resultlog=log\")\n assert result.ret == 2\n"},{"col":0,"comment":"null","endLoc":164,"header":"def test_conftestcutdir_inplace_considered(testdir)","id":2962,"name":"test_conftestcutdir_inplace_considered","nodeType":"Function","startLoc":158,"text":"def test_conftestcutdir_inplace_considered(testdir):\n conf = testdir.makeconftest(\"\")\n conftest = PytestPluginManager()\n conftest_setinitial(conftest, [conf.dirpath()], confcutdir=conf.dirpath())\n values = conftest._getconftestmodules(conf.dirpath())\n assert len(values) == 1\n assert values[0].__file__.startswith(str(conf))"},{"col":0,"comment":"null","endLoc":40,"header":"def pytest_configure(config)","id":2963,"name":"pytest_configure","nodeType":"Function","startLoc":26,"text":"def pytest_configure(config):\n resultlog = config.option.resultlog\n # prevent opening resultlog on slave nodes (xdist)\n if resultlog and not hasattr(config, \"slaveinput\"):\n dirname = os.path.dirname(os.path.abspath(resultlog))\n if not os.path.isdir(dirname):\n os.makedirs(dirname)\n logfile = open(resultlog, \"w\", 1) # line buffered\n config._resultlog = ResultLog(config, logfile)\n config.pluginmanager.register(config._resultlog)\n\n from _pytest.deprecated import RESULT_LOG\n from _pytest.warnings import _issue_warning_captured\n\n _issue_warning_captured(RESULT_LOG, config.hook, stacklevel=2)"},{"col":0,"comment":"null","endLoc":162,"header":"@pytest.hookimpl(hookwrapper=True)\ndef pytest_terminal_summary(terminalreporter)","id":2964,"name":"pytest_terminal_summary","nodeType":"Function","startLoc":156,"text":"@pytest.hookimpl(hookwrapper=True)\ndef pytest_terminal_summary(terminalreporter):\n config = terminalreporter.config\n with catch_warnings_for_item(\n config=config, ihook=config.hook, when=\"config\", item=None\n ):\n yield"},{"col":0,"comment":"","endLoc":2,"header":"warnings.py#","id":2965,"name":"","nodeType":"Function","startLoc":2,"text":"SHOW_PYTEST_WARNINGS_ARG = \"-Walways::pytest.RemovedInPytest4Warning\""},{"id":2966,"name":"release-4.6.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-4.6.1\n=======================================\n\npytest 4.6.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n\n\nHappy testing,\nThe pytest Development Team\n"},{"id":2967,"name":"LICENSE","nodeType":"TextFile","path":"","text":"The MIT License (MIT)\n\nCopyright (c) 2004-2019 Holger Krekel and others\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"},{"col":4,"comment":"null","endLoc":342,"header":"def test_restore_reloaded(self, monkeypatch)","id":2968,"name":"test_restore_reloaded","nodeType":"Function","startLoc":334,"text":"def test_restore_reloaded(self, monkeypatch):\n assert self.key not in sys.modules\n monkeypatch.setitem(sys.modules, self.key, \"something\")\n assert self.key in sys.modules\n original = dict(sys.modules)\n snapshot = SysModulesSnapshot()\n sys.modules[self.key] = \"something else\"\n snapshot.restore()\n assert sys.modules == original"},{"col":4,"comment":"null","endLoc":629,"header":"@overload\n def __init__(self: StreamHandler[TextIO], stream: None = None) -> None","id":2969,"name":"__init__","nodeType":"Function","startLoc":628,"text":"@overload\n def __init__(self: StreamHandler[TextIO], stream: None = None) -> None: ..."},{"col":4,"comment":"null","endLoc":631,"header":"@overload\n def __init__(self: StreamHandler[_StreamT], stream: _StreamT) -> None","id":2970,"name":"__init__","nodeType":"Function","startLoc":630,"text":"@overload\n def __init__(self: StreamHandler[_StreamT], stream: _StreamT) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780"},{"col":4,"comment":"null","endLoc":632,"header":"def setStream(self, stream: _StreamT) -> _StreamT | None","id":2971,"name":"setStream","nodeType":"Function","startLoc":632,"text":"def setStream(self, stream: _StreamT) -> _StreamT | None: ..."},{"attributeType":"_StreamT","col":4,"comment":"null","endLoc":626,"id":2972,"name":"stream","nodeType":"Attribute","startLoc":626,"text":"stream"},{"col":4,"comment":"null","endLoc":39,"header":"def pytest_sessionstart(self, session)","id":2973,"name":"pytest_sessionstart","nodeType":"Function","startLoc":38,"text":"def pytest_sessionstart(self, session):\n self.session = session"},{"col":4,"comment":"null","endLoc":72,"header":"def pytest_collection_modifyitems(self, session, config, items)","id":2974,"name":"pytest_collection_modifyitems","nodeType":"Function","startLoc":41,"text":"def pytest_collection_modifyitems(self, session, config, items):\n if not self.active:\n return\n if not self.lastfailed:\n self.report_status = \"no previously failed tests, not skipping.\"\n return\n\n already_passed = []\n found = False\n\n # Make a list of all tests that have been run before the last failing one.\n for item in items:\n if item.nodeid == self.lastfailed:\n found = True\n break\n else:\n already_passed.append(item)\n\n # If the previously failed test was not found among the test items,\n # do not skip any tests.\n if not found:\n self.report_status = \"previously failed test not found, not skipping.\"\n already_passed = []\n else:\n self.report_status = \"skipping {} already passed items.\".format(\n len(already_passed)\n )\n\n for item in already_passed:\n items.remove(item)\n\n config.hook.pytest_deselected(items=already_passed)"},{"col":4,"comment":"null","endLoc":208,"header":"def runtest(self)","id":2975,"name":"runtest","nodeType":"Function","startLoc":202,"text":"def runtest(self):\n _check_all_skipped(self.dtest)\n self._disable_output_capturing_for_darwin()\n failures = []\n self.runner.run(self.dtest, out=failures)\n if failures:\n raise MultipleDoctestFailures(failures)"},{"col":0,"comment":"raises pytest.skip() if all examples in the given DocTest have the SKIP\n option set.\n ","endLoc":354,"header":"def _check_all_skipped(test)","id":2976,"name":"_check_all_skipped","nodeType":"Function","startLoc":346,"text":"def _check_all_skipped(test):\n \"\"\"raises pytest.skip() if all examples in the given DocTest have the SKIP\n option set.\n \"\"\"\n import doctest\n\n all_skipped = all(x.options.get(doctest.SKIP, False) for x in test.examples)\n if all_skipped:\n pytest.skip(\"all tests skipped by +SKIP option\")"},{"col":4,"comment":"null","endLoc":54,"header":"def __init__(self, config, logfile)","id":2977,"name":"__init__","nodeType":"Function","startLoc":52,"text":"def __init__(self, config, logfile):\n self.config = config\n self.logfile = logfile # preferably line buffered"},{"col":0,"comment":"null","endLoc":178,"header":"@pytest.mark.parametrize(\"name\", \"test tests whatever .dotdir\".split())\ndef test_setinitial_conftest_subdirs(testdir, name)","id":2978,"name":"test_setinitial_conftest_subdirs","nodeType":"Function","startLoc":167,"text":"@pytest.mark.parametrize(\"name\", \"test tests whatever .dotdir\".split())\ndef test_setinitial_conftest_subdirs(testdir, name):\n sub = testdir.mkdir(name)\n subconftest = sub.ensure(\"conftest.py\")\n conftest = PytestPluginManager()\n conftest_setinitial(conftest, [sub.dirpath()], confcutdir=testdir.tmpdir)\n if name not in (\"whatever\", \".dotdir\"):\n assert subconftest in conftest._conftestpath2mod\n assert len(conftest._conftestpath2mod) == 1\n else:\n assert subconftest not in conftest._conftestpath2mod\n assert len(conftest._conftestpath2mod) == 0"},{"col":0,"comment":"null","endLoc":48,"header":"def pytest_unconfigure(config)","id":2979,"name":"pytest_unconfigure","nodeType":"Function","startLoc":43,"text":"def pytest_unconfigure(config):\n resultlog = getattr(config, \"_resultlog\", None)\n if resultlog:\n resultlog.logfile.close()\n del config._resultlog\n config.pluginmanager.unregister(resultlog)"},{"attributeType":"str","col":4,"comment":"null","endLoc":627,"id":2980,"name":"terminator","nodeType":"Attribute","startLoc":627,"text":"terminator"},{"className":"ResultLog","col":0,"comment":"null","endLoc":102,"id":2981,"nodeType":"Class","startLoc":51,"text":"class ResultLog(object):\n def __init__(self, config, logfile):\n self.config = config\n self.logfile = logfile # preferably line buffered\n\n def write_log_entry(self, testpath, lettercode, longrepr):\n print(\"%s %s\" % (lettercode, testpath), file=self.logfile)\n for line in longrepr.splitlines():\n print(\" %s\" % line, file=self.logfile)\n\n def log_outcome(self, report, lettercode, longrepr):\n testpath = getattr(report, \"nodeid\", None)\n if testpath is None:\n testpath = report.fspath\n self.write_log_entry(testpath, lettercode, longrepr)\n\n def pytest_runtest_logreport(self, report):\n if report.when != \"call\" and report.passed:\n return\n res = self.config.hook.pytest_report_teststatus(\n report=report, config=self.config\n )\n code = res[1]\n if code == \"x\":\n longrepr = str(report.longrepr)\n elif code == \"X\":\n longrepr = \"\"\n elif report.passed:\n longrepr = \"\"\n elif report.failed:\n longrepr = str(report.longrepr)\n elif report.skipped:\n longrepr = str(report.longrepr[2])\n self.log_outcome(report, code, longrepr)\n\n def pytest_collectreport(self, report):\n if not report.passed:\n if report.failed:\n code = \"F\"\n longrepr = str(report.longrepr)\n else:\n assert report.skipped\n code = \"S\"\n longrepr = \"%s:%d: %s\" % report.longrepr\n self.log_outcome(report, code, longrepr)\n\n def pytest_internalerror(self, excrepr):\n reprcrash = getattr(excrepr, \"reprcrash\", None)\n path = getattr(reprcrash, \"path\", None)\n if path is None:\n path = \"cwd:%s\" % py.path.local()\n self.write_log_entry(path, \"!\", str(excrepr))"},{"col":4,"comment":"null","endLoc":59,"header":"def write_log_entry(self, testpath, lettercode, longrepr)","id":2982,"name":"write_log_entry","nodeType":"Function","startLoc":56,"text":"def write_log_entry(self, testpath, lettercode, longrepr):\n print(\"%s %s\" % (lettercode, testpath), file=self.logfile)\n for line in longrepr.splitlines():\n print(\" %s\" % line, file=self.logfile)"},{"col":4,"comment":"null","endLoc":910,"header":"def parse(self, args, addopts=True)","id":2983,"name":"parse","nodeType":"Function","startLoc":886,"text":"def parse(self, args, addopts=True):\n # parse given cmdline arguments into this config object.\n assert not hasattr(\n self, \"args\"\n ), \"can only parse cmdline args at most once per Config object\"\n self._origargs = args\n self.hook.pytest_addhooks.call_historic(\n kwargs=dict(pluginmanager=self.pluginmanager)\n )\n self._preparse(args, addopts=addopts)\n # XXX deprecated hook:\n self.hook.pytest_cmdline_preparse(config=self, args=args)\n self._parser.after_preparse = True\n try:\n args = self._parser.parse_setoption(\n args, self.option, namespace=self.option\n )\n if not args:\n if self.invocation_dir == self.rootdir:\n args = self.getini(\"testpaths\")\n if not args:\n args = [str(self.invocation_dir)]\n self.args = args\n except PrintHelp:\n pass"},{"col":4,"comment":"null","endLoc":868,"header":"def _preparse(self, args, addopts=True)","id":2984,"name":"_preparse","nodeType":"Function","startLoc":821,"text":"def _preparse(self, args, addopts=True):\n if addopts:\n env_addopts = os.environ.get(\"PYTEST_ADDOPTS\", \"\")\n if len(env_addopts):\n args[:] = (\n self._validate_args(shlex.split(env_addopts), \"via PYTEST_ADDOPTS\")\n + args\n )\n self._initini(args)\n if addopts:\n args[:] = (\n self._validate_args(self.getini(\"addopts\"), \"via addopts config\") + args\n )\n\n self._checkversion()\n self._consider_importhook(args)\n self.pluginmanager.consider_preparse(args)\n if not os.environ.get(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\"):\n # Don't autoload from setuptools entry point. Only explicitly specified\n # plugins are going to be loaded.\n self.pluginmanager.load_setuptools_entrypoints(\"pytest11\")\n self.pluginmanager.consider_env()\n self.known_args_namespace = ns = self._parser.parse_known_args(\n args, namespace=copy.copy(self.option)\n )\n if self.known_args_namespace.confcutdir is None and self.inifile:\n confcutdir = py.path.local(self.inifile).dirname\n self.known_args_namespace.confcutdir = confcutdir\n try:\n self.hook.pytest_load_initial_conftests(\n early_config=self, args=args, parser=self._parser\n )\n except ConftestImportFailure:\n e = sys.exc_info()[1]\n if ns.help or ns.version:\n # we don't want to prevent --help/--version to work\n # so just let is pass and print a warning at the end\n from _pytest.warnings import _issue_warning_captured\n\n _issue_warning_captured(\n PytestConfigWarning(\n \"could not load initial conftests: {}\".format(e.path)\n ),\n self.hook,\n stacklevel=2,\n )\n else:\n raise"},{"col":4,"comment":"\n Disable output capturing. Otherwise, stdout is lost to doctest (#985)\n ","endLoc":221,"header":"def _disable_output_capturing_for_darwin(self)","id":2986,"name":"_disable_output_capturing_for_darwin","nodeType":"Function","startLoc":210,"text":"def _disable_output_capturing_for_darwin(self):\n \"\"\"\n Disable output capturing. Otherwise, stdout is lost to doctest (#985)\n \"\"\"\n if platform.system() != \"Darwin\":\n return\n capman = self.config.pluginmanager.getplugin(\"capturemanager\")\n if capman:\n capman.suspend_global_capture(in_=True)\n out, err = capman.read_global_capture()\n sys.stdout.write(out)\n sys.stderr.write(err)"},{"col":4,"comment":"null","endLoc":65,"header":"def log_outcome(self, report, lettercode, longrepr)","id":2987,"name":"log_outcome","nodeType":"Function","startLoc":61,"text":"def log_outcome(self, report, lettercode, longrepr):\n testpath = getattr(report, \"nodeid\", None)\n if testpath is None:\n testpath = report.fspath\n self.write_log_entry(testpath, lettercode, longrepr)"},{"col":4,"comment":"Creates a new log handler.","endLoc":237,"header":"def __init__(self)","id":2988,"name":"__init__","nodeType":"Function","startLoc":234,"text":"def __init__(self):\n \"\"\"Creates a new log handler.\"\"\"\n logging.StreamHandler.__init__(self, py.io.TextIO())\n self.records = []"},{"col":0,"comment":"null","endLoc":194,"header":"def test_conftest_confcutdir(testdir)","id":2989,"name":"test_conftest_confcutdir","nodeType":"Function","startLoc":181,"text":"def test_conftest_confcutdir(testdir):\n testdir.makeconftest(\"assert 0\")\n x = testdir.mkdir(\"x\")\n x.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def pytest_addoption(parser):\n parser.addoption(\"--xyz\", action=\"store_true\")\n \"\"\"\n )\n )\n result = testdir.runpytest(\"-h\", \"--confcutdir=%s\" % x, x)\n result.stdout.fnmatch_lines([\"*--xyz*\"])\n assert \"warning: could not load initial\" not in result.stdout.str()"},{"col":4,"comment":"null","endLoc":84,"header":"def pytest_runtest_logreport(self, report)","id":2990,"name":"pytest_runtest_logreport","nodeType":"Function","startLoc":67,"text":"def pytest_runtest_logreport(self, report):\n if report.when != \"call\" and report.passed:\n return\n res = self.config.hook.pytest_report_teststatus(\n report=report, config=self.config\n )\n code = res[1]\n if code == \"x\":\n longrepr = str(report.longrepr)\n elif code == \"X\":\n longrepr = \"\"\n elif report.passed:\n longrepr = \"\"\n elif report.failed:\n longrepr = str(report.longrepr)\n elif report.skipped:\n longrepr = str(report.longrepr[2])\n self.log_outcome(report, code, longrepr)"},{"col":0,"comment":"Ensure that conftest.py is used for resolved symlinks.","endLoc":246,"header":"@pytest.mark.skipif(\n not hasattr(py.path.local, \"mksymlinkto\"),\n reason=\"symlink not available on this platform\",\n)\ndef test_conftest_symlink(testdir)","id":2991,"name":"test_conftest_symlink","nodeType":"Function","startLoc":197,"text":"@pytest.mark.skipif(\n not hasattr(py.path.local, \"mksymlinkto\"),\n reason=\"symlink not available on this platform\",\n)\ndef test_conftest_symlink(testdir):\n \"\"\"Ensure that conftest.py is used for resolved symlinks.\"\"\"\n real = testdir.tmpdir.mkdir(\"real\")\n realtests = real.mkdir(\"app\").mkdir(\"tests\")\n testdir.tmpdir.join(\"symlinktests\").mksymlinkto(realtests)\n testdir.tmpdir.join(\"symlink\").mksymlinkto(real)\n testdir.makepyfile(\n **{\n \"real/app/tests/test_foo.py\": \"def test1(fixture): pass\",\n \"real/conftest.py\": textwrap.dedent(\n \"\"\"\n import pytest\n\n print(\"conftest_loaded\")\n\n @pytest.fixture\n def fixture():\n print(\"fixture_used\")\n \"\"\"\n ),\n }\n )\n result = testdir.runpytest(\"-vs\", \"symlinktests\")\n result.stdout.fnmatch_lines(\n [\n \"*conftest_loaded*\",\n \"real/app/tests/test_foo.py::test1 fixture_used\",\n \"PASSED\",\n ]\n )\n assert result.ret == EXIT_OK\n\n # Should not cause \"ValueError: Plugin already registered\" (#4174).\n result = testdir.runpytest(\"-vs\", \"symlink\")\n assert result.ret == EXIT_OK\n\n realtests.ensure(\"__init__.py\")\n result = testdir.runpytest(\"-vs\", \"symlinktests/test_foo.py::test1\")\n result.stdout.fnmatch_lines(\n [\n \"*conftest_loaded*\",\n \"real/app/tests/test_foo.py::test1 fixture_used\",\n \"PASSED\",\n ]\n )\n assert result.ret == EXIT_OK"},{"col":4,"comment":"Validate known args.","endLoc":819,"header":"def _validate_args(self, args, via)","id":2993,"name":"_validate_args","nodeType":"Function","startLoc":809,"text":"def _validate_args(self, args, via):\n \"\"\"Validate known args.\"\"\"\n self._parser._config_source_hint = via\n try:\n self._parser.parse_known_and_unknown_args(\n args, namespace=copy.copy(self.option)\n )\n finally:\n del self._parser._config_source_hint\n\n return args"},{"col":4,"comment":"parses and returns a namespace object with known arguments, and\n the remaining arguments unknown at this point.\n ","endLoc":118,"header":"def parse_known_and_unknown_args(self, args, namespace=None)","id":2996,"name":"parse_known_and_unknown_args","nodeType":"Function","startLoc":112,"text":"def parse_known_and_unknown_args(self, args, namespace=None):\n \"\"\"parses and returns a namespace object with known arguments, and\n the remaining arguments unknown at this point.\n \"\"\"\n optparser = self._getparser()\n args = [str(x) if isinstance(x, py.path.local) else x for x in args]\n return optparser.parse_known_args(args, namespace=namespace)"},{"col":4,"comment":"null","endLoc":132,"header":"def __init__(self, failures)","id":2997,"name":"__init__","nodeType":"Function","startLoc":130,"text":"def __init__(self, failures):\n super(MultipleDoctestFailures, self).__init__()\n self.failures = failures"},{"col":4,"comment":"null","endLoc":276,"header":"def repr_failure(self, excinfo)","id":2998,"name":"repr_failure","nodeType":"Function","startLoc":223,"text":"def repr_failure(self, excinfo):\n import doctest\n\n failures = None\n if excinfo.errisinstance((doctest.DocTestFailure, doctest.UnexpectedException)):\n failures = [excinfo.value]\n elif excinfo.errisinstance(MultipleDoctestFailures):\n failures = excinfo.value.failures\n\n if failures is not None:\n reprlocation_lines = []\n for failure in failures:\n example = failure.example\n test = failure.test\n filename = test.filename\n if test.lineno is None:\n lineno = None\n else:\n lineno = test.lineno + example.lineno + 1\n message = type(failure).__name__\n reprlocation = ReprFileLocation(filename, lineno, message)\n checker = _get_checker()\n report_choice = _get_report_choice(\n self.config.getoption(\"doctestreport\")\n )\n if lineno is not None:\n lines = failure.test.docstring.splitlines(False)\n # add line numbers to the left of the error message\n lines = [\n \"%03d %s\" % (i + test.lineno + 1, x)\n for (i, x) in enumerate(lines)\n ]\n # trim docstring error lines to 10\n lines = lines[max(example.lineno - 9, 0) : example.lineno + 1]\n else:\n lines = [\n \"EXAMPLE LOCATION UNKNOWN, not showing all tests of that example\"\n ]\n indent = \">>>\"\n for line in example.source.splitlines():\n lines.append(\"??? %s %s\" % (indent, line))\n indent = \"...\"\n if isinstance(failure, doctest.DocTestFailure):\n lines += checker.output_difference(\n example, failure.got, report_choice\n ).split(\"\\n\")\n else:\n inner_excinfo = ExceptionInfo(failure.exc_info)\n lines += [\"UNEXPECTED EXCEPTION: %s\" % repr(inner_excinfo.value)]\n lines += traceback.format_exception(*failure.exc_info)\n reprlocation_lines.append((reprlocation, lines))\n return ReprFailDoctest(reprlocation_lines)\n else:\n return super(DoctestItem, self).repr_failure(excinfo)"},{"col":0,"comment":"Check conftest.py loading when running in directory with symlinks.","endLoc":282,"header":"@pytest.mark.skipif(\n not hasattr(py.path.local, \"mksymlinkto\"),\n reason=\"symlink not available on this platform\",\n)\ndef test_conftest_symlink_files(testdir)","id":2999,"name":"test_conftest_symlink_files","nodeType":"Function","startLoc":249,"text":"@pytest.mark.skipif(\n not hasattr(py.path.local, \"mksymlinkto\"),\n reason=\"symlink not available on this platform\",\n)\ndef test_conftest_symlink_files(testdir):\n \"\"\"Check conftest.py loading when running in directory with symlinks.\"\"\"\n real = testdir.tmpdir.mkdir(\"real\")\n source = {\n \"app/test_foo.py\": \"def test1(fixture): pass\",\n \"app/__init__.py\": \"\",\n \"app/conftest.py\": textwrap.dedent(\n \"\"\"\n import pytest\n\n print(\"conftest_loaded\")\n\n @pytest.fixture\n def fixture():\n print(\"fixture_used\")\n \"\"\"\n ),\n }\n testdir.makepyfile(**{\"real/%s\" % k: v for k, v in source.items()})\n\n # Create a build directory that contains symlinks to actual files\n # but doesn't symlink actual directories.\n build = testdir.tmpdir.mkdir(\"build\")\n build.mkdir(\"app\")\n for f in source:\n build.join(f).mksymlinkto(real.join(f))\n build.chdir()\n result = testdir.runpytest(\"-vs\", \"app/test_foo.py\")\n result.stdout.fnmatch_lines([\"*conftest_loaded*\", \"PASSED\"])\n assert result.ret == EXIT_OK"},{"col":0,"comment":"","endLoc":2,"header":"fixtures.py#","id":3000,"name":"","nodeType":"Function","startLoc":2,"text":"scopename2class = {}\n\nscope2props = dict(session=())\n\nscope2props[\"package\"] = (\"fspath\",)\n\nscope2props[\"module\"] = (\"fspath\", \"module\")\n\nscope2props[\"class\"] = scope2props[\"module\"] + (\"cls\",)\n\nscope2props[\"instance\"] = scope2props[\"class\"] + (\"instance\",)\n\nscope2props[\"function\"] = scope2props[\"instance\"] + (\"function\", \"keywords\")\n\nscopes = \"session package module class function\".split()\n\nscopenum_function = scopes.index(\"function\")\n\ndefaultfuncargprefixmarker = fixture()"},{"col":4,"comment":"null","endLoc":98,"header":"def _getparser(self)","id":3001,"name":"_getparser","nodeType":"Function","startLoc":83,"text":"def _getparser(self):\n from _pytest._argcomplete import filescompleter\n\n optparser = MyOptionParser(self, self.extra_info, prog=self.prog)\n groups = self._groups + [self._anonymous]\n for group in groups:\n if group.options:\n desc = group.description or group.name\n arggroup = optparser.add_argument_group(desc)\n for option in group.options:\n n = option.names()\n a = option.attrs()\n arggroup.add_argument(*n, **a)\n # bash like autocompletion for dirs (appending '/')\n optparser.add_argument(FILE_OR_DIR, nargs=\"*\").completer = filescompleter\n return optparser"},{"id":3002,"name":"release-2.6.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.6.2: few fixes and cx_freeze support\n===========================================================================\n\npytest is a mature Python testing tool with more than a 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is drop-in compatible to 2.5.2 and 2.6.X. It also\nbrings support for including pytest with cx_freeze or similar\nfreezing tools into your single-file app distribution. For details\nsee the CHANGELOG below.\n\nSee docs at:\n\n http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n pip install -U pytest\n\nThanks to all who contributed, among them:\n\n Floris Bruynooghe\n Benjamin Peterson\n Bruno Oliveira\n\nhave fun,\nholger krekel\n\n2.6.2\n-----------\n\n- Added function pytest.freeze_includes(), which makes it easy to embed\n pytest into executables using tools like cx_freeze.\n See docs for examples and rationale. Thanks Bruno Oliveira.\n\n- Improve assertion rewriting cache invalidation precision.\n\n- fixed issue561: adapt autouse fixture example for python3.\n\n- fixed issue453: assertion rewriting issue with __repr__ containing\n \"\\n{\", \"\\n}\" and \"\\n~\".\n\n- fix issue560: correctly display code if an \"else:\" or \"finally:\" is\n followed by statements on the same line.\n\n- Fix example in monkeypatch documentation, thanks t-8ch.\n\n- fix issue572: correct tmpdir doc example for python3.\n\n- Do not mark as universal wheel because Python 2.6 is different from\n other builds due to the extra argparse dependency. Fixes issue566.\n Thanks sontek.\n"},{"id":3003,"name":"release-3.0.4.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.0.4\n============\n\npytest 3.0.4 has just been released to PyPI.\n\nThis release fixes some regressions and bugs reported in the last version,\nbeing a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n* Dan Wandschneider\n* Florian Bruhin\n* Georgy Dyuldin\n* Grigorii Eremeev\n* Jason R. Coombs\n* Manuel Jacob\n* Mathieu Clabaut\n* Michael Seifert\n* Nikolaus Rath\n* Ronny Pfannschmidt\n* Tom V\n\nHappy testing,\nThe pytest Development Team\n"},{"fileName":"freeze_support.py","filePath":"src/_pytest","id":3004,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"\nProvides a function to report all internal modules for using freezing tools\npytest\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n\ndef freeze_includes():\n \"\"\"\n Returns a list of module names used by pytest that should be\n included by cx_freeze.\n \"\"\"\n import py\n import _pytest\n\n result = list(_iter_all_modules(py))\n result += list(_iter_all_modules(_pytest))\n return result\n\n\ndef _iter_all_modules(package, prefix=\"\"):\n \"\"\"\n Iterates over the names of all modules that can be found in the given\n package, recursively.\n Example:\n _iter_all_modules(_pytest) ->\n ['_pytest.assertion.newinterpret',\n '_pytest.capture',\n '_pytest.core',\n ...\n ]\n \"\"\"\n import os\n import pkgutil\n\n if type(package) is not str:\n path, prefix = package.__path__[0], package.__name__ + \".\"\n else:\n path = package\n for _, name, is_package in pkgutil.iter_modules([path]):\n if is_package:\n for m in _iter_all_modules(os.path.join(path, name), prefix=name + \".\"):\n yield prefix + m\n else:\n yield prefix + name\n"},{"col":4,"comment":"null","endLoc":98,"header":"def pytest_runtest_logreport(self, report)","id":3005,"name":"pytest_runtest_logreport","nodeType":"Function","startLoc":74,"text":"def pytest_runtest_logreport(self, report):\n if not self.active:\n return\n\n if report.failed:\n if self.skip:\n # Remove test from the failed ones (if it exists) and unset the skip option\n # to make sure the following tests will not be skipped.\n if report.nodeid == self.lastfailed:\n self.lastfailed = None\n\n self.skip = False\n else:\n # Mark test as the last failing and interrupt the test session.\n self.lastfailed = report.nodeid\n self.session.shouldstop = (\n \"Test failed, continuing from this test next run.\"\n )\n\n else:\n # If the test was actually run and did pass.\n if report.when == \"call\":\n # Remove test from the failed ones, if exists.\n if report.nodeid == self.lastfailed:\n self.lastfailed = None"},{"col":4,"comment":"null","endLoc":102,"header":"def pytest_report_collectionfinish(self)","id":3006,"name":"pytest_report_collectionfinish","nodeType":"Function","startLoc":100,"text":"def pytest_report_collectionfinish(self):\n if self.active and self.config.getoption(\"verbose\") >= 0 and self.report_status:\n return \"stepwise: %s\" % self.report_status"},{"col":0,"comment":"","endLoc":5,"header":"freeze_support.py#","id":3007,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"\nProvides a function to report all internal modules for using freezing tools\npytest\n\"\"\""},{"col":4,"comment":"null","endLoc":359,"header":"def test_preserve_modules(self, monkeypatch)","id":3008,"name":"test_preserve_modules","nodeType":"Function","startLoc":344,"text":"def test_preserve_modules(self, monkeypatch):\n key = [self.key + str(i) for i in range(3)]\n assert not any(k in sys.modules for k in key)\n for i, k in enumerate(key):\n monkeypatch.setitem(sys.modules, k, \"something\" + str(i))\n original = dict(sys.modules)\n\n def preserve(name):\n return name in (key[0], key[1], \"some-other-key\")\n\n snapshot = SysModulesSnapshot(preserve=preserve)\n sys.modules[key[0]] = original[key[0]] = \"something else0\"\n sys.modules[key[1]] = original[key[1]] = \"something else1\"\n sys.modules[key[2]] = \"something else2\"\n snapshot.restore()\n assert sys.modules == original"},{"col":4,"comment":"null","endLoc":109,"header":"def pytest_sessionfinish(self, session)","id":3009,"name":"pytest_sessionfinish","nodeType":"Function","startLoc":104,"text":"def pytest_sessionfinish(self, session):\n if self.active:\n self.config.cache.set(\"cache/stepwise\", self.lastfailed)\n else:\n # Clear the list of failing tests if the plugin is not active.\n self.config.cache.set(\"cache/stepwise\", [])"},{"attributeType":"None","col":8,"comment":"null","endLoc":31,"id":3010,"name":"session","nodeType":"Attribute","startLoc":31,"text":"self.session"},{"attributeType":"null","col":8,"comment":"null","endLoc":30,"id":3011,"name":"active","nodeType":"Attribute","startLoc":30,"text":"self.active"},{"attributeType":"str","col":8,"comment":"null","endLoc":32,"id":3012,"name":"report_status","nodeType":"Attribute","startLoc":32,"text":"self.report_status"},{"fileName":"test_assertrewrite.py","filePath":"testing","id":3013,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport glob\nimport os\nimport py_compile\nimport stat\nimport sys\nimport textwrap\nimport zipfile\n\nimport py\nimport six\n\nimport _pytest._code\nimport pytest\nfrom _pytest.assertion import util\nfrom _pytest.assertion.rewrite import AssertionRewritingHook\nfrom _pytest.assertion.rewrite import PYTEST_TAG\nfrom _pytest.assertion.rewrite import rewrite_asserts\nfrom _pytest.main import EXIT_NOTESTSCOLLECTED\n\nast = pytest.importorskip(\"ast\")\nif sys.platform.startswith(\"java\"):\n # XXX should be xfail\n pytest.skip(\"assert rewrite does currently not work on jython\")\n\n\ndef setup_module(mod):\n mod._old_reprcompare = util._reprcompare\n _pytest._code._reprcompare = None\n\n\ndef teardown_module(mod):\n util._reprcompare = mod._old_reprcompare\n del mod._old_reprcompare\n\n\ndef rewrite(src):\n tree = ast.parse(src)\n rewrite_asserts(tree)\n return tree\n\n\ndef getmsg(f, extra_ns=None, must_pass=False):\n \"\"\"Rewrite the assertions in f, run it, and get the failure message.\"\"\"\n src = \"\\n\".join(_pytest._code.Code(f).source().lines)\n mod = rewrite(src)\n code = compile(mod, \"\", \"exec\")\n ns = {}\n if extra_ns is not None:\n ns.update(extra_ns)\n exec(code, ns)\n func = ns[f.__name__]\n try:\n func()\n except AssertionError:\n if must_pass:\n pytest.fail(\"shouldn't have raised\")\n s = six.text_type(sys.exc_info()[1])\n if not s.startswith(\"assert\"):\n return \"AssertionError: \" + s\n return s\n else:\n if not must_pass:\n pytest.fail(\"function didn't raise at all\")\n\n\nclass TestAssertionRewrite(object):\n def test_place_initial_imports(self):\n s = \"\"\"'Doc string'\\nother = stuff\"\"\"\n m = rewrite(s)\n assert isinstance(m.body[0], ast.Expr)\n for imp in m.body[1:3]:\n assert isinstance(imp, ast.Import)\n assert imp.lineno == 2\n assert imp.col_offset == 0\n assert isinstance(m.body[3], ast.Assign)\n s = \"\"\"from __future__ import division\\nother_stuff\"\"\"\n m = rewrite(s)\n assert isinstance(m.body[0], ast.ImportFrom)\n for imp in m.body[1:3]:\n assert isinstance(imp, ast.Import)\n assert imp.lineno == 2\n assert imp.col_offset == 0\n assert isinstance(m.body[3], ast.Expr)\n s = \"\"\"'doc string'\\nfrom __future__ import division\"\"\"\n m = rewrite(s)\n assert isinstance(m.body[0], ast.Expr)\n assert isinstance(m.body[1], ast.ImportFrom)\n for imp in m.body[2:4]:\n assert isinstance(imp, ast.Import)\n assert imp.lineno == 2\n assert imp.col_offset == 0\n s = \"\"\"'doc string'\\nfrom __future__ import division\\nother\"\"\"\n m = rewrite(s)\n assert isinstance(m.body[0], ast.Expr)\n assert isinstance(m.body[1], ast.ImportFrom)\n for imp in m.body[2:4]:\n assert isinstance(imp, ast.Import)\n assert imp.lineno == 3\n assert imp.col_offset == 0\n assert isinstance(m.body[4], ast.Expr)\n s = \"\"\"from . import relative\\nother_stuff\"\"\"\n m = rewrite(s)\n for imp in m.body[:2]:\n assert isinstance(imp, ast.Import)\n assert imp.lineno == 1\n assert imp.col_offset == 0\n assert isinstance(m.body[3], ast.Expr)\n\n def test_dont_rewrite(self):\n s = \"\"\"'PYTEST_DONT_REWRITE'\\nassert 14\"\"\"\n m = rewrite(s)\n assert len(m.body) == 2\n assert m.body[1].msg is None\n\n def test_dont_rewrite_plugin(self, testdir):\n contents = {\n \"conftest.py\": \"pytest_plugins = 'plugin'; import plugin\",\n \"plugin.py\": \"'PYTEST_DONT_REWRITE'\",\n \"test_foo.py\": \"def test_foo(): pass\",\n }\n testdir.makepyfile(**contents)\n result = testdir.runpytest_subprocess()\n assert \"warnings\" not in \"\".join(result.outlines)\n\n def test_name(self, request):\n def f():\n assert False\n\n assert getmsg(f) == \"assert False\"\n\n def f():\n f = False\n assert f\n\n assert getmsg(f) == \"assert False\"\n\n def f():\n assert a_global # noqa\n\n assert getmsg(f, {\"a_global\": False}) == \"assert False\"\n\n def f():\n assert sys == 42\n\n verbose = request.config.getoption(\"verbose\")\n msg = getmsg(f, {\"sys\": sys})\n if verbose > 0:\n assert msg == (\n \"assert == 42\\n\"\n \" -\\n\"\n \" +42\"\n )\n else:\n assert msg == \"assert sys == 42\"\n\n def f():\n assert cls == 42 # noqa: F821\n\n class X(object):\n pass\n\n msg = getmsg(f, {\"cls\": X}).splitlines()\n if verbose > 0:\n if six.PY2:\n assert msg == [\n \"assert == 42\",\n \" -\",\n \" +42\",\n ]\n else:\n assert msg == [\n \"assert .X'> == 42\",\n \" -.X'>\",\n \" +42\",\n ]\n else:\n assert msg == [\"assert cls == 42\"]\n\n def test_dont_rewrite_if_hasattr_fails(self, request):\n class Y(object):\n \"\"\" A class whos getattr fails, but not with `AttributeError` \"\"\"\n\n def __getattr__(self, attribute_name):\n raise KeyError()\n\n def __repr__(self):\n return \"Y\"\n\n def __init__(self):\n self.foo = 3\n\n def f():\n assert cls().foo == 2 # noqa\n\n # XXX: looks like the \"where\" should also be there in verbose mode?!\n message = getmsg(f, {\"cls\": Y}).splitlines()\n if request.config.getoption(\"verbose\") > 0:\n assert message == [\"assert 3 == 2\", \" -3\", \" +2\"]\n else:\n assert message == [\n \"assert 3 == 2\",\n \" + where 3 = Y.foo\",\n \" + where Y = cls()\",\n ]\n\n def test_assert_already_has_message(self):\n def f():\n assert False, \"something bad!\"\n\n assert getmsg(f) == \"AssertionError: something bad!\\nassert False\"\n\n def test_assertion_message(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert 1 == 2, \"The failure message\"\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\"*AssertionError*The failure message*\", \"*assert 1 == 2*\"]\n )\n\n def test_assertion_message_multiline(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert 1 == 2, \"A multiline\\\\nfailure message\"\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\"*AssertionError*A multiline*\", \"*failure message*\", \"*assert 1 == 2*\"]\n )\n\n def test_assertion_message_tuple(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert 1 == 2, (1, 2)\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\"*AssertionError*%s*\" % repr((1, 2)), \"*assert 1 == 2*\"]\n )\n\n def test_assertion_message_expr(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert 1 == 2, 1 + 2\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines([\"*AssertionError*3*\", \"*assert 1 == 2*\"])\n\n def test_assertion_message_escape(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert 1 == 2, 'To be escaped: %'\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\"*AssertionError: To be escaped: %\", \"*assert 1 == 2\"]\n )\n\n @pytest.mark.skipif(\n sys.version_info < (3,), reason=\"bytes is a string type in python 2\"\n )\n def test_assertion_messages_bytes(self, testdir):\n testdir.makepyfile(\"def test_bytes_assertion():\\n assert False, b'ohai!'\\n\")\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines([\"*AssertionError: b'ohai!'\", \"*assert False\"])\n\n def test_boolop(self):\n def f():\n f = g = False\n assert f and g\n\n assert getmsg(f) == \"assert (False)\"\n\n def f():\n f = True\n g = False\n assert f and g\n\n assert getmsg(f) == \"assert (True and False)\"\n\n def f():\n f = False\n g = True\n assert f and g\n\n assert getmsg(f) == \"assert (False)\"\n\n def f():\n f = g = False\n assert f or g\n\n assert getmsg(f) == \"assert (False or False)\"\n\n def f():\n f = g = False\n assert not f and not g\n\n getmsg(f, must_pass=True)\n\n def x():\n return False\n\n def f():\n assert x() and x()\n\n assert (\n getmsg(f, {\"x\": x})\n == \"\"\"assert (False)\n + where False = x()\"\"\"\n )\n\n def f():\n assert False or x()\n\n assert (\n getmsg(f, {\"x\": x})\n == \"\"\"assert (False or False)\n + where False = x()\"\"\"\n )\n\n def f():\n assert 1 in {} and 2 in {}\n\n assert getmsg(f) == \"assert (1 in {})\"\n\n def f():\n x = 1\n y = 2\n assert x in {1: None} and y in {}\n\n assert getmsg(f) == \"assert (1 in {1: None} and 2 in {})\"\n\n def f():\n f = True\n g = False\n assert f or g\n\n getmsg(f, must_pass=True)\n\n def f():\n f = g = h = lambda: True\n assert f() and g() and h()\n\n getmsg(f, must_pass=True)\n\n def test_short_circuit_evaluation(self):\n def f():\n assert True or explode # noqa\n\n getmsg(f, must_pass=True)\n\n def f():\n x = 1\n assert x == 1 or x == 2\n\n getmsg(f, must_pass=True)\n\n def test_unary_op(self):\n def f():\n x = True\n assert not x\n\n assert getmsg(f) == \"assert not True\"\n\n def f():\n x = 0\n assert ~x + 1\n\n assert getmsg(f) == \"assert (~0 + 1)\"\n\n def f():\n x = 3\n assert -x + x\n\n assert getmsg(f) == \"assert (-3 + 3)\"\n\n def f():\n x = 0\n assert +x + x\n\n assert getmsg(f) == \"assert (+0 + 0)\"\n\n def test_binary_op(self):\n def f():\n x = 1\n y = -1\n assert x + y\n\n assert getmsg(f) == \"assert (1 + -1)\"\n\n def f():\n assert not 5 % 4\n\n assert getmsg(f) == \"assert not (5 % 4)\"\n\n def test_boolop_percent(self):\n def f():\n assert 3 % 2 and False\n\n assert getmsg(f) == \"assert ((3 % 2) and False)\"\n\n def f():\n assert False or 4 % 2\n\n assert getmsg(f) == \"assert (False or (4 % 2))\"\n\n @pytest.mark.skipif(\"sys.version_info < (3,5)\")\n def test_at_operator_issue1290(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class Matrix(object):\n def __init__(self, num):\n self.num = num\n def __matmul__(self, other):\n return self.num * other.num\n\n def test_multmat_operator():\n assert Matrix(2) @ Matrix(3) == 6\"\"\"\n )\n testdir.runpytest().assert_outcomes(passed=1)\n\n @pytest.mark.skipif(\"sys.version_info < (3,5)\")\n def test_starred_with_side_effect(self, testdir):\n \"\"\"See #4412\"\"\"\n testdir.makepyfile(\n \"\"\"\\\n def test():\n f = lambda x: x\n x = iter([1, 2, 3])\n assert 2 * next(x) == f(*[next(x)])\n \"\"\"\n )\n testdir.runpytest().assert_outcomes(passed=1)\n\n def test_call(self):\n def g(a=42, *args, **kwargs):\n return False\n\n ns = {\"g\": g}\n\n def f():\n assert g()\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g()\"\"\"\n )\n\n def f():\n assert g(1)\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g(1)\"\"\"\n )\n\n def f():\n assert g(1, 2)\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g(1, 2)\"\"\"\n )\n\n def f():\n assert g(1, g=42)\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g(1, g=42)\"\"\"\n )\n\n def f():\n assert g(1, 3, g=23)\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g(1, 3, g=23)\"\"\"\n )\n\n def f():\n seq = [1, 2, 3]\n assert g(*seq)\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g(*[1, 2, 3])\"\"\"\n )\n\n def f():\n x = \"a\"\n assert g(**{x: 2})\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g(**{'a': 2})\"\"\"\n )\n\n def test_attribute(self):\n class X(object):\n g = 3\n\n ns = {\"x\": X}\n\n def f():\n assert not x.g # noqa\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert not 3\n + where 3 = x.g\"\"\"\n )\n\n def f():\n x.a = False # noqa\n assert x.a # noqa\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = x.a\"\"\"\n )\n\n def test_comparisons(self):\n def f():\n a, b = range(2)\n assert b < a\n\n assert getmsg(f) == \"\"\"assert 1 < 0\"\"\"\n\n def f():\n a, b, c = range(3)\n assert a > b > c\n\n assert getmsg(f) == \"\"\"assert 0 > 1\"\"\"\n\n def f():\n a, b, c = range(3)\n assert a < b > c\n\n assert getmsg(f) == \"\"\"assert 1 > 2\"\"\"\n\n def f():\n a, b, c = range(3)\n assert a < b <= c\n\n getmsg(f, must_pass=True)\n\n def f():\n a, b, c = range(3)\n assert a < b\n assert b < c\n\n getmsg(f, must_pass=True)\n\n def test_len(self, request):\n def f():\n values = list(range(10))\n assert len(values) == 11\n\n msg = getmsg(f)\n if request.config.getoption(\"verbose\") > 0:\n assert msg == \"assert 10 == 11\\n -10\\n +11\"\n else:\n assert msg == \"assert 10 == 11\\n + where 10 = len([0, 1, 2, 3, 4, 5, ...])\"\n\n def test_custom_reprcompare(self, monkeypatch):\n def my_reprcompare(op, left, right):\n return \"42\"\n\n monkeypatch.setattr(util, \"_reprcompare\", my_reprcompare)\n\n def f():\n assert 42 < 3\n\n assert getmsg(f) == \"assert 42\"\n\n def my_reprcompare(op, left, right):\n return \"{} {} {}\".format(left, op, right)\n\n monkeypatch.setattr(util, \"_reprcompare\", my_reprcompare)\n\n def f():\n assert 1 < 3 < 5 <= 4 < 7\n\n assert getmsg(f) == \"assert 5 <= 4\"\n\n def test_assert_raising_nonzero_in_comparison(self):\n def f():\n class A(object):\n def __nonzero__(self):\n raise ValueError(42)\n\n def __lt__(self, other):\n return A()\n\n def __repr__(self):\n return \"\"\n\n def myany(x):\n return False\n\n assert myany(A() < 0)\n\n assert \" < 0\" in getmsg(f)\n\n def test_formatchar(self):\n def f():\n assert \"%test\" == \"test\"\n\n assert getmsg(f).startswith(\"assert '%test' == 'test'\")\n\n def test_custom_repr(self, request):\n def f():\n class Foo(object):\n a = 1\n\n def __repr__(self):\n return \"\\n{ \\n~ \\n}\"\n\n f = Foo()\n assert 0 == f.a\n\n lines = util._format_lines([getmsg(f)])\n if request.config.getoption(\"verbose\") > 0:\n assert lines == [\"assert 0 == 1\\n -0\\n +1\"]\n else:\n assert lines == [\"assert 0 == 1\\n + where 1 = \\\\n{ \\\\n~ \\\\n}.a\"]\n\n def test_custom_repr_non_ascii(self):\n def f():\n class A(object):\n name = u\"ä\"\n\n def __repr__(self):\n return self.name.encode(\"UTF-8\") # only legal in python2\n\n a = A()\n assert not a.name\n\n msg = getmsg(f)\n assert \"UnicodeDecodeError\" not in msg\n assert \"UnicodeEncodeError\" not in msg\n\n\nclass TestRewriteOnImport(object):\n def test_pycache_is_a_file(self, testdir):\n testdir.tmpdir.join(\"__pycache__\").write(\"Hello\")\n testdir.makepyfile(\n \"\"\"\n def test_rewritten():\n assert \"@py_builtins\" in globals()\"\"\"\n )\n assert testdir.runpytest().ret == 0\n\n def test_pycache_is_readonly(self, testdir):\n cache = testdir.tmpdir.mkdir(\"__pycache__\")\n old_mode = cache.stat().mode\n cache.chmod(old_mode ^ stat.S_IWRITE)\n testdir.makepyfile(\n \"\"\"\n def test_rewritten():\n assert \"@py_builtins\" in globals()\"\"\"\n )\n try:\n assert testdir.runpytest().ret == 0\n finally:\n cache.chmod(old_mode)\n\n def test_zipfile(self, testdir):\n z = testdir.tmpdir.join(\"myzip.zip\")\n z_fn = str(z)\n f = zipfile.ZipFile(z_fn, \"w\")\n try:\n f.writestr(\"test_gum/__init__.py\", \"\")\n f.writestr(\"test_gum/test_lizard.py\", \"\")\n finally:\n f.close()\n z.chmod(256)\n testdir.makepyfile(\n \"\"\"\n import sys\n sys.path.append(%r)\n import test_gum.test_lizard\"\"\"\n % (z_fn,)\n )\n assert testdir.runpytest().ret == EXIT_NOTESTSCOLLECTED\n\n def test_readonly(self, testdir):\n sub = testdir.mkdir(\"testing\")\n sub.join(\"test_readonly.py\").write(\n b\"\"\"\ndef test_rewritten():\n assert \"@py_builtins\" in globals()\n \"\"\",\n \"wb\",\n )\n old_mode = sub.stat().mode\n sub.chmod(320)\n try:\n assert testdir.runpytest().ret == 0\n finally:\n sub.chmod(old_mode)\n\n def test_dont_write_bytecode(self, testdir, monkeypatch):\n testdir.makepyfile(\n \"\"\"\n import os\n def test_no_bytecode():\n assert \"__pycache__\" in __cached__\n assert not os.path.exists(__cached__)\n assert not os.path.exists(os.path.dirname(__cached__))\"\"\"\n )\n monkeypatch.setenv(\"PYTHONDONTWRITEBYTECODE\", \"1\")\n assert testdir.runpytest_subprocess().ret == 0\n\n def test_orphaned_pyc_file(self, testdir):\n if sys.version_info < (3, 0) and hasattr(sys, \"pypy_version_info\"):\n pytest.skip(\"pypy2 doesn't run orphaned pyc files\")\n\n testdir.makepyfile(\n \"\"\"\n import orphan\n def test_it():\n assert orphan.value == 17\n \"\"\"\n )\n testdir.makepyfile(\n orphan=\"\"\"\n value = 17\n \"\"\"\n )\n py_compile.compile(\"orphan.py\")\n os.remove(\"orphan.py\")\n\n # Python 3 puts the .pyc files in a __pycache__ directory, and will\n # not import from there without source. It will import a .pyc from\n # the source location though.\n if not os.path.exists(\"orphan.pyc\"):\n pycs = glob.glob(\"__pycache__/orphan.*.pyc\")\n assert len(pycs) == 1\n os.rename(pycs[0], \"orphan.pyc\")\n\n assert testdir.runpytest().ret == 0\n\n @pytest.mark.skipif('\"__pypy__\" in sys.modules')\n def test_pyc_vs_pyo(self, testdir, monkeypatch):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_optimized():\n \"hello\"\n assert test_optimized.__doc__ is None\"\"\"\n )\n p = py.path.local.make_numbered_dir(\n prefix=\"runpytest-\", keep=None, rootdir=testdir.tmpdir\n )\n tmp = \"--basetemp=%s\" % p\n monkeypatch.setenv(\"PYTHONOPTIMIZE\", \"2\")\n monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", raising=False)\n assert testdir.runpytest_subprocess(tmp).ret == 0\n tagged = \"test_pyc_vs_pyo.\" + PYTEST_TAG\n assert tagged + \".pyo\" in os.listdir(\"__pycache__\")\n monkeypatch.undo()\n monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", raising=False)\n assert testdir.runpytest_subprocess(tmp).ret == 1\n assert tagged + \".pyc\" in os.listdir(\"__pycache__\")\n\n def test_package(self, testdir):\n pkg = testdir.tmpdir.join(\"pkg\")\n pkg.mkdir()\n pkg.join(\"__init__.py\").ensure()\n pkg.join(\"test_blah.py\").write(\n \"\"\"\ndef test_rewritten():\n assert \"@py_builtins\" in globals()\"\"\"\n )\n assert testdir.runpytest().ret == 0\n\n def test_translate_newlines(self, testdir):\n content = \"def test_rewritten():\\r\\n assert '@py_builtins' in globals()\"\n b = content.encode(\"utf-8\")\n testdir.tmpdir.join(\"test_newlines.py\").write(b, \"wb\")\n assert testdir.runpytest().ret == 0\n\n @pytest.mark.skipif(\n sys.version_info < (3, 4),\n reason=\"packages without __init__.py not supported on python 2\",\n )\n def test_package_without__init__py(self, testdir):\n pkg = testdir.mkdir(\"a_package_without_init_py\")\n pkg.join(\"module.py\").ensure()\n testdir.makepyfile(\"import a_package_without_init_py.module\")\n assert testdir.runpytest().ret == EXIT_NOTESTSCOLLECTED\n\n def test_rewrite_warning(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n pytest.register_assert_rewrite(\"_pytest\")\n \"\"\"\n )\n # needs to be a subprocess because pytester explicitly disables this warning\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*Module already imported*: _pytest\"])\n\n def test_rewrite_module_imported_from_conftest(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import test_rewrite_module_imported\n \"\"\"\n )\n testdir.makepyfile(\n test_rewrite_module_imported=\"\"\"\n def test_rewritten():\n assert \"@py_builtins\" in globals()\n \"\"\"\n )\n assert testdir.runpytest_subprocess().ret == 0\n\n def test_remember_rewritten_modules(self, pytestconfig, testdir, monkeypatch):\n \"\"\"\n AssertionRewriteHook should remember rewritten modules so it\n doesn't give false positives (#2005).\n \"\"\"\n monkeypatch.syspath_prepend(testdir.tmpdir)\n testdir.makepyfile(test_remember_rewritten_modules=\"\")\n warnings = []\n hook = AssertionRewritingHook(pytestconfig)\n monkeypatch.setattr(\n hook, \"_warn_already_imported\", lambda code, msg: warnings.append(msg)\n )\n hook.find_module(\"test_remember_rewritten_modules\")\n hook.load_module(\"test_remember_rewritten_modules\")\n hook.mark_rewrite(\"test_remember_rewritten_modules\")\n hook.mark_rewrite(\"test_remember_rewritten_modules\")\n assert warnings == []\n\n def test_rewrite_warning_using_pytest_plugins(self, testdir):\n testdir.makepyfile(\n **{\n \"conftest.py\": \"pytest_plugins = ['core', 'gui', 'sci']\",\n \"core.py\": \"\",\n \"gui.py\": \"pytest_plugins = ['core', 'sci']\",\n \"sci.py\": \"pytest_plugins = ['core']\",\n \"test_rewrite_warning_pytest_plugins.py\": \"def test(): pass\",\n }\n )\n testdir.chdir()\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*= 1 passed in *=*\"])\n assert \"pytest-warning summary\" not in result.stdout.str()\n\n def test_rewrite_warning_using_pytest_plugins_env_var(self, testdir, monkeypatch):\n monkeypatch.setenv(\"PYTEST_PLUGINS\", \"plugin\")\n testdir.makepyfile(\n **{\n \"plugin.py\": \"\",\n \"test_rewrite_warning_using_pytest_plugins_env_var.py\": \"\"\"\n import plugin\n pytest_plugins = ['plugin']\n def test():\n pass\n \"\"\",\n }\n )\n testdir.chdir()\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*= 1 passed in *=*\"])\n assert \"pytest-warning summary\" not in result.stdout.str()\n\n @pytest.mark.skipif(sys.version_info[0] > 2, reason=\"python 2 only\")\n def test_rewrite_future_imports(self, testdir):\n \"\"\"Test that rewritten modules don't inherit the __future__ flags\n from the assertrewrite module.\n\n assertion.rewrite imports __future__.division (and others), so\n ensure rewritten modules don't inherit those flags.\n\n The test below will fail if __future__.division is enabled\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n def test():\n x = 1 / 2\n assert type(x) is int\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0\n\n\nclass TestAssertionRewriteHookDetails(object):\n def test_loader_is_package_false_for_module(self, testdir):\n testdir.makepyfile(\n test_fun=\"\"\"\n def test_loader():\n assert not __loader__.is_package(__name__)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 passed*\"])\n\n def test_loader_is_package_true_for_package(self, testdir):\n testdir.makepyfile(\n test_fun=\"\"\"\n def test_loader():\n assert not __loader__.is_package(__name__)\n\n def test_fun():\n assert __loader__.is_package('fun')\n\n def test_missing():\n assert not __loader__.is_package('pytest_not_there')\n \"\"\"\n )\n testdir.mkpydir(\"fun\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 3 passed*\"])\n\n @pytest.mark.skipif(\"sys.version_info[0] >= 3\")\n @pytest.mark.xfail(\"hasattr(sys, 'pypy_translation_info')\")\n def test_assume_ascii(self, testdir):\n content = \"u'\\xe2\\x99\\xa5\\x01\\xfe'\"\n testdir.tmpdir.join(\"test_encoding.py\").write(content, \"wb\")\n res = testdir.runpytest()\n assert res.ret != 0\n assert \"SyntaxError: Non-ASCII character\" in res.stdout.str()\n\n @pytest.mark.skipif(\"sys.version_info[0] >= 3\")\n def test_detect_coding_cookie(self, testdir):\n testdir.makepyfile(\n test_cookie=\"\"\"\n # -*- coding: utf-8 -*-\n u\"St\\xc3\\xa4d\"\n def test_rewritten():\n assert \"@py_builtins\" in globals()\"\"\"\n )\n assert testdir.runpytest().ret == 0\n\n @pytest.mark.skipif(\"sys.version_info[0] >= 3\")\n def test_detect_coding_cookie_second_line(self, testdir):\n testdir.makepyfile(\n test_cookie=\"\"\"\n # -*- coding: utf-8 -*-\n u\"St\\xc3\\xa4d\"\n def test_rewritten():\n assert \"@py_builtins\" in globals()\"\"\"\n )\n assert testdir.runpytest().ret == 0\n\n @pytest.mark.skipif(\"sys.version_info[0] >= 3\")\n def test_detect_coding_cookie_crlf(self, testdir):\n testdir.makepyfile(\n test_cookie=\"\"\"\n # -*- coding: utf-8 -*-\n u\"St\\xc3\\xa4d\"\n def test_rewritten():\n assert \"@py_builtins\" in globals()\"\"\"\n )\n assert testdir.runpytest().ret == 0\n\n def test_sys_meta_path_munged(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_meta_path():\n import sys; sys.meta_path = []\"\"\"\n )\n assert testdir.runpytest().ret == 0\n\n def test_write_pyc(self, testdir, tmpdir, monkeypatch):\n from _pytest.assertion.rewrite import _write_pyc\n from _pytest.assertion import AssertionState\n import atomicwrites\n from contextlib import contextmanager\n\n config = testdir.parseconfig([])\n state = AssertionState(config, \"rewrite\")\n source_path = tmpdir.ensure(\"source.py\")\n pycpath = tmpdir.join(\"pyc\").strpath\n assert _write_pyc(state, [1], source_path.stat(), pycpath)\n\n @contextmanager\n def atomic_write_failed(fn, mode=\"r\", overwrite=False):\n e = IOError()\n e.errno = 10\n raise e\n yield\n\n monkeypatch.setattr(atomicwrites, \"atomic_write\", atomic_write_failed)\n assert not _write_pyc(state, [1], source_path.stat(), pycpath)\n\n def test_resources_provider_for_loader(self, testdir):\n \"\"\"\n Attempts to load resources from a package should succeed normally,\n even when the AssertionRewriteHook is used to load the modules.\n\n See #366 for details.\n \"\"\"\n pytest.importorskip(\"pkg_resources\")\n\n testdir.mkpydir(\"testpkg\")\n contents = {\n \"testpkg/test_pkg\": \"\"\"\n import pkg_resources\n\n import pytest\n from _pytest.assertion.rewrite import AssertionRewritingHook\n\n def test_load_resource():\n assert isinstance(__loader__, AssertionRewritingHook)\n res = pkg_resources.resource_string(__name__, 'resource.txt')\n res = res.decode('ascii')\n assert res == 'Load me please.'\n \"\"\"\n }\n testdir.makepyfile(**contents)\n testdir.maketxtfile(**{\"testpkg/resource\": \"Load me please.\"})\n\n result = testdir.runpytest_subprocess()\n result.assert_outcomes(passed=1)\n\n def test_read_pyc(self, tmpdir):\n \"\"\"\n Ensure that the `_read_pyc` can properly deal with corrupted pyc files.\n In those circumstances it should just give up instead of generating\n an exception that is propagated to the caller.\n \"\"\"\n import py_compile\n from _pytest.assertion.rewrite import _read_pyc\n\n source = tmpdir.join(\"source.py\")\n pyc = source + \"c\"\n\n source.write(\"def test(): pass\")\n py_compile.compile(str(source), str(pyc))\n\n contents = pyc.read(mode=\"rb\")\n strip_bytes = 20 # header is around 8 bytes, strip a little more\n assert len(contents) > strip_bytes\n pyc.write(contents[:strip_bytes], mode=\"wb\")\n\n assert _read_pyc(source, str(pyc)) is None # no error\n\n def test_reload_is_same(self, testdir):\n # A file that will be picked up during collecting.\n testdir.tmpdir.join(\"file.py\").ensure()\n testdir.tmpdir.join(\"pytest.ini\").write(\n textwrap.dedent(\n \"\"\"\n [pytest]\n python_files = *.py\n \"\"\"\n )\n )\n\n testdir.makepyfile(\n test_fun=\"\"\"\n import sys\n try:\n from imp import reload\n except ImportError:\n pass\n\n def test_loader():\n import file\n assert sys.modules[\"file\"] is reload(file)\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines([\"* 1 passed*\"])\n\n def test_reload_reloads(self, testdir):\n \"\"\"Reloading a module after change picks up the change.\"\"\"\n testdir.tmpdir.join(\"file.py\").write(\n textwrap.dedent(\n \"\"\"\n def reloaded():\n return False\n\n def rewrite_self():\n with open(__file__, 'w') as self:\n self.write('def reloaded(): return True')\n \"\"\"\n )\n )\n testdir.tmpdir.join(\"pytest.ini\").write(\n textwrap.dedent(\n \"\"\"\n [pytest]\n python_files = *.py\n \"\"\"\n )\n )\n\n testdir.makepyfile(\n test_fun=\"\"\"\n import sys\n try:\n from imp import reload\n except ImportError:\n pass\n\n def test_loader():\n import file\n assert not file.reloaded()\n file.rewrite_self()\n reload(file)\n assert file.reloaded()\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines([\"* 1 passed*\"])\n\n def test_get_data_support(self, testdir):\n \"\"\"Implement optional PEP302 api (#808).\n \"\"\"\n path = testdir.mkpydir(\"foo\")\n path.join(\"test_foo.py\").write(\n textwrap.dedent(\n \"\"\"\\\n class Test(object):\n def test_foo(self):\n import pkgutil\n data = pkgutil.get_data('foo.test_foo', 'data.txt')\n assert data == b'Hey'\n \"\"\"\n )\n )\n path.join(\"data.txt\").write(\"Hey\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_issue731(testdir):\n testdir.makepyfile(\n \"\"\"\n class LongReprWithBraces(object):\n def __repr__(self):\n return 'LongReprWithBraces({' + ('a' * 80) + '}' + ('a' * 120) + ')'\n\n def some_method(self):\n return False\n\n def test_long_repr():\n obj = LongReprWithBraces()\n assert obj.some_method()\n \"\"\"\n )\n result = testdir.runpytest()\n assert \"unbalanced braces\" not in result.stdout.str()\n\n\nclass TestIssue925(object):\n def test_simple_case(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_ternary_display():\n assert (False == False) == False\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*E*assert (False == False) == False\"])\n\n def test_long_case(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_ternary_display():\n assert False == (False == True) == True\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*E*assert (False == True) == True\"])\n\n def test_many_brackets(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_ternary_display():\n assert True == ((False == True) == True)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*E*assert True == ((False == True) == True)\"])\n\n\nclass TestIssue2121:\n def test_rewrite_python_files_contain_subdirs(self, testdir):\n testdir.makepyfile(\n **{\n \"tests/file.py\": \"\"\"\n def test_simple_failure():\n assert 1 + 1 == 3\n \"\"\"\n }\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n python_files = tests/**.py\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*E*assert (1 + 1) == 3\"])\n\n\n@pytest.mark.skipif(\n sys.maxsize <= (2 ** 31 - 1), reason=\"Causes OverflowError on 32bit systems\"\n)\n@pytest.mark.parametrize(\"offset\", [-1, +1])\ndef test_source_mtime_long_long(testdir, offset):\n \"\"\"Support modification dates after 2038 in rewritten files (#4903).\n\n pytest would crash with:\n\n fp.write(struct.pack(\"\n # ['c:', 'projects', 'my_project', 'path.py']\n parts = str(path).split(os.path.sep)\n # add 'path' to basenames to be checked.\n self._basenames_to_check_rewrite.add(os.path.splitext(parts[-1])[0])\n\n # Note: conftest already by default in _basenames_to_check_rewrite.\n parts = name.split(\".\")\n if parts[-1] in self._basenames_to_check_rewrite:\n return False\n\n # For matching the name it must be as if it was a filename.\n path = PurePath(os.path.sep.join(parts) + \".py\")\n\n for pat in self.fnpats:\n # if the pattern contains subdirectories (\"tests/**.py\" for example) we can't bail out based\n # on the name alone because we need to match against the full path\n if os.path.dirname(pat):\n return False\n if fnmatch_ex(pat, path):\n return False\n\n if self._is_marked_for_rewrite(name, state):\n return False\n\n state.trace(\"early skip of rewriting module: %s\" % (name,))\n return True\n\n def _should_rewrite(self, name, fn_pypath, state):\n # always rewrite conftest files\n fn = str(fn_pypath)\n if fn_pypath.basename == \"conftest.py\":\n state.trace(\"rewriting conftest file: %r\" % (fn,))\n return True\n\n if self.session is not None:\n if self.session.isinitpath(fn):\n state.trace(\"matched test file (was specified on cmdline): %r\" % (fn,))\n return True\n\n # modules not passed explicitly on the command line are only\n # rewritten if they match the naming convention for test files\n for pat in self.fnpats:\n if fn_pypath.fnmatch(pat):\n state.trace(\"matched test file %r\" % (fn,))\n return True\n\n return self._is_marked_for_rewrite(name, state)\n\n def _is_marked_for_rewrite(self, name, state):\n try:\n return self._marked_for_rewrite_cache[name]\n except KeyError:\n for marked in self._must_rewrite:\n if name == marked or name.startswith(marked + \".\"):\n state.trace(\"matched marked file %r (from %r)\" % (name, marked))\n self._marked_for_rewrite_cache[name] = True\n return True\n\n self._marked_for_rewrite_cache[name] = False\n return False\n\n def mark_rewrite(self, *names):\n \"\"\"Mark import names as needing to be rewritten.\n\n The named module or package as well as any nested modules will\n be rewritten on import.\n \"\"\"\n already_imported = (\n set(names).intersection(sys.modules).difference(self._rewritten_names)\n )\n for name in already_imported:\n if not AssertionRewriter.is_rewrite_disabled(\n sys.modules[name].__doc__ or \"\"\n ):\n self._warn_already_imported(name)\n self._must_rewrite.update(names)\n self._marked_for_rewrite_cache.clear()\n\n def _warn_already_imported(self, name):\n from _pytest.warning_types import PytestAssertRewriteWarning\n from _pytest.warnings import _issue_warning_captured\n\n _issue_warning_captured(\n PytestAssertRewriteWarning(\n \"Module already imported so cannot be rewritten: %s\" % name\n ),\n self.config.hook,\n stacklevel=5,\n )\n\n def load_module(self, name):\n co, pyc = self.modules.pop(name)\n if name in sys.modules:\n # If there is an existing module object named 'fullname' in\n # sys.modules, the loader must use that existing module. (Otherwise,\n # the reload() builtin will not work correctly.)\n mod = sys.modules[name]\n else:\n # I wish I could just call imp.load_compiled here, but __file__ has to\n # be set properly. In Python 3.2+, this all would be handled correctly\n # by load_compiled.\n mod = sys.modules[name] = imp.new_module(name)\n try:\n mod.__file__ = co.co_filename\n # Normally, this attribute is 3.2+.\n mod.__cached__ = pyc\n mod.__loader__ = self\n # Normally, this attribute is 3.4+\n mod.__spec__ = spec_from_file_location(name, co.co_filename, loader=self)\n exec(co, mod.__dict__)\n except: # noqa\n if name in sys.modules:\n del sys.modules[name]\n raise\n return sys.modules[name]\n\n def is_package(self, name):\n try:\n fd, fn, desc = self._imp_find_module(name)\n except ImportError:\n return False\n if fd is not None:\n fd.close()\n tp = desc[2]\n return tp == imp.PKG_DIRECTORY\n\n def get_data(self, pathname):\n \"\"\"Optional PEP302 get_data API.\n \"\"\"\n with open(pathname, \"rb\") as f:\n return f.read()"},{"attributeType":"null","col":12,"comment":"null","endLoc":35,"id":3015,"name":"lastfailed","nodeType":"Attribute","startLoc":35,"text":"self.lastfailed"},{"attributeType":"null","col":12,"comment":"null","endLoc":36,"id":3016,"name":"skip","nodeType":"Attribute","startLoc":36,"text":"self.skip"},{"col":4,"comment":"null","endLoc":81,"header":"def set_session(self, session)","id":3017,"name":"set_session","nodeType":"Function","startLoc":79,"text":"def set_session(self, session):\n self.session = session\n self._session_paths_checked = False"},{"col":4,"comment":"Indirection so we can mock calls to find_module originated from the hook during testing","endLoc":85,"header":"def _imp_find_module(self, name, path=None)","id":3018,"name":"_imp_find_module","nodeType":"Function","startLoc":83,"text":"def _imp_find_module(self, name, path=None):\n \"\"\"Indirection so we can mock calls to find_module originated from the hook during testing\"\"\"\n return imp.find_module(name, path)"},{"attributeType":"{getvalue}","col":8,"comment":"null","endLoc":29,"id":3019,"name":"config","nodeType":"Attribute","startLoc":29,"text":"self.config"},{"col":0,"comment":"null","endLoc":19,"header":"def pytest_addoption(parser)","id":3020,"name":"pytest_addoption","nodeType":"Function","startLoc":5,"text":"def pytest_addoption(parser):\n group = parser.getgroup(\"general\")\n group.addoption(\n \"--sw\",\n \"--stepwise\",\n action=\"store_true\",\n dest=\"stepwise\",\n help=\"exit on test failure and continue from last failing test next time\",\n )\n group.addoption(\n \"--stepwise-skip\",\n action=\"store_true\",\n dest=\"stepwise_skip\",\n help=\"ignore the first failing test but stop on the next failing test\",\n )"},{"col":0,"comment":"null","endLoc":24,"header":"@pytest.hookimpl\ndef pytest_configure(config)","id":3021,"name":"pytest_configure","nodeType":"Function","startLoc":22,"text":"@pytest.hookimpl\ndef pytest_configure(config):\n config.pluginmanager.register(StepwisePlugin(config), \"stepwiseplugin\")"},{"col":4,"comment":"null","endLoc":182,"header":"def find_module(self, name, path=None)","id":3023,"name":"find_module","nodeType":"Function","startLoc":87,"text":"def find_module(self, name, path=None):\n if self._writing_pyc:\n return None\n state = self.config._assertstate\n if self._early_rewrite_bailout(name, state):\n return None\n state.trace(\"find_module called for: %s\" % name)\n names = name.rsplit(\".\", 1)\n lastname = names[-1]\n pth = None\n if path is not None:\n # Starting with Python 3.3, path is a _NamespacePath(), which\n # causes problems if not converted to list.\n path = list(path)\n if len(path) == 1:\n pth = path[0]\n if pth is None:\n try:\n fd, fn, desc = self._imp_find_module(lastname, path)\n except ImportError:\n return None\n if fd is not None:\n fd.close()\n tp = desc[2]\n if tp == imp.PY_COMPILED:\n if hasattr(imp, \"source_from_cache\"):\n try:\n fn = imp.source_from_cache(fn)\n except ValueError:\n # Python 3 doesn't like orphaned but still-importable\n # .pyc files.\n fn = fn[:-1]\n else:\n fn = fn[:-1]\n elif tp != imp.PY_SOURCE:\n # Don't know what this is.\n return None\n else:\n fn = os.path.join(pth, name.rpartition(\".\")[2] + \".py\")\n\n fn_pypath = py.path.local(fn)\n if not self._should_rewrite(name, fn_pypath, state):\n return None\n\n self._rewritten_names.add(name)\n\n # The requested module looks like a test file, so rewrite it. This is\n # the most magical part of the process: load the source, rewrite the\n # asserts, and load the rewritten source. We also cache the rewritten\n # module code in a special pyc. We must be aware of the possibility of\n # concurrent pytest processes rewriting and loading pycs. To avoid\n # tricky race conditions, we maintain the following invariant: The\n # cached pyc is always a complete, valid pyc. Operations on it must be\n # atomic. POSIX's atomic rename comes in handy.\n write = not sys.dont_write_bytecode\n cache_dir = os.path.join(fn_pypath.dirname, \"__pycache__\")\n if write:\n try:\n os.mkdir(cache_dir)\n except OSError:\n e = sys.exc_info()[1].errno\n if e == errno.EEXIST:\n # Either the __pycache__ directory already exists (the\n # common case) or it's blocked by a non-dir node. In the\n # latter case, we'll ignore it in _write_pyc.\n pass\n elif e in [errno.ENOENT, errno.ENOTDIR]:\n # One of the path components was not a directory, likely\n # because we're in a zip file.\n write = False\n elif e in [errno.EACCES, errno.EROFS, errno.EPERM]:\n state.trace(\"read only directory: %r\" % fn_pypath.dirname)\n write = False\n else:\n raise\n cache_name = fn_pypath.basename[:-3] + PYC_TAIL\n pyc = os.path.join(cache_dir, cache_name)\n # Notice that even if we're in a read-only directory, I'm going\n # to check for a cached pyc. This may not be optimal...\n co = _read_pyc(fn_pypath, pyc, state.trace)\n if co is None:\n state.trace(\"rewriting %r\" % (fn,))\n source_stat, co = _rewrite_test(self.config, fn_pypath)\n if co is None:\n # Probably a SyntaxError in the test.\n return None\n if write:\n self._writing_pyc = True\n try:\n _write_pyc(state, co, source_stat, pyc)\n finally:\n self._writing_pyc = False\n else:\n state.trace(\"found cached rewritten pyc for %r\" % (fn,))\n self.modules[name] = co, pyc\n return self"},{"col":4,"comment":"\n This is a fast way to get out of rewriting modules. Profiling has\n shown that the call to imp.find_module (inside of the find_module\n from this class) is a major slowdown, so, this method tries to\n filter what we're sure won't be rewritten before getting to it.\n ","endLoc":220,"header":"def _early_rewrite_bailout(self, name, state)","id":3024,"name":"_early_rewrite_bailout","nodeType":"Function","startLoc":184,"text":"def _early_rewrite_bailout(self, name, state):\n \"\"\"\n This is a fast way to get out of rewriting modules. Profiling has\n shown that the call to imp.find_module (inside of the find_module\n from this class) is a major slowdown, so, this method tries to\n filter what we're sure won't be rewritten before getting to it.\n \"\"\"\n if self.session is not None and not self._session_paths_checked:\n self._session_paths_checked = True\n for path in self.session._initialpaths:\n # Make something as c:/projects/my_project/path.py ->\n # ['c:', 'projects', 'my_project', 'path.py']\n parts = str(path).split(os.path.sep)\n # add 'path' to basenames to be checked.\n self._basenames_to_check_rewrite.add(os.path.splitext(parts[-1])[0])\n\n # Note: conftest already by default in _basenames_to_check_rewrite.\n parts = name.split(\".\")\n if parts[-1] in self._basenames_to_check_rewrite:\n return False\n\n # For matching the name it must be as if it was a filename.\n path = PurePath(os.path.sep.join(parts) + \".py\")\n\n for pat in self.fnpats:\n # if the pattern contains subdirectories (\"tests/**.py\" for example) we can't bail out based\n # on the name alone because we need to match against the full path\n if os.path.dirname(pat):\n return False\n if fnmatch_ex(pat, path):\n return False\n\n if self._is_marked_for_rewrite(name, state):\n return False\n\n state.trace(\"early skip of rewriting module: %s\" % (name,))\n return True"},{"col":4,"comment":"null","endLoc":336,"header":"def __init__(self, parser, extra_info=None, prog=None)","id":3025,"name":"__init__","nodeType":"Function","startLoc":323,"text":"def __init__(self, parser, extra_info=None, prog=None):\n if not extra_info:\n extra_info = {}\n self._parser = parser\n argparse.ArgumentParser.__init__(\n self,\n prog=prog,\n usage=parser._usage,\n add_help=False,\n formatter_class=DropShorterLongHelpFormatter,\n )\n # extra_info is a dict of (param -> value) to display if there's\n # an usage error to provide more contextual information to the user\n self.extra_info = extra_info"},{"col":4,"comment":"null","endLoc":95,"header":"def pytest_collectreport(self, report)","id":3026,"name":"pytest_collectreport","nodeType":"Function","startLoc":86,"text":"def pytest_collectreport(self, report):\n if not report.passed:\n if report.failed:\n code = \"F\"\n longrepr = str(report.longrepr)\n else:\n assert report.skipped\n code = \"S\"\n longrepr = \"%s:%d: %s\" % report.longrepr\n self.log_outcome(report, code, longrepr)"},{"id":3027,"name":"globaltoc.html","nodeType":"TextFile","path":"doc/en/_templates","text":"

{{ _('Table Of Contents') }}

\n\n\n\n{%- if display_toc %}\n
\n {{ toc }}\n{%- endif %}\n"},{"col":0,"comment":"null","endLoc":291,"header":"def test_no_conftest(testdir)","id":3028,"name":"test_no_conftest","nodeType":"Function","startLoc":285,"text":"def test_no_conftest(testdir):\n testdir.makeconftest(\"assert 0\")\n result = testdir.runpytest(\"--noconftest\")\n assert result.ret == EXIT_NOTESTSCOLLECTED\n\n result = testdir.runpytest()\n assert result.ret == EXIT_USAGEERROR"},{"id":3029,"name":"src/_pytest/mark","nodeType":"Package"},{"fileName":"structures.py","filePath":"src/_pytest/mark","id":3030,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport inspect\nimport warnings\nfrom collections import namedtuple\nfrom operator import attrgetter\n\nimport attr\nimport six\n\nfrom ..compat import ascii_escaped\nfrom ..compat import getfslineno\nfrom ..compat import MappingMixin\nfrom ..compat import NOTSET\nfrom _pytest.deprecated import PYTEST_PARAM_UNKNOWN_KWARGS\nfrom _pytest.outcomes import fail\nfrom _pytest.warning_types import PytestUnknownMarkWarning\n\nEMPTY_PARAMETERSET_OPTION = \"empty_parameter_set_mark\"\n\n\ndef alias(name, warning=None):\n getter = attrgetter(name)\n\n def warned(self):\n warnings.warn(warning, stacklevel=2)\n return getter(self)\n\n return property(getter if warning is None else warned, doc=\"alias for \" + name)\n\n\ndef istestfunc(func):\n return (\n hasattr(func, \"__call__\")\n and getattr(func, \"__name__\", \"\") != \"\"\n )\n\n\ndef get_empty_parameterset_mark(config, argnames, func):\n from ..nodes import Collector\n\n requested_mark = config.getini(EMPTY_PARAMETERSET_OPTION)\n if requested_mark in (\"\", None, \"skip\"):\n mark = MARK_GEN.skip\n elif requested_mark == \"xfail\":\n mark = MARK_GEN.xfail(run=False)\n elif requested_mark == \"fail_at_collect\":\n f_name = func.__name__\n _, lineno = getfslineno(func)\n raise Collector.CollectError(\n \"Empty parameter set in '%s' at line %d\" % (f_name, lineno + 1)\n )\n else:\n raise LookupError(requested_mark)\n fs, lineno = getfslineno(func)\n reason = \"got empty parameter set %r, function %s at %s:%d\" % (\n argnames,\n func.__name__,\n fs,\n lineno,\n )\n return mark(reason=reason)\n\n\nclass ParameterSet(namedtuple(\"ParameterSet\", \"values, marks, id\")):\n @classmethod\n def param(cls, *values, **kwargs):\n marks = kwargs.pop(\"marks\", ())\n if isinstance(marks, MarkDecorator):\n marks = (marks,)\n else:\n assert isinstance(marks, (tuple, list, set))\n\n id_ = kwargs.pop(\"id\", None)\n if id_ is not None:\n if not isinstance(id_, six.string_types):\n raise TypeError(\n \"Expected id to be a string, got {}: {!r}\".format(type(id_), id_)\n )\n id_ = ascii_escaped(id_)\n\n if kwargs:\n warnings.warn(\n PYTEST_PARAM_UNKNOWN_KWARGS.format(args=sorted(kwargs)), stacklevel=3\n )\n return cls(values, marks, id_)\n\n @classmethod\n def extract_from(cls, parameterset, force_tuple=False):\n \"\"\"\n :param parameterset:\n a legacy style parameterset that may or may not be a tuple,\n and may or may not be wrapped into a mess of mark objects\n\n :param force_tuple:\n enforce tuple wrapping so single argument tuple values\n don't get decomposed and break tests\n \"\"\"\n\n if isinstance(parameterset, cls):\n return parameterset\n if force_tuple:\n return cls.param(parameterset)\n else:\n return cls(parameterset, marks=[], id=None)\n\n @staticmethod\n def _parse_parametrize_args(argnames, argvalues, *args, **kwargs):\n if not isinstance(argnames, (tuple, list)):\n argnames = [x.strip() for x in argnames.split(\",\") if x.strip()]\n force_tuple = len(argnames) == 1\n else:\n force_tuple = False\n return argnames, force_tuple\n\n @staticmethod\n def _parse_parametrize_parameters(argvalues, force_tuple):\n return [\n ParameterSet.extract_from(x, force_tuple=force_tuple) for x in argvalues\n ]\n\n @classmethod\n def _for_parametrize(cls, argnames, argvalues, func, config, function_definition):\n argnames, force_tuple = cls._parse_parametrize_args(argnames, argvalues)\n parameters = cls._parse_parametrize_parameters(argvalues, force_tuple)\n del argvalues\n\n if parameters:\n # check all parameter sets have the correct number of values\n for param in parameters:\n if len(param.values) != len(argnames):\n msg = (\n '{nodeid}: in \"parametrize\" the number of names ({names_len}):\\n'\n \" {names}\\n\"\n \"must be equal to the number of values ({values_len}):\\n\"\n \" {values}\"\n )\n fail(\n msg.format(\n nodeid=function_definition.nodeid,\n values=param.values,\n names=argnames,\n names_len=len(argnames),\n values_len=len(param.values),\n ),\n pytrace=False,\n )\n else:\n # empty parameter set (likely computed at runtime): create a single\n # parameter set with NOTSET values, with the \"empty parameter set\" mark applied to it\n mark = get_empty_parameterset_mark(config, argnames, func)\n parameters.append(\n ParameterSet(values=(NOTSET,) * len(argnames), marks=[mark], id=None)\n )\n return argnames, parameters\n\n\n@attr.s(frozen=True)\nclass Mark(object):\n #: name of the mark\n name = attr.ib(type=str)\n #: positional arguments of the mark decorator\n args = attr.ib() # List[object]\n #: keyword arguments of the mark decorator\n kwargs = attr.ib() # Dict[str, object]\n\n def combined_with(self, other):\n \"\"\"\n :param other: the mark to combine with\n :type other: Mark\n :rtype: Mark\n\n combines by appending args and merging the mappings\n \"\"\"\n assert self.name == other.name\n return Mark(\n self.name, self.args + other.args, dict(self.kwargs, **other.kwargs)\n )\n\n\n@attr.s\nclass MarkDecorator(object):\n \"\"\" A decorator for test functions and test classes. When applied\n it will create :class:`MarkInfo` objects which may be\n :ref:`retrieved by hooks as item keywords `.\n MarkDecorator instances are often created like this::\n\n mark1 = pytest.mark.NAME # simple MarkDecorator\n mark2 = pytest.mark.NAME(name1=value) # parametrized MarkDecorator\n\n and can then be applied as decorators to test functions::\n\n @mark2\n def test_function():\n pass\n\n When a MarkDecorator instance is called it does the following:\n 1. If called with a single class as its only positional argument and no\n additional keyword arguments, it attaches itself to the class so it\n gets applied automatically to all test cases found in that class.\n 2. If called with a single function as its only positional argument and\n no additional keyword arguments, it attaches a MarkInfo object to the\n function, containing all the arguments already stored internally in\n the MarkDecorator.\n 3. When called in any other case, it performs a 'fake construction' call,\n i.e. it returns a new MarkDecorator instance with the original\n MarkDecorator's content updated with the arguments passed to this\n call.\n\n Note: The rules above prevent MarkDecorator objects from storing only a\n single function or class reference as their positional argument with no\n additional keyword or positional arguments.\n\n \"\"\"\n\n mark = attr.ib(validator=attr.validators.instance_of(Mark))\n\n name = alias(\"mark.name\")\n args = alias(\"mark.args\")\n kwargs = alias(\"mark.kwargs\")\n\n @property\n def markname(self):\n return self.name # for backward-compat (2.4.1 had this attr)\n\n def __eq__(self, other):\n return self.mark == other.mark if isinstance(other, MarkDecorator) else False\n\n def __repr__(self):\n return \"\" % (self.mark,)\n\n def with_args(self, *args, **kwargs):\n \"\"\" return a MarkDecorator with extra arguments added\n\n unlike call this can be used even if the sole argument is a callable/class\n\n :return: MarkDecorator\n \"\"\"\n\n mark = Mark(self.name, args, kwargs)\n return self.__class__(self.mark.combined_with(mark))\n\n def __call__(self, *args, **kwargs):\n \"\"\" if passed a single callable argument: decorate it with mark info.\n otherwise add *args/**kwargs in-place to mark information. \"\"\"\n if args and not kwargs:\n func = args[0]\n is_class = inspect.isclass(func)\n if len(args) == 1 and (istestfunc(func) or is_class):\n store_mark(func, self.mark)\n return func\n return self.with_args(*args, **kwargs)\n\n\ndef get_unpacked_marks(obj):\n \"\"\"\n obtain the unpacked marks that are stored on an object\n \"\"\"\n mark_list = getattr(obj, \"pytestmark\", [])\n if not isinstance(mark_list, list):\n mark_list = [mark_list]\n return normalize_mark_list(mark_list)\n\n\ndef normalize_mark_list(mark_list):\n \"\"\"\n normalizes marker decorating helpers to mark objects\n\n :type mark_list: List[Union[Mark, Markdecorator]]\n :rtype: List[Mark]\n \"\"\"\n extracted = [\n getattr(mark, \"mark\", mark) for mark in mark_list\n ] # unpack MarkDecorator\n for mark in extracted:\n if not isinstance(mark, Mark):\n raise TypeError(\"got {!r} instead of Mark\".format(mark))\n return [x for x in extracted if isinstance(x, Mark)]\n\n\ndef store_mark(obj, mark):\n \"\"\"store a Mark on an object\n this is used to implement the Mark declarations/decorators correctly\n \"\"\"\n assert isinstance(mark, Mark), mark\n # always reassign name to avoid updating pytestmark\n # in a reference that was only borrowed\n obj.pytestmark = get_unpacked_marks(obj) + [mark]\n\n\nclass MarkGenerator(object):\n \"\"\" Factory for :class:`MarkDecorator` objects - exposed as\n a ``pytest.mark`` singleton instance. Example::\n\n import pytest\n @pytest.mark.slowtest\n def test_function():\n pass\n\n will set a 'slowtest' :class:`MarkInfo` object\n on the ``test_function`` object. \"\"\"\n\n _config = None\n _markers = set()\n\n def __getattr__(self, name):\n if name[0] == \"_\":\n raise AttributeError(\"Marker name must NOT start with underscore\")\n\n if self._config is not None:\n # We store a set of markers as a performance optimisation - if a mark\n # name is in the set we definitely know it, but a mark may be known and\n # not in the set. We therefore start by updating the set!\n if name not in self._markers:\n for line in self._config.getini(\"markers\"):\n # example lines: \"skipif(condition): skip the given test if...\"\n # or \"hypothesis: tests which use Hypothesis\", so to get the\n # marker name we split on both `:` and `(`.\n marker = line.split(\":\")[0].split(\"(\")[0].strip()\n self._markers.add(marker)\n\n # If the name is not in the set of known marks after updating,\n # then it really is time to issue a warning or an error.\n if name not in self._markers:\n if self._config.option.strict_markers:\n fail(\n \"{!r} not found in `markers` configuration option\".format(name),\n pytrace=False,\n )\n else:\n warnings.warn(\n \"Unknown pytest.mark.%s - is this a typo? You can register \"\n \"custom marks to avoid this warning - for details, see \"\n \"https://docs.pytest.org/en/latest/mark.html\" % name,\n PytestUnknownMarkWarning,\n )\n\n return MarkDecorator(Mark(name, (), {}))\n\n\nMARK_GEN = MarkGenerator()\n\n\nclass NodeKeywords(MappingMixin):\n def __init__(self, node):\n self.node = node\n self.parent = node.parent\n self._markers = {node.name: True}\n\n def __getitem__(self, key):\n try:\n return self._markers[key]\n except KeyError:\n if self.parent is None:\n raise\n return self.parent.keywords[key]\n\n def __setitem__(self, key, value):\n self._markers[key] = value\n\n def __delitem__(self, key):\n raise ValueError(\"cannot delete key in keywords dict\")\n\n def __iter__(self):\n seen = self._seen()\n return iter(seen)\n\n def _seen(self):\n seen = set(self._markers)\n if self.parent is not None:\n seen.update(self.parent.keywords)\n return seen\n\n def __len__(self):\n return len(self._seen())\n\n def __repr__(self):\n return \"\" % (self.node,)\n\n\n@attr.s(cmp=False, hash=False)\nclass NodeMarkers(object):\n \"\"\"\n internal structure for storing marks belonging to a node\n\n ..warning::\n\n unstable api\n\n \"\"\"\n\n own_markers = attr.ib(default=attr.Factory(list))\n\n def update(self, add_markers):\n \"\"\"update the own markers\n \"\"\"\n self.own_markers.extend(add_markers)\n\n def find(self, name):\n \"\"\"\n find markers in own nodes or parent nodes\n needs a better place\n \"\"\"\n for mark in self.own_markers:\n if mark.name == name:\n yield mark\n\n def __iter__(self):\n return iter(self.own_markers)\n"},{"col":0,"comment":"null","endLoc":47,"header":"def namedtuple(\n typename: str,\n field_names: str | Iterable[str],\n *,\n rename: bool = False,\n module: str | None = None,\n defaults: Iterable[Any] | None = None,\n) -> type[tuple[Any, ...]]","id":3031,"name":"namedtuple","nodeType":"Function","startLoc":40,"text":"def namedtuple(\n typename: str,\n field_names: str | Iterable[str],\n *,\n rename: bool = False,\n module: str | None = None,\n defaults: Iterable[Any] | None = None,\n) -> type[tuple[Any, ...]]: ..."},{"className":"attrgetter","col":0,"comment":"\n attrgetter(attr, ...) --> attrgetter object\n \n Return a callable object that fetches the given attribute(s) from its operand.\n After f = attrgetter('name'), the call f(r) returns r.name.\n After g = attrgetter('name', 'date'), the call g(r) returns (r.name, r.date).\n After h = attrgetter('name.first', 'name.last'), the call h(r) returns\n (r.name.first, r.name.last).\n ","endLoc":280,"id":3032,"nodeType":"Class","startLoc":248,"text":"class attrgetter(object):\n \"\"\"\n attrgetter(attr, ...) --> attrgetter object\n \n Return a callable object that fetches the given attribute(s) from its operand.\n After f = attrgetter('name'), the call f(r) returns r.name.\n After g = attrgetter('name', 'date'), the call g(r) returns (r.name, r.date).\n After h = attrgetter('name.first', 'name.last'), the call h(r) returns\n (r.name.first, r.name.last).\n \"\"\"\n def __call__(self, *args, **kwargs): # real signature unknown\n \"\"\" Call self as a function. \"\"\"\n pass\n\n def __getattribute__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return getattr(self, name). \"\"\"\n pass\n\n def __init__(self, attr, *more): # real signature unknown; restored from __doc__\n pass\n\n @staticmethod # known case of __new__\n def __new__(*args, **kwargs): # real signature unknown\n \"\"\" Create and return a new object. See help(type) for accurate signature. \"\"\"\n pass\n\n def __reduce__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return state information for pickling \"\"\"\n pass\n\n def __repr__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return repr(self). \"\"\"\n pass"},{"col":0,"comment":"null","endLoc":306,"header":"def test_conftest_existing_resultlog(testdir)","id":3033,"name":"test_conftest_existing_resultlog","nodeType":"Function","startLoc":294,"text":"def test_conftest_existing_resultlog(testdir):\n x = testdir.mkdir(\"tests\")\n x.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def pytest_addoption(parser):\n parser.addoption(\"--xyz\", action=\"store_true\")\n \"\"\"\n )\n )\n testdir.makefile(ext=\".log\", result=\"\") # Writes result.log\n result = testdir.runpytest(\"-h\", \"--resultlog\", \"result.log\")\n result.stdout.fnmatch_lines([\"*--xyz*\"])"},{"col":0,"comment":"\n Returns a doctest.OutputChecker subclass that takes in account the\n ALLOW_UNICODE option to ignore u'' prefixes in strings and ALLOW_BYTES\n to strip b'' prefixes.\n Useful when the same doctest should run in Python 2 and Python 3.\n\n An inner class is used to avoid importing \"doctest\" at the module\n level.\n ","endLoc":515,"header":"def _get_checker()","id":3034,"name":"_get_checker","nodeType":"Function","startLoc":463,"text":"def _get_checker():\n \"\"\"\n Returns a doctest.OutputChecker subclass that takes in account the\n ALLOW_UNICODE option to ignore u'' prefixes in strings and ALLOW_BYTES\n to strip b'' prefixes.\n Useful when the same doctest should run in Python 2 and Python 3.\n\n An inner class is used to avoid importing \"doctest\" at the module\n level.\n \"\"\"\n if hasattr(_get_checker, \"LiteralsOutputChecker\"):\n return _get_checker.LiteralsOutputChecker()\n\n import doctest\n import re\n\n class LiteralsOutputChecker(doctest.OutputChecker):\n \"\"\"\n Copied from doctest_nose_plugin.py from the nltk project:\n https://github.com/nltk/nltk\n\n Further extended to also support byte literals.\n \"\"\"\n\n _unicode_literal_re = re.compile(r\"(\\W|^)[uU]([rR]?[\\'\\\"])\", re.UNICODE)\n _bytes_literal_re = re.compile(r\"(\\W|^)[bB]([rR]?[\\'\\\"])\", re.UNICODE)\n\n def check_output(self, want, got, optionflags):\n res = doctest.OutputChecker.check_output(self, want, got, optionflags)\n if res:\n return True\n\n allow_unicode = optionflags & _get_allow_unicode_flag()\n allow_bytes = optionflags & _get_allow_bytes_flag()\n if not allow_unicode and not allow_bytes:\n return False\n\n else: # pragma: no cover\n\n def remove_prefixes(regex, txt):\n return re.sub(regex, r\"\\1\\2\", txt)\n\n if allow_unicode:\n want = remove_prefixes(self._unicode_literal_re, want)\n got = remove_prefixes(self._unicode_literal_re, got)\n if allow_bytes:\n want = remove_prefixes(self._bytes_literal_re, want)\n got = remove_prefixes(self._bytes_literal_re, got)\n res = doctest.OutputChecker.check_output(self, want, got, optionflags)\n return res\n\n _get_checker.LiteralsOutputChecker = LiteralsOutputChecker\n return _get_checker.LiteralsOutputChecker()"},{"col":0,"comment":"null","endLoc":321,"header":"def test_conftest_existing_junitxml(testdir)","id":3035,"name":"test_conftest_existing_junitxml","nodeType":"Function","startLoc":309,"text":"def test_conftest_existing_junitxml(testdir):\n x = testdir.mkdir(\"tests\")\n x.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def pytest_addoption(parser):\n parser.addoption(\"--xyz\", action=\"store_true\")\n \"\"\"\n )\n )\n testdir.makefile(ext=\".xml\", junit=\"\") # Writes junit.xml\n result = testdir.runpytest(\"-h\", \"--junitxml\", \"junit.xml\")\n result.stdout.fnmatch_lines([\"*--xyz*\"])"},{"id":3036,"name":"links.html","nodeType":"TextFile","path":"doc/en/_templates","text":"

Useful Links

\n\n"},{"col":4,"comment":" Call self as a function. ","endLoc":260,"header":"def __call__(self, *args, **kwargs)","id":3037,"name":"__call__","nodeType":"Function","startLoc":258,"text":"def __call__(self, *args, **kwargs): # real signature unknown\n \"\"\" Call self as a function. \"\"\"\n pass"},{"col":4,"comment":" Return getattr(self, name). ","endLoc":264,"header":"def __getattribute__(self, *args, **kwargs)","id":3038,"name":"__getattribute__","nodeType":"Function","startLoc":262,"text":"def __getattribute__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return getattr(self, name). \"\"\"\n pass"},{"col":4,"comment":"null","endLoc":267,"header":"def __init__(self, attr, *more)","id":3039,"name":"__init__","nodeType":"Function","startLoc":266,"text":"def __init__(self, attr, *more): # real signature unknown; restored from __doc__\n pass"},{"col":4,"comment":" Create and return a new object. See help(type) for accurate signature. ","endLoc":272,"header":"@staticmethod # known case of __new__\n def __new__(*args, **kwargs)","id":3040,"name":"__new__","nodeType":"Function","startLoc":269,"text":"@staticmethod # known case of __new__\n def __new__(*args, **kwargs): # real signature unknown\n \"\"\" Create and return a new object. See help(type) for accurate signature. \"\"\"\n pass"},{"col":4,"comment":" Return state information for pickling ","endLoc":276,"header":"def __reduce__(self, *args, **kwargs)","id":3041,"name":"__reduce__","nodeType":"Function","startLoc":274,"text":"def __reduce__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return state information for pickling \"\"\"\n pass"},{"col":4,"comment":" Return repr(self). ","endLoc":280,"header":"def __repr__(self, *args, **kwargs)","id":3042,"name":"__repr__","nodeType":"Function","startLoc":278,"text":"def __repr__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return repr(self). \"\"\"\n pass"},{"className":"MutableMapping","col":0,"comment":"null","endLoc":741,"id":3043,"nodeType":"Class","startLoc":693,"text":"class MutableMapping(Mapping[_KT, _VT]):\n @abstractmethod\n def __setitem__(self, key: _KT, value: _VT, /) -> None: ...\n @abstractmethod\n def __delitem__(self, key: _KT, /) -> None: ...\n def clear(self) -> None: ...\n @overload\n def pop(self, key: _KT, /) -> _VT: ...\n @overload\n def pop(self, key: _KT, /, default: _VT) -> _VT: ...\n @overload\n def pop(self, key: _KT, /, default: _T) -> _VT | _T: ...\n def popitem(self) -> tuple[_KT, _VT]: ...\n # This overload should be allowed only if the value type is compatible with None.\n #\n # Keep the following methods in line with MutableMapping.setdefault, modulo positional-only differences:\n # -- collections.OrderedDict.setdefault\n # -- collections.ChainMap.setdefault\n # -- weakref.WeakKeyDictionary.setdefault\n @overload\n def setdefault(self: MutableMapping[_KT, _T | None], key: _KT, default: None = None, /) -> _T | None: ...\n @overload\n def setdefault(self, key: _KT, default: _VT, /) -> _VT: ...\n # 'update' used to take a Union, but using overloading is better.\n # The second overloaded type here is a bit too general, because\n # Mapping[tuple[_KT, _VT], W] is a subclass of Iterable[tuple[_KT, _VT]],\n # but will always have the behavior of the first overloaded type\n # at runtime, leading to keys of a mix of types _KT and tuple[_KT, _VT].\n # We don't currently have any way of forcing all Mappings to use\n # the first overload, but by using overloading rather than a Union,\n # mypy will commit to using the first overload when the argument is\n # known to be a Mapping with unknown type parameters, which is closer\n # to the behavior we want. See mypy issue #1430.\n #\n # Various mapping classes have __ior__ methods that should be kept roughly in line with .update():\n # -- dict.__ior__\n # -- os._Environ.__ior__\n # -- collections.UserDict.__ior__\n # -- collections.ChainMap.__ior__\n # -- peewee.attrdict.__add__\n # -- peewee.attrdict.__iadd__\n # -- weakref.WeakValueDictionary.__ior__\n # -- weakref.WeakKeyDictionary.__ior__\n @overload\n def update(self, m: SupportsKeysAndGetItem[_KT, _VT], /, **kwargs: _VT) -> None: ...\n @overload\n def update(self, m: Iterable[tuple[_KT, _VT]], /, **kwargs: _VT) -> None: ...\n @overload\n def update(self, **kwargs: _VT) -> None: ..."},{"id":3044,"name":"release-3.2.4.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.2.4\n=======================================\n\npytest 3.2.4 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n* Christian Boelsen\n* Christoph Buchner\n* Daw-Ran Liou\n* Florian Bruhin\n* Franck Michea\n* Leonard Lausen\n* Matty G\n* Owen Tuz\n* Pavel Karateev\n* Pierre GIRAUD\n* Ronny Pfannschmidt\n* Stephen Finucane\n* Sviatoslav Abakumov\n* Thomas Hisch\n* Tom Dalton\n* Xuan Luong\n* Yorgos Pagles\n* Семён Марьясин\n\n\nHappy testing,\nThe pytest Development Team\n"},{"col":4,"comment":"Keep the log records in a list in addition to the log text.","endLoc":242,"header":"def emit(self, record)","id":3045,"name":"emit","nodeType":"Function","startLoc":239,"text":"def emit(self, record):\n \"\"\"Keep the log records in a list in addition to the log text.\"\"\"\n self.records.append(record)\n logging.StreamHandler.emit(self, record)"},{"id":3046,"name":"release-2.3.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.3.2: some fixes and more traceback-printing speed\n===========================================================================\n\npytest-2.3.2 is another stabilization release:\n\n- issue 205: fixes a regression with conftest detection\n- issue 208/29: fixes traceback-printing speed in some bad cases\n- fix teardown-ordering for parametrized setups\n- fix unittest and trial compat behaviour with respect to runTest() methods\n- issue 206 and others: some improvements to packaging\n- fix issue127 and others: improve some docs\n\nSee\n\n http://pytest.org/\n\nfor general information. To install or upgrade pytest:\n\n pip install -U pytest # or\n easy_install -U pytest\n\nbest,\nholger krekel\n\n\nChanges between 2.3.1 and 2.3.2\n-----------------------------------\n\n- fix issue208 and fix issue29 use new py version to avoid long pauses\n when printing tracebacks in long modules\n\n- fix issue205 - conftests in subdirs customizing\n pytest_pycollect_makemodule and pytest_pycollect_makeitem\n now work properly\n\n- fix teardown-ordering for parametrized setups\n\n- fix issue127 - better documentation for pytest_addoption\n and related objects.\n\n- fix unittest behaviour: TestCase.runtest only called if there are\n test methods defined\n\n- improve trial support: don't collect its empty\n unittest.TestCase.runTest() method\n\n- \"python setup.py test\" now works with pytest itself\n\n- fix/improve internal/packaging related bits:\n\n - exception message check of test_nose.py now passes on python33 as well\n\n - issue206 - fix test_assertrewrite.py to work when a global\n PYTHONDONTWRITEBYTECODE=1 is present\n\n - add tox.ini to pytest distribution so that ignore-dirs and others config\n bits are properly distributed for maintainers who run pytest-own tests\n"},{"fileName":"skip.py","filePath":"bench","id":3047,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom six.moves import range\n\nimport pytest\n\nSKIP = True\n\n\n@pytest.mark.parametrize(\"x\", range(5000))\ndef test_foo(x):\n if SKIP:\n pytest.skip(\"heh\")\n"},{"className":"range","col":0,"comment":"null","endLoc":1236,"id":3048,"nodeType":"Class","startLoc":1213,"text":"@final\nclass range(Sequence[int]):\n @property\n def start(self) -> int: ...\n @property\n def stop(self) -> int: ...\n @property\n def step(self) -> int: ...\n @overload\n def __new__(cls, __stop: SupportsIndex) -> Self: ...\n @overload\n def __new__(cls, __start: SupportsIndex, __stop: SupportsIndex, __step: SupportsIndex = ...) -> Self: ...\n def count(self, __value: int) -> int: ...\n def index(self, __value: int) -> int: ... # type: ignore[override]\n def __len__(self) -> int: ...\n def __eq__(self, __value: object) -> bool: ...\n def __hash__(self) -> int: ...\n def __contains__(self, __key: object) -> bool: ...\n def __iter__(self) -> Iterator[int]: ...\n @overload\n def __getitem__(self, __key: SupportsIndex) -> int: ...\n @overload\n def __getitem__(self, __key: slice) -> range: ...\n def __reversed__(self) -> Iterator[int]: ..."},{"col":4,"comment":"null","endLoc":695,"header":"@abstractmethod\n def __setitem__(self, key: _KT, value: _VT, /) -> None","id":3049,"name":"__setitem__","nodeType":"Function","startLoc":694,"text":"@abstractmethod\n def __setitem__(self, key: _KT, value: _VT, /) -> None: ..."},{"col":4,"comment":"null","endLoc":697,"header":"@abstractmethod\n def __delitem__(self, key: _KT, /) -> None","id":3050,"name":"__delitem__","nodeType":"Function","startLoc":696,"text":"@abstractmethod\n def __delitem__(self, key: _KT, /) -> None: ..."},{"col":4,"comment":"null","endLoc":700,"header":"@overload\n def pop(self, key: _KT, /) -> _VT","id":3051,"name":"pop","nodeType":"Function","startLoc":699,"text":"@overload\n def pop(self, key: _KT, /) -> _VT: ..."},{"col":4,"comment":"null","endLoc":702,"header":"@overload\n def pop(self, key: _KT, /, default: _VT) -> _VT","id":3052,"name":"pop","nodeType":"Function","startLoc":701,"text":"@overload\n def pop(self, key: _KT, /, default: _VT) -> _VT: ..."},{"col":4,"comment":"null","endLoc":704,"header":"@overload\n def pop(self, key: _KT, /, default: _T) -> _VT | _T","id":3053,"name":"pop","nodeType":"Function","startLoc":703,"text":"@overload\n def pop(self, key: _KT, /, default: _T) -> _VT | _T: ..."},{"col":4,"comment":"null","endLoc":705,"header":"def popitem(self) -> tuple[_KT, _VT]","id":3054,"name":"popitem","nodeType":"Function","startLoc":705,"text":"def popitem(self) -> tuple[_KT, _VT]: ..."},{"col":0,"comment":"null","endLoc":336,"header":"def test_conftest_import_order(testdir, monkeypatch)","id":3055,"name":"test_conftest_import_order","nodeType":"Function","startLoc":324,"text":"def test_conftest_import_order(testdir, monkeypatch):\n ct1 = testdir.makeconftest(\"\")\n sub = testdir.mkdir(\"sub\")\n ct2 = sub.join(\"conftest.py\")\n ct2.write(\"\")\n\n def impct(p):\n return p\n\n conftest = PytestPluginManager()\n conftest._confcutdir = testdir.tmpdir\n monkeypatch.setattr(conftest, \"_importconftest\", impct)\n assert conftest._getconftestmodules(sub) == [ct1, ct2]"},{"className":"ParameterSet","col":0,"comment":"null","endLoc":154,"id":3056,"nodeType":"Class","startLoc":64,"text":"class ParameterSet(namedtuple(\"ParameterSet\", \"values, marks, id\")):\n @classmethod\n def param(cls, *values, **kwargs):\n marks = kwargs.pop(\"marks\", ())\n if isinstance(marks, MarkDecorator):\n marks = (marks,)\n else:\n assert isinstance(marks, (tuple, list, set))\n\n id_ = kwargs.pop(\"id\", None)\n if id_ is not None:\n if not isinstance(id_, six.string_types):\n raise TypeError(\n \"Expected id to be a string, got {}: {!r}\".format(type(id_), id_)\n )\n id_ = ascii_escaped(id_)\n\n if kwargs:\n warnings.warn(\n PYTEST_PARAM_UNKNOWN_KWARGS.format(args=sorted(kwargs)), stacklevel=3\n )\n return cls(values, marks, id_)\n\n @classmethod\n def extract_from(cls, parameterset, force_tuple=False):\n \"\"\"\n :param parameterset:\n a legacy style parameterset that may or may not be a tuple,\n and may or may not be wrapped into a mess of mark objects\n\n :param force_tuple:\n enforce tuple wrapping so single argument tuple values\n don't get decomposed and break tests\n \"\"\"\n\n if isinstance(parameterset, cls):\n return parameterset\n if force_tuple:\n return cls.param(parameterset)\n else:\n return cls(parameterset, marks=[], id=None)\n\n @staticmethod\n def _parse_parametrize_args(argnames, argvalues, *args, **kwargs):\n if not isinstance(argnames, (tuple, list)):\n argnames = [x.strip() for x in argnames.split(\",\") if x.strip()]\n force_tuple = len(argnames) == 1\n else:\n force_tuple = False\n return argnames, force_tuple\n\n @staticmethod\n def _parse_parametrize_parameters(argvalues, force_tuple):\n return [\n ParameterSet.extract_from(x, force_tuple=force_tuple) for x in argvalues\n ]\n\n @classmethod\n def _for_parametrize(cls, argnames, argvalues, func, config, function_definition):\n argnames, force_tuple = cls._parse_parametrize_args(argnames, argvalues)\n parameters = cls._parse_parametrize_parameters(argvalues, force_tuple)\n del argvalues\n\n if parameters:\n # check all parameter sets have the correct number of values\n for param in parameters:\n if len(param.values) != len(argnames):\n msg = (\n '{nodeid}: in \"parametrize\" the number of names ({names_len}):\\n'\n \" {names}\\n\"\n \"must be equal to the number of values ({values_len}):\\n\"\n \" {values}\"\n )\n fail(\n msg.format(\n nodeid=function_definition.nodeid,\n values=param.values,\n names=argnames,\n names_len=len(argnames),\n values_len=len(param.values),\n ),\n pytrace=False,\n )\n else:\n # empty parameter set (likely computed at runtime): create a single\n # parameter set with NOTSET values, with the \"empty parameter set\" mark applied to it\n mark = get_empty_parameterset_mark(config, argnames, func)\n parameters.append(\n ParameterSet(values=(NOTSET,) * len(argnames), marks=[mark], id=None)\n )\n return argnames, parameters"},{"className":"Mark","col":0,"comment":"null","endLoc":177,"id":3057,"nodeType":"Class","startLoc":157,"text":"@attr.s(frozen=True)\nclass Mark(object):\n #: name of the mark\n name = attr.ib(type=str)\n #: positional arguments of the mark decorator\n args = attr.ib() # List[object]\n #: keyword arguments of the mark decorator\n kwargs = attr.ib() # Dict[str, object]\n\n def combined_with(self, other):\n \"\"\"\n :param other: the mark to combine with\n :type other: Mark\n :rtype: Mark\n\n combines by appending args and merging the mappings\n \"\"\"\n assert self.name == other.name\n return Mark(\n self.name, self.args + other.args, dict(self.kwargs, **other.kwargs)\n )"},{"col":4,"comment":"\n :param other: the mark to combine with\n :type other: Mark\n :rtype: Mark\n\n combines by appending args and merging the mappings\n ","endLoc":177,"header":"def combined_with(self, other)","id":3058,"name":"combined_with","nodeType":"Function","startLoc":166,"text":"def combined_with(self, other):\n \"\"\"\n :param other: the mark to combine with\n :type other: Mark\n :rtype: Mark\n\n combines by appending args and merging the mappings\n \"\"\"\n assert self.name == other.name\n return Mark(\n self.name, self.args + other.args, dict(self.kwargs, **other.kwargs)\n )"},{"col":4,"comment":"null","endLoc":1216,"header":"@property\n def start(self) -> int","id":3059,"name":"start","nodeType":"Function","startLoc":1215,"text":"@property\n def start(self) -> int: ..."},{"col":4,"comment":"null","endLoc":1218,"header":"@property\n def stop(self) -> int","id":3060,"name":"stop","nodeType":"Function","startLoc":1217,"text":"@property\n def stop(self) -> int: ..."},{"col":4,"comment":"null","endLoc":1220,"header":"@property\n def step(self) -> int","id":3061,"name":"step","nodeType":"Function","startLoc":1219,"text":"@property\n def step(self) -> int: ..."},{"col":4,"comment":"null","endLoc":1225,"header":"def count(self, __value: int) -> int","id":3062,"name":"count","nodeType":"Function","startLoc":1225,"text":"def count(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":1226,"header":"def index(self, __value: int) -> int","id":3063,"name":"index","nodeType":"Function","startLoc":1226,"text":"def index(self, __value: int) -> int: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":1227,"header":"def __len__(self) -> int","id":3064,"name":"__len__","nodeType":"Function","startLoc":1227,"text":"def __len__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":1228,"header":"def __eq__(self, __value: object) -> bool","id":3065,"name":"__eq__","nodeType":"Function","startLoc":1228,"text":"def __eq__(self, __value: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":1229,"header":"def __hash__(self) -> int","id":3066,"name":"__hash__","nodeType":"Function","startLoc":1229,"text":"def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":1230,"header":"def __contains__(self, __key: object) -> bool","id":3067,"name":"__contains__","nodeType":"Function","startLoc":1230,"text":"def __contains__(self, __key: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":1231,"header":"def __iter__(self) -> Iterator[int]","id":3068,"name":"__iter__","nodeType":"Function","startLoc":1231,"text":"def __iter__(self) -> Iterator[int]: ..."},{"col":4,"comment":"null","endLoc":1233,"header":"@overload\n def __getitem__(self, __key: SupportsIndex) -> int","id":3069,"name":"__getitem__","nodeType":"Function","startLoc":1232,"text":"@overload\n def __getitem__(self, __key: SupportsIndex) -> int: ..."},{"col":4,"comment":"null","endLoc":1235,"header":"@overload\n def __getitem__(self, __key: slice) -> range","id":3070,"name":"__getitem__","nodeType":"Function","startLoc":1234,"text":"@overload\n def __getitem__(self, __key: slice) -> range: ..."},{"col":4,"comment":"null","endLoc":1236,"header":"def __reversed__(self) -> Iterator[int]","id":3071,"name":"__reversed__","nodeType":"Function","startLoc":1236,"text":"def __reversed__(self) -> Iterator[int]: ..."},{"className":"range","col":0,"comment":"\n range(stop) -> range object\n range(start, stop[, step]) -> range object\n \n Return an object that produces a sequence of integers from start (inclusive)\n to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.\n start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.\n These are exactly the valid indices for a list of 4 elements.\n When step is given, it specifies the increment (or decrement).\n ","endLoc":4394,"id":3072,"nodeType":"Class","startLoc":4297,"text":"class range(object):\n \"\"\"\n range(stop) -> range object\n range(start, stop[, step]) -> range object\n \n Return an object that produces a sequence of integers from start (inclusive)\n to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.\n start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.\n These are exactly the valid indices for a list of 4 elements.\n When step is given, it specifies the increment (or decrement).\n \"\"\"\n def count(self, value): # real signature unknown; restored from __doc__\n \"\"\" rangeobject.count(value) -> integer -- return number of occurrences of value \"\"\"\n return 0\n\n def index(self, value): # real signature unknown; restored from __doc__\n \"\"\"\n rangeobject.index(value) -> integer -- return index of value.\n Raise ValueError if the value is not present.\n \"\"\"\n return 0\n\n def __bool__(self, *args, **kwargs): # real signature unknown\n \"\"\" self != 0 \"\"\"\n pass\n\n def __contains__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return key in self. \"\"\"\n pass\n\n def __eq__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self==value. \"\"\"\n pass\n\n def __getattribute__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return getattr(self, name). \"\"\"\n pass\n\n def __getitem__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self[key]. \"\"\"\n pass\n\n def __ge__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self>=value. \"\"\"\n pass\n\n def __gt__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self>value. \"\"\"\n pass\n\n def __hash__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return hash(self). \"\"\"\n pass\n\n def __init__(self, stop): # real signature unknown; restored from __doc__\n pass\n\n def __iter__(self, *args, **kwargs): # real signature unknown\n \"\"\" Implement iter(self). \"\"\"\n pass\n\n def __len__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return len(self). \"\"\"\n pass\n\n def __le__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self<=value. \"\"\"\n pass\n\n def __lt__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self integer -- return number of occurrences of value ","endLoc":4310,"header":"def count(self, value)","id":3073,"name":"count","nodeType":"Function","startLoc":4308,"text":"def count(self, value): # real signature unknown; restored from __doc__\n \"\"\" rangeobject.count(value) -> integer -- return number of occurrences of value \"\"\"\n return 0"},{"col":4,"comment":"\n rangeobject.index(value) -> integer -- return index of value.\n Raise ValueError if the value is not present.\n ","endLoc":4317,"header":"def index(self, value)","id":3074,"name":"index","nodeType":"Function","startLoc":4312,"text":"def index(self, value): # real signature unknown; restored from __doc__\n \"\"\"\n rangeobject.index(value) -> integer -- return index of value.\n Raise ValueError if the value is not present.\n \"\"\"\n return 0"},{"col":4,"comment":" self != 0 ","endLoc":4321,"header":"def __bool__(self, *args, **kwargs)","id":3075,"name":"__bool__","nodeType":"Function","startLoc":4319,"text":"def __bool__(self, *args, **kwargs): # real signature unknown\n \"\"\" self != 0 \"\"\"\n pass"},{"col":4,"comment":" Return key in self. ","endLoc":4325,"header":"def __contains__(self, *args, **kwargs)","id":3076,"name":"__contains__","nodeType":"Function","startLoc":4323,"text":"def __contains__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return key in self. \"\"\"\n pass"},{"col":4,"comment":" Return self==value. ","endLoc":4329,"header":"def __eq__(self, *args, **kwargs)","id":3077,"name":"__eq__","nodeType":"Function","startLoc":4327,"text":"def __eq__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self==value. \"\"\"\n pass"},{"col":4,"comment":" Return getattr(self, name). ","endLoc":4333,"header":"def __getattribute__(self, *args, **kwargs)","id":3078,"name":"__getattribute__","nodeType":"Function","startLoc":4331,"text":"def __getattribute__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return getattr(self, name). \"\"\"\n pass"},{"col":4,"comment":" Return self[key]. ","endLoc":4337,"header":"def __getitem__(self, *args, **kwargs)","id":3079,"name":"__getitem__","nodeType":"Function","startLoc":4335,"text":"def __getitem__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self[key]. \"\"\"\n pass"},{"col":4,"comment":" Return self>=value. ","endLoc":4341,"header":"def __ge__(self, *args, **kwargs)","id":3080,"name":"__ge__","nodeType":"Function","startLoc":4339,"text":"def __ge__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self>=value. \"\"\"\n pass"},{"col":4,"comment":" Return self>value. ","endLoc":4345,"header":"def __gt__(self, *args, **kwargs)","id":3081,"name":"__gt__","nodeType":"Function","startLoc":4343,"text":"def __gt__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self>value. \"\"\"\n pass"},{"col":4,"comment":" Return hash(self). ","endLoc":4349,"header":"def __hash__(self, *args, **kwargs)","id":3083,"name":"__hash__","nodeType":"Function","startLoc":4347,"text":"def __hash__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return hash(self). \"\"\"\n pass"},{"col":4,"comment":"null","endLoc":4352,"header":"def __init__(self, stop)","id":3084,"name":"__init__","nodeType":"Function","startLoc":4351,"text":"def __init__(self, stop): # real signature unknown; restored from __doc__\n pass"},{"col":4,"comment":" Implement iter(self). ","endLoc":4356,"header":"def __iter__(self, *args, **kwargs)","id":3085,"name":"__iter__","nodeType":"Function","startLoc":4354,"text":"def __iter__(self, *args, **kwargs): # real signature unknown\n \"\"\" Implement iter(self). \"\"\"\n pass"},{"col":4,"comment":" Return len(self). ","endLoc":4360,"header":"def __len__(self, *args, **kwargs)","id":3086,"name":"__len__","nodeType":"Function","startLoc":4358,"text":"def __len__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return len(self). \"\"\"\n pass"},{"col":4,"comment":" Return self<=value. ","endLoc":4364,"header":"def __le__(self, *args, **kwargs)","id":3087,"name":"__le__","nodeType":"Function","startLoc":4362,"text":"def __le__(self, *args, **kwargs): # real signature unknown\n \"\"\" Return self<=value. \"\"\"\n pass"},{"col":4,"comment":" Return self log level\n self._initial_log_levels = {} # Dict[str, int]\n\n def _finalize(self):\n \"\"\"Finalizes the fixture.\n\n This restores the log levels changed by :meth:`set_level`.\n \"\"\"\n # restore log levels\n for logger_name, level in self._initial_log_levels.items():\n logger = logging.getLogger(logger_name)\n logger.setLevel(level)\n\n @property\n def handler(self):\n \"\"\"\n :rtype: LogCaptureHandler\n \"\"\"\n return self._item.catch_log_handler\n\n def get_records(self, when):\n \"\"\"\n Get the logging records for one of the possible test phases.\n\n :param str when:\n Which test phase to obtain the records from. Valid values are: \"setup\", \"call\" and \"teardown\".\n\n :rtype: List[logging.LogRecord]\n :return: the list of captured records at the given stage\n\n .. versionadded:: 3.4\n \"\"\"\n handler = self._item.catch_log_handlers.get(when)\n if handler:\n return handler.records\n else:\n return []\n\n @property\n def text(self):\n \"\"\"Returns the formatted log text.\"\"\"\n return _remove_ansi_escape_sequences(self.handler.stream.getvalue())\n\n @property\n def records(self):\n \"\"\"Returns the list of log records.\"\"\"\n return self.handler.records\n\n @property\n def record_tuples(self):\n \"\"\"Returns a list of a stripped down version of log records intended\n for use in assertion comparison.\n\n The format of the tuple is:\n\n (logger_name, log_level, message)\n \"\"\"\n return [(r.name, r.levelno, r.getMessage()) for r in self.records]\n\n @property\n def messages(self):\n \"\"\"Returns a list of format-interpolated log messages.\n\n Unlike 'records', which contains the format string and parameters for interpolation, log messages in this list\n are all interpolated.\n Unlike 'text', which contains the output from the handler, log messages in this list are unadorned with\n levels, timestamps, etc, making exact comparisons more reliable.\n\n Note that traceback or stack info (from :func:`logging.exception` or the `exc_info` or `stack_info` arguments\n to the logging functions) is not included, as this is added by the formatter in the handler.\n\n .. versionadded:: 3.7\n \"\"\"\n return [r.getMessage() for r in self.records]\n\n def clear(self):\n \"\"\"Reset the list of log records and the captured log text.\"\"\"\n self.handler.reset()\n\n def set_level(self, level, logger=None):\n \"\"\"Sets the level for capturing of logs. The level will be restored to its previous value at the end of\n the test.\n\n :param int level: the logger to level.\n :param str logger: the logger to update the level. If not given, the root logger level is updated.\n\n .. versionchanged:: 3.4\n The levels of the loggers changed by this function will be restored to their initial values at the\n end of the test.\n \"\"\"\n logger_name = logger\n logger = logging.getLogger(logger_name)\n # save the original log-level to restore it during teardown\n self._initial_log_levels.setdefault(logger_name, logger.level)\n logger.setLevel(level)\n\n @contextmanager\n def at_level(self, level, logger=None):\n \"\"\"Context manager that sets the level for capturing of logs. After the end of the 'with' statement the\n level is restored to its original value.\n\n :param int level: the logger to level.\n :param str logger: the logger to update the level. If not given, the root logger level is updated.\n \"\"\"\n logger = logging.getLogger(logger)\n orig_level = logger.level\n logger.setLevel(level)\n try:\n yield\n finally:\n logger.setLevel(orig_level)"},{"col":4,"comment":"Creates a new funcarg.","endLoc":256,"header":"def __init__(self, item)","id":3111,"name":"__init__","nodeType":"Function","startLoc":252,"text":"def __init__(self, item):\n \"\"\"Creates a new funcarg.\"\"\"\n self._item = item\n # dict of log name -> log level\n self._initial_log_levels = {} # Dict[str, int]"},{"col":4,"comment":"Finalizes the fixture.\n\n This restores the log levels changed by :meth:`set_level`.\n ","endLoc":266,"header":"def _finalize(self)","id":3112,"name":"_finalize","nodeType":"Function","startLoc":258,"text":"def _finalize(self):\n \"\"\"Finalizes the fixture.\n\n This restores the log levels changed by :meth:`set_level`.\n \"\"\"\n # restore log levels\n for logger_name, level in self._initial_log_levels.items():\n logger = logging.getLogger(logger_name)\n logger.setLevel(level)"},{"col":0,"comment":"null","endLoc":401,"header":"def test_conftest_found_with_double_dash(testdir)","id":3113,"name":"test_conftest_found_with_double_dash","nodeType":"Function","startLoc":384,"text":"def test_conftest_found_with_double_dash(testdir):\n sub = testdir.mkdir(\"sub\")\n sub.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def pytest_addoption(parser):\n parser.addoption(\"--hello-world\", action=\"store_true\")\n \"\"\"\n )\n )\n p = sub.join(\"test_hello.py\")\n p.write(\"def test_hello(): pass\")\n result = testdir.runpytest(str(p) + \"::test_hello\", \"-h\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *--hello-world*\n \"\"\"\n )"},{"attributeType":"null","col":8,"comment":"null","endLoc":54,"id":3114,"name":"logfile","nodeType":"Attribute","startLoc":54,"text":"self.logfile"},{"attributeType":"null","col":8,"comment":"null","endLoc":53,"id":3115,"name":"config","nodeType":"Attribute","startLoc":53,"text":"self.config"},{"className":"TestWithFunctionIntegration","col":0,"comment":"null","endLoc":135,"id":3116,"nodeType":"Class","startLoc":58,"text":"class TestWithFunctionIntegration(object):\n # XXX (hpk) i think that the resultlog plugin should\n # provide a Parser object so that one can remain\n # ignorant regarding formatting details.\n def getresultlog(self, testdir, arg):\n resultlog = testdir.tmpdir.join(\"resultlog\")\n testdir.plugins.append(\"resultlog\")\n args = [\"--resultlog=%s\" % resultlog] + [arg]\n testdir.runpytest(*args)\n return [x for x in resultlog.readlines(cr=0) if x]\n\n def test_collection_report(self, testdir):\n ok = testdir.makepyfile(test_collection_ok=\"\")\n fail = testdir.makepyfile(test_collection_fail=\"XXX\")\n lines = self.getresultlog(testdir, ok)\n assert not lines\n\n lines = self.getresultlog(testdir, fail)\n assert lines\n assert lines[0].startswith(\"F \")\n assert lines[0].endswith(\"test_collection_fail.py\"), lines[0]\n for x in lines[1:]:\n assert x.startswith(\" \")\n assert \"XXX\" in \"\".join(lines[1:])\n\n def test_log_test_outcomes(self, testdir):\n mod = testdir.makepyfile(\n test_mod=\"\"\"\n import pytest\n def test_pass(): pass\n def test_skip(): pytest.skip(\"hello\")\n def test_fail(): raise ValueError(\"FAIL\")\n\n @pytest.mark.xfail\n def test_xfail(): raise ValueError(\"XFAIL\")\n @pytest.mark.xfail\n def test_xpass(): pass\n\n \"\"\"\n )\n lines = self.getresultlog(testdir, mod)\n assert len(lines) >= 3\n assert lines[0].startswith(\". \")\n assert lines[0].endswith(\"test_pass\")\n assert lines[1].startswith(\"s \"), lines[1]\n assert lines[1].endswith(\"test_skip\")\n assert lines[2].find(\"hello\") != -1\n\n assert lines[3].startswith(\"F \")\n assert lines[3].endswith(\"test_fail\")\n tb = \"\".join(lines[4:8])\n assert tb.find('raise ValueError(\"FAIL\")') != -1\n\n assert lines[8].startswith(\"x \")\n tb = \"\".join(lines[8:14])\n assert tb.find('raise ValueError(\"XFAIL\")') != -1\n\n assert lines[14].startswith(\"X \")\n assert len(lines) == 15\n\n @pytest.mark.parametrize(\"style\", (\"native\", \"long\", \"short\"))\n def test_internal_exception(self, style):\n # they are produced for example by a teardown failing\n # at the end of the run or a failing hook invocation\n try:\n raise ValueError\n except ValueError:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n reslog = ResultLog(None, py.io.TextIO())\n reslog.pytest_internalerror(excinfo.getrepr(style=style))\n entry = reslog.logfile.getvalue()\n entry_lines = entry.splitlines()\n\n assert entry_lines[0].startswith(\"! \")\n if style != \"native\":\n assert os.path.basename(__file__)[:-9] in entry_lines[0] # .pyc/class\n assert entry_lines[-1][0] == \" \"\n assert \"ValueError\" in entry"},{"col":4,"comment":"null","endLoc":67,"header":"def getresultlog(self, testdir, arg)","id":3117,"name":"getresultlog","nodeType":"Function","startLoc":62,"text":"def getresultlog(self, testdir, arg):\n resultlog = testdir.tmpdir.join(\"resultlog\")\n testdir.plugins.append(\"resultlog\")\n args = [\"--resultlog=%s\" % resultlog] + [arg]\n testdir.runpytest(*args)\n return [x for x in resultlog.readlines(cr=0) if x]"},{"col":0,"comment":"Test that conftest files are detected only up to an ini file, unless\n an explicit --confcutdir option is given.\n ","endLoc":556,"header":"@pytest.mark.parametrize(\n \"confcutdir,passed,error\", [(\".\", 2, 0), (\"src\", 1, 1), (None, 1, 1)]\n)\ndef test_search_conftest_up_to_inifile(testdir, confcutdir, passed, error)","id":3118,"name":"test_search_conftest_up_to_inifile","nodeType":"Function","startLoc":508,"text":"@pytest.mark.parametrize(\n \"confcutdir,passed,error\", [(\".\", 2, 0), (\"src\", 1, 1), (None, 1, 1)]\n)\ndef test_search_conftest_up_to_inifile(testdir, confcutdir, passed, error):\n \"\"\"Test that conftest files are detected only up to an ini file, unless\n an explicit --confcutdir option is given.\n \"\"\"\n root = testdir.tmpdir\n src = root.join(\"src\").ensure(dir=1)\n src.join(\"pytest.ini\").write(\"[pytest]\")\n src.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def fix1(): pass\n \"\"\"\n )\n )\n src.join(\"test_foo.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_1(fix1):\n pass\n def test_2(out_of_reach):\n pass\n \"\"\"\n )\n )\n root.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def out_of_reach(): pass\n \"\"\"\n )\n )\n\n args = [str(src)]\n if confcutdir:\n args = [\"--confcutdir=%s\" % root.join(confcutdir)]\n result = testdir.runpytest(*args)\n match = \"\"\n if passed:\n match += \"*%d passed*\" % passed\n if error:\n match += \"*%d error*\" % error\n result.stdout.fnmatch_lines(match)"},{"col":4,"comment":"null","endLoc":81,"header":"def test_collection_report(self, testdir)","id":3119,"name":"test_collection_report","nodeType":"Function","startLoc":69,"text":"def test_collection_report(self, testdir):\n ok = testdir.makepyfile(test_collection_ok=\"\")\n fail = testdir.makepyfile(test_collection_fail=\"XXX\")\n lines = self.getresultlog(testdir, ok)\n assert not lines\n\n lines = self.getresultlog(testdir, fail)\n assert lines\n assert lines[0].startswith(\"F \")\n assert lines[0].endswith(\"test_collection_fail.py\"), lines[0]\n for x in lines[1:]:\n assert x.startswith(\" \")\n assert \"XXX\" in \"\".join(lines[1:])"},{"col":4,"comment":"null","endLoc":767,"header":"def _initini(self, args)","id":3120,"name":"_initini","nodeType":"Function","startLoc":752,"text":"def _initini(self, args):\n ns, unknown_args = self._parser.parse_known_and_unknown_args(\n args, namespace=copy.copy(self.option)\n )\n r = determine_setup(\n ns.inifilename,\n ns.file_or_dir + unknown_args,\n rootdir_cmd_arg=ns.rootdir or None,\n config=self,\n )\n self.rootdir, self.inifile, self.inicfg = r\n self._parser.extra_info[\"rootdir\"] = self.rootdir\n self._parser.extra_info[\"inifile\"] = self.inifile\n self._parser.addini(\"addopts\", \"extra command line options\", \"args\")\n self._parser.addini(\"minversion\", \"minimally required pytest version\")\n self._override_ini = ns.override_ini or ()"},{"col":4,"comment":" register an ini-file option.\n\n :name: name of the ini-variable\n :type: type of the variable, can be ``pathlist``, ``args``, ``linelist``\n or ``bool``.\n :default: default value if no ini-file option exists but is queried.\n\n The value of ini-variables can be retrieved via a call to\n :py:func:`config.getini(name) <_pytest.config.Config.getini>`.\n ","endLoc":133,"header":"def addini(self, name, help, type=None, default=None)","id":3121,"name":"addini","nodeType":"Function","startLoc":120,"text":"def addini(self, name, help, type=None, default=None):\n \"\"\" register an ini-file option.\n\n :name: name of the ini-variable\n :type: type of the variable, can be ``pathlist``, ``args``, ``linelist``\n or ``bool``.\n :default: default value if no ini-file option exists but is queried.\n\n The value of ini-variables can be retrieved via a call to\n :py:func:`config.getini(name) <_pytest.config.Config.getini>`.\n \"\"\"\n assert type in (None, \"pathlist\", \"args\", \"linelist\", \"bool\")\n self._inidict[name] = (help, type, default)\n self._ininames.append(name)"},{"col":4,"comment":" return configuration value from an :ref:`ini file `. If the\n specified name hasn't been registered through a prior\n :py:func:`parser.addini <_pytest.config.Parser.addini>`\n call (usually from a plugin), a ValueError is raised. ","endLoc":929,"header":"def getini(self, name)","id":3122,"name":"getini","nodeType":"Function","startLoc":920,"text":"def getini(self, name):\n \"\"\" return configuration value from an :ref:`ini file `. If the\n specified name hasn't been registered through a prior\n :py:func:`parser.addini <_pytest.config.Parser.addini>`\n call (usually from a plugin), a ValueError is raised. \"\"\"\n try:\n return self._inicache[name]\n except KeyError:\n self._inicache[name] = val = self._getini(name)\n return val"},{"col":4,"comment":"null","endLoc":960,"header":"def _getini(self, name)","id":3123,"name":"_getini","nodeType":"Function","startLoc":931,"text":"def _getini(self, name):\n try:\n description, type, default = self._parser._inidict[name]\n except KeyError:\n raise ValueError(\"unknown configuration value: %r\" % (name,))\n value = self._get_override_ini_value(name)\n if value is None:\n try:\n value = self.inicfg[name]\n except KeyError:\n if default is not None:\n return default\n if type is None:\n return \"\"\n return []\n if type == \"pathlist\":\n dp = py.path.local(self.inicfg.config.path).dirpath()\n values = []\n for relpath in shlex.split(value):\n values.append(dp.join(relpath, abs=True))\n return values\n elif type == \"args\":\n return shlex.split(value)\n elif type == \"linelist\":\n return [t for t in map(lambda x: x.strip(), value.split(\"\\n\")) if t]\n elif type == \"bool\":\n return bool(_strtobool(value.strip()))\n else:\n assert type is None\n return value"},{"col":4,"comment":"null","endLoc":989,"header":"def _get_override_ini_value(self, name)","id":3124,"name":"_get_override_ini_value","nodeType":"Function","startLoc":976,"text":"def _get_override_ini_value(self, name):\n value = None\n # override_ini is a list of \"ini=value\" options\n # always use the last item if multiple values are set for same ini-name,\n # e.g. -o foo=bar1 -o foo=bar2 will set foo to bar2\n for ini_config in self._override_ini:\n try:\n key, user_ini_value = ini_config.split(\"=\", 1)\n except ValueError:\n raise UsageError(\"-o/--override-ini expects option=value style.\")\n else:\n if key == name:\n value = user_ini_value\n return value"},{"col":35,"endLoc":955,"id":3125,"nodeType":"Lambda","startLoc":955,"text":"lambda x: x.strip()"},{"col":0,"comment":"Convert a string representation of truth to true (1) or false (0).\n\n True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values\n are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if\n 'val' is anything else.\n\n .. note:: copied from distutils.util\n ","endLoc":1101,"header":"def _strtobool(val)","id":3126,"name":"_strtobool","nodeType":"Function","startLoc":1086,"text":"def _strtobool(val):\n \"\"\"Convert a string representation of truth to true (1) or false (0).\n\n True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values\n are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if\n 'val' is anything else.\n\n .. note:: copied from distutils.util\n \"\"\"\n val = val.lower()\n if val in (\"y\", \"yes\", \"t\", \"true\", \"on\", \"1\"):\n return 1\n elif val in (\"n\", \"no\", \"f\", \"false\", \"off\", \"0\"):\n return 0\n else:\n raise ValueError(\"invalid truth value %r\" % (val,))"},{"col":4,"comment":"null","endLoc":884,"header":"def _checkversion(self)","id":3127,"name":"_checkversion","nodeType":"Function","startLoc":870,"text":"def _checkversion(self):\n import pytest\n\n minver = self.inicfg.get(\"minversion\", None)\n if minver:\n if Version(minver) > Version(pytest.__version__):\n raise pytest.UsageError(\n \"%s:%d: requires pytest-%s, actual pytest-%s'\"\n % (\n self.inicfg.config.path,\n self.inicfg.lineof(\"minversion\"),\n minver,\n pytest.__version__,\n )\n )"},{"col":4,"comment":"Install the PEP 302 import hook if using assertion rewriting.\n\n Needs to parse the --assert= option from the commandline\n and find all the installed plugins to mark them for rewriting\n by the importhook.\n ","endLoc":785,"header":"def _consider_importhook(self, args)","id":3128,"name":"_consider_importhook","nodeType":"Function","startLoc":769,"text":"def _consider_importhook(self, args):\n \"\"\"Install the PEP 302 import hook if using assertion rewriting.\n\n Needs to parse the --assert= option from the commandline\n and find all the installed plugins to mark them for rewriting\n by the importhook.\n \"\"\"\n ns, unknown_args = self._parser.parse_known_and_unknown_args(args)\n mode = getattr(ns, \"assertmode\", \"plain\")\n if mode == \"rewrite\":\n try:\n hook = _pytest.assertion.install_importhook(self)\n except SystemError:\n mode = \"plain\"\n else:\n self._mark_plugins_for_rewrite(hook)\n _warn_about_missing_assertion(mode)"},{"col":0,"comment":"null","endLoc":576,"header":"def test_issue1073_conftest_special_objects(testdir)","id":3129,"name":"test_issue1073_conftest_special_objects","nodeType":"Function","startLoc":559,"text":"def test_issue1073_conftest_special_objects(testdir):\n testdir.makeconftest(\n \"\"\"\\\n class DontTouchMe(object):\n def __getattr__(self, x):\n raise Exception('cant touch me')\n\n x = DontTouchMe()\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\\\n def test_some():\n pass\n \"\"\"\n )\n res = testdir.runpytest()\n assert res.ret == 0"},{"col":0,"comment":"null","endLoc":593,"header":"def test_conftest_exception_handling(testdir)","id":3130,"name":"test_conftest_exception_handling","nodeType":"Function","startLoc":579,"text":"def test_conftest_exception_handling(testdir):\n testdir.makeconftest(\n \"\"\"\\\n raise ValueError()\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\\\n def test_some():\n pass\n \"\"\"\n )\n res = testdir.runpytest()\n assert res.ret == 4\n assert \"raise ValueError()\" in [line.strip() for line in res.errlines]"},{"col":4,"comment":"null","endLoc":120,"header":"def __init__(self, reprlocation_lines)","id":3131,"name":"__init__","nodeType":"Function","startLoc":118,"text":"def __init__(self, reprlocation_lines):\n # List of (reprlocation, lines) tuples\n self.reprlocation_lines = reprlocation_lines"},{"col":0,"comment":"Session's gethookproxy() would cache conftests incorrectly (#2016).\n It was decided to remove the cache altogether.\n ","endLoc":615,"header":"def test_hook_proxy(testdir)","id":3132,"name":"test_hook_proxy","nodeType":"Function","startLoc":596,"text":"def test_hook_proxy(testdir):\n \"\"\"Session's gethookproxy() would cache conftests incorrectly (#2016).\n It was decided to remove the cache altogether.\n \"\"\"\n testdir.makepyfile(\n **{\n \"root/demo-0/test_foo1.py\": \"def test1(): pass\",\n \"root/demo-a/test_foo2.py\": \"def test1(): pass\",\n \"root/demo-a/conftest.py\": \"\"\"\\\n def pytest_ignore_collect(path, config):\n return True\n \"\"\",\n \"root/demo-b/test_foo3.py\": \"def test1(): pass\",\n \"root/demo-c/test_foo4.py\": \"def test1(): pass\",\n }\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"*test_foo1.py*\", \"*test_foo3.py*\", \"*test_foo4.py*\", \"*3 passed*\"]\n )"},{"col":0,"comment":"null","endLoc":631,"header":"def test_required_option_help(testdir)","id":3133,"name":"test_required_option_help","nodeType":"Function","startLoc":618,"text":"def test_required_option_help(testdir):\n testdir.makeconftest(\"assert 0\")\n x = testdir.mkdir(\"x\")\n x.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def pytest_addoption(parser):\n parser.addoption(\"--xyz\", action=\"store_true\", required=True)\n \"\"\"\n )\n )\n result = testdir.runpytest(\"-h\", x)\n assert \"argument --xyz is required\" not in result.stdout.str()\n assert \"general:\" in result.stdout.str()"},{"col":4,"comment":"null","endLoc":279,"header":"def reportinfo(self)","id":3134,"name":"reportinfo","nodeType":"Function","startLoc":278,"text":"def reportinfo(self):\n return self.fspath, self.dtest.lineno, \"[doctest] %s\" % self.name"},{"attributeType":"null","col":8,"comment":"null","endLoc":188,"id":3135,"name":"dtest","nodeType":"Attribute","startLoc":188,"text":"self.dtest"},{"attributeType":"null","col":8,"comment":"null","endLoc":189,"id":3136,"name":"obj","nodeType":"Attribute","startLoc":189,"text":"self.obj"},{"col":4,"comment":"null","endLoc":254,"header":"def _is_marked_for_rewrite(self, name, state)","id":3137,"name":"_is_marked_for_rewrite","nodeType":"Function","startLoc":243,"text":"def _is_marked_for_rewrite(self, name, state):\n try:\n return self._marked_for_rewrite_cache[name]\n except KeyError:\n for marked in self._must_rewrite:\n if name == marked or name.startswith(marked + \".\"):\n state.trace(\"matched marked file %r (from %r)\" % (name, marked))\n self._marked_for_rewrite_cache[name] = True\n return True\n\n self._marked_for_rewrite_cache[name] = False\n return False"},{"attributeType":"null","col":8,"comment":"null","endLoc":187,"id":3138,"name":"runner","nodeType":"Attribute","startLoc":187,"text":"self.runner"},{"attributeType":"null","col":8,"comment":"null","endLoc":190,"id":3139,"name":"fixture_request","nodeType":"Attribute","startLoc":190,"text":"self.fixture_request"},{"id":3140,"name":"release-2.8.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.8.2: bug fixes\n=======================\n\npytest is a mature Python testing tool with more than a 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is supposed to be drop-in compatible to 2.8.1.\n\nSee below for the changes and see docs at:\n\n http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n Bruno Oliveira\n Demian Brecht\n Florian Bruhin\n Ionel Cristian Mărieș\n Raphael Pierzina\n Ronny Pfannschmidt\n holger krekel\n\nHappy testing,\nThe py.test Development Team\n\n\n2.8.2 (compared to 2.7.2)\n-----------------------------\n\n- fix #1085: proper handling of encoding errors when passing encoded byte\n strings to pytest.parametrize in Python 2.\n Thanks Themanwithoutaplan for the report and Bruno Oliveira for the PR.\n\n- fix #1087: handling SystemError when passing empty byte strings to\n pytest.parametrize in Python 3.\n Thanks Paul Kehrer for the report and Bruno Oliveira for the PR.\n\n- fix #995: fixed internal error when filtering tracebacks where one entry\n was generated by an exec() statement.\n Thanks Daniel Hahler, Ashley C Straw, Philippe Gauthier and Pavel Savchenko\n for contributing and Bruno Oliveira for the PR.\n"},{"className":"DoctestModule","col":0,"comment":"null","endLoc":442,"id":3141,"nodeType":"Class","startLoc":399,"text":"class DoctestModule(pytest.Module):\n def collect(self):\n import doctest\n\n class MockAwareDocTestFinder(doctest.DocTestFinder):\n \"\"\"\n a hackish doctest finder that overrides stdlib internals to fix a stdlib bug\n\n https://github.com/pytest-dev/pytest/issues/3456\n https://bugs.python.org/issue25532\n \"\"\"\n\n def _find(self, tests, obj, name, module, source_lines, globs, seen):\n if _is_mocked(obj):\n return\n with _patch_unwrap_mock_aware():\n\n doctest.DocTestFinder._find(\n self, tests, obj, name, module, source_lines, globs, seen\n )\n\n if self.fspath.basename == \"conftest.py\":\n module = self.config.pluginmanager._importconftest(self.fspath)\n else:\n try:\n module = self.fspath.pyimport()\n except ImportError:\n if self.config.getvalue(\"doctest_ignore_import_errors\"):\n pytest.skip(\"unable to import module %r\" % self.fspath)\n else:\n raise\n # uses internal doctest module parsing mechanism\n finder = MockAwareDocTestFinder()\n optionflags = get_optionflags(self)\n runner = _get_runner(\n verbose=0,\n optionflags=optionflags,\n checker=_get_checker(),\n continue_on_failure=_get_continue_on_failure(self.config),\n )\n\n for test in finder.find(module, module.__name__):\n if test.examples: # skip empty doctests\n yield DoctestItem(test.name, self, runner, test)"},{"col":4,"comment":"null","endLoc":442,"header":"def collect(self)","id":3142,"name":"collect","nodeType":"Function","startLoc":400,"text":"def collect(self):\n import doctest\n\n class MockAwareDocTestFinder(doctest.DocTestFinder):\n \"\"\"\n a hackish doctest finder that overrides stdlib internals to fix a stdlib bug\n\n https://github.com/pytest-dev/pytest/issues/3456\n https://bugs.python.org/issue25532\n \"\"\"\n\n def _find(self, tests, obj, name, module, source_lines, globs, seen):\n if _is_mocked(obj):\n return\n with _patch_unwrap_mock_aware():\n\n doctest.DocTestFinder._find(\n self, tests, obj, name, module, source_lines, globs, seen\n )\n\n if self.fspath.basename == \"conftest.py\":\n module = self.config.pluginmanager._importconftest(self.fspath)\n else:\n try:\n module = self.fspath.pyimport()\n except ImportError:\n if self.config.getvalue(\"doctest_ignore_import_errors\"):\n pytest.skip(\"unable to import module %r\" % self.fspath)\n else:\n raise\n # uses internal doctest module parsing mechanism\n finder = MockAwareDocTestFinder()\n optionflags = get_optionflags(self)\n runner = _get_runner(\n verbose=0,\n optionflags=optionflags,\n checker=_get_checker(),\n continue_on_failure=_get_continue_on_failure(self.config),\n )\n\n for test in finder.find(module, module.__name__):\n if test.examples: # skip empty doctests\n yield DoctestItem(test.name, self, runner, test)"},{"id":3143,"name":"release.patch.rst","nodeType":"TextFile","path":"scripts","text":"pytest-{version}\n=======================================\n\npytest {version} has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n{contributors}\n\nHappy testing,\nThe pytest Development Team\n"},{"id":3144,"name":"release-2.4.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.4.1: fixing three regressions compared to 2.3.5\n===========================================================================\n\npytest-2.4.1 is a quick follow up release to fix three regressions\ncompared to 2.3.5 before they hit more people:\n\n- When using parser.addoption() unicode arguments to the\n \"type\" keyword should also be converted to the respective types.\n thanks Floris Bruynooghe, @dnozay. (fixes issue360 and issue362)\n\n- fix dotted filename completion when using argcomplete\n thanks Anthon van der Neuth. (fixes issue361)\n\n- fix regression when a 1-tuple (\"arg\",) is used for specifying\n parametrization (the values of the parametrization were passed\n nested in a tuple). Thanks Donald Stufft.\n\n- also merge doc typo fixes, thanks Andy Dirnberger\n\nas usual, docs at http://pytest.org and upgrades via::\n\n pip install -U pytest\n\nhave fun,\nholger krekel\n"},{"fileName":"setupplan.py","filePath":"src/_pytest","id":3145,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pytest\n\n\ndef pytest_addoption(parser):\n group = parser.getgroup(\"debugconfig\")\n group.addoption(\n \"--setupplan\",\n \"--setup-plan\",\n action=\"store_true\",\n help=\"show what fixtures and tests would be executed but \"\n \"don't execute anything.\",\n )\n\n\n@pytest.hookimpl(tryfirst=True)\ndef pytest_fixture_setup(fixturedef, request):\n # Will return a dummy fixture if the setuponly option is provided.\n if request.config.option.setupplan:\n fixturedef.cached_result = (None, None, None)\n return fixturedef.cached_result\n\n\n@pytest.hookimpl(tryfirst=True)\ndef pytest_cmdline_main(config):\n if config.option.setupplan:\n config.option.setuponly = True\n config.option.setupshow = True\n"},{"col":0,"comment":"null","endLoc":17,"header":"def pytest_addoption(parser)","id":3146,"name":"pytest_addoption","nodeType":"Function","startLoc":9,"text":"def pytest_addoption(parser):\n group = parser.getgroup(\"debugconfig\")\n group.addoption(\n \"--setupplan\",\n \"--setup-plan\",\n action=\"store_true\",\n help=\"show what fixtures and tests would be executed but \"\n \"don't execute anything.\",\n )"},{"attributeType":"bool","col":0,"comment":"null","endLoc":6,"id":3147,"name":"SKIP","nodeType":"Attribute","startLoc":6,"text":"SKIP"},{"col":0,"comment":"","endLoc":2,"header":"skip.py#","id":3148,"name":"","nodeType":"Function","startLoc":2,"text":"SKIP = True"},{"col":0,"comment":"null","endLoc":25,"header":"@pytest.hookimpl(tryfirst=True)\ndef pytest_fixture_setup(fixturedef, request)","id":3149,"name":"pytest_fixture_setup","nodeType":"Function","startLoc":20,"text":"@pytest.hookimpl(tryfirst=True)\ndef pytest_fixture_setup(fixturedef, request):\n # Will return a dummy fixture if the setuponly option is provided.\n if request.config.option.setupplan:\n fixturedef.cached_result = (None, None, None)\n return fixturedef.cached_result"},{"col":0,"comment":"null","endLoc":32,"header":"@pytest.hookimpl(tryfirst=True)\ndef pytest_cmdline_main(config)","id":3150,"name":"pytest_cmdline_main","nodeType":"Function","startLoc":28,"text":"@pytest.hookimpl(tryfirst=True)\ndef pytest_cmdline_main(config):\n if config.option.setupplan:\n config.option.setuponly = True\n config.option.setupshow = True"},{"id":3151,"name":"release-2.2.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.2.2: bug fixes\n===========================================================================\n\npytest-2.2.2 (updated to 2.2.3 to fix packaging issues) is a minor\nbackward-compatible release of the versatile py.test testing tool. It\ncontains bug fixes and a few refinements particularly to reporting with\n\"--collectonly\", see below for betails.\n\nFor general information see here:\n\n http://pytest.org/\n\nTo install or upgrade pytest:\n\n pip install -U pytest # or\n easy_install -U pytest\n\nSpecial thanks for helping on this release to Ronny Pfannschmidt\nand Ralf Schmitt and the contributors of issues.\n\nbest,\nholger krekel\n\n\nChanges between 2.2.1 and 2.2.2\n----------------------------------------\n\n- fix issue101: wrong args to unittest.TestCase test function now\n produce better output\n- fix issue102: report more useful errors and hints for when a\n test directory was renamed and some pyc/__pycache__ remain\n- fix issue106: allow parametrize to be applied multiple times\n e.g. from module, class and at function level.\n- fix issue107: actually perform session scope finalization\n- don't check in parametrize if indirect parameters are funcarg names\n- add chdir method to monkeypatch funcarg\n- fix crash resulting from calling monkeypatch undo a second time\n- fix issue115: make --collectonly robust against early failure\n (missing files/directories)\n- \"-qq --collectonly\" now shows only files and the number of tests in them\n- \"-q --collectonly\" now shows test ids\n- allow adding of attributes to test reports such that it also works\n with distributed testing (no upgrade of pytest-xdist needed)\n"},{"fileName":"setup_only.py","filePath":"testing/python","id":3152,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\n@pytest.fixture(params=[\"--setup-only\", \"--setup-plan\", \"--setup-show\"], scope=\"module\")\ndef mode(request):\n return request.param\n\n\ndef test_show_only_active_fixtures(testdir, mode):\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture\n def _arg0():\n \"\"\"hidden arg0 fixture\"\"\"\n @pytest.fixture\n def arg1():\n \"\"\"arg1 docstring\"\"\"\n def test_arg1(arg1):\n pass\n '''\n )\n\n result = testdir.runpytest(mode, p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\"*SETUP F arg1*\", \"*test_arg1 (fixtures used: arg1)*\", \"*TEARDOWN F arg1*\"]\n )\n assert \"_arg0\" not in result.stdout.str()\n\n\ndef test_show_different_scopes(testdir, mode):\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture\n def arg_function():\n \"\"\"function scoped fixture\"\"\"\n @pytest.fixture(scope='session')\n def arg_session():\n \"\"\"session scoped fixture\"\"\"\n def test_arg1(arg_session, arg_function):\n pass\n '''\n )\n\n result = testdir.runpytest(mode, p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\n \"SETUP S arg_session*\",\n \"*SETUP F arg_function*\",\n \"*test_arg1 (fixtures used: arg_function, arg_session)*\",\n \"*TEARDOWN F arg_function*\",\n \"TEARDOWN S arg_session*\",\n ]\n )\n\n\ndef test_show_nested_fixtures(testdir, mode):\n testdir.makeconftest(\n '''\n import pytest\n @pytest.fixture(scope='session')\n def arg_same():\n \"\"\"session scoped fixture\"\"\"\n '''\n )\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture(scope='function')\n def arg_same(arg_same):\n \"\"\"function scoped fixture\"\"\"\n def test_arg1(arg_same):\n pass\n '''\n )\n\n result = testdir.runpytest(mode, p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\n \"SETUP S arg_same*\",\n \"*SETUP F arg_same (fixtures used: arg_same)*\",\n \"*test_arg1 (fixtures used: arg_same)*\",\n \"*TEARDOWN F arg_same*\",\n \"TEARDOWN S arg_same*\",\n ]\n )\n\n\ndef test_show_fixtures_with_autouse(testdir, mode):\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture\n def arg_function():\n \"\"\"function scoped fixture\"\"\"\n @pytest.fixture(scope='session', autouse=True)\n def arg_session():\n \"\"\"session scoped fixture\"\"\"\n def test_arg1(arg_function):\n pass\n '''\n )\n\n result = testdir.runpytest(mode, p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\n \"SETUP S arg_session*\",\n \"*SETUP F arg_function*\",\n \"*test_arg1 (fixtures used: arg_function, arg_session)*\",\n ]\n )\n\n\ndef test_show_fixtures_with_parameters(testdir, mode):\n testdir.makeconftest(\n '''\n import pytest\n @pytest.fixture(scope='session', params=['foo', 'bar'])\n def arg_same():\n \"\"\"session scoped fixture\"\"\"\n '''\n )\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture(scope='function')\n def arg_other(arg_same):\n \"\"\"function scoped fixture\"\"\"\n def test_arg1(arg_other):\n pass\n '''\n )\n\n result = testdir.runpytest(mode, p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\n \"SETUP S arg_same?foo?\",\n \"TEARDOWN S arg_same?foo?\",\n \"SETUP S arg_same?bar?\",\n \"TEARDOWN S arg_same?bar?\",\n ]\n )\n\n\ndef test_show_fixtures_with_parameter_ids(testdir, mode):\n testdir.makeconftest(\n '''\n import pytest\n @pytest.fixture(\n scope='session', params=['foo', 'bar'], ids=['spam', 'ham'])\n def arg_same():\n \"\"\"session scoped fixture\"\"\"\n '''\n )\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture(scope='function')\n def arg_other(arg_same):\n \"\"\"function scoped fixture\"\"\"\n def test_arg1(arg_other):\n pass\n '''\n )\n\n result = testdir.runpytest(mode, p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\"SETUP S arg_same?spam?\", \"SETUP S arg_same?ham?\"]\n )\n\n\ndef test_show_fixtures_with_parameter_ids_function(testdir, mode):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(params=['foo', 'bar'], ids=lambda p: p.upper())\n def foobar():\n pass\n def test_foobar(foobar):\n pass\n \"\"\"\n )\n\n result = testdir.runpytest(mode, p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines([\"*SETUP F foobar?FOO?\", \"*SETUP F foobar?BAR?\"])\n\n\ndef test_dynamic_fixture_request(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture()\n def dynamically_requested_fixture():\n pass\n @pytest.fixture()\n def dependent_fixture(request):\n request.getfixturevalue('dynamically_requested_fixture')\n def test_dyn(dependent_fixture):\n pass\n \"\"\"\n )\n\n result = testdir.runpytest(\"--setup-only\", p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\n \"*SETUP F dynamically_requested_fixture\",\n \"*TEARDOWN F dynamically_requested_fixture\",\n ]\n )\n\n\ndef test_capturing(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest, sys\n @pytest.fixture()\n def one():\n sys.stdout.write('this should be captured')\n sys.stderr.write('this should also be captured')\n @pytest.fixture()\n def two(one):\n assert 0\n def test_capturing(two):\n pass\n \"\"\"\n )\n\n result = testdir.runpytest(\"--setup-only\", p)\n result.stdout.fnmatch_lines(\n [\"this should be captured\", \"this should also be captured\"]\n )\n\n\ndef test_show_fixtures_and_execute_test(testdir):\n \"\"\" Verifies that setups are shown and tests are executed. \"\"\"\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def arg():\n assert True\n def test_arg(arg):\n assert False\n \"\"\"\n )\n\n result = testdir.runpytest(\"--setup-show\", p)\n assert result.ret == 1\n\n result.stdout.fnmatch_lines(\n [\"*SETUP F arg*\", \"*test_arg (fixtures used: arg)F*\", \"*TEARDOWN F arg*\"]\n )\n"},{"col":0,"comment":"null","endLoc":7,"header":"@pytest.fixture(params=[\"--setup-only\", \"--setup-plan\", \"--setup-show\"], scope=\"module\")\ndef mode(request)","id":3153,"name":"mode","nodeType":"Function","startLoc":5,"text":"@pytest.fixture(params=[\"--setup-only\", \"--setup-plan\", \"--setup-show\"], scope=\"module\")\ndef mode(request):\n return request.param"},{"col":0,"comment":"null","endLoc":31,"header":"def test_show_only_active_fixtures(testdir, mode)","id":3154,"name":"test_show_only_active_fixtures","nodeType":"Function","startLoc":10,"text":"def test_show_only_active_fixtures(testdir, mode):\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture\n def _arg0():\n \"\"\"hidden arg0 fixture\"\"\"\n @pytest.fixture\n def arg1():\n \"\"\"arg1 docstring\"\"\"\n def test_arg1(arg1):\n pass\n '''\n )\n\n result = testdir.runpytest(mode, p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\"*SETUP F arg1*\", \"*test_arg1 (fixtures used: arg1)*\", \"*TEARDOWN F arg1*\"]\n )\n assert \"_arg0\" not in result.stdout.str()"},{"col":4,"comment":"\n Given an importhook, mark for rewrite any top-level\n modules or packages in the distribution package for\n all pytest plugins.\n ","endLoc":807,"header":"def _mark_plugins_for_rewrite(self, hook)","id":3155,"name":"_mark_plugins_for_rewrite","nodeType":"Function","startLoc":787,"text":"def _mark_plugins_for_rewrite(self, hook):\n \"\"\"\n Given an importhook, mark for rewrite any top-level\n modules or packages in the distribution package for\n all pytest plugins.\n \"\"\"\n self.pluginmanager.rewrite_hook = hook\n\n if os.environ.get(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\"):\n # We don't autoload from setuptools entry points, no need to continue.\n return\n\n package_files = (\n str(file)\n for dist in importlib_metadata.distributions()\n if any(ep.group == \"pytest11\" for ep in dist.entry_points)\n for file in dist.files or []\n )\n\n for name in _iter_rewritable_modules(package_files):\n hook.mark_rewrite(name)"},{"col":0,"comment":"null","endLoc":633,"header":"def _iter_rewritable_modules(package_files)","id":3156,"name":"_iter_rewritable_modules","nodeType":"Function","startLoc":624,"text":"def _iter_rewritable_modules(package_files):\n for fn in package_files:\n is_simple_module = \"/\" not in fn and fn.endswith(\".py\")\n is_package = fn.count(\"/\") == 1 and fn.endswith(\"__init__.py\")\n if is_simple_module:\n module_name, _ = os.path.splitext(fn)\n yield module_name\n elif is_package:\n package_name = os.path.dirname(fn)\n yield package_name"},{"col":0,"comment":"null","endLoc":60,"header":"def test_show_different_scopes(testdir, mode)","id":3157,"name":"test_show_different_scopes","nodeType":"Function","startLoc":34,"text":"def test_show_different_scopes(testdir, mode):\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture\n def arg_function():\n \"\"\"function scoped fixture\"\"\"\n @pytest.fixture(scope='session')\n def arg_session():\n \"\"\"session scoped fixture\"\"\"\n def test_arg1(arg_session, arg_function):\n pass\n '''\n )\n\n result = testdir.runpytest(mode, p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\n \"SETUP S arg_session*\",\n \"*SETUP F arg_function*\",\n \"*test_arg1 (fixtures used: arg_function, arg_session)*\",\n \"*TEARDOWN F arg_function*\",\n \"TEARDOWN S arg_session*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":241,"header":"def _should_rewrite(self, name, fn_pypath, state)","id":3159,"name":"_should_rewrite","nodeType":"Function","startLoc":222,"text":"def _should_rewrite(self, name, fn_pypath, state):\n # always rewrite conftest files\n fn = str(fn_pypath)\n if fn_pypath.basename == \"conftest.py\":\n state.trace(\"rewriting conftest file: %r\" % (fn,))\n return True\n\n if self.session is not None:\n if self.session.isinitpath(fn):\n state.trace(\"matched test file (was specified on cmdline): %r\" % (fn,))\n return True\n\n # modules not passed explicitly on the command line are only\n # rewritten if they match the naming convention for test files\n for pat in self.fnpats:\n if fn_pypath.fnmatch(pat):\n state.trace(\"matched test file %r\" % (fn,))\n return True\n\n return self._is_marked_for_rewrite(name, state)"},{"col":0,"comment":"null","endLoc":94,"header":"def test_show_nested_fixtures(testdir, mode)","id":3160,"name":"test_show_nested_fixtures","nodeType":"Function","startLoc":63,"text":"def test_show_nested_fixtures(testdir, mode):\n testdir.makeconftest(\n '''\n import pytest\n @pytest.fixture(scope='session')\n def arg_same():\n \"\"\"session scoped fixture\"\"\"\n '''\n )\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture(scope='function')\n def arg_same(arg_same):\n \"\"\"function scoped fixture\"\"\"\n def test_arg1(arg_same):\n pass\n '''\n )\n\n result = testdir.runpytest(mode, p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\n \"SETUP S arg_same*\",\n \"*SETUP F arg_same (fixtures used: arg_same)*\",\n \"*test_arg1 (fixtures used: arg_same)*\",\n \"*TEARDOWN F arg_same*\",\n \"TEARDOWN S arg_same*\",\n ]\n )"},{"col":0,"comment":"null","endLoc":1048,"header":"def _warn_about_missing_assertion(mode)","id":3161,"name":"_warn_about_missing_assertion","nodeType":"Function","startLoc":1033,"text":"def _warn_about_missing_assertion(mode):\n if not _assertion_supported():\n if mode == \"plain\":\n sys.stderr.write(\n \"WARNING: ASSERTIONS ARE NOT EXECUTED\"\n \" and FAILING TESTS WILL PASS. Are you\"\n \" using python -O?\"\n )\n else:\n sys.stderr.write(\n \"WARNING: assertions not in test modules or\"\n \" plugins will be ignored\"\n \" because assert statements are not executed \"\n \"by the underlying Python interpreter \"\n \"(are you using python -O?)\\n\"\n )"},{"col":0,"comment":"null","endLoc":1030,"header":"def _assertion_supported()","id":3162,"name":"_assertion_supported","nodeType":"Function","startLoc":1024,"text":"def _assertion_supported():\n try:\n assert False\n except AssertionError:\n return True\n else:\n return False"},{"col":0,"comment":"null","endLoc":121,"header":"def test_show_fixtures_with_autouse(testdir, mode)","id":3163,"name":"test_show_fixtures_with_autouse","nodeType":"Function","startLoc":97,"text":"def test_show_fixtures_with_autouse(testdir, mode):\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture\n def arg_function():\n \"\"\"function scoped fixture\"\"\"\n @pytest.fixture(scope='session', autouse=True)\n def arg_session():\n \"\"\"session scoped fixture\"\"\"\n def test_arg1(arg_function):\n pass\n '''\n )\n\n result = testdir.runpytest(mode, p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\n \"SETUP S arg_session*\",\n \"*SETUP F arg_function*\",\n \"*test_arg1 (fixtures used: arg_function, arg_session)*\",\n ]\n )"},{"col":0,"comment":"null","endLoc":154,"header":"def test_show_fixtures_with_parameters(testdir, mode)","id":3164,"name":"test_show_fixtures_with_parameters","nodeType":"Function","startLoc":124,"text":"def test_show_fixtures_with_parameters(testdir, mode):\n testdir.makeconftest(\n '''\n import pytest\n @pytest.fixture(scope='session', params=['foo', 'bar'])\n def arg_same():\n \"\"\"session scoped fixture\"\"\"\n '''\n )\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture(scope='function')\n def arg_other(arg_same):\n \"\"\"function scoped fixture\"\"\"\n def test_arg1(arg_other):\n pass\n '''\n )\n\n result = testdir.runpytest(mode, p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\n \"SETUP S arg_same?foo?\",\n \"TEARDOWN S arg_same?foo?\",\n \"SETUP S arg_same?bar?\",\n \"TEARDOWN S arg_same?bar?\",\n ]\n )"},{"col":0,"comment":"null","endLoc":183,"header":"def test_show_fixtures_with_parameter_ids(testdir, mode)","id":3165,"name":"test_show_fixtures_with_parameter_ids","nodeType":"Function","startLoc":157,"text":"def test_show_fixtures_with_parameter_ids(testdir, mode):\n testdir.makeconftest(\n '''\n import pytest\n @pytest.fixture(\n scope='session', params=['foo', 'bar'], ids=['spam', 'ham'])\n def arg_same():\n \"\"\"session scoped fixture\"\"\"\n '''\n )\n p = testdir.makepyfile(\n '''\n import pytest\n @pytest.fixture(scope='function')\n def arg_other(arg_same):\n \"\"\"function scoped fixture\"\"\"\n def test_arg1(arg_other):\n pass\n '''\n )\n\n result = testdir.runpytest(mode, p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\"SETUP S arg_same?spam?\", \"SETUP S arg_same?ham?\"]\n )"},{"fileName":"compat.py","filePath":"src/_pytest","id":3166,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"\npython version compatibility code\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport codecs\nimport functools\nimport inspect\nimport re\nimport sys\nfrom contextlib import contextmanager\n\nimport py\nimport six\nfrom six import text_type\n\nimport _pytest\nfrom _pytest._io.saferepr import saferepr\nfrom _pytest.outcomes import fail\nfrom _pytest.outcomes import TEST_OUTCOME\n\ntry:\n import enum\nexcept ImportError: # pragma: no cover\n # Only available in Python 3.4+ or as a backport\n enum = None\n\n_PY3 = sys.version_info > (3, 0)\n_PY2 = not _PY3\n\n\nif _PY3:\n from inspect import signature, Parameter as Parameter\nelse:\n from funcsigs import signature, Parameter as Parameter\n\nNOTSET = object()\n\nPY35 = sys.version_info[:2] >= (3, 5)\nPY36 = sys.version_info[:2] >= (3, 6)\nMODULE_NOT_FOUND_ERROR = \"ModuleNotFoundError\" if PY36 else \"ImportError\"\n\n\nif _PY3:\n from collections.abc import MutableMapping as MappingMixin\n from collections.abc import Iterable, Mapping, Sequence, Sized\nelse:\n # those raise DeprecationWarnings in Python >=3.7\n from collections import MutableMapping as MappingMixin # noqa\n from collections import Iterable, Mapping, Sequence, Sized # noqa\n\n\nif sys.version_info >= (3, 4):\n from importlib.util import spec_from_file_location\nelse:\n\n def spec_from_file_location(*_, **__):\n return None\n\n\ndef _format_args(func):\n return str(signature(func))\n\n\nisfunction = inspect.isfunction\nisclass = inspect.isclass\n# used to work around a python2 exception info leak\nexc_clear = getattr(sys, \"exc_clear\", lambda: None)\n# The type of re.compile objects is not exposed in Python.\nREGEX_TYPE = type(re.compile(\"\"))\n\n\ndef is_generator(func):\n genfunc = inspect.isgeneratorfunction(func)\n return genfunc and not iscoroutinefunction(func)\n\n\ndef iscoroutinefunction(func):\n \"\"\"Return True if func is a decorated coroutine function.\n\n Note: copied and modified from Python 3.5's builtin couroutines.py to avoid import asyncio directly,\n which in turns also initializes the \"logging\" module as side-effect (see issue #8).\n \"\"\"\n return getattr(func, \"_is_coroutine\", False) or (\n hasattr(inspect, \"iscoroutinefunction\") and inspect.iscoroutinefunction(func)\n )\n\n\ndef getlocation(function, curdir):\n function = get_real_func(function)\n fn = py.path.local(inspect.getfile(function))\n lineno = function.__code__.co_firstlineno\n if fn.relto(curdir):\n fn = fn.relto(curdir)\n return \"%s:%d\" % (fn, lineno + 1)\n\n\ndef num_mock_patch_args(function):\n \"\"\" return number of arguments used up by mock arguments (if any) \"\"\"\n patchings = getattr(function, \"patchings\", None)\n if not patchings:\n return 0\n mock_modules = [sys.modules.get(\"mock\"), sys.modules.get(\"unittest.mock\")]\n if any(mock_modules):\n sentinels = [m.DEFAULT for m in mock_modules if m is not None]\n return len(\n [p for p in patchings if not p.attribute_name and p.new in sentinels]\n )\n return len(patchings)\n\n\ndef getfuncargnames(function, is_method=False, cls=None):\n \"\"\"Returns the names of a function's mandatory arguments.\n\n This should return the names of all function arguments that:\n * Aren't bound to an instance or type as in instance or class methods.\n * Don't have default values.\n * Aren't bound with functools.partial.\n * Aren't replaced with mocks.\n\n The is_method and cls arguments indicate that the function should\n be treated as a bound method even though it's not unless, only in\n the case of cls, the function is a static method.\n\n @RonnyPfannschmidt: This function should be refactored when we\n revisit fixtures. The fixture mechanism should ask the node for\n the fixture names, and not try to obtain directly from the\n function object well after collection has occurred.\n\n \"\"\"\n # The parameters attribute of a Signature object contains an\n # ordered mapping of parameter names to Parameter instances. This\n # creates a tuple of the names of the parameters that don't have\n # defaults.\n try:\n parameters = signature(function).parameters\n except (ValueError, TypeError) as e:\n fail(\n \"Could not determine arguments of {!r}: {}\".format(function, e),\n pytrace=False,\n )\n\n arg_names = tuple(\n p.name\n for p in parameters.values()\n if (\n p.kind is Parameter.POSITIONAL_OR_KEYWORD\n or p.kind is Parameter.KEYWORD_ONLY\n )\n and p.default is Parameter.empty\n )\n # If this function should be treated as a bound method even though\n # it's passed as an unbound method or function, remove the first\n # parameter name.\n if is_method or (\n cls and not isinstance(cls.__dict__.get(function.__name__, None), staticmethod)\n ):\n arg_names = arg_names[1:]\n # Remove any names that will be replaced with mocks.\n if hasattr(function, \"__wrapped__\"):\n arg_names = arg_names[num_mock_patch_args(function) :]\n return arg_names\n\n\n@contextmanager\ndef dummy_context_manager():\n \"\"\"Context manager that does nothing, useful in situations where you might need an actual context manager or not\n depending on some condition. Using this allow to keep the same code\"\"\"\n yield\n\n\ndef get_default_arg_names(function):\n # Note: this code intentionally mirrors the code at the beginning of getfuncargnames,\n # to get the arguments which were excluded from its result because they had default values\n return tuple(\n p.name\n for p in signature(function).parameters.values()\n if p.kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY)\n and p.default is not Parameter.empty\n )\n\n\n_non_printable_ascii_translate_table = {\n i: u\"\\\\x{:02x}\".format(i) for i in range(128) if i not in range(32, 127)\n}\n_non_printable_ascii_translate_table.update(\n {ord(\"\\t\"): u\"\\\\t\", ord(\"\\r\"): u\"\\\\r\", ord(\"\\n\"): u\"\\\\n\"}\n)\n\n\ndef _translate_non_printable(s):\n return s.translate(_non_printable_ascii_translate_table)\n\n\nif _PY3:\n STRING_TYPES = bytes, str\n UNICODE_TYPES = six.text_type\n\n if PY35:\n\n def _bytes_to_ascii(val):\n return val.decode(\"ascii\", \"backslashreplace\")\n\n else:\n\n def _bytes_to_ascii(val):\n if val:\n # source: http://goo.gl/bGsnwC\n encoded_bytes, _ = codecs.escape_encode(val)\n return encoded_bytes.decode(\"ascii\")\n else:\n # empty bytes crashes codecs.escape_encode (#1087)\n return \"\"\n\n def ascii_escaped(val):\n \"\"\"If val is pure ascii, returns it as a str(). Otherwise, escapes\n bytes objects into a sequence of escaped bytes:\n\n b'\\xc3\\xb4\\xc5\\xd6' -> u'\\\\xc3\\\\xb4\\\\xc5\\\\xd6'\n\n and escapes unicode objects into a sequence of escaped unicode\n ids, e.g.:\n\n '4\\\\nV\\\\U00043efa\\\\x0eMXWB\\\\x1e\\\\u3028\\\\u15fd\\\\xcd\\\\U0007d944'\n\n note:\n the obvious \"v.decode('unicode-escape')\" will return\n valid utf-8 unicode if it finds them in bytes, but we\n want to return escaped bytes for any byte, even if they match\n a utf-8 string.\n\n \"\"\"\n if isinstance(val, bytes):\n ret = _bytes_to_ascii(val)\n else:\n ret = val.encode(\"unicode_escape\").decode(\"ascii\")\n return _translate_non_printable(ret)\n\n\nelse:\n STRING_TYPES = six.string_types\n UNICODE_TYPES = six.text_type\n\n def ascii_escaped(val):\n \"\"\"In py2 bytes and str are the same type, so return if it's a bytes\n object, return it unchanged if it is a full ascii string,\n otherwise escape it into its binary form.\n\n If it's a unicode string, change the unicode characters into\n unicode escapes.\n\n \"\"\"\n if isinstance(val, bytes):\n try:\n ret = val.decode(\"ascii\")\n except UnicodeDecodeError:\n ret = val.encode(\"string-escape\").decode(\"ascii\")\n else:\n ret = val.encode(\"unicode-escape\").decode(\"ascii\")\n return _translate_non_printable(ret)\n\n\nclass _PytestWrapper(object):\n \"\"\"Dummy wrapper around a function object for internal use only.\n\n Used to correctly unwrap the underlying function object\n when we are creating fixtures, because we wrap the function object ourselves with a decorator\n to issue warnings when the fixture function is called directly.\n \"\"\"\n\n def __init__(self, obj):\n self.obj = obj\n\n\ndef get_real_func(obj):\n \"\"\" gets the real function object of the (possibly) wrapped object by\n functools.wraps or functools.partial.\n \"\"\"\n start_obj = obj\n for i in range(100):\n # __pytest_wrapped__ is set by @pytest.fixture when wrapping the fixture function\n # to trigger a warning if it gets called directly instead of by pytest: we don't\n # want to unwrap further than this otherwise we lose useful wrappings like @mock.patch (#3774)\n new_obj = getattr(obj, \"__pytest_wrapped__\", None)\n if isinstance(new_obj, _PytestWrapper):\n obj = new_obj.obj\n break\n new_obj = getattr(obj, \"__wrapped__\", None)\n if new_obj is None:\n break\n obj = new_obj\n else:\n raise ValueError(\n (\"could not find real function of {start}\\nstopped at {current}\").format(\n start=saferepr(start_obj), current=saferepr(obj)\n )\n )\n if isinstance(obj, functools.partial):\n obj = obj.func\n return obj\n\n\ndef get_real_method(obj, holder):\n \"\"\"\n Attempts to obtain the real function object that might be wrapping ``obj``, while at the same time\n returning a bound method to ``holder`` if the original object was a bound method.\n \"\"\"\n try:\n is_method = hasattr(obj, \"__func__\")\n obj = get_real_func(obj)\n except Exception:\n return obj\n if is_method and hasattr(obj, \"__get__\") and callable(obj.__get__):\n obj = obj.__get__(holder)\n return obj\n\n\ndef getfslineno(obj):\n # xxx let decorators etc specify a sane ordering\n obj = get_real_func(obj)\n if hasattr(obj, \"place_as\"):\n obj = obj.place_as\n fslineno = _pytest._code.getfslineno(obj)\n assert isinstance(fslineno[1], int), obj\n return fslineno\n\n\ndef getimfunc(func):\n try:\n return func.__func__\n except AttributeError:\n return func\n\n\ndef safe_getattr(object, name, default):\n \"\"\" Like getattr but return default upon any Exception or any OutcomeException.\n\n Attribute access can potentially fail for 'evil' Python objects.\n See issue #214.\n It catches OutcomeException because of #2490 (issue #580), new outcomes are derived from BaseException\n instead of Exception (for more details check #2707)\n \"\"\"\n try:\n return getattr(object, name, default)\n except TEST_OUTCOME:\n return default\n\n\ndef safe_isclass(obj):\n \"\"\"Ignore any exception via isinstance on Python 3.\"\"\"\n try:\n return isclass(obj)\n except Exception:\n return False\n\n\ndef _is_unittest_unexpected_success_a_failure():\n \"\"\"Return if the test suite should fail if an @expectedFailure unittest test PASSES.\n\n From https://docs.python.org/3/library/unittest.html?highlight=unittest#unittest.TestResult.wasSuccessful:\n Changed in version 3.4: Returns False if there were any\n unexpectedSuccesses from tests marked with the expectedFailure() decorator.\n \"\"\"\n return sys.version_info >= (3, 4)\n\n\nif _PY3:\n\n def safe_str(v):\n \"\"\"returns v as string\"\"\"\n return str(v)\n\n\nelse:\n\n def safe_str(v):\n \"\"\"returns v as string, converting to utf-8 if necessary\"\"\"\n try:\n return str(v)\n except UnicodeError:\n if not isinstance(v, text_type):\n v = text_type(v)\n errors = \"replace\"\n return v.encode(\"utf-8\", errors)\n\n\nCOLLECT_FAKEMODULE_ATTRIBUTES = (\n \"Collector\",\n \"Module\",\n \"Function\",\n \"Instance\",\n \"Session\",\n \"Item\",\n \"Class\",\n \"File\",\n \"_fillfuncargs\",\n)\n\n\ndef _setup_collect_fakemodule():\n from types import ModuleType\n import pytest\n\n pytest.collect = ModuleType(\"pytest.collect\")\n pytest.collect.__all__ = [] # used for setns\n for attr in COLLECT_FAKEMODULE_ATTRIBUTES:\n setattr(pytest.collect, attr, getattr(pytest, attr))\n\n\nif _PY2:\n # Without this the test_dupfile_on_textio will fail, otherwise CaptureIO could directly inherit from StringIO.\n from py.io import TextIO\n\n class CaptureIO(TextIO):\n @property\n def encoding(self):\n return getattr(self, \"_encoding\", \"UTF-8\")\n\n\nelse:\n import io\n\n class CaptureIO(io.TextIOWrapper):\n def __init__(self):\n super(CaptureIO, self).__init__(\n io.BytesIO(), encoding=\"UTF-8\", newline=\"\", write_through=True\n )\n\n def getvalue(self):\n return self.buffer.getvalue().decode(\"UTF-8\")\n\n\nclass FuncargnamesCompatAttr(object):\n \"\"\" helper class so that Metafunc, Function and FixtureRequest\n don't need to each define the \"funcargnames\" compatibility attribute.\n \"\"\"\n\n @property\n def funcargnames(self):\n \"\"\" alias attribute for ``fixturenames`` for pre-2.3 compatibility\"\"\"\n return self.fixturenames\n\n\nif six.PY2:\n\n def lru_cache(*_, **__):\n def dec(fn):\n return fn\n\n return dec\n\n\nelse:\n from functools import lru_cache # noqa: F401\n"},{"col":4,"comment":"\n :rtype: LogCaptureHandler\n ","endLoc":273,"header":"@property\n def handler(self)","id":3168,"name":"handler","nodeType":"Function","startLoc":268,"text":"@property\n def handler(self):\n \"\"\"\n :rtype: LogCaptureHandler\n \"\"\"\n return self._item.catch_log_handler"},{"col":4,"comment":"\n Get the logging records for one of the possible test phases.\n\n :param str when:\n Which test phase to obtain the records from. Valid values are: \"setup\", \"call\" and \"teardown\".\n\n :rtype: List[logging.LogRecord]\n :return: the list of captured records at the given stage\n\n .. versionadded:: 3.4\n ","endLoc":291,"header":"def get_records(self, when)","id":3169,"name":"get_records","nodeType":"Function","startLoc":275,"text":"def get_records(self, when):\n \"\"\"\n Get the logging records for one of the possible test phases.\n\n :param str when:\n Which test phase to obtain the records from. Valid values are: \"setup\", \"call\" and \"teardown\".\n\n :rtype: List[logging.LogRecord]\n :return: the list of captured records at the given stage\n\n .. versionadded:: 3.4\n \"\"\"\n handler = self._item.catch_log_handlers.get(when)\n if handler:\n return handler.records\n else:\n return []"},{"col":0,"comment":"null","endLoc":201,"header":"def test_show_fixtures_with_parameter_ids_function(testdir, mode)","id":3170,"name":"test_show_fixtures_with_parameter_ids_function","nodeType":"Function","startLoc":186,"text":"def test_show_fixtures_with_parameter_ids_function(testdir, mode):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(params=['foo', 'bar'], ids=lambda p: p.upper())\n def foobar():\n pass\n def test_foobar(foobar):\n pass\n \"\"\"\n )\n\n result = testdir.runpytest(mode, p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines([\"*SETUP F foobar?FOO?\", \"*SETUP F foobar?BAR?\"])"},{"col":0,"comment":"null","endLoc":227,"header":"def test_dynamic_fixture_request(testdir)","id":3171,"name":"test_dynamic_fixture_request","nodeType":"Function","startLoc":204,"text":"def test_dynamic_fixture_request(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture()\n def dynamically_requested_fixture():\n pass\n @pytest.fixture()\n def dependent_fixture(request):\n request.getfixturevalue('dynamically_requested_fixture')\n def test_dyn(dependent_fixture):\n pass\n \"\"\"\n )\n\n result = testdir.runpytest(\"--setup-only\", p)\n assert result.ret == 0\n\n result.stdout.fnmatch_lines(\n [\n \"*SETUP F dynamically_requested_fixture\",\n \"*TEARDOWN F dynamically_requested_fixture\",\n ]\n )"},{"col":0,"comment":"null","endLoc":249,"header":"def test_capturing(testdir)","id":3172,"name":"test_capturing","nodeType":"Function","startLoc":230,"text":"def test_capturing(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest, sys\n @pytest.fixture()\n def one():\n sys.stdout.write('this should be captured')\n sys.stderr.write('this should also be captured')\n @pytest.fixture()\n def two(one):\n assert 0\n def test_capturing(two):\n pass\n \"\"\"\n )\n\n result = testdir.runpytest(\"--setup-only\", p)\n result.stdout.fnmatch_lines(\n [\"this should be captured\", \"this should also be captured\"]\n )"},{"className":"Parameter","col":0,"comment":"null","endLoc":406,"id":3173,"nodeType":"Class","startLoc":377,"text":"class Parameter:\n def __init__(self, name: str, kind: _ParameterKind, *, default: Any = ..., annotation: Any = ...) -> None: ...\n empty = _empty\n\n POSITIONAL_ONLY: ClassVar[Literal[_ParameterKind.POSITIONAL_ONLY]]\n POSITIONAL_OR_KEYWORD: ClassVar[Literal[_ParameterKind.POSITIONAL_OR_KEYWORD]]\n VAR_POSITIONAL: ClassVar[Literal[_ParameterKind.VAR_POSITIONAL]]\n KEYWORD_ONLY: ClassVar[Literal[_ParameterKind.KEYWORD_ONLY]]\n VAR_KEYWORD: ClassVar[Literal[_ParameterKind.VAR_KEYWORD]]\n @property\n def name(self) -> str: ...\n @property\n def default(self) -> Any: ...\n @property\n def kind(self) -> _ParameterKind: ...\n @property\n def annotation(self) -> Any: ...\n def replace(\n self,\n *,\n name: str | type[_void] = ...,\n kind: _ParameterKind | type[_void] = ...,\n default: Any = ...,\n annotation: Any = ...,\n ) -> Self: ...\n if sys.version_info >= (3, 13):\n __replace__ = replace\n\n def __eq__(self, other: object) -> bool: ...\n def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":378,"header":"def __init__(self, name: str, kind: _ParameterKind, *, default: Any = ..., annotation: Any = ...) -> None","id":3174,"name":"__init__","nodeType":"Function","startLoc":378,"text":"def __init__(self, name: str, kind: _ParameterKind, *, default: Any = ..., annotation: Any = ...) -> None: ..."},{"col":0,"comment":" Verifies that setups are shown and tests are executed. ","endLoc":270,"header":"def test_show_fixtures_and_execute_test(testdir)","id":3175,"name":"test_show_fixtures_and_execute_test","nodeType":"Function","startLoc":252,"text":"def test_show_fixtures_and_execute_test(testdir):\n \"\"\" Verifies that setups are shown and tests are executed. \"\"\"\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def arg():\n assert True\n def test_arg(arg):\n assert False\n \"\"\"\n )\n\n result = testdir.runpytest(\"--setup-show\", p)\n assert result.ret == 1\n\n result.stdout.fnmatch_lines(\n [\"*SETUP F arg*\", \"*test_arg (fixtures used: arg)F*\", \"*TEARDOWN F arg*\"]\n )"},{"col":4,"comment":"null","endLoc":387,"header":"@property\n def name(self) -> str","id":3176,"name":"name","nodeType":"Function","startLoc":386,"text":"@property\n def name(self) -> str: ..."},{"col":4,"comment":"null","endLoc":389,"header":"@property\n def default(self) -> Any","id":3177,"name":"default","nodeType":"Function","startLoc":388,"text":"@property\n def default(self) -> Any: ..."},{"col":4,"comment":"null","endLoc":391,"header":"@property\n def kind(self) -> _ParameterKind","id":3178,"name":"kind","nodeType":"Function","startLoc":390,"text":"@property\n def kind(self) -> _ParameterKind: ..."},{"col":4,"comment":"null","endLoc":393,"header":"@property\n def annotation(self) -> Any","id":3179,"name":"annotation","nodeType":"Function","startLoc":392,"text":"@property\n def annotation(self) -> Any: ..."},{"col":4,"comment":"null","endLoc":401,"header":"def replace(\n self,\n *,\n name: str | type[_void] = ...,\n kind: _ParameterKind | type[_void] = ...,\n default: Any = ...,\n annotation: Any = ...,\n ) -> Self","id":3180,"name":"replace","nodeType":"Function","startLoc":394,"text":"def replace(\n self,\n *,\n name: str | type[_void] = ...,\n kind: _ParameterKind | type[_void] = ...,\n default: Any = ...,\n annotation: Any = ...,\n ) -> Self: ..."},{"col":4,"comment":"Returns the formatted log text.","endLoc":296,"header":"@property\n def text(self)","id":3181,"name":"text","nodeType":"Function","startLoc":293,"text":"@property\n def text(self):\n \"\"\"Returns the formatted log text.\"\"\"\n return _remove_ansi_escape_sequences(self.handler.stream.getvalue())"},{"col":4,"comment":"null","endLoc":405,"header":"def __eq__(self, other: object) -> bool","id":3182,"name":"__eq__","nodeType":"Function","startLoc":405,"text":"def __eq__(self, other: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":406,"header":"def __hash__(self) -> int","id":3183,"name":"__hash__","nodeType":"Function","startLoc":406,"text":"def __hash__(self) -> int: ..."},{"attributeType":"_empty","col":4,"comment":"null","endLoc":379,"id":3184,"name":"empty","nodeType":"Attribute","startLoc":379,"text":"empty"},{"id":3185,"name":"release-3.2.5.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.2.5\n=======================================\n\npytest 3.2.5 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n\n\nHappy testing,\nThe pytest Development Team\n"},{"id":3186,"name":"nonpython.rst","nodeType":"TextFile","path":"doc/en/example","text":"\n.. _`non-python tests`:\n\nWorking with non-python tests\n====================================================\n\n.. _`yaml plugin`:\n\nA basic example for specifying tests in Yaml files\n--------------------------------------------------------------\n\n.. _`pytest-yamlwsgi`: http://bitbucket.org/aafshar/pytest-yamlwsgi/src/tip/pytest_yamlwsgi.py\n.. _`PyYAML`: https://pypi.org/project/PyYAML/\n\nHere is an example ``conftest.py`` (extracted from Ali Afshnars special purpose `pytest-yamlwsgi`_ plugin). This ``conftest.py`` will collect ``test*.yml`` files and will execute the yaml-formatted content as custom tests:\n\n.. include:: nonpython/conftest.py\n :literal:\n\nYou can create a simple example file:\n\n.. include:: nonpython/test_simple.yml\n :literal:\n\nand if you installed `PyYAML`_ or a compatible YAML-parser you can\nnow execute the test specification:\n\n.. code-block:: pytest\n\n nonpython $ pytest test_simple.yml\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR/nonpython\n collected 2 items\n\n test_simple.yml F. [100%]\n\n ================================= FAILURES =================================\n ______________________________ usecase: hello ______________________________\n usecase execution failed\n spec failed: 'some': 'other'\n no further details known at this point.\n ==================== 1 failed, 1 passed in 0.12 seconds ====================\n\n.. regendoc:wipe\n\nYou get one dot for the passing ``sub1: sub1`` check and one failure.\nObviously in the above ``conftest.py`` you'll want to implement a more\ninteresting interpretation of the yaml-values. You can easily write\nyour own domain specific testing language this way.\n\n.. note::\n\n ``repr_failure(excinfo)`` is called for representing test failures.\n If you create custom collection nodes you can return an error\n representation string of your choice. It\n will be reported as a (red) string.\n\n``reportinfo()`` is used for representing the test location and is also\nconsulted when reporting in ``verbose`` mode:\n\n.. code-block:: pytest\n\n nonpython $ pytest -v\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR/nonpython\n collecting ... collected 2 items\n\n test_simple.yml::hello FAILED [ 50%]\n test_simple.yml::ok PASSED [100%]\n\n ================================= FAILURES =================================\n ______________________________ usecase: hello ______________________________\n usecase execution failed\n spec failed: 'some': 'other'\n no further details known at this point.\n ==================== 1 failed, 1 passed in 0.12 seconds ====================\n\n.. regendoc:wipe\n\nWhile developing your custom test collection and execution it's also\ninteresting to just look at the collection tree:\n\n.. code-block:: pytest\n\n nonpython $ pytest --collect-only\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR/nonpython\n collected 2 items\n \n \n \n \n\n ======================= no tests ran in 0.12 seconds =======================\n"},{"col":4,"comment":"parses and returns a namespace object with known arguments at this\n point.\n ","endLoc":110,"header":"def parse_known_args(self, args, namespace=None)","id":3187,"name":"parse_known_args","nodeType":"Function","startLoc":106,"text":"def parse_known_args(self, args, namespace=None):\n \"\"\"parses and returns a namespace object with known arguments at this\n point.\n \"\"\"\n return self.parse_known_and_unknown_args(args, namespace=namespace)[0]"},{"fileName":"conftest.py","filePath":"testing","id":3188,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport sys\n\nimport pytest\n\nif sys.gettrace():\n\n @pytest.fixture(autouse=True)\n def restore_tracing():\n \"\"\"Restore tracing function (when run with Coverage.py).\n\n https://bugs.python.org/issue37011\n \"\"\"\n orig_trace = sys.gettrace()\n yield\n if sys.gettrace() != orig_trace:\n sys.settrace(orig_trace)\n\n\n@pytest.hookimpl(hookwrapper=True, tryfirst=True)\ndef pytest_collection_modifyitems(config, items):\n \"\"\"Prefer faster tests.\n\n Use a hookwrapper to do this in the beginning, so e.g. --ff still works\n correctly.\n \"\"\"\n fast_items = []\n slow_items = []\n slowest_items = []\n neutral_items = []\n\n spawn_names = {\"spawn_pytest\", \"spawn\"}\n\n for item in items:\n try:\n fixtures = item.fixturenames\n except AttributeError:\n # doctest at least\n # (https://github.com/pytest-dev/pytest/issues/5070)\n neutral_items.append(item)\n else:\n if \"testdir\" in fixtures:\n if spawn_names.intersection(item.function.__code__.co_names):\n item.add_marker(pytest.mark.uses_pexpect)\n slowest_items.append(item)\n else:\n slow_items.append(item)\n item.add_marker(pytest.mark.slow)\n else:\n marker = item.get_closest_marker(\"slow\")\n if marker:\n slowest_items.append(item)\n else:\n fast_items.append(item)\n\n items[:] = fast_items + neutral_items + slow_items + slowest_items\n\n yield\n"},{"col":4,"comment":"Restore tracing function (when run with Coverage.py).\n\n https://bugs.python.org/issue37011\n ","endLoc":17,"header":"@pytest.fixture(autouse=True)\n def restore_tracing()","id":3189,"name":"restore_tracing","nodeType":"Function","startLoc":8,"text":"@pytest.fixture(autouse=True)\n def restore_tracing():\n \"\"\"Restore tracing function (when run with Coverage.py).\n\n https://bugs.python.org/issue37011\n \"\"\"\n orig_trace = sys.gettrace()\n yield\n if sys.gettrace() != orig_trace:\n sys.settrace(orig_trace)"},{"col":4,"comment":"Returns the list of log records.","endLoc":301,"header":"@property\n def records(self)","id":3190,"name":"records","nodeType":"Function","startLoc":298,"text":"@property\n def records(self):\n \"\"\"Returns the list of log records.\"\"\"\n return self.handler.records"},{"col":4,"comment":"Returns a list of a stripped down version of log records intended\n for use in assertion comparison.\n\n The format of the tuple is:\n\n (logger_name, log_level, message)\n ","endLoc":312,"header":"@property\n def record_tuples(self)","id":3191,"name":"record_tuples","nodeType":"Function","startLoc":303,"text":"@property\n def record_tuples(self):\n \"\"\"Returns a list of a stripped down version of log records intended\n for use in assertion comparison.\n\n The format of the tuple is:\n\n (logger_name, log_level, message)\n \"\"\"\n return [(r.name, r.levelno, r.getMessage()) for r in self.records]"},{"attributeType":"null","col":4,"comment":"null","endLoc":381,"id":3192,"name":"POSITIONAL_ONLY","nodeType":"Attribute","startLoc":381,"text":"POSITIONAL_ONLY"},{"col":4,"comment":"null","endLoc":104,"header":"def parse_setoption(self, args, option, namespace=None)","id":3193,"name":"parse_setoption","nodeType":"Function","startLoc":100,"text":"def parse_setoption(self, args, option, namespace=None):\n parsedoption = self.parse(args, namespace=namespace)\n for name, value in parsedoption.__dict__.items():\n setattr(option, name, value)\n return getattr(parsedoption, FILE_OR_DIR)"},{"col":4,"comment":"null","endLoc":81,"header":"def parse(self, args, namespace=None)","id":3194,"name":"parse","nodeType":"Function","startLoc":75,"text":"def parse(self, args, namespace=None):\n from _pytest._argcomplete import try_argcomplete\n\n self.optparser = self._getparser()\n try_argcomplete(self.optparser)\n args = [str(x) if isinstance(x, py.path.local) else x for x in args]\n return self.optparser.parse_args(args, namespace=namespace)"},{"col":4,"comment":"null","endLoc":116,"header":"def test_log_test_outcomes(self, testdir)","id":3195,"name":"test_log_test_outcomes","nodeType":"Function","startLoc":83,"text":"def test_log_test_outcomes(self, testdir):\n mod = testdir.makepyfile(\n test_mod=\"\"\"\n import pytest\n def test_pass(): pass\n def test_skip(): pytest.skip(\"hello\")\n def test_fail(): raise ValueError(\"FAIL\")\n\n @pytest.mark.xfail\n def test_xfail(): raise ValueError(\"XFAIL\")\n @pytest.mark.xfail\n def test_xpass(): pass\n\n \"\"\"\n )\n lines = self.getresultlog(testdir, mod)\n assert len(lines) >= 3\n assert lines[0].startswith(\". \")\n assert lines[0].endswith(\"test_pass\")\n assert lines[1].startswith(\"s \"), lines[1]\n assert lines[1].endswith(\"test_skip\")\n assert lines[2].find(\"hello\") != -1\n\n assert lines[3].startswith(\"F \")\n assert lines[3].endswith(\"test_fail\")\n tb = \"\".join(lines[4:8])\n assert tb.find('raise ValueError(\"FAIL\")') != -1\n\n assert lines[8].startswith(\"x \")\n tb = \"\".join(lines[8:14])\n assert tb.find('raise ValueError(\"XFAIL\")') != -1\n\n assert lines[14].startswith(\"X \")\n assert len(lines) == 15"},{"col":4,"comment":"null","endLoc":108,"header":"def try_argcomplete(parser)","id":3197,"name":"try_argcomplete","nodeType":"Function","startLoc":107,"text":"def try_argcomplete(parser):\n pass"},{"col":4,"comment":"null","endLoc":102,"header":"def try_argcomplete(parser)","id":3198,"name":"try_argcomplete","nodeType":"Function","startLoc":101,"text":"def try_argcomplete(parser):\n argcomplete.autocomplete(parser, always_complete_options=False)"},{"attributeType":"null","col":4,"comment":"null","endLoc":382,"id":3199,"name":"POSITIONAL_OR_KEYWORD","nodeType":"Attribute","startLoc":382,"text":"POSITIONAL_OR_KEYWORD"},{"attributeType":"null","col":4,"comment":"null","endLoc":383,"id":3200,"name":"VAR_POSITIONAL","nodeType":"Attribute","startLoc":383,"text":"VAR_POSITIONAL"},{"attributeType":"null","col":4,"comment":"null","endLoc":384,"id":3201,"name":"KEYWORD_ONLY","nodeType":"Attribute","startLoc":384,"text":"KEYWORD_ONLY"},{"attributeType":"null","col":4,"comment":"null","endLoc":385,"id":3202,"name":"VAR_KEYWORD","nodeType":"Attribute","startLoc":385,"text":"VAR_KEYWORD"},{"col":0,"comment":"Prefer faster tests.\n\n Use a hookwrapper to do this in the beginning, so e.g. --ff still works\n correctly.\n ","endLoc":58,"header":"@pytest.hookimpl(hookwrapper=True, tryfirst=True)\ndef pytest_collection_modifyitems(config, items)","id":3204,"name":"pytest_collection_modifyitems","nodeType":"Function","startLoc":20,"text":"@pytest.hookimpl(hookwrapper=True, tryfirst=True)\ndef pytest_collection_modifyitems(config, items):\n \"\"\"Prefer faster tests.\n\n Use a hookwrapper to do this in the beginning, so e.g. --ff still works\n correctly.\n \"\"\"\n fast_items = []\n slow_items = []\n slowest_items = []\n neutral_items = []\n\n spawn_names = {\"spawn_pytest\", \"spawn\"}\n\n for item in items:\n try:\n fixtures = item.fixturenames\n except AttributeError:\n # doctest at least\n # (https://github.com/pytest-dev/pytest/issues/5070)\n neutral_items.append(item)\n else:\n if \"testdir\" in fixtures:\n if spawn_names.intersection(item.function.__code__.co_names):\n item.add_marker(pytest.mark.uses_pexpect)\n slowest_items.append(item)\n else:\n slow_items.append(item)\n item.add_marker(pytest.mark.slow)\n else:\n marker = item.get_closest_marker(\"slow\")\n if marker:\n slowest_items.append(item)\n else:\n fast_items.append(item)\n\n items[:] = fast_items + neutral_items + slow_items + slowest_items\n\n yield"},{"className":"Sequence","col":0,"comment":"null","endLoc":577,"id":3205,"nodeType":"Class","startLoc":565,"text":"class Sequence(Collection[_T_co], Reversible[_T_co]):\n @overload\n @abstractmethod\n def __getitem__(self, index: int) -> _T_co: ...\n @overload\n @abstractmethod\n def __getitem__(self, index: slice) -> Sequence[_T_co]: ...\n # Mixin methods\n def index(self, value: Any, start: int = 0, stop: int = ...) -> int: ...\n def count(self, value: Any) -> int: ...\n def __contains__(self, value: object) -> bool: ...\n def __iter__(self) -> Iterator[_T_co]: ...\n def __reversed__(self) -> Iterator[_T_co]: ..."},{"col":4,"comment":"null","endLoc":568,"header":"@overload\n @abstractmethod\n def __getitem__(self, index: int) -> _T_co","id":3206,"name":"__getitem__","nodeType":"Function","startLoc":566,"text":"@overload\n @abstractmethod\n def __getitem__(self, index: int) -> _T_co: ..."},{"col":4,"comment":"null","endLoc":571,"header":"@overload\n @abstractmethod\n def __getitem__(self, index: slice) -> Sequence[_T_co]","id":3207,"name":"__getitem__","nodeType":"Function","startLoc":569,"text":"@overload\n @abstractmethod\n def __getitem__(self, index: slice) -> Sequence[_T_co]: ..."},{"col":4,"comment":"null","endLoc":573,"header":"def index(self, value: Any, start: int = 0, stop: int = ...) -> int","id":3208,"name":"index","nodeType":"Function","startLoc":573,"text":"def index(self, value: Any, start: int = 0, stop: int = ...) -> int: ..."},{"col":4,"comment":"null","endLoc":574,"header":"def count(self, value: Any) -> int","id":3209,"name":"count","nodeType":"Function","startLoc":574,"text":"def count(self, value: Any) -> int: ..."},{"col":4,"comment":"null","endLoc":575,"header":"def __contains__(self, value: object) -> bool","id":3210,"name":"__contains__","nodeType":"Function","startLoc":575,"text":"def __contains__(self, value: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":576,"header":"def __iter__(self) -> Iterator[_T_co]","id":3211,"name":"__iter__","nodeType":"Function","startLoc":576,"text":"def __iter__(self) -> Iterator[_T_co]: ..."},{"col":4,"comment":"null","endLoc":577,"header":"def __reversed__(self) -> Iterator[_T_co]","id":3212,"name":"__reversed__","nodeType":"Function","startLoc":577,"text":"def __reversed__(self) -> Iterator[_T_co]: ..."},{"col":0,"comment":"null","endLoc":303,"header":"def get_optionflags(parent)","id":3213,"name":"get_optionflags","nodeType":"Function","startLoc":297,"text":"def get_optionflags(parent):\n optionflags_str = parent.config.getini(\"doctest_optionflags\")\n flag_lookup_table = _get_flag_lookup()\n flag_acc = 0\n for flag in optionflags_str:\n flag_acc |= flag_lookup_table[flag]\n return flag_acc"},{"col":0,"comment":"null","endLoc":294,"header":"def _get_flag_lookup()","id":3214,"name":"_get_flag_lookup","nodeType":"Function","startLoc":282,"text":"def _get_flag_lookup():\n import doctest\n\n return dict(\n DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1,\n DONT_ACCEPT_BLANKLINE=doctest.DONT_ACCEPT_BLANKLINE,\n NORMALIZE_WHITESPACE=doctest.NORMALIZE_WHITESPACE,\n ELLIPSIS=doctest.ELLIPSIS,\n IGNORE_EXCEPTION_DETAIL=doctest.IGNORE_EXCEPTION_DETAIL,\n COMPARISON_FLAGS=doctest.COMPARISON_FLAGS,\n ALLOW_UNICODE=_get_allow_unicode_flag(),\n ALLOW_BYTES=_get_allow_bytes_flag(),\n )"},{"col":4,"comment":"null","endLoc":370,"header":"def test_preserve_container(self, monkeypatch)","id":3215,"name":"test_preserve_container","nodeType":"Function","startLoc":361,"text":"def test_preserve_container(self, monkeypatch):\n original = dict(sys.modules)\n assert self.key not in original\n replacement = dict(sys.modules)\n replacement[self.key] = \"life of brian\"\n snapshot = SysModulesSnapshot()\n monkeypatch.setattr(sys, \"modules\", replacement)\n snapshot.restore()\n assert sys.modules is replacement\n assert sys.modules == original"},{"col":0,"comment":"null","endLoc":35,"header":"def spec_from_file_location(\n name: str,\n location: StrOrBytesPath | None = None,\n *,\n loader: LoaderProtocol | None = None,\n submodule_search_locations: list[str] | None = ...,\n) -> importlib.machinery.ModuleSpec | None","id":3216,"name":"spec_from_file_location","nodeType":"Function","startLoc":29,"text":"def spec_from_file_location(\n name: str,\n location: StrOrBytesPath | None = None,\n *,\n loader: LoaderProtocol | None = None,\n submodule_search_locations: list[str] | None = ...,\n) -> importlib.machinery.ModuleSpec | None: ..."},{"className":"CaptureIO","col":4,"comment":"null","endLoc":420,"id":3218,"nodeType":"Class","startLoc":417,"text":"class CaptureIO(TextIO):\n @property\n def encoding(self):\n return getattr(self, \"_encoding\", \"UTF-8\")"},{"col":0,"comment":"Possibly read a pytest pyc containing rewritten code.\n\n Return rewritten code if successful or None if not.\n ","endLoc":448,"header":"def _read_pyc(source, pyc, trace=lambda x: None)","id":3219,"name":"_read_pyc","nodeType":"Function","startLoc":415,"text":"def _read_pyc(source, pyc, trace=lambda x: None):\n \"\"\"Possibly read a pytest pyc containing rewritten code.\n\n Return rewritten code if successful or None if not.\n \"\"\"\n try:\n fp = open(pyc, \"rb\")\n except IOError:\n return None\n with fp:\n try:\n mtime = int(source.mtime())\n size = source.size()\n data = fp.read(12)\n except EnvironmentError as e:\n trace(\"_read_pyc(%s): EnvironmentError %s\" % (source, e))\n return None\n # Check for invalid or out of date pyc file.\n if (\n len(data) != 12\n or data[:4] != imp.get_magic()\n or struct.unpack(\" None: ...\n # Equals the \"buffer\" argument passed in to the constructor.\n @property\n def buffer(self) -> _BufferT_co: ... # type: ignore[override]\n @property\n def closed(self) -> bool: ...\n @property\n def line_buffering(self) -> bool: ...\n @property\n def write_through(self) -> bool: ...\n def reconfigure(\n self,\n *,\n encoding: str | None = None,\n errors: str | None = None,\n newline: str | None = None,\n line_buffering: bool | None = None,\n write_through: bool | None = None,\n ) -> None: ...\n # These are inherited from TextIOBase, but must exist in the stub to satisfy mypy.\n def __enter__(self) -> Self: ...\n def __iter__(self) -> Iterator[str]: ... # type: ignore[override]\n def __next__(self) -> str: ... # type: ignore[override]\n def writelines(self, lines: Iterable[str], /) -> None: ... # type: ignore[override]\n def readline(self, size: int = -1, /) -> str: ... # type: ignore[override]\n def readlines(self, hint: int = -1, /) -> list[str]: ... # type: ignore[override]\n # Equals the \"buffer\" argument passed in to the constructor.\n def detach(self) -> _BufferT_co: ... # type: ignore[override]\n # TextIOWrapper's version of seek only supports a limited subset of\n # operations.\n def seek(self, cookie: int, whence: int = 0, /) -> int: ..."},{"col":0,"comment":"null","endLoc":287,"header":"def get_statement_startend2(lineno, node)","id":3231,"name":"get_statement_startend2","nodeType":"Function","startLoc":266,"text":"def get_statement_startend2(lineno, node):\n import ast\n\n # flatten all statements and except handlers into one lineno-list\n # AST's line numbers start indexing at 1\n values = []\n for x in ast.walk(node):\n if isinstance(x, (ast.stmt, ast.ExceptHandler)):\n values.append(x.lineno - 1)\n for name in (\"finalbody\", \"orelse\"):\n val = getattr(x, name, None)\n if val:\n # treat the finally/orelse part as its own statement\n values.append(val[0].lineno - 1 - 1)\n values.sort()\n insert_index = bisect_right(values, lineno)\n start = values[insert_index - 1]\n if insert_index >= len(values):\n end = None\n else:\n end = values[insert_index]\n return start, end"},{"col":4,"comment":"Context manager that sets the level for capturing of logs. After the end of the 'with' statement the\n level is restored to its original value.\n\n :param int level: the logger to level.\n :param str logger: the logger to update the level. If not given, the root logger level is updated.\n ","endLoc":365,"header":"@contextmanager\n def at_level(self, level, logger=None)","id":3232,"name":"at_level","nodeType":"Function","startLoc":351,"text":"@contextmanager\n def at_level(self, level, logger=None):\n \"\"\"Context manager that sets the level for capturing of logs. After the end of the 'with' statement the\n level is restored to its original value.\n\n :param int level: the logger to level.\n :param str logger: the logger to update the level. If not given, the root logger level is updated.\n \"\"\"\n logger = logging.getLogger(logger)\n orig_level = logger.level\n logger.setLevel(level)\n try:\n yield\n finally:\n logger.setLevel(orig_level)"},{"attributeType":"null","col":4,"comment":"null","endLoc":160,"id":3233,"name":"name","nodeType":"Attribute","startLoc":160,"text":"name"},{"attributeType":"null","col":4,"comment":"null","endLoc":162,"id":3234,"name":"args","nodeType":"Attribute","startLoc":162,"text":"args"},{"attributeType":"null","col":4,"comment":"null","endLoc":164,"id":3235,"name":"kwargs","nodeType":"Attribute","startLoc":164,"text":"kwargs"},{"className":"MarkDecorator","col":0,"comment":" A decorator for test functions and test classes. When applied\n it will create :class:`MarkInfo` objects which may be\n :ref:`retrieved by hooks as item keywords `.\n MarkDecorator instances are often created like this::\n\n mark1 = pytest.mark.NAME # simple MarkDecorator\n mark2 = pytest.mark.NAME(name1=value) # parametrized MarkDecorator\n\n and can then be applied as decorators to test functions::\n\n @mark2\n def test_function():\n pass\n\n When a MarkDecorator instance is called it does the following:\n 1. If called with a single class as its only positional argument and no\n additional keyword arguments, it attaches itself to the class so it\n gets applied automatically to all test cases found in that class.\n 2. If called with a single function as its only positional argument and\n no additional keyword arguments, it attaches a MarkInfo object to the\n function, containing all the arguments already stored internally in\n the MarkDecorator.\n 3. When called in any other case, it performs a 'fake construction' call,\n i.e. it returns a new MarkDecorator instance with the original\n MarkDecorator's content updated with the arguments passed to this\n call.\n\n Note: The rules above prevent MarkDecorator objects from storing only a\n single function or class reference as their positional argument with no\n additional keyword or positional arguments.\n\n ","endLoc":251,"id":3236,"nodeType":"Class","startLoc":180,"text":"@attr.s\nclass MarkDecorator(object):\n \"\"\" A decorator for test functions and test classes. When applied\n it will create :class:`MarkInfo` objects which may be\n :ref:`retrieved by hooks as item keywords `.\n MarkDecorator instances are often created like this::\n\n mark1 = pytest.mark.NAME # simple MarkDecorator\n mark2 = pytest.mark.NAME(name1=value) # parametrized MarkDecorator\n\n and can then be applied as decorators to test functions::\n\n @mark2\n def test_function():\n pass\n\n When a MarkDecorator instance is called it does the following:\n 1. If called with a single class as its only positional argument and no\n additional keyword arguments, it attaches itself to the class so it\n gets applied automatically to all test cases found in that class.\n 2. If called with a single function as its only positional argument and\n no additional keyword arguments, it attaches a MarkInfo object to the\n function, containing all the arguments already stored internally in\n the MarkDecorator.\n 3. When called in any other case, it performs a 'fake construction' call,\n i.e. it returns a new MarkDecorator instance with the original\n MarkDecorator's content updated with the arguments passed to this\n call.\n\n Note: The rules above prevent MarkDecorator objects from storing only a\n single function or class reference as their positional argument with no\n additional keyword or positional arguments.\n\n \"\"\"\n\n mark = attr.ib(validator=attr.validators.instance_of(Mark))\n\n name = alias(\"mark.name\")\n args = alias(\"mark.args\")\n kwargs = alias(\"mark.kwargs\")\n\n @property\n def markname(self):\n return self.name # for backward-compat (2.4.1 had this attr)\n\n def __eq__(self, other):\n return self.mark == other.mark if isinstance(other, MarkDecorator) else False\n\n def __repr__(self):\n return \"\" % (self.mark,)\n\n def with_args(self, *args, **kwargs):\n \"\"\" return a MarkDecorator with extra arguments added\n\n unlike call this can be used even if the sole argument is a callable/class\n\n :return: MarkDecorator\n \"\"\"\n\n mark = Mark(self.name, args, kwargs)\n return self.__class__(self.mark.combined_with(mark))\n\n def __call__(self, *args, **kwargs):\n \"\"\" if passed a single callable argument: decorate it with mark info.\n otherwise add *args/**kwargs in-place to mark information. \"\"\"\n if args and not kwargs:\n func = args[0]\n is_class = inspect.isclass(func)\n if len(args) == 1 and (istestfunc(func) or is_class):\n store_mark(func, self.mark)\n return func\n return self.with_args(*args, **kwargs)"},{"col":4,"comment":"null","endLoc":223,"header":"@property\n def markname(self)","id":3237,"name":"markname","nodeType":"Function","startLoc":221,"text":"@property\n def markname(self):\n return self.name # for backward-compat (2.4.1 had this attr)"},{"col":4,"comment":"null","endLoc":226,"header":"def __eq__(self, other)","id":3238,"name":"__eq__","nodeType":"Function","startLoc":225,"text":"def __eq__(self, other):\n return self.mark == other.mark if isinstance(other, MarkDecorator) else False"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":256,"id":3239,"name":"_initial_log_levels","nodeType":"Attribute","startLoc":256,"text":"self._initial_log_levels"},{"attributeType":"null","col":8,"comment":"null","endLoc":254,"id":3240,"name":"_item","nodeType":"Attribute","startLoc":254,"text":"self._item"},{"className":"LoggingPlugin","col":0,"comment":"Attaches to the logging module and captures log messages for each test.\n ","endLoc":657,"id":3241,"nodeType":"Class","startLoc":415,"text":"class LoggingPlugin(object):\n \"\"\"Attaches to the logging module and captures log messages for each test.\n \"\"\"\n\n def __init__(self, config):\n \"\"\"Creates a new plugin to capture log messages.\n\n The formatter can be safely shared across all handlers so\n create a single one for the entire test session here.\n \"\"\"\n self._config = config\n\n self.print_logs = get_option_ini(config, \"log_print\")\n self.formatter = self._create_formatter(\n get_option_ini(config, \"log_format\"),\n get_option_ini(config, \"log_date_format\"),\n )\n self.log_level = get_actual_log_level(config, \"log_level\")\n\n self.log_file_level = get_actual_log_level(config, \"log_file_level\")\n self.log_file_format = get_option_ini(config, \"log_file_format\", \"log_format\")\n self.log_file_date_format = get_option_ini(\n config, \"log_file_date_format\", \"log_date_format\"\n )\n self.log_file_formatter = logging.Formatter(\n self.log_file_format, datefmt=self.log_file_date_format\n )\n\n log_file = get_option_ini(config, \"log_file\")\n if log_file:\n self.log_file_handler = logging.FileHandler(\n log_file, mode=\"w\", encoding=\"UTF-8\"\n )\n self.log_file_handler.setFormatter(self.log_file_formatter)\n else:\n self.log_file_handler = None\n\n self.log_cli_handler = None\n\n self.live_logs_context = lambda: dummy_context_manager()\n # Note that the lambda for the live_logs_context is needed because\n # live_logs_context can otherwise not be entered multiple times due\n # to limitations of contextlib.contextmanager.\n\n if self._log_cli_enabled():\n self._setup_cli_logging()\n\n def _create_formatter(self, log_format, log_date_format):\n # color option doesn't exist if terminal plugin is disabled\n color = getattr(self._config.option, \"color\", \"no\")\n if color != \"no\" and ColoredLevelFormatter.LEVELNAME_FMT_REGEX.search(\n log_format\n ):\n formatter = ColoredLevelFormatter(\n create_terminal_writer(self._config), log_format, log_date_format\n )\n else:\n formatter = logging.Formatter(log_format, log_date_format)\n\n if not six.PY2:\n formatter._style = PercentStyleMultiline(formatter._style._fmt)\n return formatter\n\n def _setup_cli_logging(self):\n config = self._config\n terminal_reporter = config.pluginmanager.get_plugin(\"terminalreporter\")\n if terminal_reporter is None:\n # terminal reporter is disabled e.g. by pytest-xdist.\n return\n\n capture_manager = config.pluginmanager.get_plugin(\"capturemanager\")\n # if capturemanager plugin is disabled, live logging still works.\n log_cli_handler = _LiveLoggingStreamHandler(terminal_reporter, capture_manager)\n\n log_cli_formatter = self._create_formatter(\n get_option_ini(config, \"log_cli_format\", \"log_format\"),\n get_option_ini(config, \"log_cli_date_format\", \"log_date_format\"),\n )\n\n log_cli_level = get_actual_log_level(config, \"log_cli_level\", \"log_level\")\n self.log_cli_handler = log_cli_handler\n self.live_logs_context = lambda: catching_logs(\n log_cli_handler, formatter=log_cli_formatter, level=log_cli_level\n )\n\n def set_log_path(self, fname):\n \"\"\"Public method, which can set filename parameter for\n Logging.FileHandler(). Also creates parent directory if\n it does not exist.\n\n .. warning::\n Please considered as an experimental API.\n \"\"\"\n fname = Path(fname)\n\n if not fname.is_absolute():\n fname = Path(self._config.rootdir, fname)\n\n if not fname.parent.exists():\n fname.parent.mkdir(exist_ok=True, parents=True)\n\n self.log_file_handler = logging.FileHandler(\n str(fname), mode=\"w\", encoding=\"UTF-8\"\n )\n self.log_file_handler.setFormatter(self.log_file_formatter)\n\n def _log_cli_enabled(self):\n \"\"\"Return True if log_cli should be considered enabled, either explicitly\n or because --log-cli-level was given in the command-line.\n \"\"\"\n return self._config.getoption(\n \"--log-cli-level\"\n ) is not None or self._config.getini(\"log_cli\")\n\n @pytest.hookimpl(hookwrapper=True, tryfirst=True)\n def pytest_collection(self):\n with self.live_logs_context():\n if self.log_cli_handler:\n self.log_cli_handler.set_when(\"collection\")\n\n if self.log_file_handler is not None:\n with catching_logs(self.log_file_handler, level=self.log_file_level):\n yield\n else:\n yield\n\n @contextmanager\n def _runtest_for(self, item, when):\n with self._runtest_for_main(item, when):\n if self.log_file_handler is not None:\n with catching_logs(self.log_file_handler, level=self.log_file_level):\n yield\n else:\n yield\n\n @contextmanager\n def _runtest_for_main(self, item, when):\n \"\"\"Implements the internals of pytest_runtest_xxx() hook.\"\"\"\n with catching_logs(\n LogCaptureHandler(), formatter=self.formatter, level=self.log_level\n ) as log_handler:\n if self.log_cli_handler:\n self.log_cli_handler.set_when(when)\n\n if item is None:\n yield # run the test\n return\n\n if not hasattr(item, \"catch_log_handlers\"):\n item.catch_log_handlers = {}\n item.catch_log_handlers[when] = log_handler\n item.catch_log_handler = log_handler\n try:\n yield # run test\n finally:\n if when == \"teardown\":\n del item.catch_log_handler\n del item.catch_log_handlers\n\n if self.print_logs:\n # Add a captured log section to the report.\n log = log_handler.stream.getvalue().strip()\n item.add_report_section(when, \"log\", log)\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_setup(self, item):\n with self._runtest_for(item, \"setup\"):\n yield\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_call(self, item):\n with self._runtest_for(item, \"call\"):\n yield\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_teardown(self, item):\n with self._runtest_for(item, \"teardown\"):\n yield\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_logstart(self):\n if self.log_cli_handler:\n self.log_cli_handler.reset()\n with self._runtest_for(None, \"start\"):\n yield\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_logfinish(self):\n with self._runtest_for(None, \"finish\"):\n yield\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_logreport(self):\n with self._runtest_for(None, \"logreport\"):\n yield\n\n @pytest.hookimpl(hookwrapper=True, tryfirst=True)\n def pytest_sessionfinish(self):\n with self.live_logs_context():\n if self.log_cli_handler:\n self.log_cli_handler.set_when(\"sessionfinish\")\n if self.log_file_handler is not None:\n try:\n with catching_logs(\n self.log_file_handler, level=self.log_file_level\n ):\n yield\n finally:\n # Close the FileHandler explicitly.\n # (logging.shutdown might have lost the weakref?!)\n self.log_file_handler.close()\n else:\n yield\n\n @pytest.hookimpl(hookwrapper=True, tryfirst=True)\n def pytest_sessionstart(self):\n with self.live_logs_context():\n if self.log_cli_handler:\n self.log_cli_handler.set_when(\"sessionstart\")\n if self.log_file_handler is not None:\n with catching_logs(self.log_file_handler, level=self.log_file_level):\n yield\n else:\n yield\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtestloop(self, session):\n \"\"\"Runs all collected test items.\"\"\"\n\n if session.config.option.collectonly:\n yield\n return\n\n if self._log_cli_enabled() and self._config.getoption(\"verbose\") < 1:\n # setting verbose flag is needed to avoid messy test progress output\n self._config.option.verbose = 1\n\n with self.live_logs_context():\n if self.log_file_handler is not None:\n with catching_logs(self.log_file_handler, level=self.log_file_level):\n yield # run all the tests\n else:\n yield # run all the tests"},{"col":4,"comment":"null","endLoc":229,"header":"def __repr__(self)","id":3242,"name":"__repr__","nodeType":"Function","startLoc":228,"text":"def __repr__(self):\n return \"\" % (self.mark,)"},{"col":4,"comment":" return a MarkDecorator with extra arguments added\n\n unlike call this can be used even if the sole argument is a callable/class\n\n :return: MarkDecorator\n ","endLoc":240,"header":"def with_args(self, *args, **kwargs)","id":3243,"name":"with_args","nodeType":"Function","startLoc":231,"text":"def with_args(self, *args, **kwargs):\n \"\"\" return a MarkDecorator with extra arguments added\n\n unlike call this can be used even if the sole argument is a callable/class\n\n :return: MarkDecorator\n \"\"\"\n\n mark = Mark(self.name, args, kwargs)\n return self.__class__(self.mark.combined_with(mark))"},{"col":4,"comment":"Creates a new plugin to capture log messages.\n\n The formatter can be safely shared across all handlers so\n create a single one for the entire test session here.\n ","endLoc":460,"header":"def __init__(self, config)","id":3244,"name":"__init__","nodeType":"Function","startLoc":419,"text":"def __init__(self, config):\n \"\"\"Creates a new plugin to capture log messages.\n\n The formatter can be safely shared across all handlers so\n create a single one for the entire test session here.\n \"\"\"\n self._config = config\n\n self.print_logs = get_option_ini(config, \"log_print\")\n self.formatter = self._create_formatter(\n get_option_ini(config, \"log_format\"),\n get_option_ini(config, \"log_date_format\"),\n )\n self.log_level = get_actual_log_level(config, \"log_level\")\n\n self.log_file_level = get_actual_log_level(config, \"log_file_level\")\n self.log_file_format = get_option_ini(config, \"log_file_format\", \"log_format\")\n self.log_file_date_format = get_option_ini(\n config, \"log_file_date_format\", \"log_date_format\"\n )\n self.log_file_formatter = logging.Formatter(\n self.log_file_format, datefmt=self.log_file_date_format\n )\n\n log_file = get_option_ini(config, \"log_file\")\n if log_file:\n self.log_file_handler = logging.FileHandler(\n log_file, mode=\"w\", encoding=\"UTF-8\"\n )\n self.log_file_handler.setFormatter(self.log_file_formatter)\n else:\n self.log_file_handler = None\n\n self.log_cli_handler = None\n\n self.live_logs_context = lambda: dummy_context_manager()\n # Note that the lambda for the live_logs_context is needed because\n # live_logs_context can otherwise not be entered multiple times due\n # to limitations of contextlib.contextmanager.\n\n if self._log_cli_enabled():\n self._setup_cli_logging()"},{"className":"TextIOBase","col":0,"comment":"null","endLoc":150,"id":3245,"nodeType":"Class","startLoc":139,"text":"class TextIOBase(IOBase):\n encoding: str\n errors: str | None\n newlines: str | tuple[str, ...] | None\n def __iter__(self) -> Iterator[str]: ... # type: ignore[override]\n def __next__(self) -> str: ... # type: ignore[override]\n def detach(self) -> BinaryIO: ...\n def write(self, s: str, /) -> int: ...\n def writelines(self, lines: Iterable[str], /) -> None: ... # type: ignore[override]\n def readline(self, size: int = ..., /) -> str: ... # type: ignore[override]\n def readlines(self, hint: int = -1, /) -> list[str]: ... # type: ignore[override]\n def read(self, size: int | None = ..., /) -> str: ..."},{"className":"IOBase","col":0,"comment":"null","endLoc":78,"id":3246,"nodeType":"Class","startLoc":53,"text":"class IOBase(metaclass=abc.ABCMeta):\n def __iter__(self) -> Iterator[bytes]: ...\n def __next__(self) -> bytes: ...\n def __enter__(self) -> Self: ...\n def __exit__(\n self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n ) -> None: ...\n def close(self) -> None: ...\n def fileno(self) -> int: ...\n def flush(self) -> None: ...\n def isatty(self) -> bool: ...\n def readable(self) -> bool: ...\n read: Callable[..., Any]\n def readlines(self, hint: int = -1, /) -> list[bytes]: ...\n def seek(self, offset: int, whence: int = ..., /) -> int: ...\n def seekable(self) -> bool: ...\n def tell(self) -> int: ...\n def truncate(self, size: int | None = ..., /) -> int: ...\n def writable(self) -> bool: ...\n write: Callable[..., Any]\n def writelines(self, lines: Iterable[ReadableBuffer], /) -> None: ...\n def readline(self, size: int | None = -1, /) -> bytes: ...\n def __del__(self) -> None: ...\n @property\n def closed(self) -> bool: ...\n def _checkClosed(self) -> None: ... # undocumented"},{"col":4,"comment":"null","endLoc":54,"header":"def __iter__(self) -> Iterator[bytes]","id":3247,"name":"__iter__","nodeType":"Function","startLoc":54,"text":"def __iter__(self) -> Iterator[bytes]: ..."},{"col":4,"comment":"null","endLoc":55,"header":"def __next__(self) -> bytes","id":3248,"name":"__next__","nodeType":"Function","startLoc":55,"text":"def __next__(self) -> bytes: ..."},{"col":4,"comment":"null","endLoc":56,"header":"def __enter__(self) -> Self","id":3249,"name":"__enter__","nodeType":"Function","startLoc":56,"text":"def __enter__(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":59,"header":"def __exit__(\n self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n ) -> None","id":3250,"name":"__exit__","nodeType":"Function","startLoc":57,"text":"def __exit__(\n self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":60,"header":"def close(self) -> None","id":3251,"name":"close","nodeType":"Function","startLoc":60,"text":"def close(self) -> None: ..."},{"col":4,"comment":"null","endLoc":61,"header":"def fileno(self) -> int","id":3252,"name":"fileno","nodeType":"Function","startLoc":61,"text":"def fileno(self) -> int: ..."},{"col":4,"comment":"null","endLoc":62,"header":"def flush(self) -> None","id":3253,"name":"flush","nodeType":"Function","startLoc":62,"text":"def flush(self) -> None: ..."},{"col":4,"comment":"null","endLoc":63,"header":"def isatty(self) -> bool","id":3254,"name":"isatty","nodeType":"Function","startLoc":63,"text":"def isatty(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":64,"header":"def readable(self) -> bool","id":3255,"name":"readable","nodeType":"Function","startLoc":64,"text":"def readable(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":66,"header":"def readlines(self, hint: int = -1, /) -> list[bytes]","id":3256,"name":"readlines","nodeType":"Function","startLoc":66,"text":"def readlines(self, hint: int = -1, /) -> list[bytes]: ..."},{"col":4,"comment":"null","endLoc":67,"header":"def seek(self, offset: int, whence: int = ..., /) -> int","id":3257,"name":"seek","nodeType":"Function","startLoc":67,"text":"def seek(self, offset: int, whence: int = ..., /) -> int: ..."},{"col":4,"comment":"null","endLoc":68,"header":"def seekable(self) -> bool","id":3258,"name":"seekable","nodeType":"Function","startLoc":68,"text":"def seekable(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":69,"header":"def tell(self) -> int","id":3259,"name":"tell","nodeType":"Function","startLoc":69,"text":"def tell(self) -> int: ..."},{"col":4,"comment":"null","endLoc":70,"header":"def truncate(self, size: int | None = ..., /) -> int","id":3260,"name":"truncate","nodeType":"Function","startLoc":70,"text":"def truncate(self, size: int | None = ..., /) -> int: ..."},{"col":4,"comment":"null","endLoc":71,"header":"def writable(self) -> bool","id":3261,"name":"writable","nodeType":"Function","startLoc":71,"text":"def writable(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":73,"header":"def writelines(self, lines: Iterable[ReadableBuffer], /) -> None","id":3262,"name":"writelines","nodeType":"Function","startLoc":73,"text":"def writelines(self, lines: Iterable[ReadableBuffer], /) -> None: ..."},{"col":4,"comment":"null","endLoc":74,"header":"def readline(self, size: int | None = -1, /) -> bytes","id":3263,"name":"readline","nodeType":"Function","startLoc":74,"text":"def readline(self, size: int | None = -1, /) -> bytes: ..."},{"col":4,"comment":"null","endLoc":75,"header":"def __del__(self) -> None","id":3264,"name":"__del__","nodeType":"Function","startLoc":75,"text":"def __del__(self) -> None: ..."},{"col":4,"comment":"null","endLoc":77,"header":"@property\n def closed(self) -> bool","id":3265,"name":"closed","nodeType":"Function","startLoc":76,"text":"@property\n def closed(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":78,"header":"def _checkClosed(self) -> None","id":3266,"name":"_checkClosed","nodeType":"Function","startLoc":78,"text":"def _checkClosed(self) -> None: ... # undocumented"},{"attributeType":"(...) -> Any","col":4,"comment":"null","endLoc":65,"id":3268,"name":"read","nodeType":"Attribute","startLoc":65,"text":"read"},{"col":0,"comment":"null","endLoc":116,"header":"def get_option_ini(config, *names)","id":3269,"name":"get_option_ini","nodeType":"Function","startLoc":110,"text":"def get_option_ini(config, *names):\n for name in names:\n ret = config.getoption(name) # 'default' arg won't work as expected\n if ret is None:\n ret = config.getini(name)\n if ret:\n return ret"},{"className":"DoctestTextfile","col":0,"comment":"null","endLoc":343,"id":3270,"nodeType":"Class","startLoc":316,"text":"class DoctestTextfile(pytest.Module):\n obj = None\n\n def collect(self):\n import doctest\n\n # inspired by doctest.testfile; ideally we would use it directly,\n # but it doesn't support passing a custom checker\n encoding = self.config.getini(\"doctest_encoding\")\n text = self.fspath.read_text(encoding)\n filename = str(self.fspath)\n name = self.fspath.basename\n globs = {\"__name__\": \"__main__\"}\n\n optionflags = get_optionflags(self)\n\n runner = _get_runner(\n verbose=0,\n optionflags=optionflags,\n checker=_get_checker(),\n continue_on_failure=_get_continue_on_failure(self.config),\n )\n _fix_spoof_python2(runner, encoding)\n\n parser = doctest.DocTestParser()\n test = parser.get_doctest(text, globs, name, filename, 0)\n if test.examples:\n yield DoctestItem(test.name, self, runner, test)"},{"col":4,"comment":" if passed a single callable argument: decorate it with mark info.\n otherwise add *args/**kwargs in-place to mark information. ","endLoc":251,"header":"def __call__(self, *args, **kwargs)","id":3271,"name":"__call__","nodeType":"Function","startLoc":242,"text":"def __call__(self, *args, **kwargs):\n \"\"\" if passed a single callable argument: decorate it with mark info.\n otherwise add *args/**kwargs in-place to mark information. \"\"\"\n if args and not kwargs:\n func = args[0]\n is_class = inspect.isclass(func)\n if len(args) == 1 and (istestfunc(func) or is_class):\n store_mark(func, self.mark)\n return func\n return self.with_args(*args, **kwargs)"},{"col":4,"comment":"null","endLoc":343,"header":"def collect(self)","id":3272,"name":"collect","nodeType":"Function","startLoc":319,"text":"def collect(self):\n import doctest\n\n # inspired by doctest.testfile; ideally we would use it directly,\n # but it doesn't support passing a custom checker\n encoding = self.config.getini(\"doctest_encoding\")\n text = self.fspath.read_text(encoding)\n filename = str(self.fspath)\n name = self.fspath.basename\n globs = {\"__name__\": \"__main__\"}\n\n optionflags = get_optionflags(self)\n\n runner = _get_runner(\n verbose=0,\n optionflags=optionflags,\n checker=_get_checker(),\n continue_on_failure=_get_continue_on_failure(self.config),\n )\n _fix_spoof_python2(runner, encoding)\n\n parser = doctest.DocTestParser()\n test = parser.get_doctest(text, globs, name, filename, 0)\n if test.examples:\n yield DoctestItem(test.name, self, runner, test)"},{"attributeType":"(...) -> Any","col":4,"comment":"null","endLoc":72,"id":3273,"name":"write","nodeType":"Attribute","startLoc":72,"text":"write"},{"col":4,"comment":"null","endLoc":143,"header":"def __iter__(self) -> Iterator[str]","id":3275,"name":"__iter__","nodeType":"Function","startLoc":143,"text":"def __iter__(self) -> Iterator[str]: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":144,"header":"def __next__(self) -> str","id":3276,"name":"__next__","nodeType":"Function","startLoc":144,"text":"def __next__(self) -> str: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":145,"header":"def detach(self) -> BinaryIO","id":3277,"name":"detach","nodeType":"Function","startLoc":145,"text":"def detach(self) -> BinaryIO: ..."},{"col":4,"comment":"null","endLoc":146,"header":"def write(self, s: str, /) -> int","id":3278,"name":"write","nodeType":"Function","startLoc":146,"text":"def write(self, s: str, /) -> int: ..."},{"col":4,"comment":"null","endLoc":147,"header":"def writelines(self, lines: Iterable[str], /) -> None","id":3279,"name":"writelines","nodeType":"Function","startLoc":147,"text":"def writelines(self, lines: Iterable[str], /) -> None: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":148,"header":"def readline(self, size: int = ..., /) -> str","id":3280,"name":"readline","nodeType":"Function","startLoc":148,"text":"def readline(self, size: int = ..., /) -> str: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":149,"header":"def readlines(self, hint: int = -1, /) -> list[str]","id":3281,"name":"readlines","nodeType":"Function","startLoc":149,"text":"def readlines(self, hint: int = -1, /) -> list[str]: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":150,"header":"def read(self, size: int | None = ..., /) -> str","id":3282,"name":"read","nodeType":"Function","startLoc":150,"text":"def read(self, size: int | None = ..., /) -> str: ..."},{"attributeType":"str","col":4,"comment":"null","endLoc":140,"id":3283,"name":"encoding","nodeType":"Attribute","startLoc":140,"text":"encoding"},{"col":0,"comment":"null","endLoc":35,"header":"def istestfunc(func)","id":3284,"name":"istestfunc","nodeType":"Function","startLoc":31,"text":"def istestfunc(func):\n return (\n hasattr(func, \"__call__\")\n and getattr(func, \"__name__\", \"\") != \"\"\n )"},{"attributeType":"str | None","col":4,"comment":"null","endLoc":141,"id":3286,"name":"errors","nodeType":"Attribute","startLoc":141,"text":"errors"},{"col":0,"comment":"","endLoc":2,"header":"conftest.py#","id":3288,"name":"","nodeType":"Function","startLoc":2,"text":"if sys.gettrace():\n\n @pytest.fixture(autouse=True)\n def restore_tracing():\n \"\"\"Restore tracing function (when run with Coverage.py).\n\n https://bugs.python.org/issue37011\n \"\"\"\n orig_trace = sys.gettrace()\n yield\n if sys.gettrace() != orig_trace:\n sys.settrace(orig_trace)"},{"fileName":"test_spam.py","filePath":"testing/example_scripts/fixtures/fill_fixtures/test_extend_fixture_conftest_conftest/pkg","id":3290,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ndef test_spam(spam):\n assert spam == \"spamspam\"\n"},{"col":0,"comment":"null","endLoc":3,"header":"def test_spam(spam)","id":3291,"name":"test_spam","nodeType":"Function","startLoc":2,"text":"def test_spam(spam):\n assert spam == \"spamspam\""},{"col":0,"comment":"store a Mark on an object\n this is used to implement the Mark declarations/decorators correctly\n ","endLoc":287,"header":"def store_mark(obj, mark)","id":3292,"name":"store_mark","nodeType":"Function","startLoc":280,"text":"def store_mark(obj, mark):\n \"\"\"store a Mark on an object\n this is used to implement the Mark declarations/decorators correctly\n \"\"\"\n assert isinstance(mark, Mark), mark\n # always reassign name to avoid updating pytestmark\n # in a reference that was only borrowed\n obj.pytestmark = get_unpacked_marks(obj) + [mark]"},{"col":0,"comment":"\n Return the index where to insert item x in list a, assuming a is sorted.\n \n The return value i is such that all e in a[:i] have e <= x, and all e in\n a[i:] have e > x. So if x already appears in the list, i points just\n beyond the rightmost x already there\n \n Optional args lo (default 0) and hi (default len(a)) bound the\n slice of a to be searched.\n ","endLoc":41,"header":"def bisect_right(*args, **kwargs)","id":3293,"name":"bisect_right","nodeType":"Function","startLoc":30,"text":"def bisect_right(*args, **kwargs): # real signature unknown\n \"\"\"\n Return the index where to insert item x in list a, assuming a is sorted.\n \n The return value i is such that all e in a[:i] have e <= x, and all e in\n a[i:] have e > x. So if x already appears in the list, i points just\n beyond the rightmost x already there\n \n Optional args lo (default 0) and hi (default len(a)) bound the\n slice of a to be searched.\n \"\"\"\n pass"},{"attributeType":"str | (str, ...) | None","col":4,"comment":"null","endLoc":142,"id":3294,"name":"newlines","nodeType":"Attribute","startLoc":142,"text":"newlines"},{"col":4,"comment":"null","endLoc":135,"header":"@pytest.mark.parametrize(\"style\", (\"native\", \"long\", \"short\"))\n def test_internal_exception(self, style)","id":3295,"name":"test_internal_exception","nodeType":"Function","startLoc":118,"text":"@pytest.mark.parametrize(\"style\", (\"native\", \"long\", \"short\"))\n def test_internal_exception(self, style):\n # they are produced for example by a teardown failing\n # at the end of the run or a failing hook invocation\n try:\n raise ValueError\n except ValueError:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n reslog = ResultLog(None, py.io.TextIO())\n reslog.pytest_internalerror(excinfo.getrepr(style=style))\n entry = reslog.logfile.getvalue()\n entry_lines = entry.splitlines()\n\n assert entry_lines[0].startswith(\"! \")\n if style != \"native\":\n assert os.path.basename(__file__)[:-9] in entry_lines[0] # .pyc/class\n assert entry_lines[-1][0] == \" \"\n assert \"ValueError\" in entry"},{"attributeType":"str","col":4,"comment":"null","endLoc":312,"id":3296,"name":"key","nodeType":"Attribute","startLoc":312,"text":"key"},{"className":"TestSysPathsSnapshot","col":0,"comment":"null","endLoc":416,"id":3297,"nodeType":"Class","startLoc":373,"text":"@pytest.mark.parametrize(\"path_type\", (\"path\", \"meta_path\"))\nclass TestSysPathsSnapshot(object):\n other_path = {\"path\": \"meta_path\", \"meta_path\": \"path\"}\n\n @staticmethod\n def path(n):\n return \"my-dirty-little-secret-\" + str(n)\n\n def test_restore(self, monkeypatch, path_type):\n other_path_type = self.other_path[path_type]\n for i in range(10):\n assert self.path(i) not in getattr(sys, path_type)\n sys_path = [self.path(i) for i in range(6)]\n monkeypatch.setattr(sys, path_type, sys_path)\n original = list(sys_path)\n original_other = list(getattr(sys, other_path_type))\n snapshot = SysPathsSnapshot()\n transformation = {\"source\": (0, 1, 2, 3, 4, 5), \"target\": (6, 2, 9, 7, 5, 8)}\n assert sys_path == [self.path(x) for x in transformation[\"source\"]]\n sys_path[1] = self.path(6)\n sys_path[3] = self.path(7)\n sys_path.append(self.path(8))\n del sys_path[4]\n sys_path[3:3] = [self.path(9)]\n del sys_path[0]\n assert sys_path == [self.path(x) for x in transformation[\"target\"]]\n snapshot.restore()\n assert getattr(sys, path_type) is sys_path\n assert getattr(sys, path_type) == original\n assert getattr(sys, other_path_type) == original_other\n\n def test_preserve_container(self, monkeypatch, path_type):\n other_path_type = self.other_path[path_type]\n original_data = list(getattr(sys, path_type))\n original_other = getattr(sys, other_path_type)\n original_other_data = list(original_other)\n new = []\n snapshot = SysPathsSnapshot()\n monkeypatch.setattr(sys, path_type, new)\n snapshot.restore()\n assert getattr(sys, path_type) is new\n assert getattr(sys, path_type) == original_data\n assert getattr(sys, other_path_type) is original_other\n assert getattr(sys, other_path_type) == original_other_data"},{"col":4,"comment":"null","endLoc":379,"header":"@staticmethod\n def path(n)","id":3298,"name":"path","nodeType":"Function","startLoc":377,"text":"@staticmethod\n def path(n):\n return \"my-dirty-little-secret-\" + str(n)"},{"col":48,"endLoc":315,"id":3299,"nodeType":"Lambda","startLoc":315,"text":"lambda: next(it)"},{"className":"TextIO","col":0,"comment":"null","endLoc":831,"id":3300,"nodeType":"Class","startLoc":818,"text":"class TextIO(IO[str]):\n # See comment regarding the @properties in the `IO` class\n @property\n def buffer(self) -> BinaryIO: ...\n @property\n def encoding(self) -> str: ...\n @property\n def errors(self) -> str | None: ...\n @property\n def line_buffering(self) -> int: ... # int on PyPy, bool on CPython\n @property\n def newlines(self) -> Any: ... # None, str or tuple\n @abstractmethod\n def __enter__(self) -> TextIO: ..."},{"col":4,"comment":"return a new source object deindented.","endLoc":120,"header":"def deindent(self)","id":3302,"name":"deindent","nodeType":"Function","startLoc":116,"text":"def deindent(self):\n \"\"\"return a new source object deindented.\"\"\"\n newsource = Source()\n newsource.lines[:] = deindent(self.lines)\n return newsource"},{"col":4,"comment":" return True if source is parseable, heuristically\n deindenting it by default.\n ","endLoc":140,"header":"def isparseable(self, deindent=True)","id":3303,"name":"isparseable","nodeType":"Function","startLoc":122,"text":"def isparseable(self, deindent=True):\n \"\"\" return True if source is parseable, heuristically\n deindenting it by default.\n \"\"\"\n from parser import suite as syntax_checker\n\n if deindent:\n source = str(self.deindent())\n else:\n source = str(self)\n try:\n # compile(source+'\\n', \"x\", \"exec\")\n syntax_checker(source + \"\\n\")\n except KeyboardInterrupt:\n raise\n except Exception:\n return False\n else:\n return True"},{"col":4,"comment":"null","endLoc":821,"header":"@property\n def buffer(self) -> BinaryIO","id":3304,"name":"buffer","nodeType":"Function","startLoc":820,"text":"@property\n def buffer(self) -> BinaryIO: ..."},{"col":4,"comment":"null","endLoc":823,"header":"@property\n def encoding(self) -> str","id":3305,"name":"encoding","nodeType":"Function","startLoc":822,"text":"@property\n def encoding(self) -> str: ..."},{"col":4,"comment":"null","endLoc":825,"header":"@property\n def errors(self) -> str | None","id":3306,"name":"errors","nodeType":"Function","startLoc":824,"text":"@property\n def errors(self) -> str | None: ..."},{"col":4,"comment":"null","endLoc":827,"header":"@property\n def line_buffering(self) -> int","id":3307,"name":"line_buffering","nodeType":"Function","startLoc":826,"text":"@property\n def line_buffering(self) -> int: ... # int on PyPy, bool on CPython"},{"col":4,"comment":"null","endLoc":829,"header":"@property\n def newlines(self) -> Any","id":3308,"name":"newlines","nodeType":"Function","startLoc":828,"text":"@property\n def newlines(self) -> Any: ... # None, str or tuple"},{"col":4,"comment":"null","endLoc":831,"header":"@abstractmethod\n def __enter__(self) -> TextIO","id":3309,"name":"__enter__","nodeType":"Function","startLoc":830,"text":"@abstractmethod\n def __enter__(self) -> TextIO: ..."},{"col":4,"comment":"null","endLoc":187,"header":"def __init__(\n self,\n buffer: _BufferT_co,\n encoding: str | None = None,\n errors: str | None = None,\n newline: str | None = None,\n line_buffering: bool = False,\n write_through: bool = False,\n ) -> None","id":3310,"name":"__init__","nodeType":"Function","startLoc":179,"text":"def __init__(\n self,\n buffer: _BufferT_co,\n encoding: str | None = None,\n errors: str | None = None,\n newline: str | None = None,\n line_buffering: bool = False,\n write_through: bool = False,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":402,"header":"def test_restore(self, monkeypatch, path_type)","id":3311,"name":"test_restore","nodeType":"Function","startLoc":381,"text":"def test_restore(self, monkeypatch, path_type):\n other_path_type = self.other_path[path_type]\n for i in range(10):\n assert self.path(i) not in getattr(sys, path_type)\n sys_path = [self.path(i) for i in range(6)]\n monkeypatch.setattr(sys, path_type, sys_path)\n original = list(sys_path)\n original_other = list(getattr(sys, other_path_type))\n snapshot = SysPathsSnapshot()\n transformation = {\"source\": (0, 1, 2, 3, 4, 5), \"target\": (6, 2, 9, 7, 5, 8)}\n assert sys_path == [self.path(x) for x in transformation[\"source\"]]\n sys_path[1] = self.path(6)\n sys_path[3] = self.path(7)\n sys_path.append(self.path(8))\n del sys_path[4]\n sys_path[3:3] = [self.path(9)]\n del sys_path[0]\n assert sys_path == [self.path(x) for x in transformation[\"target\"]]\n snapshot.restore()\n assert getattr(sys, path_type) is sys_path\n assert getattr(sys, path_type) == original\n assert getattr(sys, other_path_type) == original_other"},{"col":4,"comment":"null","endLoc":190,"header":"@property\n def buffer(self) -> _BufferT_co","id":3312,"name":"buffer","nodeType":"Function","startLoc":189,"text":"@property\n def buffer(self) -> _BufferT_co: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":192,"header":"@property\n def closed(self) -> bool","id":3313,"name":"closed","nodeType":"Function","startLoc":191,"text":"@property\n def closed(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":194,"header":"@property\n def line_buffering(self) -> bool","id":3314,"name":"line_buffering","nodeType":"Function","startLoc":193,"text":"@property\n def line_buffering(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":196,"header":"@property\n def write_through(self) -> bool","id":3315,"name":"write_through","nodeType":"Function","startLoc":195,"text":"@property\n def write_through(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":205,"header":"def reconfigure(\n self,\n *,\n encoding: str | None = None,\n errors: str | None = None,\n newline: str | None = None,\n line_buffering: bool | None = None,\n write_through: bool | None = None,\n ) -> None","id":3316,"name":"reconfigure","nodeType":"Function","startLoc":197,"text":"def reconfigure(\n self,\n *,\n encoding: str | None = None,\n errors: str | None = None,\n newline: str | None = None,\n line_buffering: bool | None = None,\n write_through: bool | None = None,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":207,"header":"def __enter__(self) -> Self","id":3317,"name":"__enter__","nodeType":"Function","startLoc":207,"text":"def __enter__(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":208,"header":"def __iter__(self) -> Iterator[str]","id":3318,"name":"__iter__","nodeType":"Function","startLoc":208,"text":"def __iter__(self) -> Iterator[str]: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":209,"header":"def __next__(self) -> str","id":3319,"name":"__next__","nodeType":"Function","startLoc":209,"text":"def __next__(self) -> str: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":210,"header":"def writelines(self, lines: Iterable[str], /) -> None","id":3320,"name":"writelines","nodeType":"Function","startLoc":210,"text":"def writelines(self, lines: Iterable[str], /) -> None: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":211,"header":"def readline(self, size: int = -1, /) -> str","id":3321,"name":"readline","nodeType":"Function","startLoc":211,"text":"def readline(self, size: int = -1, /) -> str: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":212,"header":"def readlines(self, hint: int = -1, /) -> list[str]","id":3322,"name":"readlines","nodeType":"Function","startLoc":212,"text":"def readlines(self, hint: int = -1, /) -> list[str]: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":214,"header":"def detach(self) -> _BufferT_co","id":3323,"name":"detach","nodeType":"Function","startLoc":214,"text":"def detach(self) -> _BufferT_co: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":217,"header":"def seek(self, cookie: int, whence: int = 0, /) -> int","id":3324,"name":"seek","nodeType":"Function","startLoc":217,"text":"def seek(self, cookie: int, whence: int = 0, /) -> int: ..."},{"col":8,"comment":"null","endLoc":430,"header":"def __init__(self)","id":3325,"name":"__init__","nodeType":"Function","startLoc":427,"text":"def __init__(self):\n super(CaptureIO, self).__init__(\n io.BytesIO(), encoding=\"UTF-8\", newline=\"\", write_through=True\n )"},{"fileName":"test_nodes.py","filePath":"testing","id":3326,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport py\n\nimport pytest\nfrom _pytest import nodes\n\n\n@pytest.mark.parametrize(\n \"baseid, nodeid, expected\",\n (\n (\"\", \"\", True),\n (\"\", \"foo\", True),\n (\"\", \"foo/bar\", True),\n (\"\", \"foo/bar::TestBaz\", True),\n (\"foo\", \"food\", False),\n (\"foo/bar::TestBaz\", \"foo/bar\", False),\n (\"foo/bar::TestBaz\", \"foo/bar::TestBop\", False),\n (\"foo/bar\", \"foo/bar::TestBop\", True),\n ),\n)\ndef test_ischildnode(baseid, nodeid, expected):\n result = nodes.ischildnode(baseid, nodeid)\n assert result is expected\n\n\ndef test_std_warn_not_pytestwarning(testdir):\n items = testdir.getitems(\n \"\"\"\n def test():\n pass\n \"\"\"\n )\n with pytest.raises(ValueError, match=\".*instance of PytestWarning.*\"):\n items[0].warn(UserWarning(\"some warning\"))\n\n\ndef test__check_initialpaths_for_relpath():\n \"\"\"Ensure that it handles dirs, and does not always use dirname.\"\"\"\n cwd = py.path.local()\n\n class FakeSession:\n _initialpaths = [cwd]\n\n assert nodes._check_initialpaths_for_relpath(FakeSession, cwd) == \"\"\n\n sub = cwd.join(\"file\")\n\n class FakeSession:\n _initialpaths = [cwd]\n\n assert nodes._check_initialpaths_for_relpath(FakeSession, sub) == \"file\"\n\n outside = py.path.local(\"/outside\")\n assert nodes._check_initialpaths_for_relpath(FakeSession, outside) is None\n"},{"col":0,"comment":"null","endLoc":23,"header":"@pytest.mark.parametrize(\n \"baseid, nodeid, expected\",\n (\n (\"\", \"\", True),\n (\"\", \"foo\", True),\n (\"\", \"foo/bar\", True),\n (\"\", \"foo/bar","id":3327,"name":"test_ischildnode","nodeType":"Function","startLoc":8,"text":"@pytest.mark.parametrize(\n \"baseid, nodeid, expected\",\n (\n (\"\", \"\", True),\n (\"\", \"foo\", True),\n (\"\", \"foo/bar\", True),\n (\"\", \"foo/bar::TestBaz\", True),\n (\"foo\", \"food\", False),\n (\"foo/bar::TestBaz\", \"foo/bar\", False),\n (\"foo/bar::TestBaz\", \"foo/bar::TestBop\", False),\n (\"foo/bar\", \"foo/bar::TestBop\", True),\n ),\n)\ndef test_ischildnode(baseid, nodeid, expected):\n result = nodes.ischildnode(baseid, nodeid)\n assert result is expected"},{"col":0,"comment":"Return True if the nodeid is a child node of the baseid.\n\n E.g. 'foo/bar::Baz' is a child of 'foo', 'foo/bar' and 'foo/bar::Baz', but not of 'foo/blorp'\n ","endLoc":55,"header":"def ischildnode(baseid, nodeid)","id":3328,"name":"ischildnode","nodeType":"Function","startLoc":46,"text":"def ischildnode(baseid, nodeid):\n \"\"\"Return True if the nodeid is a child node of the baseid.\n\n E.g. 'foo/bar::Baz' is a child of 'foo', 'foo/bar' and 'foo/bar::Baz', but not of 'foo/blorp'\n \"\"\"\n base_parts = _splitnode(baseid)\n node_parts = _splitnode(nodeid)\n if len(node_parts) < len(base_parts):\n return False\n return node_parts[: len(base_parts)] == base_parts"},{"col":0,"comment":"Split a nodeid into constituent 'parts'.\n\n Node IDs are strings, and can be things like:\n ''\n 'testing/code'\n 'testing/code/test_excinfo.py'\n 'testing/code/test_excinfo.py::TestFormattedExcinfo'\n\n Return values are lists e.g.\n []\n ['testing', 'code']\n ['testing', 'code', 'test_excinfo.py']\n ['testing', 'code', 'test_excinfo.py', 'TestFormattedExcinfo', '()']\n ","endLoc":43,"header":"def _splitnode(nodeid)","id":3329,"name":"_splitnode","nodeType":"Function","startLoc":22,"text":"def _splitnode(nodeid):\n \"\"\"Split a nodeid into constituent 'parts'.\n\n Node IDs are strings, and can be things like:\n ''\n 'testing/code'\n 'testing/code/test_excinfo.py'\n 'testing/code/test_excinfo.py::TestFormattedExcinfo'\n\n Return values are lists e.g.\n []\n ['testing', 'code']\n ['testing', 'code', 'test_excinfo.py']\n ['testing', 'code', 'test_excinfo.py', 'TestFormattedExcinfo', '()']\n \"\"\"\n if nodeid == \"\":\n # If there is no root node at all, return an empty list so the caller's logic can remain sane\n return []\n parts = nodeid.split(SEP)\n # Replace single last element 'test_foo.py::Bar' with multiple elements 'test_foo.py', 'Bar'\n parts[-1:] = parts[-1].split(\"::\")\n return parts"},{"col":0,"comment":"Try to read and rewrite *fn* and return the code object.","endLoc":412,"header":"def _rewrite_test(config, fn)","id":3330,"name":"_rewrite_test","nodeType":"Function","startLoc":359,"text":"def _rewrite_test(config, fn):\n \"\"\"Try to read and rewrite *fn* and return the code object.\"\"\"\n state = config._assertstate\n try:\n stat = fn.stat()\n source = fn.read(\"rb\")\n except EnvironmentError:\n return None, None\n if ASCII_IS_DEFAULT_ENCODING:\n # ASCII is the default encoding in Python 2. Without a coding\n # declaration, Python 2 will complain about any bytes in the file\n # outside the ASCII range. Sadly, this behavior does not extend to\n # compile() or ast.parse(), which prefer to interpret the bytes as\n # latin-1. (At least they properly handle explicit coding cookies.) To\n # preserve this error behavior, we could force ast.parse() to use ASCII\n # as the encoding by inserting a coding cookie. Unfortunately, that\n # messes up line numbers. Thus, we have to check ourselves if anything\n # is outside the ASCII range in the case no encoding is explicitly\n # declared. For more context, see issue #269. Yay for Python 3 which\n # gets this right.\n end1 = source.find(\"\\n\")\n end2 = source.find(\"\\n\", end1 + 1)\n if (\n not source.startswith(BOM_UTF8)\n and cookie_re.match(source[0:end1]) is None\n and cookie_re.match(source[end1 + 1 : end2]) is None\n ):\n if hasattr(state, \"_indecode\"):\n # encodings imported us again, so don't rewrite.\n return None, None\n state._indecode = True\n try:\n try:\n source.decode(\"ascii\")\n except UnicodeDecodeError:\n # Let it fail in real import.\n return None, None\n finally:\n del state._indecode\n try:\n tree = ast.parse(source, filename=fn.strpath)\n except SyntaxError:\n # Let this pop up again in the real import.\n state.trace(\"failed to parse: %r\" % (fn,))\n return None, None\n rewrite_asserts(tree, fn, config)\n try:\n co = compile(tree, fn.strpath, \"exec\", dont_inherit=True)\n except SyntaxError:\n # It's possible that this error is from some bug in the\n # assertion rewriting, but I don't know of a fast way to tell.\n state.trace(\"failed to compile: %r\" % (fn,))\n return None, None\n return stat, co"},{"col":0,"comment":"null","endLoc":34,"header":"def test_std_warn_not_pytestwarning(testdir)","id":3332,"name":"test_std_warn_not_pytestwarning","nodeType":"Function","startLoc":26,"text":"def test_std_warn_not_pytestwarning(testdir):\n items = testdir.getitems(\n \"\"\"\n def test():\n pass\n \"\"\"\n )\n with pytest.raises(ValueError, match=\".*instance of PytestWarning.*\"):\n items[0].warn(UserWarning(\"some warning\"))"},{"col":0,"comment":"Rewrite the assert statements in mod.","endLoc":453,"header":"def rewrite_asserts(mod, module_path=None, config=None)","id":3341,"name":"rewrite_asserts","nodeType":"Function","startLoc":451,"text":"def rewrite_asserts(mod, module_path=None, config=None):\n \"\"\"Rewrite the assert statements in mod.\"\"\"\n AssertionRewriter(module_path, config).run(mod)"},{"col":4,"comment":"null","endLoc":721,"header":"def notify_exception(self, excinfo, option=None)","id":3342,"name":"notify_exception","nodeType":"Function","startLoc":709,"text":"def notify_exception(self, excinfo, option=None):\n if option and getattr(option, \"fulltrace\", False):\n style = \"long\"\n else:\n style = \"native\"\n excrepr = excinfo.getrepr(\n funcargs=True, showlocals=getattr(option, \"showlocals\", False), style=style\n )\n res = self.hook.pytest_internalerror(excrepr=excrepr, excinfo=excinfo)\n if not any(res):\n for line in str(excrepr).split(\"\\n\"):\n sys.stderr.write(\"INTERNALERROR> %s\\n\" % line)\n sys.stderr.flush()"},{"col":4,"comment":"null","endLoc":648,"header":"def __init__(self, module_path, config)","id":3343,"name":"__init__","nodeType":"Function","startLoc":645,"text":"def __init__(self, module_path, config):\n super(AssertionRewriter, self).__init__()\n self.module_path = module_path\n self.config = config"},{"attributeType":"null","col":4,"comment":"null","endLoc":215,"id":3344,"name":"mark","nodeType":"Attribute","startLoc":215,"text":"mark"},{"attributeType":"property","col":4,"comment":"null","endLoc":217,"id":3345,"name":"name","nodeType":"Attribute","startLoc":217,"text":"name"},{"col":0,"comment":"Ensure that it handles dirs, and does not always use dirname.","endLoc":54,"header":"def test__check_initialpaths_for_relpath()","id":3346,"name":"test__check_initialpaths_for_relpath","nodeType":"Function","startLoc":37,"text":"def test__check_initialpaths_for_relpath():\n \"\"\"Ensure that it handles dirs, and does not always use dirname.\"\"\"\n cwd = py.path.local()\n\n class FakeSession:\n _initialpaths = [cwd]\n\n assert nodes._check_initialpaths_for_relpath(FakeSession, cwd) == \"\"\n\n sub = cwd.join(\"file\")\n\n class FakeSession:\n _initialpaths = [cwd]\n\n assert nodes._check_initialpaths_for_relpath(FakeSession, sub) == \"file\"\n\n outside = py.path.local(\"/outside\")\n assert nodes._check_initialpaths_for_relpath(FakeSession, outside) is None"},{"col":0,"comment":"\n Installs a \"SpoofOut\" into the given DebugRunner so it properly deals with unicode output. This\n should patch only doctests for text files because they don't have a way to declare their\n encoding. Doctests in docstrings from Python modules don't have the same problem given that\n Python already decoded the strings.\n\n This fixes the problem related in issue #2434.\n ","endLoc":575,"header":"def _fix_spoof_python2(runner, encoding)","id":3347,"name":"_fix_spoof_python2","nodeType":"Function","startLoc":552,"text":"def _fix_spoof_python2(runner, encoding):\n \"\"\"\n Installs a \"SpoofOut\" into the given DebugRunner so it properly deals with unicode output. This\n should patch only doctests for text files because they don't have a way to declare their\n encoding. Doctests in docstrings from Python modules don't have the same problem given that\n Python already decoded the strings.\n\n This fixes the problem related in issue #2434.\n \"\"\"\n from _pytest.compat import _PY2\n\n if not _PY2:\n return\n\n from doctest import _SpoofOut\n\n class UnicodeSpoof(_SpoofOut):\n def getvalue(self):\n result = _SpoofOut.getvalue(self)\n if encoding and isinstance(result, bytes):\n result = result.decode(encoding)\n return result\n\n runner._fakeout = UnicodeSpoof()"},{"col":4,"comment":"Find all assert statements in *mod* and rewrite them.","endLoc":713,"header":"def run(self, mod)","id":3348,"name":"run","nodeType":"Function","startLoc":650,"text":"def run(self, mod):\n \"\"\"Find all assert statements in *mod* and rewrite them.\"\"\"\n if not mod.body:\n # Nothing to do.\n return\n # Insert some special imports at the top of the module but after any\n # docstrings and __future__ imports.\n aliases = [\n ast.alias(six.moves.builtins.__name__, \"@py_builtins\"),\n ast.alias(\"_pytest.assertion.rewrite\", \"@pytest_ar\"),\n ]\n doc = getattr(mod, \"docstring\", None)\n expect_docstring = doc is None\n if doc is not None and self.is_rewrite_disabled(doc):\n return\n pos = 0\n lineno = 1\n for item in mod.body:\n if (\n expect_docstring\n and isinstance(item, ast.Expr)\n and isinstance(item.value, ast.Str)\n ):\n doc = item.value.s\n if self.is_rewrite_disabled(doc):\n return\n expect_docstring = False\n elif (\n not isinstance(item, ast.ImportFrom)\n or item.level > 0\n or item.module != \"__future__\"\n ):\n lineno = item.lineno\n break\n pos += 1\n else:\n lineno = item.lineno\n imports = [\n ast.Import([alias], lineno=lineno, col_offset=0) for alias in aliases\n ]\n mod.body[pos:pos] = imports\n # Collect asserts.\n nodes = [mod]\n while nodes:\n node = nodes.pop()\n for name, field in ast.iter_fields(node):\n if isinstance(field, list):\n new = []\n for i, child in enumerate(field):\n if isinstance(child, ast.Assert):\n # Transform assert.\n new.extend(self.visit(child))\n else:\n new.append(child)\n if isinstance(child, ast.AST):\n nodes.append(child)\n setattr(node, name, new)\n elif (\n isinstance(field, ast.AST)\n # Don't recurse into expressions as they can't contain\n # asserts.\n and not isinstance(field, ast.expr)\n ):\n nodes.append(field)"},{"col":0,"comment":"null","endLoc":55,"header":"def test_write_log_entry()","id":3349,"name":"test_write_log_entry","nodeType":"Function","startLoc":19,"text":"def test_write_log_entry():\n reslog = ResultLog(None, None)\n reslog.logfile = py.io.TextIO()\n reslog.write_log_entry(\"name\", \".\", \"\")\n entry = reslog.logfile.getvalue()\n assert entry[-1] == \"\\n\"\n entry_lines = entry.splitlines()\n assert len(entry_lines) == 1\n assert entry_lines[0] == \". name\"\n\n reslog.logfile = py.io.TextIO()\n reslog.write_log_entry(\"name\", \"s\", \"Skipped\")\n entry = reslog.logfile.getvalue()\n assert entry[-1] == \"\\n\"\n entry_lines = entry.splitlines()\n assert len(entry_lines) == 2\n assert entry_lines[0] == \"s name\"\n assert entry_lines[1] == \" Skipped\"\n\n reslog.logfile = py.io.TextIO()\n reslog.write_log_entry(\"name\", \"s\", \"Skipped\\n\")\n entry = reslog.logfile.getvalue()\n assert entry[-1] == \"\\n\"\n entry_lines = entry.splitlines()\n assert len(entry_lines) == 2\n assert entry_lines[0] == \"s name\"\n assert entry_lines[1] == \" Skipped\"\n\n reslog.logfile = py.io.TextIO()\n longrepr = \" tb1\\n tb 2\\nE tb3\\nSome Error\"\n reslog.write_log_entry(\"name\", \"F\", longrepr)\n entry = reslog.logfile.getvalue()\n assert entry[-1] == \"\\n\"\n entry_lines = entry.splitlines()\n assert len(entry_lines) == 5\n assert entry_lines[0] == \"F name\"\n assert entry_lines[1:] == [\" \" + line for line in longrepr.splitlines()]"},{"attributeType":"null","col":4,"comment":"null","endLoc":317,"id":3350,"name":"obj","nodeType":"Attribute","startLoc":317,"text":"obj"},{"className":"TestDoctests","col":0,"comment":"null","endLoc":742,"id":3351,"nodeType":"Class","startLoc":19,"text":"class TestDoctests(object):\n def test_collect_testtextfile(self, testdir):\n w = testdir.maketxtfile(whatever=\"\")\n checkfile = testdir.maketxtfile(\n test_something=\"\"\"\n alskdjalsdk\n >>> i = 5\n >>> i-1\n 4\n \"\"\"\n )\n\n for x in (testdir.tmpdir, checkfile):\n # print \"checking that %s returns custom items\" % (x,)\n items, reprec = testdir.inline_genitems(x)\n assert len(items) == 1\n assert isinstance(items[0], DoctestItem)\n assert isinstance(items[0].parent, DoctestTextfile)\n # Empty file has no items.\n items, reprec = testdir.inline_genitems(w)\n assert len(items) == 0\n\n def test_collect_module_empty(self, testdir):\n path = testdir.makepyfile(whatever=\"#\")\n for p in (path, testdir.tmpdir):\n items, reprec = testdir.inline_genitems(p, \"--doctest-modules\")\n assert len(items) == 0\n\n def test_collect_module_single_modulelevel_doctest(self, testdir):\n path = testdir.makepyfile(whatever='\"\"\">>> pass\"\"\"')\n for p in (path, testdir.tmpdir):\n items, reprec = testdir.inline_genitems(p, \"--doctest-modules\")\n assert len(items) == 1\n assert isinstance(items[0], DoctestItem)\n assert isinstance(items[0].parent, DoctestModule)\n\n def test_collect_module_two_doctest_one_modulelevel(self, testdir):\n path = testdir.makepyfile(\n whatever=\"\"\"\n '>>> x = None'\n def my_func():\n \">>> magic = 42 \"\n \"\"\"\n )\n for p in (path, testdir.tmpdir):\n items, reprec = testdir.inline_genitems(p, \"--doctest-modules\")\n assert len(items) == 2\n assert isinstance(items[0], DoctestItem)\n assert isinstance(items[1], DoctestItem)\n assert isinstance(items[0].parent, DoctestModule)\n assert items[0].parent is items[1].parent\n\n def test_collect_module_two_doctest_no_modulelevel(self, testdir):\n path = testdir.makepyfile(\n whatever=\"\"\"\n '# Empty'\n def my_func():\n \">>> magic = 42 \"\n def unuseful():\n '''\n # This is a function\n # >>> # it doesn't have any doctest\n '''\n def another():\n '''\n # This is another function\n >>> import os # this one does have a doctest\n '''\n \"\"\"\n )\n for p in (path, testdir.tmpdir):\n items, reprec = testdir.inline_genitems(p, \"--doctest-modules\")\n assert len(items) == 2\n assert isinstance(items[0], DoctestItem)\n assert isinstance(items[1], DoctestItem)\n assert isinstance(items[0].parent, DoctestModule)\n assert items[0].parent is items[1].parent\n\n def test_simple_doctestfile(self, testdir):\n p = testdir.maketxtfile(\n test_doc=\"\"\"\n >>> x = 1\n >>> x == 1\n False\n \"\"\"\n )\n reprec = testdir.inline_run(p)\n reprec.assertoutcome(failed=1)\n\n def test_new_pattern(self, testdir):\n p = testdir.maketxtfile(\n xdoc=\"\"\"\n >>> x = 1\n >>> x == 1\n False\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-glob=x*.txt\")\n reprec.assertoutcome(failed=1)\n\n def test_multiple_patterns(self, testdir):\n \"\"\"Test support for multiple --doctest-glob arguments (#1255).\n \"\"\"\n testdir.maketxtfile(\n xdoc=\"\"\"\n >>> 1\n 1\n \"\"\"\n )\n testdir.makefile(\n \".foo\",\n test=\"\"\"\n >>> 1\n 1\n \"\"\",\n )\n testdir.maketxtfile(\n test_normal=\"\"\"\n >>> 1\n 1\n \"\"\"\n )\n expected = {\"xdoc.txt\", \"test.foo\", \"test_normal.txt\"}\n assert {x.basename for x in testdir.tmpdir.listdir()} == expected\n args = [\"--doctest-glob=xdoc*.txt\", \"--doctest-glob=*.foo\"]\n result = testdir.runpytest(*args)\n result.stdout.fnmatch_lines([\"*test.foo *\", \"*xdoc.txt *\", \"*2 passed*\"])\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*test_normal.txt *\", \"*1 passed*\"])\n\n @pytest.mark.parametrize(\n \" test_string, encoding\",\n [(u\"foo\", \"ascii\"), (u\"öäü\", \"latin1\"), (u\"öäü\", \"utf-8\")],\n )\n def test_encoding(self, testdir, test_string, encoding):\n \"\"\"Test support for doctest_encoding ini option.\n \"\"\"\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_encoding={}\n \"\"\".format(\n encoding\n )\n )\n doctest = u\"\"\"\n >>> u\"{}\"\n {}\n \"\"\".format(\n test_string, repr(test_string)\n )\n testdir._makefile(\".txt\", [doctest], {}, encoding=encoding)\n\n result = testdir.runpytest()\n\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_doctest_unexpected_exception(self, testdir):\n testdir.maketxtfile(\n \"\"\"\n >>> i = 0\n >>> 0 / i\n 2\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines(\n [\n \"*unexpected_exception*\",\n \"*>>> i = 0*\",\n \"*>>> 0 / i*\",\n \"*UNEXPECTED*ZeroDivision*\",\n ]\n )\n\n def test_doctest_skip(self, testdir):\n testdir.maketxtfile(\n \"\"\"\n >>> 1\n 1\n >>> import pytest\n >>> pytest.skip(\"\")\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines([\"*1 skipped*\"])\n\n def test_docstring_partial_context_around_error(self, testdir):\n \"\"\"Test that we show some context before the actual line of a failing\n doctest.\n \"\"\"\n testdir.makepyfile(\n '''\n def foo():\n \"\"\"\n text-line-1\n text-line-2\n text-line-3\n text-line-4\n text-line-5\n text-line-6\n text-line-7\n text-line-8\n text-line-9\n text-line-10\n text-line-11\n >>> 1 + 1\n 3\n\n text-line-after\n \"\"\"\n '''\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines(\n [\n \"*docstring_partial_context_around_error*\",\n \"005*text-line-3\",\n \"006*text-line-4\",\n \"013*text-line-11\",\n \"014*>>> 1 + 1\",\n \"Expected:\",\n \" 3\",\n \"Got:\",\n \" 2\",\n ]\n )\n # lines below should be trimmed out\n assert \"text-line-2\" not in result.stdout.str()\n assert \"text-line-after\" not in result.stdout.str()\n\n def test_docstring_full_context_around_error(self, testdir):\n \"\"\"Test that we show the whole context before the actual line of a failing\n doctest, provided that the context is up to 10 lines long.\n \"\"\"\n testdir.makepyfile(\n '''\n def foo():\n \"\"\"\n text-line-1\n text-line-2\n\n >>> 1 + 1\n 3\n \"\"\"\n '''\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines(\n [\n \"*docstring_full_context_around_error*\",\n \"003*text-line-1\",\n \"004*text-line-2\",\n \"006*>>> 1 + 1\",\n \"Expected:\",\n \" 3\",\n \"Got:\",\n \" 2\",\n ]\n )\n\n def test_doctest_linedata_missing(self, testdir):\n testdir.tmpdir.join(\"hello.py\").write(\n textwrap.dedent(\n \"\"\"\\\n class Fun(object):\n @property\n def test(self):\n '''\n >>> a = 1\n >>> 1/0\n '''\n \"\"\"\n )\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines(\n [\n \"*hello*\",\n \"*EXAMPLE LOCATION UNKNOWN, not showing all tests of that example*\",\n \"*1/0*\",\n \"*UNEXPECTED*ZeroDivision*\",\n \"*1 failed*\",\n ]\n )\n\n def test_doctest_unex_importerror_only_txt(self, testdir):\n testdir.maketxtfile(\n \"\"\"\n >>> import asdalsdkjaslkdjasd\n >>>\n \"\"\"\n )\n result = testdir.runpytest()\n # doctest is never executed because of error during hello.py collection\n result.stdout.fnmatch_lines(\n [\n \"*>>> import asdals*\",\n \"*UNEXPECTED*{e}*\".format(e=MODULE_NOT_FOUND_ERROR),\n \"{e}: No module named *asdal*\".format(e=MODULE_NOT_FOUND_ERROR),\n ]\n )\n\n def test_doctest_unex_importerror_with_module(self, testdir):\n testdir.tmpdir.join(\"hello.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import asdalsdkjaslkdjasd\n \"\"\"\n )\n )\n testdir.maketxtfile(\n \"\"\"\n >>> import hello\n >>>\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\")\n # doctest is never executed because of error during hello.py collection\n result.stdout.fnmatch_lines(\n [\n \"*ERROR collecting hello.py*\",\n \"*{e}: No module named *asdals*\".format(e=MODULE_NOT_FOUND_ERROR),\n \"*Interrupted: 1 errors during collection*\",\n ]\n )\n\n def test_doctestmodule(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n '''\n >>> x = 1\n >>> x == 1\n False\n\n '''\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(failed=1)\n\n def test_doctestmodule_external_and_issue116(self, testdir):\n p = testdir.mkpydir(\"hello\")\n p.join(\"__init__.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def somefunc():\n '''\n >>> i = 0\n >>> i + 1\n 2\n '''\n \"\"\"\n )\n )\n result = testdir.runpytest(p, \"--doctest-modules\")\n result.stdout.fnmatch_lines(\n [\n \"003 *>>> i = 0\",\n \"004 *>>> i + 1\",\n \"*Expected:\",\n \"* 2\",\n \"*Got:\",\n \"* 1\",\n \"*:4: DocTestFailure\",\n ]\n )\n\n def test_txtfile_failing(self, testdir):\n p = testdir.maketxtfile(\n \"\"\"\n >>> i = 0\n >>> i + 1\n 2\n \"\"\"\n )\n result = testdir.runpytest(p, \"-s\")\n result.stdout.fnmatch_lines(\n [\n \"001 >>> i = 0\",\n \"002 >>> i + 1\",\n \"Expected:\",\n \" 2\",\n \"Got:\",\n \" 1\",\n \"*test_txtfile_failing.txt:2: DocTestFailure\",\n ]\n )\n\n def test_txtfile_with_fixtures(self, testdir):\n p = testdir.maketxtfile(\n \"\"\"\n >>> dir = getfixture('tmpdir')\n >>> type(dir).__name__\n 'LocalPath'\n \"\"\"\n )\n reprec = testdir.inline_run(p)\n reprec.assertoutcome(passed=1)\n\n def test_txtfile_with_usefixtures_in_ini(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n usefixtures = myfixture\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture\n def myfixture(monkeypatch):\n monkeypatch.setenv(\"HELLO\", \"WORLD\")\n \"\"\"\n )\n\n p = testdir.maketxtfile(\n \"\"\"\n >>> import os\n >>> os.environ[\"HELLO\"]\n 'WORLD'\n \"\"\"\n )\n reprec = testdir.inline_run(p)\n reprec.assertoutcome(passed=1)\n\n def test_doctestmodule_with_fixtures(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n '''\n >>> dir = getfixture('tmpdir')\n >>> type(dir).__name__\n 'LocalPath'\n '''\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(passed=1)\n\n def test_doctestmodule_three_tests(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n '''\n >>> dir = getfixture('tmpdir')\n >>> type(dir).__name__\n 'LocalPath'\n '''\n def my_func():\n '''\n >>> magic = 42\n >>> magic - 42\n 0\n '''\n def unuseful():\n pass\n def another():\n '''\n >>> import os\n >>> os is os\n True\n '''\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(passed=3)\n\n def test_doctestmodule_two_tests_one_fail(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n class MyClass(object):\n def bad_meth(self):\n '''\n >>> magic = 42\n >>> magic\n 0\n '''\n def nice_meth(self):\n '''\n >>> magic = 42\n >>> magic - 42\n 0\n '''\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(failed=1, passed=1)\n\n def test_ignored_whitespace(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_optionflags = ELLIPSIS NORMALIZE_WHITESPACE\n \"\"\"\n )\n p = testdir.makepyfile(\n \"\"\"\n class MyClass(object):\n '''\n >>> a = \"foo \"\n >>> print(a)\n foo\n '''\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(passed=1)\n\n def test_non_ignored_whitespace(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_optionflags = ELLIPSIS\n \"\"\"\n )\n p = testdir.makepyfile(\n \"\"\"\n class MyClass(object):\n '''\n >>> a = \"foo \"\n >>> print(a)\n foo\n '''\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(failed=1, passed=0)\n\n def test_ignored_whitespace_glob(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_optionflags = ELLIPSIS NORMALIZE_WHITESPACE\n \"\"\"\n )\n p = testdir.maketxtfile(\n xdoc=\"\"\"\n >>> a = \"foo \"\n >>> print(a)\n foo\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-glob=x*.txt\")\n reprec.assertoutcome(passed=1)\n\n def test_non_ignored_whitespace_glob(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_optionflags = ELLIPSIS\n \"\"\"\n )\n p = testdir.maketxtfile(\n xdoc=\"\"\"\n >>> a = \"foo \"\n >>> print(a)\n foo\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-glob=x*.txt\")\n reprec.assertoutcome(failed=1, passed=0)\n\n def test_contains_unicode(self, testdir):\n \"\"\"Fix internal error with docstrings containing non-ascii characters.\n \"\"\"\n testdir.makepyfile(\n u'''\n # -*- coding: utf-8 -*-\n def foo():\n \"\"\"\n >>> name = 'с' # not letter 'c' but instead Cyrillic 's'.\n 'anything'\n \"\"\"\n '''\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines([\"Got nothing\", \"* 1 failed in*\"])\n\n def test_ignore_import_errors_on_doctest(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import asdf\n\n def add_one(x):\n '''\n >>> add_one(1)\n 2\n '''\n return x + 1\n \"\"\"\n )\n\n reprec = testdir.inline_run(\n p, \"--doctest-modules\", \"--doctest-ignore-import-errors\"\n )\n reprec.assertoutcome(skipped=1, failed=1, passed=0)\n\n def test_junit_report_for_doctest(self, testdir):\n \"\"\"\n #713: Fix --junit-xml option when used with --doctest-modules.\n \"\"\"\n p = testdir.makepyfile(\n \"\"\"\n def foo():\n '''\n >>> 1 + 1\n 3\n '''\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\", \"--junit-xml=junit.xml\")\n reprec.assertoutcome(failed=1)\n\n def test_unicode_doctest(self, testdir):\n \"\"\"\n Test case for issue 2434: DecodeError on Python 2 when doctest contains non-ascii\n characters.\n \"\"\"\n p = testdir.maketxtfile(\n test_unicode_doctest=\"\"\"\n .. doctest::\n\n >>> print(\n ... \"Hi\\\\n\\\\nByé\")\n Hi\n ...\n Byé\n >>> 1/0 # Byé\n 1\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\"*UNEXPECTED EXCEPTION: ZeroDivisionError*\", \"*1 failed*\"]\n )\n\n def test_unicode_doctest_module(self, testdir):\n \"\"\"\n Test case for issue 2434: DecodeError on Python 2 when doctest docstring\n contains non-ascii characters.\n \"\"\"\n p = testdir.makepyfile(\n test_unicode_doctest_module=\"\"\"\n # -*- coding: utf-8 -*-\n from __future__ import unicode_literals\n\n def fix_bad_unicode(text):\n '''\n >>> print(fix_bad_unicode('único'))\n único\n '''\n return \"único\"\n \"\"\"\n )\n result = testdir.runpytest(p, \"--doctest-modules\")\n result.stdout.fnmatch_lines([\"* 1 passed *\"])\n\n def test_print_unicode_value(self, testdir):\n \"\"\"\n Test case for issue 3583: Printing Unicode in doctest under Python 2.7\n doesn't work\n \"\"\"\n p = testdir.maketxtfile(\n test_print_unicode_value=r\"\"\"\n Here is a doctest::\n\n >>> print(u'\\xE5\\xE9\\xEE\\xF8\\xFC')\n åéîøü\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"* 1 passed *\"])\n\n def test_reportinfo(self, testdir):\n \"\"\"\n Test case to make sure that DoctestItem.reportinfo() returns lineno.\n \"\"\"\n p = testdir.makepyfile(\n test_reportinfo=\"\"\"\n def foo(x):\n '''\n >>> foo('a')\n 'b'\n '''\n return 'c'\n \"\"\"\n )\n items, reprec = testdir.inline_genitems(p, \"--doctest-modules\")\n reportinfo = items[0].reportinfo()\n assert reportinfo[1] == 1\n\n def test_valid_setup_py(self, testdir):\n \"\"\"\n Test to make sure that pytest ignores valid setup.py files when ran\n with --doctest-modules\n \"\"\"\n p = testdir.makepyfile(\n setup=\"\"\"\n from setuptools import setup, find_packages\n setup(name='sample',\n version='0.0',\n description='description',\n packages=find_packages()\n )\n \"\"\"\n )\n result = testdir.runpytest(p, \"--doctest-modules\")\n result.stdout.fnmatch_lines([\"*collected 0 items*\"])\n\n def test_invalid_setup_py(self, testdir):\n \"\"\"\n Test to make sure that pytest reads setup.py files that are not used\n for python packages when ran with --doctest-modules\n \"\"\"\n p = testdir.makepyfile(\n setup=\"\"\"\n def test_foo():\n return 'bar'\n \"\"\"\n )\n result = testdir.runpytest(p, \"--doctest-modules\")\n result.stdout.fnmatch_lines([\"*collected 1 item*\"])"},{"fileName":"truncate.py","filePath":"src/_pytest/assertion","id":3352,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"\nUtilities for truncating assertion output.\n\nCurrent default behaviour is to truncate assertion explanations at\n~8 terminal lines, unless running in \"-vv\" mode or running on CI.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nimport six\n\nDEFAULT_MAX_LINES = 8\nDEFAULT_MAX_CHARS = 8 * 80\nUSAGE_MSG = \"use '-vv' to show\"\n\n\ndef truncate_if_required(explanation, item, max_length=None):\n \"\"\"\n Truncate this assertion explanation if the given test item is eligible.\n \"\"\"\n if _should_truncate_item(item):\n return _truncate_explanation(explanation)\n return explanation\n\n\ndef _should_truncate_item(item):\n \"\"\"\n Whether or not this test item is eligible for truncation.\n \"\"\"\n verbose = item.config.option.verbose\n return verbose < 2 and not _running_on_ci()\n\n\ndef _running_on_ci():\n \"\"\"Check if we're currently running on a CI system.\"\"\"\n env_vars = [\"CI\", \"BUILD_NUMBER\"]\n return any(var in os.environ for var in env_vars)\n\n\ndef _truncate_explanation(input_lines, max_lines=None, max_chars=None):\n \"\"\"\n Truncate given list of strings that makes up the assertion explanation.\n\n Truncates to either 8 lines, or 640 characters - whichever the input reaches\n first. The remaining lines will be replaced by a usage message.\n \"\"\"\n\n if max_lines is None:\n max_lines = DEFAULT_MAX_LINES\n if max_chars is None:\n max_chars = DEFAULT_MAX_CHARS\n\n # Check if truncation required\n input_char_count = len(\"\".join(input_lines))\n if len(input_lines) <= max_lines and input_char_count <= max_chars:\n return input_lines\n\n # Truncate first to max_lines, and then truncate to max_chars if max_chars\n # is exceeded.\n truncated_explanation = input_lines[:max_lines]\n truncated_explanation = _truncate_by_char_count(truncated_explanation, max_chars)\n\n # Add ellipsis to final line\n truncated_explanation[-1] = truncated_explanation[-1] + \"...\"\n\n # Append useful message to explanation\n truncated_line_count = len(input_lines) - len(truncated_explanation)\n truncated_line_count += 1 # Account for the part-truncated final line\n msg = \"...Full output truncated\"\n if truncated_line_count == 1:\n msg += \" ({} line hidden)\".format(truncated_line_count)\n else:\n msg += \" ({} lines hidden)\".format(truncated_line_count)\n msg += \", {}\".format(USAGE_MSG)\n truncated_explanation.extend([six.text_type(\"\"), six.text_type(msg)])\n return truncated_explanation\n\n\ndef _truncate_by_char_count(input_lines, max_chars):\n # Check if truncation required\n if len(\"\".join(input_lines)) <= max_chars:\n return input_lines\n\n # Find point at which input length exceeds total allowed length\n iterated_char_count = 0\n for iterated_index, input_line in enumerate(input_lines):\n if iterated_char_count + len(input_line) > max_chars:\n break\n iterated_char_count += len(input_line)\n\n # Create truncated explanation with modified final line\n truncated_result = input_lines[:iterated_index]\n final_line = input_lines[iterated_index]\n if final_line:\n final_line_truncate_point = max_chars - iterated_char_count\n final_line = final_line[:final_line_truncate_point]\n truncated_result.append(final_line)\n return truncated_result\n"},{"attributeType":"int","col":0,"comment":"null","endLoc":16,"id":3353,"name":"DEFAULT_MAX_LINES","nodeType":"Attribute","startLoc":16,"text":"DEFAULT_MAX_LINES"},{"attributeType":"int","col":0,"comment":"null","endLoc":17,"id":3354,"name":"DEFAULT_MAX_CHARS","nodeType":"Attribute","startLoc":17,"text":"DEFAULT_MAX_CHARS"},{"col":4,"comment":"null","endLoc":39,"header":"def test_collect_testtextfile(self, testdir)","id":3357,"name":"test_collect_testtextfile","nodeType":"Function","startLoc":20,"text":"def test_collect_testtextfile(self, testdir):\n w = testdir.maketxtfile(whatever=\"\")\n checkfile = testdir.maketxtfile(\n test_something=\"\"\"\n alskdjalsdk\n >>> i = 5\n >>> i-1\n 4\n \"\"\"\n )\n\n for x in (testdir.tmpdir, checkfile):\n # print \"checking that %s returns custom items\" % (x,)\n items, reprec = testdir.inline_genitems(x)\n assert len(items) == 1\n assert isinstance(items[0], DoctestItem)\n assert isinstance(items[0].parent, DoctestTextfile)\n # Empty file has no items.\n items, reprec = testdir.inline_genitems(w)\n assert len(items) == 0"},{"col":4,"comment":"null","endLoc":143,"header":"def __str__(self)","id":3358,"name":"__str__","nodeType":"Function","startLoc":142,"text":"def __str__(self):\n return \"\\n\".join(self.lines)"},{"attributeType":"null","col":4,"comment":"null","endLoc":25,"id":3359,"name":"_compilecounter","nodeType":"Attribute","startLoc":25,"text":"_compilecounter"},{"attributeType":"null","col":4,"comment":"null","endLoc":53,"id":3360,"name":"__hash__","nodeType":"Attribute","startLoc":53,"text":"__hash__"},{"attributeType":"null","col":8,"comment":"null","endLoc":28,"id":3361,"name":"lines","nodeType":"Attribute","startLoc":28,"text":"self.lines"},{"col":0,"comment":"","endLoc":2,"header":"__init__.py#","id":3362,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" python inspection/code generation API \"\"\""},{"attributeType":"str","col":0,"comment":"null","endLoc":18,"id":3363,"name":"USAGE_MSG","nodeType":"Attribute","startLoc":18,"text":"USAGE_MSG"},{"col":0,"comment":"","endLoc":7,"header":"truncate.py#","id":3364,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"\nUtilities for truncating assertion output.\n\nCurrent default behaviour is to truncate assertion explanations at\n~8 terminal lines, unless running in \"-vv\" mode or running on CI.\n\"\"\"\n\nDEFAULT_MAX_LINES = 8\n\nDEFAULT_MAX_CHARS = 8 * 80\n\nUSAGE_MSG = \"use '-vv' to show\""},{"id":3365,"name":"src/_pytest/_io","nodeType":"Package"},{"fileName":"saferepr.py","filePath":"src/_pytest/_io","id":3366,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pprint\n\nfrom six.moves import reprlib\n\n\ndef _call_and_format_exception(call, x, *args):\n try:\n # Try the vanilla repr and make sure that the result is a string\n return call(x, *args)\n except Exception as exc:\n exc_name = type(exc).__name__\n try:\n exc_info = str(exc)\n except Exception:\n exc_info = \"unknown\"\n return '<[%s(\"%s\") raised in repr()] %s object at 0x%x>' % (\n exc_name,\n exc_info,\n x.__class__.__name__,\n id(x),\n )\n\n\nclass SafeRepr(reprlib.Repr):\n \"\"\"subclass of repr.Repr that limits the resulting size of repr()\n and includes information on exceptions raised during the call.\n \"\"\"\n\n def repr(self, x):\n return self._callhelper(reprlib.Repr.repr, self, x)\n\n def repr_unicode(self, x, level):\n # Strictly speaking wrong on narrow builds\n def repr(u):\n if \"'\" not in u:\n return u\"'%s'\" % u\n elif '\"' not in u:\n return u'\"%s\"' % u\n else:\n return u\"'%s'\" % u.replace(\"'\", r\"\\'\")\n\n s = repr(x[: self.maxstring])\n if len(s) > self.maxstring:\n i = max(0, (self.maxstring - 3) // 2)\n j = max(0, self.maxstring - 3 - i)\n s = repr(x[:i] + x[len(x) - j :])\n s = s[:i] + \"...\" + s[len(s) - j :]\n return s\n\n def repr_instance(self, x, level):\n return self._callhelper(repr, x)\n\n def _callhelper(self, call, x, *args):\n s = _call_and_format_exception(call, x, *args)\n if len(s) > self.maxsize:\n i = max(0, (self.maxsize - 3) // 2)\n j = max(0, self.maxsize - 3 - i)\n s = s[:i] + \"...\" + s[len(s) - j :]\n return s\n\n\ndef safeformat(obj):\n \"\"\"return a pretty printed string for the given object.\n Failing __repr__ functions of user instances will be represented\n with a short exception info.\n \"\"\"\n return _call_and_format_exception(pprint.pformat, obj)\n\n\ndef saferepr(obj, maxsize=240):\n \"\"\"return a size-limited safe repr-string for the given object.\n Failing __repr__ functions of user instances will be represented\n with a short exception info and 'saferepr' generally takes\n care to never raise exceptions itself. This function is a wrapper\n around the Repr/reprlib functionality of the standard 2.6 lib.\n \"\"\"\n # review exception handling\n srepr = SafeRepr()\n srepr.maxstring = maxsize\n srepr.maxsize = maxsize\n srepr.maxother = 160\n return srepr.repr(obj)\n"},{"className":"SafeRepr","col":0,"comment":"subclass of repr.Repr that limits the resulting size of repr()\n and includes information on exceptions raised during the call.\n ","endLoc":60,"id":3367,"nodeType":"Class","startLoc":25,"text":"class SafeRepr(reprlib.Repr):\n \"\"\"subclass of repr.Repr that limits the resulting size of repr()\n and includes information on exceptions raised during the call.\n \"\"\"\n\n def repr(self, x):\n return self._callhelper(reprlib.Repr.repr, self, x)\n\n def repr_unicode(self, x, level):\n # Strictly speaking wrong on narrow builds\n def repr(u):\n if \"'\" not in u:\n return u\"'%s'\" % u\n elif '\"' not in u:\n return u'\"%s\"' % u\n else:\n return u\"'%s'\" % u.replace(\"'\", r\"\\'\")\n\n s = repr(x[: self.maxstring])\n if len(s) > self.maxstring:\n i = max(0, (self.maxstring - 3) // 2)\n j = max(0, self.maxstring - 3 - i)\n s = repr(x[:i] + x[len(x) - j :])\n s = s[:i] + \"...\" + s[len(s) - j :]\n return s\n\n def repr_instance(self, x, level):\n return self._callhelper(repr, x)\n\n def _callhelper(self, call, x, *args):\n s = _call_and_format_exception(call, x, *args)\n if len(s) > self.maxsize:\n i = max(0, (self.maxsize - 3) // 2)\n j = max(0, self.maxsize - 3 - i)\n s = s[:i] + \"...\" + s[len(s) - j :]\n return s"},{"className":"Repr","col":0,"comment":"null","endLoc":61,"id":3368,"nodeType":"Class","startLoc":14,"text":"class Repr:\n maxlevel: int\n maxdict: int\n maxlist: int\n maxtuple: int\n maxset: int\n maxfrozenset: int\n maxdeque: int\n maxarray: int\n maxlong: int\n maxstring: int\n maxother: int\n if sys.version_info >= (3, 11):\n fillvalue: str\n if sys.version_info >= (3, 12):\n indent: str | int | None\n\n if sys.version_info >= (3, 12):\n def __init__(\n self,\n *,\n maxlevel: int = 6,\n maxtuple: int = 6,\n maxlist: int = 6,\n maxarray: int = 5,\n maxdict: int = 4,\n maxset: int = 6,\n maxfrozenset: int = 6,\n maxdeque: int = 6,\n maxstring: int = 30,\n maxlong: int = 40,\n maxother: int = 30,\n fillvalue: str = \"...\",\n indent: str | int | None = None,\n ) -> None: ...\n\n def repr(self, x: Any) -> str: ...\n def repr1(self, x: Any, level: int) -> str: ...\n def repr_tuple(self, x: tuple[Any, ...], level: int) -> str: ...\n def repr_list(self, x: list[Any], level: int) -> str: ...\n def repr_array(self, x: array[Any], level: int) -> str: ...\n def repr_set(self, x: set[Any], level: int) -> str: ...\n def repr_frozenset(self, x: frozenset[Any], level: int) -> str: ...\n def repr_deque(self, x: deque[Any], level: int) -> str: ...\n def repr_dict(self, x: dict[Any, Any], level: int) -> str: ...\n def repr_str(self, x: str, level: int) -> str: ...\n def repr_int(self, x: int, level: int) -> str: ...\n def repr_instance(self, x: Any, level: int) -> str: ..."},{"col":4,"comment":"null","endLoc":45,"header":"def test_collect_module_empty(self, testdir)","id":3369,"name":"test_collect_module_empty","nodeType":"Function","startLoc":41,"text":"def test_collect_module_empty(self, testdir):\n path = testdir.makepyfile(whatever=\"#\")\n for p in (path, testdir.tmpdir):\n items, reprec = testdir.inline_genitems(p, \"--doctest-modules\")\n assert len(items) == 0"},{"id":3370,"name":"testing/example_scripts/acceptance","nodeType":"Package"},{"fileName":"fixture_mock_integration.py","filePath":"testing/example_scripts/acceptance","id":3371,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"Reproduces issue #3774\"\"\"\n\ntry:\n import mock\nexcept ImportError:\n import unittest.mock as mock\n\nimport pytest\n\nconfig = {\"mykey\": \"ORIGINAL\"}\n\n\n@pytest.fixture(scope=\"function\")\n@mock.patch.dict(config, {\"mykey\": \"MOCKED\"})\ndef my_fixture():\n return config[\"mykey\"]\n\n\ndef test_foobar(my_fixture):\n assert my_fixture == \"MOCKED\"\n"},{"col":4,"comment":"null","endLoc":53,"header":"def test_collect_module_single_modulelevel_doctest(self, testdir)","id":3372,"name":"test_collect_module_single_modulelevel_doctest","nodeType":"Function","startLoc":47,"text":"def test_collect_module_single_modulelevel_doctest(self, testdir):\n path = testdir.makepyfile(whatever='\"\"\">>> pass\"\"\"')\n for p in (path, testdir.tmpdir):\n items, reprec = testdir.inline_genitems(p, \"--doctest-modules\")\n assert len(items) == 1\n assert isinstance(items[0], DoctestItem)\n assert isinstance(items[0].parent, DoctestModule)"},{"col":0,"comment":"null","endLoc":17,"header":"@pytest.fixture(scope=\"function\")\n@mock.patch.dict(config, {\"mykey\"","id":3373,"name":"my_fixture","nodeType":"Function","startLoc":14,"text":"@pytest.fixture(scope=\"function\")\n@mock.patch.dict(config, {\"mykey\": \"MOCKED\"})\ndef my_fixture():\n return config[\"mykey\"]"},{"col":4,"comment":"null","endLoc":50,"header":"def repr(self, x: Any) -> str","id":3374,"name":"repr","nodeType":"Function","startLoc":50,"text":"def repr(self, x: Any) -> str: ..."},{"col":4,"comment":"null","endLoc":51,"header":"def repr1(self, x: Any, level: int) -> str","id":3375,"name":"repr1","nodeType":"Function","startLoc":51,"text":"def repr1(self, x: Any, level: int) -> str: ..."},{"col":4,"comment":"null","endLoc":52,"header":"def repr_tuple(self, x: tuple[Any, ...], level: int) -> str","id":3376,"name":"repr_tuple","nodeType":"Function","startLoc":52,"text":"def repr_tuple(self, x: tuple[Any, ...], level: int) -> str: ..."},{"col":4,"comment":"null","endLoc":53,"header":"def repr_list(self, x: list[Any], level: int) -> str","id":3377,"name":"repr_list","nodeType":"Function","startLoc":53,"text":"def repr_list(self, x: list[Any], level: int) -> str: ..."},{"col":4,"comment":"null","endLoc":54,"header":"def repr_array(self, x: array[Any], level: int) -> str","id":3378,"name":"repr_array","nodeType":"Function","startLoc":54,"text":"def repr_array(self, x: array[Any], level: int) -> str: ..."},{"col":4,"comment":"null","endLoc":55,"header":"def repr_set(self, x: set[Any], level: int) -> str","id":3379,"name":"repr_set","nodeType":"Function","startLoc":55,"text":"def repr_set(self, x: set[Any], level: int) -> str: ..."},{"col":4,"comment":"null","endLoc":56,"header":"def repr_frozenset(self, x: frozenset[Any], level: int) -> str","id":3380,"name":"repr_frozenset","nodeType":"Function","startLoc":56,"text":"def repr_frozenset(self, x: frozenset[Any], level: int) -> str: ..."},{"col":4,"comment":"null","endLoc":57,"header":"def repr_deque(self, x: deque[Any], level: int) -> str","id":3381,"name":"repr_deque","nodeType":"Function","startLoc":57,"text":"def repr_deque(self, x: deque[Any], level: int) -> str: ..."},{"col":4,"comment":"null","endLoc":58,"header":"def repr_dict(self, x: dict[Any, Any], level: int) -> str","id":3382,"name":"repr_dict","nodeType":"Function","startLoc":58,"text":"def repr_dict(self, x: dict[Any, Any], level: int) -> str: ..."},{"col":4,"comment":"null","endLoc":59,"header":"def repr_str(self, x: str, level: int) -> str","id":3383,"name":"repr_str","nodeType":"Function","startLoc":59,"text":"def repr_str(self, x: str, level: int) -> str: ..."},{"col":4,"comment":"null","endLoc":60,"header":"def repr_int(self, x: int, level: int) -> str","id":3384,"name":"repr_int","nodeType":"Function","startLoc":60,"text":"def repr_int(self, x: int, level: int) -> str: ..."},{"col":4,"comment":"null","endLoc":61,"header":"def repr_instance(self, x: Any, level: int) -> str","id":3385,"name":"repr_instance","nodeType":"Function","startLoc":61,"text":"def repr_instance(self, x: Any, level: int) -> str: ..."},{"attributeType":"int","col":4,"comment":"null","endLoc":15,"id":3386,"name":"maxlevel","nodeType":"Attribute","startLoc":15,"text":"maxlevel"},{"col":4,"comment":"null","endLoc":69,"header":"def test_collect_module_two_doctest_one_modulelevel(self, testdir)","id":3387,"name":"test_collect_module_two_doctest_one_modulelevel","nodeType":"Function","startLoc":55,"text":"def test_collect_module_two_doctest_one_modulelevel(self, testdir):\n path = testdir.makepyfile(\n whatever=\"\"\"\n '>>> x = None'\n def my_func():\n \">>> magic = 42 \"\n \"\"\"\n )\n for p in (path, testdir.tmpdir):\n items, reprec = testdir.inline_genitems(p, \"--doctest-modules\")\n assert len(items) == 2\n assert isinstance(items[0], DoctestItem)\n assert isinstance(items[1], DoctestItem)\n assert isinstance(items[0].parent, DoctestModule)\n assert items[0].parent is items[1].parent"},{"attributeType":"int","col":4,"comment":"null","endLoc":16,"id":3388,"name":"maxdict","nodeType":"Attribute","startLoc":16,"text":"maxdict"},{"attributeType":"int","col":4,"comment":"null","endLoc":17,"id":3389,"name":"maxlist","nodeType":"Attribute","startLoc":17,"text":"maxlist"},{"attributeType":"int","col":4,"comment":"null","endLoc":18,"id":3390,"name":"maxtuple","nodeType":"Attribute","startLoc":18,"text":"maxtuple"},{"attributeType":"int","col":4,"comment":"null","endLoc":19,"id":3391,"name":"maxset","nodeType":"Attribute","startLoc":19,"text":"maxset"},{"attributeType":"int","col":4,"comment":"null","endLoc":20,"id":3392,"name":"maxfrozenset","nodeType":"Attribute","startLoc":20,"text":"maxfrozenset"},{"attributeType":"int","col":4,"comment":"null","endLoc":21,"id":3393,"name":"maxdeque","nodeType":"Attribute","startLoc":21,"text":"maxdeque"},{"attributeType":"int","col":4,"comment":"null","endLoc":22,"id":3394,"name":"maxarray","nodeType":"Attribute","startLoc":22,"text":"maxarray"},{"attributeType":"int","col":4,"comment":"null","endLoc":23,"id":3395,"name":"maxlong","nodeType":"Attribute","startLoc":23,"text":"maxlong"},{"attributeType":"int","col":4,"comment":"null","endLoc":24,"id":3396,"name":"maxstring","nodeType":"Attribute","startLoc":24,"text":"maxstring"},{"attributeType":"int","col":4,"comment":"null","endLoc":25,"id":3397,"name":"maxother","nodeType":"Attribute","startLoc":25,"text":"maxother"},{"col":4,"comment":"null","endLoc":31,"header":"def repr(self, x)","id":3398,"name":"repr","nodeType":"Function","startLoc":30,"text":"def repr(self, x):\n return self._callhelper(reprlib.Repr.repr, self, x)"},{"col":4,"comment":"null","endLoc":95,"header":"def test_collect_module_two_doctest_no_modulelevel(self, testdir)","id":3399,"name":"test_collect_module_two_doctest_no_modulelevel","nodeType":"Function","startLoc":71,"text":"def test_collect_module_two_doctest_no_modulelevel(self, testdir):\n path = testdir.makepyfile(\n whatever=\"\"\"\n '# Empty'\n def my_func():\n \">>> magic = 42 \"\n def unuseful():\n '''\n # This is a function\n # >>> # it doesn't have any doctest\n '''\n def another():\n '''\n # This is another function\n >>> import os # this one does have a doctest\n '''\n \"\"\"\n )\n for p in (path, testdir.tmpdir):\n items, reprec = testdir.inline_genitems(p, \"--doctest-modules\")\n assert len(items) == 2\n assert isinstance(items[0], DoctestItem)\n assert isinstance(items[1], DoctestItem)\n assert isinstance(items[0].parent, DoctestModule)\n assert items[0].parent is items[1].parent"},{"col":4,"comment":"null","endLoc":106,"header":"def test_simple_doctestfile(self, testdir)","id":3400,"name":"test_simple_doctestfile","nodeType":"Function","startLoc":97,"text":"def test_simple_doctestfile(self, testdir):\n p = testdir.maketxtfile(\n test_doc=\"\"\"\n >>> x = 1\n >>> x == 1\n False\n \"\"\"\n )\n reprec = testdir.inline_run(p)\n reprec.assertoutcome(failed=1)"},{"col":4,"comment":"null","endLoc":117,"header":"def test_new_pattern(self, testdir)","id":3402,"name":"test_new_pattern","nodeType":"Function","startLoc":108,"text":"def test_new_pattern(self, testdir):\n p = testdir.maketxtfile(\n xdoc=\"\"\"\n >>> x = 1\n >>> x == 1\n False\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-glob=x*.txt\")\n reprec.assertoutcome(failed=1)"},{"col":4,"comment":"null","endLoc":728,"header":"def cwd_relative_nodeid(self, nodeid)","id":3405,"name":"cwd_relative_nodeid","nodeType":"Function","startLoc":723,"text":"def cwd_relative_nodeid(self, nodeid):\n # nodeid's are relative to the rootpath, compute relative to cwd\n if self.invocation_dir != self.rootdir:\n fullpath = self.rootdir.join(nodeid)\n nodeid = self.invocation_dir.bestrelpath(fullpath)\n return nodeid"},{"attributeType":"property","col":4,"comment":"null","endLoc":218,"id":3406,"name":"args","nodeType":"Attribute","startLoc":218,"text":"args"},{"attributeType":"property","col":4,"comment":"null","endLoc":219,"id":3407,"name":"kwargs","nodeType":"Attribute","startLoc":219,"text":"kwargs"},{"className":"NodeKeywords","col":0,"comment":"null","endLoc":377,"id":3408,"nodeType":"Class","startLoc":343,"text":"class NodeKeywords(MappingMixin):\n def __init__(self, node):\n self.node = node\n self.parent = node.parent\n self._markers = {node.name: True}\n\n def __getitem__(self, key):\n try:\n return self._markers[key]\n except KeyError:\n if self.parent is None:\n raise\n return self.parent.keywords[key]\n\n def __setitem__(self, key, value):\n self._markers[key] = value\n\n def __delitem__(self, key):\n raise ValueError(\"cannot delete key in keywords dict\")\n\n def __iter__(self):\n seen = self._seen()\n return iter(seen)\n\n def _seen(self):\n seen = set(self._markers)\n if self.parent is not None:\n seen.update(self.parent.keywords)\n return seen\n\n def __len__(self):\n return len(self._seen())\n\n def __repr__(self):\n return \"\" % (self.node,)"},{"col":4,"comment":" constructor useable for subprocesses. ","endLoc":738,"header":"@classmethod\n def fromdictargs(cls, option_dict, args)","id":3409,"name":"fromdictargs","nodeType":"Function","startLoc":730,"text":"@classmethod\n def fromdictargs(cls, option_dict, args):\n \"\"\" constructor useable for subprocesses. \"\"\"\n config = get_config(args)\n config.option.__dict__.update(option_dict)\n config.parse(args, addopts=False)\n for x in config.option.plugins:\n config.pluginmanager.consider_pluginarg(x)\n return config"},{"col":4,"comment":"null","endLoc":355,"header":"def __getitem__(self, key)","id":3410,"name":"__getitem__","nodeType":"Function","startLoc":349,"text":"def __getitem__(self, key):\n try:\n return self._markers[key]\n except KeyError:\n if self.parent is None:\n raise\n return self.parent.keywords[key]"},{"col":4,"comment":"Test support for multiple --doctest-glob arguments (#1255).\n ","endLoc":147,"header":"def test_multiple_patterns(self, testdir)","id":3411,"name":"test_multiple_patterns","nodeType":"Function","startLoc":119,"text":"def test_multiple_patterns(self, testdir):\n \"\"\"Test support for multiple --doctest-glob arguments (#1255).\n \"\"\"\n testdir.maketxtfile(\n xdoc=\"\"\"\n >>> 1\n 1\n \"\"\"\n )\n testdir.makefile(\n \".foo\",\n test=\"\"\"\n >>> 1\n 1\n \"\"\",\n )\n testdir.maketxtfile(\n test_normal=\"\"\"\n >>> 1\n 1\n \"\"\"\n )\n expected = {\"xdoc.txt\", \"test.foo\", \"test_normal.txt\"}\n assert {x.basename for x in testdir.tmpdir.listdir()} == expected\n args = [\"--doctest-glob=xdoc*.txt\", \"--doctest-glob=*.foo\"]\n result = testdir.runpytest(*args)\n result.stdout.fnmatch_lines([\"*test.foo *\", \"*xdoc.txt *\", \"*2 passed*\"])\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*test_normal.txt *\", \"*1 passed*\"])"},{"col":4,"comment":"null","endLoc":358,"header":"def __setitem__(self, key, value)","id":3412,"name":"__setitem__","nodeType":"Function","startLoc":357,"text":"def __setitem__(self, key, value):\n self._markers[key] = value"},{"col":4,"comment":"null","endLoc":361,"header":"def __delitem__(self, key)","id":3413,"name":"__delitem__","nodeType":"Function","startLoc":360,"text":"def __delitem__(self, key):\n raise ValueError(\"cannot delete key in keywords dict\")"},{"col":4,"comment":"null","endLoc":365,"header":"def __iter__(self)","id":3414,"name":"__iter__","nodeType":"Function","startLoc":363,"text":"def __iter__(self):\n seen = self._seen()\n return iter(seen)"},{"col":0,"comment":"null","endLoc":167,"header":"def test_generic(testdir, LineMatcher)","id":3415,"name":"test_generic","nodeType":"Function","startLoc":138,"text":"def test_generic(testdir, LineMatcher):\n testdir.plugins.append(\"resultlog\")\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_pass():\n pass\n def test_fail():\n assert 0\n def test_skip():\n pytest.skip(\"\")\n @pytest.mark.xfail\n def test_xfail():\n assert 0\n @pytest.mark.xfail(run=False)\n def test_xfail_norun():\n assert 0\n \"\"\"\n )\n testdir.runpytest(\"--resultlog=result.log\")\n lines = testdir.tmpdir.join(\"result.log\").readlines(cr=0)\n LineMatcher(lines).fnmatch_lines(\n [\n \". *:test_pass\",\n \"F *:test_fail\",\n \"s *:test_skip\",\n \"x *:test_xfail\",\n \"x *:test_xfail_norun\",\n ]\n )"},{"col":0,"comment":"--resultlog should automatically create directories for the log file","endLoc":182,"header":"def test_makedir_for_resultlog(testdir, LineMatcher)","id":3416,"name":"test_makedir_for_resultlog","nodeType":"Function","startLoc":170,"text":"def test_makedir_for_resultlog(testdir, LineMatcher):\n \"\"\"--resultlog should automatically create directories for the log file\"\"\"\n testdir.plugins.append(\"resultlog\")\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_pass():\n pass\n \"\"\"\n )\n testdir.runpytest(\"--resultlog=path/to/result.log\")\n lines = testdir.tmpdir.join(\"path/to/result.log\").readlines(cr=0)\n LineMatcher(lines).fnmatch_lines([\". *:test_pass\"])"},{"col":4,"comment":"Test support for doctest_encoding ini option.\n ","endLoc":174,"header":"@pytest.mark.parametrize(\n \" test_string, encoding\",\n [(u\"foo\", \"ascii\"), (u\"öäü\", \"latin1\"), (u\"öäü\", \"utf-8\")],\n )\n def test_encoding(self, testdir, test_string, encoding)","id":3417,"name":"test_encoding","nodeType":"Function","startLoc":149,"text":"@pytest.mark.parametrize(\n \" test_string, encoding\",\n [(u\"foo\", \"ascii\"), (u\"öäü\", \"latin1\"), (u\"öäü\", \"utf-8\")],\n )\n def test_encoding(self, testdir, test_string, encoding):\n \"\"\"Test support for doctest_encoding ini option.\n \"\"\"\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_encoding={}\n \"\"\".format(\n encoding\n )\n )\n doctest = u\"\"\"\n >>> u\"{}\"\n {}\n \"\"\".format(\n test_string, repr(test_string)\n )\n testdir._makefile(\".txt\", [doctest], {}, encoding=encoding)\n\n result = testdir.runpytest()\n\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":0,"comment":"null","endLoc":198,"header":"def test_no_resultlog_on_slaves(testdir)","id":3418,"name":"test_no_resultlog_on_slaves","nodeType":"Function","startLoc":185,"text":"def test_no_resultlog_on_slaves(testdir):\n config = testdir.parseconfig(\"-p\", \"resultlog\", \"--resultlog=resultlog\")\n\n assert not hasattr(config, \"_resultlog\")\n pytest_configure(config)\n assert hasattr(config, \"_resultlog\")\n pytest_unconfigure(config)\n assert not hasattr(config, \"_resultlog\")\n\n config.slaveinput = {}\n pytest_configure(config)\n assert not hasattr(config, \"_resultlog\")\n pytest_unconfigure(config)\n assert not hasattr(config, \"_resultlog\")"},{"col":4,"comment":"null","endLoc":717,"header":"@staticmethod\n def is_rewrite_disabled(docstring)","id":3419,"name":"is_rewrite_disabled","nodeType":"Function","startLoc":715,"text":"@staticmethod\n def is_rewrite_disabled(docstring):\n return \"PYTEST_DONT_REWRITE\" in docstring"},{"col":4,"comment":"null","endLoc":416,"header":"def test_preserve_container(self, monkeypatch, path_type)","id":3420,"name":"test_preserve_container","nodeType":"Function","startLoc":404,"text":"def test_preserve_container(self, monkeypatch, path_type):\n other_path_type = self.other_path[path_type]\n original_data = list(getattr(sys, path_type))\n original_other = getattr(sys, other_path_type)\n original_other_data = list(original_other)\n new = []\n snapshot = SysPathsSnapshot()\n monkeypatch.setattr(sys, path_type, new)\n snapshot.restore()\n assert getattr(sys, path_type) is new\n assert getattr(sys, path_type) == original_data\n assert getattr(sys, other_path_type) is original_other\n assert getattr(sys, other_path_type) == original_other_data"},{"col":0,"comment":"null","endLoc":21,"header":"def test_foobar(my_fixture)","id":3421,"name":"test_foobar","nodeType":"Function","startLoc":20,"text":"def test_foobar(my_fixture):\n assert my_fixture == \"MOCKED\""},{"attributeType":"null","col":28,"comment":"null","endLoc":7,"id":3422,"name":"mock","nodeType":"Attribute","startLoc":7,"text":"mock"},{"col":0,"comment":"null","endLoc":221,"header":"def test_failure_issue380(testdir)","id":3423,"name":"test_failure_issue380","nodeType":"Function","startLoc":201,"text":"def test_failure_issue380(testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n class MyCollector(pytest.File):\n def collect(self):\n raise ValueError()\n def repr_failure(self, excinfo):\n return \"somestring\"\n def pytest_collect_file(path, parent):\n return MyCollector(parent=parent, fspath=path)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--resultlog=log\")\n assert result.ret == 2"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":11,"id":3424,"name":"config","nodeType":"Attribute","startLoc":11,"text":"config"},{"col":0,"comment":"","endLoc":2,"header":"fixture_mock_integration.py#","id":3425,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"Reproduces issue #3774\"\"\"\n\ntry:\n import mock\nexcept ImportError:\n import unittest.mock as mock\n\nconfig = {\"mykey\": \"ORIGINAL\"}"},{"attributeType":"null","col":0,"comment":"null","endLoc":16,"id":3426,"name":"pytestmark","nodeType":"Attribute","startLoc":16,"text":"pytestmark"},{"col":0,"comment":"","endLoc":2,"header":"test_resultlog.py#","id":3427,"name":"","nodeType":"Function","startLoc":2,"text":"pytestmark = pytest.mark.filterwarnings(\"ignore:--result-log is deprecated\")"},{"col":4,"comment":"null","endLoc":476,"header":"def _create_formatter(self, log_format, log_date_format)","id":3430,"name":"_create_formatter","nodeType":"Function","startLoc":462,"text":"def _create_formatter(self, log_format, log_date_format):\n # color option doesn't exist if terminal plugin is disabled\n color = getattr(self._config.option, \"color\", \"no\")\n if color != \"no\" and ColoredLevelFormatter.LEVELNAME_FMT_REGEX.search(\n log_format\n ):\n formatter = ColoredLevelFormatter(\n create_terminal_writer(self._config), log_format, log_date_format\n )\n else:\n formatter = logging.Formatter(log_format, log_date_format)\n\n if not six.PY2:\n formatter._style = PercentStyleMultiline(formatter._style._fmt)\n return formatter"},{"col":0,"comment":"Return the actual logging level.","endLoc":406,"header":"def get_actual_log_level(config, *setting_names)","id":3434,"name":"get_actual_log_level","nodeType":"Function","startLoc":384,"text":"def get_actual_log_level(config, *setting_names):\n \"\"\"Return the actual logging level.\"\"\"\n\n for setting_name in setting_names:\n log_level = config.getoption(setting_name)\n if log_level is None:\n log_level = config.getini(setting_name)\n if log_level:\n break\n else:\n return\n\n if isinstance(log_level, six.string_types):\n log_level = log_level.upper()\n try:\n return int(getattr(logging, log_level, log_level))\n except ValueError:\n # Python logging does not recognise this as a logging level\n raise pytest.UsageError(\n \"'{}' is not recognized as a logging level name for \"\n \"'{}'. Please consider passing the \"\n \"logging level num instead.\".format(log_level, setting_name)\n )"},{"id":3435,"name":"release-2.7.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.7.0: fixes, features, speed improvements\n===========================================================================\n\npytest is a mature Python testing tool with more than a 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is supposed to be drop-in compatible to 2.6.X.\n\nSee below for the changes and see docs at:\n\n http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n pip install -U pytest\n\nThanks to all who contributed, among them:\n\n Anatoly Bubenkoff\n Floris Bruynooghe\n Brianna Laugher\n Eric Siegerman\n Daniel Hahler\n Charles Cloud\n Tom Viner\n Holger Peters\n Ldiary Translations\n almarklein\n\nhave fun,\nholger krekel\n\n2.7.0 (compared to 2.6.4)\n-----------------------------\n\n- fix issue435: make reload() work when assert rewriting is active.\n Thanks Daniel Hahler.\n\n- fix issue616: conftest.py files and their contained fixutres are now\n properly considered for visibility, independently from the exact\n current working directory and test arguments that are used.\n Many thanks to Eric Siegerman and his PR235 which contains\n systematic tests for conftest visibility and now passes.\n This change also introduces the concept of a ``rootdir`` which\n is printed as a new pytest header and documented in the pytest\n customize web page.\n\n- change reporting of \"diverted\" tests, i.e. tests that are collected\n in one file but actually come from another (e.g. when tests in a test class\n come from a base class in a different file). We now show the nodeid\n and indicate via a postfix the other file.\n\n- add ability to set command line options by environment variable PYTEST_ADDOPTS.\n\n- added documentation on the new pytest-dev teams on bitbucket and\n github. See https://pytest.org/latest/contributing.html .\n Thanks to Anatoly for pushing and initial work on this.\n\n- fix issue650: new option ``--docttest-ignore-import-errors`` which\n will turn import errors in doctests into skips. Thanks Charles Cloud\n for the complete PR.\n\n- fix issue655: work around different ways that cause python2/3\n to leak sys.exc_info into fixtures/tests causing failures in 3rd party code\n\n- fix issue615: assertion rewriting did not correctly escape % signs\n when formatting boolean operations, which tripped over mixing\n booleans with modulo operators. Thanks to Tom Viner for the report,\n triaging and fix.\n\n- implement issue351: add ability to specify parametrize ids as a callable\n to generate custom test ids. Thanks Brianna Laugher for the idea and\n implementation.\n\n- introduce and document new hookwrapper mechanism useful for plugins\n which want to wrap the execution of certain hooks for their purposes.\n This supersedes the undocumented ``__multicall__`` protocol which\n pytest itself and some external plugins use. Note that pytest-2.8\n is scheduled to drop supporting the old ``__multicall__``\n and only support the hookwrapper protocol.\n\n- majorly speed up invocation of plugin hooks\n\n- use hookwrapper mechanism in builtin pytest plugins.\n\n- add a doctest ini option for doctest flags, thanks Holger Peters.\n\n- add note to docs that if you want to mark a parameter and the\n parameter is a callable, you also need to pass in a reason to disambiguate\n it from the \"decorator\" case. Thanks Tom Viner.\n\n- \"python_classes\" and \"python_functions\" options now support glob-patterns\n for test discovery, as discussed in issue600. Thanks Ldiary Translations.\n\n- allow to override parametrized fixtures with non-parametrized ones and vice versa (bubenkoff).\n\n- fix issue463: raise specific error for 'parameterize' misspelling (pfctdayelise).\n\n- On failure, the ``sys.last_value``, ``sys.last_type`` and\n ``sys.last_traceback`` are set, so that a user can inspect the error\n via postmortem debugging (almarklein).\n"},{"id":3436,"name":"goodpractices.rst","nodeType":"TextFile","path":"doc/en","text":".. highlightlang:: python\n.. _`goodpractices`:\n\nGood Integration Practices\n=================================================\n\nInstall package with pip\n-------------------------------------------------\n\nFor development, we recommend you use venv_ for virtual environments\n(or virtualenv_ for Python 2.7) and\npip_ for installing your application and any dependencies,\nas well as the ``pytest`` package itself.\nThis ensures your code and dependencies are isolated from your system Python installation.\n\nNext, place a ``setup.py`` file in the root of your package with the following minimum content::\n\n from setuptools import setup, find_packages\n\n setup(name=\"PACKAGENAME\", packages=find_packages())\n\nWhere ``PACKAGENAME`` is the name of your package. You can then install your package in \"editable\" mode by running from the same directory::\n\n pip install -e .\n\nwhich lets you change your source code (both tests and application) and rerun tests at will.\nThis is similar to running ``python setup.py develop`` or ``conda develop`` in that it installs\nyour package using a symlink to your development code.\n\n.. _`test discovery`:\n.. _`Python test discovery`:\n\nConventions for Python test discovery\n-------------------------------------------------\n\n``pytest`` implements the following standard test discovery:\n\n* If no arguments are specified then collection starts from :confval:`testpaths`\n (if configured) or the current directory. Alternatively, command line arguments\n can be used in any combination of directories, file names or node ids.\n* Recurse into directories, unless they match :confval:`norecursedirs`.\n* In those directories, search for ``test_*.py`` or ``*_test.py`` files, imported by their `test package name`_.\n* From those files, collect test items:\n\n * ``test`` prefixed test functions or methods outside of class\n * ``test`` prefixed test functions or methods inside ``Test`` prefixed test classes (without an ``__init__`` method)\n\nFor examples of how to customize your test discovery :doc:`example/pythoncollection`.\n\nWithin Python modules, ``pytest`` also discovers tests using the standard\n:ref:`unittest.TestCase ` subclassing technique.\n\n\nChoosing a test layout / import rules\n-------------------------------------\n\n``pytest`` supports two common test layouts:\n\nTests outside application code\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nPutting tests into an extra directory outside your actual application code\nmight be useful if you have many functional tests or for other reasons want\nto keep tests separate from actual application code (often a good idea)::\n\n setup.py\n mypkg/\n __init__.py\n app.py\n view.py\n tests/\n test_app.py\n test_view.py\n ...\n\nThis has the following benefits:\n\n* Your tests can run against an installed version after executing ``pip install .``.\n* Your tests can run against the local copy with an editable install after executing ``pip install --editable .``.\n* If you don't have a ``setup.py`` file and are relying on the fact that Python by default puts the current\n directory in ``sys.path`` to import your package, you can execute ``python -m pytest`` to execute the tests against the\n local copy directly, without using ``pip``.\n\n.. note::\n\n See :ref:`pythonpath` for more information about the difference between calling ``pytest`` and\n ``python -m pytest``.\n\nNote that using this scheme your test files must have **unique names**, because\n``pytest`` will import them as *top-level* modules since there are no packages\nto derive a full package name from. In other words, the test files in the example above will\nbe imported as ``test_app`` and ``test_view`` top-level modules by adding ``tests/`` to\n``sys.path``.\n\nIf you need to have test modules with the same name, you might add ``__init__.py`` files to your\n``tests`` folder and subfolders, changing them to packages::\n\n setup.py\n mypkg/\n ...\n tests/\n __init__.py\n foo/\n __init__.py\n test_view.py\n bar/\n __init__.py\n test_view.py\n\nNow pytest will load the modules as ``tests.foo.test_view`` and ``tests.bar.test_view``, allowing\nyou to have modules with the same name. But now this introduces a subtle problem: in order to load\nthe test modules from the ``tests`` directory, pytest prepends the root of the repository to\n``sys.path``, which adds the side-effect that now ``mypkg`` is also importable.\nThis is problematic if you are using a tool like `tox`_ to test your package in a virtual environment,\nbecause you want to test the *installed* version of your package, not the local code from the repository.\n\nIn this situation, it is **strongly** suggested to use a ``src`` layout where application root package resides in a\nsub-directory of your root::\n\n setup.py\n src/\n mypkg/\n __init__.py\n app.py\n view.py\n tests/\n __init__.py\n foo/\n __init__.py\n test_view.py\n bar/\n __init__.py\n test_view.py\n\n\nThis layout prevents a lot of common pitfalls and has many benefits, which are better explained in this excellent\n`blog post by Ionel Cristian Mărieș `_.\n\nTests as part of application code\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nInlining test directories into your application package\nis useful if you have direct relation between tests and application modules and\nwant to distribute them along with your application::\n\n setup.py\n mypkg/\n __init__.py\n app.py\n view.py\n test/\n __init__.py\n test_app.py\n test_view.py\n ...\n\nIn this scheme, it is easy to run your tests using the ``--pyargs`` option::\n\n pytest --pyargs mypkg\n\n``pytest`` will discover where ``mypkg`` is installed and collect tests from there.\n\nNote that this layout also works in conjunction with the ``src`` layout mentioned in the previous section.\n\n\n.. note::\n\n You can use Python3 namespace packages (PEP420) for your application\n but pytest will still perform `test package name`_ discovery based on the\n presence of ``__init__.py`` files. If you use one of the\n two recommended file system layouts above but leave away the ``__init__.py``\n files from your directories it should just work on Python3.3 and above. From\n \"inlined tests\", however, you will need to use absolute imports for\n getting at your application code.\n\n.. _`test package name`:\n\n.. note::\n\n If ``pytest`` finds an \"a/b/test_module.py\" test file while\n recursing into the filesystem it determines the import name\n as follows:\n\n * determine ``basedir``: this is the first \"upward\" (towards the root)\n directory not containing an ``__init__.py``. If e.g. both ``a``\n and ``b`` contain an ``__init__.py`` file then the parent directory\n of ``a`` will become the ``basedir``.\n\n * perform ``sys.path.insert(0, basedir)`` to make the test module\n importable under the fully qualified import name.\n\n * ``import a.b.test_module`` where the path is determined\n by converting path separators ``/`` into \".\" characters. This means\n you must follow the convention of having directory and file\n names map directly to the import names.\n\n The reason for this somewhat evolved importing technique is\n that in larger projects multiple test modules might import\n from each other and thus deriving a canonical import name helps\n to avoid surprises such as a test module getting imported twice.\n\n\n.. _`virtualenv`: https://pypi.org/project/virtualenv/\n.. _`buildout`: http://www.buildout.org/\n.. _pip: https://pypi.org/project/pip/\n\n.. _`use tox`:\n\ntox\n------\n\nOnce you are done with your work and want to make sure that your actual\npackage passes all tests you may want to look into `tox`_, the\nvirtualenv test automation tool and its `pytest support\n`_.\ntox helps you to setup virtualenv environments with pre-defined\ndependencies and then executing a pre-configured test command with\noptions. It will run tests against the installed package and not\nagainst your source code checkout, helping to detect packaging\nglitches.\n\n\nIntegrating with setuptools / ``python setup.py test`` / ``pytest-runner``\n--------------------------------------------------------------------------\n\nYou can integrate test runs into your setuptools based project\nwith the `pytest-runner `_ plugin.\n\nAdd this to ``setup.py`` file:\n\n.. code-block:: python\n\n from setuptools import setup\n\n setup(\n # ...,\n setup_requires=[\"pytest-runner\", ...],\n tests_require=[\"pytest\", ...],\n # ...,\n )\n\n\nAnd create an alias into ``setup.cfg`` file:\n\n\n.. code-block:: ini\n\n [aliases]\n test=pytest\n\nIf you now type::\n\n python setup.py test\n\nthis will execute your tests using ``pytest-runner``. As this is a\nstandalone version of ``pytest`` no prior installation whatsoever is\nrequired for calling the test command. You can also pass additional\narguments to pytest such as your test directory or other\noptions using ``--addopts``.\n\nYou can also specify other pytest-ini options in your ``setup.cfg`` file\nby putting them into a ``[tool:pytest]`` section:\n\n.. code-block:: ini\n\n [tool:pytest]\n addopts = --verbose\n python_files = testing/*/*.py\n\n\nManual Integration\n^^^^^^^^^^^^^^^^^^\n\nIf for some reason you don't want/can't use ``pytest-runner``, you can write\nyour own setuptools Test command for invoking pytest.\n\n.. code-block:: python\n\n import sys\n\n from setuptools.command.test import test as TestCommand\n\n\n class PyTest(TestCommand):\n user_options = [(\"pytest-args=\", \"a\", \"Arguments to pass to pytest\")]\n\n def initialize_options(self):\n TestCommand.initialize_options(self)\n self.pytest_args = \"\"\n\n def run_tests(self):\n import shlex\n\n # import here, cause outside the eggs aren't loaded\n import pytest\n\n errno = pytest.main(shlex.split(self.pytest_args))\n sys.exit(errno)\n\n\n setup(\n # ...,\n tests_require=[\"pytest\"],\n cmdclass={\"pytest\": PyTest},\n )\n\nNow if you run::\n\n python setup.py test\n\nthis will download ``pytest`` if needed and then run your tests\nas you would expect it to. You can pass a single string of arguments\nusing the ``--pytest-args`` or ``-a`` command-line option. For example::\n\n python setup.py test -a \"--durations=5\"\n\nis equivalent to running ``pytest --durations=5``.\n\n\n.. include:: links.inc\n"},{"id":3437,"name":"release-3.1.3.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.1.3\n=======================================\n\npytest 3.1.3 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Antoine Legrand\n* Bruno Oliveira\n* Max Moroz\n* Raphael Pierzina\n* Ronny Pfannschmidt\n* Ryan Fitzpatrick\n\n\nHappy testing,\nThe pytest Development Team\n"},{"id":3438,"name":"recwarn.rst","nodeType":"TextFile","path":"doc/en","text":":orphan:\n\nThis page has been moved, please see :ref:`assertwarnings`.\n"},{"id":3439,"name":"doc/en/example/costlysetup","nodeType":"Package"},{"fileName":"conftest.py","filePath":"doc/en/example/costlysetup","id":3440,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\n@pytest.fixture(\"session\")\ndef setup(request):\n setup = CostlySetup()\n yield setup\n setup.finalize()\n\n\nclass CostlySetup(object):\n def __init__(self):\n import time\n\n print(\"performing costly setup\")\n time.sleep(5)\n self.timecostly = 1\n\n def finalize(self):\n del self.timecostly\n"},{"className":"CostlySetup","col":0,"comment":"null","endLoc":21,"id":3441,"nodeType":"Class","startLoc":12,"text":"class CostlySetup(object):\n def __init__(self):\n import time\n\n print(\"performing costly setup\")\n time.sleep(5)\n self.timecostly = 1\n\n def finalize(self):\n del self.timecostly"},{"col":4,"comment":"null","endLoc":18,"header":"def __init__(self)","id":3442,"name":"__init__","nodeType":"Function","startLoc":13,"text":"def __init__(self):\n import time\n\n print(\"performing costly setup\")\n time.sleep(5)\n self.timecostly = 1"},{"col":4,"comment":"null","endLoc":45,"header":"def visit(self, node: AST) -> Any","id":3443,"name":"visit","nodeType":"Function","startLoc":45,"text":"def visit(self, node: AST) -> Any: ..."},{"col":4,"comment":"null","endLoc":21,"header":"def finalize(self)","id":3445,"name":"finalize","nodeType":"Function","startLoc":20,"text":"def finalize(self):\n del self.timecostly"},{"attributeType":"int","col":8,"comment":"null","endLoc":18,"id":3446,"name":"timecostly","nodeType":"Attribute","startLoc":18,"text":"self.timecostly"},{"col":0,"comment":"null","endLoc":349,"header":"def _write_pyc(state, co, source_stat, pyc)","id":3447,"name":"_write_pyc","nodeType":"Function","startLoc":328,"text":"def _write_pyc(state, co, source_stat, pyc):\n # Technically, we don't have to have the same pyc format as\n # (C)Python, since these \"pycs\" should never be seen by builtin\n # import. However, there's little reason deviate, and I hope\n # sometime to be able to use imp.load_compiled to load them. (See\n # the comment in load_module above.)\n try:\n with atomicwrites.atomic_write(pyc, mode=\"wb\", overwrite=True) as fp:\n fp.write(imp.get_magic())\n # as of now, bytecode header expects 32-bit numbers for size and mtime (#4903)\n mtime = int(source_stat.mtime) & 0xFFFFFFFF\n size = source_stat.size & 0xFFFFFFFF\n # \">> i = 0\n >>> 0 / i\n 2\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines(\n [\n \"*unexpected_exception*\",\n \"*>>> i = 0*\",\n \"*>>> 0 / i*\",\n \"*UNEXPECTED*ZeroDivision*\",\n ]\n )"},{"attributeType":"TypedDict","col":4,"comment":"null","endLoc":375,"id":3449,"name":"other_path","nodeType":"Attribute","startLoc":375,"text":"other_path"},{"col":0,"comment":"null","endLoc":76,"header":"def test_make_hook_recorder(testdir)","id":3450,"name":"test_make_hook_recorder","nodeType":"Function","startLoc":26,"text":"def test_make_hook_recorder(testdir):\n item = testdir.getitem(\"def test_func(): pass\")\n recorder = testdir.make_hook_recorder(item.config.pluginmanager)\n assert not recorder.getfailures()\n\n pytest.xfail(\"internal reportrecorder tests need refactoring\")\n\n class rep(object):\n excinfo = None\n passed = False\n failed = True\n skipped = False\n when = \"call\"\n\n recorder.hook.pytest_runtest_logreport(report=rep)\n failures = recorder.getfailures()\n assert failures == [rep]\n failures = recorder.getfailures()\n assert failures == [rep]\n\n class rep(object):\n excinfo = None\n passed = False\n failed = False\n skipped = True\n when = \"call\"\n\n rep.passed = False\n rep.skipped = True\n recorder.hook.pytest_runtest_logreport(report=rep)\n\n modcol = testdir.getmodulecol(\"\")\n rep = modcol.config.hook.pytest_make_collect_report(collector=modcol)\n rep.passed = False\n rep.failed = True\n rep.skipped = False\n recorder.hook.pytest_collectreport(report=rep)\n\n passed, skipped, failed = recorder.listoutcomes()\n assert not passed and skipped and failed\n\n numpassed, numskipped, numfailed = recorder.countoutcomes()\n assert numpassed == 0\n assert numskipped == 1\n assert numfailed == 1\n assert len(recorder.getfailedcollections()) == 1\n\n recorder.unregister()\n recorder.clear()\n recorder.hook.pytest_runtest_logreport(report=rep)\n pytest.raises(ValueError, recorder.getfailures)"},{"col":4,"comment":"null","endLoc":204,"header":"def test_doctest_skip(self, testdir)","id":3451,"name":"test_doctest_skip","nodeType":"Function","startLoc":194,"text":"def test_doctest_skip(self, testdir):\n testdir.maketxtfile(\n \"\"\"\n >>> 1\n 1\n >>> import pytest\n >>> pytest.skip(\"\")\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines([\"*1 skipped*\"])"},{"col":0,"comment":"null","endLoc":9,"header":"@pytest.fixture(\"session\")\ndef setup(request)","id":3452,"name":"setup","nodeType":"Function","startLoc":5,"text":"@pytest.fixture(\"session\")\ndef setup(request):\n setup = CostlySetup()\n yield setup\n setup.finalize()"},{"col":4,"comment":"null","endLoc":371,"header":"def _seen(self)","id":3453,"name":"_seen","nodeType":"Function","startLoc":367,"text":"def _seen(self):\n seen = set(self._markers)\n if self.parent is not None:\n seen.update(self.parent.keywords)\n return seen"},{"col":4,"comment":"Test that we show some context before the actual line of a failing\n doctest.\n ","endLoc":248,"header":"def test_docstring_partial_context_around_error(self, testdir)","id":3454,"name":"test_docstring_partial_context_around_error","nodeType":"Function","startLoc":206,"text":"def test_docstring_partial_context_around_error(self, testdir):\n \"\"\"Test that we show some context before the actual line of a failing\n doctest.\n \"\"\"\n testdir.makepyfile(\n '''\n def foo():\n \"\"\"\n text-line-1\n text-line-2\n text-line-3\n text-line-4\n text-line-5\n text-line-6\n text-line-7\n text-line-8\n text-line-9\n text-line-10\n text-line-11\n >>> 1 + 1\n 3\n\n text-line-after\n \"\"\"\n '''\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines(\n [\n \"*docstring_partial_context_around_error*\",\n \"005*text-line-3\",\n \"006*text-line-4\",\n \"013*text-line-11\",\n \"014*>>> 1 + 1\",\n \"Expected:\",\n \" 3\",\n \"Got:\",\n \" 2\",\n ]\n )\n # lines below should be trimmed out\n assert \"text-line-2\" not in result.stdout.str()\n assert \"text-line-after\" not in result.stdout.str()"},{"col":4,"comment":"null","endLoc":374,"header":"def __len__(self)","id":3455,"name":"__len__","nodeType":"Function","startLoc":373,"text":"def __len__(self):\n return len(self._seen())"},{"col":4,"comment":"Test that we show the whole context before the actual line of a failing\n doctest, provided that the context is up to 10 lines long.\n ","endLoc":278,"header":"def test_docstring_full_context_around_error(self, testdir)","id":3456,"name":"test_docstring_full_context_around_error","nodeType":"Function","startLoc":250,"text":"def test_docstring_full_context_around_error(self, testdir):\n \"\"\"Test that we show the whole context before the actual line of a failing\n doctest, provided that the context is up to 10 lines long.\n \"\"\"\n testdir.makepyfile(\n '''\n def foo():\n \"\"\"\n text-line-1\n text-line-2\n\n >>> 1 + 1\n 3\n \"\"\"\n '''\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines(\n [\n \"*docstring_full_context_around_error*\",\n \"003*text-line-1\",\n \"004*text-line-2\",\n \"006*>>> 1 + 1\",\n \"Expected:\",\n \" 3\",\n \"Got:\",\n \" 2\",\n ]\n )"},{"col":4,"comment":"null","endLoc":377,"header":"def __repr__(self)","id":3457,"name":"__repr__","nodeType":"Function","startLoc":376,"text":"def __repr__(self):\n return \"\" % (self.node,)"},{"attributeType":"{parent, name}","col":8,"comment":"null","endLoc":345,"id":3458,"name":"node","nodeType":"Attribute","startLoc":345,"text":"self.node"},{"col":4,"comment":"null","endLoc":303,"header":"def test_doctest_linedata_missing(self, testdir)","id":3459,"name":"test_doctest_linedata_missing","nodeType":"Function","startLoc":280,"text":"def test_doctest_linedata_missing(self, testdir):\n testdir.tmpdir.join(\"hello.py\").write(\n textwrap.dedent(\n \"\"\"\\\n class Fun(object):\n @property\n def test(self):\n '''\n >>> a = 1\n >>> 1/0\n '''\n \"\"\"\n )\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines(\n [\n \"*hello*\",\n \"*EXAMPLE LOCATION UNKNOWN, not showing all tests of that example*\",\n \"*1/0*\",\n \"*UNEXPECTED*ZeroDivision*\",\n \"*1 failed*\",\n ]\n )"},{"fileName":"collect.py","filePath":"testing/python","id":3460,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport textwrap\n\nimport _pytest._code\nimport pytest\nfrom _pytest.main import EXIT_NOTESTSCOLLECTED\nfrom _pytest.nodes import Collector\n\n\nclass TestModule(object):\n def test_failing_import(self, testdir):\n modcol = testdir.getmodulecol(\"import alksdjalskdjalkjals\")\n pytest.raises(Collector.CollectError, modcol.collect)\n\n def test_import_duplicate(self, testdir):\n a = testdir.mkdir(\"a\")\n b = testdir.mkdir(\"b\")\n p = a.ensure(\"test_whatever.py\")\n p.pyimport()\n del sys.modules[\"test_whatever\"]\n b.ensure(\"test_whatever.py\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*import*mismatch*\",\n \"*imported*test_whatever*\",\n \"*%s*\" % a.join(\"test_whatever.py\"),\n \"*not the same*\",\n \"*%s*\" % b.join(\"test_whatever.py\"),\n \"*HINT*\",\n ]\n )\n\n def test_import_prepend_append(self, testdir, monkeypatch):\n root1 = testdir.mkdir(\"root1\")\n root2 = testdir.mkdir(\"root2\")\n root1.ensure(\"x456.py\")\n root2.ensure(\"x456.py\")\n p = root2.join(\"test_x456.py\")\n monkeypatch.syspath_prepend(str(root1))\n p.write(\n textwrap.dedent(\n \"\"\"\\\n import x456\n def test():\n assert x456.__file__.startswith({!r})\n \"\"\".format(\n str(root2)\n )\n )\n )\n with root2.as_cwd():\n reprec = testdir.inline_run(\"--import-mode=append\")\n reprec.assertoutcome(passed=0, failed=1)\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_syntax_error_in_module(self, testdir):\n modcol = testdir.getmodulecol(\"this is a syntax error\")\n pytest.raises(modcol.CollectError, modcol.collect)\n pytest.raises(modcol.CollectError, modcol.collect)\n\n def test_module_considers_pluginmanager_at_import(self, testdir):\n modcol = testdir.getmodulecol(\"pytest_plugins='xasdlkj',\")\n pytest.raises(ImportError, lambda: modcol.obj)\n\n def test_invalid_test_module_name(self, testdir):\n a = testdir.mkdir(\"a\")\n a.ensure(\"test_one.part1.py\")\n result = testdir.runpytest(\"-rw\")\n result.stdout.fnmatch_lines(\n [\n \"ImportError while importing test module*test_one.part1*\",\n \"Hint: make sure your test modules/packages have valid Python names.\",\n ]\n )\n\n @pytest.mark.parametrize(\"verbose\", [0, 1, 2])\n def test_show_traceback_import_error(self, testdir, verbose):\n \"\"\"Import errors when collecting modules should display the traceback (#1976).\n\n With low verbosity we omit pytest and internal modules, otherwise show all traceback entries.\n \"\"\"\n testdir.makepyfile(\n foo_traceback_import_error=\"\"\"\n from bar_traceback_import_error import NOT_AVAILABLE\n \"\"\",\n bar_traceback_import_error=\"\",\n )\n testdir.makepyfile(\n \"\"\"\n import foo_traceback_import_error\n \"\"\"\n )\n args = (\"-v\",) * verbose\n result = testdir.runpytest(*args)\n result.stdout.fnmatch_lines(\n [\n \"ImportError while importing test module*\",\n \"Traceback:\",\n \"*from bar_traceback_import_error import NOT_AVAILABLE\",\n \"*cannot import name *NOT_AVAILABLE*\",\n ]\n )\n assert result.ret == 2\n\n stdout = result.stdout.str()\n for name in (\"_pytest\", os.path.join(\"py\", \"_path\")):\n if verbose == 2:\n assert name in stdout\n else:\n assert name not in stdout\n\n def test_show_traceback_import_error_unicode(self, testdir):\n \"\"\"Check test modules collected which raise ImportError with unicode messages\n are handled properly (#2336).\n \"\"\"\n testdir.makepyfile(\n u\"\"\"\n # -*- coding: utf-8 -*-\n raise ImportError(u'Something bad happened ☺')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"ImportError while importing test module*\",\n \"Traceback:\",\n \"*raise ImportError*Something bad happened*\",\n ]\n )\n assert result.ret == 2\n\n\nclass TestClass(object):\n def test_class_with_init_warning(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class TestClass1(object):\n def __init__(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rw\")\n result.stdout.fnmatch_lines(\n [\n \"*cannot collect test class 'TestClass1' because it has \"\n \"a __init__ constructor (from: test_class_with_init_warning.py)\"\n ]\n )\n\n def test_class_with_new_warning(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class TestClass1(object):\n def __new__(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rw\")\n result.stdout.fnmatch_lines(\n [\n \"*cannot collect test class 'TestClass1' because it has \"\n \"a __new__ constructor (from: test_class_with_new_warning.py)\"\n ]\n )\n\n def test_class_subclassobject(self, testdir):\n testdir.getmodulecol(\n \"\"\"\n class test(object):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*collected 0*\"])\n\n def test_static_method(self, testdir):\n \"\"\"Support for collecting staticmethod tests (#2528, #2699)\"\"\"\n testdir.getmodulecol(\n \"\"\"\n import pytest\n class Test(object):\n @staticmethod\n def test_something():\n pass\n\n @pytest.fixture\n def fix(self):\n return 1\n\n @staticmethod\n def test_fix(fix):\n assert fix == 1\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*collected 2 items*\", \"*2 passed in*\"])\n\n def test_setup_teardown_class_as_classmethod(self, testdir):\n testdir.makepyfile(\n test_mod1=\"\"\"\n class TestClassMethod(object):\n @classmethod\n def setup_class(cls):\n pass\n def test_1(self):\n pass\n @classmethod\n def teardown_class(cls):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_issue1035_obj_has_getattr(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n class Chameleon(object):\n def __getattr__(self, name):\n return True\n chameleon = Chameleon()\n \"\"\"\n )\n colitems = modcol.collect()\n assert len(colitems) == 0\n\n def test_issue1579_namedtuple(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import collections\n\n TestCase = collections.namedtuple('TestCase', ['a'])\n \"\"\"\n )\n result = testdir.runpytest(\"-rw\")\n result.stdout.fnmatch_lines(\n \"*cannot collect test class 'TestCase' \"\n \"because it has a __new__ constructor*\"\n )\n\n def test_issue2234_property(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class TestCase(object):\n @property\n def prop(self):\n raise NotImplementedError()\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n\n\nclass TestFunction(object):\n def test_getmodulecollector(self, testdir):\n item = testdir.getitem(\"def test_func(): pass\")\n modcol = item.getparent(pytest.Module)\n assert isinstance(modcol, pytest.Module)\n assert hasattr(modcol.obj, \"test_func\")\n\n @pytest.mark.filterwarnings(\"default\")\n def test_function_as_object_instance_ignored(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class A(object):\n def __call__(self, tmpdir):\n 0/0\n\n test_a = A()\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"collected 0 items\",\n \"*test_function_as_object_instance_ignored.py:2: \"\n \"*cannot collect 'test_a' because it is not a function.\",\n ]\n )\n\n @staticmethod\n def make_function(testdir, **kwargs):\n from _pytest.fixtures import FixtureManager\n\n config = testdir.parseconfigure()\n session = testdir.Session(config)\n session._fixturemanager = FixtureManager(session)\n\n return pytest.Function(config=config, parent=session, **kwargs)\n\n def test_function_equality(self, testdir, tmpdir):\n def func1():\n pass\n\n def func2():\n pass\n\n f1 = self.make_function(testdir, name=\"name\", args=(1,), callobj=func1)\n assert f1 == f1\n f2 = self.make_function(testdir, name=\"name\", callobj=func2)\n assert f1 != f2\n\n def test_repr_produces_actual_test_id(self, testdir):\n f = self.make_function(\n testdir, name=r\"test[\\xe5]\", callobj=self.test_repr_produces_actual_test_id\n )\n assert repr(f) == r\"\"\n\n def test_issue197_parametrize_emptyset(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('arg', [])\n def test_function(arg):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(skipped=1)\n\n def test_single_tuple_unwraps_values(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize(('arg',), [(1,)])\n def test_function(arg):\n assert arg == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_issue213_parametrize_value_no_equal(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n class A(object):\n def __eq__(self, other):\n raise ValueError(\"not possible\")\n @pytest.mark.parametrize('arg', [A()])\n def test_function(arg):\n assert arg.__class__.__name__ == \"A\"\n \"\"\"\n )\n reprec = testdir.inline_run(\"--fulltrace\")\n reprec.assertoutcome(passed=1)\n\n def test_parametrize_with_non_hashable_values(self, testdir):\n \"\"\"Test parametrization with non-hashable values.\"\"\"\n testdir.makepyfile(\n \"\"\"\n archival_mapping = {\n '1.0': {'tag': '1.0'},\n '1.2.2a1': {'tag': 'release-1.2.2a1'},\n }\n\n import pytest\n @pytest.mark.parametrize('key value'.split(),\n archival_mapping.items())\n def test_archival_to_version(key, value):\n assert key in archival_mapping\n assert value == archival_mapping[key]\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(passed=2)\n\n def test_parametrize_with_non_hashable_values_indirect(self, testdir):\n \"\"\"Test parametrization with non-hashable values with indirect parametrization.\"\"\"\n testdir.makepyfile(\n \"\"\"\n archival_mapping = {\n '1.0': {'tag': '1.0'},\n '1.2.2a1': {'tag': 'release-1.2.2a1'},\n }\n\n import pytest\n\n @pytest.fixture\n def key(request):\n return request.param\n\n @pytest.fixture\n def value(request):\n return request.param\n\n @pytest.mark.parametrize('key value'.split(),\n archival_mapping.items(), indirect=True)\n def test_archival_to_version(key, value):\n assert key in archival_mapping\n assert value == archival_mapping[key]\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(passed=2)\n\n def test_parametrize_overrides_fixture(self, testdir):\n \"\"\"Test parametrization when parameter overrides existing fixture with same name.\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def value():\n return 'value'\n\n @pytest.mark.parametrize('value',\n ['overridden'])\n def test_overridden_via_param(value):\n assert value == 'overridden'\n\n @pytest.mark.parametrize('somevalue', ['overridden'])\n def test_not_overridden(value, somevalue):\n assert value == 'value'\n assert somevalue == 'overridden'\n\n @pytest.mark.parametrize('other,value', [('foo', 'overridden')])\n def test_overridden_via_multiparam(other, value):\n assert other == 'foo'\n assert value == 'overridden'\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(passed=3)\n\n def test_parametrize_overrides_parametrized_fixture(self, testdir):\n \"\"\"Test parametrization when parameter overrides existing parametrized fixture with same name.\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[1, 2])\n def value(request):\n return request.param\n\n @pytest.mark.parametrize('value',\n ['overridden'])\n def test_overridden_via_param(value):\n assert value == 'overridden'\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(passed=1)\n\n def test_parametrize_overrides_indirect_dependency_fixture(self, testdir):\n \"\"\"Test parametrization when parameter overrides a fixture that a test indirectly depends on\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n fix3_instantiated = False\n\n @pytest.fixture\n def fix1(fix2):\n return fix2 + '1'\n\n @pytest.fixture\n def fix2(fix3):\n return fix3 + '2'\n\n @pytest.fixture\n def fix3():\n global fix3_instantiated\n fix3_instantiated = True\n return '3'\n\n @pytest.mark.parametrize('fix2', ['2'])\n def test_it(fix1):\n assert fix1 == '21'\n assert not fix3_instantiated\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(passed=1)\n\n def test_parametrize_with_mark(self, testdir):\n items = testdir.getitems(\n \"\"\"\n import pytest\n @pytest.mark.foo\n @pytest.mark.parametrize('arg', [\n 1,\n pytest.param(2, marks=[pytest.mark.baz, pytest.mark.bar])\n ])\n def test_function(arg):\n pass\n \"\"\"\n )\n keywords = [item.keywords for item in items]\n assert (\n \"foo\" in keywords[0]\n and \"bar\" not in keywords[0]\n and \"baz\" not in keywords[0]\n )\n assert \"foo\" in keywords[1] and \"bar\" in keywords[1] and \"baz\" in keywords[1]\n\n def test_function_equality_with_callspec(self, testdir, tmpdir):\n items = testdir.getitems(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('arg', [1,2])\n def test_function(arg):\n pass\n \"\"\"\n )\n assert items[0] != items[1]\n assert not (items[0] == items[1])\n\n def test_pyfunc_call(self, testdir):\n item = testdir.getitem(\"def test_func(): raise ValueError\")\n config = item.config\n\n class MyPlugin1(object):\n def pytest_pyfunc_call(self, pyfuncitem):\n raise ValueError\n\n class MyPlugin2(object):\n def pytest_pyfunc_call(self, pyfuncitem):\n return True\n\n config.pluginmanager.register(MyPlugin1())\n config.pluginmanager.register(MyPlugin2())\n config.hook.pytest_runtest_setup(item=item)\n config.hook.pytest_pyfunc_call(pyfuncitem=item)\n\n def test_multiple_parametrize(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('x', [0, 1])\n @pytest.mark.parametrize('y', [2, 3])\n def test1(x, y):\n pass\n \"\"\"\n )\n colitems = modcol.collect()\n assert colitems[0].name == \"test1[2-0]\"\n assert colitems[1].name == \"test1[2-1]\"\n assert colitems[2].name == \"test1[3-0]\"\n assert colitems[3].name == \"test1[3-1]\"\n\n def test_issue751_multiple_parametrize_with_ids(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('x', [0], ids=['c'])\n @pytest.mark.parametrize('y', [0, 1], ids=['a', 'b'])\n class Test(object):\n def test1(self, x, y):\n pass\n def test2(self, x, y):\n pass\n \"\"\"\n )\n colitems = modcol.collect()[0].collect()[0].collect()\n assert colitems[0].name == \"test1[a-c]\"\n assert colitems[1].name == \"test1[b-c]\"\n assert colitems[2].name == \"test2[a-c]\"\n assert colitems[3].name == \"test2[b-c]\"\n\n def test_parametrize_skipif(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n m = pytest.mark.skipif('True')\n\n @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])\n def test_skip_if(x):\n assert x < 2\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed, 1 skipped in *\"])\n\n def test_parametrize_skip(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n m = pytest.mark.skip('')\n\n @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])\n def test_skip(x):\n assert x < 2\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed, 1 skipped in *\"])\n\n def test_parametrize_skipif_no_skip(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n m = pytest.mark.skipif('False')\n\n @pytest.mark.parametrize('x', [0, 1, m(2)])\n def test_skipif_no_skip(x):\n assert x < 2\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 failed, 2 passed in *\"])\n\n def test_parametrize_xfail(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n m = pytest.mark.xfail('True')\n\n @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])\n def test_xfail(x):\n assert x < 2\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed, 1 xfailed in *\"])\n\n def test_parametrize_passed(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n m = pytest.mark.xfail('True')\n\n @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])\n def test_xfail(x):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed, 1 xpassed in *\"])\n\n def test_parametrize_xfail_passed(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n m = pytest.mark.xfail('False')\n\n @pytest.mark.parametrize('x', [0, 1, m(2)])\n def test_passed(x):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 3 passed in *\"])\n\n def test_function_original_name(self, testdir):\n items = testdir.getitems(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('arg', [1,2])\n def test_func(arg):\n pass\n \"\"\"\n )\n assert [x.originalname for x in items] == [\"test_func\", \"test_func\"]\n\n\nclass TestSorting(object):\n def test_check_equality(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n def test_pass(): pass\n def test_fail(): assert 0\n \"\"\"\n )\n fn1 = testdir.collect_by_name(modcol, \"test_pass\")\n assert isinstance(fn1, pytest.Function)\n fn2 = testdir.collect_by_name(modcol, \"test_pass\")\n assert isinstance(fn2, pytest.Function)\n\n assert fn1 == fn2\n assert fn1 != modcol\n if sys.version_info < (3, 0):\n assert cmp(fn1, fn2) == 0 # NOQA\n assert hash(fn1) == hash(fn2)\n\n fn3 = testdir.collect_by_name(modcol, \"test_fail\")\n assert isinstance(fn3, pytest.Function)\n assert not (fn1 == fn3)\n assert fn1 != fn3\n\n for fn in fn1, fn2, fn3:\n assert fn != 3\n assert fn != modcol\n assert fn != [1, 2, 3]\n assert [1, 2, 3] != fn\n assert modcol != fn\n\n def test_allow_sane_sorting_for_decorators(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n def dec(f):\n g = lambda: f(2)\n g.place_as = f\n return g\n\n\n def test_b(y):\n pass\n test_b = dec(test_b)\n\n def test_a(y):\n pass\n test_a = dec(test_a)\n \"\"\"\n )\n colitems = modcol.collect()\n assert len(colitems) == 2\n assert [item.name for item in colitems] == [\"test_b\", \"test_a\"]\n\n\nclass TestConftestCustomization(object):\n def test_pytest_pycollect_module(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n class MyModule(pytest.Module):\n pass\n def pytest_pycollect_makemodule(path, parent):\n if path.basename == \"test_xyz.py\":\n return MyModule(path, parent)\n \"\"\"\n )\n testdir.makepyfile(\"def test_some(): pass\")\n testdir.makepyfile(test_xyz=\"def test_func(): pass\")\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"* 3\n\n def test_traceback_error_during_import(self, testdir):\n testdir.makepyfile(\n \"\"\"\n x = 1\n x = 2\n x = 17\n asd\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret != 0\n out = result.stdout.str()\n assert \"x = 1\" not in out\n assert \"x = 2\" not in out\n result.stdout.fnmatch_lines([\" *asd*\", \"E*NameError*\"])\n result = testdir.runpytest(\"--fulltrace\")\n out = result.stdout.str()\n assert \"x = 1\" in out\n assert \"x = 2\" in out\n result.stdout.fnmatch_lines([\">*asd*\", \"E*NameError*\"])\n\n def test_traceback_filter_error_during_fixture_collection(self, testdir):\n \"\"\"integration test for issue #995.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n def fail_me(func):\n ns = {}\n exec('def w(): raise ValueError(\"fail me\")', ns)\n return ns['w']\n\n @pytest.fixture(scope='class')\n @fail_me\n def fail_fixture():\n pass\n\n def test_failing_fixture(fail_fixture):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret != 0\n out = result.stdout.str()\n assert \"INTERNALERROR>\" not in out\n result.stdout.fnmatch_lines([\"*ValueError: fail me*\", \"* 1 error in *\"])\n\n def test_filter_traceback_generated_code(self):\n \"\"\"test that filter_traceback() works with the fact that\n _pytest._code.code.Code.path attribute might return an str object.\n In this case, one of the entries on the traceback was produced by\n dynamically generated code.\n See: https://bitbucket.org/pytest-dev/py/issues/71\n This fixes #995.\n \"\"\"\n from _pytest.python import filter_traceback\n\n try:\n ns = {}\n exec(\"def foo(): raise ValueError\", ns)\n ns[\"foo\"]()\n except ValueError:\n _, _, tb = sys.exc_info()\n\n tb = _pytest._code.Traceback(tb)\n assert isinstance(tb[-1].path, str)\n assert not filter_traceback(tb[-1])\n\n def test_filter_traceback_path_no_longer_valid(self, testdir):\n \"\"\"test that filter_traceback() works with the fact that\n _pytest._code.code.Code.path attribute might return an str object.\n In this case, one of the files in the traceback no longer exists.\n This fixes #1133.\n \"\"\"\n from _pytest.python import filter_traceback\n\n testdir.syspathinsert()\n testdir.makepyfile(\n filter_traceback_entry_as_str=\"\"\"\n def foo():\n raise ValueError\n \"\"\"\n )\n try:\n import filter_traceback_entry_as_str\n\n filter_traceback_entry_as_str.foo()\n except ValueError:\n _, _, tb = sys.exc_info()\n\n testdir.tmpdir.join(\"filter_traceback_entry_as_str.py\").remove()\n tb = _pytest._code.Traceback(tb)\n assert isinstance(tb[-1].path, str)\n assert filter_traceback(tb[-1])\n\n\nclass TestReportInfo(object):\n def test_itemreport_reportinfo(self, testdir, linecomp):\n testdir.makeconftest(\n \"\"\"\n import pytest\n class MyFunction(pytest.Function):\n def reportinfo(self):\n return \"ABCDE\", 42, \"custom\"\n def pytest_pycollect_makeitem(collector, name, obj):\n if name == \"test_func\":\n return MyFunction(name, parent=collector)\n \"\"\"\n )\n item = testdir.getitem(\"def test_func(): pass\")\n item.config.pluginmanager.getplugin(\"runner\")\n assert item.location == (\"ABCDE\", 42, \"custom\")\n\n def test_func_reportinfo(self, testdir):\n item = testdir.getitem(\"def test_func(): pass\")\n fspath, lineno, modpath = item.reportinfo()\n assert fspath == item.fspath\n assert lineno == 0\n assert modpath == \"test_func\"\n\n def test_class_reportinfo(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n # lineno 0\n class TestClass(object):\n def test_hello(self): pass\n \"\"\"\n )\n classcol = testdir.collect_by_name(modcol, \"TestClass\")\n fspath, lineno, msg = classcol.reportinfo()\n assert fspath == modcol.fspath\n assert lineno == 1\n assert msg == \"TestClass\"\n\n @pytest.mark.filterwarnings(\n \"ignore:usage of Generator.Function is deprecated, please use pytest.Function instead\"\n )\n def test_reportinfo_with_nasty_getattr(self, testdir):\n # https://github.com/pytest-dev/pytest/issues/1204\n modcol = testdir.getmodulecol(\n \"\"\"\n # lineno 0\n class TestClass(object):\n def __getattr__(self, name):\n return \"this is not an int\"\n\n def test_foo(self):\n pass\n \"\"\"\n )\n classcol = testdir.collect_by_name(modcol, \"TestClass\")\n instance = classcol.collect()[0]\n fspath, lineno, msg = instance.reportinfo()\n\n\ndef test_customized_python_discovery(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n python_files=check_*.py\n python_classes=Check\n python_functions=check\n \"\"\"\n )\n p = testdir.makepyfile(\n \"\"\"\n def check_simple():\n pass\n class CheckMyApp(object):\n def check_meth(self):\n pass\n \"\"\"\n )\n p2 = p.new(basename=p.basename.replace(\"test\", \"check\"))\n p.move(p2)\n result = testdir.runpytest(\"--collect-only\", \"-s\")\n result.stdout.fnmatch_lines(\n [\"*check_customized*\", \"*check_simple*\", \"*CheckMyApp*\", \"*check_meth*\"]\n )\n\n result = testdir.runpytest()\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n\ndef test_customized_python_discovery_functions(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n python_functions=_test\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def _test_underscore():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\", \"-s\")\n result.stdout.fnmatch_lines([\"*_test_underscore*\"])\n\n result = testdir.runpytest()\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_unorderable_types(testdir):\n testdir.makepyfile(\n \"\"\"\n class TestJoinEmpty(object):\n pass\n\n def make_test():\n class Test(object):\n pass\n Test.__name__ = \"TestFoo\"\n return Test\n TestFoo = make_test()\n \"\"\"\n )\n result = testdir.runpytest()\n assert \"TypeError\" not in result.stdout.str()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n\n\ndef test_collect_functools_partial(testdir):\n \"\"\"\n Test that collection of functools.partial object works, and arguments\n to the wrapped functions are dealt correctly (see #811).\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import functools\n import pytest\n\n @pytest.fixture\n def fix1():\n return 'fix1'\n\n @pytest.fixture\n def fix2():\n return 'fix2'\n\n def check1(i, fix1):\n assert i == 2\n assert fix1 == 'fix1'\n\n def check2(fix1, i):\n assert i == 2\n assert fix1 == 'fix1'\n\n def check3(fix1, i, fix2):\n assert i == 2\n assert fix1 == 'fix1'\n assert fix2 == 'fix2'\n\n test_ok_1 = functools.partial(check1, i=2)\n test_ok_2 = functools.partial(check1, i=2, fix1='fix1')\n test_ok_3 = functools.partial(check1, 2)\n test_ok_4 = functools.partial(check2, i=2)\n test_ok_5 = functools.partial(check3, i=2)\n test_ok_6 = functools.partial(check3, i=2, fix1='fix1')\n\n test_fail_1 = functools.partial(check2, 2)\n test_fail_2 = functools.partial(check3, 2)\n \"\"\"\n )\n result = testdir.inline_run()\n result.assertoutcome(passed=6, failed=2)\n\n\n@pytest.mark.filterwarnings(\"default\")\ndef test_dont_collect_non_function_callable(testdir):\n \"\"\"Test for issue https://github.com/pytest-dev/pytest/issues/331\n\n In this case an INTERNALERROR occurred trying to report the failure of\n a test like this one because py test failed to get the source lines.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n class Oh(object):\n def __call__(self):\n pass\n\n test_a = Oh()\n\n def test_real():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rw\")\n result.stdout.fnmatch_lines(\n [\n \"*collected 1 item*\",\n \"*test_dont_collect_non_function_callable.py:2: *cannot collect 'test_a' because it is not a function*\",\n \"*1 passed, 1 warnings in *\",\n ]\n )\n\n\ndef test_class_injection_does_not_break_collection(testdir):\n \"\"\"Tests whether injection during collection time will terminate testing.\n\n In this case the error should not occur if the TestClass itself\n is modified during collection time, and the original method list\n is still used for collection.\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n from test_inject import TestClass\n def pytest_generate_tests(metafunc):\n TestClass.changed_var = {}\n \"\"\"\n )\n testdir.makepyfile(\n test_inject='''\n class TestClass(object):\n def test_injection(self):\n \"\"\"Test being parametrized.\"\"\"\n pass\n '''\n )\n result = testdir.runpytest()\n assert (\n \"RuntimeError: dictionary changed size during iteration\"\n not in result.stdout.str()\n )\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_syntax_error_with_non_ascii_chars(testdir):\n \"\"\"Fix decoding issue while formatting SyntaxErrors during collection (#578)\n \"\"\"\n testdir.makepyfile(\n u\"\"\"\n # -*- coding: utf-8 -*-\n\n ☃\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*ERROR collecting*\", \"*SyntaxError*\", \"*1 error in*\"])\n\n\ndef test_skip_duplicates_by_default(testdir):\n \"\"\"Test for issue https://github.com/pytest-dev/pytest/issues/1609 (#1609)\n\n Ignore duplicate directories.\n \"\"\"\n a = testdir.mkdir(\"a\")\n fh = a.join(\"test_a.py\")\n fh.write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n def test_real():\n pass\n \"\"\"\n )\n )\n result = testdir.runpytest(a.strpath, a.strpath)\n result.stdout.fnmatch_lines([\"*collected 1 item*\"])\n\n\ndef test_keep_duplicates(testdir):\n \"\"\"Test for issue https://github.com/pytest-dev/pytest/issues/1609 (#1609)\n\n Use --keep-duplicates to collect tests from duplicate directories.\n \"\"\"\n a = testdir.mkdir(\"a\")\n fh = a.join(\"test_a.py\")\n fh.write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n def test_real():\n pass\n \"\"\"\n )\n )\n result = testdir.runpytest(\"--keep-duplicates\", a.strpath, a.strpath)\n result.stdout.fnmatch_lines([\"*collected 2 item*\"])\n\n\ndef test_package_collection_infinite_recursion(testdir):\n testdir.copy_example(\"collect/package_infinite_recursion\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_package_collection_init_given_as_argument(testdir):\n \"\"\"Regression test for #3749\"\"\"\n p = testdir.copy_example(\"collect/package_init_given_as_arg\")\n result = testdir.runpytest(p / \"pkg\" / \"__init__.py\")\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_package_with_modules(testdir):\n \"\"\"\n .\n └── root\n ├── __init__.py\n ├── sub1\n │ ├── __init__.py\n │ └── sub1_1\n │ ├── __init__.py\n │ └── test_in_sub1.py\n └── sub2\n └── test\n └── test_in_sub2.py\n\n \"\"\"\n root = testdir.mkpydir(\"root\")\n sub1 = root.mkdir(\"sub1\")\n sub1.ensure(\"__init__.py\")\n sub1_test = sub1.mkdir(\"sub1_1\")\n sub1_test.ensure(\"__init__.py\")\n sub2 = root.mkdir(\"sub2\")\n sub2_test = sub2.mkdir(\"sub2\")\n\n sub1_test.join(\"test_in_sub1.py\").write(\"def test_1(): pass\")\n sub2_test.join(\"test_in_sub2.py\").write(\"def test_2(): pass\")\n\n # Execute from .\n result = testdir.runpytest(\"-v\", \"-s\")\n result.assert_outcomes(passed=2)\n\n # Execute from . with one argument \"root\"\n result = testdir.runpytest(\"-v\", \"-s\", \"root\")\n result.assert_outcomes(passed=2)\n\n # Chdir into package's root and execute with no args\n root.chdir()\n result = testdir.runpytest(\"-v\", \"-s\")\n result.assert_outcomes(passed=2)\n\n\ndef test_package_ordering(testdir):\n \"\"\"\n .\n └── root\n ├── Test_root.py\n ├── __init__.py\n ├── sub1\n │ ├── Test_sub1.py\n │ └── __init__.py\n └── sub2\n └── test\n └── test_sub2.py\n\n \"\"\"\n testdir.makeini(\n \"\"\"\n [pytest]\n python_files=*.py\n \"\"\"\n )\n root = testdir.mkpydir(\"root\")\n sub1 = root.mkdir(\"sub1\")\n sub1.ensure(\"__init__.py\")\n sub2 = root.mkdir(\"sub2\")\n sub2_test = sub2.mkdir(\"sub2\")\n\n root.join(\"Test_root.py\").write(\"def test_1(): pass\")\n sub1.join(\"Test_sub1.py\").write(\"def test_2(): pass\")\n sub2_test.join(\"test_sub2.py\").write(\"def test_3(): pass\")\n\n # Execute from .\n result = testdir.runpytest(\"-v\", \"-s\")\n result.assert_outcomes(passed=3)\n"},{"className":"TestModule","col":0,"comment":"null","endLoc":134,"id":3461,"nodeType":"Class","startLoc":12,"text":"class TestModule(object):\n def test_failing_import(self, testdir):\n modcol = testdir.getmodulecol(\"import alksdjalskdjalkjals\")\n pytest.raises(Collector.CollectError, modcol.collect)\n\n def test_import_duplicate(self, testdir):\n a = testdir.mkdir(\"a\")\n b = testdir.mkdir(\"b\")\n p = a.ensure(\"test_whatever.py\")\n p.pyimport()\n del sys.modules[\"test_whatever\"]\n b.ensure(\"test_whatever.py\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*import*mismatch*\",\n \"*imported*test_whatever*\",\n \"*%s*\" % a.join(\"test_whatever.py\"),\n \"*not the same*\",\n \"*%s*\" % b.join(\"test_whatever.py\"),\n \"*HINT*\",\n ]\n )\n\n def test_import_prepend_append(self, testdir, monkeypatch):\n root1 = testdir.mkdir(\"root1\")\n root2 = testdir.mkdir(\"root2\")\n root1.ensure(\"x456.py\")\n root2.ensure(\"x456.py\")\n p = root2.join(\"test_x456.py\")\n monkeypatch.syspath_prepend(str(root1))\n p.write(\n textwrap.dedent(\n \"\"\"\\\n import x456\n def test():\n assert x456.__file__.startswith({!r})\n \"\"\".format(\n str(root2)\n )\n )\n )\n with root2.as_cwd():\n reprec = testdir.inline_run(\"--import-mode=append\")\n reprec.assertoutcome(passed=0, failed=1)\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_syntax_error_in_module(self, testdir):\n modcol = testdir.getmodulecol(\"this is a syntax error\")\n pytest.raises(modcol.CollectError, modcol.collect)\n pytest.raises(modcol.CollectError, modcol.collect)\n\n def test_module_considers_pluginmanager_at_import(self, testdir):\n modcol = testdir.getmodulecol(\"pytest_plugins='xasdlkj',\")\n pytest.raises(ImportError, lambda: modcol.obj)\n\n def test_invalid_test_module_name(self, testdir):\n a = testdir.mkdir(\"a\")\n a.ensure(\"test_one.part1.py\")\n result = testdir.runpytest(\"-rw\")\n result.stdout.fnmatch_lines(\n [\n \"ImportError while importing test module*test_one.part1*\",\n \"Hint: make sure your test modules/packages have valid Python names.\",\n ]\n )\n\n @pytest.mark.parametrize(\"verbose\", [0, 1, 2])\n def test_show_traceback_import_error(self, testdir, verbose):\n \"\"\"Import errors when collecting modules should display the traceback (#1976).\n\n With low verbosity we omit pytest and internal modules, otherwise show all traceback entries.\n \"\"\"\n testdir.makepyfile(\n foo_traceback_import_error=\"\"\"\n from bar_traceback_import_error import NOT_AVAILABLE\n \"\"\",\n bar_traceback_import_error=\"\",\n )\n testdir.makepyfile(\n \"\"\"\n import foo_traceback_import_error\n \"\"\"\n )\n args = (\"-v\",) * verbose\n result = testdir.runpytest(*args)\n result.stdout.fnmatch_lines(\n [\n \"ImportError while importing test module*\",\n \"Traceback:\",\n \"*from bar_traceback_import_error import NOT_AVAILABLE\",\n \"*cannot import name *NOT_AVAILABLE*\",\n ]\n )\n assert result.ret == 2\n\n stdout = result.stdout.str()\n for name in (\"_pytest\", os.path.join(\"py\", \"_path\")):\n if verbose == 2:\n assert name in stdout\n else:\n assert name not in stdout\n\n def test_show_traceback_import_error_unicode(self, testdir):\n \"\"\"Check test modules collected which raise ImportError with unicode messages\n are handled properly (#2336).\n \"\"\"\n testdir.makepyfile(\n u\"\"\"\n # -*- coding: utf-8 -*-\n raise ImportError(u'Something bad happened ☺')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"ImportError while importing test module*\",\n \"Traceback:\",\n \"*raise ImportError*Something bad happened*\",\n ]\n )\n assert result.ret == 2"},{"col":4,"comment":"null","endLoc":320,"header":"def test_doctest_unex_importerror_only_txt(self, testdir)","id":3462,"name":"test_doctest_unex_importerror_only_txt","nodeType":"Function","startLoc":305,"text":"def test_doctest_unex_importerror_only_txt(self, testdir):\n testdir.maketxtfile(\n \"\"\"\n >>> import asdalsdkjaslkdjasd\n >>>\n \"\"\"\n )\n result = testdir.runpytest()\n # doctest is never executed because of error during hello.py collection\n result.stdout.fnmatch_lines(\n [\n \"*>>> import asdals*\",\n \"*UNEXPECTED*{e}*\".format(e=MODULE_NOT_FOUND_ERROR),\n \"{e}: No module named *asdal*\".format(e=MODULE_NOT_FOUND_ERROR),\n ]\n )"},{"col":4,"comment":"null","endLoc":15,"header":"def test_failing_import(self, testdir)","id":3463,"name":"test_failing_import","nodeType":"Function","startLoc":13,"text":"def test_failing_import(self, testdir):\n modcol = testdir.getmodulecol(\"import alksdjalskdjalkjals\")\n pytest.raises(Collector.CollectError, modcol.collect)"},{"col":8,"comment":"null","endLoc":433,"header":"def getvalue(self)","id":3464,"name":"getvalue","nodeType":"Function","startLoc":432,"text":"def getvalue(self):\n return self.buffer.getvalue().decode(\"UTF-8\")"},{"fileName":"conftest.py","filePath":"testing/example_scripts/fixtures/fill_fixtures/test_conftest_funcargs_only_available_in_subdir/sub1","id":3466,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\n@pytest.fixture\ndef arg1(request):\n with pytest.raises(Exception):\n request.getfixturevalue(\"arg2\")\n"},{"col":0,"comment":"null","endLoc":8,"header":"@pytest.fixture\ndef arg1(request)","id":3467,"name":"arg1","nodeType":"Function","startLoc":5,"text":"@pytest.fixture\ndef arg1(request):\n with pytest.raises(Exception):\n request.getfixturevalue(\"arg2\")"},{"col":4,"comment":"null","endLoc":344,"header":"def test_doctest_unex_importerror_with_module(self, testdir)","id":3468,"name":"test_doctest_unex_importerror_with_module","nodeType":"Function","startLoc":322,"text":"def test_doctest_unex_importerror_with_module(self, testdir):\n testdir.tmpdir.join(\"hello.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import asdalsdkjaslkdjasd\n \"\"\"\n )\n )\n testdir.maketxtfile(\n \"\"\"\n >>> import hello\n >>>\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\")\n # doctest is never executed because of error during hello.py collection\n result.stdout.fnmatch_lines(\n [\n \"*ERROR collecting hello.py*\",\n \"*{e}: No module named *asdals*\".format(e=MODULE_NOT_FOUND_ERROR),\n \"*Interrupted: 1 errors during collection*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":34,"header":"def test_import_duplicate(self, testdir)","id":3470,"name":"test_import_duplicate","nodeType":"Function","startLoc":17,"text":"def test_import_duplicate(self, testdir):\n a = testdir.mkdir(\"a\")\n b = testdir.mkdir(\"b\")\n p = a.ensure(\"test_whatever.py\")\n p.pyimport()\n del sys.modules[\"test_whatever\"]\n b.ensure(\"test_whatever.py\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*import*mismatch*\",\n \"*imported*test_whatever*\",\n \"*%s*\" % a.join(\"test_whatever.py\"),\n \"*not the same*\",\n \"*%s*\" % b.join(\"test_whatever.py\"),\n \"*HINT*\",\n ]\n )"},{"attributeType":"null","col":8,"comment":"null","endLoc":346,"id":3471,"name":"parent","nodeType":"Attribute","startLoc":346,"text":"self.parent"},{"attributeType":"dict","col":8,"comment":"null","endLoc":347,"id":3472,"name":"_markers","nodeType":"Attribute","startLoc":347,"text":"self._markers"},{"className":"NodeMarkers","col":0,"comment":"\n internal structure for storing marks belonging to a node\n\n ..warning::\n\n unstable api\n\n ","endLoc":408,"id":3473,"nodeType":"Class","startLoc":380,"text":"@attr.s(cmp=False, hash=False)\nclass NodeMarkers(object):\n \"\"\"\n internal structure for storing marks belonging to a node\n\n ..warning::\n\n unstable api\n\n \"\"\"\n\n own_markers = attr.ib(default=attr.Factory(list))\n\n def update(self, add_markers):\n \"\"\"update the own markers\n \"\"\"\n self.own_markers.extend(add_markers)\n\n def find(self, name):\n \"\"\"\n find markers in own nodes or parent nodes\n needs a better place\n \"\"\"\n for mark in self.own_markers:\n if mark.name == name:\n yield mark\n\n def __iter__(self):\n return iter(self.own_markers)"},{"col":4,"comment":"update the own markers\n ","endLoc":396,"header":"def update(self, add_markers)","id":3474,"name":"update","nodeType":"Function","startLoc":393,"text":"def update(self, add_markers):\n \"\"\"update the own markers\n \"\"\"\n self.own_markers.extend(add_markers)"},{"col":4,"comment":"Mark import names as needing to be rewritten.\n\n The named module or package as well as any nested modules will\n be rewritten on import.\n ","endLoc":271,"header":"def mark_rewrite(self, *names)","id":3475,"name":"mark_rewrite","nodeType":"Function","startLoc":256,"text":"def mark_rewrite(self, *names):\n \"\"\"Mark import names as needing to be rewritten.\n\n The named module or package as well as any nested modules will\n be rewritten on import.\n \"\"\"\n already_imported = (\n set(names).intersection(sys.modules).difference(self._rewritten_names)\n )\n for name in already_imported:\n if not AssertionRewriter.is_rewrite_disabled(\n sys.modules[name].__doc__ or \"\"\n ):\n self._warn_already_imported(name)\n self._must_rewrite.update(names)\n self._marked_for_rewrite_cache.clear()"},{"col":4,"comment":"null","endLoc":358,"header":"def test_doctestmodule(self, testdir)","id":3476,"name":"test_doctestmodule","nodeType":"Function","startLoc":346,"text":"def test_doctestmodule(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n '''\n >>> x = 1\n >>> x == 1\n False\n\n '''\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(failed=1)"},{"col":4,"comment":"null","endLoc":58,"header":"def test_import_prepend_append(self, testdir, monkeypatch)","id":3477,"name":"test_import_prepend_append","nodeType":"Function","startLoc":36,"text":"def test_import_prepend_append(self, testdir, monkeypatch):\n root1 = testdir.mkdir(\"root1\")\n root2 = testdir.mkdir(\"root2\")\n root1.ensure(\"x456.py\")\n root2.ensure(\"x456.py\")\n p = root2.join(\"test_x456.py\")\n monkeypatch.syspath_prepend(str(root1))\n p.write(\n textwrap.dedent(\n \"\"\"\\\n import x456\n def test():\n assert x456.__file__.startswith({!r})\n \"\"\".format(\n str(root2)\n )\n )\n )\n with root2.as_cwd():\n reprec = testdir.inline_run(\"--import-mode=append\")\n reprec.assertoutcome(passed=0, failed=1)\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":"\n find markers in own nodes or parent nodes\n needs a better place\n ","endLoc":405,"header":"def find(self, name)","id":3478,"name":"find","nodeType":"Function","startLoc":398,"text":"def find(self, name):\n \"\"\"\n find markers in own nodes or parent nodes\n needs a better place\n \"\"\"\n for mark in self.own_markers:\n if mark.name == name:\n yield mark"},{"col":4,"comment":"null","endLoc":408,"header":"def __iter__(self)","id":3479,"name":"__iter__","nodeType":"Function","startLoc":407,"text":"def __iter__(self):\n return iter(self.own_markers)"},{"attributeType":"null","col":4,"comment":"null","endLoc":391,"id":3480,"name":"own_markers","nodeType":"Attribute","startLoc":391,"text":"own_markers"},{"col":0,"comment":"null","endLoc":28,"header":"def alias(name, warning=None)","id":3481,"name":"alias","nodeType":"Function","startLoc":21,"text":"def alias(name, warning=None):\n getter = attrgetter(name)\n\n def warned(self):\n warnings.warn(warning, stacklevel=2)\n return getter(self)\n\n return property(getter if warning is None else warned, doc=\"alias for \" + name)"},{"col":0,"comment":"null","endLoc":83,"header":"def test_parseconfig(testdir)","id":3483,"name":"test_parseconfig","nodeType":"Function","startLoc":79,"text":"def test_parseconfig(testdir):\n config1 = testdir.parseconfig()\n config2 = testdir.parseconfig()\n assert config2 != config1\n assert config1 != pytest.config"},{"col":0,"comment":"null","endLoc":95,"header":"def test_testdir_runs_with_plugin(testdir)","id":3484,"name":"test_testdir_runs_with_plugin","nodeType":"Function","startLoc":86,"text":"def test_testdir_runs_with_plugin(testdir):\n testdir.makepyfile(\n \"\"\"\n pytest_plugins = \"pytester\"\n def test_hello(testdir):\n assert 1\n \"\"\"\n )\n result = testdir.runpytest()\n result.assert_outcomes(passed=1)"},{"col":0,"comment":"null","endLoc":112,"header":"def test_runresult_assertion_on_xfail(testdir)","id":3485,"name":"test_runresult_assertion_on_xfail","nodeType":"Function","startLoc":98,"text":"def test_runresult_assertion_on_xfail(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n pytest_plugins = \"pytester\"\n\n @pytest.mark.xfail\n def test_potato():\n assert False\n \"\"\"\n )\n result = testdir.runpytest()\n result.assert_outcomes(xfailed=1)\n assert result.ret == 0"},{"col":0,"comment":"null","endLoc":129,"header":"def test_runresult_assertion_on_xpassed(testdir)","id":3486,"name":"test_runresult_assertion_on_xpassed","nodeType":"Function","startLoc":115,"text":"def test_runresult_assertion_on_xpassed(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n pytest_plugins = \"pytester\"\n\n @pytest.mark.xfail\n def test_potato():\n assert True\n \"\"\"\n )\n result = testdir.runpytest()\n result.assert_outcomes(xpassed=1)\n assert result.ret == 0"},{"col":0,"comment":"null","endLoc":140,"header":"def test_runresult_repr()","id":3487,"name":"test_runresult_repr","nodeType":"Function","startLoc":132,"text":"def test_runresult_repr():\n from _pytest.pytester import RunResult\n\n assert (\n repr(\n RunResult(ret=\"ret\", outlines=[\"\"], errlines=[\"some\", \"errors\"], duration=1)\n )\n == \"\"\n )"},{"id":3488,"name":"py27-py34-deprecation.rst","nodeType":"TextFile","path":"doc/en","text":"Python 2.7 and 3.4 support plan\n===============================\n\nPython 2.7 EOL is fast approaching, with\nupstream support `ending in 2020 `__.\nPython 3.4's last release is scheduled for\n`March 2019 `__. pytest is one of\nthe participating projects of the https://python3statement.org.\n\nThe **pytest 4.6** series will be the last to support Python 2.7 and 3.4, and is scheduled\nto be released by **mid-2019**. **pytest 5.0** and onwards will support only Python 3.5+.\n\nThanks to the `python_requires`_ ``setuptools`` option,\nPython 2.7 and Python 3.4 users using a modern ``pip`` version\nwill install the last pytest ``4.6`` version automatically even if ``5.0`` or later\nare available on PyPI.\n\nWhile pytest ``5.0`` will be the new mainstream and development version, until **January 2020**\nthe pytest core team plans to make bug-fix releases of the pytest ``4.6`` series by\nback-porting patches to the ``4.6-maintenance`` branch that affect Python 2 users.\n\n**After 2020**, the core team will no longer actively backport patches, but the ``4.6-maintenance``\nbranch will continue to exist so the community itself can contribute patches. The core team will\nbe happy to accept those patches and make new ``4.6`` releases **until mid-2020**.\n\n.. _`python_requires`: https://packaging.python.org/guides/distributing-packages-using-setuptools/#python-requires>\n"},{"col":4,"comment":"null","endLoc":385,"header":"def test_doctestmodule_external_and_issue116(self, testdir)","id":3489,"name":"test_doctestmodule_external_and_issue116","nodeType":"Function","startLoc":360,"text":"def test_doctestmodule_external_and_issue116(self, testdir):\n p = testdir.mkpydir(\"hello\")\n p.join(\"__init__.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def somefunc():\n '''\n >>> i = 0\n >>> i + 1\n 2\n '''\n \"\"\"\n )\n )\n result = testdir.runpytest(p, \"--doctest-modules\")\n result.stdout.fnmatch_lines(\n [\n \"003 *>>> i = 0\",\n \"004 *>>> i + 1\",\n \"*Expected:\",\n \"* 2\",\n \"*Got:\",\n \"* 1\",\n \"*:4: DocTestFailure\",\n ]\n )"},{"col":4,"comment":"null","endLoc":383,"header":"def __init__(self, ret, outlines, errlines, duration)","id":3494,"name":"__init__","nodeType":"Function","startLoc":377,"text":"def __init__(self, ret, outlines, errlines, duration):\n self.ret = ret\n self.outlines = outlines\n self.errlines = errlines\n self.stdout = LineMatcher(outlines)\n self.stderr = LineMatcher(errlines)\n self.duration = duration"},{"col":0,"comment":"null","endLoc":157,"header":"def test_xpassed_with_strict_is_considered_a_failure(testdir)","id":3495,"name":"test_xpassed_with_strict_is_considered_a_failure","nodeType":"Function","startLoc":143,"text":"def test_xpassed_with_strict_is_considered_a_failure(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n pytest_plugins = \"pytester\"\n\n @pytest.mark.xfail(strict=True)\n def test_potato():\n assert True\n \"\"\"\n )\n result = testdir.runpytest()\n result.assert_outcomes(failed=1)\n assert result.ret != 0"},{"fileName":"conf.py","filePath":"doc/en","id":3496,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n#\n# pytest documentation build configuration file, created by\n# sphinx-quickstart on Fri Oct 8 17:54:28 2010.\n#\n# This file is execfile()d with the current directory set to its containing dir.\n#\n# Note that not all possible configuration values are present in this\n# autogenerated file.\n#\n# All configuration values have a default; values that are commented out\n# serve to show the default.\n# The version info for the project you're documenting, acts as replacement for\n# |version| and |release|, also used in various other places throughout the\n# built documents.\n#\n# The full version, including alpha/beta/rc tags.\n# The short X.Y version.\nimport datetime\nimport os\nimport sys\n\nfrom _pytest import __version__ as version\n\nrelease = \".\".join(version.split(\".\")[:2])\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n# sys.path.insert(0, os.path.abspath('.'))\n\nautodoc_member_order = \"bysource\"\ntodo_include_todos = 1\n\n# -- General configuration -----------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\n# needs_sphinx = '1.0'\n\n# Add any Sphinx extension module names here, as strings. They can be extensions\n# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.\nextensions = [\n \"pygments_pytest\",\n \"sphinx.ext.autodoc\",\n \"sphinx.ext.autosummary\",\n \"sphinx.ext.intersphinx\",\n \"sphinx.ext.todo\",\n \"sphinx.ext.viewcode\",\n \"sphinx_removed_in\",\n \"sphinxcontrib_trio\",\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = [\"_templates\"]\n\n# The suffix of source filenames.\nsource_suffix = \".rst\"\n\n# The encoding of source files.\n# source_encoding = 'utf-8-sig'\n\n# The master toctree document.\nmaster_doc = \"contents\"\n\n# General information about the project.\nproject = u\"pytest\"\nyear = datetime.datetime.utcnow().year\ncopyright = u\"2015–2019 , holger krekel and pytest-dev team\"\n\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n# language = None\n\n# There are two options for replacing |today|: either, you set today to some\n# non-false value, then it is used:\n# today = ''\n# Else, today_fmt is used as the format for a strftime call.\n# today_fmt = '%B %d, %Y'\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\nexclude_patterns = [\n \"links.inc\",\n \"_build\",\n \"naming20.rst\",\n \"test/*\",\n \"old_*\",\n \"*attic*\",\n \"*/attic*\",\n \"funcargs.rst\",\n \"setup.rst\",\n \"example/remoteinterp.rst\",\n]\n\n\n# The reST default role (used for this markup: `text`) to use for all documents.\n# default_role = None\n\n# If true, '()' will be appended to :func: etc. cross-reference text.\n# add_function_parentheses = True\n\n# If true, the current module name will be prepended to all description\n# unit titles (such as .. function::).\nadd_module_names = False\n\n# If true, sectionauthor and moduleauthor directives will be shown in the\n# output. They are ignored by default.\n# show_authors = False\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = \"sphinx\"\n\n\n# A list of ignored prefixes for module index sorting.\n# modindex_common_prefix = []\n\n\n# -- Options for HTML output ---------------------------------------------------\n\nsys.path.append(os.path.abspath(\"_themes\"))\nhtml_theme_path = [\"_themes\"]\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\nhtml_theme = \"flask\"\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further. For a list of options available for each theme, see the\n# documentation.\nhtml_theme_options = {\"index_logo\": None}\n\n# Add any paths that contain custom themes here, relative to this directory.\n# html_theme_path = []\n\n# The name for this set of Sphinx documents. If None, it defaults to\n# \" v documentation\".\nhtml_title = \"pytest documentation\"\n\n# A shorter title for the navigation bar. Default is the same as html_title.\nhtml_short_title = \"pytest-%s\" % release\n\n# The name of an image file (relative to this directory) to place at the top\n# of the sidebar.\nhtml_logo = \"img/pytest1.png\"\n\n# The name of an image file (within the static path) to use as favicon of the\n# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32\n# pixels large.\nhtml_favicon = \"img/pytest1favi.ico\"\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\n# html_static_path = ['_static']\n\n# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,\n# using the given strftime format.\n# html_last_updated_fmt = '%b %d, %Y'\n\n# If true, SmartyPants will be used to convert quotes and dashes to\n# typographically correct entities.\n# html_use_smartypants = True\n\n# Custom sidebar templates, maps document names to template names.\n# html_sidebars = {}\n# html_sidebars = {'index': 'indexsidebar.html'}\n\nhtml_sidebars = {\n \"index\": [\n \"sidebarintro.html\",\n \"globaltoc.html\",\n \"links.html\",\n \"sourcelink.html\",\n \"searchbox.html\",\n ],\n \"**\": [\n \"globaltoc.html\",\n \"relations.html\",\n \"links.html\",\n \"sourcelink.html\",\n \"searchbox.html\",\n ],\n}\n\n# Additional templates that should be rendered to pages, maps page names to\n# template names.\n# html_additional_pages = {}\n# html_additional_pages = {'index': 'index.html'}\n\n\n# If false, no module index is generated.\nhtml_domain_indices = True\n\n# If false, no index is generated.\nhtml_use_index = False\n\n# If true, the index is split into individual pages for each letter.\n# html_split_index = False\n\n# If true, links to the reST sources are added to the pages.\nhtml_show_sourcelink = False\n\n# If true, \"Created using Sphinx\" is shown in the HTML footer. Default is True.\n# html_show_sphinx = True\n\n# If true, \"(C) Copyright ...\" is shown in the HTML footer. Default is True.\n# html_show_copyright = True\n\n# If true, an OpenSearch description file will be output, and all pages will\n# contain a tag referring to it. The value of this option must be the\n# base URL from which the finished HTML is served.\n# html_use_opensearch = ''\n\n# This is the file name suffix for HTML files (e.g. \".xhtml\").\n# html_file_suffix = None\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = \"pytestdoc\"\n\n\n# -- Options for LaTeX output --------------------------------------------------\n\n# The paper size ('letter' or 'a4').\n# latex_paper_size = 'letter'\n\n# The font size ('10pt', '11pt' or '12pt').\n# latex_font_size = '10pt'\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title, author, documentclass [howto/manual]).\nlatex_documents = [\n (\n \"contents\",\n \"pytest.tex\",\n u\"pytest Documentation\",\n u\"holger krekel, trainer and consultant, http://merlinux.eu\",\n \"manual\",\n )\n]\n\n# The name of an image file (relative to this directory) to place at the top of\n# the title page.\nlatex_logo = \"img/pytest1.png\"\n\n# For \"manual\" documents, if this is true, then toplevel headings are parts,\n# not chapters.\n# latex_use_parts = False\n\n# If true, show page references after internal links.\n# latex_show_pagerefs = False\n\n# If true, show URL addresses after external links.\n# latex_show_urls = False\n\n# Additional stuff for the LaTeX preamble.\n# latex_preamble = ''\n\n# Documents to append as an appendix to all manuals.\n# latex_appendices = []\n\n# If false, no module index is generated.\nlatex_domain_indices = False\n\n# -- Options for manual page output --------------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [(\"usage\", \"pytest\", u\"pytest usage\", [u\"holger krekel at merlinux eu\"], 1)]\n\n\n# -- Options for Epub output ---------------------------------------------------\n\n# Bibliographic Dublin Core info.\nepub_title = u\"pytest\"\nepub_author = u\"holger krekel at merlinux eu\"\nepub_publisher = u\"holger krekel at merlinux eu\"\nepub_copyright = u\"2013, holger krekel et alii\"\n\n# The language of the text. It defaults to the language option\n# or en if the language is not set.\n# epub_language = ''\n\n# The scheme of the identifier. Typical schemes are ISBN or URL.\n# epub_scheme = ''\n\n# The unique identifier of the text. This can be a ISBN number\n# or the project homepage.\n# epub_identifier = ''\n\n# A unique identification for the text.\n# epub_uid = ''\n\n# HTML files that should be inserted before the pages created by sphinx.\n# The format is a list of tuples containing the path and title.\n# epub_pre_files = []\n\n# HTML files shat should be inserted after the pages created by sphinx.\n# The format is a list of tuples containing the path and title.\n# epub_post_files = []\n\n# A list of files that should not be packed into the epub file.\n# epub_exclude_files = []\n\n# The depth of the table of contents in toc.ncx.\n# epub_tocdepth = 3\n\n# Allow duplicate toc entries.\n# epub_tocdup = True\n\n\n# -- Options for texinfo output ------------------------------------------------\n\ntexinfo_documents = [\n (\n master_doc,\n \"pytest\",\n \"pytest Documentation\",\n (\n \"Holger Krekel@*Benjamin Peterson@*Ronny Pfannschmidt@*\"\n \"Floris Bruynooghe@*others\"\n ),\n \"pytest\",\n \"simple powerful testing with Python\",\n \"Programming\",\n 1,\n )\n]\n\n\n# Example configuration for intersphinx: refer to the Python standard library.\nintersphinx_mapping = {\"python\": (\"https://docs.python.org/3\", None)}\n\n\ndef setup(app):\n # from sphinx.ext.autodoc import cut_lines\n # app.connect('autodoc-process-docstring', cut_lines(4, what=['module']))\n app.add_object_type(\n \"confval\",\n \"confval\",\n objname=\"configuration value\",\n indextemplate=\"pair: %s; configuration value\",\n )\n"},{"col":0,"comment":"null","endLoc":178,"header":"def make_holder()","id":3497,"name":"make_holder","nodeType":"Function","startLoc":160,"text":"def make_holder():\n class apiclass(object):\n def pytest_xyz(self, arg):\n \"x\"\n\n def pytest_xyz_noarg(self):\n \"x\"\n\n apimod = type(os)(\"api\")\n\n def pytest_xyz(arg):\n \"x\"\n\n def pytest_xyz_noarg():\n \"x\"\n\n apimod.pytest_xyz = pytest_xyz\n apimod.pytest_xyz_noarg = pytest_xyz_noarg\n return apiclass, apimod"},{"col":4,"comment":"null","endLoc":406,"header":"def test_txtfile_failing(self, testdir)","id":3498,"name":"test_txtfile_failing","nodeType":"Function","startLoc":387,"text":"def test_txtfile_failing(self, testdir):\n p = testdir.maketxtfile(\n \"\"\"\n >>> i = 0\n >>> i + 1\n 2\n \"\"\"\n )\n result = testdir.runpytest(p, \"-s\")\n result.stdout.fnmatch_lines(\n [\n \"001 >>> i = 0\",\n \"002 >>> i + 1\",\n \"Expected:\",\n \" 2\",\n \"Got:\",\n \" 1\",\n \"*test_txtfile_failing.txt:2: DocTestFailure\",\n ]\n )"},{"col":0,"comment":"","endLoc":2,"header":"structures.py#","id":3500,"name":"","nodeType":"Function","startLoc":2,"text":"EMPTY_PARAMETERSET_OPTION = \"empty_parameter_set_mark\"\n\nMARK_GEN = MarkGenerator()"},{"col":0,"comment":"null","endLoc":343,"header":"def setup(app)","id":3501,"name":"setup","nodeType":"Function","startLoc":335,"text":"def setup(app):\n # from sphinx.ext.autodoc import cut_lines\n # app.connect('autodoc-process-docstring', cut_lines(4, what=['module']))\n app.add_object_type(\n \"confval\",\n \"confval\",\n objname=\"configuration value\",\n indextemplate=\"pair: %s; configuration value\",\n )"},{"col":4,"comment":"null","endLoc":417,"header":"def test_txtfile_with_fixtures(self, testdir)","id":3502,"name":"test_txtfile_with_fixtures","nodeType":"Function","startLoc":408,"text":"def test_txtfile_with_fixtures(self, testdir):\n p = testdir.maketxtfile(\n \"\"\"\n >>> dir = getfixture('tmpdir')\n >>> type(dir).__name__\n 'LocalPath'\n \"\"\"\n )\n reprec = testdir.inline_run(p)\n reprec.assertoutcome(passed=1)"},{"id":3503,"name":"tmpdir.rst","nodeType":"TextFile","path":"doc/en","text":"\n.. _`tmpdir handling`:\n.. _tmpdir:\n\nTemporary directories and files\n================================================\n\nThe ``tmp_path`` fixture\n------------------------\n\n\n\n\nYou can use the ``tmp_path`` fixture which will\nprovide a temporary directory unique to the test invocation,\ncreated in the `base temporary directory`_.\n\n``tmp_path`` is a ``pathlib/pathlib2.Path`` object. Here is an example test usage:\n\n.. code-block:: python\n\n # content of test_tmp_path.py\n import os\n\n CONTENT = u\"content\"\n\n\n def test_create_file(tmp_path):\n d = tmp_path / \"sub\"\n d.mkdir()\n p = d / \"hello.txt\"\n p.write_text(CONTENT)\n assert p.read_text() == CONTENT\n assert len(list(tmp_path.iterdir())) == 1\n assert 0\n\nRunning this would result in a passed test except for the last\n``assert 0`` line which we use to look at values:\n\n.. code-block:: pytest\n\n $ pytest test_tmp_path.py\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 1 item\n\n test_tmp_path.py F [100%]\n\n ================================= FAILURES =================================\n _____________________________ test_create_file _____________________________\n\n tmp_path = PosixPath('PYTEST_TMPDIR/test_create_file0')\n\n def test_create_file(tmp_path):\n d = tmp_path / \"sub\"\n d.mkdir()\n p = d / \"hello.txt\"\n p.write_text(CONTENT)\n assert p.read_text() == CONTENT\n assert len(list(tmp_path.iterdir())) == 1\n > assert 0\n E assert 0\n\n test_tmp_path.py:13: AssertionError\n ========================= 1 failed in 0.12 seconds =========================\n\n.. _`tmp_path_factory example`:\n\nThe ``tmp_path_factory`` fixture\n--------------------------------\n\n\n\n\nThe ``tmp_path_factory`` is a session-scoped fixture which can be used\nto create arbitrary temporary directories from any other fixture or test.\n\nIt is intended to replace ``tmpdir_factory``, and returns :class:`pathlib.Path` instances.\n\nSee :ref:`tmp_path_factory API ` for details.\n\n\nThe 'tmpdir' fixture\n--------------------\n\nYou can use the ``tmpdir`` fixture which will\nprovide a temporary directory unique to the test invocation,\ncreated in the `base temporary directory`_.\n\n``tmpdir`` is a `py.path.local`_ object which offers ``os.path`` methods\nand more. Here is an example test usage::\n\n # content of test_tmpdir.py\n import os\n def test_create_file(tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"hello.txt\")\n p.write(\"content\")\n assert p.read() == \"content\"\n assert len(tmpdir.listdir()) == 1\n assert 0\n\nRunning this would result in a passed test except for the last\n``assert 0`` line which we use to look at values:\n\n.. code-block:: pytest\n\n $ pytest test_tmpdir.py\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 1 item\n\n test_tmpdir.py F [100%]\n\n ================================= FAILURES =================================\n _____________________________ test_create_file _____________________________\n\n tmpdir = local('PYTEST_TMPDIR/test_create_file0')\n\n def test_create_file(tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"hello.txt\")\n p.write(\"content\")\n assert p.read() == \"content\"\n assert len(tmpdir.listdir()) == 1\n > assert 0\n E assert 0\n\n test_tmpdir.py:7: AssertionError\n ========================= 1 failed in 0.12 seconds =========================\n\n.. _`tmpdir factory example`:\n\nThe 'tmpdir_factory' fixture\n----------------------------\n\n\n\nThe ``tmpdir_factory`` is a session-scoped fixture which can be used\nto create arbitrary temporary directories from any other fixture or test.\n\nFor example, suppose your test suite needs a large image on disk, which is\ngenerated procedurally. Instead of computing the same image for each test\nthat uses it into its own ``tmpdir``, you can generate it once per-session\nto save time:\n\n.. code-block:: python\n\n # contents of conftest.py\n import pytest\n\n\n @pytest.fixture(scope=\"session\")\n def image_file(tmpdir_factory):\n img = compute_expensive_image()\n fn = tmpdir_factory.mktemp(\"data\").join(\"img.png\")\n img.save(str(fn))\n return fn\n\n\n # contents of test_image.py\n def test_histogram(image_file):\n img = load_image(image_file)\n # compute and test histogram\n\nSee :ref:`tmpdir_factory API ` for details.\n\n\n.. _`base temporary directory`:\n\nThe default base temporary directory\n-----------------------------------------------\n\nTemporary directories are by default created as sub-directories of\nthe system temporary directory. The base name will be ``pytest-NUM`` where\n``NUM`` will be incremented with each test run. Moreover, entries older\nthan 3 temporary directories will be removed.\n\nYou can override the default temporary directory setting like this:\n\n.. code-block:: bash\n\n pytest --basetemp=mydir\n\nWhen distributing tests on the local machine, ``pytest`` takes care to\nconfigure a basetemp directory for the sub processes such that all temporary\ndata lands below a single per-test run basetemp directory.\n\n.. _`py.path.local`: https://py.readthedocs.io/en/latest/path.html\n"},{"id":3504,"name":"pythonpath.rst","nodeType":"TextFile","path":"doc/en","text":".. _pythonpath:\n\npytest import mechanisms and ``sys.path``/``PYTHONPATH``\n========================================================\n\nHere's a list of scenarios where pytest may need to change ``sys.path`` in order\nto import test modules or ``conftest.py`` files.\n\nTest modules / ``conftest.py`` files inside packages\n----------------------------------------------------\n\nConsider this file and directory layout::\n\n root/\n |- foo/\n |- __init__.py\n |- conftest.py\n |- bar/\n |- __init__.py\n |- tests/\n |- __init__.py\n |- test_foo.py\n\n\nWhen executing::\n\n pytest root/\n\n\n\npytest will find ``foo/bar/tests/test_foo.py`` and realize it is part of a package given that\nthere's an ``__init__.py`` file in the same folder. It will then search upwards until it can find the\nlast folder which still contains an ``__init__.py`` file in order to find the package *root* (in\nthis case ``foo/``). To load the module, it will insert ``root/`` to the front of\n``sys.path`` (if not there already) in order to load\n``test_foo.py`` as the *module* ``foo.bar.tests.test_foo``.\n\nThe same logic applies to the ``conftest.py`` file: it will be imported as ``foo.conftest`` module.\n\nPreserving the full package name is important when tests live in a package to avoid problems\nand allow test modules to have duplicated names. This is also discussed in details in\n:ref:`test discovery`.\n\nStandalone test modules / ``conftest.py`` files\n-----------------------------------------------\n\nConsider this file and directory layout::\n\n root/\n |- foo/\n |- conftest.py\n |- bar/\n |- tests/\n |- test_foo.py\n\n\nWhen executing::\n\n pytest root/\n\npytest will find ``foo/bar/tests/test_foo.py`` and realize it is NOT part of a package given that\nthere's no ``__init__.py`` file in the same folder. It will then add ``root/foo/bar/tests`` to\n``sys.path`` in order to import ``test_foo.py`` as the *module* ``test_foo``. The same is done\nwith the ``conftest.py`` file by adding ``root/foo`` to ``sys.path`` to import it as ``conftest``.\n\nFor this reason this layout cannot have test modules with the same name, as they all will be\nimported in the global import namespace.\n\nThis is also discussed in details in :ref:`test discovery`.\n\nInvoking ``pytest`` versus ``python -m pytest``\n-----------------------------------------------\n\nRunning pytest with ``python -m pytest [...]`` instead of ``pytest [...]`` yields nearly\nequivalent behaviour, except that the former call will add the current directory to ``sys.path``.\nSee also :ref:`cmdline`.\n"},{"id":3505,"name":"mark.rst","nodeType":"TextFile","path":"doc/en","text":".. _mark:\n\nMarking test functions with attributes\n======================================\n\nBy using the ``pytest.mark`` helper you can easily set\nmetadata on your test functions. There are\nsome builtin markers, for example:\n\n* :ref:`skip ` - always skip a test function\n* :ref:`skipif ` - skip a test function if a certain condition is met\n* :ref:`xfail ` - produce an \"expected failure\" outcome if a certain\n condition is met\n* :ref:`parametrize ` to perform multiple calls\n to the same test function.\n\nIt's easy to create custom markers or to apply markers\nto whole test classes or modules. Those markers can be used by plugins, and also\nare commonly used to :ref:`select tests ` on the command-line with the ``-m`` option.\n\nSee :ref:`mark examples` for examples which also serve as documentation.\n\n.. note::\n\n Marks can only be applied to tests, having no effect on\n :ref:`fixtures `.\n\n\nRegistering marks\n-----------------\n\nYou can register custom marks in your ``pytest.ini`` file like this:\n\n.. code-block:: ini\n\n [pytest]\n markers =\n slow: marks tests as slow (deselect with '-m \"not slow\"')\n serial\n\nNote that everything after the ``:`` is an optional description.\n\nAlternatively, you can register new markers programatically in a\n:ref:`pytest_configure ` hook:\n\n.. code-block:: python\n\n def pytest_configure(config):\n config.addinivalue_line(\n \"markers\", \"env(name): mark test to run only on named environment\"\n )\n\n\nRegistered marks appear in pytest's help text and do not emit warnings (see the next section). It\nis recommended that third-party plugins always :ref:`register their markers `.\n\n.. _unknown-marks:\n\nRaising errors on unknown marks\n-------------------------------\n\nUnregistered marks applied with the ``@pytest.mark.name_of_the_mark`` decorator\nwill always emit a warning in order to avoid silently doing something\nsurprising due to mis-typed names. As described in the previous section, you can disable\nthe warning for custom marks by registering them in your ``pytest.ini`` file or\nusing a custom ``pytest_configure`` hook.\n\nWhen the ``--strict-markers`` command-line flag is passed, any unknown marks applied\nwith the ``@pytest.mark.name_of_the_mark`` decorator will trigger an error. You can\nenforce this validation in your project by adding ``--strict-markers`` to ``addopts``:\n\n.. code-block:: ini\n\n [pytest]\n addopts = --strict-markers\n markers =\n slow: marks tests as slow (deselect with '-m \"not slow\"')\n serial\n"},{"id":3506,"name":"logging.rst","nodeType":"TextFile","path":"doc/en","text":".. _logging:\n\nLogging\n-------\n\n\n\n\npytest captures log messages of level ``WARNING`` or above automatically and displays them in their own section\nfor each failed test in the same manner as captured stdout and stderr.\n\nRunning without options:\n\n.. code-block:: bash\n\n pytest\n\nShows failed tests like so:\n\n.. code-block:: pytest\n\n ----------------------- Captured stdlog call ----------------------\n test_reporting.py 26 WARNING text going to logger\n ----------------------- Captured stdout call ----------------------\n text going to stdout\n ----------------------- Captured stderr call ----------------------\n text going to stderr\n ==================== 2 failed in 0.02 seconds =====================\n\nBy default each captured log message shows the module, line number, log level\nand message.\n\nIf desired the log and date format can be specified to\nanything that the logging module supports by passing specific formatting options:\n\n.. code-block:: bash\n\n pytest --log-format=\"%(asctime)s %(levelname)s %(message)s\" \\\n --log-date-format=\"%Y-%m-%d %H:%M:%S\"\n\nShows failed tests like so:\n\n.. code-block:: pytest\n\n ----------------------- Captured stdlog call ----------------------\n 2010-04-10 14:48:44 WARNING text going to logger\n ----------------------- Captured stdout call ----------------------\n text going to stdout\n ----------------------- Captured stderr call ----------------------\n text going to stderr\n ==================== 2 failed in 0.02 seconds =====================\n\nThese options can also be customized through ``pytest.ini`` file:\n\n.. code-block:: ini\n\n [pytest]\n log_format = %(asctime)s %(levelname)s %(message)s\n log_date_format = %Y-%m-%d %H:%M:%S\n\nFurther it is possible to disable reporting of captured content (stdout,\nstderr and logs) on failed tests completely with:\n\n.. code-block:: bash\n\n pytest --show-capture=no\n\n\ncaplog fixture\n^^^^^^^^^^^^^^\n\nInside tests it is possible to change the log level for the captured log\nmessages. This is supported by the ``caplog`` fixture::\n\n def test_foo(caplog):\n caplog.set_level(logging.INFO)\n pass\n\nBy default the level is set on the root logger,\nhowever as a convenience it is also possible to set the log level of any\nlogger::\n\n def test_foo(caplog):\n caplog.set_level(logging.CRITICAL, logger='root.baz')\n pass\n\nThe log levels set are restored automatically at the end of the test.\n\nIt is also possible to use a context manager to temporarily change the log\nlevel inside a ``with`` block::\n\n def test_bar(caplog):\n with caplog.at_level(logging.INFO):\n pass\n\nAgain, by default the level of the root logger is affected but the level of any\nlogger can be changed instead with::\n\n def test_bar(caplog):\n with caplog.at_level(logging.CRITICAL, logger='root.baz'):\n pass\n\nLastly all the logs sent to the logger during the test run are made available on\nthe fixture in the form of both the ``logging.LogRecord`` instances and the final log text.\nThis is useful for when you want to assert on the contents of a message::\n\n def test_baz(caplog):\n func_under_test()\n for record in caplog.records:\n assert record.levelname != 'CRITICAL'\n assert 'wally' not in caplog.text\n\nFor all the available attributes of the log records see the\n``logging.LogRecord`` class.\n\nYou can also resort to ``record_tuples`` if all you want to do is to ensure,\nthat certain messages have been logged under a given logger name with a given\nseverity and message::\n\n def test_foo(caplog):\n logging.getLogger().info('boo %s', 'arg')\n\n assert caplog.record_tuples == [\n ('root', logging.INFO, 'boo arg'),\n ]\n\nYou can call ``caplog.clear()`` to reset the captured log records in a test::\n\n def test_something_with_clearing_records(caplog):\n some_method_that_creates_log_records()\n caplog.clear()\n your_test_method()\n assert ['Foo'] == [rec.message for rec in caplog.records]\n\n\nThe ``caplog.records`` attribute contains records from the current stage only, so\ninside the ``setup`` phase it contains only setup logs, same with the ``call`` and\n``teardown`` phases.\n\nTo access logs from other stages, use the ``caplog.get_records(when)`` method. As an example,\nif you want to make sure that tests which use a certain fixture never log any warnings, you can inspect\nthe records for the ``setup`` and ``call`` stages during teardown like so:\n\n.. code-block:: python\n\n @pytest.fixture\n def window(caplog):\n window = create_window()\n yield window\n for when in (\"setup\", \"call\"):\n messages = [\n x.message for x in caplog.get_records(when) if x.level == logging.WARNING\n ]\n if messages:\n pytest.fail(\n \"warning messages encountered during testing: {}\".format(messages)\n )\n\n\n\nThe full API is available at :class:`_pytest.logging.LogCaptureFixture`.\n\n\n.. _live_logs:\n\nLive Logs\n^^^^^^^^^\n\nBy setting the :confval:`log_cli` configuration option to ``true``, pytest will output\nlogging records as they are emitted directly into the console.\n\nYou can specify the logging level for which log records with equal or higher\nlevel are printed to the console by passing ``--log-cli-level``. This setting\naccepts the logging level names as seen in python's documentation or an integer\nas the logging level num.\n\nAdditionally, you can also specify ``--log-cli-format`` and\n``--log-cli-date-format`` which mirror and default to ``--log-format`` and\n``--log-date-format`` if not provided, but are applied only to the console\nlogging handler.\n\nAll of the CLI log options can also be set in the configuration INI file. The\noption names are:\n\n* ``log_cli_level``\n* ``log_cli_format``\n* ``log_cli_date_format``\n\nIf you need to record the whole test suite logging calls to a file, you can pass\n``--log-file=/path/to/log/file``. This log file is opened in write mode which\nmeans that it will be overwritten at each run tests session.\n\nYou can also specify the logging level for the log file by passing\n``--log-file-level``. This setting accepts the logging level names as seen in\npython's documentation(ie, uppercased level names) or an integer as the logging\nlevel num.\n\nAdditionally, you can also specify ``--log-file-format`` and\n``--log-file-date-format`` which are equal to ``--log-format`` and\n``--log-date-format`` but are applied to the log file logging handler.\n\nAll of the log file options can also be set in the configuration INI file. The\noption names are:\n\n* ``log_file``\n* ``log_file_level``\n* ``log_file_format``\n* ``log_file_date_format``\n\nYou can call ``set_log_path()`` to customize the log_file path dynamically. This functionality\nis considered **experimental**.\n\n.. _log_release_notes:\n\nRelease notes\n^^^^^^^^^^^^^\n\nThis feature was introduced as a drop-in replacement for the `pytest-catchlog\n`_ plugin and they conflict\nwith each other. The backward compatibility API with ``pytest-capturelog``\nhas been dropped when this feature was introduced, so if for that reason you\nstill need ``pytest-catchlog`` you can disable the internal feature by\nadding to your ``pytest.ini``:\n\n.. code-block:: ini\n\n [pytest]\n addopts=-p no:logging\n\n\n.. _log_changes_3_4:\n\nIncompatible changes in pytest 3.4\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nThis feature was introduced in ``3.3`` and some **incompatible changes** have been\nmade in ``3.4`` after community feedback:\n\n* Log levels are no longer changed unless explicitly requested by the :confval:`log_level` configuration\n or ``--log-level`` command-line options. This allows users to configure logger objects themselves.\n* :ref:`Live Logs ` is now disabled by default and can be enabled setting the\n :confval:`log_cli` configuration option to ``true``. When enabled, the verbosity is increased so logging for each\n test is visible.\n* :ref:`Live Logs ` are now sent to ``sys.stdout`` and no longer require the ``-s`` command-line option\n to work.\n\nIf you want to partially restore the logging behavior of version ``3.3``, you can add this options to your ``ini``\nfile:\n\n.. code-block:: ini\n\n [pytest]\n log_cli=true\n log_level=NOTSET\n\nMore details about the discussion that lead to this changes can be read in\nissue `#3013 `_.\n"},{"id":3507,"name":".coveragerc","nodeType":"TextFile","path":"","text":"[run]\ninclude =\n src/*\n testing/*\n */lib/python*/site-packages/_pytest/*\n */lib/python*/site-packages/pytest.py\n */pypy*/site-packages/_pytest/*\n */pypy*/site-packages/pytest.py\n *\\Lib\\site-packages\\_pytest\\*\n *\\Lib\\site-packages\\pytest.py\nparallel = 1\nbranch = 1\n\n[paths]\nsource = src/\n */lib/python*/site-packages/\n */pypy*/site-packages/\n *\\Lib\\site-packages\\\n"},{"id":3508,"name":"testing/example_scripts/perf_examples/collect_stats","nodeType":"Package"},{"fileName":"generate_folders.py","filePath":"testing/example_scripts/perf_examples/collect_stats","id":3509,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport argparse\nimport pathlib\n\nHERE = pathlib.Path(__file__).parent\nTEST_CONTENT = (HERE / \"template_test.py\").read_bytes()\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"numbers\", nargs=\"*\", type=int)\n\n\ndef generate_folders(root, elements, *more_numbers):\n fill_len = len(str(elements))\n if more_numbers:\n for i in range(elements):\n new_folder = root.joinpath(f\"foo_{i:0>{fill_len}}\")\n new_folder.mkdir()\n new_folder.joinpath(\"__init__.py\").write_bytes(TEST_CONTENT)\n generate_folders(new_folder, *more_numbers)\n else:\n for i in range(elements):\n new_test = root.joinpath(f\"test_{i:0<{fill_len}}.py\")\n new_test.write_bytes(TEST_CONTENT)\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n generate_folders(HERE, *(args.numbers or (10, 100)))\n"},{"col":4,"comment":"null","endLoc":60,"header":"def _callhelper(self, call, x, *args)","id":3510,"name":"_callhelper","nodeType":"Function","startLoc":54,"text":"def _callhelper(self, call, x, *args):\n s = _call_and_format_exception(call, x, *args)\n if len(s) > self.maxsize:\n i = max(0, (self.maxsize - 3) // 2)\n j = max(0, self.maxsize - 3 - i)\n s = s[:i] + \"...\" + s[len(s) - j :]\n return s"},{"col":4,"comment":"null","endLoc":443,"header":"def test_txtfile_with_usefixtures_in_ini(self, testdir)","id":3511,"name":"test_txtfile_with_usefixtures_in_ini","nodeType":"Function","startLoc":419,"text":"def test_txtfile_with_usefixtures_in_ini(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n usefixtures = myfixture\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture\n def myfixture(monkeypatch):\n monkeypatch.setenv(\"HELLO\", \"WORLD\")\n \"\"\"\n )\n\n p = testdir.maketxtfile(\n \"\"\"\n >>> import os\n >>> os.environ[\"HELLO\"]\n 'WORLD'\n \"\"\"\n )\n reprec = testdir.inline_run(p)\n reprec.assertoutcome(passed=1)"},{"col":0,"comment":"null","endLoc":23,"header":"def generate_folders(root, elements, *more_numbers)","id":3512,"name":"generate_folders","nodeType":"Function","startLoc":12,"text":"def generate_folders(root, elements, *more_numbers):\n fill_len = len(str(elements))\n if more_numbers:\n for i in range(elements):\n new_folder = root.joinpath(f\"foo_{i:0>{fill_len}}\")\n new_folder.mkdir()\n new_folder.joinpath(\"__init__.py\").write_bytes(TEST_CONTENT)\n generate_folders(new_folder, *more_numbers)\n else:\n for i in range(elements):\n new_test = root.joinpath(f\"test_{i:0<{fill_len}}.py\")\n new_test.write_bytes(TEST_CONTENT)"},{"col":4,"comment":"null","endLoc":49,"header":"def repr_unicode(self, x, level)","id":3513,"name":"repr_unicode","nodeType":"Function","startLoc":33,"text":"def repr_unicode(self, x, level):\n # Strictly speaking wrong on narrow builds\n def repr(u):\n if \"'\" not in u:\n return u\"'%s'\" % u\n elif '\"' not in u:\n return u'\"%s\"' % u\n else:\n return u\"'%s'\" % u.replace(\"'\", r\"\\'\")\n\n s = repr(x[: self.maxstring])\n if len(s) > self.maxstring:\n i = max(0, (self.maxstring - 3) // 2)\n j = max(0, self.maxstring - 3 - i)\n s = repr(x[:i] + x[len(x) - j :])\n s = s[:i] + \"...\" + s[len(s) - j :]\n return s"},{"col":4,"comment":"null","endLoc":456,"header":"def test_doctestmodule_with_fixtures(self, testdir)","id":3515,"name":"test_doctestmodule_with_fixtures","nodeType":"Function","startLoc":445,"text":"def test_doctestmodule_with_fixtures(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n '''\n >>> dir = getfixture('tmpdir')\n >>> type(dir).__name__\n 'LocalPath'\n '''\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":"null","endLoc":483,"header":"def test_doctestmodule_three_tests(self, testdir)","id":3516,"name":"test_doctestmodule_three_tests","nodeType":"Function","startLoc":458,"text":"def test_doctestmodule_three_tests(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n '''\n >>> dir = getfixture('tmpdir')\n >>> type(dir).__name__\n 'LocalPath'\n '''\n def my_func():\n '''\n >>> magic = 42\n >>> magic - 42\n 0\n '''\n def unuseful():\n pass\n def another():\n '''\n >>> import os\n >>> os is os\n True\n '''\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(passed=3)"},{"col":4,"comment":"null","endLoc":504,"header":"def test_doctestmodule_two_tests_one_fail(self, testdir)","id":3517,"name":"test_doctestmodule_two_tests_one_fail","nodeType":"Function","startLoc":485,"text":"def test_doctestmodule_two_tests_one_fail(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n class MyClass(object):\n def bad_meth(self):\n '''\n >>> magic = 42\n >>> magic\n 0\n '''\n def nice_meth(self):\n '''\n >>> magic = 42\n >>> magic - 42\n 0\n '''\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(failed=1, passed=1)"},{"col":0,"comment":"null","endLoc":193,"header":"@pytest.mark.parametrize(\"holder\", make_holder())\ndef test_hookrecorder_basic(holder)","id":3518,"name":"test_hookrecorder_basic","nodeType":"Function","startLoc":181,"text":"@pytest.mark.parametrize(\"holder\", make_holder())\ndef test_hookrecorder_basic(holder):\n pm = PytestPluginManager()\n pm.add_hookspecs(holder)\n rec = HookRecorder(pm)\n pm.hook.pytest_xyz(arg=123)\n call = rec.popcall(\"pytest_xyz\")\n assert call.arg == 123\n assert call._name == \"pytest_xyz\"\n pytest.raises(pytest.fail.Exception, rec.popcall, \"abc\")\n pm.hook.pytest_xyz_noarg()\n call = rec.popcall(\"pytest_xyz_noarg\")\n assert call._name == \"pytest_xyz_noarg\""},{"col":4,"comment":"null","endLoc":525,"header":"def test_ignored_whitespace(self, testdir)","id":3519,"name":"test_ignored_whitespace","nodeType":"Function","startLoc":506,"text":"def test_ignored_whitespace(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_optionflags = ELLIPSIS NORMALIZE_WHITESPACE\n \"\"\"\n )\n p = testdir.makepyfile(\n \"\"\"\n class MyClass(object):\n '''\n >>> a = \"foo \"\n >>> print(a)\n foo\n '''\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(passed=1)"},{"col":0,"comment":"Ignore any exception via isinstance on Python 3.","endLoc":357,"header":"def safe_isclass(obj)","id":3520,"name":"safe_isclass","nodeType":"Function","startLoc":352,"text":"def safe_isclass(obj):\n \"\"\"Ignore any exception via isinstance on Python 3.\"\"\"\n try:\n return isclass(obj)\n except Exception:\n return False"},{"col":4,"comment":"null","endLoc":546,"header":"def test_non_ignored_whitespace(self, testdir)","id":3521,"name":"test_non_ignored_whitespace","nodeType":"Function","startLoc":527,"text":"def test_non_ignored_whitespace(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_optionflags = ELLIPSIS\n \"\"\"\n )\n p = testdir.makepyfile(\n \"\"\"\n class MyClass(object):\n '''\n >>> a = \"foo \"\n >>> print(a)\n foo\n '''\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(failed=1, passed=0)"},{"col":0,"comment":"Return if the test suite should fail if an @expectedFailure unittest test PASSES.\n\n From https://docs.python.org/3/library/unittest.html?highlight=unittest#unittest.TestResult.wasSuccessful:\n Changed in version 3.4: Returns False if there were any\n unexpectedSuccesses from tests marked with the expectedFailure() decorator.\n ","endLoc":367,"header":"def _is_unittest_unexpected_success_a_failure()","id":3522,"name":"_is_unittest_unexpected_success_a_failure","nodeType":"Function","startLoc":360,"text":"def _is_unittest_unexpected_success_a_failure():\n \"\"\"Return if the test suite should fail if an @expectedFailure unittest test PASSES.\n\n From https://docs.python.org/3/library/unittest.html?highlight=unittest#unittest.TestResult.wasSuccessful:\n Changed in version 3.4: Returns False if there were any\n unexpectedSuccesses from tests marked with the expectedFailure() decorator.\n \"\"\"\n return sys.version_info >= (3, 4)"},{"attributeType":"bool","col":0,"comment":"null","endLoc":31,"id":3523,"name":"_PY3","nodeType":"Attribute","startLoc":31,"text":"_PY3"},{"col":4,"comment":"null","endLoc":563,"header":"def test_ignored_whitespace_glob(self, testdir)","id":3524,"name":"test_ignored_whitespace_glob","nodeType":"Function","startLoc":548,"text":"def test_ignored_whitespace_glob(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_optionflags = ELLIPSIS NORMALIZE_WHITESPACE\n \"\"\"\n )\n p = testdir.maketxtfile(\n xdoc=\"\"\"\n >>> a = \"foo \"\n >>> print(a)\n foo\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-glob=x*.txt\")\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":"null","endLoc":580,"header":"def test_non_ignored_whitespace_glob(self, testdir)","id":3525,"name":"test_non_ignored_whitespace_glob","nodeType":"Function","startLoc":565,"text":"def test_non_ignored_whitespace_glob(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_optionflags = ELLIPSIS\n \"\"\"\n )\n p = testdir.maketxtfile(\n xdoc=\"\"\"\n >>> a = \"foo \"\n >>> print(a)\n foo\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-glob=x*.txt\")\n reprec.assertoutcome(failed=1, passed=0)"},{"col":4,"comment":"Fix internal error with docstrings containing non-ascii characters.\n ","endLoc":596,"header":"def test_contains_unicode(self, testdir)","id":3526,"name":"test_contains_unicode","nodeType":"Function","startLoc":582,"text":"def test_contains_unicode(self, testdir):\n \"\"\"Fix internal error with docstrings containing non-ascii characters.\n \"\"\"\n testdir.makepyfile(\n u'''\n # -*- coding: utf-8 -*-\n def foo():\n \"\"\"\n >>> name = 'с' # not letter 'c' but instead Cyrillic 's'.\n 'anything'\n \"\"\"\n '''\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines([\"Got nothing\", \"* 1 failed in*\"])"},{"col":4,"comment":"null","endLoc":615,"header":"def test_ignore_import_errors_on_doctest(self, testdir)","id":3527,"name":"test_ignore_import_errors_on_doctest","nodeType":"Function","startLoc":598,"text":"def test_ignore_import_errors_on_doctest(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import asdf\n\n def add_one(x):\n '''\n >>> add_one(1)\n 2\n '''\n return x + 1\n \"\"\"\n )\n\n reprec = testdir.inline_run(\n p, \"--doctest-modules\", \"--doctest-ignore-import-errors\"\n )\n reprec.assertoutcome(skipped=1, failed=1, passed=0)"},{"col":4,"comment":"\n #713: Fix --junit-xml option when used with --doctest-modules.\n ","endLoc":632,"header":"def test_junit_report_for_doctest(self, testdir)","id":3528,"name":"test_junit_report_for_doctest","nodeType":"Function","startLoc":617,"text":"def test_junit_report_for_doctest(self, testdir):\n \"\"\"\n #713: Fix --junit-xml option when used with --doctest-modules.\n \"\"\"\n p = testdir.makepyfile(\n \"\"\"\n def foo():\n '''\n >>> 1 + 1\n 3\n '''\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\", \"--junit-xml=junit.xml\")\n reprec.assertoutcome(failed=1)"},{"attributeType":"null","col":35,"comment":"null","endLoc":23,"id":3529,"name":"version","nodeType":"Attribute","startLoc":23,"text":"version"},{"col":4,"comment":"\n Test case for issue 2434: DecodeError on Python 2 when doctest contains non-ascii\n characters.\n ","endLoc":655,"header":"def test_unicode_doctest(self, testdir)","id":3530,"name":"test_unicode_doctest","nodeType":"Function","startLoc":634,"text":"def test_unicode_doctest(self, testdir):\n \"\"\"\n Test case for issue 2434: DecodeError on Python 2 when doctest contains non-ascii\n characters.\n \"\"\"\n p = testdir.maketxtfile(\n test_unicode_doctest=\"\"\"\n .. doctest::\n\n >>> print(\n ... \"Hi\\\\n\\\\nByé\")\n Hi\n ...\n Byé\n >>> 1/0 # Byé\n 1\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\"*UNEXPECTED EXCEPTION: ZeroDivisionError*\", \"*1 failed*\"]\n )"},{"attributeType":"LiteralString | str","col":0,"comment":"null","endLoc":25,"id":3531,"name":"release","nodeType":"Attribute","startLoc":25,"text":"release"},{"col":4,"comment":"\n Test case for issue 2434: DecodeError on Python 2 when doctest docstring\n contains non-ascii characters.\n ","endLoc":676,"header":"def test_unicode_doctest_module(self, testdir)","id":3532,"name":"test_unicode_doctest_module","nodeType":"Function","startLoc":657,"text":"def test_unicode_doctest_module(self, testdir):\n \"\"\"\n Test case for issue 2434: DecodeError on Python 2 when doctest docstring\n contains non-ascii characters.\n \"\"\"\n p = testdir.makepyfile(\n test_unicode_doctest_module=\"\"\"\n # -*- coding: utf-8 -*-\n from __future__ import unicode_literals\n\n def fix_bad_unicode(text):\n '''\n >>> print(fix_bad_unicode('único'))\n único\n '''\n return \"único\"\n \"\"\"\n )\n result = testdir.runpytest(p, \"--doctest-modules\")\n result.stdout.fnmatch_lines([\"* 1 passed *\"])"},{"col":4,"comment":"\n Test case for issue 3583: Printing Unicode in doctest under Python 2.7\n doesn't work\n ","endLoc":692,"header":"def test_print_unicode_value(self, testdir)","id":3533,"name":"test_print_unicode_value","nodeType":"Function","startLoc":678,"text":"def test_print_unicode_value(self, testdir):\n \"\"\"\n Test case for issue 3583: Printing Unicode in doctest under Python 2.7\n doesn't work\n \"\"\"\n p = testdir.maketxtfile(\n test_print_unicode_value=r\"\"\"\n Here is a doctest::\n\n >>> print(u'\\xE5\\xE9\\xEE\\xF8\\xFC')\n åéîøü\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"* 1 passed *\"])"},{"col":4,"comment":"null","endLoc":52,"header":"def repr_instance(self, x, level)","id":3534,"name":"repr_instance","nodeType":"Function","startLoc":51,"text":"def repr_instance(self, x, level):\n return self._callhelper(repr, x)"},{"col":0,"comment":"null","endLoc":202,"header":"def test_makepyfile_unicode(testdir)","id":3535,"name":"test_makepyfile_unicode","nodeType":"Function","startLoc":196,"text":"def test_makepyfile_unicode(testdir):\n global unichr\n try:\n unichr(65)\n except NameError:\n unichr = chr\n testdir.makepyfile(unichr(0xFFFD))"},{"col":4,"comment":"\n Test case to make sure that DoctestItem.reportinfo() returns lineno.\n ","endLoc":710,"header":"def test_reportinfo(self, testdir)","id":3536,"name":"test_reportinfo","nodeType":"Function","startLoc":694,"text":"def test_reportinfo(self, testdir):\n \"\"\"\n Test case to make sure that DoctestItem.reportinfo() returns lineno.\n \"\"\"\n p = testdir.makepyfile(\n test_reportinfo=\"\"\"\n def foo(x):\n '''\n >>> foo('a')\n 'b'\n '''\n return 'c'\n \"\"\"\n )\n items, reprec = testdir.inline_genitems(p, \"--doctest-modules\")\n reportinfo = items[0].reportinfo()\n assert reportinfo[1] == 1"},{"col":0,"comment":"Ensure makepyfile accepts utf-8 bytes as input (#2738)","endLoc":214,"header":"def test_makepyfile_utf8(testdir)","id":3537,"name":"test_makepyfile_utf8","nodeType":"Function","startLoc":205,"text":"def test_makepyfile_utf8(testdir):\n \"\"\"Ensure makepyfile accepts utf-8 bytes as input (#2738)\"\"\"\n utf8_contents = u\"\"\"\n def setup_function(function):\n mixed_encoding = u'São Paulo'\n \"\"\".encode(\n \"utf-8\"\n )\n p = testdir.makepyfile(utf8_contents)\n assert u\"mixed_encoding = u'São Paulo'\".encode(\"utf-8\") in p.read(\"rb\")"},{"col":4,"comment":"\n Test to make sure that pytest ignores valid setup.py files when ran\n with --doctest-modules\n ","endLoc":728,"header":"def test_valid_setup_py(self, testdir)","id":3538,"name":"test_valid_setup_py","nodeType":"Function","startLoc":712,"text":"def test_valid_setup_py(self, testdir):\n \"\"\"\n Test to make sure that pytest ignores valid setup.py files when ran\n with --doctest-modules\n \"\"\"\n p = testdir.makepyfile(\n setup=\"\"\"\n from setuptools import setup, find_packages\n setup(name='sample',\n version='0.0',\n description='description',\n packages=find_packages()\n )\n \"\"\"\n )\n result = testdir.runpytest(p, \"--doctest-modules\")\n result.stdout.fnmatch_lines([\"*collected 0 items*\"])"},{"col":4,"comment":"\n Test to make sure that pytest reads setup.py files that are not used\n for python packages when ran with --doctest-modules\n ","endLoc":742,"header":"def test_invalid_setup_py(self, testdir)","id":3539,"name":"test_invalid_setup_py","nodeType":"Function","startLoc":730,"text":"def test_invalid_setup_py(self, testdir):\n \"\"\"\n Test to make sure that pytest reads setup.py files that are not used\n for python packages when ran with --doctest-modules\n \"\"\"\n p = testdir.makepyfile(\n setup=\"\"\"\n def test_foo():\n return 'bar'\n \"\"\"\n )\n result = testdir.runpytest(p, \"--doctest-modules\")\n result.stdout.fnmatch_lines([\"*collected 1 item*\"])"},{"col":0,"comment":"null","endLoc":297,"header":"def test_assert_outcomes_after_pytest_error(testdir)","id":3540,"name":"test_assert_outcomes_after_pytest_error","nodeType":"Function","startLoc":292,"text":"def test_assert_outcomes_after_pytest_error(testdir):\n testdir.makepyfile(\"def test_foo(): assert True\")\n\n result = testdir.runpytest(\"--unexpected-argument\")\n with pytest.raises(ValueError, match=\"Pytest terminal report not found\"):\n result.assert_outcomes(passed=0)"},{"col":4,"comment":"null","endLoc":283,"header":"def _warn_already_imported(self, name)","id":3541,"name":"_warn_already_imported","nodeType":"Function","startLoc":273,"text":"def _warn_already_imported(self, name):\n from _pytest.warning_types import PytestAssertRewriteWarning\n from _pytest.warnings import _issue_warning_captured\n\n _issue_warning_captured(\n PytestAssertRewriteWarning(\n \"Module already imported so cannot be rewritten: %s\" % name\n ),\n self.config.hook,\n stacklevel=5,\n )"},{"col":0,"comment":"null","endLoc":308,"header":"def test_cwd_snapshot(tmpdir)","id":3542,"name":"test_cwd_snapshot","nodeType":"Function","startLoc":300,"text":"def test_cwd_snapshot(tmpdir):\n foo = tmpdir.ensure(\"foo\", dir=1)\n bar = tmpdir.ensure(\"bar\", dir=1)\n foo.chdir()\n snapshot = CwdSnapshot()\n bar.chdir()\n assert py.path.local() == bar\n snapshot.restore()\n assert py.path.local() == foo"},{"className":"TestLiterals","col":0,"comment":"null","endLoc":852,"id":3543,"nodeType":"Class","startLoc":745,"text":"class TestLiterals(object):\n @pytest.mark.parametrize(\"config_mode\", [\"ini\", \"comment\"])\n def test_allow_unicode(self, testdir, config_mode):\n \"\"\"Test that doctests which output unicode work in all python versions\n tested by pytest when the ALLOW_UNICODE option is used (either in\n the ini file or by an inline comment).\n \"\"\"\n if config_mode == \"ini\":\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_optionflags = ALLOW_UNICODE\n \"\"\"\n )\n comment = \"\"\n else:\n comment = \"#doctest: +ALLOW_UNICODE\"\n\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> b'12'.decode('ascii') {comment}\n '12'\n \"\"\".format(\n comment=comment\n )\n )\n testdir.makepyfile(\n foo=\"\"\"\n def foo():\n '''\n >>> b'12'.decode('ascii') {comment}\n '12'\n '''\n \"\"\".format(\n comment=comment\n )\n )\n reprec = testdir.inline_run(\"--doctest-modules\")\n reprec.assertoutcome(passed=2)\n\n @pytest.mark.parametrize(\"config_mode\", [\"ini\", \"comment\"])\n def test_allow_bytes(self, testdir, config_mode):\n \"\"\"Test that doctests which output bytes work in all python versions\n tested by pytest when the ALLOW_BYTES option is used (either in\n the ini file or by an inline comment)(#1287).\n \"\"\"\n if config_mode == \"ini\":\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_optionflags = ALLOW_BYTES\n \"\"\"\n )\n comment = \"\"\n else:\n comment = \"#doctest: +ALLOW_BYTES\"\n\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> b'foo' {comment}\n 'foo'\n \"\"\".format(\n comment=comment\n )\n )\n testdir.makepyfile(\n foo=\"\"\"\n def foo():\n '''\n >>> b'foo' {comment}\n 'foo'\n '''\n \"\"\".format(\n comment=comment\n )\n )\n reprec = testdir.inline_run(\"--doctest-modules\")\n reprec.assertoutcome(passed=2)\n\n def test_unicode_string(self, testdir):\n \"\"\"Test that doctests which output unicode fail in Python 2 when\n the ALLOW_UNICODE option is not used. The same test should pass\n in Python 3.\n \"\"\"\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> b'12'.decode('ascii')\n '12'\n \"\"\"\n )\n reprec = testdir.inline_run()\n passed = int(sys.version_info[0] >= 3)\n reprec.assertoutcome(passed=passed, failed=int(not passed))\n\n def test_bytes_literal(self, testdir):\n \"\"\"Test that doctests which output bytes fail in Python 3 when\n the ALLOW_BYTES option is not used. The same test should pass\n in Python 2 (#1287).\n \"\"\"\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> b'foo'\n 'foo'\n \"\"\"\n )\n reprec = testdir.inline_run()\n passed = int(sys.version_info[0] == 2)\n reprec.assertoutcome(passed=passed, failed=int(not passed))"},{"col":4,"comment":"Test that doctests which output unicode work in all python versions\n tested by pytest when the ALLOW_UNICODE option is used (either in\n the ini file or by an inline comment).\n ","endLoc":783,"header":"@pytest.mark.parametrize(\"config_mode\", [\"ini\", \"comment\"])\n def test_allow_unicode(self, testdir, config_mode)","id":3544,"name":"test_allow_unicode","nodeType":"Function","startLoc":746,"text":"@pytest.mark.parametrize(\"config_mode\", [\"ini\", \"comment\"])\n def test_allow_unicode(self, testdir, config_mode):\n \"\"\"Test that doctests which output unicode work in all python versions\n tested by pytest when the ALLOW_UNICODE option is used (either in\n the ini file or by an inline comment).\n \"\"\"\n if config_mode == \"ini\":\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_optionflags = ALLOW_UNICODE\n \"\"\"\n )\n comment = \"\"\n else:\n comment = \"#doctest: +ALLOW_UNICODE\"\n\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> b'12'.decode('ascii') {comment}\n '12'\n \"\"\".format(\n comment=comment\n )\n )\n testdir.makepyfile(\n foo=\"\"\"\n def foo():\n '''\n >>> b'12'.decode('ascii') {comment}\n '12'\n '''\n \"\"\".format(\n comment=comment\n )\n )\n reprec = testdir.inline_run(\"--doctest-modules\")\n reprec.assertoutcome(passed=2)"},{"col":0,"comment":"null","endLoc":421,"header":"def test_testdir_subprocess(testdir)","id":3545,"name":"test_testdir_subprocess","nodeType":"Function","startLoc":419,"text":"def test_testdir_subprocess(testdir):\n testfile = testdir.makepyfile(\"def test_one(): pass\")\n assert testdir.runpytest_subprocess(testfile).ret == 0"},{"col":4,"comment":"null","endLoc":63,"header":"def test_syntax_error_in_module(self, testdir)","id":3546,"name":"test_syntax_error_in_module","nodeType":"Function","startLoc":60,"text":"def test_syntax_error_in_module(self, testdir):\n modcol = testdir.getmodulecol(\"this is a syntax error\")\n pytest.raises(modcol.CollectError, modcol.collect)\n pytest.raises(modcol.CollectError, modcol.collect)"},{"col":0,"comment":"null","endLoc":426,"header":"def test_unicode_args(testdir)","id":3547,"name":"test_unicode_args","nodeType":"Function","startLoc":424,"text":"def test_unicode_args(testdir):\n result = testdir.runpytest(\"-k\", u\"💩\")\n assert result.ret == EXIT_NOTESTSCOLLECTED"},{"col":0,"comment":"null","endLoc":431,"header":"def test_testdir_run_no_timeout(testdir)","id":3548,"name":"test_testdir_run_no_timeout","nodeType":"Function","startLoc":429,"text":"def test_testdir_run_no_timeout(testdir):\n testfile = testdir.makepyfile(\"def test_no_timeout(): pass\")\n assert testdir.runpytest_subprocess(testfile).ret == EXIT_OK"},{"col":4,"comment":"null","endLoc":67,"header":"def test_module_considers_pluginmanager_at_import(self, testdir)","id":3549,"name":"test_module_considers_pluginmanager_at_import","nodeType":"Function","startLoc":65,"text":"def test_module_considers_pluginmanager_at_import(self, testdir):\n modcol = testdir.getmodulecol(\"pytest_plugins='xasdlkj',\")\n pytest.raises(ImportError, lambda: modcol.obj)"},{"col":0,"comment":"null","endLoc":445,"header":"def test_testdir_run_with_timeout(testdir)","id":3550,"name":"test_testdir_run_with_timeout","nodeType":"Function","startLoc":434,"text":"def test_testdir_run_with_timeout(testdir):\n testfile = testdir.makepyfile(\"def test_no_timeout(): pass\")\n\n timeout = 120\n\n start = time.time()\n result = testdir.runpytest_subprocess(testfile, timeout=timeout)\n end = time.time()\n duration = end - start\n\n assert result.ret == EXIT_OK\n assert duration < timeout"},{"col":35,"endLoc":67,"id":3551,"nodeType":"Lambda","startLoc":67,"text":"lambda: modcol.obj"},{"col":4,"comment":"null","endLoc":78,"header":"def test_invalid_test_module_name(self, testdir)","id":3552,"name":"test_invalid_test_module_name","nodeType":"Function","startLoc":69,"text":"def test_invalid_test_module_name(self, testdir):\n a = testdir.mkdir(\"a\")\n a.ensure(\"test_one.part1.py\")\n result = testdir.runpytest(\"-rw\")\n result.stdout.fnmatch_lines(\n [\n \"ImportError while importing test module*test_one.part1*\",\n \"Hint: make sure your test modules/packages have valid Python names.\",\n ]\n )"},{"col":0,"comment":"null","endLoc":457,"header":"def test_testdir_run_timeout_expires(testdir)","id":3553,"name":"test_testdir_run_timeout_expires","nodeType":"Function","startLoc":448,"text":"def test_testdir_run_timeout_expires(testdir):\n testfile = testdir.makepyfile(\n \"\"\"\n import time\n\n def test_timeout():\n time.sleep(10)\"\"\"\n )\n with pytest.raises(testdir.TimeoutExpired):\n testdir.runpytest_subprocess(testfile, timeout=1)"},{"col":4,"comment":"Import errors when collecting modules should display the traceback (#1976).\n\n With low verbosity we omit pytest and internal modules, otherwise show all traceback entries.\n ","endLoc":114,"header":"@pytest.mark.parametrize(\"verbose\", [0, 1, 2])\n def test_show_traceback_import_error(self, testdir, verbose)","id":3554,"name":"test_show_traceback_import_error","nodeType":"Function","startLoc":80,"text":"@pytest.mark.parametrize(\"verbose\", [0, 1, 2])\n def test_show_traceback_import_error(self, testdir, verbose):\n \"\"\"Import errors when collecting modules should display the traceback (#1976).\n\n With low verbosity we omit pytest and internal modules, otherwise show all traceback entries.\n \"\"\"\n testdir.makepyfile(\n foo_traceback_import_error=\"\"\"\n from bar_traceback_import_error import NOT_AVAILABLE\n \"\"\",\n bar_traceback_import_error=\"\",\n )\n testdir.makepyfile(\n \"\"\"\n import foo_traceback_import_error\n \"\"\"\n )\n args = (\"-v\",) * verbose\n result = testdir.runpytest(*args)\n result.stdout.fnmatch_lines(\n [\n \"ImportError while importing test module*\",\n \"Traceback:\",\n \"*from bar_traceback_import_error import NOT_AVAILABLE\",\n \"*cannot import name *NOT_AVAILABLE*\",\n ]\n )\n assert result.ret == 2\n\n stdout = result.stdout.str()\n for name in (\"_pytest\", os.path.join(\"py\", \"_path\")):\n if verbose == 2:\n assert name in stdout\n else:\n assert name not in stdout"},{"attributeType":"bool","col":0,"comment":"null","endLoc":32,"id":3555,"name":"_PY2","nodeType":"Attribute","startLoc":32,"text":"_PY2"},{"attributeType":"bool","col":0,"comment":"null","endLoc":42,"id":3556,"name":"PY35","nodeType":"Attribute","startLoc":42,"text":"PY35"},{"id":3557,"name":"testing/example_scripts/fixtures/fill_fixtures/test_extend_fixture_conftest_conftest","nodeType":"Package"},{"fileName":"conftest.py","filePath":"testing/example_scripts/fixtures/fill_fixtures/test_extend_fixture_conftest_conftest","id":3558,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\n@pytest.fixture\ndef spam():\n return \"spam\"\n"},{"col":0,"comment":"null","endLoc":7,"header":"@pytest.fixture\ndef spam()","id":3559,"name":"spam","nodeType":"Function","startLoc":5,"text":"@pytest.fixture\ndef spam():\n return \"spam\""},{"col":0,"comment":"Test LineMatcher with regard to passing in a set (accidentally).","endLoc":472,"header":"def test_linematcher_with_nonlist()","id":3560,"name":"test_linematcher_with_nonlist","nodeType":"Function","startLoc":460,"text":"def test_linematcher_with_nonlist():\n \"\"\"Test LineMatcher with regard to passing in a set (accidentally).\"\"\"\n lm = LineMatcher([])\n\n with pytest.raises(AssertionError):\n lm.fnmatch_lines(set())\n with pytest.raises(AssertionError):\n lm.fnmatch_lines({})\n lm.fnmatch_lines([])\n lm.fnmatch_lines(())\n\n assert lm._getlines({}) == {}\n assert lm._getlines(set()) == set()"},{"id":3561,"name":"testing/example_scripts/fixtures/custom_item","nodeType":"Package"},{"fileName":"conftest.py","filePath":"testing/example_scripts/fixtures/custom_item","id":3562,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\nclass CustomItem(pytest.Item, pytest.File):\n def runtest(self):\n pass\n\n\ndef pytest_collect_file(path, parent):\n return CustomItem(path, parent)\n"},{"className":"CustomItem","col":0,"comment":"null","endLoc":7,"id":3563,"nodeType":"Class","startLoc":5,"text":"class CustomItem(pytest.Item, pytest.File):\n def runtest(self):\n pass"},{"col":4,"comment":"null","endLoc":7,"header":"def runtest(self)","id":3564,"name":"runtest","nodeType":"Function","startLoc":6,"text":"def runtest(self):\n pass"},{"col":0,"comment":"null","endLoc":11,"header":"def pytest_collect_file(path, parent)","id":3565,"name":"pytest_collect_file","nodeType":"Function","startLoc":10,"text":"def pytest_collect_file(path, parent):\n return CustomItem(path, parent)"},{"col":4,"comment":"null","endLoc":309,"header":"def load_module(self, name)","id":3566,"name":"load_module","nodeType":"Function","startLoc":285,"text":"def load_module(self, name):\n co, pyc = self.modules.pop(name)\n if name in sys.modules:\n # If there is an existing module object named 'fullname' in\n # sys.modules, the loader must use that existing module. (Otherwise,\n # the reload() builtin will not work correctly.)\n mod = sys.modules[name]\n else:\n # I wish I could just call imp.load_compiled here, but __file__ has to\n # be set properly. In Python 3.2+, this all would be handled correctly\n # by load_compiled.\n mod = sys.modules[name] = imp.new_module(name)\n try:\n mod.__file__ = co.co_filename\n # Normally, this attribute is 3.2+.\n mod.__cached__ = pyc\n mod.__loader__ = self\n # Normally, this attribute is 3.4+\n mod.__spec__ = spec_from_file_location(name, co.co_filename, loader=self)\n exec(co, mod.__dict__)\n except: # noqa\n if name in sys.modules:\n del sys.modules[name]\n raise\n return sys.modules[name]"},{"col":4,"comment":"Test that doctests which output bytes work in all python versions\n tested by pytest when the ALLOW_BYTES option is used (either in\n the ini file or by an inline comment)(#1287).\n ","endLoc":822,"header":"@pytest.mark.parametrize(\"config_mode\", [\"ini\", \"comment\"])\n def test_allow_bytes(self, testdir, config_mode)","id":3567,"name":"test_allow_bytes","nodeType":"Function","startLoc":785,"text":"@pytest.mark.parametrize(\"config_mode\", [\"ini\", \"comment\"])\n def test_allow_bytes(self, testdir, config_mode):\n \"\"\"Test that doctests which output bytes work in all python versions\n tested by pytest when the ALLOW_BYTES option is used (either in\n the ini file or by an inline comment)(#1287).\n \"\"\"\n if config_mode == \"ini\":\n testdir.makeini(\n \"\"\"\n [pytest]\n doctest_optionflags = ALLOW_BYTES\n \"\"\"\n )\n comment = \"\"\n else:\n comment = \"#doctest: +ALLOW_BYTES\"\n\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> b'foo' {comment}\n 'foo'\n \"\"\".format(\n comment=comment\n )\n )\n testdir.makepyfile(\n foo=\"\"\"\n def foo():\n '''\n >>> b'foo' {comment}\n 'foo'\n '''\n \"\"\".format(\n comment=comment\n )\n )\n reprec = testdir.inline_run(\"--doctest-modules\")\n reprec.assertoutcome(passed=2)"},{"attributeType":"str","col":0,"comment":"null","endLoc":32,"id":3568,"name":"autodoc_member_order","nodeType":"Attribute","startLoc":32,"text":"autodoc_member_order"},{"attributeType":"int","col":0,"comment":"null","endLoc":33,"id":3569,"name":"todo_include_todos","nodeType":"Attribute","startLoc":33,"text":"todo_include_todos"},{"attributeType":"list","col":0,"comment":"null","endLoc":42,"id":3570,"name":"extensions","nodeType":"Attribute","startLoc":42,"text":"extensions"},{"attributeType":"list","col":0,"comment":"null","endLoc":54,"id":3571,"name":"templates_path","nodeType":"Attribute","startLoc":54,"text":"templates_path"},{"attributeType":"str","col":0,"comment":"null","endLoc":57,"id":3572,"name":"source_suffix","nodeType":"Attribute","startLoc":57,"text":"source_suffix"},{"col":4,"comment":"null","endLoc":319,"header":"def is_package(self, name)","id":3573,"name":"is_package","nodeType":"Function","startLoc":311,"text":"def is_package(self, name):\n try:\n fd, fn, desc = self._imp_find_module(name)\n except ImportError:\n return False\n if fd is not None:\n fd.close()\n tp = desc[2]\n return tp == imp.PKG_DIRECTORY"},{"attributeType":"str","col":0,"comment":"null","endLoc":63,"id":3574,"name":"master_doc","nodeType":"Attribute","startLoc":63,"text":"master_doc"},{"attributeType":"str","col":0,"comment":"null","endLoc":66,"id":3575,"name":"project","nodeType":"Attribute","startLoc":66,"text":"project"},{"attributeType":"int","col":0,"comment":"null","endLoc":67,"id":3576,"name":"year","nodeType":"Attribute","startLoc":67,"text":"year"},{"col":4,"comment":"null","endLoc":746,"header":"def _processopt(self, opt)","id":3577,"name":"_processopt","nodeType":"Function","startLoc":740,"text":"def _processopt(self, opt):\n for name in opt._short_opts + opt._long_opts:\n self._opt2dest[name] = opt.dest\n\n if hasattr(opt, \"default\") and opt.dest:\n if not hasattr(self.option, opt.dest):\n setattr(self.option, opt.dest, opt.default)"},{"col":4,"comment":"Optional PEP302 get_data API.\n ","endLoc":325,"header":"def get_data(self, pathname)","id":3578,"name":"get_data","nodeType":"Function","startLoc":321,"text":"def get_data(self, pathname):\n \"\"\"Optional PEP302 get_data API.\n \"\"\"\n with open(pathname, \"rb\") as f:\n return f.read()"},{"col":4,"comment":"null","endLoc":750,"header":"@hookimpl(trylast=True)\n def pytest_load_initial_conftests(self, early_config)","id":3580,"name":"pytest_load_initial_conftests","nodeType":"Function","startLoc":748,"text":"@hookimpl(trylast=True)\n def pytest_load_initial_conftests(self, early_config):\n self.pluginmanager._set_initial_conftests(early_config.known_args_namespace)"},{"col":4,"comment":"Test that doctests which output unicode fail in Python 2 when\n the ALLOW_UNICODE option is not used. The same test should pass\n in Python 3.\n ","endLoc":837,"header":"def test_unicode_string(self, testdir)","id":3581,"name":"test_unicode_string","nodeType":"Function","startLoc":824,"text":"def test_unicode_string(self, testdir):\n \"\"\"Test that doctests which output unicode fail in Python 2 when\n the ALLOW_UNICODE option is not used. The same test should pass\n in Python 3.\n \"\"\"\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> b'12'.decode('ascii')\n '12'\n \"\"\"\n )\n reprec = testdir.inline_run()\n passed = int(sys.version_info[0] >= 3)\n reprec.assertoutcome(passed=passed, failed=int(not passed))"},{"attributeType":"null","col":8,"comment":"null","endLoc":70,"id":3582,"name":"_rewritten_names","nodeType":"Attribute","startLoc":70,"text":"self._rewritten_names"},{"attributeType":"null","col":8,"comment":"null","endLoc":76,"id":3583,"name":"_marked_for_rewrite_cache","nodeType":"Attribute","startLoc":76,"text":"self._marked_for_rewrite_cache"},{"attributeType":"null","col":8,"comment":"null","endLoc":68,"id":3584,"name":"session","nodeType":"Attribute","startLoc":68,"text":"self.session"},{"attributeType":"null","col":8,"comment":"null","endLoc":77,"id":3585,"name":"_session_paths_checked","nodeType":"Attribute","startLoc":77,"text":"self._session_paths_checked"},{"col":4,"comment":" add a line to an ini-file option. The option must have been\n declared but might not yet be set in which case the line becomes the\n the first line in its value. ","endLoc":918,"header":"def addinivalue_line(self, name, line)","id":3586,"name":"addinivalue_line","nodeType":"Function","startLoc":912,"text":"def addinivalue_line(self, name, line):\n \"\"\" add a line to an ini-file option. The option must have been\n declared but might not yet be set in which case the line becomes the\n the first line in its value. \"\"\"\n x = self.getini(name)\n assert isinstance(x, list)\n x.append(line) # modifies the cached list inline"},{"attributeType":"null","col":12,"comment":"null","endLoc":67,"id":3587,"name":"fnpats","nodeType":"Attribute","startLoc":67,"text":"self.fnpats"},{"col":4,"comment":"Check test modules collected which raise ImportError with unicode messages\n are handled properly (#2336).\n ","endLoc":134,"header":"def test_show_traceback_import_error_unicode(self, testdir)","id":3588,"name":"test_show_traceback_import_error_unicode","nodeType":"Function","startLoc":116,"text":"def test_show_traceback_import_error_unicode(self, testdir):\n \"\"\"Check test modules collected which raise ImportError with unicode messages\n are handled properly (#2336).\n \"\"\"\n testdir.makepyfile(\n u\"\"\"\n # -*- coding: utf-8 -*-\n raise ImportError(u'Something bad happened ☺')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"ImportError while importing test module*\",\n \"Traceback:\",\n \"*raise ImportError*Something bad happened*\",\n ]\n )\n assert result.ret == 2"},{"attributeType":"null","col":8,"comment":"null","endLoc":75,"id":3589,"name":"_basenames_to_check_rewrite","nodeType":"Attribute","startLoc":75,"text":"self._basenames_to_check_rewrite"},{"attributeType":"null","col":8,"comment":"null","endLoc":63,"id":3590,"name":"config","nodeType":"Attribute","startLoc":63,"text":"self.config"},{"attributeType":"null","col":8,"comment":"null","endLoc":74,"id":3591,"name":"_writing_pyc","nodeType":"Attribute","startLoc":74,"text":"self._writing_pyc"},{"attributeType":"null","col":8,"comment":"null","endLoc":69,"id":3592,"name":"modules","nodeType":"Attribute","startLoc":69,"text":"self.modules"},{"attributeType":"null","col":8,"comment":"null","endLoc":71,"id":3593,"name":"_must_rewrite","nodeType":"Attribute","startLoc":71,"text":"self._must_rewrite"},{"attributeType":"null","col":4,"comment":"null","endLoc":43,"id":3594,"name":"PYTEST_TAG","nodeType":"Attribute","startLoc":43,"text":"PYTEST_TAG"},{"attributeType":"null","col":4,"comment":"null","endLoc":34,"id":3595,"name":"PYTEST_TAG","nodeType":"Attribute","startLoc":34,"text":"PYTEST_TAG"},{"className":"TestClass","col":0,"comment":"null","endLoc":255,"id":3596,"nodeType":"Class","startLoc":137,"text":"class TestClass(object):\n def test_class_with_init_warning(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class TestClass1(object):\n def __init__(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rw\")\n result.stdout.fnmatch_lines(\n [\n \"*cannot collect test class 'TestClass1' because it has \"\n \"a __init__ constructor (from: test_class_with_init_warning.py)\"\n ]\n )\n\n def test_class_with_new_warning(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class TestClass1(object):\n def __new__(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rw\")\n result.stdout.fnmatch_lines(\n [\n \"*cannot collect test class 'TestClass1' because it has \"\n \"a __new__ constructor (from: test_class_with_new_warning.py)\"\n ]\n )\n\n def test_class_subclassobject(self, testdir):\n testdir.getmodulecol(\n \"\"\"\n class test(object):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*collected 0*\"])\n\n def test_static_method(self, testdir):\n \"\"\"Support for collecting staticmethod tests (#2528, #2699)\"\"\"\n testdir.getmodulecol(\n \"\"\"\n import pytest\n class Test(object):\n @staticmethod\n def test_something():\n pass\n\n @pytest.fixture\n def fix(self):\n return 1\n\n @staticmethod\n def test_fix(fix):\n assert fix == 1\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*collected 2 items*\", \"*2 passed in*\"])\n\n def test_setup_teardown_class_as_classmethod(self, testdir):\n testdir.makepyfile(\n test_mod1=\"\"\"\n class TestClassMethod(object):\n @classmethod\n def setup_class(cls):\n pass\n def test_1(self):\n pass\n @classmethod\n def teardown_class(cls):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_issue1035_obj_has_getattr(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n class Chameleon(object):\n def __getattr__(self, name):\n return True\n chameleon = Chameleon()\n \"\"\"\n )\n colitems = modcol.collect()\n assert len(colitems) == 0\n\n def test_issue1579_namedtuple(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import collections\n\n TestCase = collections.namedtuple('TestCase', ['a'])\n \"\"\"\n )\n result = testdir.runpytest(\"-rw\")\n result.stdout.fnmatch_lines(\n \"*cannot collect test class 'TestCase' \"\n \"because it has a __new__ constructor*\"\n )\n\n def test_issue2234_property(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class TestCase(object):\n @property\n def prop(self):\n raise NotImplementedError()\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED"},{"col":4,"comment":"null","endLoc":152,"header":"def test_class_with_init_warning(self, testdir)","id":3597,"name":"test_class_with_init_warning","nodeType":"Function","startLoc":138,"text":"def test_class_with_init_warning(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class TestClass1(object):\n def __init__(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rw\")\n result.stdout.fnmatch_lines(\n [\n \"*cannot collect test class 'TestClass1' because it has \"\n \"a __init__ constructor (from: test_class_with_init_warning.py)\"\n ]\n )"},{"fileName":"test_funcarg_lookupfails.py","filePath":"testing/example_scripts/fixtures/fill_fixtures","id":3598,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\n@pytest.fixture\ndef xyzsomething(request):\n return 42\n\n\ndef test_func(some):\n pass\n"},{"col":0,"comment":"null","endLoc":7,"header":"@pytest.fixture\ndef xyzsomething(request)","id":3599,"name":"xyzsomething","nodeType":"Function","startLoc":5,"text":"@pytest.fixture\ndef xyzsomething(request):\n return 42"},{"col":0,"comment":"null","endLoc":11,"header":"def test_func(some)","id":3600,"name":"test_func","nodeType":"Function","startLoc":10,"text":"def test_func(some):\n pass"},{"fileName":"multipython.py","filePath":"doc/en/example","id":3601,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"\nmodule containing a parametrized tests testing cross-python\nserialization via the pickle module.\n\"\"\"\nimport distutils.spawn\nimport subprocess\nimport textwrap\n\nimport pytest\n\npythonlist = [\"python2.7\", \"python3.4\", \"python3.5\"]\n\n\n@pytest.fixture(params=pythonlist)\ndef python1(request, tmpdir):\n picklefile = tmpdir.join(\"data.pickle\")\n return Python(request.param, picklefile)\n\n\n@pytest.fixture(params=pythonlist)\ndef python2(request, python1):\n return Python(request.param, python1.picklefile)\n\n\nclass Python(object):\n def __init__(self, version, picklefile):\n self.pythonpath = distutils.spawn.find_executable(version)\n if not self.pythonpath:\n pytest.skip(\"{!r} not found\".format(version))\n self.picklefile = picklefile\n\n def dumps(self, obj):\n dumpfile = self.picklefile.dirpath(\"dump.py\")\n dumpfile.write(\n textwrap.dedent(\n r\"\"\"\n import pickle\n f = open({!r}, 'wb')\n s = pickle.dump({!r}, f, protocol=2)\n f.close()\n \"\"\".format(\n str(self.picklefile), obj\n )\n )\n )\n subprocess.check_call((self.pythonpath, str(dumpfile)))\n\n def load_and_is_true(self, expression):\n loadfile = self.picklefile.dirpath(\"load.py\")\n loadfile.write(\n textwrap.dedent(\n r\"\"\"\n import pickle\n f = open({!r}, 'rb')\n obj = pickle.load(f)\n f.close()\n res = eval({!r})\n if not res:\n raise SystemExit(1)\n \"\"\".format(\n str(self.picklefile), expression\n )\n )\n )\n print(loadfile)\n subprocess.check_call((self.pythonpath, str(loadfile)))\n\n\n@pytest.mark.parametrize(\"obj\", [42, {}, {1: 3}])\ndef test_basic_objects(python1, python2, obj):\n python1.dumps(obj)\n python2.load_and_is_true(\"obj == %s\" % obj)\n"},{"attributeType":"str","col":0,"comment":"null","endLoc":68,"id":3602,"name":"copyright","nodeType":"Attribute","startLoc":68,"text":"copyright"},{"col":4,"comment":"null","endLoc":168,"header":"def test_class_with_new_warning(self, testdir)","id":3603,"name":"test_class_with_new_warning","nodeType":"Function","startLoc":154,"text":"def test_class_with_new_warning(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class TestClass1(object):\n def __new__(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rw\")\n result.stdout.fnmatch_lines(\n [\n \"*cannot collect test class 'TestClass1' because it has \"\n \"a __new__ constructor (from: test_class_with_new_warning.py)\"\n ]\n )"},{"attributeType":"list","col":0,"comment":"null","endLoc":83,"id":3604,"name":"exclude_patterns","nodeType":"Attribute","startLoc":83,"text":"exclude_patterns"},{"col":33,"endLoc":454,"id":3605,"nodeType":"Lambda","startLoc":454,"text":"lambda: dummy_context_manager()"},{"className":"Python","col":0,"comment":"null","endLoc":67,"id":3606,"nodeType":"Class","startLoc":26,"text":"class Python(object):\n def __init__(self, version, picklefile):\n self.pythonpath = distutils.spawn.find_executable(version)\n if not self.pythonpath:\n pytest.skip(\"{!r} not found\".format(version))\n self.picklefile = picklefile\n\n def dumps(self, obj):\n dumpfile = self.picklefile.dirpath(\"dump.py\")\n dumpfile.write(\n textwrap.dedent(\n r\"\"\"\n import pickle\n f = open({!r}, 'wb')\n s = pickle.dump({!r}, f, protocol=2)\n f.close()\n \"\"\".format(\n str(self.picklefile), obj\n )\n )\n )\n subprocess.check_call((self.pythonpath, str(dumpfile)))\n\n def load_and_is_true(self, expression):\n loadfile = self.picklefile.dirpath(\"load.py\")\n loadfile.write(\n textwrap.dedent(\n r\"\"\"\n import pickle\n f = open({!r}, 'rb')\n obj = pickle.load(f)\n f.close()\n res = eval({!r})\n if not res:\n raise SystemExit(1)\n \"\"\".format(\n str(self.picklefile), expression\n )\n )\n )\n print(loadfile)\n subprocess.check_call((self.pythonpath, str(loadfile)))"},{"col":4,"comment":"null","endLoc":974,"header":"def _getconftest_pathlist(self, name, path)","id":3607,"name":"_getconftest_pathlist","nodeType":"Function","startLoc":962,"text":"def _getconftest_pathlist(self, name, path):\n try:\n mod, relroots = self.pluginmanager._rget_with_confmod(name, path)\n except KeyError:\n return None\n modpath = py.path.local(mod.__file__).dirpath()\n values = []\n for relroot in relroots:\n if not isinstance(relroot, py.path.local):\n relroot = relroot.replace(\"/\", py.path.local.sep)\n relroot = modpath.join(relroot, abs=True)\n values.append(relroot)\n return values"},{"col":4,"comment":"null","endLoc":178,"header":"def test_class_subclassobject(self, testdir)","id":3608,"name":"test_class_subclassobject","nodeType":"Function","startLoc":170,"text":"def test_class_subclassobject(self, testdir):\n testdir.getmodulecol(\n \"\"\"\n class test(object):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*collected 0*\"])"},{"col":4,"comment":"null","endLoc":31,"header":"def __init__(self, version, picklefile)","id":3609,"name":"__init__","nodeType":"Function","startLoc":27,"text":"def __init__(self, version, picklefile):\n self.pythonpath = distutils.spawn.find_executable(version)\n if not self.pythonpath:\n pytest.skip(\"{!r} not found\".format(version))\n self.picklefile = picklefile"},{"attributeType":"bool","col":0,"comment":"null","endLoc":105,"id":3610,"name":"add_module_names","nodeType":"Attribute","startLoc":105,"text":"add_module_names"},{"attributeType":"str","col":0,"comment":"null","endLoc":112,"id":3611,"name":"pygments_style","nodeType":"Attribute","startLoc":112,"text":"pygments_style"},{"col":4,"comment":"Support for collecting staticmethod tests (#2528, #2699)","endLoc":200,"header":"def test_static_method(self, testdir)","id":3612,"name":"test_static_method","nodeType":"Function","startLoc":180,"text":"def test_static_method(self, testdir):\n \"\"\"Support for collecting staticmethod tests (#2528, #2699)\"\"\"\n testdir.getmodulecol(\n \"\"\"\n import pytest\n class Test(object):\n @staticmethod\n def test_something():\n pass\n\n @pytest.fixture\n def fix(self):\n return 1\n\n @staticmethod\n def test_fix(fix):\n assert fix == 1\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*collected 2 items*\", \"*2 passed in*\"])"},{"attributeType":"list","col":0,"comment":"null","endLoc":122,"id":3613,"name":"html_theme_path","nodeType":"Attribute","startLoc":122,"text":"html_theme_path"},{"attributeType":"str","col":0,"comment":"null","endLoc":126,"id":3614,"name":"html_theme","nodeType":"Attribute","startLoc":126,"text":"html_theme"},{"col":4,"comment":"Return True if log_cli should be considered enabled, either explicitly\n or because --log-cli-level was given in the command-line.\n ","endLoc":527,"header":"def _log_cli_enabled(self)","id":3615,"name":"_log_cli_enabled","nodeType":"Function","startLoc":521,"text":"def _log_cli_enabled(self):\n \"\"\"Return True if log_cli should be considered enabled, either explicitly\n or because --log-cli-level was given in the command-line.\n \"\"\"\n return self._config.getoption(\n \"--log-cli-level\"\n ) is not None or self._config.getini(\"log_cli\")"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":131,"id":3616,"name":"html_theme_options","nodeType":"Attribute","startLoc":131,"text":"html_theme_options"},{"col":4,"comment":"null","endLoc":217,"header":"def test_setup_teardown_class_as_classmethod(self, testdir)","id":3617,"name":"test_setup_teardown_class_as_classmethod","nodeType":"Function","startLoc":202,"text":"def test_setup_teardown_class_as_classmethod(self, testdir):\n testdir.makepyfile(\n test_mod1=\"\"\"\n class TestClassMethod(object):\n @classmethod\n def setup_class(cls):\n pass\n def test_1(self):\n pass\n @classmethod\n def teardown_class(cls):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":4,"comment":"null","endLoc":498,"header":"def _setup_cli_logging(self)","id":3618,"name":"_setup_cli_logging","nodeType":"Function","startLoc":478,"text":"def _setup_cli_logging(self):\n config = self._config\n terminal_reporter = config.pluginmanager.get_plugin(\"terminalreporter\")\n if terminal_reporter is None:\n # terminal reporter is disabled e.g. by pytest-xdist.\n return\n\n capture_manager = config.pluginmanager.get_plugin(\"capturemanager\")\n # if capturemanager plugin is disabled, live logging still works.\n log_cli_handler = _LiveLoggingStreamHandler(terminal_reporter, capture_manager)\n\n log_cli_formatter = self._create_formatter(\n get_option_ini(config, \"log_cli_format\", \"log_format\"),\n get_option_ini(config, \"log_cli_date_format\", \"log_date_format\"),\n )\n\n log_cli_level = get_actual_log_level(config, \"log_cli_level\", \"log_level\")\n self.log_cli_handler = log_cli_handler\n self.live_logs_context = lambda: catching_logs(\n log_cli_handler, formatter=log_cli_formatter, level=log_cli_level\n )"},{"col":4,"comment":"null","endLoc":229,"header":"def test_issue1035_obj_has_getattr(self, testdir)","id":3619,"name":"test_issue1035_obj_has_getattr","nodeType":"Function","startLoc":219,"text":"def test_issue1035_obj_has_getattr(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n class Chameleon(object):\n def __getattr__(self, name):\n return True\n chameleon = Chameleon()\n \"\"\"\n )\n colitems = modcol.collect()\n assert len(colitems) == 0"},{"attributeType":"str","col":0,"comment":"null","endLoc":138,"id":3620,"name":"html_title","nodeType":"Attribute","startLoc":138,"text":"html_title"},{"attributeType":"str","col":0,"comment":"null","endLoc":141,"id":3621,"name":"html_short_title","nodeType":"Attribute","startLoc":141,"text":"html_short_title"},{"col":4,"comment":"null","endLoc":243,"header":"def test_issue1579_namedtuple(self, testdir)","id":3622,"name":"test_issue1579_namedtuple","nodeType":"Function","startLoc":231,"text":"def test_issue1579_namedtuple(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import collections\n\n TestCase = collections.namedtuple('TestCase', ['a'])\n \"\"\"\n )\n result = testdir.runpytest(\"-rw\")\n result.stdout.fnmatch_lines(\n \"*cannot collect test class 'TestCase' \"\n \"because it has a __new__ constructor*\"\n )"},{"col":4,"comment":"null","endLoc":255,"header":"def test_issue2234_property(self, testdir)","id":3623,"name":"test_issue2234_property","nodeType":"Function","startLoc":245,"text":"def test_issue2234_property(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class TestCase(object):\n @property\n def prop(self):\n raise NotImplementedError()\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED"},{"className":"TestFunction","col":0,"comment":"null","endLoc":664,"id":3624,"nodeType":"Class","startLoc":258,"text":"class TestFunction(object):\n def test_getmodulecollector(self, testdir):\n item = testdir.getitem(\"def test_func(): pass\")\n modcol = item.getparent(pytest.Module)\n assert isinstance(modcol, pytest.Module)\n assert hasattr(modcol.obj, \"test_func\")\n\n @pytest.mark.filterwarnings(\"default\")\n def test_function_as_object_instance_ignored(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class A(object):\n def __call__(self, tmpdir):\n 0/0\n\n test_a = A()\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"collected 0 items\",\n \"*test_function_as_object_instance_ignored.py:2: \"\n \"*cannot collect 'test_a' because it is not a function.\",\n ]\n )\n\n @staticmethod\n def make_function(testdir, **kwargs):\n from _pytest.fixtures import FixtureManager\n\n config = testdir.parseconfigure()\n session = testdir.Session(config)\n session._fixturemanager = FixtureManager(session)\n\n return pytest.Function(config=config, parent=session, **kwargs)\n\n def test_function_equality(self, testdir, tmpdir):\n def func1():\n pass\n\n def func2():\n pass\n\n f1 = self.make_function(testdir, name=\"name\", args=(1,), callobj=func1)\n assert f1 == f1\n f2 = self.make_function(testdir, name=\"name\", callobj=func2)\n assert f1 != f2\n\n def test_repr_produces_actual_test_id(self, testdir):\n f = self.make_function(\n testdir, name=r\"test[\\xe5]\", callobj=self.test_repr_produces_actual_test_id\n )\n assert repr(f) == r\"\"\n\n def test_issue197_parametrize_emptyset(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('arg', [])\n def test_function(arg):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(skipped=1)\n\n def test_single_tuple_unwraps_values(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize(('arg',), [(1,)])\n def test_function(arg):\n assert arg == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_issue213_parametrize_value_no_equal(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n class A(object):\n def __eq__(self, other):\n raise ValueError(\"not possible\")\n @pytest.mark.parametrize('arg', [A()])\n def test_function(arg):\n assert arg.__class__.__name__ == \"A\"\n \"\"\"\n )\n reprec = testdir.inline_run(\"--fulltrace\")\n reprec.assertoutcome(passed=1)\n\n def test_parametrize_with_non_hashable_values(self, testdir):\n \"\"\"Test parametrization with non-hashable values.\"\"\"\n testdir.makepyfile(\n \"\"\"\n archival_mapping = {\n '1.0': {'tag': '1.0'},\n '1.2.2a1': {'tag': 'release-1.2.2a1'},\n }\n\n import pytest\n @pytest.mark.parametrize('key value'.split(),\n archival_mapping.items())\n def test_archival_to_version(key, value):\n assert key in archival_mapping\n assert value == archival_mapping[key]\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(passed=2)\n\n def test_parametrize_with_non_hashable_values_indirect(self, testdir):\n \"\"\"Test parametrization with non-hashable values with indirect parametrization.\"\"\"\n testdir.makepyfile(\n \"\"\"\n archival_mapping = {\n '1.0': {'tag': '1.0'},\n '1.2.2a1': {'tag': 'release-1.2.2a1'},\n }\n\n import pytest\n\n @pytest.fixture\n def key(request):\n return request.param\n\n @pytest.fixture\n def value(request):\n return request.param\n\n @pytest.mark.parametrize('key value'.split(),\n archival_mapping.items(), indirect=True)\n def test_archival_to_version(key, value):\n assert key in archival_mapping\n assert value == archival_mapping[key]\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(passed=2)\n\n def test_parametrize_overrides_fixture(self, testdir):\n \"\"\"Test parametrization when parameter overrides existing fixture with same name.\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def value():\n return 'value'\n\n @pytest.mark.parametrize('value',\n ['overridden'])\n def test_overridden_via_param(value):\n assert value == 'overridden'\n\n @pytest.mark.parametrize('somevalue', ['overridden'])\n def test_not_overridden(value, somevalue):\n assert value == 'value'\n assert somevalue == 'overridden'\n\n @pytest.mark.parametrize('other,value', [('foo', 'overridden')])\n def test_overridden_via_multiparam(other, value):\n assert other == 'foo'\n assert value == 'overridden'\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(passed=3)\n\n def test_parametrize_overrides_parametrized_fixture(self, testdir):\n \"\"\"Test parametrization when parameter overrides existing parametrized fixture with same name.\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[1, 2])\n def value(request):\n return request.param\n\n @pytest.mark.parametrize('value',\n ['overridden'])\n def test_overridden_via_param(value):\n assert value == 'overridden'\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(passed=1)\n\n def test_parametrize_overrides_indirect_dependency_fixture(self, testdir):\n \"\"\"Test parametrization when parameter overrides a fixture that a test indirectly depends on\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n fix3_instantiated = False\n\n @pytest.fixture\n def fix1(fix2):\n return fix2 + '1'\n\n @pytest.fixture\n def fix2(fix3):\n return fix3 + '2'\n\n @pytest.fixture\n def fix3():\n global fix3_instantiated\n fix3_instantiated = True\n return '3'\n\n @pytest.mark.parametrize('fix2', ['2'])\n def test_it(fix1):\n assert fix1 == '21'\n assert not fix3_instantiated\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(passed=1)\n\n def test_parametrize_with_mark(self, testdir):\n items = testdir.getitems(\n \"\"\"\n import pytest\n @pytest.mark.foo\n @pytest.mark.parametrize('arg', [\n 1,\n pytest.param(2, marks=[pytest.mark.baz, pytest.mark.bar])\n ])\n def test_function(arg):\n pass\n \"\"\"\n )\n keywords = [item.keywords for item in items]\n assert (\n \"foo\" in keywords[0]\n and \"bar\" not in keywords[0]\n and \"baz\" not in keywords[0]\n )\n assert \"foo\" in keywords[1] and \"bar\" in keywords[1] and \"baz\" in keywords[1]\n\n def test_function_equality_with_callspec(self, testdir, tmpdir):\n items = testdir.getitems(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('arg', [1,2])\n def test_function(arg):\n pass\n \"\"\"\n )\n assert items[0] != items[1]\n assert not (items[0] == items[1])\n\n def test_pyfunc_call(self, testdir):\n item = testdir.getitem(\"def test_func(): raise ValueError\")\n config = item.config\n\n class MyPlugin1(object):\n def pytest_pyfunc_call(self, pyfuncitem):\n raise ValueError\n\n class MyPlugin2(object):\n def pytest_pyfunc_call(self, pyfuncitem):\n return True\n\n config.pluginmanager.register(MyPlugin1())\n config.pluginmanager.register(MyPlugin2())\n config.hook.pytest_runtest_setup(item=item)\n config.hook.pytest_pyfunc_call(pyfuncitem=item)\n\n def test_multiple_parametrize(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('x', [0, 1])\n @pytest.mark.parametrize('y', [2, 3])\n def test1(x, y):\n pass\n \"\"\"\n )\n colitems = modcol.collect()\n assert colitems[0].name == \"test1[2-0]\"\n assert colitems[1].name == \"test1[2-1]\"\n assert colitems[2].name == \"test1[3-0]\"\n assert colitems[3].name == \"test1[3-1]\"\n\n def test_issue751_multiple_parametrize_with_ids(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('x', [0], ids=['c'])\n @pytest.mark.parametrize('y', [0, 1], ids=['a', 'b'])\n class Test(object):\n def test1(self, x, y):\n pass\n def test2(self, x, y):\n pass\n \"\"\"\n )\n colitems = modcol.collect()[0].collect()[0].collect()\n assert colitems[0].name == \"test1[a-c]\"\n assert colitems[1].name == \"test1[b-c]\"\n assert colitems[2].name == \"test2[a-c]\"\n assert colitems[3].name == \"test2[b-c]\"\n\n def test_parametrize_skipif(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n m = pytest.mark.skipif('True')\n\n @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])\n def test_skip_if(x):\n assert x < 2\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed, 1 skipped in *\"])\n\n def test_parametrize_skip(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n m = pytest.mark.skip('')\n\n @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])\n def test_skip(x):\n assert x < 2\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed, 1 skipped in *\"])\n\n def test_parametrize_skipif_no_skip(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n m = pytest.mark.skipif('False')\n\n @pytest.mark.parametrize('x', [0, 1, m(2)])\n def test_skipif_no_skip(x):\n assert x < 2\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 failed, 2 passed in *\"])\n\n def test_parametrize_xfail(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n m = pytest.mark.xfail('True')\n\n @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])\n def test_xfail(x):\n assert x < 2\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed, 1 xfailed in *\"])\n\n def test_parametrize_passed(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n m = pytest.mark.xfail('True')\n\n @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])\n def test_xfail(x):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed, 1 xpassed in *\"])\n\n def test_parametrize_xfail_passed(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n m = pytest.mark.xfail('False')\n\n @pytest.mark.parametrize('x', [0, 1, m(2)])\n def test_passed(x):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 3 passed in *\"])\n\n def test_function_original_name(self, testdir):\n items = testdir.getitems(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('arg', [1,2])\n def test_func(arg):\n pass\n \"\"\"\n )\n assert [x.originalname for x in items] == [\"test_func\", \"test_func\"]"},{"col":4,"comment":"null","endLoc":263,"header":"def test_getmodulecollector(self, testdir)","id":3625,"name":"test_getmodulecollector","nodeType":"Function","startLoc":259,"text":"def test_getmodulecollector(self, testdir):\n item = testdir.getitem(\"def test_func(): pass\")\n modcol = item.getparent(pytest.Module)\n assert isinstance(modcol, pytest.Module)\n assert hasattr(modcol.obj, \"test_func\")"},{"className":"TestAssertionRewrite","col":0,"comment":"null","endLoc":672,"id":3626,"nodeType":"Class","startLoc":71,"text":"class TestAssertionRewrite(object):\n def test_place_initial_imports(self):\n s = \"\"\"'Doc string'\\nother = stuff\"\"\"\n m = rewrite(s)\n assert isinstance(m.body[0], ast.Expr)\n for imp in m.body[1:3]:\n assert isinstance(imp, ast.Import)\n assert imp.lineno == 2\n assert imp.col_offset == 0\n assert isinstance(m.body[3], ast.Assign)\n s = \"\"\"from __future__ import division\\nother_stuff\"\"\"\n m = rewrite(s)\n assert isinstance(m.body[0], ast.ImportFrom)\n for imp in m.body[1:3]:\n assert isinstance(imp, ast.Import)\n assert imp.lineno == 2\n assert imp.col_offset == 0\n assert isinstance(m.body[3], ast.Expr)\n s = \"\"\"'doc string'\\nfrom __future__ import division\"\"\"\n m = rewrite(s)\n assert isinstance(m.body[0], ast.Expr)\n assert isinstance(m.body[1], ast.ImportFrom)\n for imp in m.body[2:4]:\n assert isinstance(imp, ast.Import)\n assert imp.lineno == 2\n assert imp.col_offset == 0\n s = \"\"\"'doc string'\\nfrom __future__ import division\\nother\"\"\"\n m = rewrite(s)\n assert isinstance(m.body[0], ast.Expr)\n assert isinstance(m.body[1], ast.ImportFrom)\n for imp in m.body[2:4]:\n assert isinstance(imp, ast.Import)\n assert imp.lineno == 3\n assert imp.col_offset == 0\n assert isinstance(m.body[4], ast.Expr)\n s = \"\"\"from . import relative\\nother_stuff\"\"\"\n m = rewrite(s)\n for imp in m.body[:2]:\n assert isinstance(imp, ast.Import)\n assert imp.lineno == 1\n assert imp.col_offset == 0\n assert isinstance(m.body[3], ast.Expr)\n\n def test_dont_rewrite(self):\n s = \"\"\"'PYTEST_DONT_REWRITE'\\nassert 14\"\"\"\n m = rewrite(s)\n assert len(m.body) == 2\n assert m.body[1].msg is None\n\n def test_dont_rewrite_plugin(self, testdir):\n contents = {\n \"conftest.py\": \"pytest_plugins = 'plugin'; import plugin\",\n \"plugin.py\": \"'PYTEST_DONT_REWRITE'\",\n \"test_foo.py\": \"def test_foo(): pass\",\n }\n testdir.makepyfile(**contents)\n result = testdir.runpytest_subprocess()\n assert \"warnings\" not in \"\".join(result.outlines)\n\n def test_name(self, request):\n def f():\n assert False\n\n assert getmsg(f) == \"assert False\"\n\n def f():\n f = False\n assert f\n\n assert getmsg(f) == \"assert False\"\n\n def f():\n assert a_global # noqa\n\n assert getmsg(f, {\"a_global\": False}) == \"assert False\"\n\n def f():\n assert sys == 42\n\n verbose = request.config.getoption(\"verbose\")\n msg = getmsg(f, {\"sys\": sys})\n if verbose > 0:\n assert msg == (\n \"assert == 42\\n\"\n \" -\\n\"\n \" +42\"\n )\n else:\n assert msg == \"assert sys == 42\"\n\n def f():\n assert cls == 42 # noqa: F821\n\n class X(object):\n pass\n\n msg = getmsg(f, {\"cls\": X}).splitlines()\n if verbose > 0:\n if six.PY2:\n assert msg == [\n \"assert == 42\",\n \" -\",\n \" +42\",\n ]\n else:\n assert msg == [\n \"assert .X'> == 42\",\n \" -.X'>\",\n \" +42\",\n ]\n else:\n assert msg == [\"assert cls == 42\"]\n\n def test_dont_rewrite_if_hasattr_fails(self, request):\n class Y(object):\n \"\"\" A class whos getattr fails, but not with `AttributeError` \"\"\"\n\n def __getattr__(self, attribute_name):\n raise KeyError()\n\n def __repr__(self):\n return \"Y\"\n\n def __init__(self):\n self.foo = 3\n\n def f():\n assert cls().foo == 2 # noqa\n\n # XXX: looks like the \"where\" should also be there in verbose mode?!\n message = getmsg(f, {\"cls\": Y}).splitlines()\n if request.config.getoption(\"verbose\") > 0:\n assert message == [\"assert 3 == 2\", \" -3\", \" +2\"]\n else:\n assert message == [\n \"assert 3 == 2\",\n \" + where 3 = Y.foo\",\n \" + where Y = cls()\",\n ]\n\n def test_assert_already_has_message(self):\n def f():\n assert False, \"something bad!\"\n\n assert getmsg(f) == \"AssertionError: something bad!\\nassert False\"\n\n def test_assertion_message(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert 1 == 2, \"The failure message\"\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\"*AssertionError*The failure message*\", \"*assert 1 == 2*\"]\n )\n\n def test_assertion_message_multiline(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert 1 == 2, \"A multiline\\\\nfailure message\"\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\"*AssertionError*A multiline*\", \"*failure message*\", \"*assert 1 == 2*\"]\n )\n\n def test_assertion_message_tuple(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert 1 == 2, (1, 2)\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\"*AssertionError*%s*\" % repr((1, 2)), \"*assert 1 == 2*\"]\n )\n\n def test_assertion_message_expr(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert 1 == 2, 1 + 2\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines([\"*AssertionError*3*\", \"*assert 1 == 2*\"])\n\n def test_assertion_message_escape(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert 1 == 2, 'To be escaped: %'\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\"*AssertionError: To be escaped: %\", \"*assert 1 == 2\"]\n )\n\n @pytest.mark.skipif(\n sys.version_info < (3,), reason=\"bytes is a string type in python 2\"\n )\n def test_assertion_messages_bytes(self, testdir):\n testdir.makepyfile(\"def test_bytes_assertion():\\n assert False, b'ohai!'\\n\")\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines([\"*AssertionError: b'ohai!'\", \"*assert False\"])\n\n def test_boolop(self):\n def f():\n f = g = False\n assert f and g\n\n assert getmsg(f) == \"assert (False)\"\n\n def f():\n f = True\n g = False\n assert f and g\n\n assert getmsg(f) == \"assert (True and False)\"\n\n def f():\n f = False\n g = True\n assert f and g\n\n assert getmsg(f) == \"assert (False)\"\n\n def f():\n f = g = False\n assert f or g\n\n assert getmsg(f) == \"assert (False or False)\"\n\n def f():\n f = g = False\n assert not f and not g\n\n getmsg(f, must_pass=True)\n\n def x():\n return False\n\n def f():\n assert x() and x()\n\n assert (\n getmsg(f, {\"x\": x})\n == \"\"\"assert (False)\n + where False = x()\"\"\"\n )\n\n def f():\n assert False or x()\n\n assert (\n getmsg(f, {\"x\": x})\n == \"\"\"assert (False or False)\n + where False = x()\"\"\"\n )\n\n def f():\n assert 1 in {} and 2 in {}\n\n assert getmsg(f) == \"assert (1 in {})\"\n\n def f():\n x = 1\n y = 2\n assert x in {1: None} and y in {}\n\n assert getmsg(f) == \"assert (1 in {1: None} and 2 in {})\"\n\n def f():\n f = True\n g = False\n assert f or g\n\n getmsg(f, must_pass=True)\n\n def f():\n f = g = h = lambda: True\n assert f() and g() and h()\n\n getmsg(f, must_pass=True)\n\n def test_short_circuit_evaluation(self):\n def f():\n assert True or explode # noqa\n\n getmsg(f, must_pass=True)\n\n def f():\n x = 1\n assert x == 1 or x == 2\n\n getmsg(f, must_pass=True)\n\n def test_unary_op(self):\n def f():\n x = True\n assert not x\n\n assert getmsg(f) == \"assert not True\"\n\n def f():\n x = 0\n assert ~x + 1\n\n assert getmsg(f) == \"assert (~0 + 1)\"\n\n def f():\n x = 3\n assert -x + x\n\n assert getmsg(f) == \"assert (-3 + 3)\"\n\n def f():\n x = 0\n assert +x + x\n\n assert getmsg(f) == \"assert (+0 + 0)\"\n\n def test_binary_op(self):\n def f():\n x = 1\n y = -1\n assert x + y\n\n assert getmsg(f) == \"assert (1 + -1)\"\n\n def f():\n assert not 5 % 4\n\n assert getmsg(f) == \"assert not (5 % 4)\"\n\n def test_boolop_percent(self):\n def f():\n assert 3 % 2 and False\n\n assert getmsg(f) == \"assert ((3 % 2) and False)\"\n\n def f():\n assert False or 4 % 2\n\n assert getmsg(f) == \"assert (False or (4 % 2))\"\n\n @pytest.mark.skipif(\"sys.version_info < (3,5)\")\n def test_at_operator_issue1290(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class Matrix(object):\n def __init__(self, num):\n self.num = num\n def __matmul__(self, other):\n return self.num * other.num\n\n def test_multmat_operator():\n assert Matrix(2) @ Matrix(3) == 6\"\"\"\n )\n testdir.runpytest().assert_outcomes(passed=1)\n\n @pytest.mark.skipif(\"sys.version_info < (3,5)\")\n def test_starred_with_side_effect(self, testdir):\n \"\"\"See #4412\"\"\"\n testdir.makepyfile(\n \"\"\"\\\n def test():\n f = lambda x: x\n x = iter([1, 2, 3])\n assert 2 * next(x) == f(*[next(x)])\n \"\"\"\n )\n testdir.runpytest().assert_outcomes(passed=1)\n\n def test_call(self):\n def g(a=42, *args, **kwargs):\n return False\n\n ns = {\"g\": g}\n\n def f():\n assert g()\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g()\"\"\"\n )\n\n def f():\n assert g(1)\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g(1)\"\"\"\n )\n\n def f():\n assert g(1, 2)\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g(1, 2)\"\"\"\n )\n\n def f():\n assert g(1, g=42)\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g(1, g=42)\"\"\"\n )\n\n def f():\n assert g(1, 3, g=23)\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g(1, 3, g=23)\"\"\"\n )\n\n def f():\n seq = [1, 2, 3]\n assert g(*seq)\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g(*[1, 2, 3])\"\"\"\n )\n\n def f():\n x = \"a\"\n assert g(**{x: 2})\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g(**{'a': 2})\"\"\"\n )\n\n def test_attribute(self):\n class X(object):\n g = 3\n\n ns = {\"x\": X}\n\n def f():\n assert not x.g # noqa\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert not 3\n + where 3 = x.g\"\"\"\n )\n\n def f():\n x.a = False # noqa\n assert x.a # noqa\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = x.a\"\"\"\n )\n\n def test_comparisons(self):\n def f():\n a, b = range(2)\n assert b < a\n\n assert getmsg(f) == \"\"\"assert 1 < 0\"\"\"\n\n def f():\n a, b, c = range(3)\n assert a > b > c\n\n assert getmsg(f) == \"\"\"assert 0 > 1\"\"\"\n\n def f():\n a, b, c = range(3)\n assert a < b > c\n\n assert getmsg(f) == \"\"\"assert 1 > 2\"\"\"\n\n def f():\n a, b, c = range(3)\n assert a < b <= c\n\n getmsg(f, must_pass=True)\n\n def f():\n a, b, c = range(3)\n assert a < b\n assert b < c\n\n getmsg(f, must_pass=True)\n\n def test_len(self, request):\n def f():\n values = list(range(10))\n assert len(values) == 11\n\n msg = getmsg(f)\n if request.config.getoption(\"verbose\") > 0:\n assert msg == \"assert 10 == 11\\n -10\\n +11\"\n else:\n assert msg == \"assert 10 == 11\\n + where 10 = len([0, 1, 2, 3, 4, 5, ...])\"\n\n def test_custom_reprcompare(self, monkeypatch):\n def my_reprcompare(op, left, right):\n return \"42\"\n\n monkeypatch.setattr(util, \"_reprcompare\", my_reprcompare)\n\n def f():\n assert 42 < 3\n\n assert getmsg(f) == \"assert 42\"\n\n def my_reprcompare(op, left, right):\n return \"{} {} {}\".format(left, op, right)\n\n monkeypatch.setattr(util, \"_reprcompare\", my_reprcompare)\n\n def f():\n assert 1 < 3 < 5 <= 4 < 7\n\n assert getmsg(f) == \"assert 5 <= 4\"\n\n def test_assert_raising_nonzero_in_comparison(self):\n def f():\n class A(object):\n def __nonzero__(self):\n raise ValueError(42)\n\n def __lt__(self, other):\n return A()\n\n def __repr__(self):\n return \"\"\n\n def myany(x):\n return False\n\n assert myany(A() < 0)\n\n assert \" < 0\" in getmsg(f)\n\n def test_formatchar(self):\n def f():\n assert \"%test\" == \"test\"\n\n assert getmsg(f).startswith(\"assert '%test' == 'test'\")\n\n def test_custom_repr(self, request):\n def f():\n class Foo(object):\n a = 1\n\n def __repr__(self):\n return \"\\n{ \\n~ \\n}\"\n\n f = Foo()\n assert 0 == f.a\n\n lines = util._format_lines([getmsg(f)])\n if request.config.getoption(\"verbose\") > 0:\n assert lines == [\"assert 0 == 1\\n -0\\n +1\"]\n else:\n assert lines == [\"assert 0 == 1\\n + where 1 = \\\\n{ \\\\n~ \\\\n}.a\"]\n\n def test_custom_repr_non_ascii(self):\n def f():\n class A(object):\n name = u\"ä\"\n\n def __repr__(self):\n return self.name.encode(\"UTF-8\") # only legal in python2\n\n a = A()\n assert not a.name\n\n msg = getmsg(f)\n assert \"UnicodeDecodeError\" not in msg\n assert \"UnicodeEncodeError\" not in msg"},{"col":4,"comment":"null","endLoc":283,"header":"@pytest.mark.filterwarnings(\"default\")\n def test_function_as_object_instance_ignored(self, testdir)","id":3627,"name":"test_function_as_object_instance_ignored","nodeType":"Function","startLoc":265,"text":"@pytest.mark.filterwarnings(\"default\")\n def test_function_as_object_instance_ignored(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class A(object):\n def __call__(self, tmpdir):\n 0/0\n\n test_a = A()\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"collected 0 items\",\n \"*test_function_as_object_instance_ignored.py:2: \"\n \"*cannot collect 'test_a' because it is not a function.\",\n ]\n )"},{"col":4,"comment":"null","endLoc":112,"header":"def test_place_initial_imports(self)","id":3628,"name":"test_place_initial_imports","nodeType":"Function","startLoc":72,"text":"def test_place_initial_imports(self):\n s = \"\"\"'Doc string'\\nother = stuff\"\"\"\n m = rewrite(s)\n assert isinstance(m.body[0], ast.Expr)\n for imp in m.body[1:3]:\n assert isinstance(imp, ast.Import)\n assert imp.lineno == 2\n assert imp.col_offset == 0\n assert isinstance(m.body[3], ast.Assign)\n s = \"\"\"from __future__ import division\\nother_stuff\"\"\"\n m = rewrite(s)\n assert isinstance(m.body[0], ast.ImportFrom)\n for imp in m.body[1:3]:\n assert isinstance(imp, ast.Import)\n assert imp.lineno == 2\n assert imp.col_offset == 0\n assert isinstance(m.body[3], ast.Expr)\n s = \"\"\"'doc string'\\nfrom __future__ import division\"\"\"\n m = rewrite(s)\n assert isinstance(m.body[0], ast.Expr)\n assert isinstance(m.body[1], ast.ImportFrom)\n for imp in m.body[2:4]:\n assert isinstance(imp, ast.Import)\n assert imp.lineno == 2\n assert imp.col_offset == 0\n s = \"\"\"'doc string'\\nfrom __future__ import division\\nother\"\"\"\n m = rewrite(s)\n assert isinstance(m.body[0], ast.Expr)\n assert isinstance(m.body[1], ast.ImportFrom)\n for imp in m.body[2:4]:\n assert isinstance(imp, ast.Import)\n assert imp.lineno == 3\n assert imp.col_offset == 0\n assert isinstance(m.body[4], ast.Expr)\n s = \"\"\"from . import relative\\nother_stuff\"\"\"\n m = rewrite(s)\n for imp in m.body[:2]:\n assert isinstance(imp, ast.Import)\n assert imp.lineno == 1\n assert imp.col_offset == 0\n assert isinstance(m.body[3], ast.Expr)"},{"col":4,"comment":"null","endLoc":293,"header":"@staticmethod\n def make_function(testdir, **kwargs)","id":3629,"name":"make_function","nodeType":"Function","startLoc":285,"text":"@staticmethod\n def make_function(testdir, **kwargs):\n from _pytest.fixtures import FixtureManager\n\n config = testdir.parseconfigure()\n session = testdir.Session(config)\n session._fixturemanager = FixtureManager(session)\n\n return pytest.Function(config=config, parent=session, **kwargs)"},{"attributeType":"Path","col":0,"comment":"null","endLoc":5,"id":3631,"name":"HERE","nodeType":"Attribute","startLoc":5,"text":"HERE"},{"col":0,"comment":"null","endLoc":44,"header":"def rewrite(src)","id":3632,"name":"rewrite","nodeType":"Function","startLoc":41,"text":"def rewrite(src):\n tree = ast.parse(src)\n rewrite_asserts(tree)\n return tree"},{"col":4,"comment":"null","endLoc":305,"header":"def test_function_equality(self, testdir, tmpdir)","id":3633,"name":"test_function_equality","nodeType":"Function","startLoc":295,"text":"def test_function_equality(self, testdir, tmpdir):\n def func1():\n pass\n\n def func2():\n pass\n\n f1 = self.make_function(testdir, name=\"name\", args=(1,), callobj=func1)\n assert f1 == f1\n f2 = self.make_function(testdir, name=\"name\", callobj=func2)\n assert f1 != f2"},{"col":0,"comment":"null","endLoc":485,"header":"def test_pytester_addopts(request, monkeypatch)","id":3634,"name":"test_pytester_addopts","nodeType":"Function","startLoc":475,"text":"def test_pytester_addopts(request, monkeypatch):\n monkeypatch.setenv(\"PYTEST_ADDOPTS\", \"--orig-unused\")\n\n testdir = request.getfixturevalue(\"testdir\")\n\n try:\n assert \"PYTEST_ADDOPTS\" not in os.environ\n finally:\n testdir.finalize()\n\n assert os.environ[\"PYTEST_ADDOPTS\"] == \"--orig-unused\""},{"col":4,"comment":" return command line option value.\n\n :arg name: name of the option. You may also specify\n the literal ``--OPT`` option instead of the \"dest\" option name.\n :arg default: default value if no option of that name exists.\n :arg skip: if True raise pytest.skip if option does not exists\n or has a None value.\n ","endLoc":1013,"header":"def getoption(self, name, default=notset, skip=False)","id":3635,"name":"getoption","nodeType":"Function","startLoc":991,"text":"def getoption(self, name, default=notset, skip=False):\n \"\"\" return command line option value.\n\n :arg name: name of the option. You may also specify\n the literal ``--OPT`` option instead of the \"dest\" option name.\n :arg default: default value if no option of that name exists.\n :arg skip: if True raise pytest.skip if option does not exists\n or has a None value.\n \"\"\"\n name = self._opt2dest.get(name, name)\n try:\n val = getattr(self.option, name)\n if val is None and skip:\n raise AttributeError(name)\n return val\n except AttributeError:\n if default is not notset:\n return default\n if skip:\n import pytest\n\n pytest.skip(\"no %r option found\" % (name,))\n raise ValueError(\"no option named %r\" % (name,))"},{"col":0,"comment":"null","endLoc":515,"header":"def test_run_stdin(testdir)","id":3636,"name":"test_run_stdin","nodeType":"Function","startLoc":488,"text":"def test_run_stdin(testdir):\n with pytest.raises(testdir.TimeoutExpired):\n testdir.run(\n sys.executable,\n \"-c\",\n \"import sys, time; time.sleep(1); print(sys.stdin.read())\",\n stdin=subprocess.PIPE,\n timeout=0.1,\n )\n\n with pytest.raises(testdir.TimeoutExpired):\n result = testdir.run(\n sys.executable,\n \"-c\",\n \"import sys, time; time.sleep(1); print(sys.stdin.read())\",\n stdin=b\"input\\n2ndline\",\n timeout=0.1,\n )\n\n result = testdir.run(\n sys.executable,\n \"-c\",\n \"import sys; print(sys.stdin.read())\",\n stdin=b\"input\\n2ndline\",\n )\n assert result.stdout.lines == [\"input\", \"2ndline\"]\n assert result.stderr.str() == \"\"\n assert result.ret == 0"},{"attributeType":"function","col":0,"comment":"null","endLoc":68,"id":3637,"name":"isfunction","nodeType":"Attribute","startLoc":68,"text":"isfunction"},{"col":4,"comment":"null","endLoc":311,"header":"def test_repr_produces_actual_test_id(self, testdir)","id":3638,"name":"test_repr_produces_actual_test_id","nodeType":"Function","startLoc":307,"text":"def test_repr_produces_actual_test_id(self, testdir):\n f = self.make_function(\n testdir, name=r\"test[\\xe5]\", callobj=self.test_repr_produces_actual_test_id\n )\n assert repr(f) == r\"\""},{"attributeType":"Pattern","col":0,"comment":"null","endLoc":73,"id":3639,"name":"REGEX_TYPE","nodeType":"Attribute","startLoc":73,"text":"REGEX_TYPE"},{"col":4,"comment":"\n :param _pytest.terminal.TerminalReporter terminal_reporter:\n :param _pytest.capture.CaptureManager capture_manager:\n ","endLoc":678,"header":"def __init__(self, terminal_reporter, capture_manager)","id":3640,"name":"__init__","nodeType":"Function","startLoc":669,"text":"def __init__(self, terminal_reporter, capture_manager):\n \"\"\"\n :param _pytest.terminal.TerminalReporter terminal_reporter:\n :param _pytest.capture.CaptureManager capture_manager:\n \"\"\"\n logging.StreamHandler.__init__(self, stream=terminal_reporter)\n self.capture_manager = capture_manager\n self.reset()\n self.set_when(None)\n self._test_outcome_written = False"},{"attributeType":"str","col":0,"comment":"null","endLoc":145,"id":3641,"name":"html_logo","nodeType":"Attribute","startLoc":145,"text":"html_logo"},{"attributeType":"str","col":0,"comment":"null","endLoc":150,"id":3642,"name":"html_favicon","nodeType":"Attribute","startLoc":150,"text":"html_favicon"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":169,"id":3643,"name":"html_sidebars","nodeType":"Attribute","startLoc":169,"text":"html_sidebars"},{"attributeType":"bool","col":0,"comment":"null","endLoc":193,"id":3644,"name":"html_domain_indices","nodeType":"Attribute","startLoc":193,"text":"html_domain_indices"},{"attributeType":"bool","col":0,"comment":"null","endLoc":196,"id":3645,"name":"html_use_index","nodeType":"Attribute","startLoc":196,"text":"html_use_index"},{"attributeType":"bool","col":0,"comment":"null","endLoc":202,"id":3646,"name":"html_show_sourcelink","nodeType":"Attribute","startLoc":202,"text":"html_show_sourcelink"},{"attributeType":"str","col":0,"comment":"null","endLoc":219,"id":3647,"name":"htmlhelp_basename","nodeType":"Attribute","startLoc":219,"text":"htmlhelp_basename"},{"attributeType":"list","col":0,"comment":"null","endLoc":232,"id":3648,"name":"latex_documents","nodeType":"Attribute","startLoc":232,"text":"latex_documents"},{"attributeType":"str","col":0,"comment":"null","endLoc":244,"id":3649,"name":"latex_logo","nodeType":"Attribute","startLoc":244,"text":"latex_logo"},{"attributeType":"bool","col":0,"comment":"null","endLoc":263,"id":3650,"name":"latex_domain_indices","nodeType":"Attribute","startLoc":263,"text":"latex_domain_indices"},{"attributeType":"list","col":0,"comment":"null","endLoc":269,"id":3651,"name":"man_pages","nodeType":"Attribute","startLoc":269,"text":"man_pages"},{"attributeType":"str","col":0,"comment":"null","endLoc":275,"id":3652,"name":"epub_title","nodeType":"Attribute","startLoc":275,"text":"epub_title"},{"attributeType":"str","col":0,"comment":"null","endLoc":276,"id":3653,"name":"epub_author","nodeType":"Attribute","startLoc":276,"text":"epub_author"},{"attributeType":"str","col":0,"comment":"null","endLoc":277,"id":3654,"name":"epub_publisher","nodeType":"Attribute","startLoc":277,"text":"epub_publisher"},{"attributeType":"str","col":0,"comment":"null","endLoc":278,"id":3655,"name":"epub_copyright","nodeType":"Attribute","startLoc":278,"text":"epub_copyright"},{"attributeType":"list","col":0,"comment":"null","endLoc":314,"id":3656,"name":"texinfo_documents","nodeType":"Attribute","startLoc":314,"text":"texinfo_documents"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":332,"id":3657,"name":"intersphinx_mapping","nodeType":"Attribute","startLoc":332,"text":"intersphinx_mapping"},{"col":4,"comment":"null","endLoc":323,"header":"def test_issue197_parametrize_emptyset(self, testdir)","id":3658,"name":"test_issue197_parametrize_emptyset","nodeType":"Function","startLoc":313,"text":"def test_issue197_parametrize_emptyset(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('arg', [])\n def test_function(arg):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(skipped=1)"},{"col":0,"comment":"","endLoc":19,"header":"conf.py#","id":3659,"name":"","nodeType":"Function","startLoc":19,"text":"release = \".\".join(version.split(\".\")[:2])\n\nautodoc_member_order = \"bysource\"\n\ntodo_include_todos = 1\n\nextensions = [\n \"pygments_pytest\",\n \"sphinx.ext.autodoc\",\n \"sphinx.ext.autosummary\",\n \"sphinx.ext.intersphinx\",\n \"sphinx.ext.todo\",\n \"sphinx.ext.viewcode\",\n \"sphinx_removed_in\",\n \"sphinxcontrib_trio\",\n]\n\ntemplates_path = [\"_templates\"]\n\nsource_suffix = \".rst\"\n\nmaster_doc = \"contents\"\n\nproject = u\"pytest\"\n\nyear = datetime.datetime.utcnow().year\n\ncopyright = u\"2015–2019 , holger krekel and pytest-dev team\"\n\nexclude_patterns = [\n \"links.inc\",\n \"_build\",\n \"naming20.rst\",\n \"test/*\",\n \"old_*\",\n \"*attic*\",\n \"*/attic*\",\n \"funcargs.rst\",\n \"setup.rst\",\n \"example/remoteinterp.rst\",\n]\n\nadd_module_names = False\n\npygments_style = \"sphinx\"\n\nsys.path.append(os.path.abspath(\"_themes\"))\n\nhtml_theme_path = [\"_themes\"]\n\nhtml_theme = \"flask\"\n\nhtml_theme_options = {\"index_logo\": None}\n\nhtml_title = \"pytest documentation\"\n\nhtml_short_title = \"pytest-%s\" % release\n\nhtml_logo = \"img/pytest1.png\"\n\nhtml_favicon = \"img/pytest1favi.ico\"\n\nhtml_sidebars = {\n \"index\": [\n \"sidebarintro.html\",\n \"globaltoc.html\",\n \"links.html\",\n \"sourcelink.html\",\n \"searchbox.html\",\n ],\n \"**\": [\n \"globaltoc.html\",\n \"relations.html\",\n \"links.html\",\n \"sourcelink.html\",\n \"searchbox.html\",\n ],\n}\n\nhtml_domain_indices = True\n\nhtml_use_index = False\n\nhtml_show_sourcelink = False\n\nhtmlhelp_basename = \"pytestdoc\"\n\nlatex_documents = [\n (\n \"contents\",\n \"pytest.tex\",\n u\"pytest Documentation\",\n u\"holger krekel, trainer and consultant, http://merlinux.eu\",\n \"manual\",\n )\n]\n\nlatex_logo = \"img/pytest1.png\"\n\nlatex_domain_indices = False\n\nman_pages = [(\"usage\", \"pytest\", u\"pytest usage\", [u\"holger krekel at merlinux eu\"], 1)]\n\nepub_title = u\"pytest\"\n\nepub_author = u\"holger krekel at merlinux eu\"\n\nepub_publisher = u\"holger krekel at merlinux eu\"\n\nepub_copyright = u\"2013, holger krekel et alii\"\n\ntexinfo_documents = [\n (\n master_doc,\n \"pytest\",\n \"pytest Documentation\",\n (\n \"Holger Krekel@*Benjamin Peterson@*Ronny Pfannschmidt@*\"\n \"Floris Bruynooghe@*others\"\n ),\n \"pytest\",\n \"simple powerful testing with Python\",\n \"Programming\",\n 1,\n )\n]\n\nintersphinx_mapping = {\"python\": (\"https://docs.python.org/3\", None)}"},{"attributeType":"dict","col":0,"comment":"null","endLoc":186,"id":3661,"name":"_non_printable_ascii_translate_table","nodeType":"Attribute","startLoc":186,"text":"_non_printable_ascii_translate_table"},{"col":4,"comment":"null","endLoc":47,"header":"def dumps(self, obj)","id":3662,"name":"dumps","nodeType":"Function","startLoc":33,"text":"def dumps(self, obj):\n dumpfile = self.picklefile.dirpath(\"dump.py\")\n dumpfile.write(\n textwrap.dedent(\n r\"\"\"\n import pickle\n f = open({!r}, 'wb')\n s = pickle.dump({!r}, f, protocol=2)\n f.close()\n \"\"\".format(\n str(self.picklefile), obj\n )\n )\n )\n subprocess.check_call((self.pythonpath, str(dumpfile)))"},{"col":0,"comment":"null","endLoc":529,"header":"def test_popen_stdin_pipe(testdir)","id":3663,"name":"test_popen_stdin_pipe","nodeType":"Function","startLoc":518,"text":"def test_popen_stdin_pipe(testdir):\n proc = testdir.popen(\n [sys.executable, \"-c\", \"import sys; print(sys.stdin.read())\"],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n stdin=subprocess.PIPE,\n )\n stdin = b\"input\\n2ndline\"\n stdout, stderr = proc.communicate(input=stdin)\n assert stdout.decode(\"utf8\").splitlines() == [\"input\", \"2ndline\"]\n assert stderr == b\"\"\n assert proc.returncode == 0"},{"col":4,"comment":"null","endLoc":335,"header":"def test_single_tuple_unwraps_values(self, testdir)","id":3664,"name":"test_single_tuple_unwraps_values","nodeType":"Function","startLoc":325,"text":"def test_single_tuple_unwraps_values(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize(('arg',), [(1,)])\n def test_function(arg):\n assert arg == 1\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":0,"comment":"null","endLoc":542,"header":"def test_popen_stdin_bytes(testdir)","id":3665,"name":"test_popen_stdin_bytes","nodeType":"Function","startLoc":532,"text":"def test_popen_stdin_bytes(testdir):\n proc = testdir.popen(\n [sys.executable, \"-c\", \"import sys; print(sys.stdin.read())\"],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n stdin=b\"input\\n2ndline\",\n )\n stdout, stderr = proc.communicate()\n assert stdout.decode(\"utf8\").splitlines() == [\"input\", \"2ndline\"]\n assert stderr == b\"\"\n assert proc.returncode == 0"},{"col":0,"comment":"null","endLoc":561,"header":"def test_popen_default_stdin_stderr_and_stdin_None(testdir)","id":3666,"name":"test_popen_default_stdin_stderr_and_stdin_None","nodeType":"Function","startLoc":545,"text":"def test_popen_default_stdin_stderr_and_stdin_None(testdir):\n # stdout, stderr default to pipes,\n # stdin can be None to not close the pipe, avoiding\n # \"ValueError: flush of closed file\" with `communicate()`.\n p1 = testdir.makepyfile(\n \"\"\"\n import sys\n print(sys.stdin.read()) # empty\n print('stdout')\n sys.stderr.write('stderr')\n \"\"\"\n )\n proc = testdir.popen([sys.executable, str(p1)], stdin=None)\n stdout, stderr = proc.communicate(b\"ignored\")\n assert stdout.splitlines() == [b\"\", b\"stdout\"]\n assert stderr.splitlines() == [b\"stderr\"]\n assert proc.returncode == 0"},{"col":4,"comment":"Reset the handler; should be called before the start of each test","endLoc":682,"header":"def reset(self)","id":3667,"name":"reset","nodeType":"Function","startLoc":680,"text":"def reset(self):\n \"\"\"Reset the handler; should be called before the start of each test\"\"\"\n self._first_record_emitted = False"},{"col":4,"comment":"null","endLoc":350,"header":"def test_issue213_parametrize_value_no_equal(self, testdir)","id":3668,"name":"test_issue213_parametrize_value_no_equal","nodeType":"Function","startLoc":337,"text":"def test_issue213_parametrize_value_no_equal(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n class A(object):\n def __eq__(self, other):\n raise ValueError(\"not possible\")\n @pytest.mark.parametrize('arg', [A()])\n def test_function(arg):\n assert arg.__class__.__name__ == \"A\"\n \"\"\"\n )\n reprec = testdir.inline_run(\"--fulltrace\")\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":"Prepares for the given test phase (setup/call/teardown)","endLoc":689,"header":"def set_when(self, when)","id":3669,"name":"set_when","nodeType":"Function","startLoc":684,"text":"def set_when(self, when):\n \"\"\"Prepares for the given test phase (setup/call/teardown)\"\"\"\n self._when = when\n self._section_name_shown = False\n if when == \"start\":\n self._test_outcome_written = False"},{"col":4,"comment":" (deprecated, use getoption()) ","endLoc":1017,"header":"def getvalue(self, name, path=None)","id":3670,"name":"getvalue","nodeType":"Function","startLoc":1015,"text":"def getvalue(self, name, path=None):\n \"\"\" (deprecated, use getoption()) \"\"\"\n return self.getoption(name)"},{"col":4,"comment":"Test parametrization with non-hashable values.","endLoc":370,"header":"def test_parametrize_with_non_hashable_values(self, testdir)","id":3671,"name":"test_parametrize_with_non_hashable_values","nodeType":"Function","startLoc":352,"text":"def test_parametrize_with_non_hashable_values(self, testdir):\n \"\"\"Test parametrization with non-hashable values.\"\"\"\n testdir.makepyfile(\n \"\"\"\n archival_mapping = {\n '1.0': {'tag': '1.0'},\n '1.2.2a1': {'tag': 'release-1.2.2a1'},\n }\n\n import pytest\n @pytest.mark.parametrize('key value'.split(),\n archival_mapping.items())\n def test_archival_to_version(key, value):\n assert key in archival_mapping\n assert value == archival_mapping[key]\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(passed=2)"},{"col":4,"comment":"Test parametrization with non-hashable values with indirect parametrization.","endLoc":399,"header":"def test_parametrize_with_non_hashable_values_indirect(self, testdir)","id":3672,"name":"test_parametrize_with_non_hashable_values_indirect","nodeType":"Function","startLoc":372,"text":"def test_parametrize_with_non_hashable_values_indirect(self, testdir):\n \"\"\"Test parametrization with non-hashable values with indirect parametrization.\"\"\"\n testdir.makepyfile(\n \"\"\"\n archival_mapping = {\n '1.0': {'tag': '1.0'},\n '1.2.2a1': {'tag': 'release-1.2.2a1'},\n }\n\n import pytest\n\n @pytest.fixture\n def key(request):\n return request.param\n\n @pytest.fixture\n def value(request):\n return request.param\n\n @pytest.mark.parametrize('key value'.split(),\n archival_mapping.items(), indirect=True)\n def test_archival_to_version(key, value):\n assert key in archival_mapping\n assert value == archival_mapping[key]\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(passed=2)"},{"id":3673,"name":"testing/example_scripts","nodeType":"Package"},{"fileName":"issue_519.py","filePath":"testing/example_scripts","id":3674,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pprint\n\nimport pytest\n\n\ndef pytest_generate_tests(metafunc):\n if \"arg1\" in metafunc.fixturenames:\n metafunc.parametrize(\"arg1\", [\"arg1v1\", \"arg1v2\"], scope=\"module\")\n\n if \"arg2\" in metafunc.fixturenames:\n metafunc.parametrize(\"arg2\", [\"arg2v1\", \"arg2v2\"], scope=\"function\")\n\n\n@pytest.fixture(scope=\"session\")\ndef checked_order():\n order = []\n\n yield order\n pprint.pprint(order)\n assert order == [\n (\"testing/example_scripts/issue_519.py\", \"fix1\", \"arg1v1\"),\n (\"test_one[arg1v1-arg2v1]\", \"fix2\", \"arg2v1\"),\n (\"test_two[arg1v1-arg2v1]\", \"fix2\", \"arg2v1\"),\n (\"test_one[arg1v1-arg2v2]\", \"fix2\", \"arg2v2\"),\n (\"test_two[arg1v1-arg2v2]\", \"fix2\", \"arg2v2\"),\n (\"testing/example_scripts/issue_519.py\", \"fix1\", \"arg1v2\"),\n (\"test_one[arg1v2-arg2v1]\", \"fix2\", \"arg2v1\"),\n (\"test_two[arg1v2-arg2v1]\", \"fix2\", \"arg2v1\"),\n (\"test_one[arg1v2-arg2v2]\", \"fix2\", \"arg2v2\"),\n (\"test_two[arg1v2-arg2v2]\", \"fix2\", \"arg2v2\"),\n ]\n\n\n@pytest.yield_fixture(scope=\"module\")\ndef fix1(request, arg1, checked_order):\n checked_order.append((request.node.name, \"fix1\", arg1))\n yield \"fix1-\" + arg1\n\n\n@pytest.yield_fixture(scope=\"function\")\ndef fix2(request, fix1, arg2, checked_order):\n checked_order.append((request.node.name, \"fix2\", arg2))\n yield \"fix2-\" + arg2 + fix1\n\n\ndef test_one(fix2):\n pass\n\n\ndef test_two(fix2):\n pass\n"},{"col":0,"comment":"null","endLoc":12,"header":"def pytest_generate_tests(metafunc)","id":3675,"name":"pytest_generate_tests","nodeType":"Function","startLoc":7,"text":"def pytest_generate_tests(metafunc):\n if \"arg1\" in metafunc.fixturenames:\n metafunc.parametrize(\"arg1\", [\"arg1v1\", \"arg1v2\"], scope=\"module\")\n\n if \"arg2\" in metafunc.fixturenames:\n metafunc.parametrize(\"arg2\", [\"arg2v1\", \"arg2v2\"], scope=\"function\")"},{"col":4,"comment":"Test parametrization when parameter overrides existing fixture with same name.","endLoc":428,"header":"def test_parametrize_overrides_fixture(self, testdir)","id":3676,"name":"test_parametrize_overrides_fixture","nodeType":"Function","startLoc":401,"text":"def test_parametrize_overrides_fixture(self, testdir):\n \"\"\"Test parametrization when parameter overrides existing fixture with same name.\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def value():\n return 'value'\n\n @pytest.mark.parametrize('value',\n ['overridden'])\n def test_overridden_via_param(value):\n assert value == 'overridden'\n\n @pytest.mark.parametrize('somevalue', ['overridden'])\n def test_not_overridden(value, somevalue):\n assert value == 'value'\n assert somevalue == 'overridden'\n\n @pytest.mark.parametrize('other,value', [('foo', 'overridden')])\n def test_overridden_via_multiparam(other, value):\n assert other == 'foo'\n assert value == 'overridden'\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(passed=3)"},{"col":0,"comment":"null","endLoc":587,"header":"def test_spawn_uses_tmphome(testdir)","id":3677,"name":"test_spawn_uses_tmphome","nodeType":"Function","startLoc":564,"text":"def test_spawn_uses_tmphome(testdir):\n import os\n\n tmphome = str(testdir.tmpdir)\n\n # Does use HOME only during run.\n assert os.environ.get(\"HOME\") != tmphome\n\n testdir._env_run_update[\"CUSTOMENV\"] = \"42\"\n\n p1 = testdir.makepyfile(\n \"\"\"\n import os\n\n def test():\n assert os.environ[\"HOME\"] == {tmphome!r}\n assert os.environ[\"CUSTOMENV\"] == \"42\"\n \"\"\".format(\n tmphome=tmphome\n )\n )\n child = testdir.spawn_pytest(str(p1))\n out = child.read()\n assert child.wait() == 0, out.decode(\"utf8\")"},{"col":4,"comment":"Test parametrization when parameter overrides existing parametrized fixture with same name.","endLoc":447,"header":"def test_parametrize_overrides_parametrized_fixture(self, testdir)","id":3678,"name":"test_parametrize_overrides_parametrized_fixture","nodeType":"Function","startLoc":430,"text":"def test_parametrize_overrides_parametrized_fixture(self, testdir):\n \"\"\"Test parametrization when parameter overrides existing parametrized fixture with same name.\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture(params=[1, 2])\n def value(request):\n return request.param\n\n @pytest.mark.parametrize('value',\n ['overridden'])\n def test_overridden_via_param(value):\n assert value == 'overridden'\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(passed=1)"},{"col":4,"comment":"Test parametrization when parameter overrides a fixture that a test indirectly depends on","endLoc":478,"header":"def test_parametrize_overrides_indirect_dependency_fixture(self, testdir)","id":3679,"name":"test_parametrize_overrides_indirect_dependency_fixture","nodeType":"Function","startLoc":449,"text":"def test_parametrize_overrides_indirect_dependency_fixture(self, testdir):\n \"\"\"Test parametrization when parameter overrides a fixture that a test indirectly depends on\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n fix3_instantiated = False\n\n @pytest.fixture\n def fix1(fix2):\n return fix2 + '1'\n\n @pytest.fixture\n def fix2(fix3):\n return fix3 + '2'\n\n @pytest.fixture\n def fix3():\n global fix3_instantiated\n fix3_instantiated = True\n return '3'\n\n @pytest.mark.parametrize('fix2', ['2'])\n def test_it(fix1):\n assert fix1 == '21'\n assert not fix3_instantiated\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(passed=1)"},{"col":4,"comment":"null","endLoc":499,"header":"def test_parametrize_with_mark(self, testdir)","id":3680,"name":"test_parametrize_with_mark","nodeType":"Function","startLoc":480,"text":"def test_parametrize_with_mark(self, testdir):\n items = testdir.getitems(\n \"\"\"\n import pytest\n @pytest.mark.foo\n @pytest.mark.parametrize('arg', [\n 1,\n pytest.param(2, marks=[pytest.mark.baz, pytest.mark.bar])\n ])\n def test_function(arg):\n pass\n \"\"\"\n )\n keywords = [item.keywords for item in items]\n assert (\n \"foo\" in keywords[0]\n and \"bar\" not in keywords[0]\n and \"baz\" not in keywords[0]\n )\n assert \"foo\" in keywords[1] and \"bar\" in keywords[1] and \"baz\" in keywords[1]"},{"col":4,"comment":"null","endLoc":511,"header":"def test_function_equality_with_callspec(self, testdir, tmpdir)","id":3681,"name":"test_function_equality_with_callspec","nodeType":"Function","startLoc":501,"text":"def test_function_equality_with_callspec(self, testdir, tmpdir):\n items = testdir.getitems(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('arg', [1,2])\n def test_function(arg):\n pass\n \"\"\"\n )\n assert items[0] != items[1]\n assert not (items[0] == items[1])"},{"col":4,"comment":"null","endLoc":528,"header":"def test_pyfunc_call(self, testdir)","id":3682,"name":"test_pyfunc_call","nodeType":"Function","startLoc":513,"text":"def test_pyfunc_call(self, testdir):\n item = testdir.getitem(\"def test_func(): raise ValueError\")\n config = item.config\n\n class MyPlugin1(object):\n def pytest_pyfunc_call(self, pyfuncitem):\n raise ValueError\n\n class MyPlugin2(object):\n def pytest_pyfunc_call(self, pyfuncitem):\n return True\n\n config.pluginmanager.register(MyPlugin1())\n config.pluginmanager.register(MyPlugin2())\n config.hook.pytest_runtest_setup(item=item)\n config.hook.pytest_pyfunc_call(pyfuncitem=item)"},{"col":4,"comment":" (deprecated, use getoption(skip=True)) ","endLoc":1021,"header":"def getvalueorskip(self, name, path=None)","id":3683,"name":"getvalueorskip","nodeType":"Function","startLoc":1019,"text":"def getvalueorskip(self, name, path=None):\n \"\"\" (deprecated, use getoption(skip=True)) \"\"\"\n return self.getoption(name, skip=True)"},{"attributeType":"bool","col":8,"comment":"null","endLoc":659,"id":3684,"name":"_configured","nodeType":"Attribute","startLoc":659,"text":"self._configured"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":656,"id":3685,"name":"_opt2dest","nodeType":"Attribute","startLoc":656,"text":"self._opt2dest"},{"attributeType":"Parser","col":8,"comment":"null","endLoc":646,"id":3686,"name":"_parser","nodeType":"Attribute","startLoc":646,"text":"self._parser"},{"attributeType":"list","col":8,"comment":"null","endLoc":657,"id":3687,"name":"_cleanup","nodeType":"Attribute","startLoc":657,"text":"self._cleanup"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":654,"id":3688,"name":"_inicache","nodeType":"Attribute","startLoc":654,"text":"self._inicache"},{"attributeType":"null","col":8,"comment":"null","endLoc":651,"id":3689,"name":"pluginmanager","nodeType":"Attribute","startLoc":651,"text":"self.pluginmanager"},{"attributeType":"()","col":8,"comment":"null","endLoc":655,"id":3690,"name":"_override_ini","nodeType":"Attribute","startLoc":655,"text":"self._override_ini"},{"attributeType":"null","col":8,"comment":"null","endLoc":762,"id":3691,"name":"rootdir","nodeType":"Attribute","startLoc":762,"text":"self.rootdir"},{"attributeType":"null","col":8,"comment":"null","endLoc":891,"id":3692,"name":"_origargs","nodeType":"Attribute","startLoc":891,"text":"self._origargs"},{"attributeType":"null","col":36,"comment":"null","endLoc":762,"id":3693,"name":"inicfg","nodeType":"Attribute","startLoc":762,"text":"self.inicfg"},{"attributeType":"list | list | str | bool","col":12,"comment":"null","endLoc":908,"id":3694,"name":"args","nodeType":"Attribute","startLoc":908,"text":"self.args"},{"attributeType":"null","col":27,"comment":"null","endLoc":13,"id":3695,"name":"pytester","nodeType":"Attribute","startLoc":13,"text":"pytester"},{"col":0,"comment":"null","endLoc":32,"header":"@pytest.fixture(scope=\"session\")\ndef checked_order()","id":3696,"name":"checked_order","nodeType":"Function","startLoc":15,"text":"@pytest.fixture(scope=\"session\")\ndef checked_order():\n order = []\n\n yield order\n pprint.pprint(order)\n assert order == [\n (\"testing/example_scripts/issue_519.py\", \"fix1\", \"arg1v1\"),\n (\"test_one[arg1v1-arg2v1]\", \"fix2\", \"arg2v1\"),\n (\"test_two[arg1v1-arg2v1]\", \"fix2\", \"arg2v1\"),\n (\"test_one[arg1v1-arg2v2]\", \"fix2\", \"arg2v2\"),\n (\"test_two[arg1v1-arg2v2]\", \"fix2\", \"arg2v2\"),\n (\"testing/example_scripts/issue_519.py\", \"fix1\", \"arg1v2\"),\n (\"test_one[arg1v2-arg2v1]\", \"fix2\", \"arg2v1\"),\n (\"test_two[arg1v2-arg2v1]\", \"fix2\", \"arg2v1\"),\n (\"test_one[arg1v2-arg2v2]\", \"fix2\", \"arg2v2\"),\n (\"test_two[arg1v2-arg2v2]\", \"fix2\", \"arg2v2\"),\n ]"},{"col":4,"comment":"null","endLoc":118,"header":"def test_dont_rewrite(self)","id":3697,"name":"test_dont_rewrite","nodeType":"Function","startLoc":114,"text":"def test_dont_rewrite(self):\n s = \"\"\"'PYTEST_DONT_REWRITE'\\nassert 14\"\"\"\n m = rewrite(s)\n assert len(m.body) == 2\n assert m.body[1].msg is None"},{"col":4,"comment":"null","endLoc":544,"header":"def test_multiple_parametrize(self, testdir)","id":3698,"name":"test_multiple_parametrize","nodeType":"Function","startLoc":530,"text":"def test_multiple_parametrize(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('x', [0, 1])\n @pytest.mark.parametrize('y', [2, 3])\n def test1(x, y):\n pass\n \"\"\"\n )\n colitems = modcol.collect()\n assert colitems[0].name == \"test1[2-0]\"\n assert colitems[1].name == \"test1[2-1]\"\n assert colitems[2].name == \"test1[3-0]\"\n assert colitems[3].name == \"test1[3-1]\""},{"col":4,"comment":"null","endLoc":128,"header":"def test_dont_rewrite_plugin(self, testdir)","id":3699,"name":"test_dont_rewrite_plugin","nodeType":"Function","startLoc":120,"text":"def test_dont_rewrite_plugin(self, testdir):\n contents = {\n \"conftest.py\": \"pytest_plugins = 'plugin'; import plugin\",\n \"plugin.py\": \"'PYTEST_DONT_REWRITE'\",\n \"test_foo.py\": \"def test_foo(): pass\",\n }\n testdir.makepyfile(**contents)\n result = testdir.runpytest_subprocess()\n assert \"warnings\" not in \"\".join(result.outlines)"},{"col":4,"comment":"null","endLoc":563,"header":"def test_issue751_multiple_parametrize_with_ids(self, testdir)","id":3700,"name":"test_issue751_multiple_parametrize_with_ids","nodeType":"Function","startLoc":546,"text":"def test_issue751_multiple_parametrize_with_ids(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('x', [0], ids=['c'])\n @pytest.mark.parametrize('y', [0, 1], ids=['a', 'b'])\n class Test(object):\n def test1(self, x, y):\n pass\n def test2(self, x, y):\n pass\n \"\"\"\n )\n colitems = modcol.collect()[0].collect()[0].collect()\n assert colitems[0].name == \"test1[a-c]\"\n assert colitems[1].name == \"test1[b-c]\"\n assert colitems[2].name == \"test2[a-c]\"\n assert colitems[3].name == \"test2[b-c]\""},{"attributeType":"null","col":8,"comment":"null","endLoc":652,"id":3701,"name":"trace","nodeType":"Attribute","startLoc":652,"text":"self.trace"},{"id":3702,"name":"nose.rst","nodeType":"TextFile","path":"doc/en","text":".. _`noseintegration`:\n\nRunning tests written for nose\n=======================================\n\n.. include:: links.inc\n\n``pytest`` has basic support for running tests written for nose_.\n\n.. _nosestyle:\n\nUsage\n-------------\n\nAfter :ref:`installation` type:\n\n.. code-block:: bash\n\n python setup.py develop # make sure tests can import our package\n pytest # instead of 'nosetests'\n\nand you should be able to run your nose style tests and\nmake use of pytest's capabilities.\n\nSupported nose Idioms\n----------------------\n\n* setup and teardown at module/class/method level\n* SkipTest exceptions and markers\n* setup/teardown decorators\n* ``yield``-based tests and their setup (considered deprecated as of pytest 3.0)\n* ``__test__`` attribute on modules/classes/functions\n* general usage of nose utilities\n\nUnsupported idioms / known issues\n----------------------------------\n\n- unittest-style ``setUp, tearDown, setUpClass, tearDownClass``\n are recognized only on ``unittest.TestCase`` classes but not\n on plain classes. ``nose`` supports these methods also on plain\n classes but pytest deliberately does not. As nose and pytest already\n both support ``setup_class, teardown_class, setup_method, teardown_method``\n it doesn't seem useful to duplicate the unittest-API like nose does.\n If you however rather think pytest should support the unittest-spelling on\n plain classes please post `to this issue\n `_.\n\n- nose imports test modules with the same import path (e.g.\n ``tests.test_mod``) but different file system paths\n (e.g. ``tests/test_mode.py`` and ``other/tests/test_mode.py``)\n by extending sys.path/import semantics. pytest does not do that\n but there is discussion in `#268 `_ for adding some support. Note that\n `nose2 choose to avoid this sys.path/import hackery `_.\n\n If you place a conftest.py file in the root directory of your project\n (as determined by pytest) pytest will run tests \"nose style\" against\n the code below that directory by adding it to your ``sys.path`` instead of\n running against your installed code.\n\n You may find yourself wanting to do this if you ran ``python setup.py install``\n to set up your project, as opposed to ``python setup.py develop`` or any of\n the package manager equivalents. Installing with develop in a\n virtual environment like tox is recommended over this pattern.\n\n- nose-style doctests are not collected and executed correctly,\n also doctest fixtures don't work.\n\n- no nose-configuration is recognized.\n\n- ``yield``-based methods don't support ``setup`` properly because\n the ``setup`` method is always called in the same class instance.\n There are no plans to fix this currently because ``yield``-tests\n are deprecated in pytest 3.0, with ``pytest.mark.parametrize``\n being the recommended alternative.\n"},{"col":4,"comment":"null","endLoc":578,"header":"def test_parametrize_skipif(self, testdir)","id":3703,"name":"test_parametrize_skipif","nodeType":"Function","startLoc":565,"text":"def test_parametrize_skipif(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n m = pytest.mark.skipif('True')\n\n @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])\n def test_skip_if(x):\n assert x < 2\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed, 1 skipped in *\"])"},{"col":4,"comment":"null","endLoc":182,"header":"def test_name(self, request)","id":3704,"name":"test_name","nodeType":"Function","startLoc":130,"text":"def test_name(self, request):\n def f():\n assert False\n\n assert getmsg(f) == \"assert False\"\n\n def f():\n f = False\n assert f\n\n assert getmsg(f) == \"assert False\"\n\n def f():\n assert a_global # noqa\n\n assert getmsg(f, {\"a_global\": False}) == \"assert False\"\n\n def f():\n assert sys == 42\n\n verbose = request.config.getoption(\"verbose\")\n msg = getmsg(f, {\"sys\": sys})\n if verbose > 0:\n assert msg == (\n \"assert == 42\\n\"\n \" -\\n\"\n \" +42\"\n )\n else:\n assert msg == \"assert sys == 42\"\n\n def f():\n assert cls == 42 # noqa: F821\n\n class X(object):\n pass\n\n msg = getmsg(f, {\"cls\": X}).splitlines()\n if verbose > 0:\n if six.PY2:\n assert msg == [\n \"assert == 42\",\n \" -\",\n \" +42\",\n ]\n else:\n assert msg == [\n \"assert .X'> == 42\",\n \" -.X'>\",\n \" +42\",\n ]\n else:\n assert msg == [\"assert cls == 42\"]"},{"attributeType":"null","col":8,"comment":"null","endLoc":653,"id":3705,"name":"hook","nodeType":"Attribute","startLoc":653,"text":"self.hook"},{"attributeType":"null","col":22,"comment":"null","endLoc":762,"id":3706,"name":"inifile","nodeType":"Attribute","startLoc":762,"text":"self.inifile"},{"attributeType":"null","col":8,"comment":"null","endLoc":843,"id":3707,"name":"known_args_namespace","nodeType":"Attribute","startLoc":843,"text":"self.known_args_namespace"},{"id":3708,"name":"release-2.1.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"py.test 2.1.1: assertion fixes and improved junitxml output\n===========================================================================\n\npytest-2.1.1 is a backward compatible maintenance release of the\npopular py.test testing tool. See extensive docs with examples here:\n\n http://pytest.org/\n\nMost bug fixes address remaining issues with the perfected assertions\nintroduced with 2.1.0 - many thanks to the bug reporters and to Benjamin\nPeterson for helping to fix them. Also, junitxml output now produces\nsystem-out/err tags which lead to better displays of tracebacks with Jenkins.\n\nAlso a quick note to package maintainers and others interested: there now\nis a \"pytest\" man page which can be generated with \"make man\" in doc/.\n\nIf you want to install or upgrade pytest, just type one of::\n\n pip install -U pytest # or\n easy_install -U pytest\n\nbest,\nholger krekel / http://merlinux.eu\n\nChanges between 2.1.0 and 2.1.1\n----------------------------------------------\n\n- fix issue64 / pytest.set_trace now works within pytest_generate_tests hooks\n- fix issue60 / fix error conditions involving the creation of __pycache__\n- fix issue63 / assertion rewriting on inserts involving strings containing '%'\n- fix assertion rewriting on calls with a ** arg\n- don't cache rewritten modules if bytecode generation is disabled\n- fix assertion rewriting in read-only directories\n- fix issue59: provide system-out/err tags for junitxml output\n- fix issue61: assertion rewriting on boolean operations with 3 or more operands\n- you can now build a man page with \"cd doc ; make man\"\n"},{"col":4,"comment":"null","endLoc":593,"header":"def test_parametrize_skip(self, testdir)","id":3709,"name":"test_parametrize_skip","nodeType":"Function","startLoc":580,"text":"def test_parametrize_skip(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n m = pytest.mark.skip('')\n\n @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])\n def test_skip(x):\n assert x < 2\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed, 1 skipped in *\"])"},{"col":0,"comment":"Rewrite the assertions in f, run it, and get the failure message.","endLoc":68,"header":"def getmsg(f, extra_ns=None, must_pass=False)","id":3710,"name":"getmsg","nodeType":"Function","startLoc":47,"text":"def getmsg(f, extra_ns=None, must_pass=False):\n \"\"\"Rewrite the assertions in f, run it, and get the failure message.\"\"\"\n src = \"\\n\".join(_pytest._code.Code(f).source().lines)\n mod = rewrite(src)\n code = compile(mod, \"\", \"exec\")\n ns = {}\n if extra_ns is not None:\n ns.update(extra_ns)\n exec(code, ns)\n func = ns[f.__name__]\n try:\n func()\n except AssertionError:\n if must_pass:\n pytest.fail(\"shouldn't have raised\")\n s = six.text_type(sys.exc_info()[1])\n if not s.startswith(\"assert\"):\n return \"AssertionError: \" + s\n return s\n else:\n if not must_pass:\n pytest.fail(\"function didn't raise at all\")"},{"id":3711,"name":"release-3.8.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.8.1\n=======================================\n\npytest 3.8.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Ankit Goel\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Maximilian Albert\n* Ronny Pfannschmidt\n* William Jamir Silva\n* wim glenn\n\n\nHappy testing,\nThe pytest Development Team\n"},{"col":4,"comment":"null","endLoc":608,"header":"def test_parametrize_skipif_no_skip(self, testdir)","id":3712,"name":"test_parametrize_skipif_no_skip","nodeType":"Function","startLoc":595,"text":"def test_parametrize_skipif_no_skip(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n m = pytest.mark.skipif('False')\n\n @pytest.mark.parametrize('x', [0, 1, m(2)])\n def test_skipif_no_skip(x):\n assert x < 2\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 failed, 2 passed in *\"])"},{"attributeType":"null","col":8,"comment":"null","endLoc":660,"id":3713,"name":"invocation_dir","nodeType":"Attribute","startLoc":660,"text":"self.invocation_dir"},{"attributeType":"Namespace","col":8,"comment":"null","endLoc":642,"id":3714,"name":"option","nodeType":"Attribute","startLoc":642,"text":"self.option"},{"col":0,"comment":"Argparse type validator for directory arguments.\n\n :path: path of directory\n :optname: name of the option\n ","endLoc":115,"header":"def directory_arg(path, optname)","id":3715,"name":"directory_arg","nodeType":"Function","startLoc":107,"text":"def directory_arg(path, optname):\n \"\"\"Argparse type validator for directory arguments.\n\n :path: path of directory\n :optname: name of the option\n \"\"\"\n if not os.path.isdir(path):\n raise UsageError(\"{} must be a directory, given: {}\".format(optname, path))\n return path"},{"col":0,"comment":"null","endLoc":38,"header":"@pytest.yield_fixture(scope=\"module\")\ndef fix1(request, arg1, checked_order)","id":3716,"name":"fix1","nodeType":"Function","startLoc":35,"text":"@pytest.yield_fixture(scope=\"module\")\ndef fix1(request, arg1, checked_order):\n checked_order.append((request.node.name, \"fix1\", arg1))\n yield \"fix1-\" + arg1"},{"col":4,"comment":"null","endLoc":623,"header":"def test_parametrize_xfail(self, testdir)","id":3717,"name":"test_parametrize_xfail","nodeType":"Function","startLoc":610,"text":"def test_parametrize_xfail(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n m = pytest.mark.xfail('True')\n\n @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])\n def test_xfail(x):\n assert x < 2\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed, 1 xfailed in *\"])"},{"col":4,"comment":"null","endLoc":638,"header":"def test_parametrize_passed(self, testdir)","id":3718,"name":"test_parametrize_passed","nodeType":"Function","startLoc":625,"text":"def test_parametrize_passed(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n m = pytest.mark.xfail('True')\n\n @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])\n def test_xfail(x):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed, 1 xpassed in *\"])"},{"col":0,"comment":"\n Obtain a new instance of the\n :py:class:`_pytest.config.PytestPluginManager`, with default plugins\n already loaded.\n\n This function can be used by integration with other tools, like hooking\n into pytest to run tests into an IDE.\n ","endLoc":180,"header":"def get_plugin_manager()","id":3719,"name":"get_plugin_manager","nodeType":"Function","startLoc":171,"text":"def get_plugin_manager():\n \"\"\"\n Obtain a new instance of the\n :py:class:`_pytest.config.PytestPluginManager`, with default plugins\n already loaded.\n\n This function can be used by integration with other tools, like hooking\n into pytest to run tests into an IDE.\n \"\"\"\n return get_config().pluginmanager"},{"col":0,"comment":"null","endLoc":1070,"header":"def setns(obj, dic)","id":3720,"name":"setns","nodeType":"Function","startLoc":1051,"text":"def setns(obj, dic):\n import pytest\n\n for name, value in dic.items():\n if isinstance(value, dict):\n mod = getattr(obj, name, None)\n if mod is None:\n modname = \"pytest.%s\" % name\n mod = types.ModuleType(modname)\n sys.modules[modname] = mod\n mod.__all__ = []\n setattr(obj, name, mod)\n obj.__all__.append(name)\n setns(mod, value)\n else:\n setattr(obj, name, value)\n obj.__all__.append(name)\n # if obj != pytest:\n # pytest.__all__.append(name)\n setattr(pytest, name, value)"},{"col":0,"comment":"null","endLoc":44,"header":"@pytest.yield_fixture(scope=\"function\")\ndef fix2(request, fix1, arg2, checked_order)","id":3721,"name":"fix2","nodeType":"Function","startLoc":41,"text":"@pytest.yield_fixture(scope=\"function\")\ndef fix2(request, fix1, arg2, checked_order):\n checked_order.append((request.node.name, \"fix2\", arg2))\n yield \"fix2-\" + arg2 + fix1"},{"col":0,"comment":"null","endLoc":48,"header":"def test_one(fix2)","id":3722,"name":"test_one","nodeType":"Function","startLoc":47,"text":"def test_one(fix2):\n pass"},{"col":0,"comment":"null","endLoc":52,"header":"def test_two(fix2)","id":3723,"name":"test_two","nodeType":"Function","startLoc":51,"text":"def test_two(fix2):\n pass"},{"attributeType":"str","col":4,"comment":"null","endLoc":200,"id":3724,"name":"UNICODE_TYPES","nodeType":"Attribute","startLoc":200,"text":"UNICODE_TYPES"},{"id":3725,"name":"release-2.3.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.3.1: fix regression with factory functions\n===========================================================================\n\npytest-2.3.1 is a quick follow-up release:\n\n- fix issue202 - regression with fixture functions/funcarg factories:\n using \"self\" is now safe again and works as in 2.2.4. Thanks\n to Eduard Schettino for the quick bug report.\n\n- disable pexpect pytest self tests on Freebsd - thanks Koob for the\n quick reporting\n\n- fix/improve interactive docs with --markers\n\nSee\n\n http://pytest.org/\n\nfor general information. To install or upgrade pytest:\n\n pip install -U pytest # or\n easy_install -U pytest\n\nbest,\nholger krekel\n\n\nChanges between 2.3.0 and 2.3.1\n-----------------------------------\n\n- fix issue202 - fix regression: using \"self\" from fixture functions now\n works as expected (it's the same \"self\" instance that a test method\n which uses the fixture sees)\n\n- skip pexpect using tests (test_pdb.py mostly) on freebsd* systems\n due to pexpect not supporting it properly (hanging)\n\n- link to web pages from --markers output which provides help for\n pytest.mark.* usage.\n"},{"fileName":"test_compat.py","filePath":"testing","id":3726,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nfrom functools import wraps\n\nimport six\n\nimport pytest\nfrom _pytest.compat import _PytestWrapper\nfrom _pytest.compat import get_real_func\nfrom _pytest.compat import is_generator\nfrom _pytest.compat import safe_getattr\nfrom _pytest.compat import safe_isclass\nfrom _pytest.outcomes import OutcomeException\n\n\ndef test_is_generator():\n def zap():\n yield # pragma: no cover\n\n def foo():\n pass # pragma: no cover\n\n assert is_generator(zap)\n assert not is_generator(foo)\n\n\ndef test_real_func_loop_limit():\n class Evil(object):\n def __init__(self):\n self.left = 1000\n\n def __repr__(self):\n return \"\".format(left=self.left)\n\n def __getattr__(self, attr):\n if not self.left:\n raise RuntimeError(\"it's over\") # pragma: no cover\n self.left -= 1\n return self\n\n evil = Evil()\n\n with pytest.raises(\n ValueError,\n match=(\n \"could not find real function of \\n\"\n \"stopped at \"\n ),\n ):\n get_real_func(evil)\n\n\ndef test_get_real_func():\n \"\"\"Check that get_real_func correctly unwraps decorators until reaching the real function\"\"\"\n\n def decorator(f):\n @wraps(f)\n def inner():\n pass # pragma: no cover\n\n if six.PY2:\n inner.__wrapped__ = f\n return inner\n\n def func():\n pass # pragma: no cover\n\n wrapped_func = decorator(decorator(func))\n assert get_real_func(wrapped_func) is func\n\n wrapped_func2 = decorator(decorator(wrapped_func))\n assert get_real_func(wrapped_func2) is func\n\n # special case for __pytest_wrapped__ attribute: used to obtain the function up until the point\n # a function was wrapped by pytest itself\n wrapped_func2.__pytest_wrapped__ = _PytestWrapper(wrapped_func)\n assert get_real_func(wrapped_func2) is wrapped_func\n\n\n@pytest.mark.skipif(\n sys.version_info < (3, 4), reason=\"asyncio available in Python 3.4+\"\n)\ndef test_is_generator_asyncio(testdir):\n testdir.makepyfile(\n \"\"\"\n from _pytest.compat import is_generator\n import asyncio\n @asyncio.coroutine\n def baz():\n yield from [1,2,3]\n\n def test_is_generator_asyncio():\n assert not is_generator(baz)\n \"\"\"\n )\n # avoid importing asyncio into pytest's own process,\n # which in turn imports logging (#8)\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\n@pytest.mark.skipif(\n sys.version_info < (3, 5), reason=\"async syntax available in Python 3.5+\"\n)\ndef test_is_generator_async_syntax(testdir):\n testdir.makepyfile(\n \"\"\"\n from _pytest.compat import is_generator\n def test_is_generator_py35():\n async def foo():\n await foo()\n\n async def bar():\n pass\n\n assert not is_generator(foo)\n assert not is_generator(bar)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\nclass ErrorsHelper(object):\n @property\n def raise_exception(self):\n raise Exception(\"exception should be catched\")\n\n @property\n def raise_fail(self):\n pytest.fail(\"fail should be catched\")\n\n\ndef test_helper_failures():\n helper = ErrorsHelper()\n with pytest.raises(Exception):\n helper.raise_exception\n with pytest.raises(OutcomeException):\n helper.raise_fail\n\n\ndef test_safe_getattr():\n helper = ErrorsHelper()\n assert safe_getattr(helper, \"raise_exception\", \"default\") == \"default\"\n assert safe_getattr(helper, \"raise_fail\", \"default\") == \"default\"\n\n\ndef test_safe_isclass():\n assert safe_isclass(type) is True\n\n class CrappyClass(Exception):\n @property\n def __class__(self):\n assert False, \"Should be ignored\"\n\n assert safe_isclass(CrappyClass()) is False\n"},{"attributeType":"str","col":4,"comment":"null","endLoc":245,"id":3727,"name":"UNICODE_TYPES","nodeType":"Attribute","startLoc":245,"text":"UNICODE_TYPES"},{"col":33,"endLoc":498,"id":3728,"nodeType":"Lambda","startLoc":496,"text":"lambda: catching_logs(\n log_cli_handler, formatter=log_cli_formatter, level=log_cli_level\n )"},{"col":4,"comment":"Public method, which can set filename parameter for\n Logging.FileHandler(). Also creates parent directory if\n it does not exist.\n\n .. warning::\n Please considered as an experimental API.\n ","endLoc":519,"header":"def set_log_path(self, fname)","id":3729,"name":"set_log_path","nodeType":"Function","startLoc":500,"text":"def set_log_path(self, fname):\n \"\"\"Public method, which can set filename parameter for\n Logging.FileHandler(). Also creates parent directory if\n it does not exist.\n\n .. warning::\n Please considered as an experimental API.\n \"\"\"\n fname = Path(fname)\n\n if not fname.is_absolute():\n fname = Path(self._config.rootdir, fname)\n\n if not fname.parent.exists():\n fname.parent.mkdir(exist_ok=True, parents=True)\n\n self.log_file_handler = logging.FileHandler(\n str(fname), mode=\"w\", encoding=\"UTF-8\"\n )\n self.log_file_handler.setFormatter(self.log_file_formatter)"},{"attributeType":"(str, str, str, str, str, str, str, str, str)","col":0,"comment":"null","endLoc":390,"id":3730,"name":"COLLECT_FAKEMODULE_ATTRIBUTES","nodeType":"Attribute","startLoc":390,"text":"COLLECT_FAKEMODULE_ATTRIBUTES"},{"attributeType":"bytes","col":0,"comment":"null","endLoc":6,"id":3731,"name":"TEST_CONTENT","nodeType":"Attribute","startLoc":6,"text":"TEST_CONTENT"},{"className":"ErrorsHelper","col":0,"comment":"null","endLoc":135,"id":3732,"nodeType":"Class","startLoc":128,"text":"class ErrorsHelper(object):\n @property\n def raise_exception(self):\n raise Exception(\"exception should be catched\")\n\n @property\n def raise_fail(self):\n pytest.fail(\"fail should be catched\")"},{"col":4,"comment":"null","endLoc":653,"header":"def test_parametrize_xfail_passed(self, testdir)","id":3733,"name":"test_parametrize_xfail_passed","nodeType":"Function","startLoc":640,"text":"def test_parametrize_xfail_passed(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n m = pytest.mark.xfail('False')\n\n @pytest.mark.parametrize('x', [0, 1, m(2)])\n def test_passed(x):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 3 passed in *\"])"},{"col":4,"comment":"null","endLoc":131,"header":"@property\n def raise_exception(self)","id":3734,"name":"raise_exception","nodeType":"Function","startLoc":129,"text":"@property\n def raise_exception(self):\n raise Exception(\"exception should be catched\")"},{"fileName":"test_stepwise.py","filePath":"testing","id":3735,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport sys\n\nimport pytest\n\n\n@pytest.fixture\ndef stepwise_testdir(testdir):\n # Rather than having to modify our testfile between tests, we introduce\n # a flag for wether or not the second test should fail.\n testdir.makeconftest(\n \"\"\"\ndef pytest_addoption(parser):\n group = parser.getgroup('general')\n group.addoption('--fail', action='store_true', dest='fail')\n group.addoption('--fail-last', action='store_true', dest='fail_last')\n\"\"\"\n )\n\n # Create a simple test suite.\n testdir.makepyfile(\n test_a=\"\"\"\ndef test_success_before_fail():\n assert 1\n\ndef test_fail_on_flag(request):\n assert not request.config.getvalue('fail')\n\ndef test_success_after_fail():\n assert 1\n\ndef test_fail_last_on_flag(request):\n assert not request.config.getvalue('fail_last')\n\ndef test_success_after_last_fail():\n assert 1\n\"\"\"\n )\n\n testdir.makepyfile(\n test_b=\"\"\"\ndef test_success():\n assert 1\n\"\"\"\n )\n\n # customize cache directory so we don't use the tox's cache directory, which makes tests in this module flaky\n testdir.makeini(\n \"\"\"\n [pytest]\n cache_dir = .cache\n \"\"\"\n )\n\n return testdir\n\n\n@pytest.fixture\ndef error_testdir(testdir):\n testdir.makepyfile(\n test_a=\"\"\"\ndef test_error(nonexisting_fixture):\n assert 1\n\ndef test_success_after_fail():\n assert 1\n\"\"\"\n )\n\n return testdir\n\n\n@pytest.fixture\ndef broken_testdir(testdir):\n testdir.makepyfile(\n working_testfile=\"def test_proper(): assert 1\", broken_testfile=\"foobar\"\n )\n return testdir\n\n\ndef test_run_without_stepwise(stepwise_testdir):\n result = stepwise_testdir.runpytest(\"-v\", \"--strict-markers\", \"--fail\")\n\n result.stdout.fnmatch_lines([\"*test_success_before_fail PASSED*\"])\n result.stdout.fnmatch_lines([\"*test_fail_on_flag FAILED*\"])\n result.stdout.fnmatch_lines([\"*test_success_after_fail PASSED*\"])\n\n\ndef test_fail_and_continue_with_stepwise(stepwise_testdir):\n # Run the tests with a failing second test.\n result = stepwise_testdir.runpytest(\n \"-v\", \"--strict-markers\", \"--stepwise\", \"--fail\"\n )\n assert not result.stderr.str()\n\n stdout = result.stdout.str()\n # Make sure we stop after first failing test.\n assert \"test_success_before_fail PASSED\" in stdout\n assert \"test_fail_on_flag FAILED\" in stdout\n assert \"test_success_after_fail\" not in stdout\n\n # \"Fix\" the test that failed in the last run and run it again.\n result = stepwise_testdir.runpytest(\"-v\", \"--strict-markers\", \"--stepwise\")\n assert not result.stderr.str()\n\n stdout = result.stdout.str()\n # Make sure the latest failing test runs and then continues.\n assert \"test_success_before_fail\" not in stdout\n assert \"test_fail_on_flag PASSED\" in stdout\n assert \"test_success_after_fail PASSED\" in stdout\n\n\ndef test_run_with_skip_option(stepwise_testdir):\n result = stepwise_testdir.runpytest(\n \"-v\",\n \"--strict-markers\",\n \"--stepwise\",\n \"--stepwise-skip\",\n \"--fail\",\n \"--fail-last\",\n )\n assert not result.stderr.str()\n\n stdout = result.stdout.str()\n # Make sure first fail is ignore and second fail stops the test run.\n assert \"test_fail_on_flag FAILED\" in stdout\n assert \"test_success_after_fail PASSED\" in stdout\n assert \"test_fail_last_on_flag FAILED\" in stdout\n assert \"test_success_after_last_fail\" not in stdout\n\n\ndef test_fail_on_errors(error_testdir):\n result = error_testdir.runpytest(\"-v\", \"--strict-markers\", \"--stepwise\")\n\n assert not result.stderr.str()\n stdout = result.stdout.str()\n\n assert \"test_error ERROR\" in stdout\n assert \"test_success_after_fail\" not in stdout\n\n\ndef test_change_testfile(stepwise_testdir):\n result = stepwise_testdir.runpytest(\n \"-v\", \"--strict-markers\", \"--stepwise\", \"--fail\", \"test_a.py\"\n )\n assert not result.stderr.str()\n\n stdout = result.stdout.str()\n assert \"test_fail_on_flag FAILED\" in stdout\n\n # Make sure the second test run starts from the beginning, since the\n # test to continue from does not exist in testfile_b.\n result = stepwise_testdir.runpytest(\n \"-v\", \"--strict-markers\", \"--stepwise\", \"test_b.py\"\n )\n assert not result.stderr.str()\n\n stdout = result.stdout.str()\n assert \"test_success PASSED\" in stdout\n\n\n@pytest.mark.parametrize(\"broken_first\", [True, False])\ndef test_stop_on_collection_errors(broken_testdir, broken_first):\n \"\"\"Stop during collection errors. Broken test first or broken test last\n actually surfaced a bug (#5444), so we test both situations.\"\"\"\n files = [\"working_testfile.py\", \"broken_testfile.py\"]\n if broken_first:\n files.reverse()\n result = broken_testdir.runpytest(\"-v\", \"--strict-markers\", \"--stepwise\", *files)\n result.stdout.fnmatch_lines(\"*errors during collection*\")\n\n\ndef test_xfail_handling(testdir):\n \"\"\"Ensure normal xfail is ignored, and strict xfail interrupts the session in sw mode\n\n (#5547)\n \"\"\"\n contents = \"\"\"\n import pytest\n def test_a(): pass\n\n @pytest.mark.xfail(strict={strict})\n def test_b(): assert {assert_value}\n\n def test_c(): pass\n def test_d(): pass\n \"\"\"\n testdir.makepyfile(contents.format(assert_value=\"0\", strict=\"False\"))\n result = testdir.runpytest(\"--sw\", \"-v\")\n result.stdout.fnmatch_lines(\n [\n \"*::test_a PASSED *\",\n \"*::test_b XFAIL *\",\n \"*::test_c PASSED *\",\n \"*::test_d PASSED *\",\n \"* 3 passed, 1 xfailed in *\",\n ]\n )\n\n testdir.makepyfile(contents.format(assert_value=\"1\", strict=\"True\"))\n result = testdir.runpytest(\"--sw\", \"-v\")\n result.stdout.fnmatch_lines(\n [\n \"*::test_a PASSED *\",\n \"*::test_b FAILED *\",\n \"* Interrupted*\",\n \"* 1 failed, 1 passed in *\",\n ]\n )\n\n # because we are writing to the same file, mtime might not be affected enough to\n # invalidate the cache, making this next run flaky\n if not sys.dont_write_bytecode:\n testdir.tmpdir.join(\"__pycache__\").remove()\n testdir.makepyfile(contents.format(assert_value=\"0\", strict=\"True\"))\n result = testdir.runpytest(\"--sw\", \"-v\")\n result.stdout.fnmatch_lines(\n [\n \"*::test_b XFAIL *\",\n \"*::test_c PASSED *\",\n \"*::test_d PASSED *\",\n \"* 2 passed, 1 deselected, 1 xfailed in *\",\n ]\n )\n"},{"col":0,"comment":"null","endLoc":55,"header":"@pytest.fixture\ndef stepwise_testdir(testdir)","id":3736,"name":"stepwise_testdir","nodeType":"Function","startLoc":7,"text":"@pytest.fixture\ndef stepwise_testdir(testdir):\n # Rather than having to modify our testfile between tests, we introduce\n # a flag for wether or not the second test should fail.\n testdir.makeconftest(\n \"\"\"\ndef pytest_addoption(parser):\n group = parser.getgroup('general')\n group.addoption('--fail', action='store_true', dest='fail')\n group.addoption('--fail-last', action='store_true', dest='fail_last')\n\"\"\"\n )\n\n # Create a simple test suite.\n testdir.makepyfile(\n test_a=\"\"\"\ndef test_success_before_fail():\n assert 1\n\ndef test_fail_on_flag(request):\n assert not request.config.getvalue('fail')\n\ndef test_success_after_fail():\n assert 1\n\ndef test_fail_last_on_flag(request):\n assert not request.config.getvalue('fail_last')\n\ndef test_success_after_last_fail():\n assert 1\n\"\"\"\n )\n\n testdir.makepyfile(\n test_b=\"\"\"\ndef test_success():\n assert 1\n\"\"\"\n )\n\n # customize cache directory so we don't use the tox's cache directory, which makes tests in this module flaky\n testdir.makeini(\n \"\"\"\n [pytest]\n cache_dir = .cache\n \"\"\"\n )\n\n return testdir"},{"col":4,"comment":"null","endLoc":664,"header":"def test_function_original_name(self, testdir)","id":3737,"name":"test_function_original_name","nodeType":"Function","startLoc":655,"text":"def test_function_original_name(self, testdir):\n items = testdir.getitems(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('arg', [1,2])\n def test_func(arg):\n pass\n \"\"\"\n )\n assert [x.originalname for x in items] == [\"test_func\", \"test_func\"]"},{"col":0,"comment":"","endLoc":4,"header":"compat.py#","id":3738,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"\npython version compatibility code\n\"\"\"\n\ntry:\n import enum\nexcept ImportError: # pragma: no cover\n # Only available in Python 3.4+ or as a backport\n enum = None\n\n_PY3 = sys.version_info > (3, 0)\n\n_PY2 = not _PY3\n\nif _PY3:\n from inspect import signature, Parameter as Parameter\nelse:\n from funcsigs import signature, Parameter as Parameter\n\nNOTSET = object()\n\nPY35 = sys.version_info[:2] >= (3, 5)\n\nPY36 = sys.version_info[:2] >= (3, 6)\n\nMODULE_NOT_FOUND_ERROR = \"ModuleNotFoundError\" if PY36 else \"ImportError\"\n\nif _PY3:\n from collections.abc import MutableMapping as MappingMixin\n from collections.abc import Iterable, Mapping, Sequence, Sized\nelse:\n # those raise DeprecationWarnings in Python >=3.7\n from collections import MutableMapping as MappingMixin # noqa\n from collections import Iterable, Mapping, Sequence, Sized # noqa\n\nif sys.version_info >= (3, 4):\n from importlib.util import spec_from_file_location\nelse:\n\n def spec_from_file_location(*_, **__):\n return None\n\nisfunction = inspect.isfunction\n\nisclass = inspect.isclass\n\nexc_clear = getattr(sys, \"exc_clear\", lambda: None)\n\nREGEX_TYPE = type(re.compile(\"\"))\n\n_non_printable_ascii_translate_table = {\n i: u\"\\\\x{:02x}\".format(i) for i in range(128) if i not in range(32, 127)\n}\n\n_non_printable_ascii_translate_table.update(\n {ord(\"\\t\"): u\"\\\\t\", ord(\"\\r\"): u\"\\\\r\", ord(\"\\n\"): u\"\\\\n\"}\n)\n\nif _PY3:\n STRING_TYPES = bytes, str\n UNICODE_TYPES = six.text_type\n\n if PY35:\n\n def _bytes_to_ascii(val):\n return val.decode(\"ascii\", \"backslashreplace\")\n\n else:\n\n def _bytes_to_ascii(val):\n if val:\n # source: http://goo.gl/bGsnwC\n encoded_bytes, _ = codecs.escape_encode(val)\n return encoded_bytes.decode(\"ascii\")\n else:\n # empty bytes crashes codecs.escape_encode (#1087)\n return \"\"\n\n def ascii_escaped(val):\n \"\"\"If val is pure ascii, returns it as a str(). Otherwise, escapes\n bytes objects into a sequence of escaped bytes:\n\n b'\\xc3\\xb4\\xc5\\xd6' -> u'\\\\xc3\\\\xb4\\\\xc5\\\\xd6'\n\n and escapes unicode objects into a sequence of escaped unicode\n ids, e.g.:\n\n '4\\\\nV\\\\U00043efa\\\\x0eMXWB\\\\x1e\\\\u3028\\\\u15fd\\\\xcd\\\\U0007d944'\n\n note:\n the obvious \"v.decode('unicode-escape')\" will return\n valid utf-8 unicode if it finds them in bytes, but we\n want to return escaped bytes for any byte, even if they match\n a utf-8 string.\n\n \"\"\"\n if isinstance(val, bytes):\n ret = _bytes_to_ascii(val)\n else:\n ret = val.encode(\"unicode_escape\").decode(\"ascii\")\n return _translate_non_printable(ret)\n\n\nelse:\n STRING_TYPES = six.string_types\n UNICODE_TYPES = six.text_type\n\n def ascii_escaped(val):\n \"\"\"In py2 bytes and str are the same type, so return if it's a bytes\n object, return it unchanged if it is a full ascii string,\n otherwise escape it into its binary form.\n\n If it's a unicode string, change the unicode characters into\n unicode escapes.\n\n \"\"\"\n if isinstance(val, bytes):\n try:\n ret = val.decode(\"ascii\")\n except UnicodeDecodeError:\n ret = val.encode(\"string-escape\").decode(\"ascii\")\n else:\n ret = val.encode(\"unicode-escape\").decode(\"ascii\")\n return _translate_non_printable(ret)\n\nif _PY3:\n\n def safe_str(v):\n \"\"\"returns v as string\"\"\"\n return str(v)\n\n\nelse:\n\n def safe_str(v):\n \"\"\"returns v as string, converting to utf-8 if necessary\"\"\"\n try:\n return str(v)\n except UnicodeError:\n if not isinstance(v, text_type):\n v = text_type(v)\n errors = \"replace\"\n return v.encode(\"utf-8\", errors)\n\nCOLLECT_FAKEMODULE_ATTRIBUTES = (\n \"Collector\",\n \"Module\",\n \"Function\",\n \"Instance\",\n \"Session\",\n \"Item\",\n \"Class\",\n \"File\",\n \"_fillfuncargs\",\n)\n\nif _PY2:\n # Without this the test_dupfile_on_textio will fail, otherwise CaptureIO could directly inherit from StringIO.\n from py.io import TextIO\n\n class CaptureIO(TextIO):\n @property\n def encoding(self):\n return getattr(self, \"_encoding\", \"UTF-8\")\n\n\nelse:\n import io\n\n class CaptureIO(io.TextIOWrapper):\n def __init__(self):\n super(CaptureIO, self).__init__(\n io.BytesIO(), encoding=\"UTF-8\", newline=\"\", write_through=True\n )\n\n def getvalue(self):\n return self.buffer.getvalue().decode(\"UTF-8\")\n\nif six.PY2:\n\n def lru_cache(*_, **__):\n def dec(fn):\n return fn\n\n return dec\n\n\nelse:\n from functools import lru_cache # noqa: F401"},{"className":"TestSorting","col":0,"comment":"null","endLoc":718,"id":3739,"nodeType":"Class","startLoc":667,"text":"class TestSorting(object):\n def test_check_equality(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n def test_pass(): pass\n def test_fail(): assert 0\n \"\"\"\n )\n fn1 = testdir.collect_by_name(modcol, \"test_pass\")\n assert isinstance(fn1, pytest.Function)\n fn2 = testdir.collect_by_name(modcol, \"test_pass\")\n assert isinstance(fn2, pytest.Function)\n\n assert fn1 == fn2\n assert fn1 != modcol\n if sys.version_info < (3, 0):\n assert cmp(fn1, fn2) == 0 # NOQA\n assert hash(fn1) == hash(fn2)\n\n fn3 = testdir.collect_by_name(modcol, \"test_fail\")\n assert isinstance(fn3, pytest.Function)\n assert not (fn1 == fn3)\n assert fn1 != fn3\n\n for fn in fn1, fn2, fn3:\n assert fn != 3\n assert fn != modcol\n assert fn != [1, 2, 3]\n assert [1, 2, 3] != fn\n assert modcol != fn\n\n def test_allow_sane_sorting_for_decorators(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n def dec(f):\n g = lambda: f(2)\n g.place_as = f\n return g\n\n\n def test_b(y):\n pass\n test_b = dec(test_b)\n\n def test_a(y):\n pass\n test_a = dec(test_a)\n \"\"\"\n )\n colitems = modcol.collect()\n assert len(colitems) == 2\n assert [item.name for item in colitems] == [\"test_b\", \"test_a\"]"},{"col":4,"comment":"null","endLoc":135,"header":"@property\n def raise_fail(self)","id":3740,"name":"raise_fail","nodeType":"Function","startLoc":133,"text":"@property\n def raise_fail(self):\n pytest.fail(\"fail should be catched\")"},{"col":4,"comment":"null","endLoc":696,"header":"def test_check_equality(self, testdir)","id":3741,"name":"test_check_equality","nodeType":"Function","startLoc":668,"text":"def test_check_equality(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n def test_pass(): pass\n def test_fail(): assert 0\n \"\"\"\n )\n fn1 = testdir.collect_by_name(modcol, \"test_pass\")\n assert isinstance(fn1, pytest.Function)\n fn2 = testdir.collect_by_name(modcol, \"test_pass\")\n assert isinstance(fn2, pytest.Function)\n\n assert fn1 == fn2\n assert fn1 != modcol\n if sys.version_info < (3, 0):\n assert cmp(fn1, fn2) == 0 # NOQA\n assert hash(fn1) == hash(fn2)\n\n fn3 = testdir.collect_by_name(modcol, \"test_fail\")\n assert isinstance(fn3, pytest.Function)\n assert not (fn1 == fn3)\n assert fn1 != fn3\n\n for fn in fn1, fn2, fn3:\n assert fn != 3\n assert fn != modcol\n assert fn != [1, 2, 3]\n assert [1, 2, 3] != fn\n assert modcol != fn"},{"col":0,"comment":"null","endLoc":28,"header":"def test_is_generator()","id":3742,"name":"test_is_generator","nodeType":"Function","startLoc":20,"text":"def test_is_generator():\n def zap():\n yield # pragma: no cover\n\n def foo():\n pass # pragma: no cover\n\n assert is_generator(zap)\n assert not is_generator(foo)"},{"col":0,"comment":"null","endLoc":54,"header":"def test_real_func_loop_limit()","id":3743,"name":"test_real_func_loop_limit","nodeType":"Function","startLoc":31,"text":"def test_real_func_loop_limit():\n class Evil(object):\n def __init__(self):\n self.left = 1000\n\n def __repr__(self):\n return \"\".format(left=self.left)\n\n def __getattr__(self, attr):\n if not self.left:\n raise RuntimeError(\"it's over\") # pragma: no cover\n self.left -= 1\n return self\n\n evil = Evil()\n\n with pytest.raises(\n ValueError,\n match=(\n \"could not find real function of \\n\"\n \"stopped at \"\n ),\n ):\n get_real_func(evil)"},{"col":38,"endLoc":71,"id":3744,"nodeType":"Lambda","startLoc":71,"text":"lambda: None"},{"col":0,"comment":"null","endLoc":70,"header":"@pytest.fixture\ndef error_testdir(testdir)","id":3745,"name":"error_testdir","nodeType":"Function","startLoc":58,"text":"@pytest.fixture\ndef error_testdir(testdir):\n testdir.makepyfile(\n test_a=\"\"\"\ndef test_error(nonexisting_fixture):\n assert 1\n\ndef test_success_after_fail():\n assert 1\n\"\"\"\n )\n\n return testdir"},{"col":0,"comment":"null","endLoc":78,"header":"@pytest.fixture\ndef broken_testdir(testdir)","id":3746,"name":"broken_testdir","nodeType":"Function","startLoc":73,"text":"@pytest.fixture\ndef broken_testdir(testdir):\n testdir.makepyfile(\n working_testfile=\"def test_proper(): assert 1\", broken_testfile=\"foobar\"\n )\n return testdir"},{"col":0,"comment":"null","endLoc":86,"header":"def test_run_without_stepwise(stepwise_testdir)","id":3747,"name":"test_run_without_stepwise","nodeType":"Function","startLoc":81,"text":"def test_run_without_stepwise(stepwise_testdir):\n result = stepwise_testdir.runpytest(\"-v\", \"--strict-markers\", \"--fail\")\n\n result.stdout.fnmatch_lines([\"*test_success_before_fail PASSED*\"])\n result.stdout.fnmatch_lines([\"*test_fail_on_flag FAILED*\"])\n result.stdout.fnmatch_lines([\"*test_success_after_fail PASSED*\"])"},{"col":0,"comment":"null","endLoc":110,"header":"def test_fail_and_continue_with_stepwise(stepwise_testdir)","id":3748,"name":"test_fail_and_continue_with_stepwise","nodeType":"Function","startLoc":89,"text":"def test_fail_and_continue_with_stepwise(stepwise_testdir):\n # Run the tests with a failing second test.\n result = stepwise_testdir.runpytest(\n \"-v\", \"--strict-markers\", \"--stepwise\", \"--fail\"\n )\n assert not result.stderr.str()\n\n stdout = result.stdout.str()\n # Make sure we stop after first failing test.\n assert \"test_success_before_fail PASSED\" in stdout\n assert \"test_fail_on_flag FAILED\" in stdout\n assert \"test_success_after_fail\" not in stdout\n\n # \"Fix\" the test that failed in the last run and run it again.\n result = stepwise_testdir.runpytest(\"-v\", \"--strict-markers\", \"--stepwise\")\n assert not result.stderr.str()\n\n stdout = result.stdout.str()\n # Make sure the latest failing test runs and then continues.\n assert \"test_success_before_fail\" not in stdout\n assert \"test_fail_on_flag PASSED\" in stdout\n assert \"test_success_after_fail PASSED\" in stdout"},{"attributeType":"ArgumentParser","col":0,"comment":"null","endLoc":8,"id":3749,"name":"parser","nodeType":"Attribute","startLoc":8,"text":"parser"},{"attributeType":"(str, str, str, str, str)","col":0,"comment":"null","endLoc":119,"id":3750,"name":"essential_plugins","nodeType":"Attribute","startLoc":119,"text":"essential_plugins"},{"attributeType":"(str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str)","col":0,"comment":"null","endLoc":127,"id":3751,"name":"default_plugins","nodeType":"Attribute","startLoc":127,"text":"default_plugins"},{"col":0,"comment":"null","endLoc":129,"header":"def test_run_with_skip_option(stepwise_testdir)","id":3752,"name":"test_run_with_skip_option","nodeType":"Function","startLoc":113,"text":"def test_run_with_skip_option(stepwise_testdir):\n result = stepwise_testdir.runpytest(\n \"-v\",\n \"--strict-markers\",\n \"--stepwise\",\n \"--stepwise-skip\",\n \"--fail\",\n \"--fail-last\",\n )\n assert not result.stderr.str()\n\n stdout = result.stdout.str()\n # Make sure first fail is ignore and second fail stops the test run.\n assert \"test_fail_on_flag FAILED\" in stdout\n assert \"test_success_after_fail PASSED\" in stdout\n assert \"test_fail_last_on_flag FAILED\" in stdout\n assert \"test_success_after_last_fail\" not in stdout"},{"col":4,"comment":"null","endLoc":67,"header":"def load_and_is_true(self, expression)","id":3753,"name":"load_and_is_true","nodeType":"Function","startLoc":49,"text":"def load_and_is_true(self, expression):\n loadfile = self.picklefile.dirpath(\"load.py\")\n loadfile.write(\n textwrap.dedent(\n r\"\"\"\n import pickle\n f = open({!r}, 'rb')\n obj = pickle.load(f)\n f.close()\n res = eval({!r})\n if not res:\n raise SystemExit(1)\n \"\"\".format(\n str(self.picklefile), expression\n )\n )\n )\n print(loadfile)\n subprocess.check_call((self.pythonpath, str(loadfile)))"},{"col":0,"comment":"null","endLoc":139,"header":"def test_fail_on_errors(error_testdir)","id":3755,"name":"test_fail_on_errors","nodeType":"Function","startLoc":132,"text":"def test_fail_on_errors(error_testdir):\n result = error_testdir.runpytest(\"-v\", \"--strict-markers\", \"--stepwise\")\n\n assert not result.stderr.str()\n stdout = result.stdout.str()\n\n assert \"test_error ERROR\" in stdout\n assert \"test_success_after_fail\" not in stdout"},{"col":0,"comment":"Check that get_real_func correctly unwraps decorators until reaching the real function","endLoc":81,"header":"def test_get_real_func()","id":3756,"name":"test_get_real_func","nodeType":"Function","startLoc":57,"text":"def test_get_real_func():\n \"\"\"Check that get_real_func correctly unwraps decorators until reaching the real function\"\"\"\n\n def decorator(f):\n @wraps(f)\n def inner():\n pass # pragma: no cover\n\n if six.PY2:\n inner.__wrapped__ = f\n return inner\n\n def func():\n pass # pragma: no cover\n\n wrapped_func = decorator(decorator(func))\n assert get_real_func(wrapped_func) is func\n\n wrapped_func2 = decorator(decorator(wrapped_func))\n assert get_real_func(wrapped_func2) is func\n\n # special case for __pytest_wrapped__ attribute: used to obtain the function up until the point\n # a function was wrapped by pytest itself\n wrapped_func2.__pytest_wrapped__ = _PytestWrapper(wrapped_func)\n assert get_real_func(wrapped_func2) is wrapped_func"},{"col":0,"comment":"null","endLoc":159,"header":"def test_change_testfile(stepwise_testdir)","id":3757,"name":"test_change_testfile","nodeType":"Function","startLoc":142,"text":"def test_change_testfile(stepwise_testdir):\n result = stepwise_testdir.runpytest(\n \"-v\", \"--strict-markers\", \"--stepwise\", \"--fail\", \"test_a.py\"\n )\n assert not result.stderr.str()\n\n stdout = result.stdout.str()\n assert \"test_fail_on_flag FAILED\" in stdout\n\n # Make sure the second test run starts from the beginning, since the\n # test to continue from does not exist in testfile_b.\n result = stepwise_testdir.runpytest(\n \"-v\", \"--strict-markers\", \"--stepwise\", \"test_b.py\"\n )\n assert not result.stderr.str()\n\n stdout = result.stdout.str()\n assert \"test_success PASSED\" in stdout"},{"col":0,"comment":"Stop during collection errors. Broken test first or broken test last\n actually surfaced a bug (#5444), so we test both situations.","endLoc":170,"header":"@pytest.mark.parametrize(\"broken_first\", [True, False])\ndef test_stop_on_collection_errors(broken_testdir, broken_first)","id":3759,"name":"test_stop_on_collection_errors","nodeType":"Function","startLoc":162,"text":"@pytest.mark.parametrize(\"broken_first\", [True, False])\ndef test_stop_on_collection_errors(broken_testdir, broken_first):\n \"\"\"Stop during collection errors. Broken test first or broken test last\n actually surfaced a bug (#5444), so we test both situations.\"\"\"\n files = [\"working_testfile.py\", \"broken_testfile.py\"]\n if broken_first:\n files.reverse()\n result = broken_testdir.runpytest(\"-v\", \"--strict-markers\", \"--stepwise\", *files)\n result.stdout.fnmatch_lines(\"*errors during collection*\")"},{"attributeType":"str | None","col":8,"comment":"null","endLoc":28,"id":3760,"name":"pythonpath","nodeType":"Attribute","startLoc":28,"text":"self.pythonpath"},{"attributeType":"null","col":8,"comment":"null","endLoc":31,"id":3761,"name":"picklefile","nodeType":"Attribute","startLoc":31,"text":"self.picklefile"},{"col":0,"comment":"null","endLoc":18,"header":"@pytest.fixture(params=pythonlist)\ndef python1(request, tmpdir)","id":3762,"name":"python1","nodeType":"Function","startLoc":15,"text":"@pytest.fixture(params=pythonlist)\ndef python1(request, tmpdir):\n picklefile = tmpdir.join(\"data.pickle\")\n return Python(request.param, picklefile)"},{"col":4,"comment":"Test that doctests which output bytes fail in Python 3 when\n the ALLOW_BYTES option is not used. The same test should pass\n in Python 2 (#1287).\n ","endLoc":852,"header":"def test_bytes_literal(self, testdir)","id":3763,"name":"test_bytes_literal","nodeType":"Function","startLoc":839,"text":"def test_bytes_literal(self, testdir):\n \"\"\"Test that doctests which output bytes fail in Python 3 when\n the ALLOW_BYTES option is not used. The same test should pass\n in Python 2 (#1287).\n \"\"\"\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> b'foo'\n 'foo'\n \"\"\"\n )\n reprec = testdir.inline_run()\n passed = int(sys.version_info[0] == 2)\n reprec.assertoutcome(passed=passed, failed=int(not passed))"},{"attributeType":"set","col":0,"comment":"null","endLoc":153,"id":3764,"name":"builtin_plugins","nodeType":"Attribute","startLoc":153,"text":"builtin_plugins"},{"col":0,"comment":"null","endLoc":103,"header":"@pytest.mark.skipif(\n sys.version_info < (3, 4), reason=\"asyncio available in Python 3.4+\"\n)\ndef test_is_generator_asyncio(testdir)","id":3765,"name":"test_is_generator_asyncio","nodeType":"Function","startLoc":84,"text":"@pytest.mark.skipif(\n sys.version_info < (3, 4), reason=\"asyncio available in Python 3.4+\"\n)\ndef test_is_generator_asyncio(testdir):\n testdir.makepyfile(\n \"\"\"\n from _pytest.compat import is_generator\n import asyncio\n @asyncio.coroutine\n def baz():\n yield from [1,2,3]\n\n def test_is_generator_asyncio():\n assert not is_generator(baz)\n \"\"\"\n )\n # avoid importing asyncio into pytest's own process,\n # which in turn imports logging (#8)\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":0,"comment":"null","endLoc":23,"header":"@pytest.fixture(params=pythonlist)\ndef python2(request, python1)","id":3766,"name":"python2","nodeType":"Function","startLoc":21,"text":"@pytest.fixture(params=pythonlist)\ndef python2(request, python1):\n return Python(request.param, python1.picklefile)"},{"col":0,"comment":"Ensure normal xfail is ignored, and strict xfail interrupts the session in sw mode\n\n (#5547)\n ","endLoc":224,"header":"def test_xfail_handling(testdir)","id":3767,"name":"test_xfail_handling","nodeType":"Function","startLoc":173,"text":"def test_xfail_handling(testdir):\n \"\"\"Ensure normal xfail is ignored, and strict xfail interrupts the session in sw mode\n\n (#5547)\n \"\"\"\n contents = \"\"\"\n import pytest\n def test_a(): pass\n\n @pytest.mark.xfail(strict={strict})\n def test_b(): assert {assert_value}\n\n def test_c(): pass\n def test_d(): pass\n \"\"\"\n testdir.makepyfile(contents.format(assert_value=\"0\", strict=\"False\"))\n result = testdir.runpytest(\"--sw\", \"-v\")\n result.stdout.fnmatch_lines(\n [\n \"*::test_a PASSED *\",\n \"*::test_b XFAIL *\",\n \"*::test_c PASSED *\",\n \"*::test_d PASSED *\",\n \"* 3 passed, 1 xfailed in *\",\n ]\n )\n\n testdir.makepyfile(contents.format(assert_value=\"1\", strict=\"True\"))\n result = testdir.runpytest(\"--sw\", \"-v\")\n result.stdout.fnmatch_lines(\n [\n \"*::test_a PASSED *\",\n \"*::test_b FAILED *\",\n \"* Interrupted*\",\n \"* 1 failed, 1 passed in *\",\n ]\n )\n\n # because we are writing to the same file, mtime might not be affected enough to\n # invalidate the cache, making this next run flaky\n if not sys.dont_write_bytecode:\n testdir.tmpdir.join(\"__pycache__\").remove()\n testdir.makepyfile(contents.format(assert_value=\"0\", strict=\"True\"))\n result = testdir.runpytest(\"--sw\", \"-v\")\n result.stdout.fnmatch_lines(\n [\n \"*::test_b XFAIL *\",\n \"*::test_c PASSED *\",\n \"*::test_d PASSED *\",\n \"* 2 passed, 1 deselected, 1 xfailed in *\",\n ]\n )"},{"col":0,"comment":"null","endLoc":73,"header":"@pytest.mark.parametrize(\"obj\", [42, {}, {1: 3}])\ndef test_basic_objects(python1, python2, obj)","id":3768,"name":"test_basic_objects","nodeType":"Function","startLoc":70,"text":"@pytest.mark.parametrize(\"obj\", [42, {}, {1: 3}])\ndef test_basic_objects(python1, python2, obj):\n python1.dumps(obj)\n python2.load_and_is_true(\"obj == %s\" % obj)"},{"col":0,"comment":"null","endLoc":125,"header":"@pytest.mark.skipif(\n sys.version_info < (3, 5), reason=\"async syntax available in Python 3.5+\"\n)\ndef test_is_generator_async_syntax(testdir)","id":3769,"name":"test_is_generator_async_syntax","nodeType":"Function","startLoc":106,"text":"@pytest.mark.skipif(\n sys.version_info < (3, 5), reason=\"async syntax available in Python 3.5+\"\n)\ndef test_is_generator_async_syntax(testdir):\n testdir.makepyfile(\n \"\"\"\n from _pytest.compat import is_generator\n def test_is_generator_py35():\n async def foo():\n await foo()\n\n async def bar():\n pass\n\n assert not is_generator(foo)\n assert not is_generator(bar)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"attributeType":"list","col":0,"comment":"null","endLoc":12,"id":3770,"name":"pythonlist","nodeType":"Attribute","startLoc":12,"text":"pythonlist"},{"col":0,"comment":"","endLoc":5,"header":"multipython.py#","id":3771,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"\nmodule containing a parametrized tests testing cross-python\nserialization via the pickle module.\n\"\"\"\n\npythonlist = [\"python2.7\", \"python3.4\", \"python3.5\"]"},{"attributeType":"Namespace","col":4,"comment":"null","endLoc":27,"id":3772,"name":"args","nodeType":"Attribute","startLoc":27,"text":"args"},{"col":0,"comment":"null","endLoc":143,"header":"def test_helper_failures()","id":3773,"name":"test_helper_failures","nodeType":"Function","startLoc":138,"text":"def test_helper_failures():\n helper = ErrorsHelper()\n with pytest.raises(Exception):\n helper.raise_exception\n with pytest.raises(OutcomeException):\n helper.raise_fail"},{"fileName":"__init__.py","filePath":"testing/example_scripts/collect/package_init_given_as_arg/pkg","id":3774,"nodeType":"File","text":""},{"id":3775,"name":"doc/en/_themes","nodeType":"Package"},{"id":3776,"name":"README","nodeType":"TextFile","path":"doc/en/_themes","text":"Flask Sphinx Styles\n===================\n\nThis repository contains sphinx styles for Flask and Flask related\nprojects. To use this style in your Sphinx documentation, follow\nthis guide:\n\n1. put this folder as _themes into your docs folder. Alternatively\n you can also use git submodules to check out the contents there.\n2. add this to your conf.py:\n\n sys.path.append(os.path.abspath('_themes'))\n html_theme_path = ['_themes']\n html_theme = 'flask'\n\nThe following themes exist:\n\n- 'flask' - the standard flask documentation theme for large\n projects\n- 'flask_small' - small one-page theme. Intended to be used by\n very small addon libraries for flask.\n\nThe following options exist for the flask_small theme:\n\n [options]\n index_logo = '' filename of a picture in _static\n to be used as replacement for the\n h1 in the index.rst file.\n index_logo_height = 120px height of the index logo\n github_fork = '' repository name on github for the\n \"fork me\" badge\n"},{"attributeType":"Notset","col":0,"comment":"null","endLoc":621,"id":3777,"name":"notset","nodeType":"Attribute","startLoc":621,"text":"notset"},{"col":0,"comment":"","endLoc":2,"header":"__init__.py#","id":3778,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" command line options, ini-file and conftest.py processing. \"\"\"\n\nhookimpl = HookimplMarker(\"pytest\")\n\nhookspec = HookspecMarker(\"pytest\")\n\nessential_plugins = ( # fmt: off\n \"mark\",\n \"main\",\n \"runner\",\n \"fixtures\",\n \"helpconfig\", # Provides -p.\n) # fmt: on\n\ndefault_plugins = essential_plugins + (\n \"python\",\n \"terminal\",\n \"debugging\",\n \"unittest\",\n \"capture\",\n \"skipping\",\n \"tmpdir\",\n \"monkeypatch\",\n \"recwarn\",\n \"pastebin\",\n \"nose\",\n \"assertion\",\n \"junitxml\",\n \"resultlog\",\n \"doctest\",\n \"cacheprovider\",\n \"freeze_support\",\n \"setuponly\",\n \"setupplan\",\n \"stepwise\",\n \"warnings\",\n \"logging\",\n \"reports\",\n)\n\nbuiltin_plugins = set(default_plugins)\n\nbuiltin_plugins.add(\"pytester\")\n\nnotset = Notset()"},{"col":0,"comment":"null","endLoc":149,"header":"def test_safe_getattr()","id":3779,"name":"test_safe_getattr","nodeType":"Function","startLoc":146,"text":"def test_safe_getattr():\n helper = ErrorsHelper()\n assert safe_getattr(helper, \"raise_exception\", \"default\") == \"default\"\n assert safe_getattr(helper, \"raise_fail\", \"default\") == \"default\""},{"col":0,"comment":"null","endLoc":160,"header":"def test_safe_isclass()","id":3780,"name":"test_safe_isclass","nodeType":"Function","startLoc":152,"text":"def test_safe_isclass():\n assert safe_isclass(type) is True\n\n class CrappyClass(Exception):\n @property\n def __class__(self):\n assert False, \"Should be ignored\"\n\n assert safe_isclass(CrappyClass()) is False"},{"fileName":"test_runner_xunit.py","filePath":"testing","id":3781,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"\n test correct setup/teardowns at\n module, class, and instance level\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pytest\n\n\ndef test_module_and_function_setup(testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n modlevel = []\n def setup_module(module):\n assert not modlevel\n module.modlevel.append(42)\n\n def teardown_module(module):\n modlevel.pop()\n\n def setup_function(function):\n function.answer = 17\n\n def teardown_function(function):\n del function.answer\n\n def test_modlevel():\n assert modlevel[0] == 42\n assert test_modlevel.answer == 17\n\n class TestFromClass(object):\n def test_module(self):\n assert modlevel[0] == 42\n assert not hasattr(test_modlevel, 'answer')\n \"\"\"\n )\n rep = reprec.matchreport(\"test_modlevel\")\n assert rep.passed\n rep = reprec.matchreport(\"test_module\")\n assert rep.passed\n\n\ndef test_module_setup_failure_no_teardown(testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n values = []\n def setup_module(module):\n values.append(1)\n 0/0\n\n def test_nothing():\n pass\n\n def teardown_module(module):\n values.append(2)\n \"\"\"\n )\n reprec.assertoutcome(failed=1)\n calls = reprec.getcalls(\"pytest_runtest_setup\")\n assert calls[0].item.module.values == [1]\n\n\ndef test_setup_function_failure_no_teardown(testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n modlevel = []\n def setup_function(function):\n modlevel.append(1)\n 0/0\n\n def teardown_function(module):\n modlevel.append(2)\n\n def test_func():\n pass\n \"\"\"\n )\n calls = reprec.getcalls(\"pytest_runtest_setup\")\n assert calls[0].item.module.modlevel == [1]\n\n\ndef test_class_setup(testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n class TestSimpleClassSetup(object):\n clslevel = []\n def setup_class(cls):\n cls.clslevel.append(23)\n\n def teardown_class(cls):\n cls.clslevel.pop()\n\n def test_classlevel(self):\n assert self.clslevel[0] == 23\n\n class TestInheritedClassSetupStillWorks(TestSimpleClassSetup):\n def test_classlevel_anothertime(self):\n assert self.clslevel == [23]\n\n def test_cleanup():\n assert not TestSimpleClassSetup.clslevel\n assert not TestInheritedClassSetupStillWorks.clslevel\n \"\"\"\n )\n reprec.assertoutcome(passed=1 + 2 + 1)\n\n\ndef test_class_setup_failure_no_teardown(testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n class TestSimpleClassSetup(object):\n clslevel = []\n def setup_class(cls):\n 0/0\n\n def teardown_class(cls):\n cls.clslevel.append(1)\n\n def test_classlevel(self):\n pass\n\n def test_cleanup():\n assert not TestSimpleClassSetup.clslevel\n \"\"\"\n )\n reprec.assertoutcome(failed=1, passed=1)\n\n\ndef test_method_setup(testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n class TestSetupMethod(object):\n def setup_method(self, meth):\n self.methsetup = meth\n def teardown_method(self, meth):\n del self.methsetup\n\n def test_some(self):\n assert self.methsetup == self.test_some\n\n def test_other(self):\n assert self.methsetup == self.test_other\n \"\"\"\n )\n reprec.assertoutcome(passed=2)\n\n\ndef test_method_setup_failure_no_teardown(testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n class TestMethodSetup(object):\n clslevel = []\n def setup_method(self, method):\n self.clslevel.append(1)\n 0/0\n\n def teardown_method(self, method):\n self.clslevel.append(2)\n\n def test_method(self):\n pass\n\n def test_cleanup():\n assert TestMethodSetup.clslevel == [1]\n \"\"\"\n )\n reprec.assertoutcome(failed=1, passed=1)\n\n\ndef test_method_setup_uses_fresh_instances(testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n class TestSelfState1(object):\n memory = []\n def test_hello(self):\n self.memory.append(self)\n\n def test_afterhello(self):\n assert self != self.memory[0]\n \"\"\"\n )\n reprec.assertoutcome(passed=2, failed=0)\n\n\ndef test_setup_that_skips_calledagain(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def setup_module(mod):\n pytest.skip(\"x\")\n def test_function1():\n pass\n def test_function2():\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(p)\n reprec.assertoutcome(skipped=2)\n\n\ndef test_setup_fails_again_on_all_tests(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def setup_module(mod):\n raise ValueError(42)\n def test_function1():\n pass\n def test_function2():\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(p)\n reprec.assertoutcome(failed=2)\n\n\ndef test_setup_funcarg_setup_when_outer_scope_fails(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def setup_module(mod):\n raise ValueError(42)\n @pytest.fixture\n def hello(request):\n raise ValueError(\"xyz43\")\n def test_function1(hello):\n pass\n def test_function2(hello):\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n \"*function1*\",\n \"*ValueError*42*\",\n \"*function2*\",\n \"*ValueError*42*\",\n \"*2 error*\",\n ]\n )\n assert \"xyz43\" not in result.stdout.str()\n\n\n@pytest.mark.parametrize(\"arg\", [\"\", \"arg\"])\ndef test_setup_teardown_function_level_with_optional_argument(\n testdir, monkeypatch, arg\n):\n \"\"\"parameter to setup/teardown xunit-style functions parameter is now optional (#1728).\"\"\"\n import sys\n\n trace_setups_teardowns = []\n monkeypatch.setattr(\n sys, \"trace_setups_teardowns\", trace_setups_teardowns, raising=False\n )\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n import sys\n\n trace = sys.trace_setups_teardowns.append\n\n def setup_module({arg}): trace('setup_module')\n def teardown_module({arg}): trace('teardown_module')\n\n def setup_function({arg}): trace('setup_function')\n def teardown_function({arg}): trace('teardown_function')\n\n def test_function_1(): pass\n def test_function_2(): pass\n\n class Test(object):\n def setup_method(self, {arg}): trace('setup_method')\n def teardown_method(self, {arg}): trace('teardown_method')\n\n def test_method_1(self): pass\n def test_method_2(self): pass\n \"\"\".format(\n arg=arg\n )\n )\n result = testdir.inline_run(p)\n result.assertoutcome(passed=4)\n\n expected = [\n \"setup_module\",\n \"setup_function\",\n \"teardown_function\",\n \"setup_function\",\n \"teardown_function\",\n \"setup_method\",\n \"teardown_method\",\n \"setup_method\",\n \"teardown_method\",\n \"teardown_module\",\n ]\n assert trace_setups_teardowns == expected\n"},{"col":0,"comment":"null","endLoc":43,"header":"def test_module_and_function_setup(testdir)","id":3782,"name":"test_module_and_function_setup","nodeType":"Function","startLoc":13,"text":"def test_module_and_function_setup(testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n modlevel = []\n def setup_module(module):\n assert not modlevel\n module.modlevel.append(42)\n\n def teardown_module(module):\n modlevel.pop()\n\n def setup_function(function):\n function.answer = 17\n\n def teardown_function(function):\n del function.answer\n\n def test_modlevel():\n assert modlevel[0] == 42\n assert test_modlevel.answer == 17\n\n class TestFromClass(object):\n def test_module(self):\n assert modlevel[0] == 42\n assert not hasattr(test_modlevel, 'answer')\n \"\"\"\n )\n rep = reprec.matchreport(\"test_modlevel\")\n assert rep.passed\n rep = reprec.matchreport(\"test_module\")\n assert rep.passed"},{"id":3783,"name":"CONTRIBUTING.rst","nodeType":"TextFile","path":"","text":"============================\nContribution getting started\n============================\n\nContributions are highly welcomed and appreciated. Every little help counts,\nso do not hesitate!\n\n.. contents:: Contribution links\n :depth: 2\n\n\n.. _submitfeedback:\n\nFeature requests and feedback\n-----------------------------\n\nDo you like pytest? Share some love on Twitter or in your blog posts!\n\nWe'd also like to hear about your propositions and suggestions. Feel free to\n`submit them as issues `_ and:\n\n* Explain in detail how they should work.\n* Keep the scope as narrow as possible. This will make it easier to implement.\n\n\n.. _reportbugs:\n\nReport bugs\n-----------\n\nReport bugs for pytest in the `issue tracker `_.\n\nIf you are reporting a bug, please include:\n\n* Your operating system name and version.\n* Any details about your local setup that might be helpful in troubleshooting,\n specifically the Python interpreter version, installed libraries, and pytest\n version.\n* Detailed steps to reproduce the bug.\n\nIf you can write a demonstration test that currently fails but should pass\n(xfail), that is a very useful commit to make as well, even if you cannot\nfix the bug itself.\n\n\n.. _fixbugs:\n\nFix bugs\n--------\n\nLook through the `GitHub issues for bugs `_.\n\n:ref:`Talk ` to developers to find out how you can fix specific bugs.\n\nDon't forget to check the issue trackers of your favourite plugins, too!\n\n.. _writeplugins:\n\nImplement features\n------------------\n\nLook through the `GitHub issues for enhancements `_.\n\n:ref:`Talk ` to developers to find out how you can implement specific\nfeatures.\n\nWrite documentation\n-------------------\n\nPytest could always use more documentation. What exactly is needed?\n\n* More complementary documentation. Have you perhaps found something unclear?\n* Documentation translations. We currently have only English.\n* Docstrings. There can never be too many of them.\n* Blog posts, articles and such -- they're all very appreciated.\n\nYou can also edit documentation files directly in the GitHub web interface,\nwithout using a local copy. This can be convenient for small fixes.\n\n.. note::\n Build the documentation locally with the following command:\n\n .. code:: bash\n\n $ tox -e docs\n\n The built documentation should be available in the ``doc/en/_build/``.\n\n Where 'en' refers to the documentation language.\n\n.. _submitplugin:\n\nSubmitting Plugins to pytest-dev\n--------------------------------\n\nPytest development of the core, some plugins and support code happens\nin repositories living under the ``pytest-dev`` organisations:\n\n- `pytest-dev on GitHub `_\n\n- `pytest-dev on Bitbucket `_\n\nAll pytest-dev Contributors team members have write access to all contained\nrepositories. Pytest core and plugins are generally developed\nusing `pull requests`_ to respective repositories.\n\nThe objectives of the ``pytest-dev`` organisation are:\n\n* Having a central location for popular pytest plugins\n* Sharing some of the maintenance responsibility (in case a maintainer no\n longer wishes to maintain a plugin)\n\nYou can submit your plugin by subscribing to the `pytest-dev mail list\n`_ and writing a\nmail pointing to your existing pytest plugin repository which must have\nthe following:\n\n- PyPI presence with a ``setup.py`` that contains a license, ``pytest-``\n prefixed name, version number, authors, short and long description.\n\n- a ``tox.ini`` for running tests using `tox `_.\n\n- a ``README.txt`` describing how to use the plugin and on which\n platforms it runs.\n\n- a ``LICENSE.txt`` file or equivalent containing the licensing\n information, with matching info in ``setup.py``.\n\n- an issue tracker for bug reports and enhancement requests.\n\n- a `changelog `_\n\nIf no contributor strongly objects and two agree, the repository can then be\ntransferred to the ``pytest-dev`` organisation.\n\nHere's a rundown of how a repository transfer usually proceeds\n(using a repository named ``joedoe/pytest-xyz`` as example):\n\n* ``joedoe`` transfers repository ownership to ``pytest-dev`` administrator ``calvin``.\n* ``calvin`` creates ``pytest-xyz-admin`` and ``pytest-xyz-developers`` teams, inviting ``joedoe`` to both as **maintainer**.\n* ``calvin`` transfers repository to ``pytest-dev`` and configures team access:\n\n - ``pytest-xyz-admin`` **admin** access;\n - ``pytest-xyz-developers`` **write** access;\n\nThe ``pytest-dev/Contributors`` team has write access to all projects, and\nevery project administrator is in it. We recommend that each plugin has at least three\npeople who have the right to release to PyPI.\n\nRepository owners can rest assured that no ``pytest-dev`` administrator will ever make\nreleases of your repository or take ownership in any way, except in rare cases\nwhere someone becomes unresponsive after months of contact attempts.\nAs stated, the objective is to share maintenance and avoid \"plugin-abandon\".\n\n\n.. _`pull requests`:\n.. _pull-requests:\n\nPreparing Pull Requests\n-----------------------\n\nShort version\n~~~~~~~~~~~~~\n\n#. Fork the repository.\n#. Enable and install `pre-commit `_ to ensure style-guides and code checks are followed.\n#. Target ``master`` for bugfixes and doc changes.\n#. Target ``features`` for new features or functionality changes.\n#. Follow **PEP-8** for naming and `black `_ for formatting.\n#. Tests are run using ``tox``::\n\n tox -e linting,py27,py37\n\n The test environments above are usually enough to cover most cases locally.\n\n#. Write a ``changelog`` entry: ``changelog/2574.bugfix``, use issue id number\n and one of ``bugfix``, ``removal``, ``feature``, ``vendor``, ``doc`` or\n ``trivial`` for the issue type.\n#. Unless your change is a trivial or a documentation fix (e.g., a typo or reword of a small section) please\n add yourself to the ``AUTHORS`` file, in alphabetical order.\n\n\nLong version\n~~~~~~~~~~~~\n\nWhat is a \"pull request\"? It informs the project's core developers about the\nchanges you want to review and merge. Pull requests are stored on\n`GitHub servers `_.\nOnce you send a pull request, we can discuss its potential modifications and\neven add more commits to it later on. There's an excellent tutorial on how Pull\nRequests work in the\n`GitHub Help Center `_.\n\nHere is a simple overview, with pytest-specific bits:\n\n#. Fork the\n `pytest GitHub repository `__. It's\n fine to use ``pytest`` as your fork repository name because it will live\n under your user.\n\n#. Clone your fork locally using `git `_ and create a branch::\n\n $ git clone git@github.com:YOUR_GITHUB_USERNAME/pytest.git\n $ cd pytest\n # now, to fix a bug create your own branch off \"master\":\n\n $ git checkout -b your-bugfix-branch-name master\n\n # or to instead add a feature create your own branch off \"features\":\n\n $ git checkout -b your-feature-branch-name features\n\n Given we have \"major.minor.micro\" version numbers, bugfixes will usually\n be released in micro releases whereas features will be released in\n minor releases and incompatible changes in major releases.\n\n If you need some help with Git, follow this quick start\n guide: https://git.wiki.kernel.org/index.php/QuickStart\n\n#. Install `pre-commit `_ and its hook on the pytest repo::\n\n $ pip install --user pre-commit\n $ pre-commit install\n\n Afterwards ``pre-commit`` will run whenever you commit.\n\n https://pre-commit.com/ is a framework for managing and maintaining multi-language pre-commit hooks\n to ensure code-style and code formatting is consistent.\n\n#. Install tox\n\n Tox is used to run all the tests and will automatically setup virtualenvs\n to run the tests in.\n (will implicitly use http://www.virtualenv.org/en/latest/)::\n\n $ pip install tox\n\n#. Run all the tests\n\n You need to have Python 2.7 and 3.7 available in your system. Now\n running tests is as simple as issuing this command::\n\n $ tox -e linting,py27,py37\n\n This command will run tests via the \"tox\" tool against Python 2.7 and 3.7\n and also perform \"lint\" coding-style checks.\n\n#. You can now edit your local working copy and run the tests again as necessary. Please follow PEP-8 for naming.\n\n You can pass different options to ``tox``. For example, to run tests on Python 2.7 and pass options to pytest\n (e.g. enter pdb on failure) to pytest you can do::\n\n $ tox -e py27 -- --pdb\n\n Or to only run tests in a particular test module on Python 3.7::\n\n $ tox -e py37 -- testing/test_config.py\n\n\n When committing, ``pre-commit`` will re-format the files if necessary.\n\n#. Commit and push once your tests pass and you are happy with your change(s)::\n\n $ git commit -a -m \"\"\n $ git push -u\n\n#. Create a new changelog entry in ``changelog``. The file should be named ``.``,\n where *issueid* is the number of the issue related to the change and *type* is one of\n ``bugfix``, ``removal``, ``feature``, ``vendor``, ``doc`` or ``trivial``.\n\n#. Add yourself to ``AUTHORS`` file if not there yet, in alphabetical order.\n\n#. Finally, submit a pull request through the GitHub website using this data::\n\n head-fork: YOUR_GITHUB_USERNAME/pytest\n compare: your-branch-name\n\n base-fork: pytest-dev/pytest\n base: master # if it's a bugfix\n base: features # if it's a feature\n\n\nWriting Tests\n----------------------------\n\nWriting tests for plugins or for pytest itself is often done using the `testdir fixture `_, as a \"black-box\" test.\n\nFor example, to ensure a simple test passes you can write:\n\n.. code-block:: python\n\n def test_true_assertion(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert True\n \"\"\"\n )\n result = testdir.runpytest()\n result.assert_outcomes(failed=0, passed=1)\n\n\nAlternatively, it is possible to make checks based on the actual output of the termal using\n*glob-like* expressions:\n\n.. code-block:: python\n\n def test_true_assertion(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert False\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*assert False*\", \"*1 failed*\"])\n\nWhen choosing a file where to write a new test, take a look at the existing files and see if there's\none file which looks like a good fit. For example, a regression test about a bug in the ``--lf`` option\nshould go into ``test_cacheprovider.py``, given that this option is implemented in ``cacheprovider.py``.\nIf in doubt, go ahead and open a PR with your best guess and we can discuss this over the code.\n\n\nJoining the Development Team\n----------------------------\n\nAnyone who has successfully seen through a pull request which did not\nrequire any extra work from the development team to merge will\nthemselves gain commit access if they so wish (if we forget to ask please send a friendly\nreminder). This does not mean your workflow to contribute changes,\neveryone goes through the same pull-request-and-review process and\nno-one merges their own pull requests unless already approved. It does however mean you can\nparticipate in the development process more fully since you can merge\npull requests from other contributors yourself after having reviewed\nthem.\n"},{"id":3784,"name":".pre-commit-config.yaml","nodeType":"TextFile","path":"","text":"exclude: doc/en/example/py2py3/test_py2.py\nrepos:\n- repo: https://github.com/python/black\n rev: 19.3b0\n hooks:\n - id: black\n args: [--safe, --quiet]\n language_version: python3\n- repo: https://github.com/asottile/blacken-docs\n rev: v0.5.0\n hooks:\n - id: blacken-docs\n additional_dependencies: [black==19.3b0]\n language_version: python3\n- repo: https://github.com/pre-commit/pre-commit-hooks\n rev: v2.2.2\n hooks:\n - id: trailing-whitespace\n - id: end-of-file-fixer\n - id: fix-encoding-pragma\n - id: check-yaml\n - id: debug-statements\n exclude: _pytest/debugging.py\n language_version: python3\n- repo: https://gitlab.com/pycqa/flake8\n rev: 3.7.7\n hooks:\n - id: flake8\n language_version: python3\n- repo: https://github.com/asottile/reorder_python_imports\n rev: v1.4.0\n hooks:\n - id: reorder-python-imports\n args: ['--application-directories=.:src']\n- repo: https://github.com/asottile/pyupgrade\n rev: v1.15.0\n hooks:\n - id: pyupgrade\n args: [--keep-percent-format]\n- repo: https://github.com/pre-commit/pygrep-hooks\n rev: v1.3.0\n hooks:\n - id: rst-backticks\n- repo: local\n hooks:\n - id: rst\n name: rst\n entry: rst-lint --encoding utf-8\n files: ^(CHANGELOG.rst|HOWTORELEASE.rst|README.rst|TIDELIFT.rst|changelog/.*)$\n language: python\n additional_dependencies: [pygments, restructuredtext_lint]\n - id: changelogs-rst\n name: changelog filenames\n language: fail\n entry: 'changelog files must be named ####.(feature|bugfix|doc|deprecation|removal|vendor|trivial).rst'\n exclude: changelog/(\\d+\\.(feature|bugfix|doc|deprecation|removal|vendor|trivial).rst|README.rst|_template.rst)\n files: ^changelog/\n - id: py-deprecated\n name: py library is deprecated\n language: pygrep\n entry: >\n (?x)\\bpy\\.(\n _code\\.|\n builtin\\.|\n code\\.|\n io\\.(BytesIO|saferepr)|\n path\\.local\\.sysfind|\n process\\.|\n std\\.\n )\n types: [python]\n"},{"col":0,"comment":"null","endLoc":63,"header":"def test_module_setup_failure_no_teardown(testdir)","id":3785,"name":"test_module_setup_failure_no_teardown","nodeType":"Function","startLoc":46,"text":"def test_module_setup_failure_no_teardown(testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n values = []\n def setup_module(module):\n values.append(1)\n 0/0\n\n def test_nothing():\n pass\n\n def teardown_module(module):\n values.append(2)\n \"\"\"\n )\n reprec.assertoutcome(failed=1)\n calls = reprec.getcalls(\"pytest_runtest_setup\")\n assert calls[0].item.module.values == [1]"},{"id":3786,"name":"release-2.4.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.4.2: colorama on windows, plugin/tmpdir fixes\n===========================================================================\n\npytest-2.4.2 is another bug-fixing release:\n\n- on Windows require colorama and a newer py lib so that py.io.TerminalWriter()\n now uses colorama instead of its own ctypes hacks. (fixes issue365)\n thanks Paul Moore for bringing it up.\n\n- fix \"-k\" matching of tests where \"repr\" and \"attr\" and other names would\n cause wrong matches because of an internal implementation quirk\n (don't ask) which is now properly implemented. fixes issue345.\n\n- avoid tmpdir fixture to create too long filenames especially\n when parametrization is used (issue354)\n\n- fix pytest-pep8 and pytest-flakes / pytest interactions\n (collection names in mark plugin was assuming an item always\n has a function which is not true for those plugins etc.)\n Thanks Andi Zeidler.\n\n- introduce node.get_marker/node.add_marker API for plugins\n like pytest-pep8 and pytest-flakes to avoid the messy\n details of the node.keywords pseudo-dicts. Adapted\n docs.\n\n- remove attempt to \"dup\" stdout at startup as it's icky.\n the normal capturing should catch enough possibilities\n of tests messing up standard FDs.\n\n- add pluginmanager.do_configure(config) as a link to\n config.do_configure() for plugin-compatibility\n\nas usual, docs at http://pytest.org and upgrades via::\n\n pip install -U pytest\n\nhave fun,\nholger krekel\n"},{"col":0,"comment":"null","endLoc":82,"header":"def test_setup_function_failure_no_teardown(testdir)","id":3787,"name":"test_setup_function_failure_no_teardown","nodeType":"Function","startLoc":66,"text":"def test_setup_function_failure_no_teardown(testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n modlevel = []\n def setup_function(function):\n modlevel.append(1)\n 0/0\n\n def teardown_function(module):\n modlevel.append(2)\n\n def test_func():\n pass\n \"\"\"\n )\n calls = reprec.getcalls(\"pytest_runtest_setup\")\n assert calls[0].item.module.modlevel == [1]"},{"col":0,"comment":"null","endLoc":108,"header":"def test_class_setup(testdir)","id":3788,"name":"test_class_setup","nodeType":"Function","startLoc":85,"text":"def test_class_setup(testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n class TestSimpleClassSetup(object):\n clslevel = []\n def setup_class(cls):\n cls.clslevel.append(23)\n\n def teardown_class(cls):\n cls.clslevel.pop()\n\n def test_classlevel(self):\n assert self.clslevel[0] == 23\n\n class TestInheritedClassSetupStillWorks(TestSimpleClassSetup):\n def test_classlevel_anothertime(self):\n assert self.clslevel == [23]\n\n def test_cleanup():\n assert not TestSimpleClassSetup.clslevel\n assert not TestInheritedClassSetupStillWorks.clslevel\n \"\"\"\n )\n reprec.assertoutcome(passed=1 + 2 + 1)"},{"id":3789,"name":"release-2.1.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"py.test 2.1.0: perfected assertions and bug fixes\n===========================================================================\n\nWelcome to the release of pytest-2.1, a mature testing tool for Python,\nsupporting CPython 2.4-3.2, Jython and latest PyPy interpreters. See\nthe improved extensive docs (now also as PDF!) with tested examples here:\n\n http://pytest.org/\n\nThe single biggest news about this release are **perfected assertions**\ncourtesy of Benjamin Peterson. You can now safely use ``assert``\nstatements in test modules without having to worry about side effects\nor python optimization (\"-OO\") options. This is achieved by rewriting\nassert statements in test modules upon import, using a PEP302 hook.\nSee http://pytest.org/assert.html#advanced-assertion-introspection for\ndetailed information. The work has been partly sponsored by my company,\nmerlinux GmbH.\n\nFor further details on bug fixes and smaller enhancements see below.\n\nIf you want to install or upgrade pytest, just type one of::\n\n pip install -U pytest # or\n easy_install -U pytest\n\nbest,\nholger krekel / http://merlinux.eu\n\nChanges between 2.0.3 and 2.1.0\n----------------------------------------------\n\n- fix issue53 call nosestyle setup functions with correct ordering\n- fix issue58 and issue59: new assertion code fixes\n- merge Benjamin's assertionrewrite branch: now assertions\n for test modules on python 2.6 and above are done by rewriting\n the AST and saving the pyc file before the test module is imported.\n see doc/assert.txt for more info.\n- fix issue43: improve doctests with better traceback reporting on\n unexpected exceptions\n- fix issue47: timing output in junitxml for test cases is now correct\n- fix issue48: typo in MarkInfo repr leading to exception\n- fix issue49: avoid confusing error when initialization partially fails\n- fix issue44: env/username expansion for junitxml file path\n- show releaselevel information in test runs for pypy\n- reworked doc pages for better navigation and PDF generation\n- report KeyboardInterrupt even if interrupted during session startup\n- fix issue 35 - provide PDF doc version and download link from index page\n"},{"col":0,"comment":"null","endLoc":129,"header":"def test_class_setup_failure_no_teardown(testdir)","id":3790,"name":"test_class_setup_failure_no_teardown","nodeType":"Function","startLoc":111,"text":"def test_class_setup_failure_no_teardown(testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n class TestSimpleClassSetup(object):\n clslevel = []\n def setup_class(cls):\n 0/0\n\n def teardown_class(cls):\n cls.clslevel.append(1)\n\n def test_classlevel(self):\n pass\n\n def test_cleanup():\n assert not TestSimpleClassSetup.clslevel\n \"\"\"\n )\n reprec.assertoutcome(failed=1, passed=1)"},{"col":4,"comment":"null","endLoc":718,"header":"def test_allow_sane_sorting_for_decorators(self, testdir)","id":3791,"name":"test_allow_sane_sorting_for_decorators","nodeType":"Function","startLoc":698,"text":"def test_allow_sane_sorting_for_decorators(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n def dec(f):\n g = lambda: f(2)\n g.place_as = f\n return g\n\n\n def test_b(y):\n pass\n test_b = dec(test_b)\n\n def test_a(y):\n pass\n test_a = dec(test_a)\n \"\"\"\n )\n colitems = modcol.collect()\n assert len(colitems) == 2\n assert [item.name for item in colitems] == [\"test_b\", \"test_a\"]"},{"col":0,"comment":"null","endLoc":148,"header":"def test_method_setup(testdir)","id":3792,"name":"test_method_setup","nodeType":"Function","startLoc":132,"text":"def test_method_setup(testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n class TestSetupMethod(object):\n def setup_method(self, meth):\n self.methsetup = meth\n def teardown_method(self, meth):\n del self.methsetup\n\n def test_some(self):\n assert self.methsetup == self.test_some\n\n def test_other(self):\n assert self.methsetup == self.test_other\n \"\"\"\n )\n reprec.assertoutcome(passed=2)"},{"id":3793,"name":"testing/example_scripts/marks/marks_considered_keywords","nodeType":"Package"},{"fileName":"conftest.py","filePath":"testing/example_scripts/marks/marks_considered_keywords","id":3794,"nodeType":"File","text":""},{"col":0,"comment":"null","endLoc":170,"header":"def test_method_setup_failure_no_teardown(testdir)","id":3795,"name":"test_method_setup_failure_no_teardown","nodeType":"Function","startLoc":151,"text":"def test_method_setup_failure_no_teardown(testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n class TestMethodSetup(object):\n clslevel = []\n def setup_method(self, method):\n self.clslevel.append(1)\n 0/0\n\n def teardown_method(self, method):\n self.clslevel.append(2)\n\n def test_method(self):\n pass\n\n def test_cleanup():\n assert TestMethodSetup.clslevel == [1]\n \"\"\"\n )\n reprec.assertoutcome(failed=1, passed=1)"},{"className":"TestConftestCustomization","col":0,"comment":"null","endLoc":851,"id":3796,"nodeType":"Class","startLoc":721,"text":"class TestConftestCustomization(object):\n def test_pytest_pycollect_module(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n class MyModule(pytest.Module):\n pass\n def pytest_pycollect_makemodule(path, parent):\n if path.basename == \"test_xyz.py\":\n return MyModule(path, parent)\n \"\"\"\n )\n testdir.makepyfile(\"def test_some(): pass\")\n testdir.makepyfile(test_xyz=\"def test_func(): pass\")\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*","id":3802,"name":"","nodeType":"Function","startLoc":2,"text":"__all__ = [\"__version__\"]\n\ntry:\n from ._version import version as __version__\nexcept ImportError:\n # broken installation, we don't even try\n # unknown only works because we do poor mans version compare\n __version__ = \"unknown\""},{"col":4,"comment":"null","endLoc":761,"header":"def test_customized_pymakemodule_issue205_subdir(self, testdir)","id":3803,"name":"test_customized_pymakemodule_issue205_subdir","nodeType":"Function","startLoc":738,"text":"def test_customized_pymakemodule_issue205_subdir(self, testdir):\n b = testdir.mkdir(\"a\").mkdir(\"b\")\n b.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.hookimpl(hookwrapper=True)\n def pytest_pycollect_makemodule():\n outcome = yield\n mod = outcome.get_result()\n mod.obj.hello = \"world\"\n \"\"\"\n )\n )\n b.join(\"test_module.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_hello():\n assert hello == \"world\"\n \"\"\"\n )\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":"null","endLoc":794,"header":"def test_customized_pymakeitem(self, testdir)","id":3804,"name":"test_customized_pymakeitem","nodeType":"Function","startLoc":763,"text":"def test_customized_pymakeitem(self, testdir):\n b = testdir.mkdir(\"a\").mkdir(\"b\")\n b.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.hookimpl(hookwrapper=True)\n def pytest_pycollect_makeitem():\n outcome = yield\n if outcome.excinfo is None:\n result = outcome.get_result()\n if result:\n for func in result:\n func._some123 = \"world\"\n \"\"\"\n )\n )\n b.join(\"test_module.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n\n @pytest.fixture()\n def obj(request):\n return request.node._some123\n def test_hello(obj):\n assert obj == \"world\"\n \"\"\"\n )\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":0,"comment":"null","endLoc":217,"header":"def test_setup_fails_again_on_all_tests(testdir)","id":3805,"name":"test_setup_fails_again_on_all_tests","nodeType":"Function","startLoc":204,"text":"def test_setup_fails_again_on_all_tests(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def setup_module(mod):\n raise ValueError(42)\n def test_function1():\n pass\n def test_function2():\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(p)\n reprec.assertoutcome(failed=2)"},{"col":4,"comment":"null","endLoc":809,"header":"def test_pytest_pycollect_makeitem(self, testdir)","id":3806,"name":"test_pytest_pycollect_makeitem","nodeType":"Function","startLoc":796,"text":"def test_pytest_pycollect_makeitem(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n class MyFunction(pytest.Function):\n pass\n def pytest_pycollect_makeitem(collector, name, obj):\n if name == \"some\":\n return MyFunction(name, collector)\n \"\"\"\n )\n testdir.makepyfile(\"def some(): pass\")\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*MyFunction*some*\"])"},{"fileName":"test_parseopt.py","filePath":"testing","id":3807,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport distutils.spawn\nimport os\nimport sys\n\nimport py\n\nimport pytest\nfrom _pytest.config import argparsing as parseopt\nfrom _pytest.config.exceptions import UsageError\n\n\n@pytest.fixture\ndef parser():\n return parseopt.Parser()\n\n\nclass TestParser(object):\n def test_no_help_by_default(self):\n parser = parseopt.Parser(usage=\"xyz\")\n pytest.raises(UsageError, lambda: parser.parse([\"-h\"]))\n\n def test_custom_prog(self, parser):\n \"\"\"Custom prog can be set for `argparse.ArgumentParser`.\"\"\"\n assert parser._getparser().prog == os.path.basename(sys.argv[0])\n parser.prog = \"custom-prog\"\n assert parser._getparser().prog == \"custom-prog\"\n\n def test_argument(self):\n with pytest.raises(parseopt.ArgumentError):\n # need a short or long option\n argument = parseopt.Argument()\n argument = parseopt.Argument(\"-t\")\n assert argument._short_opts == [\"-t\"]\n assert argument._long_opts == []\n assert argument.dest == \"t\"\n argument = parseopt.Argument(\"-t\", \"--test\")\n assert argument._short_opts == [\"-t\"]\n assert argument._long_opts == [\"--test\"]\n assert argument.dest == \"test\"\n argument = parseopt.Argument(\"-t\", \"--test\", dest=\"abc\")\n assert argument.dest == \"abc\"\n assert str(argument) == (\n \"Argument(_short_opts: ['-t'], _long_opts: ['--test'], dest: 'abc')\"\n )\n\n def test_argument_type(self):\n argument = parseopt.Argument(\"-t\", dest=\"abc\", type=int)\n assert argument.type is int\n argument = parseopt.Argument(\"-t\", dest=\"abc\", type=str)\n assert argument.type is str\n argument = parseopt.Argument(\"-t\", dest=\"abc\", type=float)\n assert argument.type is float\n with pytest.warns(DeprecationWarning):\n with pytest.raises(KeyError):\n argument = parseopt.Argument(\"-t\", dest=\"abc\", type=\"choice\")\n argument = parseopt.Argument(\n \"-t\", dest=\"abc\", type=str, choices=[\"red\", \"blue\"]\n )\n assert argument.type is str\n\n def test_argument_processopt(self):\n argument = parseopt.Argument(\"-t\", type=int)\n argument.default = 42\n argument.dest = \"abc\"\n res = argument.attrs()\n assert res[\"default\"] == 42\n assert res[\"dest\"] == \"abc\"\n\n def test_group_add_and_get(self, parser):\n group = parser.getgroup(\"hello\", description=\"desc\")\n assert group.name == \"hello\"\n assert group.description == \"desc\"\n\n def test_getgroup_simple(self, parser):\n group = parser.getgroup(\"hello\", description=\"desc\")\n assert group.name == \"hello\"\n assert group.description == \"desc\"\n group2 = parser.getgroup(\"hello\")\n assert group2 is group\n\n def test_group_ordering(self, parser):\n parser.getgroup(\"1\")\n parser.getgroup(\"2\")\n parser.getgroup(\"3\", after=\"1\")\n groups = parser._groups\n groups_names = [x.name for x in groups]\n assert groups_names == list(\"132\")\n\n def test_group_addoption(self):\n group = parseopt.OptionGroup(\"hello\")\n group.addoption(\"--option1\", action=\"store_true\")\n assert len(group.options) == 1\n assert isinstance(group.options[0], parseopt.Argument)\n\n def test_group_addoption_conflict(self):\n group = parseopt.OptionGroup(\"hello again\")\n group.addoption(\"--option1\", \"--option-1\", action=\"store_true\")\n with pytest.raises(ValueError) as err:\n group.addoption(\"--option1\", \"--option-one\", action=\"store_true\")\n assert str({\"--option1\"}) in str(err.value)\n\n def test_group_shortopt_lowercase(self, parser):\n group = parser.getgroup(\"hello\")\n with pytest.raises(ValueError):\n group.addoption(\"-x\", action=\"store_true\")\n assert len(group.options) == 0\n group._addoption(\"-x\", action=\"store_true\")\n assert len(group.options) == 1\n\n def test_parser_addoption(self, parser):\n group = parser.getgroup(\"custom options\")\n assert len(group.options) == 0\n group.addoption(\"--option1\", action=\"store_true\")\n assert len(group.options) == 1\n\n def test_parse(self, parser):\n parser.addoption(\"--hello\", dest=\"hello\", action=\"store\")\n args = parser.parse([\"--hello\", \"world\"])\n assert args.hello == \"world\"\n assert not getattr(args, parseopt.FILE_OR_DIR)\n\n def test_parse2(self, parser):\n args = parser.parse([py.path.local()])\n assert getattr(args, parseopt.FILE_OR_DIR)[0] == py.path.local()\n\n def test_parse_known_args(self, parser):\n parser.parse_known_args([py.path.local()])\n parser.addoption(\"--hello\", action=\"store_true\")\n ns = parser.parse_known_args([\"x\", \"--y\", \"--hello\", \"this\"])\n assert ns.hello\n assert ns.file_or_dir == [\"x\"]\n\n def test_parse_known_and_unknown_args(self, parser):\n parser.addoption(\"--hello\", action=\"store_true\")\n ns, unknown = parser.parse_known_and_unknown_args(\n [\"x\", \"--y\", \"--hello\", \"this\"]\n )\n assert ns.hello\n assert ns.file_or_dir == [\"x\"]\n assert unknown == [\"--y\", \"this\"]\n\n def test_parse_will_set_default(self, parser):\n parser.addoption(\"--hello\", dest=\"hello\", default=\"x\", action=\"store\")\n option = parser.parse([])\n assert option.hello == \"x\"\n del option.hello\n parser.parse_setoption([], option)\n assert option.hello == \"x\"\n\n def test_parse_setoption(self, parser):\n parser.addoption(\"--hello\", dest=\"hello\", action=\"store\")\n parser.addoption(\"--world\", dest=\"world\", default=42)\n\n class A(object):\n pass\n\n option = A()\n args = parser.parse_setoption([\"--hello\", \"world\"], option)\n assert option.hello == \"world\"\n assert option.world == 42\n assert not args\n\n def test_parse_special_destination(self, parser):\n parser.addoption(\"--ultimate-answer\", type=int)\n args = parser.parse([\"--ultimate-answer\", \"42\"])\n assert args.ultimate_answer == 42\n\n def test_parse_split_positional_arguments(self, parser):\n parser.addoption(\"-R\", action=\"store_true\")\n parser.addoption(\"-S\", action=\"store_false\")\n args = parser.parse([\"-R\", \"4\", \"2\", \"-S\"])\n assert getattr(args, parseopt.FILE_OR_DIR) == [\"4\", \"2\"]\n args = parser.parse([\"-R\", \"-S\", \"4\", \"2\", \"-R\"])\n assert getattr(args, parseopt.FILE_OR_DIR) == [\"4\", \"2\"]\n assert args.R is True\n assert args.S is False\n args = parser.parse([\"-R\", \"4\", \"-S\", \"2\"])\n assert getattr(args, parseopt.FILE_OR_DIR) == [\"4\", \"2\"]\n assert args.R is True\n assert args.S is False\n\n def test_parse_defaultgetter(self):\n def defaultget(option):\n if not hasattr(option, \"type\"):\n return\n if option.type is int:\n option.default = 42\n elif option.type is str:\n option.default = \"world\"\n\n parser = parseopt.Parser(processopt=defaultget)\n parser.addoption(\"--this\", dest=\"this\", type=int, action=\"store\")\n parser.addoption(\"--hello\", dest=\"hello\", type=str, action=\"store\")\n parser.addoption(\"--no\", dest=\"no\", action=\"store_true\")\n option = parser.parse([])\n assert option.hello == \"world\"\n assert option.this == 42\n assert option.no is False\n\n def test_drop_short_helper(self):\n parser = argparse.ArgumentParser(\n formatter_class=parseopt.DropShorterLongHelpFormatter\n )\n parser.add_argument(\n \"-t\", \"--twoword\", \"--duo\", \"--two-word\", \"--two\", help=\"foo\"\n ).map_long_option = {\"two\": \"two-word\"}\n # throws error on --deux only!\n parser.add_argument(\n \"-d\", \"--deuxmots\", \"--deux-mots\", action=\"store_true\", help=\"foo\"\n ).map_long_option = {\"deux\": \"deux-mots\"}\n parser.add_argument(\"-s\", action=\"store_true\", help=\"single short\")\n parser.add_argument(\"--abc\", \"-a\", action=\"store_true\", help=\"bar\")\n parser.add_argument(\"--klm\", \"-k\", \"--kl-m\", action=\"store_true\", help=\"bar\")\n parser.add_argument(\n \"-P\", \"--pq-r\", \"-p\", \"--pqr\", action=\"store_true\", help=\"bar\"\n )\n parser.add_argument(\n \"--zwei-wort\", \"--zweiwort\", \"--zweiwort\", action=\"store_true\", help=\"bar\"\n )\n parser.add_argument(\n \"-x\", \"--exit-on-first\", \"--exitfirst\", action=\"store_true\", help=\"spam\"\n ).map_long_option = {\"exitfirst\": \"exit-on-first\"}\n parser.add_argument(\"files_and_dirs\", nargs=\"*\")\n args = parser.parse_args([\"-k\", \"--duo\", \"hallo\", \"--exitfirst\"])\n assert args.twoword == \"hallo\"\n assert args.klm is True\n assert args.zwei_wort is False\n assert args.exit_on_first is True\n assert args.s is False\n args = parser.parse_args([\"--deux-mots\"])\n with pytest.raises(AttributeError):\n assert args.deux_mots is True\n assert args.deuxmots is True\n args = parser.parse_args([\"file\", \"dir\"])\n assert \"|\".join(args.files_and_dirs) == \"file|dir\"\n\n def test_drop_short_0(self, parser):\n parser.addoption(\"--funcarg\", \"--func-arg\", action=\"store_true\")\n parser.addoption(\"--abc-def\", \"--abc-def\", action=\"store_true\")\n parser.addoption(\"--klm-hij\", action=\"store_true\")\n args = parser.parse([\"--funcarg\", \"--k\"])\n assert args.funcarg is True\n assert args.abc_def is False\n assert args.klm_hij is True\n\n def test_drop_short_2(self, parser):\n parser.addoption(\"--func-arg\", \"--doit\", action=\"store_true\")\n args = parser.parse([\"--doit\"])\n assert args.func_arg is True\n\n def test_drop_short_3(self, parser):\n parser.addoption(\"--func-arg\", \"--funcarg\", \"--doit\", action=\"store_true\")\n args = parser.parse([\"abcd\"])\n assert args.func_arg is False\n assert args.file_or_dir == [\"abcd\"]\n\n def test_drop_short_help0(self, parser, capsys):\n parser.addoption(\"--func-args\", \"--doit\", help=\"foo\", action=\"store_true\")\n parser.parse([])\n help = parser.optparser.format_help()\n assert \"--func-args, --doit foo\" in help\n\n # testing would be more helpful with all help generated\n def test_drop_short_help1(self, parser, capsys):\n group = parser.getgroup(\"general\")\n group.addoption(\"--doit\", \"--func-args\", action=\"store_true\", help=\"foo\")\n group._addoption(\n \"-h\",\n \"--help\",\n action=\"store_true\",\n dest=\"help\",\n help=\"show help message and configuration info\",\n )\n parser.parse([\"-h\"])\n help = parser.optparser.format_help()\n assert \"-doit, --func-args foo\" in help\n\n def test_multiple_metavar_help(self, parser):\n \"\"\"\n Help text for options with a metavar tuple should display help\n in the form \"--preferences=value1 value2 value3\" (#2004).\n \"\"\"\n group = parser.getgroup(\"general\")\n group.addoption(\n \"--preferences\", metavar=(\"value1\", \"value2\", \"value3\"), nargs=3\n )\n group._addoption(\"-h\", \"--help\", action=\"store_true\", dest=\"help\")\n parser.parse([\"-h\"])\n help = parser.optparser.format_help()\n assert \"--preferences=value1 value2 value3\" in help\n\n\ndef test_argcomplete(testdir, monkeypatch):\n if not distutils.spawn.find_executable(\"bash\"):\n pytest.skip(\"bash not available\")\n script = str(testdir.tmpdir.join(\"test_argcomplete\"))\n\n with open(str(script), \"w\") as fp:\n # redirect output from argcomplete to stdin and stderr is not trivial\n # http://stackoverflow.com/q/12589419/1307905\n # so we use bash\n fp.write('COMP_WORDBREAKS=\"$COMP_WORDBREAKS\" python -m pytest 8>&1 9>&2')\n # alternative would be exteneded Testdir.{run(),_run(),popen()} to be able\n # to handle a keyword argument env that replaces os.environ in popen or\n # extends the copy, advantage: could not forget to restore\n monkeypatch.setenv(\"_ARGCOMPLETE\", \"1\")\n monkeypatch.setenv(\"_ARGCOMPLETE_IFS\", \"\\x0b\")\n monkeypatch.setenv(\"COMP_WORDBREAKS\", \" \\\\t\\\\n\\\"\\\\'><=;|&(:\")\n\n arg = \"--fu\"\n monkeypatch.setenv(\"COMP_LINE\", \"pytest \" + arg)\n monkeypatch.setenv(\"COMP_POINT\", str(len(\"pytest \" + arg)))\n result = testdir.run(\"bash\", str(script), arg)\n if result.ret == 255:\n # argcomplete not found\n pytest.skip(\"argcomplete not available\")\n elif not result.stdout.str():\n pytest.skip(\n \"bash provided no output on stdout, argcomplete not available? (stderr={!r})\".format(\n result.stderr.str()\n )\n )\n else:\n result.stdout.fnmatch_lines([\"--funcargs\", \"--fulltrace\"])\n os.mkdir(\"test_argcomplete.d\")\n arg = \"test_argc\"\n monkeypatch.setenv(\"COMP_LINE\", \"pytest \" + arg)\n monkeypatch.setenv(\"COMP_POINT\", str(len(\"pytest \" + arg)))\n result = testdir.run(\"bash\", str(script), arg)\n result.stdout.fnmatch_lines([\"test_argcomplete\", \"test_argcomplete.d/\"])\n"},{"className":"TestParser","col":0,"comment":"null","endLoc":296,"id":3808,"nodeType":"Class","startLoc":23,"text":"class TestParser(object):\n def test_no_help_by_default(self):\n parser = parseopt.Parser(usage=\"xyz\")\n pytest.raises(UsageError, lambda: parser.parse([\"-h\"]))\n\n def test_custom_prog(self, parser):\n \"\"\"Custom prog can be set for `argparse.ArgumentParser`.\"\"\"\n assert parser._getparser().prog == os.path.basename(sys.argv[0])\n parser.prog = \"custom-prog\"\n assert parser._getparser().prog == \"custom-prog\"\n\n def test_argument(self):\n with pytest.raises(parseopt.ArgumentError):\n # need a short or long option\n argument = parseopt.Argument()\n argument = parseopt.Argument(\"-t\")\n assert argument._short_opts == [\"-t\"]\n assert argument._long_opts == []\n assert argument.dest == \"t\"\n argument = parseopt.Argument(\"-t\", \"--test\")\n assert argument._short_opts == [\"-t\"]\n assert argument._long_opts == [\"--test\"]\n assert argument.dest == \"test\"\n argument = parseopt.Argument(\"-t\", \"--test\", dest=\"abc\")\n assert argument.dest == \"abc\"\n assert str(argument) == (\n \"Argument(_short_opts: ['-t'], _long_opts: ['--test'], dest: 'abc')\"\n )\n\n def test_argument_type(self):\n argument = parseopt.Argument(\"-t\", dest=\"abc\", type=int)\n assert argument.type is int\n argument = parseopt.Argument(\"-t\", dest=\"abc\", type=str)\n assert argument.type is str\n argument = parseopt.Argument(\"-t\", dest=\"abc\", type=float)\n assert argument.type is float\n with pytest.warns(DeprecationWarning):\n with pytest.raises(KeyError):\n argument = parseopt.Argument(\"-t\", dest=\"abc\", type=\"choice\")\n argument = parseopt.Argument(\n \"-t\", dest=\"abc\", type=str, choices=[\"red\", \"blue\"]\n )\n assert argument.type is str\n\n def test_argument_processopt(self):\n argument = parseopt.Argument(\"-t\", type=int)\n argument.default = 42\n argument.dest = \"abc\"\n res = argument.attrs()\n assert res[\"default\"] == 42\n assert res[\"dest\"] == \"abc\"\n\n def test_group_add_and_get(self, parser):\n group = parser.getgroup(\"hello\", description=\"desc\")\n assert group.name == \"hello\"\n assert group.description == \"desc\"\n\n def test_getgroup_simple(self, parser):\n group = parser.getgroup(\"hello\", description=\"desc\")\n assert group.name == \"hello\"\n assert group.description == \"desc\"\n group2 = parser.getgroup(\"hello\")\n assert group2 is group\n\n def test_group_ordering(self, parser):\n parser.getgroup(\"1\")\n parser.getgroup(\"2\")\n parser.getgroup(\"3\", after=\"1\")\n groups = parser._groups\n groups_names = [x.name for x in groups]\n assert groups_names == list(\"132\")\n\n def test_group_addoption(self):\n group = parseopt.OptionGroup(\"hello\")\n group.addoption(\"--option1\", action=\"store_true\")\n assert len(group.options) == 1\n assert isinstance(group.options[0], parseopt.Argument)\n\n def test_group_addoption_conflict(self):\n group = parseopt.OptionGroup(\"hello again\")\n group.addoption(\"--option1\", \"--option-1\", action=\"store_true\")\n with pytest.raises(ValueError) as err:\n group.addoption(\"--option1\", \"--option-one\", action=\"store_true\")\n assert str({\"--option1\"}) in str(err.value)\n\n def test_group_shortopt_lowercase(self, parser):\n group = parser.getgroup(\"hello\")\n with pytest.raises(ValueError):\n group.addoption(\"-x\", action=\"store_true\")\n assert len(group.options) == 0\n group._addoption(\"-x\", action=\"store_true\")\n assert len(group.options) == 1\n\n def test_parser_addoption(self, parser):\n group = parser.getgroup(\"custom options\")\n assert len(group.options) == 0\n group.addoption(\"--option1\", action=\"store_true\")\n assert len(group.options) == 1\n\n def test_parse(self, parser):\n parser.addoption(\"--hello\", dest=\"hello\", action=\"store\")\n args = parser.parse([\"--hello\", \"world\"])\n assert args.hello == \"world\"\n assert not getattr(args, parseopt.FILE_OR_DIR)\n\n def test_parse2(self, parser):\n args = parser.parse([py.path.local()])\n assert getattr(args, parseopt.FILE_OR_DIR)[0] == py.path.local()\n\n def test_parse_known_args(self, parser):\n parser.parse_known_args([py.path.local()])\n parser.addoption(\"--hello\", action=\"store_true\")\n ns = parser.parse_known_args([\"x\", \"--y\", \"--hello\", \"this\"])\n assert ns.hello\n assert ns.file_or_dir == [\"x\"]\n\n def test_parse_known_and_unknown_args(self, parser):\n parser.addoption(\"--hello\", action=\"store_true\")\n ns, unknown = parser.parse_known_and_unknown_args(\n [\"x\", \"--y\", \"--hello\", \"this\"]\n )\n assert ns.hello\n assert ns.file_or_dir == [\"x\"]\n assert unknown == [\"--y\", \"this\"]\n\n def test_parse_will_set_default(self, parser):\n parser.addoption(\"--hello\", dest=\"hello\", default=\"x\", action=\"store\")\n option = parser.parse([])\n assert option.hello == \"x\"\n del option.hello\n parser.parse_setoption([], option)\n assert option.hello == \"x\"\n\n def test_parse_setoption(self, parser):\n parser.addoption(\"--hello\", dest=\"hello\", action=\"store\")\n parser.addoption(\"--world\", dest=\"world\", default=42)\n\n class A(object):\n pass\n\n option = A()\n args = parser.parse_setoption([\"--hello\", \"world\"], option)\n assert option.hello == \"world\"\n assert option.world == 42\n assert not args\n\n def test_parse_special_destination(self, parser):\n parser.addoption(\"--ultimate-answer\", type=int)\n args = parser.parse([\"--ultimate-answer\", \"42\"])\n assert args.ultimate_answer == 42\n\n def test_parse_split_positional_arguments(self, parser):\n parser.addoption(\"-R\", action=\"store_true\")\n parser.addoption(\"-S\", action=\"store_false\")\n args = parser.parse([\"-R\", \"4\", \"2\", \"-S\"])\n assert getattr(args, parseopt.FILE_OR_DIR) == [\"4\", \"2\"]\n args = parser.parse([\"-R\", \"-S\", \"4\", \"2\", \"-R\"])\n assert getattr(args, parseopt.FILE_OR_DIR) == [\"4\", \"2\"]\n assert args.R is True\n assert args.S is False\n args = parser.parse([\"-R\", \"4\", \"-S\", \"2\"])\n assert getattr(args, parseopt.FILE_OR_DIR) == [\"4\", \"2\"]\n assert args.R is True\n assert args.S is False\n\n def test_parse_defaultgetter(self):\n def defaultget(option):\n if not hasattr(option, \"type\"):\n return\n if option.type is int:\n option.default = 42\n elif option.type is str:\n option.default = \"world\"\n\n parser = parseopt.Parser(processopt=defaultget)\n parser.addoption(\"--this\", dest=\"this\", type=int, action=\"store\")\n parser.addoption(\"--hello\", dest=\"hello\", type=str, action=\"store\")\n parser.addoption(\"--no\", dest=\"no\", action=\"store_true\")\n option = parser.parse([])\n assert option.hello == \"world\"\n assert option.this == 42\n assert option.no is False\n\n def test_drop_short_helper(self):\n parser = argparse.ArgumentParser(\n formatter_class=parseopt.DropShorterLongHelpFormatter\n )\n parser.add_argument(\n \"-t\", \"--twoword\", \"--duo\", \"--two-word\", \"--two\", help=\"foo\"\n ).map_long_option = {\"two\": \"two-word\"}\n # throws error on --deux only!\n parser.add_argument(\n \"-d\", \"--deuxmots\", \"--deux-mots\", action=\"store_true\", help=\"foo\"\n ).map_long_option = {\"deux\": \"deux-mots\"}\n parser.add_argument(\"-s\", action=\"store_true\", help=\"single short\")\n parser.add_argument(\"--abc\", \"-a\", action=\"store_true\", help=\"bar\")\n parser.add_argument(\"--klm\", \"-k\", \"--kl-m\", action=\"store_true\", help=\"bar\")\n parser.add_argument(\n \"-P\", \"--pq-r\", \"-p\", \"--pqr\", action=\"store_true\", help=\"bar\"\n )\n parser.add_argument(\n \"--zwei-wort\", \"--zweiwort\", \"--zweiwort\", action=\"store_true\", help=\"bar\"\n )\n parser.add_argument(\n \"-x\", \"--exit-on-first\", \"--exitfirst\", action=\"store_true\", help=\"spam\"\n ).map_long_option = {\"exitfirst\": \"exit-on-first\"}\n parser.add_argument(\"files_and_dirs\", nargs=\"*\")\n args = parser.parse_args([\"-k\", \"--duo\", \"hallo\", \"--exitfirst\"])\n assert args.twoword == \"hallo\"\n assert args.klm is True\n assert args.zwei_wort is False\n assert args.exit_on_first is True\n assert args.s is False\n args = parser.parse_args([\"--deux-mots\"])\n with pytest.raises(AttributeError):\n assert args.deux_mots is True\n assert args.deuxmots is True\n args = parser.parse_args([\"file\", \"dir\"])\n assert \"|\".join(args.files_and_dirs) == \"file|dir\"\n\n def test_drop_short_0(self, parser):\n parser.addoption(\"--funcarg\", \"--func-arg\", action=\"store_true\")\n parser.addoption(\"--abc-def\", \"--abc-def\", action=\"store_true\")\n parser.addoption(\"--klm-hij\", action=\"store_true\")\n args = parser.parse([\"--funcarg\", \"--k\"])\n assert args.funcarg is True\n assert args.abc_def is False\n assert args.klm_hij is True\n\n def test_drop_short_2(self, parser):\n parser.addoption(\"--func-arg\", \"--doit\", action=\"store_true\")\n args = parser.parse([\"--doit\"])\n assert args.func_arg is True\n\n def test_drop_short_3(self, parser):\n parser.addoption(\"--func-arg\", \"--funcarg\", \"--doit\", action=\"store_true\")\n args = parser.parse([\"abcd\"])\n assert args.func_arg is False\n assert args.file_or_dir == [\"abcd\"]\n\n def test_drop_short_help0(self, parser, capsys):\n parser.addoption(\"--func-args\", \"--doit\", help=\"foo\", action=\"store_true\")\n parser.parse([])\n help = parser.optparser.format_help()\n assert \"--func-args, --doit foo\" in help\n\n # testing would be more helpful with all help generated\n def test_drop_short_help1(self, parser, capsys):\n group = parser.getgroup(\"general\")\n group.addoption(\"--doit\", \"--func-args\", action=\"store_true\", help=\"foo\")\n group._addoption(\n \"-h\",\n \"--help\",\n action=\"store_true\",\n dest=\"help\",\n help=\"show help message and configuration info\",\n )\n parser.parse([\"-h\"])\n help = parser.optparser.format_help()\n assert \"-doit, --func-args foo\" in help\n\n def test_multiple_metavar_help(self, parser):\n \"\"\"\n Help text for options with a metavar tuple should display help\n in the form \"--preferences=value1 value2 value3\" (#2004).\n \"\"\"\n group = parser.getgroup(\"general\")\n group.addoption(\n \"--preferences\", metavar=(\"value1\", \"value2\", \"value3\"), nargs=3\n )\n group._addoption(\"-h\", \"--help\", action=\"store_true\", dest=\"help\")\n parser.parse([\"-h\"])\n help = parser.optparser.format_help()\n assert \"--preferences=value1 value2 value3\" in help"},{"col":4,"comment":"null","endLoc":26,"header":"def test_no_help_by_default(self)","id":3809,"name":"test_no_help_by_default","nodeType":"Function","startLoc":24,"text":"def test_no_help_by_default(self):\n parser = parseopt.Parser(usage=\"xyz\")\n pytest.raises(UsageError, lambda: parser.parse([\"-h\"]))"},{"col":0,"comment":"null","endLoc":245,"header":"def test_setup_funcarg_setup_when_outer_scope_fails(testdir)","id":3810,"name":"test_setup_funcarg_setup_when_outer_scope_fails","nodeType":"Function","startLoc":220,"text":"def test_setup_funcarg_setup_when_outer_scope_fails(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def setup_module(mod):\n raise ValueError(42)\n @pytest.fixture\n def hello(request):\n raise ValueError(\"xyz43\")\n def test_function1(hello):\n pass\n def test_function2(hello):\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n \"*function1*\",\n \"*ValueError*42*\",\n \"*function2*\",\n \"*ValueError*42*\",\n \"*2 error*\",\n ]\n )\n assert \"xyz43\" not in result.stdout.str()"},{"col":4,"comment":"null","endLoc":818,"header":"def test_makeitem_non_underscore(self, testdir, monkeypatch)","id":3811,"name":"test_makeitem_non_underscore","nodeType":"Function","startLoc":811,"text":"def test_makeitem_non_underscore(self, testdir, monkeypatch):\n modcol = testdir.getmodulecol(\"def _hello(): pass\")\n values = []\n monkeypatch.setattr(\n pytest.Module, \"_makeitem\", lambda self, name, obj: values.append(name)\n )\n values = modcol.collect()\n assert \"_hello\" not in values"},{"col":0,"comment":"parameter to setup/teardown xunit-style functions parameter is now optional (#1728).","endLoc":300,"header":"@pytest.mark.parametrize(\"arg\", [\"\", \"arg\"])\ndef test_setup_teardown_function_level_with_optional_argument(\n testdir, monkeypatch, arg\n)","id":3812,"name":"test_setup_teardown_function_level_with_optional_argument","nodeType":"Function","startLoc":248,"text":"@pytest.mark.parametrize(\"arg\", [\"\", \"arg\"])\ndef test_setup_teardown_function_level_with_optional_argument(\n testdir, monkeypatch, arg\n):\n \"\"\"parameter to setup/teardown xunit-style functions parameter is now optional (#1728).\"\"\"\n import sys\n\n trace_setups_teardowns = []\n monkeypatch.setattr(\n sys, \"trace_setups_teardowns\", trace_setups_teardowns, raising=False\n )\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n import sys\n\n trace = sys.trace_setups_teardowns.append\n\n def setup_module({arg}): trace('setup_module')\n def teardown_module({arg}): trace('teardown_module')\n\n def setup_function({arg}): trace('setup_function')\n def teardown_function({arg}): trace('teardown_function')\n\n def test_function_1(): pass\n def test_function_2(): pass\n\n class Test(object):\n def setup_method(self, {arg}): trace('setup_method')\n def teardown_method(self, {arg}): trace('teardown_method')\n\n def test_method_1(self): pass\n def test_method_2(self): pass\n \"\"\".format(\n arg=arg\n )\n )\n result = testdir.inline_run(p)\n result.assertoutcome(passed=4)\n\n expected = [\n \"setup_module\",\n \"setup_function\",\n \"teardown_function\",\n \"setup_function\",\n \"teardown_function\",\n \"setup_method\",\n \"teardown_method\",\n \"setup_method\",\n \"teardown_method\",\n \"teardown_module\",\n ]\n assert trace_setups_teardowns == expected"},{"className":"TestDoctestSkips","col":0,"comment":"\n If all examples in a doctest are skipped due to the SKIP option, then\n the tests should be SKIPPED rather than PASSED. (#957)\n ","endLoc":933,"id":3813,"nodeType":"Class","startLoc":855,"text":"class TestDoctestSkips(object):\n \"\"\"\n If all examples in a doctest are skipped due to the SKIP option, then\n the tests should be SKIPPED rather than PASSED. (#957)\n \"\"\"\n\n @pytest.fixture(params=[\"text\", \"module\"])\n def makedoctest(self, testdir, request):\n def makeit(doctest):\n mode = request.param\n if mode == \"text\":\n testdir.maketxtfile(doctest)\n else:\n assert mode == \"module\"\n testdir.makepyfile('\"\"\"\\n%s\"\"\"' % doctest)\n\n return makeit\n\n def test_one_skipped(self, testdir, makedoctest):\n makedoctest(\n \"\"\"\n >>> 1 + 1 # doctest: +SKIP\n 2\n >>> 2 + 2\n 4\n \"\"\"\n )\n reprec = testdir.inline_run(\"--doctest-modules\")\n reprec.assertoutcome(passed=1)\n\n def test_one_skipped_failed(self, testdir, makedoctest):\n makedoctest(\n \"\"\"\n >>> 1 + 1 # doctest: +SKIP\n 2\n >>> 2 + 2\n 200\n \"\"\"\n )\n reprec = testdir.inline_run(\"--doctest-modules\")\n reprec.assertoutcome(failed=1)\n\n def test_all_skipped(self, testdir, makedoctest):\n makedoctest(\n \"\"\"\n >>> 1 + 1 # doctest: +SKIP\n 2\n >>> 2 + 2 # doctest: +SKIP\n 200\n \"\"\"\n )\n reprec = testdir.inline_run(\"--doctest-modules\")\n reprec.assertoutcome(skipped=1)\n\n def test_vacuous_all_skipped(self, testdir, makedoctest):\n makedoctest(\"\")\n reprec = testdir.inline_run(\"--doctest-modules\")\n reprec.assertoutcome(passed=0, skipped=0)\n\n def test_continue_on_failure(self, testdir):\n testdir.maketxtfile(\n test_something=\"\"\"\n >>> i = 5\n >>> def foo():\n ... raise ValueError('error1')\n >>> foo()\n >>> i\n >>> i + 2\n 7\n >>> i + 1\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\", \"--doctest-continue-on-failure\")\n result.assert_outcomes(passed=0, failed=1)\n # The lines that contains the failure are 4, 5, and 8. The first one\n # is a stack trace and the other two are mismatches.\n result.stdout.fnmatch_lines(\n [\"*4: UnexpectedException*\", \"*5: DocTestFailure*\", \"*8: DocTestFailure*\"]\n )"},{"fileName":"test_reports.py","filePath":"testing","id":3814,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\nfrom _pytest.pathlib import Path\nfrom _pytest.reports import CollectReport\nfrom _pytest.reports import TestReport\n\n\nclass TestReportSerialization(object):\n def test_xdist_longrepr_to_str_issue_241(self, testdir):\n \"\"\"\n Regarding issue pytest-xdist#241\n\n This test came originally from test_remote.py in xdist (ca03269).\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n def test_a(): assert False\n def test_b(): pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 6\n test_a_call = reports[1]\n assert test_a_call.when == \"call\"\n assert test_a_call.outcome == \"failed\"\n assert test_a_call._to_json()[\"longrepr\"][\"reprtraceback\"][\"style\"] == \"long\"\n test_b_call = reports[4]\n assert test_b_call.when == \"call\"\n assert test_b_call.outcome == \"passed\"\n assert test_b_call._to_json()[\"longrepr\"] is None\n\n def test_xdist_report_longrepr_reprcrash_130(self, testdir):\n \"\"\"Regarding issue pytest-xdist#130\n\n This test came originally from test_remote.py in xdist (ca03269).\n \"\"\"\n reprec = testdir.inline_runsource(\n \"\"\"\n def test_fail():\n assert False, 'Expected Message'\n \"\"\"\n )\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 3\n rep = reports[1]\n added_section = (\"Failure Metadata\", str(\"metadata metadata\"), \"*\")\n rep.longrepr.sections.append(added_section)\n d = rep._to_json()\n a = TestReport._from_json(d)\n # Check assembled == rep\n assert a.__dict__.keys() == rep.__dict__.keys()\n for key in rep.__dict__.keys():\n if key != \"longrepr\":\n assert getattr(a, key) == getattr(rep, key)\n assert rep.longrepr.reprcrash.lineno == a.longrepr.reprcrash.lineno\n assert rep.longrepr.reprcrash.message == a.longrepr.reprcrash.message\n assert rep.longrepr.reprcrash.path == a.longrepr.reprcrash.path\n assert rep.longrepr.reprtraceback.entrysep == a.longrepr.reprtraceback.entrysep\n assert (\n rep.longrepr.reprtraceback.extraline == a.longrepr.reprtraceback.extraline\n )\n assert rep.longrepr.reprtraceback.style == a.longrepr.reprtraceback.style\n assert rep.longrepr.sections == a.longrepr.sections\n # Missing section attribute PR171\n assert added_section in a.longrepr.sections\n\n def test_reprentries_serialization_170(self, testdir):\n \"\"\"Regarding issue pytest-xdist#170\n\n This test came originally from test_remote.py in xdist (ca03269).\n \"\"\"\n from _pytest._code.code import ReprEntry\n\n reprec = testdir.inline_runsource(\n \"\"\"\n def test_repr_entry():\n x = 0\n assert x\n \"\"\",\n \"--showlocals\",\n )\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 3\n rep = reports[1]\n d = rep._to_json()\n a = TestReport._from_json(d)\n\n rep_entries = rep.longrepr.reprtraceback.reprentries\n a_entries = a.longrepr.reprtraceback.reprentries\n for i in range(len(a_entries)):\n assert isinstance(rep_entries[i], ReprEntry)\n assert rep_entries[i].lines == a_entries[i].lines\n assert rep_entries[i].reprfileloc.lineno == a_entries[i].reprfileloc.lineno\n assert (\n rep_entries[i].reprfileloc.message == a_entries[i].reprfileloc.message\n )\n assert rep_entries[i].reprfileloc.path == a_entries[i].reprfileloc.path\n assert rep_entries[i].reprfuncargs.args == a_entries[i].reprfuncargs.args\n assert rep_entries[i].reprlocals.lines == a_entries[i].reprlocals.lines\n assert rep_entries[i].style == a_entries[i].style\n\n def test_reprentries_serialization_196(self, testdir):\n \"\"\"Regarding issue pytest-xdist#196\n\n This test came originally from test_remote.py in xdist (ca03269).\n \"\"\"\n from _pytest._code.code import ReprEntryNative\n\n reprec = testdir.inline_runsource(\n \"\"\"\n def test_repr_entry_native():\n x = 0\n assert x\n \"\"\",\n \"--tb=native\",\n )\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 3\n rep = reports[1]\n d = rep._to_json()\n a = TestReport._from_json(d)\n\n rep_entries = rep.longrepr.reprtraceback.reprentries\n a_entries = a.longrepr.reprtraceback.reprentries\n for i in range(len(a_entries)):\n assert isinstance(rep_entries[i], ReprEntryNative)\n assert rep_entries[i].lines == a_entries[i].lines\n\n def test_itemreport_outcomes(self, testdir):\n \"\"\"\n This test came originally from test_remote.py in xdist (ca03269).\n \"\"\"\n reprec = testdir.inline_runsource(\n \"\"\"\n import py\n def test_pass(): pass\n def test_fail(): 0/0\n @py.test.mark.skipif(\"True\")\n def test_skip(): pass\n def test_skip_imperative():\n py.test.skip(\"hello\")\n @py.test.mark.xfail(\"True\")\n def test_xfail(): 0/0\n def test_xfail_imperative():\n py.test.xfail(\"hello\")\n \"\"\"\n )\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 17 # with setup/teardown \"passed\" reports\n for rep in reports:\n d = rep._to_json()\n newrep = TestReport._from_json(d)\n assert newrep.passed == rep.passed\n assert newrep.failed == rep.failed\n assert newrep.skipped == rep.skipped\n if newrep.skipped and not hasattr(newrep, \"wasxfail\"):\n assert len(newrep.longrepr) == 3\n assert newrep.outcome == rep.outcome\n assert newrep.when == rep.when\n assert newrep.keywords == rep.keywords\n if rep.failed:\n assert newrep.longreprtext == rep.longreprtext\n\n def test_collectreport_passed(self, testdir):\n \"\"\"This test came originally from test_remote.py in xdist (ca03269).\"\"\"\n reprec = testdir.inline_runsource(\"def test_func(): pass\")\n reports = reprec.getreports(\"pytest_collectreport\")\n for rep in reports:\n d = rep._to_json()\n newrep = CollectReport._from_json(d)\n assert newrep.passed == rep.passed\n assert newrep.failed == rep.failed\n assert newrep.skipped == rep.skipped\n\n def test_collectreport_fail(self, testdir):\n \"\"\"This test came originally from test_remote.py in xdist (ca03269).\"\"\"\n reprec = testdir.inline_runsource(\"qwe abc\")\n reports = reprec.getreports(\"pytest_collectreport\")\n assert reports\n for rep in reports:\n d = rep._to_json()\n newrep = CollectReport._from_json(d)\n assert newrep.passed == rep.passed\n assert newrep.failed == rep.failed\n assert newrep.skipped == rep.skipped\n if rep.failed:\n assert newrep.longrepr == str(rep.longrepr)\n\n def test_extended_report_deserialization(self, testdir):\n \"\"\"This test came originally from test_remote.py in xdist (ca03269).\"\"\"\n reprec = testdir.inline_runsource(\"qwe abc\")\n reports = reprec.getreports(\"pytest_collectreport\")\n assert reports\n for rep in reports:\n rep.extra = True\n d = rep._to_json()\n newrep = CollectReport._from_json(d)\n assert newrep.extra\n assert newrep.passed == rep.passed\n assert newrep.failed == rep.failed\n assert newrep.skipped == rep.skipped\n if rep.failed:\n assert newrep.longrepr == str(rep.longrepr)\n\n def test_paths_support(self, testdir):\n \"\"\"Report attributes which are py.path or pathlib objects should become strings.\"\"\"\n testdir.makepyfile(\n \"\"\"\n def test_a():\n assert False\n \"\"\"\n )\n reprec = testdir.inline_run()\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 3\n test_a_call = reports[1]\n test_a_call.path1 = testdir.tmpdir\n test_a_call.path2 = Path(testdir.tmpdir)\n data = test_a_call._to_json()\n assert data[\"path1\"] == str(testdir.tmpdir)\n assert data[\"path2\"] == str(testdir.tmpdir)\n\n def test_unserialization_failure(self, testdir):\n \"\"\"Check handling of failure during unserialization of report types.\"\"\"\n testdir.makepyfile(\n \"\"\"\n def test_a():\n assert False\n \"\"\"\n )\n reprec = testdir.inline_run()\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 3\n test_a_call = reports[1]\n data = test_a_call._to_json()\n entry = data[\"longrepr\"][\"reprtraceback\"][\"reprentries\"][0]\n assert entry[\"type\"] == \"ReprEntry\"\n\n entry[\"type\"] = \"Unknown\"\n with pytest.raises(\n RuntimeError, match=\"INTERNALERROR: Unknown entry type returned: Unknown\"\n ):\n TestReport._from_json(data)\n\n\nclass TestHooks:\n \"\"\"Test that the hooks are working correctly for plugins\"\"\"\n\n def test_test_report(self, testdir, pytestconfig):\n testdir.makepyfile(\n \"\"\"\n def test_a(): assert False\n def test_b(): pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 6\n for rep in reports:\n data = pytestconfig.hook.pytest_report_to_serializable(\n config=pytestconfig, report=rep\n )\n assert data[\"_report_type\"] == \"TestReport\"\n new_rep = pytestconfig.hook.pytest_report_from_serializable(\n config=pytestconfig, data=data\n )\n assert new_rep.nodeid == rep.nodeid\n assert new_rep.when == rep.when\n assert new_rep.outcome == rep.outcome\n\n def test_collect_report(self, testdir, pytestconfig):\n testdir.makepyfile(\n \"\"\"\n def test_a(): assert False\n def test_b(): pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reports = reprec.getreports(\"pytest_collectreport\")\n assert len(reports) == 2\n for rep in reports:\n data = pytestconfig.hook.pytest_report_to_serializable(\n config=pytestconfig, report=rep\n )\n assert data[\"_report_type\"] == \"CollectReport\"\n new_rep = pytestconfig.hook.pytest_report_from_serializable(\n config=pytestconfig, data=data\n )\n assert new_rep.nodeid == rep.nodeid\n assert new_rep.when == \"collect\"\n assert new_rep.outcome == rep.outcome\n\n @pytest.mark.parametrize(\n \"hook_name\", [\"pytest_runtest_logreport\", \"pytest_collectreport\"]\n )\n def test_invalid_report_types(self, testdir, pytestconfig, hook_name):\n testdir.makepyfile(\n \"\"\"\n def test_a(): pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reports = reprec.getreports(hook_name)\n assert reports\n rep = reports[0]\n data = pytestconfig.hook.pytest_report_to_serializable(\n config=pytestconfig, report=rep\n )\n data[\"_report_type\"] = \"Unknown\"\n with pytest.raises(AssertionError):\n _ = pytestconfig.hook.pytest_report_from_serializable(\n config=pytestconfig, data=data\n )\n"},{"col":4,"comment":"null","endLoc":871,"header":"@pytest.fixture(params=[\"text\", \"module\"])\n def makedoctest(self, testdir, request)","id":3815,"name":"makedoctest","nodeType":"Function","startLoc":861,"text":"@pytest.fixture(params=[\"text\", \"module\"])\n def makedoctest(self, testdir, request):\n def makeit(doctest):\n mode = request.param\n if mode == \"text\":\n testdir.maketxtfile(doctest)\n else:\n assert mode == \"module\"\n testdir.makepyfile('\"\"\"\\n%s\"\"\"' % doctest)\n\n return makeit"},{"col":34,"endLoc":26,"id":3816,"nodeType":"Lambda","startLoc":26,"text":"lambda: parser.parse([\"-h\"])"},{"col":4,"comment":"Custom prog can be set for `argparse.ArgumentParser`.","endLoc":32,"header":"def test_custom_prog(self, parser)","id":3817,"name":"test_custom_prog","nodeType":"Function","startLoc":28,"text":"def test_custom_prog(self, parser):\n \"\"\"Custom prog can be set for `argparse.ArgumentParser`.\"\"\"\n assert parser._getparser().prog == os.path.basename(sys.argv[0])\n parser.prog = \"custom-prog\"\n assert parser._getparser().prog == \"custom-prog\""},{"className":"CollectReport","col":0,"comment":"null","endLoc":409,"id":3818,"nodeType":"Class","startLoc":389,"text":"class CollectReport(BaseReport):\n when = \"collect\"\n\n def __init__(self, nodeid, outcome, longrepr, result, sections=(), **extra):\n self.nodeid = nodeid\n self.outcome = outcome\n self.longrepr = longrepr\n self.result = result or []\n self.sections = list(sections)\n self.__dict__.update(extra)\n\n @property\n def location(self):\n return (self.fspath, None, self.fspath)\n\n def __repr__(self):\n return \"\" % (\n self.nodeid,\n len(self.result),\n self.outcome,\n )"},{"fileName":"test_session.py","filePath":"testing","id":3819,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pytest\nfrom _pytest.main import EXIT_NOTESTSCOLLECTED\n\n\nclass SessionTests(object):\n def test_basic_testitem_events(self, testdir):\n tfile = testdir.makepyfile(\n \"\"\"\n def test_one():\n pass\n def test_one_one():\n assert 0\n def test_other():\n raise ValueError(23)\n class TestClass(object):\n def test_two(self, someargs):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(tfile)\n passed, skipped, failed = reprec.listoutcomes()\n assert len(skipped) == 0\n assert len(passed) == 1\n assert len(failed) == 3\n\n def end(x):\n return x.nodeid.split(\"::\")[-1]\n\n assert end(failed[0]) == \"test_one_one\"\n assert end(failed[1]) == \"test_other\"\n itemstarted = reprec.getcalls(\"pytest_itemcollected\")\n assert len(itemstarted) == 4\n # XXX check for failing funcarg setup\n # colreports = reprec.getcalls(\"pytest_collectreport\")\n # assert len(colreports) == 4\n # assert colreports[1].report.failed\n\n def test_nested_import_error(self, testdir):\n tfile = testdir.makepyfile(\n \"\"\"\n import import_fails\n def test_this():\n assert import_fails.a == 1\n \"\"\",\n import_fails=\"\"\"\n import does_not_work\n a = 1\n \"\"\",\n )\n reprec = testdir.inline_run(tfile)\n values = reprec.getfailedcollections()\n assert len(values) == 1\n out = str(values[0].longrepr)\n assert out.find(\"does_not_work\") != -1\n\n def test_raises_output(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n import pytest\n def test_raises_doesnt():\n pytest.raises(ValueError, int, \"3\")\n \"\"\"\n )\n passed, skipped, failed = reprec.listoutcomes()\n assert len(failed) == 1\n out = failed[0].longrepr.reprcrash.message\n assert \"DID NOT RAISE\" in out\n\n def test_syntax_error_module(self, testdir):\n reprec = testdir.inline_runsource(\"this is really not python\")\n values = reprec.getfailedcollections()\n assert len(values) == 1\n out = str(values[0].longrepr)\n assert out.find(str(\"not python\")) != -1\n\n def test_exit_first_problem(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n def test_one(): assert 0\n def test_two(): assert 0\n \"\"\",\n \"--exitfirst\",\n )\n passed, skipped, failed = reprec.countoutcomes()\n assert failed == 1\n assert passed == skipped == 0\n\n def test_maxfail(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n def test_one(): assert 0\n def test_two(): assert 0\n def test_three(): assert 0\n \"\"\",\n \"--maxfail=2\",\n )\n passed, skipped, failed = reprec.countoutcomes()\n assert failed == 2\n assert passed == skipped == 0\n\n def test_broken_repr(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n class BrokenRepr1(object):\n foo=0\n def __repr__(self):\n raise Exception(\"Ha Ha fooled you, I'm a broken repr().\")\n\n class TestBrokenClass(object):\n def test_explicit_bad_repr(self):\n t = BrokenRepr1()\n with pytest.raises(Exception, match=\"I'm a broken repr\"):\n repr(t)\n\n def test_implicit_bad_repr1(self):\n t = BrokenRepr1()\n assert t.foo == 1\n\n \"\"\"\n )\n reprec = testdir.inline_run(p)\n passed, skipped, failed = reprec.listoutcomes()\n assert (len(passed), len(skipped), len(failed)) == (1, 0, 1)\n out = failed[0].longrepr.reprcrash.message\n assert (\n out.find(\n \"\"\"[Exception(\"Ha Ha fooled you, I'm a broken repr().\") raised in repr()]\"\"\"\n )\n != -1\n )\n\n def test_broken_repr_with_showlocals_verbose(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n class ObjWithErrorInRepr:\n def __repr__(self):\n raise NotImplementedError\n\n def test_repr_error():\n x = ObjWithErrorInRepr()\n assert x == \"value\"\n \"\"\"\n )\n reprec = testdir.inline_run(\"--showlocals\", \"-vv\", p)\n passed, skipped, failed = reprec.listoutcomes()\n assert (len(passed), len(skipped), len(failed)) == (0, 0, 1)\n entries = failed[0].longrepr.reprtraceback.reprentries\n assert len(entries) == 1\n repr_locals = entries[0].reprlocals\n assert repr_locals.lines\n assert len(repr_locals.lines) == 1\n assert repr_locals.lines[0].startswith(\n 'x = <[NotImplementedError(\"\") raised in repr()] ObjWithErrorInRepr'\n )\n\n def test_skip_file_by_conftest(self, testdir):\n testdir.makepyfile(\n conftest=\"\"\"\n import pytest\n def pytest_collect_file():\n pytest.skip(\"intentional\")\n \"\"\",\n test_file=\"\"\"\n def test_one(): pass\n \"\"\",\n )\n try:\n reprec = testdir.inline_run(testdir.tmpdir)\n except pytest.skip.Exception: # pragma: no cover\n pytest.fail(\"wrong skipped caught\")\n reports = reprec.getreports(\"pytest_collectreport\")\n assert len(reports) == 1\n assert reports[0].skipped\n\n\nclass TestNewSession(SessionTests):\n def test_order_of_execution(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n values = []\n def test_1():\n values.append(1)\n def test_2():\n values.append(2)\n def test_3():\n assert values == [1,2]\n class Testmygroup(object):\n reslist = values\n def test_1(self):\n self.reslist.append(1)\n def test_2(self):\n self.reslist.append(2)\n def test_3(self):\n self.reslist.append(3)\n def test_4(self):\n assert self.reslist == [1,2,1,2,3]\n \"\"\"\n )\n passed, skipped, failed = reprec.countoutcomes()\n assert failed == skipped == 0\n assert passed == 7\n\n def test_collect_only_with_various_situations(self, testdir):\n p = testdir.makepyfile(\n test_one=\"\"\"\n def test_one():\n raise ValueError()\n\n class TestX(object):\n def test_method_one(self):\n pass\n\n class TestY(TestX):\n pass\n \"\"\",\n test_three=\"xxxdsadsadsadsa\",\n __init__=\"\",\n )\n reprec = testdir.inline_run(\"--collect-only\", p.dirpath())\n\n itemstarted = reprec.getcalls(\"pytest_itemcollected\")\n assert len(itemstarted) == 3\n assert not reprec.getreports(\"pytest_runtest_logreport\")\n started = reprec.getcalls(\"pytest_collectstart\")\n finished = reprec.getreports(\"pytest_collectreport\")\n assert len(started) == len(finished)\n assert len(started) == 8\n colfail = [x for x in finished if x.failed]\n assert len(colfail) == 1\n\n def test_minus_x_import_error(self, testdir):\n testdir.makepyfile(__init__=\"\")\n testdir.makepyfile(test_one=\"xxxx\", test_two=\"yyyy\")\n reprec = testdir.inline_run(\"-x\", testdir.tmpdir)\n finished = reprec.getreports(\"pytest_collectreport\")\n colfail = [x for x in finished if x.failed]\n assert len(colfail) == 1\n\n def test_minus_x_overridden_by_maxfail(self, testdir):\n testdir.makepyfile(__init__=\"\")\n testdir.makepyfile(test_one=\"xxxx\", test_two=\"yyyy\", test_third=\"zzz\")\n reprec = testdir.inline_run(\"-x\", \"--maxfail=2\", testdir.tmpdir)\n finished = reprec.getreports(\"pytest_collectreport\")\n colfail = [x for x in finished if x.failed]\n assert len(colfail) == 2\n\n\ndef test_plugin_specify(testdir):\n with pytest.raises(ImportError):\n testdir.parseconfig(\"-p\", \"nqweotexistent\")\n # pytest.raises(ImportError,\n # \"config.do_configure(config)\"\n # )\n\n\ndef test_plugin_already_exists(testdir):\n config = testdir.parseconfig(\"-p\", \"terminal\")\n assert config.option.plugins == [\"terminal\"]\n config._do_configure()\n config._ensure_unconfigure()\n\n\ndef test_exclude(testdir):\n hellodir = testdir.mkdir(\"hello\")\n hellodir.join(\"test_hello.py\").write(\"x y syntaxerror\")\n hello2dir = testdir.mkdir(\"hello2\")\n hello2dir.join(\"test_hello2.py\").write(\"x y syntaxerror\")\n testdir.makepyfile(test_ok=\"def test_pass(): pass\")\n result = testdir.runpytest(\"--ignore=hello\", \"--ignore=hello2\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_exclude_glob(testdir):\n hellodir = testdir.mkdir(\"hello\")\n hellodir.join(\"test_hello.py\").write(\"x y syntaxerror\")\n hello2dir = testdir.mkdir(\"hello2\")\n hello2dir.join(\"test_hello2.py\").write(\"x y syntaxerror\")\n hello3dir = testdir.mkdir(\"hallo3\")\n hello3dir.join(\"test_hello3.py\").write(\"x y syntaxerror\")\n subdir = testdir.mkdir(\"sub\")\n subdir.join(\"test_hello4.py\").write(\"x y syntaxerror\")\n testdir.makepyfile(test_ok=\"def test_pass(): pass\")\n result = testdir.runpytest(\"--ignore-glob=*h[ea]llo*\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_deselect(testdir):\n testdir.makepyfile(\n test_a=\"\"\"\n import pytest\n\n def test_a1(): pass\n\n @pytest.mark.parametrize('b', range(3))\n def test_a2(b): pass\n\n class TestClass:\n def test_c1(self): pass\n\n def test_c2(self): pass\n \"\"\"\n )\n result = testdir.runpytest(\n \"-v\",\n \"--deselect=test_a.py::test_a2[1]\",\n \"--deselect=test_a.py::test_a2[2]\",\n \"--deselect=test_a.py::TestClass::test_c1\",\n )\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*3 passed, 3 deselected*\"])\n for line in result.stdout.lines:\n assert not line.startswith((\"test_a.py::test_a2[1]\", \"test_a.py::test_a2[2]\"))\n\n\ndef test_sessionfinish_with_start(testdir):\n testdir.makeconftest(\n \"\"\"\n import os\n values = []\n def pytest_sessionstart():\n values.append(os.getcwd())\n os.chdir(\"..\")\n\n def pytest_sessionfinish():\n assert values[0] == os.getcwd()\n\n \"\"\"\n )\n res = testdir.runpytest(\"--collect-only\")\n assert res.ret == EXIT_NOTESTSCOLLECTED\n\n\n@pytest.mark.parametrize(\"path\", [\"root\", \"{relative}/root\", \"{environment}/root\"])\ndef test_rootdir_option_arg(testdir, monkeypatch, path):\n monkeypatch.setenv(\"PY_ROOTDIR_PATH\", str(testdir.tmpdir))\n path = path.format(relative=str(testdir.tmpdir), environment=\"$PY_ROOTDIR_PATH\")\n\n rootdir = testdir.mkdir(\"root\")\n rootdir.mkdir(\"tests\")\n testdir.makepyfile(\n \"\"\"\n import os\n def test_one():\n assert 1\n \"\"\"\n )\n\n result = testdir.runpytest(\"--rootdir={}\".format(path))\n result.stdout.fnmatch_lines(\n [\n \"*rootdir: {}/root\".format(testdir.tmpdir),\n \"root/test_rootdir_option_arg.py *\",\n \"*1 passed*\",\n ]\n )\n\n\ndef test_rootdir_wrong_option_arg(testdir):\n testdir.makepyfile(\n \"\"\"\n import os\n def test_one():\n assert 1\n \"\"\"\n )\n\n result = testdir.runpytest(\"--rootdir=wrong_dir\")\n result.stderr.fnmatch_lines(\n [\"*Directory *wrong_dir* not found. Check your '--rootdir' option.*\"]\n )\n"},{"className":"SessionTests","col":0,"comment":"null","endLoc":179,"id":3820,"nodeType":"Class","startLoc":10,"text":"class SessionTests(object):\n def test_basic_testitem_events(self, testdir):\n tfile = testdir.makepyfile(\n \"\"\"\n def test_one():\n pass\n def test_one_one():\n assert 0\n def test_other():\n raise ValueError(23)\n class TestClass(object):\n def test_two(self, someargs):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(tfile)\n passed, skipped, failed = reprec.listoutcomes()\n assert len(skipped) == 0\n assert len(passed) == 1\n assert len(failed) == 3\n\n def end(x):\n return x.nodeid.split(\"::\")[-1]\n\n assert end(failed[0]) == \"test_one_one\"\n assert end(failed[1]) == \"test_other\"\n itemstarted = reprec.getcalls(\"pytest_itemcollected\")\n assert len(itemstarted) == 4\n # XXX check for failing funcarg setup\n # colreports = reprec.getcalls(\"pytest_collectreport\")\n # assert len(colreports) == 4\n # assert colreports[1].report.failed\n\n def test_nested_import_error(self, testdir):\n tfile = testdir.makepyfile(\n \"\"\"\n import import_fails\n def test_this():\n assert import_fails.a == 1\n \"\"\",\n import_fails=\"\"\"\n import does_not_work\n a = 1\n \"\"\",\n )\n reprec = testdir.inline_run(tfile)\n values = reprec.getfailedcollections()\n assert len(values) == 1\n out = str(values[0].longrepr)\n assert out.find(\"does_not_work\") != -1\n\n def test_raises_output(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n import pytest\n def test_raises_doesnt():\n pytest.raises(ValueError, int, \"3\")\n \"\"\"\n )\n passed, skipped, failed = reprec.listoutcomes()\n assert len(failed) == 1\n out = failed[0].longrepr.reprcrash.message\n assert \"DID NOT RAISE\" in out\n\n def test_syntax_error_module(self, testdir):\n reprec = testdir.inline_runsource(\"this is really not python\")\n values = reprec.getfailedcollections()\n assert len(values) == 1\n out = str(values[0].longrepr)\n assert out.find(str(\"not python\")) != -1\n\n def test_exit_first_problem(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n def test_one(): assert 0\n def test_two(): assert 0\n \"\"\",\n \"--exitfirst\",\n )\n passed, skipped, failed = reprec.countoutcomes()\n assert failed == 1\n assert passed == skipped == 0\n\n def test_maxfail(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n def test_one(): assert 0\n def test_two(): assert 0\n def test_three(): assert 0\n \"\"\",\n \"--maxfail=2\",\n )\n passed, skipped, failed = reprec.countoutcomes()\n assert failed == 2\n assert passed == skipped == 0\n\n def test_broken_repr(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n class BrokenRepr1(object):\n foo=0\n def __repr__(self):\n raise Exception(\"Ha Ha fooled you, I'm a broken repr().\")\n\n class TestBrokenClass(object):\n def test_explicit_bad_repr(self):\n t = BrokenRepr1()\n with pytest.raises(Exception, match=\"I'm a broken repr\"):\n repr(t)\n\n def test_implicit_bad_repr1(self):\n t = BrokenRepr1()\n assert t.foo == 1\n\n \"\"\"\n )\n reprec = testdir.inline_run(p)\n passed, skipped, failed = reprec.listoutcomes()\n assert (len(passed), len(skipped), len(failed)) == (1, 0, 1)\n out = failed[0].longrepr.reprcrash.message\n assert (\n out.find(\n \"\"\"[Exception(\"Ha Ha fooled you, I'm a broken repr().\") raised in repr()]\"\"\"\n )\n != -1\n )\n\n def test_broken_repr_with_showlocals_verbose(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n class ObjWithErrorInRepr:\n def __repr__(self):\n raise NotImplementedError\n\n def test_repr_error():\n x = ObjWithErrorInRepr()\n assert x == \"value\"\n \"\"\"\n )\n reprec = testdir.inline_run(\"--showlocals\", \"-vv\", p)\n passed, skipped, failed = reprec.listoutcomes()\n assert (len(passed), len(skipped), len(failed)) == (0, 0, 1)\n entries = failed[0].longrepr.reprtraceback.reprentries\n assert len(entries) == 1\n repr_locals = entries[0].reprlocals\n assert repr_locals.lines\n assert len(repr_locals.lines) == 1\n assert repr_locals.lines[0].startswith(\n 'x = <[NotImplementedError(\"\") raised in repr()] ObjWithErrorInRepr'\n )\n\n def test_skip_file_by_conftest(self, testdir):\n testdir.makepyfile(\n conftest=\"\"\"\n import pytest\n def pytest_collect_file():\n pytest.skip(\"intentional\")\n \"\"\",\n test_file=\"\"\"\n def test_one(): pass\n \"\"\",\n )\n try:\n reprec = testdir.inline_run(testdir.tmpdir)\n except pytest.skip.Exception: # pragma: no cover\n pytest.fail(\"wrong skipped caught\")\n reports = reprec.getreports(\"pytest_collectreport\")\n assert len(reports) == 1\n assert reports[0].skipped"},{"col":4,"comment":"null","endLoc":41,"header":"def test_basic_testitem_events(self, testdir)","id":3821,"name":"test_basic_testitem_events","nodeType":"Function","startLoc":11,"text":"def test_basic_testitem_events(self, testdir):\n tfile = testdir.makepyfile(\n \"\"\"\n def test_one():\n pass\n def test_one_one():\n assert 0\n def test_other():\n raise ValueError(23)\n class TestClass(object):\n def test_two(self, someargs):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(tfile)\n passed, skipped, failed = reprec.listoutcomes()\n assert len(skipped) == 0\n assert len(passed) == 1\n assert len(failed) == 3\n\n def end(x):\n return x.nodeid.split(\"::\")[-1]\n\n assert end(failed[0]) == \"test_one_one\"\n assert end(failed[1]) == \"test_other\"\n itemstarted = reprec.getcalls(\"pytest_itemcollected\")\n assert len(itemstarted) == 4\n # XXX check for failing funcarg setup\n # colreports = reprec.getcalls(\"pytest_collectreport\")\n # assert len(colreports) == 4\n # assert colreports[1].report.failed"},{"col":4,"comment":"null","endLoc":50,"header":"def test_argument(self)","id":3822,"name":"test_argument","nodeType":"Function","startLoc":34,"text":"def test_argument(self):\n with pytest.raises(parseopt.ArgumentError):\n # need a short or long option\n argument = parseopt.Argument()\n argument = parseopt.Argument(\"-t\")\n assert argument._short_opts == [\"-t\"]\n assert argument._long_opts == []\n assert argument.dest == \"t\"\n argument = parseopt.Argument(\"-t\", \"--test\")\n assert argument._short_opts == [\"-t\"]\n assert argument._long_opts == [\"--test\"]\n assert argument.dest == \"test\"\n argument = parseopt.Argument(\"-t\", \"--test\", dest=\"abc\")\n assert argument.dest == \"abc\"\n assert str(argument) == (\n \"Argument(_short_opts: ['-t'], _long_opts: ['--test'], dest: 'abc')\"\n )"},{"col":4,"comment":"store parms in private vars for use in add_argument","endLoc":221,"header":"def __init__(self, *names, **attrs)","id":3824,"name":"__init__","nodeType":"Function","startLoc":163,"text":"def __init__(self, *names, **attrs):\n \"\"\"store parms in private vars for use in add_argument\"\"\"\n self._attrs = attrs\n self._short_opts = []\n self._long_opts = []\n self.dest = attrs.get(\"dest\")\n if \"%default\" in (attrs.get(\"help\") or \"\"):\n warnings.warn(\n 'pytest now uses argparse. \"%default\" should be'\n ' changed to \"%(default)s\" ',\n DeprecationWarning,\n stacklevel=3,\n )\n try:\n typ = attrs[\"type\"]\n except KeyError:\n pass\n else:\n # this might raise a keyerror as well, don't want to catch that\n if isinstance(typ, six.string_types):\n if typ == \"choice\":\n warnings.warn(\n \"`type` argument to addoption() is the string %r.\"\n \" For choices this is optional and can be omitted, \"\n \" but when supplied should be a type (for example `str` or `int`).\"\n \" (options: %s)\" % (typ, names),\n DeprecationWarning,\n stacklevel=4,\n )\n # argparse expects a type here take it from\n # the type of the first element\n attrs[\"type\"] = type(attrs[\"choices\"][0])\n else:\n warnings.warn(\n \"`type` argument to addoption() is the string %r, \"\n \" but when supplied should be a type (for example `str` or `int`).\"\n \" (options: %s)\" % (typ, names),\n DeprecationWarning,\n stacklevel=4,\n )\n attrs[\"type\"] = Argument._typ_map[typ]\n # used in test_parseopt -> test_parse_defaultgetter\n self.type = attrs[\"type\"]\n else:\n self.type = typ\n try:\n # attribute existence is tested in Config._processopt\n self.default = attrs[\"default\"]\n except KeyError:\n pass\n self._set_opt_strings(names)\n if not self.dest:\n if self._long_opts:\n self.dest = self._long_opts[0][2:].replace(\"-\", \"_\")\n else:\n try:\n self.dest = self._short_opts[0][1:]\n except IndexError:\n raise ArgumentError(\"need a long or short option\", self)"},{"col":0,"comment":"","endLoc":5,"header":"test_runner_xunit.py#","id":3825,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"\n test correct setup/teardowns at\n module, class, and instance level\n\"\"\""},{"col":4,"comment":"null","endLoc":59,"header":"def test_nested_import_error(self, testdir)","id":3826,"name":"test_nested_import_error","nodeType":"Function","startLoc":43,"text":"def test_nested_import_error(self, testdir):\n tfile = testdir.makepyfile(\n \"\"\"\n import import_fails\n def test_this():\n assert import_fails.a == 1\n \"\"\",\n import_fails=\"\"\"\n import does_not_work\n a = 1\n \"\"\",\n )\n reprec = testdir.inline_run(tfile)\n values = reprec.getfailedcollections()\n assert len(values) == 1\n out = str(values[0].longrepr)\n assert out.find(\"does_not_work\") != -1"},{"id":3827,"name":"release-2.7.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.7.2: bug fixes\n=======================\n\npytest is a mature Python testing tool with more than a 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is supposed to be drop-in compatible to 2.7.1.\n\nSee below for the changes and see docs at:\n\n http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n Bruno Oliveira\n Floris Bruynooghe\n Punyashloka Biswal\n Aron Curzon\n Benjamin Peterson\n Thomas De Schampheleire\n Edison Gustavo Muenz\n Holger Krekel\n\nHappy testing,\nThe py.test Development Team\n\n\n2.7.2 (compared to 2.7.1)\n-----------------------------\n\n- fix issue767: pytest.raises value attribute does not contain the exception\n instance on Python 2.6. Thanks Eric Siegerman for providing the test\n case and Bruno Oliveira for PR.\n\n- Automatically create directory for junitxml and results log.\n Thanks Aron Curzon.\n\n- fix issue713: JUnit XML reports for doctest failures.\n Thanks Punyashloka Biswal.\n\n- fix issue735: assertion failures on debug versions of Python 3.4+\n Thanks Benjamin Peterson.\n\n- fix issue114: skipif marker reports to internal skipping plugin;\n Thanks Floris Bruynooghe for reporting and Bruno Oliveira for the PR.\n\n- fix issue748: unittest.SkipTest reports to internal pytest unittest plugin.\n Thanks Thomas De Schampheleire for reporting and Bruno Oliveira for the PR.\n\n- fix issue718: failed to create representation of sets containing unsortable\n elements in python 2. Thanks Edison Gustavo Muenz\n\n- fix issue756, fix issue752 (and similar issues): depend on py-1.4.29\n which has a refined algorithm for traceback generation.\n"},{"fileName":"resultlog.py","filePath":"src/_pytest","id":3828,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\" log machine-parseable test session result information in a plain\ntext file.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nimport py\n\n\ndef pytest_addoption(parser):\n group = parser.getgroup(\"terminal reporting\", \"resultlog plugin options\")\n group.addoption(\n \"--resultlog\",\n \"--result-log\",\n action=\"store\",\n metavar=\"path\",\n default=None,\n help=\"DEPRECATED path for machine-readable result log.\",\n )\n\n\ndef pytest_configure(config):\n resultlog = config.option.resultlog\n # prevent opening resultlog on slave nodes (xdist)\n if resultlog and not hasattr(config, \"slaveinput\"):\n dirname = os.path.dirname(os.path.abspath(resultlog))\n if not os.path.isdir(dirname):\n os.makedirs(dirname)\n logfile = open(resultlog, \"w\", 1) # line buffered\n config._resultlog = ResultLog(config, logfile)\n config.pluginmanager.register(config._resultlog)\n\n from _pytest.deprecated import RESULT_LOG\n from _pytest.warnings import _issue_warning_captured\n\n _issue_warning_captured(RESULT_LOG, config.hook, stacklevel=2)\n\n\ndef pytest_unconfigure(config):\n resultlog = getattr(config, \"_resultlog\", None)\n if resultlog:\n resultlog.logfile.close()\n del config._resultlog\n config.pluginmanager.unregister(resultlog)\n\n\nclass ResultLog(object):\n def __init__(self, config, logfile):\n self.config = config\n self.logfile = logfile # preferably line buffered\n\n def write_log_entry(self, testpath, lettercode, longrepr):\n print(\"%s %s\" % (lettercode, testpath), file=self.logfile)\n for line in longrepr.splitlines():\n print(\" %s\" % line, file=self.logfile)\n\n def log_outcome(self, report, lettercode, longrepr):\n testpath = getattr(report, \"nodeid\", None)\n if testpath is None:\n testpath = report.fspath\n self.write_log_entry(testpath, lettercode, longrepr)\n\n def pytest_runtest_logreport(self, report):\n if report.when != \"call\" and report.passed:\n return\n res = self.config.hook.pytest_report_teststatus(\n report=report, config=self.config\n )\n code = res[1]\n if code == \"x\":\n longrepr = str(report.longrepr)\n elif code == \"X\":\n longrepr = \"\"\n elif report.passed:\n longrepr = \"\"\n elif report.failed:\n longrepr = str(report.longrepr)\n elif report.skipped:\n longrepr = str(report.longrepr[2])\n self.log_outcome(report, code, longrepr)\n\n def pytest_collectreport(self, report):\n if not report.passed:\n if report.failed:\n code = \"F\"\n longrepr = str(report.longrepr)\n else:\n assert report.skipped\n code = \"S\"\n longrepr = \"%s:%d: %s\" % report.longrepr\n self.log_outcome(report, code, longrepr)\n\n def pytest_internalerror(self, excrepr):\n reprcrash = getattr(excrepr, \"reprcrash\", None)\n path = getattr(reprcrash, \"path\", None)\n if path is None:\n path = \"cwd:%s\" % py.path.local()\n self.write_log_entry(path, \"!\", str(excrepr))\n"},{"col":0,"comment":"null","endLoc":23,"header":"def pytest_addoption(parser)","id":3829,"name":"pytest_addoption","nodeType":"Function","startLoc":14,"text":"def pytest_addoption(parser):\n group = parser.getgroup(\"terminal reporting\", \"resultlog plugin options\")\n group.addoption(\n \"--resultlog\",\n \"--result-log\",\n action=\"store\",\n metavar=\"path\",\n default=None,\n help=\"DEPRECATED path for machine-readable result log.\",\n )"},{"col":40,"endLoc":815,"id":3830,"nodeType":"Lambda","startLoc":815,"text":"lambda self, name, obj: values.append(name)"},{"col":4,"comment":"Ensure we can collect files with weird file extensions as Python\n modules (#2369)","endLoc":851,"header":"def test_issue2369_collect_module_fileext(self, testdir)","id":3831,"name":"test_issue2369_collect_module_fileext","nodeType":"Function","startLoc":820,"text":"def test_issue2369_collect_module_fileext(self, testdir):\n \"\"\"Ensure we can collect files with weird file extensions as Python\n modules (#2369)\"\"\"\n # We'll implement a little finder and loader to import files containing\n # Python source code whose file extension is \".narf\".\n testdir.makeconftest(\n \"\"\"\n import sys, os, imp\n from _pytest.python import Module\n\n class Loader(object):\n def load_module(self, name):\n return imp.load_source(name, name + \".narf\")\n class Finder(object):\n def find_module(self, name, path=None):\n if os.path.exists(name + \".narf\"):\n return Loader()\n sys.meta_path.append(Finder())\n\n def pytest_collect_file(path, parent):\n if path.ext == \".narf\":\n return Module(path, parent)\"\"\"\n )\n testdir.makefile(\n \".narf\",\n \"\"\"\\\n def test_something():\n assert 1 + 1 == 2\"\"\",\n )\n # Use runpytest_subprocess, since we're futzing with sys.meta_path.\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":0,"comment":"","endLoc":4,"header":"resultlog.py#","id":3832,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" log machine-parseable test session result information in a plain\ntext file.\n\"\"\""},{"id":3833,"name":"testing/example_scripts/issue88_initial_file_multinodes","nodeType":"Package"},{"fileName":"test_hello.py","filePath":"testing/example_scripts/issue88_initial_file_multinodes","id":3834,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ndef test_hello():\n pass\n"},{"col":0,"comment":"null","endLoc":3,"header":"def test_hello()","id":3835,"name":"test_hello","nodeType":"Function","startLoc":2,"text":"def test_hello():\n pass"},{"id":3836,"name":"changelog","nodeType":"Package"},{"id":3837,"name":"README.rst","nodeType":"TextFile","path":"changelog","text":"This directory contains \"newsfragments\" which are short files that contain a small **ReST**-formatted\ntext that will be added to the next ``CHANGELOG``.\n\nThe ``CHANGELOG`` will be read by users, so this description should be aimed to pytest users\ninstead of describing internal changes which are only relevant to the developers.\n\nMake sure to use full sentences with correct case and punctuation, for example::\n\n Fix issue with non-ascii messages from the ``warnings`` module.\n\nEach file should be named like ``..rst``, where\n```` is an issue number, and ```` is one of:\n\n* ``feature``: new user facing features, like new command-line options and new behavior.\n* ``bugfix``: fixes a reported bug.\n* ``doc``: documentation improvement, like rewording an entire session or adding missing docs.\n* ``deprecation``: feature deprecation.\n* ``removal``: feature removal.\n* ``vendor``: changes in packages vendored in pytest.\n* ``trivial``: fixing a small typo or internal change that might be noteworthy.\n\nSo for example: ``123.feature.rst``, ``456.bugfix.rst``.\n\nIf your PR fixes an issue, use that number here. If there is no issue,\nthen after you submit the PR and get the PR number you can add a\nchangelog using that instead.\n\nIf you are not sure what issue type to use, don't hesitate to ask in your PR.\n\n``towncrier`` preserves multiple paragraphs and formatting (code blocks, lists, and so on), but for entries\nother than ``features`` it is usually better to stick to a single paragraph to keep it concise. You can install\n``towncrier`` and then run ``towncrier --draft``\nif you want to get a preview of how your change will look in the final release notes.\n"},{"fileName":"conftest.py","filePath":"testing/example_scripts/issue88_initial_file_multinodes","id":3838,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\nclass MyFile(pytest.File):\n def collect(self):\n return [MyItem(\"hello\", parent=self)]\n\n\ndef pytest_collect_file(path, parent):\n return MyFile(path, parent)\n\n\nclass MyItem(pytest.Item):\n pass\n"},{"className":"MyFile","col":0,"comment":"null","endLoc":7,"id":3839,"nodeType":"Class","startLoc":5,"text":"class MyFile(pytest.File):\n def collect(self):\n return [MyItem(\"hello\", parent=self)]"},{"col":4,"comment":"null","endLoc":7,"header":"def collect(self)","id":3840,"name":"collect","nodeType":"Function","startLoc":6,"text":"def collect(self):\n return [MyItem(\"hello\", parent=self)]"},{"className":"TestTracebackCutting","col":0,"comment":"null","endLoc":1022,"id":3841,"nodeType":"Class","startLoc":896,"text":"class TestTracebackCutting(object):\n def test_skip_simple(self):\n with pytest.raises(pytest.skip.Exception) as excinfo:\n pytest.skip(\"xxx\")\n assert excinfo.traceback[-1].frame.code.name == \"skip\"\n assert excinfo.traceback[-1].ishidden()\n\n def test_traceback_argsetup(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def hello(request):\n raise ValueError(\"xyz\")\n \"\"\"\n )\n p = testdir.makepyfile(\"def test(hello): pass\")\n result = testdir.runpytest(p)\n assert result.ret != 0\n out = result.stdout.str()\n assert \"xyz\" in out\n assert \"conftest.py:5: ValueError\" in out\n numentries = out.count(\"_ _ _\") # separator for traceback entries\n assert numentries == 0\n\n result = testdir.runpytest(\"--fulltrace\", p)\n out = result.stdout.str()\n assert \"conftest.py:5: ValueError\" in out\n numentries = out.count(\"_ _ _ _\") # separator for traceback entries\n assert numentries > 3\n\n def test_traceback_error_during_import(self, testdir):\n testdir.makepyfile(\n \"\"\"\n x = 1\n x = 2\n x = 17\n asd\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret != 0\n out = result.stdout.str()\n assert \"x = 1\" not in out\n assert \"x = 2\" not in out\n result.stdout.fnmatch_lines([\" *asd*\", \"E*NameError*\"])\n result = testdir.runpytest(\"--fulltrace\")\n out = result.stdout.str()\n assert \"x = 1\" in out\n assert \"x = 2\" in out\n result.stdout.fnmatch_lines([\">*asd*\", \"E*NameError*\"])\n\n def test_traceback_filter_error_during_fixture_collection(self, testdir):\n \"\"\"integration test for issue #995.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n def fail_me(func):\n ns = {}\n exec('def w(): raise ValueError(\"fail me\")', ns)\n return ns['w']\n\n @pytest.fixture(scope='class')\n @fail_me\n def fail_fixture():\n pass\n\n def test_failing_fixture(fail_fixture):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret != 0\n out = result.stdout.str()\n assert \"INTERNALERROR>\" not in out\n result.stdout.fnmatch_lines([\"*ValueError: fail me*\", \"* 1 error in *\"])\n\n def test_filter_traceback_generated_code(self):\n \"\"\"test that filter_traceback() works with the fact that\n _pytest._code.code.Code.path attribute might return an str object.\n In this case, one of the entries on the traceback was produced by\n dynamically generated code.\n See: https://bitbucket.org/pytest-dev/py/issues/71\n This fixes #995.\n \"\"\"\n from _pytest.python import filter_traceback\n\n try:\n ns = {}\n exec(\"def foo(): raise ValueError\", ns)\n ns[\"foo\"]()\n except ValueError:\n _, _, tb = sys.exc_info()\n\n tb = _pytest._code.Traceback(tb)\n assert isinstance(tb[-1].path, str)\n assert not filter_traceback(tb[-1])\n\n def test_filter_traceback_path_no_longer_valid(self, testdir):\n \"\"\"test that filter_traceback() works with the fact that\n _pytest._code.code.Code.path attribute might return an str object.\n In this case, one of the files in the traceback no longer exists.\n This fixes #1133.\n \"\"\"\n from _pytest.python import filter_traceback\n\n testdir.syspathinsert()\n testdir.makepyfile(\n filter_traceback_entry_as_str=\"\"\"\n def foo():\n raise ValueError\n \"\"\"\n )\n try:\n import filter_traceback_entry_as_str\n\n filter_traceback_entry_as_str.foo()\n except ValueError:\n _, _, tb = sys.exc_info()\n\n testdir.tmpdir.join(\"filter_traceback_entry_as_str.py\").remove()\n tb = _pytest._code.Traceback(tb)\n assert isinstance(tb[-1].path, str)\n assert filter_traceback(tb[-1])"},{"col":4,"comment":"null","endLoc":901,"header":"def test_skip_simple(self)","id":3842,"name":"test_skip_simple","nodeType":"Function","startLoc":897,"text":"def test_skip_simple(self):\n with pytest.raises(pytest.skip.Exception) as excinfo:\n pytest.skip(\"xxx\")\n assert excinfo.traceback[-1].frame.code.name == \"skip\"\n assert excinfo.traceback[-1].ishidden()"},{"col":4,"comment":"null","endLoc":539,"header":"@pytest.hookimpl(hookwrapper=True, tryfirst=True)\n def pytest_collection(self)","id":3843,"name":"pytest_collection","nodeType":"Function","startLoc":529,"text":"@pytest.hookimpl(hookwrapper=True, tryfirst=True)\n def pytest_collection(self):\n with self.live_logs_context():\n if self.log_cli_handler:\n self.log_cli_handler.set_when(\"collection\")\n\n if self.log_file_handler is not None:\n with catching_logs(self.log_file_handler, level=self.log_file_level):\n yield\n else:\n yield"},{"col":4,"comment":"null","endLoc":883,"header":"def test_one_skipped(self, testdir, makedoctest)","id":3844,"name":"test_one_skipped","nodeType":"Function","startLoc":873,"text":"def test_one_skipped(self, testdir, makedoctest):\n makedoctest(\n \"\"\"\n >>> 1 + 1 # doctest: +SKIP\n 2\n >>> 2 + 2\n 4\n \"\"\"\n )\n reprec = testdir.inline_run(\"--doctest-modules\")\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":"null","endLoc":926,"header":"def test_traceback_argsetup(self, testdir)","id":3846,"name":"test_traceback_argsetup","nodeType":"Function","startLoc":903,"text":"def test_traceback_argsetup(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def hello(request):\n raise ValueError(\"xyz\")\n \"\"\"\n )\n p = testdir.makepyfile(\"def test(hello): pass\")\n result = testdir.runpytest(p)\n assert result.ret != 0\n out = result.stdout.str()\n assert \"xyz\" in out\n assert \"conftest.py:5: ValueError\" in out\n numentries = out.count(\"_ _ _\") # separator for traceback entries\n assert numentries == 0\n\n result = testdir.runpytest(\"--fulltrace\", p)\n out = result.stdout.str()\n assert \"conftest.py:5: ValueError\" in out\n numentries = out.count(\"_ _ _ _\") # separator for traceback entries\n assert numentries > 3"},{"className":"BaseReport","col":0,"comment":"null","endLoc":266,"id":3847,"nodeType":"Class","startLoc":35,"text":"class BaseReport(object):\n when = None\n location = None\n\n def __init__(self, **kw):\n self.__dict__.update(kw)\n\n def toterminal(self, out):\n if hasattr(self, \"node\"):\n out.line(getslaveinfoline(self.node))\n\n longrepr = self.longrepr\n if longrepr is None:\n return\n\n if hasattr(longrepr, \"toterminal\"):\n longrepr.toterminal(out)\n else:\n try:\n out.line(longrepr)\n except UnicodeEncodeError:\n out.line(\"\")\n\n def get_sections(self, prefix):\n for name, content in self.sections:\n if name.startswith(prefix):\n yield prefix, content\n\n @property\n def longreprtext(self):\n \"\"\"\n Read-only property that returns the full string representation\n of ``longrepr``.\n\n .. versionadded:: 3.0\n \"\"\"\n tw = py.io.TerminalWriter(stringio=True)\n tw.hasmarkup = False\n self.toterminal(tw)\n exc = tw.stringio.getvalue()\n return exc.strip()\n\n @property\n def caplog(self):\n \"\"\"Return captured log lines, if log capturing is enabled\n\n .. versionadded:: 3.5\n \"\"\"\n return \"\\n\".join(\n content for (prefix, content) in self.get_sections(\"Captured log\")\n )\n\n @property\n def capstdout(self):\n \"\"\"Return captured text from stdout, if capturing is enabled\n\n .. versionadded:: 3.0\n \"\"\"\n return \"\".join(\n content for (prefix, content) in self.get_sections(\"Captured stdout\")\n )\n\n @property\n def capstderr(self):\n \"\"\"Return captured text from stderr, if capturing is enabled\n\n .. versionadded:: 3.0\n \"\"\"\n return \"\".join(\n content for (prefix, content) in self.get_sections(\"Captured stderr\")\n )\n\n passed = property(lambda x: x.outcome == \"passed\")\n failed = property(lambda x: x.outcome == \"failed\")\n skipped = property(lambda x: x.outcome == \"skipped\")\n\n @property\n def fspath(self):\n return self.nodeid.split(\"::\")[0]\n\n @property\n def count_towards_summary(self):\n \"\"\"\n **Experimental**\n\n Returns True if this report should be counted towards the totals shown at the end of the\n test session: \"1 passed, 1 failure, etc\".\n\n .. note::\n\n This function is considered **experimental**, so beware that it is subject to changes\n even in patch releases.\n \"\"\"\n return True\n\n @property\n def head_line(self):\n \"\"\"\n **Experimental**\n\n Returns the head line shown with longrepr output for this report, more commonly during\n traceback representation during failures::\n\n ________ Test.foo ________\n\n\n In the example above, the head_line is \"Test.foo\".\n\n .. note::\n\n This function is considered **experimental**, so beware that it is subject to changes\n even in patch releases.\n \"\"\"\n if self.location is not None:\n fspath, lineno, domain = self.location\n return domain\n\n def _get_verbose_word(self, config):\n _category, _short, verbose = config.hook.pytest_report_teststatus(\n report=self, config=config\n )\n return verbose\n\n def _to_json(self):\n \"\"\"\n This was originally the serialize_report() function from xdist (ca03269).\n\n Returns the contents of this report as a dict of builtin entries, suitable for\n serialization.\n\n Experimental method.\n \"\"\"\n\n def disassembled_report(rep):\n reprtraceback = rep.longrepr.reprtraceback.__dict__.copy()\n reprcrash = rep.longrepr.reprcrash.__dict__.copy()\n\n new_entries = []\n for entry in reprtraceback[\"reprentries\"]:\n entry_data = {\n \"type\": type(entry).__name__,\n \"data\": entry.__dict__.copy(),\n }\n for key, value in entry_data[\"data\"].items():\n if hasattr(value, \"__dict__\"):\n entry_data[\"data\"][key] = value.__dict__.copy()\n new_entries.append(entry_data)\n\n reprtraceback[\"reprentries\"] = new_entries\n\n return {\n \"reprcrash\": reprcrash,\n \"reprtraceback\": reprtraceback,\n \"sections\": rep.longrepr.sections,\n }\n\n d = self.__dict__.copy()\n if hasattr(self.longrepr, \"toterminal\"):\n if hasattr(self.longrepr, \"reprtraceback\") and hasattr(\n self.longrepr, \"reprcrash\"\n ):\n d[\"longrepr\"] = disassembled_report(self)\n else:\n d[\"longrepr\"] = six.text_type(self.longrepr)\n else:\n d[\"longrepr\"] = self.longrepr\n for name in d:\n if isinstance(d[name], (py.path.local, Path)):\n d[name] = str(d[name])\n elif name == \"result\":\n d[name] = None # for now\n return d\n\n @classmethod\n def _from_json(cls, reportdict):\n \"\"\"\n This was originally the serialize_report() function from xdist (ca03269).\n\n Factory method that returns either a TestReport or CollectReport, depending on the calling\n class. It's the callers responsibility to know which class to pass here.\n\n Experimental method.\n \"\"\"\n if reportdict[\"longrepr\"]:\n if (\n \"reprcrash\" in reportdict[\"longrepr\"]\n and \"reprtraceback\" in reportdict[\"longrepr\"]\n ):\n\n reprtraceback = reportdict[\"longrepr\"][\"reprtraceback\"]\n reprcrash = reportdict[\"longrepr\"][\"reprcrash\"]\n\n unserialized_entries = []\n reprentry = None\n for entry_data in reprtraceback[\"reprentries\"]:\n data = entry_data[\"data\"]\n entry_type = entry_data[\"type\"]\n if entry_type == \"ReprEntry\":\n reprfuncargs = None\n reprfileloc = None\n reprlocals = None\n if data[\"reprfuncargs\"]:\n reprfuncargs = ReprFuncArgs(**data[\"reprfuncargs\"])\n if data[\"reprfileloc\"]:\n reprfileloc = ReprFileLocation(**data[\"reprfileloc\"])\n if data[\"reprlocals\"]:\n reprlocals = ReprLocals(data[\"reprlocals\"][\"lines\"])\n\n reprentry = ReprEntry(\n lines=data[\"lines\"],\n reprfuncargs=reprfuncargs,\n reprlocals=reprlocals,\n filelocrepr=reprfileloc,\n style=data[\"style\"],\n )\n elif entry_type == \"ReprEntryNative\":\n reprentry = ReprEntryNative(data[\"lines\"])\n else:\n _report_unserialization_failure(entry_type, cls, reportdict)\n unserialized_entries.append(reprentry)\n reprtraceback[\"reprentries\"] = unserialized_entries\n\n exception_info = ReprExceptionInfo(\n reprtraceback=ReprTraceback(**reprtraceback),\n reprcrash=ReprFileLocation(**reprcrash),\n )\n\n for section in reportdict[\"longrepr\"][\"sections\"]:\n exception_info.addsection(*section)\n reportdict[\"longrepr\"] = exception_info\n\n return cls(**reportdict)"},{"col":4,"comment":"null","endLoc":895,"header":"def test_one_skipped_failed(self, testdir, makedoctest)","id":3848,"name":"test_one_skipped_failed","nodeType":"Function","startLoc":885,"text":"def test_one_skipped_failed(self, testdir, makedoctest):\n makedoctest(\n \"\"\"\n >>> 1 + 1 # doctest: +SKIP\n 2\n >>> 2 + 2\n 200\n \"\"\"\n )\n reprec = testdir.inline_run(\"--doctest-modules\")\n reprec.assertoutcome(failed=1)"},{"col":4,"comment":"null","endLoc":40,"header":"def __init__(self, **kw)","id":3849,"name":"__init__","nodeType":"Function","startLoc":39,"text":"def __init__(self, **kw):\n self.__dict__.update(kw)"},{"col":4,"comment":"null","endLoc":907,"header":"def test_all_skipped(self, testdir, makedoctest)","id":3850,"name":"test_all_skipped","nodeType":"Function","startLoc":897,"text":"def test_all_skipped(self, testdir, makedoctest):\n makedoctest(\n \"\"\"\n >>> 1 + 1 # doctest: +SKIP\n 2\n >>> 2 + 2 # doctest: +SKIP\n 200\n \"\"\"\n )\n reprec = testdir.inline_run(\"--doctest-modules\")\n reprec.assertoutcome(skipped=1)"},{"col":4,"comment":"null","endLoc":912,"header":"def test_vacuous_all_skipped(self, testdir, makedoctest)","id":3851,"name":"test_vacuous_all_skipped","nodeType":"Function","startLoc":909,"text":"def test_vacuous_all_skipped(self, testdir, makedoctest):\n makedoctest(\"\")\n reprec = testdir.inline_run(\"--doctest-modules\")\n reprec.assertoutcome(passed=0, skipped=0)"},{"col":4,"comment":"null","endLoc":947,"header":"def test_traceback_error_during_import(self, testdir)","id":3852,"name":"test_traceback_error_during_import","nodeType":"Function","startLoc":928,"text":"def test_traceback_error_during_import(self, testdir):\n testdir.makepyfile(\n \"\"\"\n x = 1\n x = 2\n x = 17\n asd\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret != 0\n out = result.stdout.str()\n assert \"x = 1\" not in out\n assert \"x = 2\" not in out\n result.stdout.fnmatch_lines([\" *asd*\", \"E*NameError*\"])\n result = testdir.runpytest(\"--fulltrace\")\n out = result.stdout.str()\n assert \"x = 1\" in out\n assert \"x = 2\" in out\n result.stdout.fnmatch_lines([\">*asd*\", \"E*NameError*\"])"},{"className":"MyItem","col":0,"comment":"null","endLoc":15,"id":3853,"nodeType":"Class","startLoc":14,"text":"class MyItem(pytest.Item):\n pass"},{"col":0,"comment":"null","endLoc":11,"header":"def pytest_collect_file(path, parent)","id":3854,"name":"pytest_collect_file","nodeType":"Function","startLoc":10,"text":"def pytest_collect_file(path, parent):\n return MyFile(path, parent)"},{"col":4,"comment":"null","endLoc":933,"header":"def test_continue_on_failure(self, testdir)","id":3855,"name":"test_continue_on_failure","nodeType":"Function","startLoc":914,"text":"def test_continue_on_failure(self, testdir):\n testdir.maketxtfile(\n test_something=\"\"\"\n >>> i = 5\n >>> def foo():\n ... raise ValueError('error1')\n >>> foo()\n >>> i\n >>> i + 2\n 7\n >>> i + 1\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\", \"--doctest-continue-on-failure\")\n result.assert_outcomes(passed=0, failed=1)\n # The lines that contains the failure are 4, 5, and 8. The first one\n # is a stack trace and the other two are mismatches.\n result.stdout.fnmatch_lines(\n [\"*4: UnexpectedException*\", \"*5: DocTestFailure*\", \"*8: DocTestFailure*\"]\n )"},{"className":"TestDoctestAutoUseFixtures","col":0,"comment":"null","endLoc":1077,"id":3856,"nodeType":"Class","startLoc":936,"text":"class TestDoctestAutoUseFixtures(object):\n\n SCOPES = [\"module\", \"session\", \"class\", \"function\"]\n\n def test_doctest_module_session_fixture(self, testdir):\n \"\"\"Test that session fixtures are initialized for doctest modules (#768)\n \"\"\"\n # session fixture which changes some global data, which will\n # be accessed by doctests in a module\n testdir.makeconftest(\n \"\"\"\n import pytest\n import sys\n\n @pytest.yield_fixture(autouse=True, scope='session')\n def myfixture():\n assert not hasattr(sys, 'pytest_session_data')\n sys.pytest_session_data = 1\n yield\n del sys.pytest_session_data\n \"\"\"\n )\n testdir.makepyfile(\n foo=\"\"\"\n import sys\n\n def foo():\n '''\n >>> assert sys.pytest_session_data == 1\n '''\n\n def bar():\n '''\n >>> assert sys.pytest_session_data == 1\n '''\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n @pytest.mark.parametrize(\"scope\", SCOPES)\n @pytest.mark.parametrize(\"enable_doctest\", [True, False])\n def test_fixture_scopes(self, testdir, scope, enable_doctest):\n \"\"\"Test that auto-use fixtures work properly with doctest modules.\n See #1057 and #1100.\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(autouse=True, scope=\"{scope}\")\n def auto(request):\n return 99\n \"\"\".format(\n scope=scope\n )\n )\n testdir.makepyfile(\n test_1='''\n def test_foo():\n \"\"\"\n >>> getfixture('auto') + 1\n 100\n \"\"\"\n def test_bar():\n assert 1\n '''\n )\n params = (\"--doctest-modules\",) if enable_doctest else ()\n passes = 3 if enable_doctest else 2\n result = testdir.runpytest(*params)\n result.stdout.fnmatch_lines([\"*=== %d passed in *\" % passes])\n\n @pytest.mark.parametrize(\"scope\", SCOPES)\n @pytest.mark.parametrize(\"autouse\", [True, False])\n @pytest.mark.parametrize(\"use_fixture_in_doctest\", [True, False])\n def test_fixture_module_doctest_scopes(\n self, testdir, scope, autouse, use_fixture_in_doctest\n ):\n \"\"\"Test that auto-use fixtures work properly with doctest files.\n See #1057 and #1100.\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(autouse={autouse}, scope=\"{scope}\")\n def auto(request):\n return 99\n \"\"\".format(\n scope=scope, autouse=autouse\n )\n )\n if use_fixture_in_doctest:\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> getfixture('auto')\n 99\n \"\"\"\n )\n else:\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> 1 + 1\n 2\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\")\n assert \"FAILURES\" not in str(result.stdout.str())\n result.stdout.fnmatch_lines([\"*=== 1 passed in *\"])\n\n @pytest.mark.parametrize(\"scope\", SCOPES)\n def test_auto_use_request_attributes(self, testdir, scope):\n \"\"\"Check that all attributes of a request in an autouse fixture\n behave as expected when requested for a doctest item.\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(autouse=True, scope=\"{scope}\")\n def auto(request):\n if \"{scope}\" == 'module':\n assert request.module is None\n if \"{scope}\" == 'class':\n assert request.cls is None\n if \"{scope}\" == 'function':\n assert request.function is None\n return 99\n \"\"\".format(\n scope=scope\n )\n )\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> 1 + 1\n 2\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\")\n assert \"FAILURES\" not in str(result.stdout.str())\n result.stdout.fnmatch_lines([\"*=== 1 passed in *\"])"},{"col":4,"comment":"Test that session fixtures are initialized for doctest modules (#768)\n ","endLoc":974,"header":"def test_doctest_module_session_fixture(self, testdir)","id":3857,"name":"test_doctest_module_session_fixture","nodeType":"Function","startLoc":940,"text":"def test_doctest_module_session_fixture(self, testdir):\n \"\"\"Test that session fixtures are initialized for doctest modules (#768)\n \"\"\"\n # session fixture which changes some global data, which will\n # be accessed by doctests in a module\n testdir.makeconftest(\n \"\"\"\n import pytest\n import sys\n\n @pytest.yield_fixture(autouse=True, scope='session')\n def myfixture():\n assert not hasattr(sys, 'pytest_session_data')\n sys.pytest_session_data = 1\n yield\n del sys.pytest_session_data\n \"\"\"\n )\n testdir.makepyfile(\n foo=\"\"\"\n import sys\n\n def foo():\n '''\n >>> assert sys.pytest_session_data == 1\n '''\n\n def bar():\n '''\n >>> assert sys.pytest_session_data == 1\n '''\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines([\"*2 passed*\"])"},{"col":4,"comment":"integration test for issue #995.\n ","endLoc":974,"header":"def test_traceback_filter_error_during_fixture_collection(self, testdir)","id":3858,"name":"test_traceback_filter_error_during_fixture_collection","nodeType":"Function","startLoc":949,"text":"def test_traceback_filter_error_during_fixture_collection(self, testdir):\n \"\"\"integration test for issue #995.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n def fail_me(func):\n ns = {}\n exec('def w(): raise ValueError(\"fail me\")', ns)\n return ns['w']\n\n @pytest.fixture(scope='class')\n @fail_me\n def fail_fixture():\n pass\n\n def test_failing_fixture(fail_fixture):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret != 0\n out = result.stdout.str()\n assert \"INTERNALERROR>\" not in out\n result.stdout.fnmatch_lines([\"*ValueError: fail me*\", \"* 1 error in *\"])"},{"id":3859,"name":"release-3.9.3.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.9.3\n=======================================\n\npytest 3.9.3 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Andreas Profous\n* Ankit Goel\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Jon Dufresne\n* Ronny Pfannschmidt\n\n\nHappy testing,\nThe pytest Development Team\n"},{"col":4,"comment":"test that filter_traceback() works with the fact that\n _pytest._code.code.Code.path attribute might return an str object.\n In this case, one of the entries on the traceback was produced by\n dynamically generated code.\n See: https://bitbucket.org/pytest-dev/py/issues/71\n This fixes #995.\n ","endLoc":995,"header":"def test_filter_traceback_generated_code(self)","id":3860,"name":"test_filter_traceback_generated_code","nodeType":"Function","startLoc":976,"text":"def test_filter_traceback_generated_code(self):\n \"\"\"test that filter_traceback() works with the fact that\n _pytest._code.code.Code.path attribute might return an str object.\n In this case, one of the entries on the traceback was produced by\n dynamically generated code.\n See: https://bitbucket.org/pytest-dev/py/issues/71\n This fixes #995.\n \"\"\"\n from _pytest.python import filter_traceback\n\n try:\n ns = {}\n exec(\"def foo(): raise ValueError\", ns)\n ns[\"foo\"]()\n except ValueError:\n _, _, tb = sys.exc_info()\n\n tb = _pytest._code.Traceback(tb)\n assert isinstance(tb[-1].path, str)\n assert not filter_traceback(tb[-1])"},{"col":4,"comment":"Test that auto-use fixtures work properly with doctest modules.\n See #1057 and #1100.\n ","endLoc":1007,"header":"@pytest.mark.parametrize(\"scope\", SCOPES)\n @pytest.mark.parametrize(\"enable_doctest\", [True, False])\n def test_fixture_scopes(self, testdir, scope, enable_doctest)","id":3861,"name":"test_fixture_scopes","nodeType":"Function","startLoc":976,"text":"@pytest.mark.parametrize(\"scope\", SCOPES)\n @pytest.mark.parametrize(\"enable_doctest\", [True, False])\n def test_fixture_scopes(self, testdir, scope, enable_doctest):\n \"\"\"Test that auto-use fixtures work properly with doctest modules.\n See #1057 and #1100.\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(autouse=True, scope=\"{scope}\")\n def auto(request):\n return 99\n \"\"\".format(\n scope=scope\n )\n )\n testdir.makepyfile(\n test_1='''\n def test_foo():\n \"\"\"\n >>> getfixture('auto') + 1\n 100\n \"\"\"\n def test_bar():\n assert 1\n '''\n )\n params = (\"--doctest-modules\",) if enable_doctest else ()\n passes = 3 if enable_doctest else 2\n result = testdir.runpytest(*params)\n result.stdout.fnmatch_lines([\"*=== %d passed in *\" % passes])"},{"id":3862,"name":"release-3.5.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.5.1\n=======================================\n\npytest 3.5.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Brian Maissy\n* Bruno Oliveira\n* Darren Burns\n* David Chudzicki\n* Floris Bruynooghe\n* Holger Kohr\n* Irmen de Jong\n* Jeffrey Rackauckas\n* Rachel Kogan\n* Ronny Pfannschmidt\n* Stefan Scherfke\n* Tim Strazny\n* Семён Марьясин\n\n\nHappy testing,\nThe pytest Development Team\n"},{"id":3863,"name":"release-2.0.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"py.test 2.0.2: bug fixes, improved xfail/skip expressions, speed ups\n===========================================================================\n\nWelcome to pytest-2.0.2, a maintenance and bug fix release of pytest,\na mature testing tool for Python, supporting CPython 2.4-3.2, Jython\nand latest PyPy interpreters. See the extensive docs with tested examples here:\n\n http://pytest.org/\n\nIf you want to install or upgrade pytest, just type one of::\n\n pip install -U pytest # or\n easy_install -U pytest\n\nMany thanks to all issue reporters and people asking questions\nor complaining, particularly Jurko for his insistence,\nLaura, Victor and Brianna for helping with improving\nand Ronny for his general advise.\n\nbest,\nholger krekel\n\nChanges between 2.0.1 and 2.0.2\n----------------------------------------------\n\n- tackle issue32 - speed up test runs of very quick test functions\n by reducing the relative overhead\n\n- fix issue30 - extended xfail/skipif handling and improved reporting.\n If you have a syntax error in your skip/xfail\n expressions you now get nice error reports.\n\n Also you can now access module globals from xfail/skipif\n expressions so that this for example works now::\n\n import pytest\n import mymodule\n @pytest.mark.skipif(\"mymodule.__version__[0] == \"1\")\n def test_function():\n pass\n\n This will not run the test function if the module's version string\n does not start with a \"1\". Note that specifying a string instead\n of a boolean expressions allows py.test to report meaningful information\n when summarizing a test run as to what conditions lead to skipping\n (or xfail-ing) tests.\n\n- fix issue28 - setup_method and pytest_generate_tests work together\n The setup_method fixture method now gets called also for\n test function invocations generated from the pytest_generate_tests\n hook.\n\n- fix issue27 - collectonly and keyword-selection (-k) now work together\n Also, if you do \"py.test --collectonly -q\" you now get a flat list\n of test ids that you can use to paste to the py.test commandline\n in order to execute a particular test.\n\n- fix issue25 avoid reported problems with --pdb and python3.2/encodings output\n\n- fix issue23 - tmpdir argument now works on Python3.2 and WindowsXP\n Starting with Python3.2 os.symlink may be supported. By requiring\n a newer py lib version the py.path.local() implementation acknowledges\n this.\n\n- fixed typos in the docs (thanks Victor Garcia, Brianna Laugher) and particular\n thanks to Laura Creighton who also reviewed parts of the documentation.\n\n- fix slightly wrong output of verbose progress reporting for classes\n (thanks Amaury)\n\n- more precise (avoiding of) deprecation warnings for node.Class|Function accesses\n\n- avoid std unittest assertion helper code in tracebacks (thanks Ronny)\n"},{"id":3864,"name":"release-2.4.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.4.0: new fixture features/hooks and bug fixes\n===========================================================================\n\nThe just released pytest-2.4.0 brings many improvements and numerous\nbug fixes while remaining plugin- and test-suite compatible apart\nfrom a few supposedly very minor incompatibilities. See below for\na full list of details. A few feature highlights:\n\n- new yield-style fixtures `pytest.yield_fixture\n `_, allowing to use\n existing with-style context managers in fixture functions.\n\n- improved pdb support: ``import pdb ; pdb.set_trace()`` now works\n without requiring prior disabling of stdout/stderr capturing.\n Also the ``--pdb`` options works now on collection and internal errors\n and we introduced a new experimental hook for IDEs/plugins to\n intercept debugging: ``pytest_exception_interact(node, call, report)``.\n\n- shorter monkeypatch variant to allow specifying an import path as\n a target, for example: ``monkeypatch.setattr(\"requests.get\", myfunc)``\n\n- better unittest/nose compatibility: all teardown methods are now only\n called if the corresponding setup method succeeded.\n\n- integrate tab-completion on command line options if you\n have `argcomplete `_\n configured.\n\n- allow boolean expression directly with skipif/xfail\n if a \"reason\" is also specified.\n\n- a new hook ``pytest_load_initial_conftests`` allows plugins like\n `pytest-django `_ to\n influence the environment before conftest files import ``django``.\n\n- reporting: color the last line red or green depending if\n failures/errors occurred or everything passed.\n\nThe documentation has been updated to accommodate the changes,\nsee `http://pytest.org `_\n\nTo install or upgrade pytest::\n\n pip install -U pytest # or\n easy_install -U pytest\n\n\n**Many thanks to all who helped, including Floris Bruynooghe,\nBrianna Laugher, Andreas Pelme, Anthon van der Neut, Anatoly Bubenkoff,\nVladimir Keleshev, Mathieu Agopian, Ronny Pfannschmidt, Christian\nTheunert and many others.**\n\nmay passing tests be with you,\n\nholger krekel\n\nChanges between 2.3.5 and 2.4\n-----------------------------------\n\nknown incompatibilities:\n\n- if calling --genscript from python2.7 or above, you only get a\n standalone script which works on python2.7 or above. Use Python2.6\n to also get a python2.5 compatible version.\n\n- all xunit-style teardown methods (nose-style, pytest-style,\n unittest-style) will not be called if the corresponding setup method failed,\n see issue322 below.\n\n- the pytest_plugin_unregister hook wasn't ever properly called\n and there is no known implementation of the hook - so it got removed.\n\n- pytest.fixture-decorated functions cannot be generators (i.e. use\n yield) anymore. This change might be reversed in 2.4.1 if it causes\n unforeseen real-life issues. However, you can always write and return\n an inner function/generator and change the fixture consumer to iterate\n over the returned generator. This change was done in lieu of the new\n ``pytest.yield_fixture`` decorator, see below.\n\nnew features:\n\n- experimentally introduce a new ``pytest.yield_fixture`` decorator\n which accepts exactly the same parameters as pytest.fixture but\n mandates a ``yield`` statement instead of a ``return statement`` from\n fixture functions. This allows direct integration with \"with-style\"\n context managers in fixture functions and generally avoids registering\n of finalization callbacks in favour of treating the \"after-yield\" as\n teardown code. Thanks Andreas Pelme, Vladimir Keleshev, Floris\n Bruynooghe, Ronny Pfannschmidt and many others for discussions.\n\n- allow boolean expression directly with skipif/xfail\n if a \"reason\" is also specified. Rework skipping documentation\n to recommend \"condition as booleans\" because it prevents surprises\n when importing markers between modules. Specifying conditions\n as strings will remain fully supported.\n\n- reporting: color the last line red or green depending if\n failures/errors occurred or everything passed. thanks Christian\n Theunert.\n\n- make \"import pdb ; pdb.set_trace()\" work natively wrt capturing (no\n \"-s\" needed anymore), making ``pytest.set_trace()`` a mere shortcut.\n\n- fix issue181: --pdb now also works on collect errors (and\n on internal errors) . This was implemented by a slight internal\n refactoring and the introduction of a new hook\n ``pytest_exception_interact`` hook (see next item).\n\n- fix issue341: introduce new experimental hook for IDEs/terminals to\n intercept debugging: ``pytest_exception_interact(node, call, report)``.\n\n- new monkeypatch.setattr() variant to provide a shorter\n invocation for patching out classes/functions from modules:\n\n monkeypatch.setattr(\"requests.get\", myfunc)\n\n will replace the \"get\" function of the \"requests\" module with ``myfunc``.\n\n- fix issue322: tearDownClass is not run if setUpClass failed. Thanks\n Mathieu Agopian for the initial fix. Also make all of pytest/nose\n finalizer mimic the same generic behaviour: if a setupX exists and\n fails, don't run teardownX. This internally introduces a new method\n \"node.addfinalizer()\" helper which can only be called during the setup\n phase of a node.\n\n- simplify pytest.mark.parametrize() signature: allow to pass a\n CSV-separated string to specify argnames. For example:\n ``pytest.mark.parametrize(\"input,expected\", [(1,2), (2,3)])``\n works as well as the previous:\n ``pytest.mark.parametrize((\"input\", \"expected\"), ...)``.\n\n- add support for setUpModule/tearDownModule detection, thanks Brian Okken.\n\n- integrate tab-completion on options through use of \"argcomplete\".\n Thanks Anthon van der Neut for the PR.\n\n- change option names to be hyphen-separated long options but keep the\n old spelling backward compatible. py.test -h will only show the\n hyphenated version, for example \"--collect-only\" but \"--collectonly\"\n will remain valid as well (for backward-compat reasons). Many thanks to\n Anthon van der Neut for the implementation and to Hynek Schlawack for\n pushing us.\n\n- fix issue 308 - allow to mark/xfail/skip individual parameter sets\n when parametrizing. Thanks Brianna Laugher.\n\n- call new experimental pytest_load_initial_conftests hook to allow\n 3rd party plugins to do something before a conftest is loaded.\n\nBug fixes:\n\n- fix issue358 - capturing options are now parsed more properly\n by using a new parser.parse_known_args method.\n\n- pytest now uses argparse instead of optparse (thanks Anthon) which\n means that \"argparse\" is added as a dependency if installing into python2.6\n environments or below.\n\n- fix issue333: fix a case of bad unittest/pytest hook interaction.\n\n- PR27: correctly handle nose.SkipTest during collection. Thanks\n Antonio Cuni, Ronny Pfannschmidt.\n\n- fix issue355: junitxml puts name=\"pytest\" attribute to testsuite tag.\n\n- fix issue336: autouse fixture in plugins should work again.\n\n- fix issue279: improve object comparisons on assertion failure\n for standard datatypes and recognise collections.abc. Thanks to\n Brianna Laugher and Mathieu Agopian.\n\n- fix issue317: assertion rewriter support for the is_package method\n\n- fix issue335: document py.code.ExceptionInfo() object returned\n from pytest.raises(), thanks Mathieu Agopian.\n\n- remove implicit distribute_setup support from setup.py.\n\n- fix issue305: ignore any problems when writing pyc files.\n\n- SO-17664702: call fixture finalizers even if the fixture function\n partially failed (finalizers would not always be called before)\n\n- fix issue320 - fix class scope for fixtures when mixed with\n module-level functions. Thanks Anatloy Bubenkoff.\n\n- you can specify \"-q\" or \"-qq\" to get different levels of \"quieter\"\n reporting (thanks Katarzyna Jachim)\n\n- fix issue300 - Fix order of conftest loading when starting py.test\n in a subdirectory.\n\n- fix issue323 - sorting of many module-scoped arg parametrizations\n\n- make sessionfinish hooks execute with the same cwd-context as at\n session start (helps fix plugin behaviour which write output files\n with relative path such as pytest-cov)\n\n- fix issue316 - properly reference collection hooks in docs\n\n- fix issue 306 - cleanup of -k/-m options to only match markers/test\n names/keywords respectively. Thanks Wouter van Ackooy.\n\n- improved doctest counting for doctests in python modules --\n files without any doctest items will not show up anymore\n and doctest examples are counted as separate test items.\n thanks Danilo Bellini.\n\n- fix issue245 by depending on the released py-1.4.14\n which fixes py.io.dupfile to work with files with no\n mode. Thanks Jason R. Coombs.\n\n- fix junitxml generation when test output contains control characters,\n addressing issue267, thanks Jaap Broekhuizen\n\n- fix issue338: honor --tb style for setup/teardown errors as well. Thanks Maho.\n\n- fix issue307 - use yaml.safe_load in example, thanks Mark Eichin.\n\n- better parametrize error messages, thanks Brianna Laugher\n\n- pytest_terminal_summary(terminalreporter) hooks can now use\n \".section(title)\" and \".line(msg)\" methods to print extra\n information at the end of a test run.\n"},{"col":4,"comment":"null","endLoc":548,"header":"@contextmanager\n def _runtest_for(self, item, when)","id":3865,"name":"_runtest_for","nodeType":"Function","startLoc":541,"text":"@contextmanager\n def _runtest_for(self, item, when):\n with self._runtest_for_main(item, when):\n if self.log_file_handler is not None:\n with catching_logs(self.log_file_handler, level=self.log_file_level):\n yield\n else:\n yield"},{"col":4,"comment":"Test that auto-use fixtures work properly with doctest files.\n See #1057 and #1100.\n ","endLoc":1045,"header":"@pytest.mark.parametrize(\"scope\", SCOPES)\n @pytest.mark.parametrize(\"autouse\", [True, False])\n @pytest.mark.parametrize(\"use_fixture_in_doctest\", [True, False])\n def test_fixture_module_doctest_scopes(\n self, testdir, scope, autouse, use_fixture_in_doctest\n )","id":3866,"name":"test_fixture_module_doctest_scopes","nodeType":"Function","startLoc":1009,"text":"@pytest.mark.parametrize(\"scope\", SCOPES)\n @pytest.mark.parametrize(\"autouse\", [True, False])\n @pytest.mark.parametrize(\"use_fixture_in_doctest\", [True, False])\n def test_fixture_module_doctest_scopes(\n self, testdir, scope, autouse, use_fixture_in_doctest\n ):\n \"\"\"Test that auto-use fixtures work properly with doctest files.\n See #1057 and #1100.\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(autouse={autouse}, scope=\"{scope}\")\n def auto(request):\n return 99\n \"\"\".format(\n scope=scope, autouse=autouse\n )\n )\n if use_fixture_in_doctest:\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> getfixture('auto')\n 99\n \"\"\"\n )\n else:\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> 1 + 1\n 2\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\")\n assert \"FAILURES\" not in str(result.stdout.str())\n result.stdout.fnmatch_lines([\"*=== 1 passed in *\"])"},{"fileName":"nodes.py","filePath":"src/_pytest","id":3867,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport warnings\n\nimport py\nimport six\n\nimport _pytest._code\nfrom _pytest.compat import getfslineno\nfrom _pytest.mark.structures import NodeKeywords\nfrom _pytest.outcomes import fail\n\nSEP = \"/\"\n\ntracebackcutdir = py.path.local(_pytest.__file__).dirpath()\n\n\ndef _splitnode(nodeid):\n \"\"\"Split a nodeid into constituent 'parts'.\n\n Node IDs are strings, and can be things like:\n ''\n 'testing/code'\n 'testing/code/test_excinfo.py'\n 'testing/code/test_excinfo.py::TestFormattedExcinfo'\n\n Return values are lists e.g.\n []\n ['testing', 'code']\n ['testing', 'code', 'test_excinfo.py']\n ['testing', 'code', 'test_excinfo.py', 'TestFormattedExcinfo', '()']\n \"\"\"\n if nodeid == \"\":\n # If there is no root node at all, return an empty list so the caller's logic can remain sane\n return []\n parts = nodeid.split(SEP)\n # Replace single last element 'test_foo.py::Bar' with multiple elements 'test_foo.py', 'Bar'\n parts[-1:] = parts[-1].split(\"::\")\n return parts\n\n\ndef ischildnode(baseid, nodeid):\n \"\"\"Return True if the nodeid is a child node of the baseid.\n\n E.g. 'foo/bar::Baz' is a child of 'foo', 'foo/bar' and 'foo/bar::Baz', but not of 'foo/blorp'\n \"\"\"\n base_parts = _splitnode(baseid)\n node_parts = _splitnode(nodeid)\n if len(node_parts) < len(base_parts):\n return False\n return node_parts[: len(base_parts)] == base_parts\n\n\nclass Node(object):\n \"\"\" base class for Collector and Item the test collection tree.\n Collector subclasses have children, Items are terminal nodes.\"\"\"\n\n def __init__(\n self, name, parent=None, config=None, session=None, fspath=None, nodeid=None\n ):\n #: a unique name within the scope of the parent node\n self.name = name\n\n #: the parent collector node.\n self.parent = parent\n\n #: the pytest config object\n self.config = config or parent.config\n\n #: the session this node is part of\n self.session = session or parent.session\n\n #: filesystem path where this node was collected from (can be None)\n self.fspath = fspath or getattr(parent, \"fspath\", None)\n\n #: keywords/markers collected from all scopes\n self.keywords = NodeKeywords(self)\n\n #: the marker objects belonging to this node\n self.own_markers = []\n\n #: allow adding of extra keywords to use for matching\n self.extra_keyword_matches = set()\n\n # used for storing artificial fixturedefs for direct parametrization\n self._name2pseudofixturedef = {}\n\n if nodeid is not None:\n assert \"::()\" not in nodeid\n self._nodeid = nodeid\n else:\n self._nodeid = self.parent.nodeid\n if self.name != \"()\":\n self._nodeid += \"::\" + self.name\n\n @property\n def ihook(self):\n \"\"\" fspath sensitive hook proxy used to call pytest hooks\"\"\"\n return self.session.gethookproxy(self.fspath)\n\n def __repr__(self):\n return \"<%s %s>\" % (self.__class__.__name__, getattr(self, \"name\", None))\n\n def warn(self, warning):\n \"\"\"Issue a warning for this item.\n\n Warnings will be displayed after the test session, unless explicitly suppressed\n\n :param Warning warning: the warning instance to issue. Must be a subclass of PytestWarning.\n\n :raise ValueError: if ``warning`` instance is not a subclass of PytestWarning.\n\n Example usage:\n\n .. code-block:: python\n\n node.warn(PytestWarning(\"some message\"))\n\n \"\"\"\n from _pytest.warning_types import PytestWarning\n\n if not isinstance(warning, PytestWarning):\n raise ValueError(\n \"warning must be an instance of PytestWarning or subclass, got {!r}\".format(\n warning\n )\n )\n path, lineno = get_fslocation_from_item(self)\n warnings.warn_explicit(\n warning,\n category=None,\n filename=str(path),\n lineno=lineno + 1 if lineno is not None else None,\n )\n\n # methods for ordering nodes\n @property\n def nodeid(self):\n \"\"\" a ::-separated string denoting its collection tree address. \"\"\"\n return self._nodeid\n\n def __hash__(self):\n return hash(self.nodeid)\n\n def setup(self):\n pass\n\n def teardown(self):\n pass\n\n def listchain(self):\n \"\"\" return list of all parent collectors up to self,\n starting from root of collection tree. \"\"\"\n chain = []\n item = self\n while item is not None:\n chain.append(item)\n item = item.parent\n chain.reverse()\n return chain\n\n def add_marker(self, marker, append=True):\n \"\"\"dynamically add a marker object to the node.\n\n :type marker: ``str`` or ``pytest.mark.*`` object\n :param marker:\n ``append=True`` whether to append the marker,\n if ``False`` insert at position ``0``.\n \"\"\"\n from _pytest.mark import MarkDecorator, MARK_GEN\n\n if isinstance(marker, six.string_types):\n marker = getattr(MARK_GEN, marker)\n elif not isinstance(marker, MarkDecorator):\n raise ValueError(\"is not a string or pytest.mark.* Marker\")\n self.keywords[marker.name] = marker\n if append:\n self.own_markers.append(marker.mark)\n else:\n self.own_markers.insert(0, marker.mark)\n\n def iter_markers(self, name=None):\n \"\"\"\n :param name: if given, filter the results by the name attribute\n\n iterate over all markers of the node\n \"\"\"\n return (x[1] for x in self.iter_markers_with_node(name=name))\n\n def iter_markers_with_node(self, name=None):\n \"\"\"\n :param name: if given, filter the results by the name attribute\n\n iterate over all markers of the node\n returns sequence of tuples (node, mark)\n \"\"\"\n for node in reversed(self.listchain()):\n for mark in node.own_markers:\n if name is None or getattr(mark, \"name\", None) == name:\n yield node, mark\n\n def get_closest_marker(self, name, default=None):\n \"\"\"return the first marker matching the name, from closest (for example function) to farther level (for example\n module level).\n\n :param default: fallback return value of no marker was found\n :param name: name to filter by\n \"\"\"\n return next(self.iter_markers(name=name), default)\n\n def listextrakeywords(self):\n \"\"\" Return a set of all extra keywords in self and any parents.\"\"\"\n extra_keywords = set()\n for item in self.listchain():\n extra_keywords.update(item.extra_keyword_matches)\n return extra_keywords\n\n def listnames(self):\n return [x.name for x in self.listchain()]\n\n def addfinalizer(self, fin):\n \"\"\" register a function to be called when this node is finalized.\n\n This method can only be called when this node is active\n in a setup chain, for example during self.setup().\n \"\"\"\n self.session._setupstate.addfinalizer(fin, self)\n\n def getparent(self, cls):\n \"\"\" get the next parent node (including ourself)\n which is an instance of the given class\"\"\"\n current = self\n while current and not isinstance(current, cls):\n current = current.parent\n return current\n\n def _prunetraceback(self, excinfo):\n pass\n\n def _repr_failure_py(self, excinfo, style=None):\n if excinfo.errisinstance(fail.Exception):\n if not excinfo.value.pytrace:\n return six.text_type(excinfo.value)\n fm = self.session._fixturemanager\n if excinfo.errisinstance(fm.FixtureLookupError):\n return excinfo.value.formatrepr()\n tbfilter = True\n if self.config.getoption(\"fulltrace\", False):\n style = \"long\"\n else:\n tb = _pytest._code.Traceback([excinfo.traceback[-1]])\n self._prunetraceback(excinfo)\n if len(excinfo.traceback) == 0:\n excinfo.traceback = tb\n tbfilter = False # prunetraceback already does it\n if style == \"auto\":\n style = \"long\"\n # XXX should excinfo.getrepr record all data and toterminal() process it?\n if style is None:\n if self.config.getoption(\"tbstyle\", \"auto\") == \"short\":\n style = \"short\"\n else:\n style = \"long\"\n\n if self.config.getoption(\"verbose\", 0) > 1:\n truncate_locals = False\n else:\n truncate_locals = True\n\n try:\n os.getcwd()\n abspath = False\n except OSError:\n abspath = True\n\n return excinfo.getrepr(\n funcargs=True,\n abspath=abspath,\n showlocals=self.config.getoption(\"showlocals\", False),\n style=style,\n tbfilter=tbfilter,\n truncate_locals=truncate_locals,\n )\n\n repr_failure = _repr_failure_py\n\n\ndef get_fslocation_from_item(item):\n \"\"\"Tries to extract the actual location from an item, depending on available attributes:\n\n * \"fslocation\": a pair (path, lineno)\n * \"obj\": a Python object that the item wraps.\n * \"fspath\": just a path\n\n :rtype: a tuple of (str|LocalPath, int) with filename and line number.\n \"\"\"\n result = getattr(item, \"location\", None)\n if result is not None:\n return result[:2]\n obj = getattr(item, \"obj\", None)\n if obj is not None:\n return getfslineno(obj)\n return getattr(item, \"fspath\", \"unknown location\"), -1\n\n\nclass Collector(Node):\n \"\"\" Collector instances create children through collect()\n and thus iteratively build a tree.\n \"\"\"\n\n class CollectError(Exception):\n \"\"\" an error during collection, contains a custom message. \"\"\"\n\n def collect(self):\n \"\"\" returns a list of children (items and collectors)\n for this collection node.\n \"\"\"\n raise NotImplementedError(\"abstract\")\n\n def repr_failure(self, excinfo):\n \"\"\" represent a collection failure. \"\"\"\n if excinfo.errisinstance(self.CollectError):\n exc = excinfo.value\n return str(exc.args[0])\n\n # Respect explicit tbstyle option, but default to \"short\"\n # (None._repr_failure_py defaults to \"long\" without \"fulltrace\" option).\n tbstyle = self.config.getoption(\"tbstyle\", \"auto\")\n if tbstyle == \"auto\":\n tbstyle = \"short\"\n\n return self._repr_failure_py(excinfo, style=tbstyle)\n\n def _prunetraceback(self, excinfo):\n if hasattr(self, \"fspath\"):\n traceback = excinfo.traceback\n ntraceback = traceback.cut(path=self.fspath)\n if ntraceback == traceback:\n ntraceback = ntraceback.cut(excludepath=tracebackcutdir)\n excinfo.traceback = ntraceback.filter()\n\n\ndef _check_initialpaths_for_relpath(session, fspath):\n for initial_path in session._initialpaths:\n if fspath.common(initial_path) == initial_path:\n return fspath.relto(initial_path)\n\n\nclass FSCollector(Collector):\n def __init__(self, fspath, parent=None, config=None, session=None, nodeid=None):\n fspath = py.path.local(fspath) # xxx only for test_resultlog.py?\n name = fspath.basename\n if parent is not None:\n rel = fspath.relto(parent.fspath)\n if rel:\n name = rel\n name = name.replace(os.sep, SEP)\n self.fspath = fspath\n\n session = session or parent.session\n\n if nodeid is None:\n nodeid = self.fspath.relto(session.config.rootdir)\n\n if not nodeid:\n nodeid = _check_initialpaths_for_relpath(session, fspath)\n if nodeid and os.sep != SEP:\n nodeid = nodeid.replace(os.sep, SEP)\n\n super(FSCollector, self).__init__(\n name, parent, config, session, nodeid=nodeid, fspath=fspath\n )\n\n\nclass File(FSCollector):\n \"\"\" base class for collecting tests from a file. \"\"\"\n\n\nclass Item(Node):\n \"\"\" a basic test invocation item. Note that for a single function\n there might be multiple test invocation items.\n \"\"\"\n\n nextitem = None\n\n def __init__(self, name, parent=None, config=None, session=None, nodeid=None):\n super(Item, self).__init__(name, parent, config, session, nodeid=nodeid)\n self._report_sections = []\n\n #: user properties is a list of tuples (name, value) that holds user\n #: defined properties for this test.\n self.user_properties = []\n\n def add_report_section(self, when, key, content):\n \"\"\"\n Adds a new report section, similar to what's done internally to add stdout and\n stderr captured output::\n\n item.add_report_section(\"call\", \"stdout\", \"report section contents\")\n\n :param str when:\n One of the possible capture states, ``\"setup\"``, ``\"call\"``, ``\"teardown\"``.\n :param str key:\n Name of the section, can be customized at will. Pytest uses ``\"stdout\"`` and\n ``\"stderr\"`` internally.\n\n :param str content:\n The full contents as a string.\n \"\"\"\n if content:\n self._report_sections.append((when, key, content))\n\n def reportinfo(self):\n return self.fspath, None, \"\"\n\n @property\n def location(self):\n try:\n return self._location\n except AttributeError:\n location = self.reportinfo()\n fspath = self.session._node_location_to_relpath(location[0])\n location = (fspath, location[1], str(location[2]))\n self._location = location\n return location\n"},{"attributeType":"str","col":0,"comment":"null","endLoc":17,"id":3868,"name":"SEP","nodeType":"Attribute","startLoc":17,"text":"SEP"},{"attributeType":"null","col":0,"comment":"null","endLoc":19,"id":3869,"name":"tracebackcutdir","nodeType":"Attribute","startLoc":19,"text":"tracebackcutdir"},{"col":0,"comment":"","endLoc":2,"header":"nodes.py#","id":3870,"name":"","nodeType":"Function","startLoc":2,"text":"SEP = \"/\"\n\ntracebackcutdir = py.path.local(_pytest.__file__).dirpath()"},{"col":4,"comment":"Implements the internals of pytest_runtest_xxx() hook.","endLoc":577,"header":"@contextmanager\n def _runtest_for_main(self, item, when)","id":3871,"name":"_runtest_for_main","nodeType":"Function","startLoc":550,"text":"@contextmanager\n def _runtest_for_main(self, item, when):\n \"\"\"Implements the internals of pytest_runtest_xxx() hook.\"\"\"\n with catching_logs(\n LogCaptureHandler(), formatter=self.formatter, level=self.log_level\n ) as log_handler:\n if self.log_cli_handler:\n self.log_cli_handler.set_when(when)\n\n if item is None:\n yield # run the test\n return\n\n if not hasattr(item, \"catch_log_handlers\"):\n item.catch_log_handlers = {}\n item.catch_log_handlers[when] = log_handler\n item.catch_log_handler = log_handler\n try:\n yield # run test\n finally:\n if when == \"teardown\":\n del item.catch_log_handler\n del item.catch_log_handlers\n\n if self.print_logs:\n # Add a captured log section to the report.\n log = log_handler.stream.getvalue().strip()\n item.add_report_section(when, \"log\", log)"},{"col":4,"comment":"test that filter_traceback() works with the fact that\n _pytest._code.code.Code.path attribute might return an str object.\n In this case, one of the files in the traceback no longer exists.\n This fixes #1133.\n ","endLoc":1022,"header":"def test_filter_traceback_path_no_longer_valid(self, testdir)","id":3872,"name":"test_filter_traceback_path_no_longer_valid","nodeType":"Function","startLoc":997,"text":"def test_filter_traceback_path_no_longer_valid(self, testdir):\n \"\"\"test that filter_traceback() works with the fact that\n _pytest._code.code.Code.path attribute might return an str object.\n In this case, one of the files in the traceback no longer exists.\n This fixes #1133.\n \"\"\"\n from _pytest.python import filter_traceback\n\n testdir.syspathinsert()\n testdir.makepyfile(\n filter_traceback_entry_as_str=\"\"\"\n def foo():\n raise ValueError\n \"\"\"\n )\n try:\n import filter_traceback_entry_as_str\n\n filter_traceback_entry_as_str.foo()\n except ValueError:\n _, _, tb = sys.exc_info()\n\n testdir.tmpdir.join(\"filter_traceback_entry_as_str.py\").remove()\n tb = _pytest._code.Traceback(tb)\n assert isinstance(tb[-1].path, str)\n assert filter_traceback(tb[-1])"},{"id":3873,"name":"testing/example_scripts/conftest_usageerror","nodeType":"Package"},{"fileName":"conftest.py","filePath":"testing/example_scripts/conftest_usageerror","id":3874,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ndef pytest_configure(config):\n import pytest\n\n raise pytest.UsageError(\"hello\")\n\n\ndef pytest_unconfigure(config):\n print(\"pytest_unconfigure_called\")\n"},{"col":0,"comment":"null","endLoc":5,"header":"def pytest_configure(config)","id":3875,"name":"pytest_configure","nodeType":"Function","startLoc":2,"text":"def pytest_configure(config):\n import pytest\n\n raise pytest.UsageError(\"hello\")"},{"col":0,"comment":"null","endLoc":9,"header":"def pytest_unconfigure(config)","id":3876,"name":"pytest_unconfigure","nodeType":"Function","startLoc":8,"text":"def pytest_unconfigure(config):\n print(\"pytest_unconfigure_called\")"},{"id":3877,"name":".gitignore","nodeType":"TextFile","path":"testing/example_scripts/perf_examples/collect_stats","text":"foo_*\n"},{"col":4,"comment":"Check that all attributes of a request in an autouse fixture\n behave as expected when requested for a doctest item.\n ","endLoc":1077,"header":"@pytest.mark.parametrize(\"scope\", SCOPES)\n def test_auto_use_request_attributes(self, testdir, scope)","id":3878,"name":"test_auto_use_request_attributes","nodeType":"Function","startLoc":1047,"text":"@pytest.mark.parametrize(\"scope\", SCOPES)\n def test_auto_use_request_attributes(self, testdir, scope):\n \"\"\"Check that all attributes of a request in an autouse fixture\n behave as expected when requested for a doctest item.\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture(autouse=True, scope=\"{scope}\")\n def auto(request):\n if \"{scope}\" == 'module':\n assert request.module is None\n if \"{scope}\" == 'class':\n assert request.cls is None\n if \"{scope}\" == 'function':\n assert request.function is None\n return 99\n \"\"\".format(\n scope=scope\n )\n )\n testdir.maketxtfile(\n test_doc=\"\"\"\n >>> 1 + 1\n 2\n \"\"\"\n )\n result = testdir.runpytest(\"--doctest-modules\")\n assert \"FAILURES\" not in str(result.stdout.str())\n result.stdout.fnmatch_lines([\"*=== 1 passed in *\"])"},{"className":"TestReportInfo","col":0,"comment":"null","endLoc":1081,"id":3879,"nodeType":"Class","startLoc":1025,"text":"class TestReportInfo(object):\n def test_itemreport_reportinfo(self, testdir, linecomp):\n testdir.makeconftest(\n \"\"\"\n import pytest\n class MyFunction(pytest.Function):\n def reportinfo(self):\n return \"ABCDE\", 42, \"custom\"\n def pytest_pycollect_makeitem(collector, name, obj):\n if name == \"test_func\":\n return MyFunction(name, parent=collector)\n \"\"\"\n )\n item = testdir.getitem(\"def test_func(): pass\")\n item.config.pluginmanager.getplugin(\"runner\")\n assert item.location == (\"ABCDE\", 42, \"custom\")\n\n def test_func_reportinfo(self, testdir):\n item = testdir.getitem(\"def test_func(): pass\")\n fspath, lineno, modpath = item.reportinfo()\n assert fspath == item.fspath\n assert lineno == 0\n assert modpath == \"test_func\"\n\n def test_class_reportinfo(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n # lineno 0\n class TestClass(object):\n def test_hello(self): pass\n \"\"\"\n )\n classcol = testdir.collect_by_name(modcol, \"TestClass\")\n fspath, lineno, msg = classcol.reportinfo()\n assert fspath == modcol.fspath\n assert lineno == 1\n assert msg == \"TestClass\"\n\n @pytest.mark.filterwarnings(\n \"ignore:usage of Generator.Function is deprecated, please use pytest.Function instead\"\n )\n def test_reportinfo_with_nasty_getattr(self, testdir):\n # https://github.com/pytest-dev/pytest/issues/1204\n modcol = testdir.getmodulecol(\n \"\"\"\n # lineno 0\n class TestClass(object):\n def __getattr__(self, name):\n return \"this is not an int\"\n\n def test_foo(self):\n pass\n \"\"\"\n )\n classcol = testdir.collect_by_name(modcol, \"TestClass\")\n instance = classcol.collect()[0]\n fspath, lineno, msg = instance.reportinfo()"},{"col":4,"comment":"null","endLoc":1040,"header":"def test_itemreport_reportinfo(self, testdir, linecomp)","id":3880,"name":"test_itemreport_reportinfo","nodeType":"Function","startLoc":1026,"text":"def test_itemreport_reportinfo(self, testdir, linecomp):\n testdir.makeconftest(\n \"\"\"\n import pytest\n class MyFunction(pytest.Function):\n def reportinfo(self):\n return \"ABCDE\", 42, \"custom\"\n def pytest_pycollect_makeitem(collector, name, obj):\n if name == \"test_func\":\n return MyFunction(name, parent=collector)\n \"\"\"\n )\n item = testdir.getitem(\"def test_func(): pass\")\n item.config.pluginmanager.getplugin(\"runner\")\n assert item.location == (\"ABCDE\", 42, \"custom\")"},{"col":4,"comment":"null","endLoc":1047,"header":"def test_func_reportinfo(self, testdir)","id":3881,"name":"test_func_reportinfo","nodeType":"Function","startLoc":1042,"text":"def test_func_reportinfo(self, testdir):\n item = testdir.getitem(\"def test_func(): pass\")\n fspath, lineno, modpath = item.reportinfo()\n assert fspath == item.fspath\n assert lineno == 0\n assert modpath == \"test_func\""},{"col":4,"comment":"null","endLoc":1061,"header":"def test_class_reportinfo(self, testdir)","id":3882,"name":"test_class_reportinfo","nodeType":"Function","startLoc":1049,"text":"def test_class_reportinfo(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n # lineno 0\n class TestClass(object):\n def test_hello(self): pass\n \"\"\"\n )\n classcol = testdir.collect_by_name(modcol, \"TestClass\")\n fspath, lineno, msg = classcol.reportinfo()\n assert fspath == modcol.fspath\n assert lineno == 1\n assert msg == \"TestClass\""},{"col":4,"comment":"null","endLoc":1081,"header":"@pytest.mark.filterwarnings(\n \"ignore:usage of Generator.Function is deprecated, please use pytest.Function instead\"\n )\n def test_reportinfo_with_nasty_getattr(self, testdir)","id":3883,"name":"test_reportinfo_with_nasty_getattr","nodeType":"Function","startLoc":1063,"text":"@pytest.mark.filterwarnings(\n \"ignore:usage of Generator.Function is deprecated, please use pytest.Function instead\"\n )\n def test_reportinfo_with_nasty_getattr(self, testdir):\n # https://github.com/pytest-dev/pytest/issues/1204\n modcol = testdir.getmodulecol(\n \"\"\"\n # lineno 0\n class TestClass(object):\n def __getattr__(self, name):\n return \"this is not an int\"\n\n def test_foo(self):\n pass\n \"\"\"\n )\n classcol = testdir.collect_by_name(modcol, \"TestClass\")\n instance = classcol.collect()[0]\n fspath, lineno, msg = instance.reportinfo()"},{"col":0,"comment":"null","endLoc":886,"header":"def test_setup_only_available_in_subdir(testdir)","id":3884,"name":"test_setup_only_available_in_subdir","nodeType":"Function","startLoc":854,"text":"def test_setup_only_available_in_subdir(testdir):\n sub1 = testdir.mkpydir(\"sub1\")\n sub2 = testdir.mkpydir(\"sub2\")\n sub1.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n def pytest_runtest_setup(item):\n assert item.fspath.purebasename == \"test_in_sub1\"\n def pytest_runtest_call(item):\n assert item.fspath.purebasename == \"test_in_sub1\"\n def pytest_runtest_teardown(item):\n assert item.fspath.purebasename == \"test_in_sub1\"\n \"\"\"\n )\n )\n sub2.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n def pytest_runtest_setup(item):\n assert item.fspath.purebasename == \"test_in_sub2\"\n def pytest_runtest_call(item):\n assert item.fspath.purebasename == \"test_in_sub2\"\n def pytest_runtest_teardown(item):\n assert item.fspath.purebasename == \"test_in_sub2\"\n \"\"\"\n )\n )\n sub1.join(\"test_in_sub1.py\").write(\"def test_1(): pass\")\n sub2.join(\"test_in_sub2.py\").write(\"def test_2(): pass\")\n result = testdir.runpytest(\"-v\", \"-s\")\n result.assert_outcomes(passed=2)"},{"attributeType":"list","col":4,"comment":"null","endLoc":938,"id":3885,"name":"SCOPES","nodeType":"Attribute","startLoc":938,"text":"SCOPES"},{"className":"TestDoctestNamespaceFixture","col":0,"comment":"null","endLoc":1139,"id":3886,"nodeType":"Class","startLoc":1080,"text":"class TestDoctestNamespaceFixture(object):\n\n SCOPES = [\"module\", \"session\", \"class\", \"function\"]\n\n @pytest.mark.parametrize(\"scope\", SCOPES)\n def test_namespace_doctestfile(self, testdir, scope):\n \"\"\"\n Check that inserting something into the namespace works in a\n simple text file doctest\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n import contextlib\n\n @pytest.fixture(autouse=True, scope=\"{scope}\")\n def add_contextlib(doctest_namespace):\n doctest_namespace['cl'] = contextlib\n \"\"\".format(\n scope=scope\n )\n )\n p = testdir.maketxtfile(\n \"\"\"\n >>> print(cl.__name__)\n contextlib\n \"\"\"\n )\n reprec = testdir.inline_run(p)\n reprec.assertoutcome(passed=1)\n\n @pytest.mark.parametrize(\"scope\", SCOPES)\n def test_namespace_pyfile(self, testdir, scope):\n \"\"\"\n Check that inserting something into the namespace works in a\n simple Python file docstring doctest\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n import contextlib\n\n @pytest.fixture(autouse=True, scope=\"{scope}\")\n def add_contextlib(doctest_namespace):\n doctest_namespace['cl'] = contextlib\n \"\"\".format(\n scope=scope\n )\n )\n p = testdir.makepyfile(\n \"\"\"\n def foo():\n '''\n >>> print(cl.__name__)\n contextlib\n '''\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":"\n Check that inserting something into the namespace works in a\n simple text file doctest\n ","endLoc":1109,"header":"@pytest.mark.parametrize(\"scope\", SCOPES)\n def test_namespace_doctestfile(self, testdir, scope)","id":3887,"name":"test_namespace_doctestfile","nodeType":"Function","startLoc":1084,"text":"@pytest.mark.parametrize(\"scope\", SCOPES)\n def test_namespace_doctestfile(self, testdir, scope):\n \"\"\"\n Check that inserting something into the namespace works in a\n simple text file doctest\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n import contextlib\n\n @pytest.fixture(autouse=True, scope=\"{scope}\")\n def add_contextlib(doctest_namespace):\n doctest_namespace['cl'] = contextlib\n \"\"\".format(\n scope=scope\n )\n )\n p = testdir.maketxtfile(\n \"\"\"\n >>> print(cl.__name__)\n contextlib\n \"\"\"\n )\n reprec = testdir.inline_run(p)\n reprec.assertoutcome(passed=1)"},{"col":0,"comment":"null","endLoc":893,"header":"def test_modulecol_roundtrip(testdir)","id":3888,"name":"test_modulecol_roundtrip","nodeType":"Function","startLoc":889,"text":"def test_modulecol_roundtrip(testdir):\n modcol = testdir.getmodulecol(\"pass\", withinit=False)\n trail = modcol.nodeid\n newcol = modcol.session.perform_collect([trail], genitems=0)[0]\n assert modcol.name == newcol.name"},{"col":0,"comment":"null","endLoc":1111,"header":"def test_customized_python_discovery(testdir)","id":3889,"name":"test_customized_python_discovery","nodeType":"Function","startLoc":1084,"text":"def test_customized_python_discovery(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n python_files=check_*.py\n python_classes=Check\n python_functions=check\n \"\"\"\n )\n p = testdir.makepyfile(\n \"\"\"\n def check_simple():\n pass\n class CheckMyApp(object):\n def check_meth(self):\n pass\n \"\"\"\n )\n p2 = p.new(basename=p.basename.replace(\"test\", \"check\"))\n p.move(p2)\n result = testdir.runpytest(\"--collect-only\", \"-s\")\n result.stdout.fnmatch_lines(\n [\"*check_customized*\", \"*check_simple*\", \"*CheckMyApp*\", \"*check_meth*\"]\n )\n\n result = testdir.runpytest()\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*2 passed*\"])"},{"col":4,"comment":"\n Check that inserting something into the namespace works in a\n simple Python file docstring doctest\n ","endLoc":1139,"header":"@pytest.mark.parametrize(\"scope\", SCOPES)\n def test_namespace_pyfile(self, testdir, scope)","id":3890,"name":"test_namespace_pyfile","nodeType":"Function","startLoc":1111,"text":"@pytest.mark.parametrize(\"scope\", SCOPES)\n def test_namespace_pyfile(self, testdir, scope):\n \"\"\"\n Check that inserting something into the namespace works in a\n simple Python file docstring doctest\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n import contextlib\n\n @pytest.fixture(autouse=True, scope=\"{scope}\")\n def add_contextlib(doctest_namespace):\n doctest_namespace['cl'] = contextlib\n \"\"\".format(\n scope=scope\n )\n )\n p = testdir.makepyfile(\n \"\"\"\n def foo():\n '''\n >>> print(cl.__name__)\n contextlib\n '''\n \"\"\"\n )\n reprec = testdir.inline_run(p, \"--doctest-modules\")\n reprec.assertoutcome(passed=1)"},{"col":0,"comment":"null","endLoc":1132,"header":"def test_customized_python_discovery_functions(testdir)","id":3891,"name":"test_customized_python_discovery_functions","nodeType":"Function","startLoc":1114,"text":"def test_customized_python_discovery_functions(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n python_functions=_test\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def _test_underscore():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\", \"-s\")\n result.stdout.fnmatch_lines([\"*_test_underscore*\"])\n\n result = testdir.runpytest()\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":4,"comment":"directly from optparse\n\n might not be necessary as this is passed to argparse later on","endLoc":269,"header":"def _set_opt_strings(self, opts)","id":3892,"name":"_set_opt_strings","nodeType":"Function","startLoc":243,"text":"def _set_opt_strings(self, opts):\n \"\"\"directly from optparse\n\n might not be necessary as this is passed to argparse later on\"\"\"\n for opt in opts:\n if len(opt) < 2:\n raise ArgumentError(\n \"invalid option string %r: \"\n \"must be at least two characters long\" % opt,\n self,\n )\n elif len(opt) == 2:\n if not (opt[0] == \"-\" and opt[1] != \"-\"):\n raise ArgumentError(\n \"invalid short option string %r: \"\n \"must be of the form -x, (x any non-dash char)\" % opt,\n self,\n )\n self._short_opts.append(opt)\n else:\n if not (opt[0:2] == \"--\" and opt[2] != \"-\"):\n raise ArgumentError(\n \"invalid long option string %r: \"\n \"must start with --, followed by non-dash\" % opt,\n self,\n )\n self._long_opts.append(opt)"},{"col":0,"comment":"null","endLoc":1151,"header":"def test_unorderable_types(testdir)","id":3893,"name":"test_unorderable_types","nodeType":"Function","startLoc":1135,"text":"def test_unorderable_types(testdir):\n testdir.makepyfile(\n \"\"\"\n class TestJoinEmpty(object):\n pass\n\n def make_test():\n class Test(object):\n pass\n Test.__name__ = \"TestFoo\"\n return Test\n TestFoo = make_test()\n \"\"\"\n )\n result = testdir.runpytest()\n assert \"TypeError\" not in result.stdout.str()\n assert result.ret == EXIT_NOTESTSCOLLECTED"},{"col":0,"comment":"\n Test that collection of functools.partial object works, and arguments\n to the wrapped functions are dealt correctly (see #811).\n ","endLoc":1197,"header":"def test_collect_functools_partial(testdir)","id":3894,"name":"test_collect_functools_partial","nodeType":"Function","startLoc":1154,"text":"def test_collect_functools_partial(testdir):\n \"\"\"\n Test that collection of functools.partial object works, and arguments\n to the wrapped functions are dealt correctly (see #811).\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import functools\n import pytest\n\n @pytest.fixture\n def fix1():\n return 'fix1'\n\n @pytest.fixture\n def fix2():\n return 'fix2'\n\n def check1(i, fix1):\n assert i == 2\n assert fix1 == 'fix1'\n\n def check2(fix1, i):\n assert i == 2\n assert fix1 == 'fix1'\n\n def check3(fix1, i, fix2):\n assert i == 2\n assert fix1 == 'fix1'\n assert fix2 == 'fix2'\n\n test_ok_1 = functools.partial(check1, i=2)\n test_ok_2 = functools.partial(check1, i=2, fix1='fix1')\n test_ok_3 = functools.partial(check1, 2)\n test_ok_4 = functools.partial(check2, i=2)\n test_ok_5 = functools.partial(check3, i=2)\n test_ok_6 = functools.partial(check3, i=2, fix1='fix1')\n\n test_fail_1 = functools.partial(check2, 2)\n test_fail_2 = functools.partial(check3, 2)\n \"\"\"\n )\n result = testdir.inline_run()\n result.assertoutcome(passed=6, failed=2)"},{"col":0,"comment":"Test for issue https://github.com/pytest-dev/pytest/issues/331\n\n In this case an INTERNALERROR occurred trying to report the failure of\n a test like this one because py test failed to get the source lines.\n ","endLoc":1226,"header":"@pytest.mark.filterwarnings(\"default\")\ndef test_dont_collect_non_function_callable(testdir)","id":3895,"name":"test_dont_collect_non_function_callable","nodeType":"Function","startLoc":1200,"text":"@pytest.mark.filterwarnings(\"default\")\ndef test_dont_collect_non_function_callable(testdir):\n \"\"\"Test for issue https://github.com/pytest-dev/pytest/issues/331\n\n In this case an INTERNALERROR occurred trying to report the failure of\n a test like this one because py test failed to get the source lines.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n class Oh(object):\n def __call__(self):\n pass\n\n test_a = Oh()\n\n def test_real():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rw\")\n result.stdout.fnmatch_lines(\n [\n \"*collected 1 item*\",\n \"*test_dont_collect_non_function_callable.py:2: *cannot collect 'test_a' because it is not a function*\",\n \"*1 passed, 1 warnings in *\",\n ]\n )"},{"col":4,"comment":"null","endLoc":144,"header":"def __init__(self, msg, option)","id":3896,"name":"__init__","nodeType":"Function","startLoc":142,"text":"def __init__(self, msg, option):\n self.msg = msg\n self.option_id = str(option)"},{"col":0,"comment":"","endLoc":2,"header":"generate_folders.py#","id":3897,"name":"","nodeType":"Function","startLoc":2,"text":"HERE = pathlib.Path(__file__).parent\n\nTEST_CONTENT = (HERE / \"template_test.py\").read_bytes()\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"numbers\", nargs=\"*\", type=int)\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n generate_folders(HERE, *(args.numbers or (10, 100)))"},{"col":0,"comment":"Tests whether injection during collection time will terminate testing.\n\n In this case the error should not occur if the TestClass itself\n is modified during collection time, and the original method list\n is still used for collection.\n ","endLoc":1256,"header":"def test_class_injection_does_not_break_collection(testdir)","id":3898,"name":"test_class_injection_does_not_break_collection","nodeType":"Function","startLoc":1229,"text":"def test_class_injection_does_not_break_collection(testdir):\n \"\"\"Tests whether injection during collection time will terminate testing.\n\n In this case the error should not occur if the TestClass itself\n is modified during collection time, and the original method list\n is still used for collection.\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n from test_inject import TestClass\n def pytest_generate_tests(metafunc):\n TestClass.changed_var = {}\n \"\"\"\n )\n testdir.makepyfile(\n test_inject='''\n class TestClass(object):\n def test_injection(self):\n \"\"\"Test being parametrized.\"\"\"\n pass\n '''\n )\n result = testdir.runpytest()\n assert (\n \"RuntimeError: dictionary changed size during iteration\"\n not in result.stdout.str()\n )\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"id":3899,"name":"release-2.8.3.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.8.3: bug fixes\n=======================\n\npytest is a mature Python testing tool with more than a 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is supposed to be drop-in compatible to 2.8.2.\n\nSee below for the changes and see docs at:\n\n http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n Bruno Oliveira\n Florian Bruhin\n Gabe Hollombe\n Gabriel Reis\n Hartmut Goebel\n John Vandenberg\n Lee Kamentsky\n Michael Birtwell\n Raphael Pierzina\n Ronny Pfannschmidt\n William Martin Stewart\n\nHappy testing,\nThe py.test Development Team\n\n\n2.8.3 (compared to 2.8.2)\n-----------------------------\n\n- fix #1169: add __name__ attribute to testcases in TestCaseFunction to\n support the @unittest.skip decorator on functions and methods.\n Thanks Lee Kamentsky for the PR.\n\n- fix #1035: collecting tests if test module level obj has __getattr__().\n Thanks Suor for the report and Bruno Oliveira / Tom Viner for the PR.\n\n- fix #331: don't collect tests if their failure cannot be reported correctly\n e.g. they are a callable instance of a class.\n\n- fix #1133: fixed internal error when filtering tracebacks where one entry\n belongs to a file which is no longer available.\n Thanks Bruno Oliveira for the PR.\n\n- enhancement made to highlight in red the name of the failing tests so\n they stand out in the output.\n Thanks Gabriel Reis for the PR.\n\n- add more talks to the documentation\n- extend documentation on the --ignore cli option\n- use pytest-runner for setuptools integration\n- minor fixes for interaction with OS X El Capitan system integrity protection (thanks Florian)\n"},{"id":3900,"name":"release-3.7.3.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.7.3\n=======================================\n\npytest 3.7.3 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Andrew Champion\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Gandalf Saxe\n* Jennifer Rinker\n* Natan Lao\n* Ondřej Súkup\n* Ronny Pfannschmidt\n* Sankt Petersbug\n* Tyler Richard\n* Victor Maryama\n* Vlad Shcherbina\n* turturica\n* wim glenn\n\n\nHappy testing,\nThe pytest Development Team\n"},{"id":3901,"name":"release-3.3.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.3.0\n=======================================\n\nThe pytest team is proud to announce the 3.3.0 release!\n\npytest is a mature Python testing tool with more than a 1600 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n http://doc.pytest.org/en/latest/changelog.html\n\nFor complete documentation, please visit:\n\n http://docs.pytest.org\n\nAs usual, you can upgrade from pypi via:\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Ceridwen\n* Daniel Hahler\n* Dirk Thomas\n* Dmitry Malinovsky\n* Florian Bruhin\n* George Y. Kussumoto\n* Hugo\n* Jesús Espino\n* Joan Massich\n* Ofir\n* OfirOshir\n* Ronny Pfannschmidt\n* Samuel Dion-Girardeau\n* Srinivas Reddy Thatiparthy\n* Sviatoslav Abakumov\n* Tarcisio Fischer\n* Thomas Hisch\n* Tyler Goodlet\n* hugovk\n* je\n* prokaktus\n\n\nHappy testing,\nThe Pytest Development Team\n"},{"attributeType":"list","col":4,"comment":"null","endLoc":1082,"id":3902,"name":"SCOPES","nodeType":"Attribute","startLoc":1082,"text":"SCOPES"},{"col":0,"comment":"Fix decoding issue while formatting SyntaxErrors during collection (#578)\n ","endLoc":1270,"header":"def test_syntax_error_with_non_ascii_chars(testdir)","id":3903,"name":"test_syntax_error_with_non_ascii_chars","nodeType":"Function","startLoc":1259,"text":"def test_syntax_error_with_non_ascii_chars(testdir):\n \"\"\"Fix decoding issue while formatting SyntaxErrors during collection (#578)\n \"\"\"\n testdir.makepyfile(\n u\"\"\"\n # -*- coding: utf-8 -*-\n\n ☃\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*ERROR collecting*\", \"*SyntaxError*\", \"*1 error in*\"])"},{"className":"TestDoctestReportingOption","col":0,"comment":"null","endLoc":1223,"id":3904,"nodeType":"Class","startLoc":1142,"text":"class TestDoctestReportingOption(object):\n def _run_doctest_report(self, testdir, format):\n testdir.makepyfile(\n \"\"\"\n def foo():\n '''\n >>> foo()\n a b\n 0 1 4\n 1 2 4\n 2 3 6\n '''\n print(' a b\\\\n'\n '0 1 4\\\\n'\n '1 2 5\\\\n'\n '2 3 6')\n \"\"\"\n )\n return testdir.runpytest(\"--doctest-modules\", \"--doctest-report\", format)\n\n @pytest.mark.parametrize(\"format\", [\"udiff\", \"UDIFF\", \"uDiFf\"])\n def test_doctest_report_udiff(self, testdir, format):\n result = self._run_doctest_report(testdir, format)\n result.stdout.fnmatch_lines(\n [\" 0 1 4\", \" -1 2 4\", \" +1 2 5\", \" 2 3 6\"]\n )\n\n def test_doctest_report_cdiff(self, testdir):\n result = self._run_doctest_report(testdir, \"cdiff\")\n result.stdout.fnmatch_lines(\n [\n \" a b\",\n \" 0 1 4\",\n \" ! 1 2 4\",\n \" 2 3 6\",\n \" --- 1,4 ----\",\n \" a b\",\n \" 0 1 4\",\n \" ! 1 2 5\",\n \" 2 3 6\",\n ]\n )\n\n def test_doctest_report_ndiff(self, testdir):\n result = self._run_doctest_report(testdir, \"ndiff\")\n result.stdout.fnmatch_lines(\n [\n \" a b\",\n \" 0 1 4\",\n \" - 1 2 4\",\n \" ? ^\",\n \" + 1 2 5\",\n \" ? ^\",\n \" 2 3 6\",\n ]\n )\n\n @pytest.mark.parametrize(\"format\", [\"none\", \"only_first_failure\"])\n def test_doctest_report_none_or_only_first_failure(self, testdir, format):\n result = self._run_doctest_report(testdir, format)\n result.stdout.fnmatch_lines(\n [\n \"Expected:\",\n \" a b\",\n \" 0 1 4\",\n \" 1 2 4\",\n \" 2 3 6\",\n \"Got:\",\n \" a b\",\n \" 0 1 4\",\n \" 1 2 5\",\n \" 2 3 6\",\n ]\n )\n\n def test_doctest_report_invalid(self, testdir):\n result = self._run_doctest_report(testdir, \"obviously_invalid_format\")\n result.stderr.fnmatch_lines(\n [\n \"*error: argument --doctest-report: invalid choice: 'obviously_invalid_format' (choose from*\"\n ]\n )"},{"id":3905,"name":"release-2.5.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.5.1: fixes and new home page styling\n===========================================================================\n\npytest is a mature Python testing tool with more than a 1000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThe 2.5.1 release maintains the \"zero-reported-bugs\" promise by fixing\nthe three bugs reported since the last release a few days ago. It also\nfeatures a new home page styling implemented by Tobias Bieniek, based on\nthe flask theme from Armin Ronacher:\n\n http://pytest.org\n\nIf you have anything more to improve styling and docs,\nwe'd be very happy to merge further pull requests.\n\nOn the coding side, the release also contains a little enhancement to\nfixture decorators allowing to directly influence generation of test\nids, thanks to Floris Bruynooghe. Other thanks for helping with\nthis release go to Anatoly Bubenkoff and Ronny Pfannschmidt.\n\nAs usual, you can upgrade from pypi via::\n\n pip install -U pytest\n\nhave fun and a nice remaining \"bug-free\" time of the year :)\nholger krekel\n\n2.5.1\n-----------------------------------\n\n- merge new documentation styling PR from Tobias Bieniek.\n\n- fix issue403: allow parametrize of multiple same-name functions within\n a collection node. Thanks Andreas Kloeckner and Alex Gaynor for reporting\n and analysis.\n\n- Allow parameterized fixtures to specify the ID of the parameters by\n adding an ids argument to pytest.fixture() and pytest.yield_fixture().\n Thanks Floris Bruynooghe.\n\n- fix issue404 by always using the binary xml escape in the junitxml\n plugin. Thanks Ronny Pfannschmidt.\n\n- fix issue407: fix addoption docstring to point to argparse instead of\n optparse. Thanks Daniel D. Wright.\n"},{"col":4,"comment":"null","endLoc":1160,"header":"def _run_doctest_report(self, testdir, format)","id":3906,"name":"_run_doctest_report","nodeType":"Function","startLoc":1143,"text":"def _run_doctest_report(self, testdir, format):\n testdir.makepyfile(\n \"\"\"\n def foo():\n '''\n >>> foo()\n a b\n 0 1 4\n 1 2 4\n 2 3 6\n '''\n print(' a b\\\\n'\n '0 1 4\\\\n'\n '1 2 5\\\\n'\n '2 3 6')\n \"\"\"\n )\n return testdir.runpytest(\"--doctest-modules\", \"--doctest-report\", format)"},{"col":4,"comment":"null","endLoc":56,"header":"def toterminal(self, out)","id":3907,"name":"toterminal","nodeType":"Function","startLoc":42,"text":"def toterminal(self, out):\n if hasattr(self, \"node\"):\n out.line(getslaveinfoline(self.node))\n\n longrepr = self.longrepr\n if longrepr is None:\n return\n\n if hasattr(longrepr, \"toterminal\"):\n longrepr.toterminal(out)\n else:\n try:\n out.line(longrepr)\n except UnicodeEncodeError:\n out.line(\"\")"},{"id":3908,"name":"release-2.9.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.9.1\n============\n\npytest is a mature Python testing tool with more than a 1100 tests\nagainst itself, passing on many different interpreters and platforms.\n\nSee below for the changes and see docs at:\n\n http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n Bruno Oliveira\n Daniel Hahler\n Dmitry Malinovsky\n Florian Bruhin\n Floris Bruynooghe\n Matt Bachmann\n Ronny Pfannschmidt\n TomV\n Vladimir Bolshakov\n Zearin\n palaviv\n\n\nHappy testing,\nThe py.test Development Team\n\n\n2.9.1 (compared to 2.9.0)\n-------------------------\n\n**Bug Fixes**\n\n* Improve error message when a plugin fails to load.\n Thanks `@nicoddemus`_ for the PR.\n\n* Fix (`#1178 `_):\n ``pytest.fail`` with non-ascii characters raises an internal pytest error.\n Thanks `@nicoddemus`_ for the PR.\n\n* Fix (`#469`_): junit parses report.nodeid incorrectly, when params IDs\n contain ``::``. Thanks `@tomviner`_ for the PR (`#1431`_).\n\n* Fix (`#578 `_): SyntaxErrors\n containing non-ascii lines at the point of failure generated an internal\n py.test error.\n Thanks `@asottile`_ for the report and `@nicoddemus`_ for the PR.\n\n* Fix (`#1437`_): When passing in a bytestring regex pattern to parameterize\n attempt to decode it as utf-8 ignoring errors.\n\n* Fix (`#649`_): parametrized test nodes cannot be specified to run on the command line.\n\n\n.. _#1437: https://github.com/pytest-dev/pytest/issues/1437\n.. _#469: https://github.com/pytest-dev/pytest/issues/469\n.. _#1431: https://github.com/pytest-dev/pytest/pull/1431\n.. _#649: https://github.com/pytest-dev/pytest/issues/649\n\n.. _@asottile: https://github.com/asottile\n.. _@nicoddemus: https://github.com/nicoddemus\n.. _@tomviner: https://github.com/tomviner\n"},{"col":0,"comment":"null","endLoc":32,"header":"def getslaveinfoline(node)","id":3909,"name":"getslaveinfoline","nodeType":"Function","startLoc":20,"text":"def getslaveinfoline(node):\n try:\n return node._slaveinfocache\n except AttributeError:\n d = node.slaveinfo\n ver = \"%s.%s.%s\" % d[\"version_info\"][:3]\n node._slaveinfocache = s = \"[%s] %s -- Python %s %s\" % (\n d[\"id\"],\n d[\"sysplatform\"],\n ver,\n d[\"executable\"],\n )\n return s"},{"id":3910,"name":"release-3.7.4.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.7.4\n=======================================\n\npytest 3.7.4 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Jiri Kuncar\n* Steve Piercy\n\n\nHappy testing,\nThe pytest Development Team\n"},{"col":4,"comment":"null","endLoc":209,"header":"def test_dont_rewrite_if_hasattr_fails(self, request)","id":3911,"name":"test_dont_rewrite_if_hasattr_fails","nodeType":"Function","startLoc":184,"text":"def test_dont_rewrite_if_hasattr_fails(self, request):\n class Y(object):\n \"\"\" A class whos getattr fails, but not with `AttributeError` \"\"\"\n\n def __getattr__(self, attribute_name):\n raise KeyError()\n\n def __repr__(self):\n return \"Y\"\n\n def __init__(self):\n self.foo = 3\n\n def f():\n assert cls().foo == 2 # noqa\n\n # XXX: looks like the \"where\" should also be there in verbose mode?!\n message = getmsg(f, {\"cls\": Y}).splitlines()\n if request.config.getoption(\"verbose\") > 0:\n assert message == [\"assert 3 == 2\", \" -3\", \" +2\"]\n else:\n assert message == [\n \"assert 3 == 2\",\n \" + where 3 = Y.foo\",\n \" + where Y = cls()\",\n ]"},{"col":4,"comment":"null","endLoc":1167,"header":"@pytest.mark.parametrize(\"format\", [\"udiff\", \"UDIFF\", \"uDiFf\"])\n def test_doctest_report_udiff(self, testdir, format)","id":3912,"name":"test_doctest_report_udiff","nodeType":"Function","startLoc":1162,"text":"@pytest.mark.parametrize(\"format\", [\"udiff\", \"UDIFF\", \"uDiFf\"])\n def test_doctest_report_udiff(self, testdir, format):\n result = self._run_doctest_report(testdir, format)\n result.stdout.fnmatch_lines(\n [\" 0 1 4\", \" -1 2 4\", \" +1 2 5\", \" 2 3 6\"]\n )"},{"id":3913,"name":"release-2.3.4.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.3.4: stabilization, more flexible selection via \"-k expr\"\n===========================================================================\n\npytest-2.3.4 is a small stabilization release of the py.test tool\nwhich offers uebersimple assertions, scalable fixture mechanisms\nand deep customization for testing with Python. This release\ncomes with the following fixes and features:\n\n- make \"-k\" option accept an expressions the same as with \"-m\" so that one\n can write: -k \"name1 or name2\" etc. This is a slight usage incompatibility\n if you used special syntax like \"TestClass.test_method\" which you now\n need to write as -k \"TestClass and test_method\" to match a certain\n method in a certain test class.\n- allow to dynamically define markers via\n item.keywords[...]=assignment integrating with \"-m\" option\n- yielded test functions will now have autouse-fixtures active but\n cannot accept fixtures as funcargs - it's anyway recommended to\n rather use the post-2.0 parametrize features instead of yield, see:\n http://pytest.org/latest/example/parametrize.html\n- fix autouse-issue where autouse-fixtures would not be discovered\n if defined in an a/conftest.py file and tests in a/tests/test_some.py\n- fix issue226 - LIFO ordering for fixture teardowns\n- fix issue224 - invocations with >256 char arguments now work\n- fix issue91 - add/discuss package/directory level setups in example\n- fixes related to autouse discovery and calling\n\nThanks in particular to Thomas Waldmann for spotting and reporting issues.\n\nSee\n\n http://pytest.org/\n\nfor general information. To install or upgrade pytest:\n\n pip install -U pytest # or\n easy_install -U pytest\n\nbest,\nholger krekel\n"},{"col":4,"comment":"null","endLoc":61,"header":"def get_sections(self, prefix)","id":3914,"name":"get_sections","nodeType":"Function","startLoc":58,"text":"def get_sections(self, prefix):\n for name, content in self.sections:\n if name.startswith(prefix):\n yield prefix, content"},{"id":3915,"name":".gitignore","nodeType":"TextFile","path":"doc/en/_themes","text":"*.pyc\n*.pyo\n.DS_Store\n"},{"col":4,"comment":"\n Read-only property that returns the full string representation\n of ``longrepr``.\n\n .. versionadded:: 3.0\n ","endLoc":75,"header":"@property\n def longreprtext(self)","id":3916,"name":"longreprtext","nodeType":"Function","startLoc":63,"text":"@property\n def longreprtext(self):\n \"\"\"\n Read-only property that returns the full string representation\n of ``longrepr``.\n\n .. versionadded:: 3.0\n \"\"\"\n tw = py.io.TerminalWriter(stringio=True)\n tw.hasmarkup = False\n self.toterminal(tw)\n exc = tw.stringio.getvalue()\n return exc.strip()"},{"col":4,"comment":"null","endLoc":215,"header":"def test_assert_already_has_message(self)","id":3917,"name":"test_assert_already_has_message","nodeType":"Function","startLoc":211,"text":"def test_assert_already_has_message(self):\n def f():\n assert False, \"something bad!\"\n\n assert getmsg(f) == \"AssertionError: something bad!\\nassert False\""},{"col":4,"comment":"null","endLoc":228,"header":"def test_assertion_message(self, testdir)","id":3918,"name":"test_assertion_message","nodeType":"Function","startLoc":217,"text":"def test_assertion_message(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert 1 == 2, \"The failure message\"\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\"*AssertionError*The failure message*\", \"*assert 1 == 2*\"]\n )"},{"col":4,"comment":"Return captured log lines, if log capturing is enabled\n\n .. versionadded:: 3.5\n ","endLoc":85,"header":"@property\n def caplog(self)","id":3919,"name":"caplog","nodeType":"Function","startLoc":77,"text":"@property\n def caplog(self):\n \"\"\"Return captured log lines, if log capturing is enabled\n\n .. versionadded:: 3.5\n \"\"\"\n return \"\\n\".join(\n content for (prefix, content) in self.get_sections(\"Captured log\")\n )"},{"col":4,"comment":"null","endLoc":241,"header":"def test_assertion_message_multiline(self, testdir)","id":3920,"name":"test_assertion_message_multiline","nodeType":"Function","startLoc":230,"text":"def test_assertion_message_multiline(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert 1 == 2, \"A multiline\\\\nfailure message\"\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\"*AssertionError*A multiline*\", \"*failure message*\", \"*assert 1 == 2*\"]\n )"},{"col":4,"comment":"null","endLoc":72,"header":"def test_raises_output(self, testdir)","id":3921,"name":"test_raises_output","nodeType":"Function","startLoc":61,"text":"def test_raises_output(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n import pytest\n def test_raises_doesnt():\n pytest.raises(ValueError, int, \"3\")\n \"\"\"\n )\n passed, skipped, failed = reprec.listoutcomes()\n assert len(failed) == 1\n out = failed[0].longrepr.reprcrash.message\n assert \"DID NOT RAISE\" in out"},{"col":4,"comment":"Return captured text from stdout, if capturing is enabled\n\n .. versionadded:: 3.0\n ","endLoc":95,"header":"@property\n def capstdout(self)","id":3922,"name":"capstdout","nodeType":"Function","startLoc":87,"text":"@property\n def capstdout(self):\n \"\"\"Return captured text from stdout, if capturing is enabled\n\n .. versionadded:: 3.0\n \"\"\"\n return \"\".join(\n content for (prefix, content) in self.get_sections(\"Captured stdout\")\n )"},{"col":4,"comment":"null","endLoc":254,"header":"def test_assertion_message_tuple(self, testdir)","id":3923,"name":"test_assertion_message_tuple","nodeType":"Function","startLoc":243,"text":"def test_assertion_message_tuple(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert 1 == 2, (1, 2)\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\"*AssertionError*%s*\" % repr((1, 2)), \"*assert 1 == 2*\"]\n )"},{"col":0,"comment":"Test for issue https://github.com/pytest-dev/pytest/issues/1609 (#1609)\n\n Ignore duplicate directories.\n ","endLoc":1290,"header":"def test_skip_duplicates_by_default(testdir)","id":3924,"name":"test_skip_duplicates_by_default","nodeType":"Function","startLoc":1273,"text":"def test_skip_duplicates_by_default(testdir):\n \"\"\"Test for issue https://github.com/pytest-dev/pytest/issues/1609 (#1609)\n\n Ignore duplicate directories.\n \"\"\"\n a = testdir.mkdir(\"a\")\n fh = a.join(\"test_a.py\")\n fh.write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n def test_real():\n pass\n \"\"\"\n )\n )\n result = testdir.runpytest(a.strpath, a.strpath)\n result.stdout.fnmatch_lines([\"*collected 1 item*\"])"},{"col":4,"comment":"null","endLoc":79,"header":"def test_syntax_error_module(self, testdir)","id":3925,"name":"test_syntax_error_module","nodeType":"Function","startLoc":74,"text":"def test_syntax_error_module(self, testdir):\n reprec = testdir.inline_runsource(\"this is really not python\")\n values = reprec.getfailedcollections()\n assert len(values) == 1\n out = str(values[0].longrepr)\n assert out.find(str(\"not python\")) != -1"},{"col":4,"comment":"Return captured text from stderr, if capturing is enabled\n\n .. versionadded:: 3.0\n ","endLoc":105,"header":"@property\n def capstderr(self)","id":3926,"name":"capstderr","nodeType":"Function","startLoc":97,"text":"@property\n def capstderr(self):\n \"\"\"Return captured text from stderr, if capturing is enabled\n\n .. versionadded:: 3.0\n \"\"\"\n return \"\".join(\n content for (prefix, content) in self.get_sections(\"Captured stderr\")\n )"},{"col":4,"comment":"null","endLoc":113,"header":"@property\n def fspath(self)","id":3927,"name":"fspath","nodeType":"Function","startLoc":111,"text":"@property\n def fspath(self):\n return self.nodeid.split(\"::\")[0]"},{"col":4,"comment":"null","endLoc":1183,"header":"def test_doctest_report_cdiff(self, testdir)","id":3928,"name":"test_doctest_report_cdiff","nodeType":"Function","startLoc":1169,"text":"def test_doctest_report_cdiff(self, testdir):\n result = self._run_doctest_report(testdir, \"cdiff\")\n result.stdout.fnmatch_lines(\n [\n \" a b\",\n \" 0 1 4\",\n \" ! 1 2 4\",\n \" 2 3 6\",\n \" --- 1,4 ----\",\n \" a b\",\n \" 0 1 4\",\n \" ! 1 2 5\",\n \" 2 3 6\",\n ]\n )"},{"col":4,"comment":"\n **Experimental**\n\n Returns True if this report should be counted towards the totals shown at the end of the\n test session: \"1 passed, 1 failure, etc\".\n\n .. note::\n\n This function is considered **experimental**, so beware that it is subject to changes\n even in patch releases.\n ","endLoc":128,"header":"@property\n def count_towards_summary(self)","id":3929,"name":"count_towards_summary","nodeType":"Function","startLoc":115,"text":"@property\n def count_towards_summary(self):\n \"\"\"\n **Experimental**\n\n Returns True if this report should be counted towards the totals shown at the end of the\n test session: \"1 passed, 1 failure, etc\".\n\n .. note::\n\n This function is considered **experimental**, so beware that it is subject to changes\n even in patch releases.\n \"\"\"\n return True"},{"col":4,"comment":"\n **Experimental**\n\n Returns the head line shown with longrepr output for this report, more commonly during\n traceback representation during failures::\n\n ________ Test.foo ________\n\n\n In the example above, the head_line is \"Test.foo\".\n\n .. note::\n\n This function is considered **experimental**, so beware that it is subject to changes\n even in patch releases.\n ","endLoc":150,"header":"@property\n def head_line(self)","id":3930,"name":"head_line","nodeType":"Function","startLoc":130,"text":"@property\n def head_line(self):\n \"\"\"\n **Experimental**\n\n Returns the head line shown with longrepr output for this report, more commonly during\n traceback representation during failures::\n\n ________ Test.foo ________\n\n\n In the example above, the head_line is \"Test.foo\".\n\n .. note::\n\n This function is considered **experimental**, so beware that it is subject to changes\n even in patch releases.\n \"\"\"\n if self.location is not None:\n fspath, lineno, domain = self.location\n return domain"},{"col":4,"comment":"null","endLoc":156,"header":"def _get_verbose_word(self, config)","id":3931,"name":"_get_verbose_word","nodeType":"Function","startLoc":152,"text":"def _get_verbose_word(self, config):\n _category, _short, verbose = config.hook.pytest_report_teststatus(\n report=self, config=config\n )\n return verbose"},{"col":4,"comment":"\n This was originally the serialize_report() function from xdist (ca03269).\n\n Returns the contents of this report as a dict of builtin entries, suitable for\n serialization.\n\n Experimental method.\n ","endLoc":206,"header":"def _to_json(self)","id":3932,"name":"_to_json","nodeType":"Function","startLoc":158,"text":"def _to_json(self):\n \"\"\"\n This was originally the serialize_report() function from xdist (ca03269).\n\n Returns the contents of this report as a dict of builtin entries, suitable for\n serialization.\n\n Experimental method.\n \"\"\"\n\n def disassembled_report(rep):\n reprtraceback = rep.longrepr.reprtraceback.__dict__.copy()\n reprcrash = rep.longrepr.reprcrash.__dict__.copy()\n\n new_entries = []\n for entry in reprtraceback[\"reprentries\"]:\n entry_data = {\n \"type\": type(entry).__name__,\n \"data\": entry.__dict__.copy(),\n }\n for key, value in entry_data[\"data\"].items():\n if hasattr(value, \"__dict__\"):\n entry_data[\"data\"][key] = value.__dict__.copy()\n new_entries.append(entry_data)\n\n reprtraceback[\"reprentries\"] = new_entries\n\n return {\n \"reprcrash\": reprcrash,\n \"reprtraceback\": reprtraceback,\n \"sections\": rep.longrepr.sections,\n }\n\n d = self.__dict__.copy()\n if hasattr(self.longrepr, \"toterminal\"):\n if hasattr(self.longrepr, \"reprtraceback\") and hasattr(\n self.longrepr, \"reprcrash\"\n ):\n d[\"longrepr\"] = disassembled_report(self)\n else:\n d[\"longrepr\"] = six.text_type(self.longrepr)\n else:\n d[\"longrepr\"] = self.longrepr\n for name in d:\n if isinstance(d[name], (py.path.local, Path)):\n d[name] = str(d[name])\n elif name == \"result\":\n d[name] = None # for now\n return d"},{"col":4,"comment":"null","endLoc":1197,"header":"def test_doctest_report_ndiff(self, testdir)","id":3933,"name":"test_doctest_report_ndiff","nodeType":"Function","startLoc":1185,"text":"def test_doctest_report_ndiff(self, testdir):\n result = self._run_doctest_report(testdir, \"ndiff\")\n result.stdout.fnmatch_lines(\n [\n \" a b\",\n \" 0 1 4\",\n \" - 1 2 4\",\n \" ? ^\",\n \" + 1 2 5\",\n \" ? ^\",\n \" 2 3 6\",\n ]\n )"},{"col":4,"comment":"null","endLoc":1215,"header":"@pytest.mark.parametrize(\"format\", [\"none\", \"only_first_failure\"])\n def test_doctest_report_none_or_only_first_failure(self, testdir, format)","id":3934,"name":"test_doctest_report_none_or_only_first_failure","nodeType":"Function","startLoc":1199,"text":"@pytest.mark.parametrize(\"format\", [\"none\", \"only_first_failure\"])\n def test_doctest_report_none_or_only_first_failure(self, testdir, format):\n result = self._run_doctest_report(testdir, format)\n result.stdout.fnmatch_lines(\n [\n \"Expected:\",\n \" a b\",\n \" 0 1 4\",\n \" 1 2 4\",\n \" 2 3 6\",\n \"Got:\",\n \" a b\",\n \" 0 1 4\",\n \" 1 2 5\",\n \" 2 3 6\",\n ]\n )"},{"col":0,"comment":"Test for issue https://github.com/pytest-dev/pytest/issues/1609 (#1609)\n\n Use --keep-duplicates to collect tests from duplicate directories.\n ","endLoc":1310,"header":"def test_keep_duplicates(testdir)","id":3935,"name":"test_keep_duplicates","nodeType":"Function","startLoc":1293,"text":"def test_keep_duplicates(testdir):\n \"\"\"Test for issue https://github.com/pytest-dev/pytest/issues/1609 (#1609)\n\n Use --keep-duplicates to collect tests from duplicate directories.\n \"\"\"\n a = testdir.mkdir(\"a\")\n fh = a.join(\"test_a.py\")\n fh.write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n def test_real():\n pass\n \"\"\"\n )\n )\n result = testdir.runpytest(\"--keep-duplicates\", a.strpath, a.strpath)\n result.stdout.fnmatch_lines([\"*collected 2 item*\"])"},{"col":4,"comment":"null","endLoc":265,"header":"def test_assertion_message_expr(self, testdir)","id":3936,"name":"test_assertion_message_expr","nodeType":"Function","startLoc":256,"text":"def test_assertion_message_expr(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert 1 == 2, 1 + 2\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines([\"*AssertionError*3*\", \"*assert 1 == 2*\"])"},{"col":4,"comment":"null","endLoc":1223,"header":"def test_doctest_report_invalid(self, testdir)","id":3937,"name":"test_doctest_report_invalid","nodeType":"Function","startLoc":1217,"text":"def test_doctest_report_invalid(self, testdir):\n result = self._run_doctest_report(testdir, \"obviously_invalid_format\")\n result.stderr.fnmatch_lines(\n [\n \"*error: argument --doctest-report: invalid choice: 'obviously_invalid_format' (choose from*\"\n ]\n )"},{"col":0,"comment":"null","endLoc":1316,"header":"def test_package_collection_infinite_recursion(testdir)","id":3938,"name":"test_package_collection_infinite_recursion","nodeType":"Function","startLoc":1313,"text":"def test_package_collection_infinite_recursion(testdir):\n testdir.copy_example(\"collect/package_infinite_recursion\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":0,"comment":"Regression test for #3749","endLoc":1323,"header":"def test_package_collection_init_given_as_argument(testdir)","id":3939,"name":"test_package_collection_init_given_as_argument","nodeType":"Function","startLoc":1319,"text":"def test_package_collection_init_given_as_argument(testdir):\n \"\"\"Regression test for #3749\"\"\"\n p = testdir.copy_example(\"collect/package_init_given_as_arg\")\n result = testdir.runpytest(p / \"pkg\" / \"__init__.py\")\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"className":"Broken","col":0,"comment":"null","endLoc":1247,"id":3940,"nodeType":"Class","startLoc":1245,"text":"class Broken:\n def __getattr__(self, _):\n raise KeyError(\"This should be an AttributeError\")"},{"col":4,"comment":"null","endLoc":1247,"header":"def __getattr__(self, _)","id":3941,"name":"__getattr__","nodeType":"Function","startLoc":1246,"text":"def __getattr__(self, _):\n raise KeyError(\"This should be an AttributeError\")"},{"col":4,"comment":"null","endLoc":278,"header":"def test_assertion_message_escape(self, testdir)","id":3942,"name":"test_assertion_message_escape","nodeType":"Function","startLoc":267,"text":"def test_assertion_message_escape(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert 1 == 2, 'To be escaped: %'\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\"*AssertionError: To be escaped: %\", \"*assert 1 == 2\"]\n )"},{"col":0,"comment":"\n .\n └── root\n ├── __init__.py\n ├── sub1\n │ ├── __init__.py\n │ └── sub1_1\n │ ├── __init__.py\n │ └── test_in_sub1.py\n └── sub2\n └── test\n └── test_in_sub2.py\n\n ","endLoc":1363,"header":"def test_package_with_modules(testdir)","id":3943,"name":"test_package_with_modules","nodeType":"Function","startLoc":1326,"text":"def test_package_with_modules(testdir):\n \"\"\"\n .\n └── root\n ├── __init__.py\n ├── sub1\n │ ├── __init__.py\n │ └── sub1_1\n │ ├── __init__.py\n │ └── test_in_sub1.py\n └── sub2\n └── test\n └── test_in_sub2.py\n\n \"\"\"\n root = testdir.mkpydir(\"root\")\n sub1 = root.mkdir(\"sub1\")\n sub1.ensure(\"__init__.py\")\n sub1_test = sub1.mkdir(\"sub1_1\")\n sub1_test.ensure(\"__init__.py\")\n sub2 = root.mkdir(\"sub2\")\n sub2_test = sub2.mkdir(\"sub2\")\n\n sub1_test.join(\"test_in_sub1.py\").write(\"def test_1(): pass\")\n sub2_test.join(\"test_in_sub2.py\").write(\"def test_2(): pass\")\n\n # Execute from .\n result = testdir.runpytest(\"-v\", \"-s\")\n result.assert_outcomes(passed=2)\n\n # Execute from . with one argument \"root\"\n result = testdir.runpytest(\"-v\", \"-s\", \"root\")\n result.assert_outcomes(passed=2)\n\n # Chdir into package's root and execute with no args\n root.chdir()\n result = testdir.runpytest(\"-v\", \"-s\")\n result.assert_outcomes(passed=2)"},{"col":4,"comment":"null","endLoc":287,"header":"@pytest.mark.skipif(\n sys.version_info < (3,), reason=\"bytes is a string type in python 2\"\n )\n def test_assertion_messages_bytes(self, testdir)","id":3944,"name":"test_assertion_messages_bytes","nodeType":"Function","startLoc":280,"text":"@pytest.mark.skipif(\n sys.version_info < (3,), reason=\"bytes is a string type in python 2\"\n )\n def test_assertion_messages_bytes(self, testdir):\n testdir.makepyfile(\"def test_bytes_assertion():\\n assert False, b'ohai!'\\n\")\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines([\"*AssertionError: b'ohai!'\", \"*assert False\"])"},{"col":0,"comment":"\n .\n └── root\n ├── Test_root.py\n ├── __init__.py\n ├── sub1\n │ ├── Test_sub1.py\n │ └── __init__.py\n ��── sub2\n └── test\n └── test_sub2.py\n\n ","endLoc":1398,"header":"def test_package_ordering(testdir)","id":3945,"name":"test_package_ordering","nodeType":"Function","startLoc":1366,"text":"def test_package_ordering(testdir):\n \"\"\"\n .\n └── root\n ├── Test_root.py\n ├── __init__.py\n ├── sub1\n │ ├── Test_sub1.py\n │ └── __init__.py\n └── sub2\n └── test\n └── test_sub2.py\n\n \"\"\"\n testdir.makeini(\n \"\"\"\n [pytest]\n python_files=*.py\n \"\"\"\n )\n root = testdir.mkpydir(\"root\")\n sub1 = root.mkdir(\"sub1\")\n sub1.ensure(\"__init__.py\")\n sub2 = root.mkdir(\"sub2\")\n sub2_test = sub2.mkdir(\"sub2\")\n\n root.join(\"Test_root.py\").write(\"def test_1(): pass\")\n sub1.join(\"Test_sub1.py\").write(\"def test_2(): pass\")\n sub2_test.join(\"test_sub2.py\").write(\"def test_3(): pass\")\n\n # Execute from .\n result = testdir.runpytest(\"-v\", \"-s\")\n result.assert_outcomes(passed=3)"},{"col":0,"comment":"null","endLoc":1242,"header":"@pytest.mark.parametrize(\"mock_module\", [\"mock\", \"unittest.mock\"])\ndef test_doctest_mock_objects_dont_recurse_missbehaved(mock_module, testdir)","id":3946,"name":"test_doctest_mock_objects_dont_recurse_missbehaved","nodeType":"Function","startLoc":1226,"text":"@pytest.mark.parametrize(\"mock_module\", [\"mock\", \"unittest.mock\"])\ndef test_doctest_mock_objects_dont_recurse_missbehaved(mock_module, testdir):\n pytest.importorskip(mock_module)\n testdir.makepyfile(\n \"\"\"\n from {mock_module} import call\n class Example(object):\n '''\n >>> 1 + 1\n 2\n '''\n \"\"\".format(\n mock_module=mock_module\n )\n )\n result = testdir.runpytest(\"--doctest-modules\")\n result.stdout.fnmatch_lines([\"* 1 passed *\"])"},{"fileName":"template_test.py","filePath":"testing/example_scripts/perf_examples/collect_stats","id":3947,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ndef test_x():\n pass\n"},{"col":0,"comment":"null","endLoc":3,"header":"def test_x()","id":3948,"name":"test_x","nodeType":"Function","startLoc":2,"text":"def test_x():\n pass"},{"fileName":"test_pdb.py","filePath":"testing","id":3949,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\n\nimport six\n\nimport _pytest._code\nimport pytest\nfrom _pytest.debugging import _validate_usepdb_cls\n\ntry:\n breakpoint\nexcept NameError:\n SUPPORTS_BREAKPOINT_BUILTIN = False\nelse:\n SUPPORTS_BREAKPOINT_BUILTIN = True\n\n\n_ENVIRON_PYTHONBREAKPOINT = os.environ.get(\"PYTHONBREAKPOINT\", \"\")\n\n\ndef runpdb_and_get_report(testdir, source):\n p = testdir.makepyfile(source)\n result = testdir.runpytest_inprocess(\"--pdb\", p)\n reports = result.reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 3, reports # setup/call/teardown\n return reports[1]\n\n\n@pytest.fixture\ndef custom_pdb_calls():\n called = []\n\n # install dummy debugger class and track which methods were called on it\n class _CustomPdb(object):\n quitting = False\n\n def __init__(self, *args, **kwargs):\n called.append(\"init\")\n\n def reset(self):\n called.append(\"reset\")\n\n def interaction(self, *args):\n called.append(\"interaction\")\n\n _pytest._CustomPdb = _CustomPdb\n return called\n\n\n@pytest.fixture\ndef custom_debugger_hook():\n called = []\n\n # install dummy debugger class and track which methods were called on it\n class _CustomDebugger(object):\n def __init__(self, *args, **kwargs):\n called.append(\"init\")\n\n def reset(self):\n called.append(\"reset\")\n\n def interaction(self, *args):\n called.append(\"interaction\")\n\n def set_trace(self, frame):\n print(\"**CustomDebugger**\")\n called.append(\"set_trace\")\n\n _pytest._CustomDebugger = _CustomDebugger\n yield called\n del _pytest._CustomDebugger\n\n\nclass TestPDB(object):\n @pytest.fixture\n def pdblist(self, request):\n monkeypatch = request.getfixturevalue(\"monkeypatch\")\n pdblist = []\n\n def mypdb(*args):\n pdblist.append(args)\n\n plugin = request.config.pluginmanager.getplugin(\"debugging\")\n monkeypatch.setattr(plugin, \"post_mortem\", mypdb)\n return pdblist\n\n def test_pdb_on_fail(self, testdir, pdblist):\n rep = runpdb_and_get_report(\n testdir,\n \"\"\"\n def test_func():\n assert 0\n \"\"\",\n )\n assert rep.failed\n assert len(pdblist) == 1\n tb = _pytest._code.Traceback(pdblist[0][0])\n assert tb[-1].name == \"test_func\"\n\n def test_pdb_on_xfail(self, testdir, pdblist):\n rep = runpdb_and_get_report(\n testdir,\n \"\"\"\n import pytest\n @pytest.mark.xfail\n def test_func():\n assert 0\n \"\"\",\n )\n assert \"xfail\" in rep.keywords\n assert not pdblist\n\n def test_pdb_on_skip(self, testdir, pdblist):\n rep = runpdb_and_get_report(\n testdir,\n \"\"\"\n import pytest\n def test_func():\n pytest.skip(\"hello\")\n \"\"\",\n )\n assert rep.skipped\n assert len(pdblist) == 0\n\n def test_pdb_on_BdbQuit(self, testdir, pdblist):\n rep = runpdb_and_get_report(\n testdir,\n \"\"\"\n import bdb\n def test_func():\n raise bdb.BdbQuit\n \"\"\",\n )\n assert rep.failed\n assert len(pdblist) == 0\n\n def test_pdb_on_KeyboardInterrupt(self, testdir, pdblist):\n rep = runpdb_and_get_report(\n testdir,\n \"\"\"\n def test_func():\n raise KeyboardInterrupt\n \"\"\",\n )\n assert rep.failed\n assert len(pdblist) == 1\n\n @staticmethod\n def flush(child):\n if child.isalive():\n # Read if the test has not (e.g. test_pdb_unittest_skip).\n child.read()\n child.wait()\n assert not child.isalive()\n\n def test_pdb_unittest_postmortem(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import unittest\n class Blub(unittest.TestCase):\n def tearDown(self):\n self.filename = None\n def test_false(self):\n self.filename = 'debug' + '.me'\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdb %s\" % p1)\n child.expect(\"Pdb\")\n child.sendline(\"p self.filename\")\n child.sendeof()\n rest = child.read().decode(\"utf8\")\n assert \"debug.me\" in rest\n self.flush(child)\n\n def test_pdb_unittest_skip(self, testdir):\n \"\"\"Test for issue #2137\"\"\"\n p1 = testdir.makepyfile(\n \"\"\"\n import unittest\n @unittest.skipIf(True, 'Skipping also with pdb active')\n class MyTestCase(unittest.TestCase):\n def test_one(self):\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(\"-rs --pdb %s\" % p1)\n child.expect(\"Skipping also with pdb active\")\n child.expect(\"1 skipped in\")\n child.sendeof()\n self.flush(child)\n\n def test_pdb_print_captured_stdout_and_stderr(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1():\n import sys\n sys.stderr.write(\"get\\\\x20rekt\")\n print(\"get\\\\x20rekt\")\n assert False\n\n def test_not_called_due_to_quit():\n pass\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdb %s\" % p1)\n child.expect(\"captured stdout\")\n child.expect(\"get rekt\")\n child.expect(\"captured stderr\")\n child.expect(\"get rekt\")\n child.expect(\"traceback\")\n child.expect(\"def test_1\")\n child.expect(\"Pdb\")\n child.sendeof()\n rest = child.read().decode(\"utf8\")\n assert \"Exit: Quitting debugger\" in rest\n assert \"= 1 failed in\" in rest\n assert \"def test_1\" not in rest\n assert \"get rekt\" not in rest\n self.flush(child)\n\n def test_pdb_dont_print_empty_captured_stdout_and_stderr(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1():\n assert False\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdb %s\" % p1)\n child.expect(\"Pdb\")\n output = child.before.decode(\"utf8\")\n child.sendeof()\n assert \"captured stdout\" not in output\n assert \"captured stderr\" not in output\n self.flush(child)\n\n @pytest.mark.parametrize(\"showcapture\", [\"all\", \"no\", \"log\"])\n def test_pdb_print_captured_logs(self, testdir, showcapture):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1():\n import logging\n logging.warn(\"get \" + \"rekt\")\n assert False\n \"\"\"\n )\n child = testdir.spawn_pytest(\n \"--show-capture={} --pdb {}\".format(showcapture, p1)\n )\n if showcapture in (\"all\", \"log\"):\n child.expect(\"captured log\")\n child.expect(\"get rekt\")\n child.expect(\"Pdb\")\n child.sendeof()\n rest = child.read().decode(\"utf8\")\n assert \"1 failed\" in rest\n self.flush(child)\n\n def test_pdb_print_captured_logs_nologging(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1():\n import logging\n logging.warn(\"get \" + \"rekt\")\n assert False\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--show-capture=all --pdb -p no:logging %s\" % p1)\n child.expect(\"get rekt\")\n output = child.before.decode(\"utf8\")\n assert \"captured log\" not in output\n child.expect(\"Pdb\")\n child.sendeof()\n rest = child.read().decode(\"utf8\")\n assert \"1 failed\" in rest\n self.flush(child)\n\n def test_pdb_interaction_exception(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def globalfunc():\n pass\n def test_1():\n pytest.raises(ValueError, globalfunc)\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdb %s\" % p1)\n child.expect(\".*def test_1\")\n child.expect(\".*pytest.raises.*globalfunc\")\n child.expect(\"Pdb\")\n child.sendline(\"globalfunc\")\n child.expect(\".*function\")\n child.sendeof()\n child.expect(\"1 failed\")\n self.flush(child)\n\n def test_pdb_interaction_on_collection_issue181(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n xxx\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdb %s\" % p1)\n # child.expect(\".*import pytest.*\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n child.expect(\"1 error\")\n self.flush(child)\n\n def test_pdb_interaction_on_internal_error(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_runtest_protocol():\n 0/0\n \"\"\"\n )\n p1 = testdir.makepyfile(\"def test_func(): pass\")\n child = testdir.spawn_pytest(\"--pdb %s\" % p1)\n child.expect(\"Pdb\")\n\n # INTERNALERROR is only displayed once via terminal reporter.\n assert (\n len(\n [\n x\n for x in child.before.decode().splitlines()\n if x.startswith(\"INTERNALERROR> Traceback\")\n ]\n )\n == 1\n )\n\n child.sendeof()\n self.flush(child)\n\n def test_pdb_interaction_capturing_simple(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1():\n i = 0\n print(\"hello17\")\n pytest.set_trace()\n i == 1\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(r\"test_1\\(\\)\")\n child.expect(\"i == 1\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n rest = child.read().decode(\"utf-8\")\n assert \"AssertionError\" in rest\n assert \"1 failed\" in rest\n assert \"def test_1\" in rest\n assert \"hello17\" in rest # out is captured\n self.flush(child)\n\n def test_pdb_set_trace_kwargs(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1():\n i = 0\n print(\"hello17\")\n pytest.set_trace(header=\"== my_header ==\")\n x = 3\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"== my_header ==\")\n assert \"PDB set_trace\" not in child.before.decode()\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n rest = child.read().decode(\"utf-8\")\n assert \"1 failed\" in rest\n assert \"def test_1\" in rest\n assert \"hello17\" in rest # out is captured\n self.flush(child)\n\n def test_pdb_set_trace_interception(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pdb\n def test_1():\n pdb.set_trace()\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"test_1\")\n child.expect(\"Pdb\")\n child.sendline(\"q\")\n rest = child.read().decode(\"utf8\")\n assert \"no tests ran\" in rest\n assert \"reading from stdin while output\" not in rest\n assert \"BdbQuit\" not in rest\n self.flush(child)\n\n def test_pdb_and_capsys(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1(capsys):\n print(\"hello1\")\n pytest.set_trace()\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"test_1\")\n child.send(\"capsys.readouterr()\\n\")\n child.expect(\"hello1\")\n child.sendeof()\n child.read()\n self.flush(child)\n\n def test_pdb_with_caplog_on_pdb_invocation(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1(capsys, caplog):\n import logging\n logging.getLogger(__name__).warning(\"some_warning\")\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdb %s\" % str(p1))\n child.send(\"caplog.record_tuples\\n\")\n child.expect_exact(\n \"[('test_pdb_with_caplog_on_pdb_invocation', 30, 'some_warning')]\"\n )\n child.sendeof()\n child.read()\n self.flush(child)\n\n def test_set_trace_capturing_afterwards(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pdb\n def test_1():\n pdb.set_trace()\n def test_2():\n print(\"hello\")\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"test_1\")\n child.send(\"c\\n\")\n child.expect(\"test_2\")\n child.expect(\"Captured\")\n child.expect(\"hello\")\n child.sendeof()\n child.read()\n self.flush(child)\n\n def test_pdb_interaction_doctest(self, testdir, monkeypatch):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def function_1():\n '''\n >>> i = 0\n >>> assert i == 1\n '''\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--doctest-modules --pdb %s\" % p1)\n child.expect(\"Pdb\")\n\n assert \"UNEXPECTED EXCEPTION: AssertionError()\" in child.before.decode(\"utf8\")\n\n child.sendline(\"'i=%i.' % i\")\n child.expect(\"Pdb\")\n assert \"\\r\\n'i=0.'\\r\\n\" in child.before.decode(\"utf8\")\n\n child.sendeof()\n rest = child.read().decode(\"utf8\")\n assert \"1 failed\" in rest\n self.flush(child)\n\n def test_pdb_interaction_capturing_twice(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1():\n i = 0\n print(\"hello17\")\n pytest.set_trace()\n x = 3\n print(\"hello18\")\n pytest.set_trace()\n x = 4\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(r\"PDB set_trace \\(IO-capturing turned off\\)\")\n child.expect(\"test_1\")\n child.expect(\"x = 3\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n child.expect(r\"PDB continue \\(IO-capturing resumed\\)\")\n child.expect(r\"PDB set_trace \\(IO-capturing turned off\\)\")\n child.expect(\"x = 4\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n child.expect(\"_ test_1 _\")\n child.expect(\"def test_1\")\n rest = child.read().decode(\"utf8\")\n assert \"Captured stdout call\" in rest\n assert \"hello17\" in rest # out is captured\n assert \"hello18\" in rest # out is captured\n assert \"1 failed\" in rest\n self.flush(child)\n\n def test_pdb_with_injected_do_debug(self, testdir):\n \"\"\"Simulates pdbpp, which injects Pdb into do_debug, and uses\n self.__class__ in do_continue.\n \"\"\"\n p1 = testdir.makepyfile(\n mytest=\"\"\"\n import pdb\n import pytest\n\n count_continue = 0\n\n class CustomPdb(pdb.Pdb, object):\n def do_debug(self, arg):\n import sys\n import types\n\n if sys.version_info < (3, ):\n do_debug_func = pdb.Pdb.do_debug.im_func\n else:\n do_debug_func = pdb.Pdb.do_debug\n\n newglobals = do_debug_func.__globals__.copy()\n newglobals['Pdb'] = self.__class__\n orig_do_debug = types.FunctionType(\n do_debug_func.__code__, newglobals,\n do_debug_func.__name__, do_debug_func.__defaults__,\n )\n return orig_do_debug(self, arg)\n do_debug.__doc__ = pdb.Pdb.do_debug.__doc__\n\n def do_continue(self, *args, **kwargs):\n global count_continue\n count_continue += 1\n return super(CustomPdb, self).do_continue(*args, **kwargs)\n\n def foo():\n print(\"print_from_foo\")\n\n def test_1():\n i = 0\n print(\"hello17\")\n pytest.set_trace()\n x = 3\n print(\"hello18\")\n\n assert count_continue == 2, \"unexpected_failure: %d != 2\" % count_continue\n pytest.fail(\"expected_failure\")\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdbcls=mytest:CustomPdb %s\" % str(p1))\n child.expect(r\"PDB set_trace \\(IO-capturing turned off\\)\")\n child.expect(r\"\\n\\(Pdb\")\n child.sendline(\"debug foo()\")\n child.expect(\"ENTERING RECURSIVE DEBUGGER\")\n child.expect(r\"\\n\\(\\(Pdb\")\n child.sendline(\"c\")\n child.expect(\"LEAVING RECURSIVE DEBUGGER\")\n assert b\"PDB continue\" not in child.before\n # No extra newline.\n assert child.before.endswith(b\"c\\r\\nprint_from_foo\\r\\n\")\n\n # set_debug should not raise outcomes.Exit, if used recrursively.\n child.sendline(\"debug 42\")\n child.sendline(\"q\")\n child.expect(\"LEAVING RECURSIVE DEBUGGER\")\n assert b\"ENTERING RECURSIVE DEBUGGER\" in child.before\n assert b\"Quitting debugger\" not in child.before\n\n child.sendline(\"c\")\n child.expect(r\"PDB continue \\(IO-capturing resumed\\)\")\n rest = child.read().decode(\"utf8\")\n assert \"hello17\" in rest # out is captured\n assert \"hello18\" in rest # out is captured\n assert \"1 failed\" in rest\n assert \"Failed: expected_failure\" in rest\n assert \"AssertionError: unexpected_failure\" not in rest\n self.flush(child)\n\n def test_pdb_without_capture(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1():\n pytest.set_trace()\n \"\"\"\n )\n child = testdir.spawn_pytest(\"-s %s\" % p1)\n child.expect(r\">>> PDB set_trace >>>\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n child.expect(r\">>> PDB continue >>>\")\n child.expect(\"1 passed\")\n self.flush(child)\n\n @pytest.mark.parametrize(\"capture_arg\", (\"\", \"-s\", \"-p no:capture\"))\n def test_pdb_continue_with_recursive_debug(self, capture_arg, testdir):\n \"\"\"Full coverage for do_debug without capturing.\n\n This is very similar to test_pdb_interaction_continue_recursive in general,\n but mocks out ``pdb.set_trace`` for providing more coverage.\n \"\"\"\n p1 = testdir.makepyfile(\n \"\"\"\n try:\n input = raw_input\n except NameError:\n pass\n\n def set_trace():\n __import__('pdb').set_trace()\n\n def test_1(monkeypatch):\n import _pytest.debugging\n\n class pytestPDBTest(_pytest.debugging.pytestPDB):\n @classmethod\n def set_trace(cls, *args, **kwargs):\n # Init PytestPdbWrapper to handle capturing.\n _pdb = cls._init_pdb(\"set_trace\", *args, **kwargs)\n\n # Mock out pdb.Pdb.do_continue.\n import pdb\n pdb.Pdb.do_continue = lambda self, arg: None\n\n print(\"===\" + \" SET_TRACE ===\")\n assert input() == \"debug set_trace()\"\n\n # Simulate PytestPdbWrapper.do_debug\n cls._recursive_debug += 1\n print(\"ENTERING RECURSIVE DEBUGGER\")\n print(\"===\" + \" SET_TRACE_2 ===\")\n\n assert input() == \"c\"\n _pdb.do_continue(\"\")\n print(\"===\" + \" SET_TRACE_3 ===\")\n\n # Simulate PytestPdbWrapper.do_debug\n print(\"LEAVING RECURSIVE DEBUGGER\")\n cls._recursive_debug -= 1\n\n print(\"===\" + \" SET_TRACE_4 ===\")\n assert input() == \"c\"\n _pdb.do_continue(\"\")\n\n def do_continue(self, arg):\n print(\"=== do_continue\")\n\n monkeypatch.setattr(_pytest.debugging, \"pytestPDB\", pytestPDBTest)\n\n import pdb\n monkeypatch.setattr(pdb, \"set_trace\", pytestPDBTest.set_trace)\n\n set_trace()\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--tb=short %s %s\" % (p1, capture_arg))\n child.expect(\"=== SET_TRACE ===\")\n before = child.before.decode(\"utf8\")\n if not capture_arg:\n assert \">>> PDB set_trace (IO-capturing turned off) >>>\" in before\n else:\n assert \">>> PDB set_trace >>>\" in before\n child.sendline(\"debug set_trace()\")\n child.expect(\"=== SET_TRACE_2 ===\")\n before = child.before.decode(\"utf8\")\n assert \"\\r\\nENTERING RECURSIVE DEBUGGER\\r\\n\" in before\n child.sendline(\"c\")\n child.expect(\"=== SET_TRACE_3 ===\")\n\n # No continue message with recursive debugging.\n before = child.before.decode(\"utf8\")\n assert \">>> PDB continue \" not in before\n\n child.sendline(\"c\")\n child.expect(\"=== SET_TRACE_4 ===\")\n before = child.before.decode(\"utf8\")\n assert \"\\r\\nLEAVING RECURSIVE DEBUGGER\\r\\n\" in before\n child.sendline(\"c\")\n rest = child.read().decode(\"utf8\")\n if not capture_arg:\n assert \"> PDB continue (IO-capturing resumed) >\" in rest\n else:\n assert \"> PDB continue >\" in rest\n assert \"1 passed in\" in rest\n\n def test_pdb_used_outside_test(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n pytest.set_trace()\n x = 5\n \"\"\"\n )\n child = testdir.spawn(\"{} {}\".format(sys.executable, p1))\n child.expect(\"x = 5\")\n child.expect(\"Pdb\")\n child.sendeof()\n self.flush(child)\n\n def test_pdb_used_in_generate_tests(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n pytest.set_trace()\n x = 5\n def test_foo(a):\n pass\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"x = 5\")\n child.expect(\"Pdb\")\n child.sendeof()\n self.flush(child)\n\n def test_pdb_collection_failure_is_shown(self, testdir):\n p1 = testdir.makepyfile(\"xxx\")\n result = testdir.runpytest_subprocess(\"--pdb\", p1)\n result.stdout.fnmatch_lines(\n [\"E NameError: *xxx*\", \"*! *Exit: Quitting debugger !*\"] # due to EOF\n )\n\n @pytest.mark.parametrize(\"post_mortem\", (False, True))\n def test_enter_leave_pdb_hooks_are_called(self, post_mortem, testdir):\n testdir.makeconftest(\n \"\"\"\n mypdb = None\n\n def pytest_configure(config):\n config.testing_verification = 'configured'\n\n def pytest_enter_pdb(config, pdb):\n assert config.testing_verification == 'configured'\n print('enter_pdb_hook')\n\n global mypdb\n mypdb = pdb\n mypdb.set_attribute = \"bar\"\n\n def pytest_leave_pdb(config, pdb):\n assert config.testing_verification == 'configured'\n print('leave_pdb_hook')\n\n global mypdb\n assert mypdb is pdb\n assert mypdb.set_attribute == \"bar\"\n \"\"\"\n )\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n\n def test_set_trace():\n pytest.set_trace()\n assert 0\n\n def test_post_mortem():\n assert 0\n \"\"\"\n )\n if post_mortem:\n child = testdir.spawn_pytest(str(p1) + \" --pdb -s -k test_post_mortem\")\n else:\n child = testdir.spawn_pytest(str(p1) + \" -k test_set_trace\")\n child.expect(\"enter_pdb_hook\")\n child.sendline(\"c\")\n if post_mortem:\n child.expect(r\"PDB continue\")\n else:\n child.expect(r\"PDB continue \\(IO-capturing resumed\\)\")\n child.expect(\"Captured stdout call\")\n rest = child.read().decode(\"utf8\")\n assert \"leave_pdb_hook\" in rest\n assert \"1 failed\" in rest\n self.flush(child)\n\n def test_pdb_custom_cls(self, testdir, custom_pdb_calls):\n p1 = testdir.makepyfile(\"\"\"xxx \"\"\")\n result = testdir.runpytest_inprocess(\"--pdb\", \"--pdbcls=_pytest:_CustomPdb\", p1)\n result.stdout.fnmatch_lines([\"*NameError*xxx*\", \"*1 error*\"])\n assert custom_pdb_calls == [\"init\", \"reset\", \"interaction\"]\n\n def test_pdb_custom_cls_invalid(self, testdir):\n result = testdir.runpytest_inprocess(\"--pdbcls=invalid\")\n result.stderr.fnmatch_lines(\n [\n \"*: error: argument --pdbcls: 'invalid' is not in the format 'modname:classname'\"\n ]\n )\n\n def test_pdb_validate_usepdb_cls(self, testdir):\n assert _validate_usepdb_cls(\"os.path:dirname.__name__\") == (\n \"os.path\",\n \"dirname.__name__\",\n )\n\n assert _validate_usepdb_cls(\"pdb:DoesNotExist\") == (\"pdb\", \"DoesNotExist\")\n\n def test_pdb_custom_cls_without_pdb(self, testdir, custom_pdb_calls):\n p1 = testdir.makepyfile(\"\"\"xxx \"\"\")\n result = testdir.runpytest_inprocess(\"--pdbcls=_pytest:_CustomPdb\", p1)\n result.stdout.fnmatch_lines([\"*NameError*xxx*\", \"*1 error*\"])\n assert custom_pdb_calls == []\n\n def test_pdb_custom_cls_with_set_trace(self, testdir, monkeypatch):\n testdir.makepyfile(\n custom_pdb=\"\"\"\n class CustomPdb(object):\n def __init__(self, *args, **kwargs):\n skip = kwargs.pop(\"skip\")\n assert skip == [\"foo.*\"]\n print(\"__init__\")\n super(CustomPdb, self).__init__(*args, **kwargs)\n\n def set_trace(*args, **kwargs):\n print('custom set_trace>')\n \"\"\"\n )\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n\n def test_foo():\n pytest.set_trace(skip=['foo.*'])\n \"\"\"\n )\n monkeypatch.setenv(\"PYTHONPATH\", str(testdir.tmpdir))\n child = testdir.spawn_pytest(\"--pdbcls=custom_pdb:CustomPdb %s\" % str(p1))\n\n child.expect(\"__init__\")\n child.expect(\"custom set_trace>\")\n self.flush(child)\n\n\nclass TestDebuggingBreakpoints(object):\n def test_supports_breakpoint_module_global(self):\n \"\"\"\n Test that supports breakpoint global marks on Python 3.7+ and not on\n CPython 3.5, 2.7\n \"\"\"\n if sys.version_info.major == 3 and sys.version_info.minor >= 7:\n assert SUPPORTS_BREAKPOINT_BUILTIN is True\n if sys.version_info.major == 3 and sys.version_info.minor == 5:\n assert SUPPORTS_BREAKPOINT_BUILTIN is False\n if sys.version_info.major == 2 and sys.version_info.minor == 7:\n assert SUPPORTS_BREAKPOINT_BUILTIN is False\n\n @pytest.mark.skipif(\n not SUPPORTS_BREAKPOINT_BUILTIN, reason=\"Requires breakpoint() builtin\"\n )\n @pytest.mark.parametrize(\"arg\", [\"--pdb\", \"\"])\n def test_sys_breakpointhook_configure_and_unconfigure(self, testdir, arg):\n \"\"\"\n Test that sys.breakpointhook is set to the custom Pdb class once configured, test that\n hook is reset to system value once pytest has been unconfigured\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import sys\n from pytest import hookimpl\n from _pytest.debugging import pytestPDB\n\n def pytest_configure(config):\n config._cleanup.append(check_restored)\n\n def check_restored():\n assert sys.breakpointhook == sys.__breakpointhook__\n\n def test_check():\n assert sys.breakpointhook == pytestPDB.set_trace\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_nothing(): pass\n \"\"\"\n )\n args = (arg,) if arg else ()\n result = testdir.runpytest_subprocess(*args)\n result.stdout.fnmatch_lines([\"*1 passed in *\"])\n\n @pytest.mark.skipif(\n not SUPPORTS_BREAKPOINT_BUILTIN, reason=\"Requires breakpoint() builtin\"\n )\n def test_pdb_custom_cls(self, testdir, custom_debugger_hook):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_nothing():\n breakpoint()\n \"\"\"\n )\n result = testdir.runpytest_inprocess(\n \"--pdb\", \"--pdbcls=_pytest:_CustomDebugger\", p1\n )\n result.stdout.fnmatch_lines([\"*CustomDebugger*\", \"*1 passed*\"])\n assert custom_debugger_hook == [\"init\", \"set_trace\"]\n\n @pytest.mark.parametrize(\"arg\", [\"--pdb\", \"\"])\n @pytest.mark.skipif(\n not SUPPORTS_BREAKPOINT_BUILTIN, reason=\"Requires breakpoint() builtin\"\n )\n def test_environ_custom_class(self, testdir, custom_debugger_hook, arg):\n testdir.makeconftest(\n \"\"\"\n import os\n import sys\n\n os.environ['PYTHONBREAKPOINT'] = '_pytest._CustomDebugger.set_trace'\n\n def pytest_configure(config):\n config._cleanup.append(check_restored)\n\n def check_restored():\n assert sys.breakpointhook == sys.__breakpointhook__\n\n def test_check():\n import _pytest\n assert sys.breakpointhook is _pytest._CustomDebugger.set_trace\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_nothing(): pass\n \"\"\"\n )\n args = (arg,) if arg else ()\n result = testdir.runpytest_subprocess(*args)\n result.stdout.fnmatch_lines([\"*1 passed in *\"])\n\n @pytest.mark.skipif(\n not SUPPORTS_BREAKPOINT_BUILTIN, reason=\"Requires breakpoint() builtin\"\n )\n @pytest.mark.skipif(\n not _ENVIRON_PYTHONBREAKPOINT == \"\",\n reason=\"Requires breakpoint() default value\",\n )\n def test_sys_breakpoint_interception(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1():\n breakpoint()\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"test_1\")\n child.expect(\"Pdb\")\n child.sendline(\"quit\")\n rest = child.read().decode(\"utf8\")\n assert \"Quitting debugger\" in rest\n assert \"reading from stdin while output\" not in rest\n TestPDB.flush(child)\n\n @pytest.mark.skipif(\n not SUPPORTS_BREAKPOINT_BUILTIN, reason=\"Requires breakpoint() builtin\"\n )\n def test_pdb_not_altered(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pdb\n def test_1():\n pdb.set_trace()\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"test_1\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n rest = child.read().decode(\"utf8\")\n assert \"1 failed\" in rest\n assert \"reading from stdin while output\" not in rest\n TestPDB.flush(child)\n\n\nclass TestTraceOption:\n def test_trace_sets_breakpoint(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1():\n assert True\n\n def test_2():\n pass\n\n def test_3():\n pass\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--trace \" + str(p1))\n child.expect(\"test_1\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n child.expect(\"test_2\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n child.expect(\"test_3\")\n child.expect(\"Pdb\")\n child.sendline(\"q\")\n child.expect_exact(\"Exit: Quitting debugger\")\n rest = child.read().decode(\"utf8\")\n assert \"2 passed in\" in rest\n assert \"reading from stdin while output\" not in rest\n # Only printed once - not on stderr.\n assert \"Exit: Quitting debugger\" not in child.before.decode(\"utf8\")\n TestPDB.flush(child)\n\n\ndef test_trace_after_runpytest(testdir):\n \"\"\"Test that debugging's pytest_configure is re-entrant.\"\"\"\n p1 = testdir.makepyfile(\n \"\"\"\n from _pytest.debugging import pytestPDB\n\n def test_outer(testdir):\n assert len(pytestPDB._saved) == 1\n\n testdir.makepyfile(\n \\\"\"\"\n from _pytest.debugging import pytestPDB\n\n def test_inner():\n assert len(pytestPDB._saved) == 2\n print()\n print(\"test_inner_\" + \"end\")\n \\\"\"\"\n )\n\n result = testdir.runpytest(\"-s\", \"-k\", \"test_inner\")\n assert result.ret == 0\n\n assert len(pytestPDB._saved) == 1\n \"\"\"\n )\n result = testdir.runpytest_subprocess(\"-s\", \"-p\", \"pytester\", str(p1))\n result.stdout.fnmatch_lines([\"test_inner_end\"])\n assert result.ret == 0\n\n\ndef test_quit_with_swallowed_SystemExit(testdir):\n \"\"\"Test that debugging's pytest_configure is re-entrant.\"\"\"\n p1 = testdir.makepyfile(\n \"\"\"\n def call_pdb_set_trace():\n __import__('pdb').set_trace()\n\n\n def test_1():\n try:\n call_pdb_set_trace()\n except SystemExit:\n pass\n\n\n def test_2():\n pass\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"Pdb\")\n child.sendline(\"q\")\n child.expect_exact(\"Exit: Quitting debugger\")\n rest = child.read().decode(\"utf8\")\n assert \"no tests ran\" in rest\n TestPDB.flush(child)\n\n\n@pytest.mark.parametrize(\"fixture\", (\"capfd\", \"capsys\"))\ndef test_pdb_suspends_fixture_capturing(testdir, fixture):\n \"\"\"Using \"-s\" with pytest should suspend/resume fixture capturing.\"\"\"\n p1 = testdir.makepyfile(\n \"\"\"\n def test_inner({fixture}):\n import sys\n\n print(\"out_inner_before\")\n sys.stderr.write(\"err_inner_before\\\\n\")\n\n __import__(\"pdb\").set_trace()\n\n print(\"out_inner_after\")\n sys.stderr.write(\"err_inner_after\\\\n\")\n\n out, err = {fixture}.readouterr()\n assert out ==\"out_inner_before\\\\nout_inner_after\\\\n\"\n assert err ==\"err_inner_before\\\\nerr_inner_after\\\\n\"\n \"\"\".format(\n fixture=fixture\n )\n )\n\n child = testdir.spawn_pytest(str(p1) + \" -s\")\n\n child.expect(\"Pdb\")\n before = child.before.decode(\"utf8\")\n assert (\n \"> PDB set_trace (IO-capturing turned off for fixture %s) >\" % (fixture)\n in before\n )\n\n # Test that capturing is really suspended.\n child.sendline(\"p 40 + 2\")\n child.expect(\"Pdb\")\n assert \"\\r\\n42\\r\\n\" in child.before.decode(\"utf8\")\n\n child.sendline(\"c\")\n rest = child.read().decode(\"utf8\")\n assert \"out_inner\" not in rest\n assert \"err_inner\" not in rest\n\n TestPDB.flush(child)\n assert child.exitstatus == 0\n assert \"= 1 passed in \" in rest\n assert \"> PDB continue (IO-capturing resumed for fixture %s) >\" % (fixture) in rest\n\n\ndef test_pdbcls_via_local_module(testdir):\n \"\"\"It should be imported in pytest_configure or later only.\"\"\"\n p1 = testdir.makepyfile(\n \"\"\"\n def test():\n print(\"before_set_trace\")\n __import__(\"pdb\").set_trace()\n \"\"\",\n mypdb=\"\"\"\n class Wrapped:\n class MyPdb:\n def set_trace(self, *args):\n print(\"set_trace_called\", args)\n\n def runcall(self, *args, **kwds):\n print(\"runcall_called\", args, kwds)\n assert \"func\" in kwds\n \"\"\",\n )\n result = testdir.runpytest(\n str(p1), \"--pdbcls=really.invalid:Value\", syspathinsert=True\n )\n result.stdout.fnmatch_lines(\n [\n \"*= FAILURES =*\",\n \"E * --pdbcls: could not import 'really.invalid:Value': No module named *really*\",\n ]\n )\n assert result.ret == 1\n\n result = testdir.runpytest(\n str(p1), \"--pdbcls=mypdb:Wrapped.MyPdb\", syspathinsert=True\n )\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*set_trace_called*\", \"* 1 passed in *\"])\n\n # Ensure that it also works with --trace.\n result = testdir.runpytest(\n str(p1), \"--pdbcls=mypdb:Wrapped.MyPdb\", \"--trace\", syspathinsert=True\n )\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*runcall_called*\", \"* 1 passed in *\"])\n\n\ndef test_raises_bdbquit_with_eoferror(testdir):\n \"\"\"It is not guaranteed that DontReadFromInput's read is called.\"\"\"\n if six.PY2:\n builtin_module = \"__builtin__\"\n input_func = \"raw_input\"\n else:\n builtin_module = \"builtins\"\n input_func = \"input\"\n p1 = testdir.makepyfile(\n \"\"\"\n def input_without_read(*args, **kwargs):\n raise EOFError()\n\n def test(monkeypatch):\n import {builtin_module}\n monkeypatch.setattr({builtin_module}, {input_func!r}, input_without_read)\n __import__('pdb').set_trace()\n \"\"\".format(\n builtin_module=builtin_module, input_func=input_func\n )\n )\n result = testdir.runpytest(str(p1))\n result.stdout.fnmatch_lines([\"E *BdbQuit\", \"*= 1 failed in*\"])\n assert result.ret == 1\n\n\ndef test_pdb_wrapper_class_is_reused(testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test():\n __import__(\"pdb\").set_trace()\n __import__(\"pdb\").set_trace()\n\n import mypdb\n instances = mypdb.instances\n assert len(instances) == 2\n assert instances[0].__class__ is instances[1].__class__\n \"\"\",\n mypdb=\"\"\"\n instances = []\n\n class MyPdb:\n def __init__(self, *args, **kwargs):\n instances.append(self)\n\n def set_trace(self, *args):\n print(\"set_trace_called\", args)\n \"\"\",\n )\n result = testdir.runpytest(str(p1), \"--pdbcls=mypdb:MyPdb\", syspathinsert=True)\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n [\"*set_trace_called*\", \"*set_trace_called*\", \"* 1 passed in *\"]\n )\n"},{"id":3950,"name":".gitignore","nodeType":"TextFile","path":"","text":"# Automatically generated by `hgimportsvn`\n.svn\n.hgsvn\n\n# Ignore local virtualenvs\nlib/\nbin/\ninclude/\n.Python/\n\n# These lines are suggested according to the svn:ignore property\n# Feel free to enable them by uncommenting them\n*.pyc\n*.pyo\n*.swp\n*.class\n*.orig\n*~\n.hypothesis/\n\n# autogenerated\nsrc/_pytest/_version.py\n# setuptools\n.eggs/\n\ndoc/*/_build\ndoc/*/.doctrees\nbuild/\ndist/\n*.egg-info\nissue/\nenv/\n.env/\n3rdparty/\n.tox\n.cache\n.pytest_cache\n.coverage\n.coverage.*\ncoverage.xml\n.ropeproject\n.idea\n.hypothesis\n.pydevproject\n.project\n.settings\n.vscode\n\n# generated by pip\npip-wheel-metadata/\n"},{"col":4,"comment":"null","endLoc":366,"header":"def test_boolop(self)","id":3951,"name":"test_boolop","nodeType":"Function","startLoc":289,"text":"def test_boolop(self):\n def f():\n f = g = False\n assert f and g\n\n assert getmsg(f) == \"assert (False)\"\n\n def f():\n f = True\n g = False\n assert f and g\n\n assert getmsg(f) == \"assert (True and False)\"\n\n def f():\n f = False\n g = True\n assert f and g\n\n assert getmsg(f) == \"assert (False)\"\n\n def f():\n f = g = False\n assert f or g\n\n assert getmsg(f) == \"assert (False or False)\"\n\n def f():\n f = g = False\n assert not f and not g\n\n getmsg(f, must_pass=True)\n\n def x():\n return False\n\n def f():\n assert x() and x()\n\n assert (\n getmsg(f, {\"x\": x})\n == \"\"\"assert (False)\n + where False = x()\"\"\"\n )\n\n def f():\n assert False or x()\n\n assert (\n getmsg(f, {\"x\": x})\n == \"\"\"assert (False or False)\n + where False = x()\"\"\"\n )\n\n def f():\n assert 1 in {} and 2 in {}\n\n assert getmsg(f) == \"assert (1 in {})\"\n\n def f():\n x = 1\n y = 2\n assert x in {1: None} and y in {}\n\n assert getmsg(f) == \"assert (1 in {1: None} and 2 in {})\"\n\n def f():\n f = True\n g = False\n assert f or g\n\n getmsg(f, must_pass=True)\n\n def f():\n f = g = h = lambda: True\n assert f() and g() and h()\n\n getmsg(f, must_pass=True)"},{"fileName":"warning_types.py","filePath":"src/_pytest","id":3952,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport attr\n\n\nclass PytestWarning(UserWarning):\n \"\"\"\n Bases: :class:`UserWarning`.\n\n Base class for all warnings emitted by pytest.\n \"\"\"\n\n\nclass PytestAssertRewriteWarning(PytestWarning):\n \"\"\"\n Bases: :class:`PytestWarning`.\n\n Warning emitted by the pytest assert rewrite module.\n \"\"\"\n\n\nclass PytestCacheWarning(PytestWarning):\n \"\"\"\n Bases: :class:`PytestWarning`.\n\n Warning emitted by the cache plugin in various situations.\n \"\"\"\n\n\nclass PytestConfigWarning(PytestWarning):\n \"\"\"\n Bases: :class:`PytestWarning`.\n\n Warning emitted for configuration issues.\n \"\"\"\n\n\nclass PytestCollectionWarning(PytestWarning):\n \"\"\"\n Bases: :class:`PytestWarning`.\n\n Warning emitted when pytest is not able to collect a file or symbol in a module.\n \"\"\"\n\n\nclass PytestDeprecationWarning(PytestWarning, DeprecationWarning):\n \"\"\"\n Bases: :class:`pytest.PytestWarning`, :class:`DeprecationWarning`.\n\n Warning class for features that will be removed in a future version.\n \"\"\"\n\n\nclass PytestExperimentalApiWarning(PytestWarning, FutureWarning):\n \"\"\"\n Bases: :class:`pytest.PytestWarning`, :class:`FutureWarning`.\n\n Warning category used to denote experiments in pytest. Use sparingly as the API might change or even be\n removed completely in future version\n \"\"\"\n\n @classmethod\n def simple(cls, apiname):\n return cls(\n \"{apiname} is an experimental api that may change over time\".format(\n apiname=apiname\n )\n )\n\n\nclass PytestUnhandledCoroutineWarning(PytestWarning):\n \"\"\"\n Bases: :class:`PytestWarning`.\n\n Warning emitted when pytest encounters a test function which is a coroutine,\n but it was not handled by any async-aware plugin. Coroutine test functions\n are not natively supported.\n \"\"\"\n\n\nclass PytestUnknownMarkWarning(PytestWarning):\n \"\"\"\n Bases: :class:`PytestWarning`.\n\n Warning emitted on use of unknown markers.\n See https://docs.pytest.org/en/latest/mark.html for details.\n \"\"\"\n\n\nclass RemovedInPytest4Warning(PytestDeprecationWarning):\n \"\"\"\n Bases: :class:`pytest.PytestDeprecationWarning`.\n\n Warning class for features scheduled to be removed in pytest 4.0.\n \"\"\"\n\n\n@attr.s\nclass UnformattedWarning(object):\n \"\"\"Used to hold warnings that need to format their message at runtime, as opposed to a direct message.\n\n Using this class avoids to keep all the warning types and messages in this module, avoiding misuse.\n \"\"\"\n\n category = attr.ib()\n template = attr.ib()\n\n def format(self, **kwargs):\n \"\"\"Returns an instance of the warning category, formatted with given kwargs\"\"\"\n return self.category(self.template.format(**kwargs))\n\n\nPYTESTER_COPY_EXAMPLE = PytestExperimentalApiWarning.simple(\"testdir.copy_example\")\n"},{"attributeType":"PytestExperimentalApiWarning","col":0,"comment":"null","endLoc":112,"id":3953,"name":"PYTESTER_COPY_EXAMPLE","nodeType":"Attribute","startLoc":112,"text":"PYTESTER_COPY_EXAMPLE"},{"className":"TestPDB","col":0,"comment":"null","endLoc":856,"id":3954,"nodeType":"Class","startLoc":79,"text":"class TestPDB(object):\n @pytest.fixture\n def pdblist(self, request):\n monkeypatch = request.getfixturevalue(\"monkeypatch\")\n pdblist = []\n\n def mypdb(*args):\n pdblist.append(args)\n\n plugin = request.config.pluginmanager.getplugin(\"debugging\")\n monkeypatch.setattr(plugin, \"post_mortem\", mypdb)\n return pdblist\n\n def test_pdb_on_fail(self, testdir, pdblist):\n rep = runpdb_and_get_report(\n testdir,\n \"\"\"\n def test_func():\n assert 0\n \"\"\",\n )\n assert rep.failed\n assert len(pdblist) == 1\n tb = _pytest._code.Traceback(pdblist[0][0])\n assert tb[-1].name == \"test_func\"\n\n def test_pdb_on_xfail(self, testdir, pdblist):\n rep = runpdb_and_get_report(\n testdir,\n \"\"\"\n import pytest\n @pytest.mark.xfail\n def test_func():\n assert 0\n \"\"\",\n )\n assert \"xfail\" in rep.keywords\n assert not pdblist\n\n def test_pdb_on_skip(self, testdir, pdblist):\n rep = runpdb_and_get_report(\n testdir,\n \"\"\"\n import pytest\n def test_func():\n pytest.skip(\"hello\")\n \"\"\",\n )\n assert rep.skipped\n assert len(pdblist) == 0\n\n def test_pdb_on_BdbQuit(self, testdir, pdblist):\n rep = runpdb_and_get_report(\n testdir,\n \"\"\"\n import bdb\n def test_func():\n raise bdb.BdbQuit\n \"\"\",\n )\n assert rep.failed\n assert len(pdblist) == 0\n\n def test_pdb_on_KeyboardInterrupt(self, testdir, pdblist):\n rep = runpdb_and_get_report(\n testdir,\n \"\"\"\n def test_func():\n raise KeyboardInterrupt\n \"\"\",\n )\n assert rep.failed\n assert len(pdblist) == 1\n\n @staticmethod\n def flush(child):\n if child.isalive():\n # Read if the test has not (e.g. test_pdb_unittest_skip).\n child.read()\n child.wait()\n assert not child.isalive()\n\n def test_pdb_unittest_postmortem(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import unittest\n class Blub(unittest.TestCase):\n def tearDown(self):\n self.filename = None\n def test_false(self):\n self.filename = 'debug' + '.me'\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdb %s\" % p1)\n child.expect(\"Pdb\")\n child.sendline(\"p self.filename\")\n child.sendeof()\n rest = child.read().decode(\"utf8\")\n assert \"debug.me\" in rest\n self.flush(child)\n\n def test_pdb_unittest_skip(self, testdir):\n \"\"\"Test for issue #2137\"\"\"\n p1 = testdir.makepyfile(\n \"\"\"\n import unittest\n @unittest.skipIf(True, 'Skipping also with pdb active')\n class MyTestCase(unittest.TestCase):\n def test_one(self):\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(\"-rs --pdb %s\" % p1)\n child.expect(\"Skipping also with pdb active\")\n child.expect(\"1 skipped in\")\n child.sendeof()\n self.flush(child)\n\n def test_pdb_print_captured_stdout_and_stderr(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1():\n import sys\n sys.stderr.write(\"get\\\\x20rekt\")\n print(\"get\\\\x20rekt\")\n assert False\n\n def test_not_called_due_to_quit():\n pass\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdb %s\" % p1)\n child.expect(\"captured stdout\")\n child.expect(\"get rekt\")\n child.expect(\"captured stderr\")\n child.expect(\"get rekt\")\n child.expect(\"traceback\")\n child.expect(\"def test_1\")\n child.expect(\"Pdb\")\n child.sendeof()\n rest = child.read().decode(\"utf8\")\n assert \"Exit: Quitting debugger\" in rest\n assert \"= 1 failed in\" in rest\n assert \"def test_1\" not in rest\n assert \"get rekt\" not in rest\n self.flush(child)\n\n def test_pdb_dont_print_empty_captured_stdout_and_stderr(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1():\n assert False\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdb %s\" % p1)\n child.expect(\"Pdb\")\n output = child.before.decode(\"utf8\")\n child.sendeof()\n assert \"captured stdout\" not in output\n assert \"captured stderr\" not in output\n self.flush(child)\n\n @pytest.mark.parametrize(\"showcapture\", [\"all\", \"no\", \"log\"])\n def test_pdb_print_captured_logs(self, testdir, showcapture):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1():\n import logging\n logging.warn(\"get \" + \"rekt\")\n assert False\n \"\"\"\n )\n child = testdir.spawn_pytest(\n \"--show-capture={} --pdb {}\".format(showcapture, p1)\n )\n if showcapture in (\"all\", \"log\"):\n child.expect(\"captured log\")\n child.expect(\"get rekt\")\n child.expect(\"Pdb\")\n child.sendeof()\n rest = child.read().decode(\"utf8\")\n assert \"1 failed\" in rest\n self.flush(child)\n\n def test_pdb_print_captured_logs_nologging(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1():\n import logging\n logging.warn(\"get \" + \"rekt\")\n assert False\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--show-capture=all --pdb -p no:logging %s\" % p1)\n child.expect(\"get rekt\")\n output = child.before.decode(\"utf8\")\n assert \"captured log\" not in output\n child.expect(\"Pdb\")\n child.sendeof()\n rest = child.read().decode(\"utf8\")\n assert \"1 failed\" in rest\n self.flush(child)\n\n def test_pdb_interaction_exception(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def globalfunc():\n pass\n def test_1():\n pytest.raises(ValueError, globalfunc)\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdb %s\" % p1)\n child.expect(\".*def test_1\")\n child.expect(\".*pytest.raises.*globalfunc\")\n child.expect(\"Pdb\")\n child.sendline(\"globalfunc\")\n child.expect(\".*function\")\n child.sendeof()\n child.expect(\"1 failed\")\n self.flush(child)\n\n def test_pdb_interaction_on_collection_issue181(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n xxx\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdb %s\" % p1)\n # child.expect(\".*import pytest.*\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n child.expect(\"1 error\")\n self.flush(child)\n\n def test_pdb_interaction_on_internal_error(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_runtest_protocol():\n 0/0\n \"\"\"\n )\n p1 = testdir.makepyfile(\"def test_func(): pass\")\n child = testdir.spawn_pytest(\"--pdb %s\" % p1)\n child.expect(\"Pdb\")\n\n # INTERNALERROR is only displayed once via terminal reporter.\n assert (\n len(\n [\n x\n for x in child.before.decode().splitlines()\n if x.startswith(\"INTERNALERROR> Traceback\")\n ]\n )\n == 1\n )\n\n child.sendeof()\n self.flush(child)\n\n def test_pdb_interaction_capturing_simple(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1():\n i = 0\n print(\"hello17\")\n pytest.set_trace()\n i == 1\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(r\"test_1\\(\\)\")\n child.expect(\"i == 1\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n rest = child.read().decode(\"utf-8\")\n assert \"AssertionError\" in rest\n assert \"1 failed\" in rest\n assert \"def test_1\" in rest\n assert \"hello17\" in rest # out is captured\n self.flush(child)\n\n def test_pdb_set_trace_kwargs(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1():\n i = 0\n print(\"hello17\")\n pytest.set_trace(header=\"== my_header ==\")\n x = 3\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"== my_header ==\")\n assert \"PDB set_trace\" not in child.before.decode()\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n rest = child.read().decode(\"utf-8\")\n assert \"1 failed\" in rest\n assert \"def test_1\" in rest\n assert \"hello17\" in rest # out is captured\n self.flush(child)\n\n def test_pdb_set_trace_interception(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pdb\n def test_1():\n pdb.set_trace()\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"test_1\")\n child.expect(\"Pdb\")\n child.sendline(\"q\")\n rest = child.read().decode(\"utf8\")\n assert \"no tests ran\" in rest\n assert \"reading from stdin while output\" not in rest\n assert \"BdbQuit\" not in rest\n self.flush(child)\n\n def test_pdb_and_capsys(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1(capsys):\n print(\"hello1\")\n pytest.set_trace()\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"test_1\")\n child.send(\"capsys.readouterr()\\n\")\n child.expect(\"hello1\")\n child.sendeof()\n child.read()\n self.flush(child)\n\n def test_pdb_with_caplog_on_pdb_invocation(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1(capsys, caplog):\n import logging\n logging.getLogger(__name__).warning(\"some_warning\")\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdb %s\" % str(p1))\n child.send(\"caplog.record_tuples\\n\")\n child.expect_exact(\n \"[('test_pdb_with_caplog_on_pdb_invocation', 30, 'some_warning')]\"\n )\n child.sendeof()\n child.read()\n self.flush(child)\n\n def test_set_trace_capturing_afterwards(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pdb\n def test_1():\n pdb.set_trace()\n def test_2():\n print(\"hello\")\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"test_1\")\n child.send(\"c\\n\")\n child.expect(\"test_2\")\n child.expect(\"Captured\")\n child.expect(\"hello\")\n child.sendeof()\n child.read()\n self.flush(child)\n\n def test_pdb_interaction_doctest(self, testdir, monkeypatch):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def function_1():\n '''\n >>> i = 0\n >>> assert i == 1\n '''\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--doctest-modules --pdb %s\" % p1)\n child.expect(\"Pdb\")\n\n assert \"UNEXPECTED EXCEPTION: AssertionError()\" in child.before.decode(\"utf8\")\n\n child.sendline(\"'i=%i.' % i\")\n child.expect(\"Pdb\")\n assert \"\\r\\n'i=0.'\\r\\n\" in child.before.decode(\"utf8\")\n\n child.sendeof()\n rest = child.read().decode(\"utf8\")\n assert \"1 failed\" in rest\n self.flush(child)\n\n def test_pdb_interaction_capturing_twice(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1():\n i = 0\n print(\"hello17\")\n pytest.set_trace()\n x = 3\n print(\"hello18\")\n pytest.set_trace()\n x = 4\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(r\"PDB set_trace \\(IO-capturing turned off\\)\")\n child.expect(\"test_1\")\n child.expect(\"x = 3\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n child.expect(r\"PDB continue \\(IO-capturing resumed\\)\")\n child.expect(r\"PDB set_trace \\(IO-capturing turned off\\)\")\n child.expect(\"x = 4\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n child.expect(\"_ test_1 _\")\n child.expect(\"def test_1\")\n rest = child.read().decode(\"utf8\")\n assert \"Captured stdout call\" in rest\n assert \"hello17\" in rest # out is captured\n assert \"hello18\" in rest # out is captured\n assert \"1 failed\" in rest\n self.flush(child)\n\n def test_pdb_with_injected_do_debug(self, testdir):\n \"\"\"Simulates pdbpp, which injects Pdb into do_debug, and uses\n self.__class__ in do_continue.\n \"\"\"\n p1 = testdir.makepyfile(\n mytest=\"\"\"\n import pdb\n import pytest\n\n count_continue = 0\n\n class CustomPdb(pdb.Pdb, object):\n def do_debug(self, arg):\n import sys\n import types\n\n if sys.version_info < (3, ):\n do_debug_func = pdb.Pdb.do_debug.im_func\n else:\n do_debug_func = pdb.Pdb.do_debug\n\n newglobals = do_debug_func.__globals__.copy()\n newglobals['Pdb'] = self.__class__\n orig_do_debug = types.FunctionType(\n do_debug_func.__code__, newglobals,\n do_debug_func.__name__, do_debug_func.__defaults__,\n )\n return orig_do_debug(self, arg)\n do_debug.__doc__ = pdb.Pdb.do_debug.__doc__\n\n def do_continue(self, *args, **kwargs):\n global count_continue\n count_continue += 1\n return super(CustomPdb, self).do_continue(*args, **kwargs)\n\n def foo():\n print(\"print_from_foo\")\n\n def test_1():\n i = 0\n print(\"hello17\")\n pytest.set_trace()\n x = 3\n print(\"hello18\")\n\n assert count_continue == 2, \"unexpected_failure: %d != 2\" % count_continue\n pytest.fail(\"expected_failure\")\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdbcls=mytest:CustomPdb %s\" % str(p1))\n child.expect(r\"PDB set_trace \\(IO-capturing turned off\\)\")\n child.expect(r\"\\n\\(Pdb\")\n child.sendline(\"debug foo()\")\n child.expect(\"ENTERING RECURSIVE DEBUGGER\")\n child.expect(r\"\\n\\(\\(Pdb\")\n child.sendline(\"c\")\n child.expect(\"LEAVING RECURSIVE DEBUGGER\")\n assert b\"PDB continue\" not in child.before\n # No extra newline.\n assert child.before.endswith(b\"c\\r\\nprint_from_foo\\r\\n\")\n\n # set_debug should not raise outcomes.Exit, if used recrursively.\n child.sendline(\"debug 42\")\n child.sendline(\"q\")\n child.expect(\"LEAVING RECURSIVE DEBUGGER\")\n assert b\"ENTERING RECURSIVE DEBUGGER\" in child.before\n assert b\"Quitting debugger\" not in child.before\n\n child.sendline(\"c\")\n child.expect(r\"PDB continue \\(IO-capturing resumed\\)\")\n rest = child.read().decode(\"utf8\")\n assert \"hello17\" in rest # out is captured\n assert \"hello18\" in rest # out is captured\n assert \"1 failed\" in rest\n assert \"Failed: expected_failure\" in rest\n assert \"AssertionError: unexpected_failure\" not in rest\n self.flush(child)\n\n def test_pdb_without_capture(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1():\n pytest.set_trace()\n \"\"\"\n )\n child = testdir.spawn_pytest(\"-s %s\" % p1)\n child.expect(r\">>> PDB set_trace >>>\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n child.expect(r\">>> PDB continue >>>\")\n child.expect(\"1 passed\")\n self.flush(child)\n\n @pytest.mark.parametrize(\"capture_arg\", (\"\", \"-s\", \"-p no:capture\"))\n def test_pdb_continue_with_recursive_debug(self, capture_arg, testdir):\n \"\"\"Full coverage for do_debug without capturing.\n\n This is very similar to test_pdb_interaction_continue_recursive in general,\n but mocks out ``pdb.set_trace`` for providing more coverage.\n \"\"\"\n p1 = testdir.makepyfile(\n \"\"\"\n try:\n input = raw_input\n except NameError:\n pass\n\n def set_trace():\n __import__('pdb').set_trace()\n\n def test_1(monkeypatch):\n import _pytest.debugging\n\n class pytestPDBTest(_pytest.debugging.pytestPDB):\n @classmethod\n def set_trace(cls, *args, **kwargs):\n # Init PytestPdbWrapper to handle capturing.\n _pdb = cls._init_pdb(\"set_trace\", *args, **kwargs)\n\n # Mock out pdb.Pdb.do_continue.\n import pdb\n pdb.Pdb.do_continue = lambda self, arg: None\n\n print(\"===\" + \" SET_TRACE ===\")\n assert input() == \"debug set_trace()\"\n\n # Simulate PytestPdbWrapper.do_debug\n cls._recursive_debug += 1\n print(\"ENTERING RECURSIVE DEBUGGER\")\n print(\"===\" + \" SET_TRACE_2 ===\")\n\n assert input() == \"c\"\n _pdb.do_continue(\"\")\n print(\"===\" + \" SET_TRACE_3 ===\")\n\n # Simulate PytestPdbWrapper.do_debug\n print(\"LEAVING RECURSIVE DEBUGGER\")\n cls._recursive_debug -= 1\n\n print(\"===\" + \" SET_TRACE_4 ===\")\n assert input() == \"c\"\n _pdb.do_continue(\"\")\n\n def do_continue(self, arg):\n print(\"=== do_continue\")\n\n monkeypatch.setattr(_pytest.debugging, \"pytestPDB\", pytestPDBTest)\n\n import pdb\n monkeypatch.setattr(pdb, \"set_trace\", pytestPDBTest.set_trace)\n\n set_trace()\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--tb=short %s %s\" % (p1, capture_arg))\n child.expect(\"=== SET_TRACE ===\")\n before = child.before.decode(\"utf8\")\n if not capture_arg:\n assert \">>> PDB set_trace (IO-capturing turned off) >>>\" in before\n else:\n assert \">>> PDB set_trace >>>\" in before\n child.sendline(\"debug set_trace()\")\n child.expect(\"=== SET_TRACE_2 ===\")\n before = child.before.decode(\"utf8\")\n assert \"\\r\\nENTERING RECURSIVE DEBUGGER\\r\\n\" in before\n child.sendline(\"c\")\n child.expect(\"=== SET_TRACE_3 ===\")\n\n # No continue message with recursive debugging.\n before = child.before.decode(\"utf8\")\n assert \">>> PDB continue \" not in before\n\n child.sendline(\"c\")\n child.expect(\"=== SET_TRACE_4 ===\")\n before = child.before.decode(\"utf8\")\n assert \"\\r\\nLEAVING RECURSIVE DEBUGGER\\r\\n\" in before\n child.sendline(\"c\")\n rest = child.read().decode(\"utf8\")\n if not capture_arg:\n assert \"> PDB continue (IO-capturing resumed) >\" in rest\n else:\n assert \"> PDB continue >\" in rest\n assert \"1 passed in\" in rest\n\n def test_pdb_used_outside_test(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n pytest.set_trace()\n x = 5\n \"\"\"\n )\n child = testdir.spawn(\"{} {}\".format(sys.executable, p1))\n child.expect(\"x = 5\")\n child.expect(\"Pdb\")\n child.sendeof()\n self.flush(child)\n\n def test_pdb_used_in_generate_tests(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n pytest.set_trace()\n x = 5\n def test_foo(a):\n pass\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"x = 5\")\n child.expect(\"Pdb\")\n child.sendeof()\n self.flush(child)\n\n def test_pdb_collection_failure_is_shown(self, testdir):\n p1 = testdir.makepyfile(\"xxx\")\n result = testdir.runpytest_subprocess(\"--pdb\", p1)\n result.stdout.fnmatch_lines(\n [\"E NameError: *xxx*\", \"*! *Exit: Quitting debugger !*\"] # due to EOF\n )\n\n @pytest.mark.parametrize(\"post_mortem\", (False, True))\n def test_enter_leave_pdb_hooks_are_called(self, post_mortem, testdir):\n testdir.makeconftest(\n \"\"\"\n mypdb = None\n\n def pytest_configure(config):\n config.testing_verification = 'configured'\n\n def pytest_enter_pdb(config, pdb):\n assert config.testing_verification == 'configured'\n print('enter_pdb_hook')\n\n global mypdb\n mypdb = pdb\n mypdb.set_attribute = \"bar\"\n\n def pytest_leave_pdb(config, pdb):\n assert config.testing_verification == 'configured'\n print('leave_pdb_hook')\n\n global mypdb\n assert mypdb is pdb\n assert mypdb.set_attribute == \"bar\"\n \"\"\"\n )\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n\n def test_set_trace():\n pytest.set_trace()\n assert 0\n\n def test_post_mortem():\n assert 0\n \"\"\"\n )\n if post_mortem:\n child = testdir.spawn_pytest(str(p1) + \" --pdb -s -k test_post_mortem\")\n else:\n child = testdir.spawn_pytest(str(p1) + \" -k test_set_trace\")\n child.expect(\"enter_pdb_hook\")\n child.sendline(\"c\")\n if post_mortem:\n child.expect(r\"PDB continue\")\n else:\n child.expect(r\"PDB continue \\(IO-capturing resumed\\)\")\n child.expect(\"Captured stdout call\")\n rest = child.read().decode(\"utf8\")\n assert \"leave_pdb_hook\" in rest\n assert \"1 failed\" in rest\n self.flush(child)\n\n def test_pdb_custom_cls(self, testdir, custom_pdb_calls):\n p1 = testdir.makepyfile(\"\"\"xxx \"\"\")\n result = testdir.runpytest_inprocess(\"--pdb\", \"--pdbcls=_pytest:_CustomPdb\", p1)\n result.stdout.fnmatch_lines([\"*NameError*xxx*\", \"*1 error*\"])\n assert custom_pdb_calls == [\"init\", \"reset\", \"interaction\"]\n\n def test_pdb_custom_cls_invalid(self, testdir):\n result = testdir.runpytest_inprocess(\"--pdbcls=invalid\")\n result.stderr.fnmatch_lines(\n [\n \"*: error: argument --pdbcls: 'invalid' is not in the format 'modname:classname'\"\n ]\n )\n\n def test_pdb_validate_usepdb_cls(self, testdir):\n assert _validate_usepdb_cls(\"os.path:dirname.__name__\") == (\n \"os.path\",\n \"dirname.__name__\",\n )\n\n assert _validate_usepdb_cls(\"pdb:DoesNotExist\") == (\"pdb\", \"DoesNotExist\")\n\n def test_pdb_custom_cls_without_pdb(self, testdir, custom_pdb_calls):\n p1 = testdir.makepyfile(\"\"\"xxx \"\"\")\n result = testdir.runpytest_inprocess(\"--pdbcls=_pytest:_CustomPdb\", p1)\n result.stdout.fnmatch_lines([\"*NameError*xxx*\", \"*1 error*\"])\n assert custom_pdb_calls == []\n\n def test_pdb_custom_cls_with_set_trace(self, testdir, monkeypatch):\n testdir.makepyfile(\n custom_pdb=\"\"\"\n class CustomPdb(object):\n def __init__(self, *args, **kwargs):\n skip = kwargs.pop(\"skip\")\n assert skip == [\"foo.*\"]\n print(\"__init__\")\n super(CustomPdb, self).__init__(*args, **kwargs)\n\n def set_trace(*args, **kwargs):\n print('custom set_trace>')\n \"\"\"\n )\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n\n def test_foo():\n pytest.set_trace(skip=['foo.*'])\n \"\"\"\n )\n monkeypatch.setenv(\"PYTHONPATH\", str(testdir.tmpdir))\n child = testdir.spawn_pytest(\"--pdbcls=custom_pdb:CustomPdb %s\" % str(p1))\n\n child.expect(\"__init__\")\n child.expect(\"custom set_trace>\")\n self.flush(child)"},{"col":0,"comment":"null","endLoc":1264,"header":"@pytest.mark.skipif(not hasattr(inspect, \"unwrap\"), reason=\"nothing to patch\")\n@pytest.mark.parametrize( # pragma","id":3955,"name":"test_warning_on_unwrap_of_broken_object","nodeType":"Function","startLoc":1250,"text":"@pytest.mark.skipif(not hasattr(inspect, \"unwrap\"), reason=\"nothing to patch\")\n@pytest.mark.parametrize( # pragma: no branch (lambdas are not called)\n \"stop\", [None, _is_mocked, lambda f: None, lambda f: False, lambda f: True]\n)\ndef test_warning_on_unwrap_of_broken_object(stop):\n bad_instance = Broken()\n assert inspect.unwrap.__module__ == \"inspect\"\n with _patch_unwrap_mock_aware():\n assert inspect.unwrap.__module__ != \"inspect\"\n with pytest.warns(\n pytest.PytestWarning, match=\"^Got KeyError.* when unwrapping\"\n ):\n with pytest.raises(KeyError):\n inspect.unwrap(bad_instance, stop=stop)\n assert inspect.unwrap.__module__ == \"inspect\""},{"id":3956,"name":"release-3.2.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.2.0\n=======================================\n\nThe pytest team is proud to announce the 3.2.0 release!\n\npytest is a mature Python testing tool with more than a 1600 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n http://doc.pytest.org/en/latest/changelog.html\n\nFor complete documentation, please visit:\n\n http://docs.pytest.org\n\nAs usual, you can upgrade from pypi via:\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Alex Hartoto\n* Andras Tim\n* Bruno Oliveira\n* Daniel Hahler\n* Florian Bruhin\n* Floris Bruynooghe\n* John Still\n* Jordan Moldow\n* Kale Kundert\n* Lawrence Mitchell\n* Llandy Riveron Del Risco\n* Maik Figura\n* Martin Altmayer\n* Mihai Capotă\n* Nathaniel Waisbrot\n* Nguyễn Hồng Quân\n* Pauli Virtanen\n* Raphael Pierzina\n* Ronny Pfannschmidt\n* Segev Finer\n* V.Kuznetsov\n\n\nHappy testing,\nThe Pytest Development Team\n"},{"col":4,"comment":"null","endLoc":91,"header":"def test_exit_first_problem(self, testdir)","id":3957,"name":"test_exit_first_problem","nodeType":"Function","startLoc":81,"text":"def test_exit_first_problem(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n def test_one(): assert 0\n def test_two(): assert 0\n \"\"\",\n \"--exitfirst\",\n )\n passed, skipped, failed = reprec.countoutcomes()\n assert failed == 1\n assert passed == skipped == 0"},{"id":3958,"name":"fixture.rst","nodeType":"TextFile","path":"doc/en","text":".. _fixture:\n.. _fixtures:\n.. _`fixture functions`:\n\npytest fixtures: explicit, modular, scalable\n========================================================\n\n.. currentmodule:: _pytest.python\n\n\n\n.. _`xUnit`: http://en.wikipedia.org/wiki/XUnit\n.. _`purpose of test fixtures`: http://en.wikipedia.org/wiki/Test_fixture#Software\n.. _`Dependency injection`: http://en.wikipedia.org/wiki/Dependency_injection\n\nThe `purpose of test fixtures`_ is to provide a fixed baseline\nupon which tests can reliably and repeatedly execute. pytest fixtures\noffer dramatic improvements over the classic xUnit style of setup/teardown\nfunctions:\n\n* fixtures have explicit names and are activated by declaring their use\n from test functions, modules, classes or whole projects.\n\n* fixtures are implemented in a modular manner, as each fixture name\n triggers a *fixture function* which can itself use other fixtures.\n\n* fixture management scales from simple unit to complex\n functional testing, allowing to parametrize fixtures and tests according\n to configuration and component options, or to re-use fixtures\n across function, class, module or whole test session scopes.\n\nIn addition, pytest continues to support :ref:`xunitsetup`. You can mix\nboth styles, moving incrementally from classic to new style, as you\nprefer. You can also start out from existing :ref:`unittest.TestCase\nstyle ` or :ref:`nose based ` projects.\n\n\n.. _`funcargs`:\n.. _`funcarg mechanism`:\n.. _`fixture function`:\n.. _`@pytest.fixture`:\n.. _`pytest.fixture`:\n\nFixtures as Function arguments\n-----------------------------------------\n\nTest functions can receive fixture objects by naming them as an input\nargument. For each argument name, a fixture function with that name provides\nthe fixture object. Fixture functions are registered by marking them with\n:py:func:`@pytest.fixture <_pytest.python.fixture>`. Let's look at a simple\nself-contained test module containing a fixture and a test function\nusing it::\n\n # content of ./test_smtpsimple.py\n import pytest\n\n @pytest.fixture\n def smtp_connection():\n import smtplib\n return smtplib.SMTP(\"smtp.gmail.com\", 587, timeout=5)\n\n def test_ehlo(smtp_connection):\n response, msg = smtp_connection.ehlo()\n assert response == 250\n assert 0 # for demo purposes\n\nHere, the ``test_ehlo`` needs the ``smtp_connection`` fixture value. pytest\nwill discover and call the :py:func:`@pytest.fixture <_pytest.python.fixture>`\nmarked ``smtp_connection`` fixture function. Running the test looks like this:\n\n.. code-block:: pytest\n\n $ pytest test_smtpsimple.py\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 1 item\n\n test_smtpsimple.py F [100%]\n\n ================================= FAILURES =================================\n ________________________________ test_ehlo _________________________________\n\n smtp_connection = \n\n def test_ehlo(smtp_connection):\n response, msg = smtp_connection.ehlo()\n assert response == 250\n > assert 0 # for demo purposes\n E assert 0\n\n test_smtpsimple.py:11: AssertionError\n ========================= 1 failed in 0.12 seconds =========================\n\nIn the failure traceback we see that the test function was called with a\n``smtp_connection`` argument, the ``smtplib.SMTP()`` instance created by the fixture\nfunction. The test function fails on our deliberate ``assert 0``. Here is\nthe exact protocol used by ``pytest`` to call the test function this way:\n\n1. pytest :ref:`finds ` the ``test_ehlo`` because\n of the ``test_`` prefix. The test function needs a function argument\n named ``smtp_connection``. A matching fixture function is discovered by\n looking for a fixture-marked function named ``smtp_connection``.\n\n2. ``smtp_connection()`` is called to create an instance.\n\n3. ``test_ehlo()`` is called and fails in the last\n line of the test function.\n\nNote that if you misspell a function argument or want\nto use one that isn't available, you'll see an error\nwith a list of available function arguments.\n\n.. note::\n\n You can always issue:\n\n .. code-block:: bash\n\n pytest --fixtures test_simplefactory.py\n\n to see available fixtures (fixtures with leading ``_`` are only shown if you add the ``-v`` option).\n\nFixtures: a prime example of dependency injection\n---------------------------------------------------\n\nFixtures allow test functions to easily receive and work\nagainst specific pre-initialized application objects without having\nto care about import/setup/cleanup details.\nIt's a prime example of `dependency injection`_ where fixture\nfunctions take the role of the *injector* and test functions are the\n*consumers* of fixture objects.\n\n.. _`conftest.py`:\n.. _`conftest`:\n\n``conftest.py``: sharing fixture functions\n------------------------------------------\n\nIf during implementing your tests you realize that you\nwant to use a fixture function from multiple test files you can move it\nto a ``conftest.py`` file.\nYou don't need to import the fixture you want to use in a test, it\nautomatically gets discovered by pytest. The discovery of\nfixture functions starts at test classes, then test modules, then\n``conftest.py`` files and finally builtin and third party plugins.\n\nYou can also use the ``conftest.py`` file to implement\n:ref:`local per-directory plugins `.\n\nSharing test data\n-----------------\n\nIf you want to make test data from files available to your tests, a good way\nto do this is by loading these data in a fixture for use by your tests.\nThis makes use of the automatic caching mechanisms of pytest.\n\nAnother good approach is by adding the data files in the ``tests`` folder.\nThere are also community plugins available to help managing this aspect of\ntesting, e.g. `pytest-datadir `__\nand `pytest-datafiles `__.\n\n.. _smtpshared:\n\nScope: sharing a fixture instance across tests in a class, module or session\n----------------------------------------------------------------------------\n\n.. regendoc:wipe\n\nFixtures requiring network access depend on connectivity and are\nusually time-expensive to create. Extending the previous example, we\ncan add a ``scope=\"module\"`` parameter to the\n:py:func:`@pytest.fixture <_pytest.python.fixture>` invocation\nto cause the decorated ``smtp_connection`` fixture function to only be invoked\nonce per test *module* (the default is to invoke once per test *function*).\nMultiple test functions in a test module will thus\neach receive the same ``smtp_connection`` fixture instance, thus saving time.\nPossible values for ``scope`` are: ``function``, ``class``, ``module``, ``package`` or ``session``.\n\nThe next example puts the fixture function into a separate ``conftest.py`` file\nso that tests from multiple test modules in the directory can\naccess the fixture function::\n\n # content of conftest.py\n import pytest\n import smtplib\n\n @pytest.fixture(scope=\"module\")\n def smtp_connection():\n return smtplib.SMTP(\"smtp.gmail.com\", 587, timeout=5)\n\nThe name of the fixture again is ``smtp_connection`` and you can access its\nresult by listing the name ``smtp_connection`` as an input parameter in any\ntest or fixture function (in or below the directory where ``conftest.py`` is\nlocated)::\n\n # content of test_module.py\n\n def test_ehlo(smtp_connection):\n response, msg = smtp_connection.ehlo()\n assert response == 250\n assert b\"smtp.gmail.com\" in msg\n assert 0 # for demo purposes\n\n def test_noop(smtp_connection):\n response, msg = smtp_connection.noop()\n assert response == 250\n assert 0 # for demo purposes\n\nWe deliberately insert failing ``assert 0`` statements in order to\ninspect what is going on and can now run the tests:\n\n.. code-block:: pytest\n\n $ pytest test_module.py\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 2 items\n\n test_module.py FF [100%]\n\n ================================= FAILURES =================================\n ________________________________ test_ehlo _________________________________\n\n smtp_connection = \n\n def test_ehlo(smtp_connection):\n response, msg = smtp_connection.ehlo()\n assert response == 250\n assert b\"smtp.gmail.com\" in msg\n > assert 0 # for demo purposes\n E assert 0\n\n test_module.py:6: AssertionError\n ________________________________ test_noop _________________________________\n\n smtp_connection = \n\n def test_noop(smtp_connection):\n response, msg = smtp_connection.noop()\n assert response == 250\n > assert 0 # for demo purposes\n E assert 0\n\n test_module.py:11: AssertionError\n ========================= 2 failed in 0.12 seconds =========================\n\nYou see the two ``assert 0`` failing and more importantly you can also see\nthat the same (module-scoped) ``smtp_connection`` object was passed into the\ntwo test functions because pytest shows the incoming argument values in the\ntraceback. As a result, the two test functions using ``smtp_connection`` run\nas quick as a single one because they reuse the same instance.\n\nIf you decide that you rather want to have a session-scoped ``smtp_connection``\ninstance, you can simply declare it:\n\n.. code-block:: python\n\n @pytest.fixture(scope=\"session\")\n def smtp_connection():\n # the returned fixture value will be shared for\n # all tests needing it\n ...\n\nFinally, the ``class`` scope will invoke the fixture once per test *class*.\n\n.. note::\n\n Pytest will only cache one instance of a fixture at a time.\n This means that when using a parametrized fixture, pytest may invoke a fixture more than once in the given scope.\n\n\n``package`` scope (experimental)\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n\n\nIn pytest 3.7 the ``package`` scope has been introduced. Package-scoped fixtures\nare finalized when the last test of a *package* finishes.\n\n.. warning::\n This functionality is considered **experimental** and may be removed in future\n versions if hidden corner-cases or serious problems with this functionality\n are discovered after it gets more usage in the wild.\n\n Use this new feature sparingly and please make sure to report any issues you find.\n\n\nHigher-scoped fixtures are instantiated first\n---------------------------------------------\n\n\n\nWithin a function request for features, fixture of higher-scopes (such as ``session``) are instantiated first than\nlower-scoped fixtures (such as ``function`` or ``class``). The relative order of fixtures of same scope follows\nthe declared order in the test function and honours dependencies between fixtures.\n\nConsider the code below:\n\n.. code-block:: python\n\n @pytest.fixture(scope=\"session\")\n def s1():\n pass\n\n\n @pytest.fixture(scope=\"module\")\n def m1():\n pass\n\n\n @pytest.fixture\n def f1(tmpdir):\n pass\n\n\n @pytest.fixture\n def f2():\n pass\n\n\n def test_foo(f1, m1, f2, s1):\n ...\n\n\nThe fixtures requested by ``test_foo`` will be instantiated in the following order:\n\n1. ``s1``: is the highest-scoped fixture (``session``).\n2. ``m1``: is the second highest-scoped fixture (``module``).\n3. ``tmpdir``: is a ``function``-scoped fixture, required by ``f1``: it needs to be instantiated at this point\n because it is a dependency of ``f1``.\n4. ``f1``: is the first ``function``-scoped fixture in ``test_foo`` parameter list.\n5. ``f2``: is the last ``function``-scoped fixture in ``test_foo`` parameter list.\n\n\n.. _`finalization`:\n\nFixture finalization / executing teardown code\n-------------------------------------------------------------\n\npytest supports execution of fixture specific finalization code\nwhen the fixture goes out of scope. By using a ``yield`` statement instead of ``return``, all\nthe code after the *yield* statement serves as the teardown code:\n\n.. code-block:: python\n\n # content of conftest.py\n\n import smtplib\n import pytest\n\n\n @pytest.fixture(scope=\"module\")\n def smtp_connection():\n smtp_connection = smtplib.SMTP(\"smtp.gmail.com\", 587, timeout=5)\n yield smtp_connection # provide the fixture value\n print(\"teardown smtp\")\n smtp_connection.close()\n\nThe ``print`` and ``smtp.close()`` statements will execute when the last test in\nthe module has finished execution, regardless of the exception status of the\ntests.\n\nLet's execute it:\n\n.. code-block:: pytest\n\n $ pytest -s -q --tb=no\n FFteardown smtp\n\n 2 failed in 0.12 seconds\n\nWe see that the ``smtp_connection`` instance is finalized after the two\ntests finished execution. Note that if we decorated our fixture\nfunction with ``scope='function'`` then fixture setup and cleanup would\noccur around each single test. In either case the test\nmodule itself does not need to change or know about these details\nof fixture setup.\n\nNote that we can also seamlessly use the ``yield`` syntax with ``with`` statements:\n\n.. code-block:: python\n\n # content of test_yield2.py\n\n import smtplib\n import pytest\n\n\n @pytest.fixture(scope=\"module\")\n def smtp_connection():\n with smtplib.SMTP(\"smtp.gmail.com\", 587, timeout=5) as smtp_connection:\n yield smtp_connection # provide the fixture value\n\n\nThe ``smtp_connection`` connection will be closed after the test finished\nexecution because the ``smtp_connection`` object automatically closes when\nthe ``with`` statement ends.\n\nNote that if an exception happens during the *setup* code (before the ``yield`` keyword), the\n*teardown* code (after the ``yield``) will not be called.\n\nAn alternative option for executing *teardown* code is to\nmake use of the ``addfinalizer`` method of the `request-context`_ object to register\nfinalization functions.\n\nHere's the ``smtp_connection`` fixture changed to use ``addfinalizer`` for cleanup:\n\n.. code-block:: python\n\n # content of conftest.py\n import smtplib\n import pytest\n\n\n @pytest.fixture(scope=\"module\")\n def smtp_connection(request):\n smtp_connection = smtplib.SMTP(\"smtp.gmail.com\", 587, timeout=5)\n\n def fin():\n print(\"teardown smtp_connection\")\n smtp_connection.close()\n\n request.addfinalizer(fin)\n return smtp_connection # provide the fixture value\n\n\nBoth ``yield`` and ``addfinalizer`` methods work similarly by calling their code after the test\nends, but ``addfinalizer`` has two key differences over ``yield``:\n\n1. It is possible to register multiple finalizer functions.\n\n2. Finalizers will always be called regardless if the fixture *setup* code raises an exception.\n This is handy to properly close all resources created by a fixture even if one of them\n fails to be created/acquired::\n\n @pytest.fixture\n def equipments(request):\n r = []\n for port in ('C1', 'C3', 'C28'):\n equip = connect(port)\n request.addfinalizer(equip.disconnect)\n r.append(equip)\n return r\n\n In the example above, if ``\"C28\"`` fails with an exception, ``\"C1\"`` and ``\"C3\"`` will still\n be properly closed. Of course, if an exception happens before the finalize function is\n registered then it will not be executed.\n\n\n.. _`request-context`:\n\nFixtures can introspect the requesting test context\n-------------------------------------------------------------\n\nFixture functions can accept the :py:class:`request ` object\nto introspect the \"requesting\" test function, class or module context.\nFurther extending the previous ``smtp_connection`` fixture example, let's\nread an optional server URL from the test module which uses our fixture::\n\n # content of conftest.py\n import pytest\n import smtplib\n\n @pytest.fixture(scope=\"module\")\n def smtp_connection(request):\n server = getattr(request.module, \"smtpserver\", \"smtp.gmail.com\")\n smtp_connection = smtplib.SMTP(server, 587, timeout=5)\n yield smtp_connection\n print(\"finalizing %s (%s)\" % (smtp_connection, server))\n smtp_connection.close()\n\nWe use the ``request.module`` attribute to optionally obtain an\n``smtpserver`` attribute from the test module. If we just execute\nagain, nothing much has changed:\n\n.. code-block:: pytest\n\n $ pytest -s -q --tb=no\n FFfinalizing (smtp.gmail.com)\n\n 2 failed in 0.12 seconds\n\nLet's quickly create another test module that actually sets the\nserver URL in its module namespace::\n\n # content of test_anothersmtp.py\n\n smtpserver = \"mail.python.org\" # will be read by smtp fixture\n\n def test_showhelo(smtp_connection):\n assert 0, smtp_connection.helo()\n\nRunning it:\n\n.. code-block:: pytest\n\n $ pytest -qq --tb=short test_anothersmtp.py\n F [100%]\n ================================= FAILURES =================================\n ______________________________ test_showhelo _______________________________\n test_anothersmtp.py:5: in test_showhelo\n assert 0, smtp_connection.helo()\n E AssertionError: (250, b'mail.python.org')\n E assert 0\n ------------------------- Captured stdout teardown -------------------------\n finalizing (mail.python.org)\n\nvoila! The ``smtp_connection`` fixture function picked up our mail server name\nfrom the module namespace.\n\n.. _`fixture-factory`:\n\nFactories as fixtures\n-------------------------------------------------------------\n\nThe \"factory as fixture\" pattern can help in situations where the result\nof a fixture is needed multiple times in a single test. Instead of returning\ndata directly, the fixture instead returns a function which generates the data.\nThis function can then be called multiple times in the test.\n\nFactories can have have parameters as needed::\n\n @pytest.fixture\n def make_customer_record():\n\n def _make_customer_record(name):\n return {\n \"name\": name,\n \"orders\": []\n }\n\n return _make_customer_record\n\n\n def test_customer_records(make_customer_record):\n customer_1 = make_customer_record(\"Lisa\")\n customer_2 = make_customer_record(\"Mike\")\n customer_3 = make_customer_record(\"Meredith\")\n\nIf the data created by the factory requires managing, the fixture can take care of that::\n\n @pytest.fixture\n def make_customer_record():\n\n created_records = []\n\n def _make_customer_record(name):\n record = models.Customer(name=name, orders=[])\n created_records.append(record)\n return record\n\n yield _make_customer_record\n\n for record in created_records:\n record.destroy()\n\n\n def test_customer_records(make_customer_record):\n customer_1 = make_customer_record(\"Lisa\")\n customer_2 = make_customer_record(\"Mike\")\n customer_3 = make_customer_record(\"Meredith\")\n\n\n.. _`fixture-parametrize`:\n\nParametrizing fixtures\n-----------------------------------------------------------------\n\nFixture functions can be parametrized in which case they will be called\nmultiple times, each time executing the set of dependent tests, i. e. the\ntests that depend on this fixture. Test functions usually do not need\nto be aware of their re-running. Fixture parametrization helps to\nwrite exhaustive functional tests for components which themselves can be\nconfigured in multiple ways.\n\nExtending the previous example, we can flag the fixture to create two\n``smtp_connection`` fixture instances which will cause all tests using the fixture\nto run twice. The fixture function gets access to each parameter\nthrough the special :py:class:`request ` object::\n\n # content of conftest.py\n import pytest\n import smtplib\n\n @pytest.fixture(scope=\"module\",\n params=[\"smtp.gmail.com\", \"mail.python.org\"])\n def smtp_connection(request):\n smtp_connection = smtplib.SMTP(request.param, 587, timeout=5)\n yield smtp_connection\n print(\"finalizing %s\" % smtp_connection)\n smtp_connection.close()\n\nThe main change is the declaration of ``params`` with\n:py:func:`@pytest.fixture <_pytest.python.fixture>`, a list of values\nfor each of which the fixture function will execute and can access\na value via ``request.param``. No test function code needs to change.\nSo let's just do another run:\n\n.. code-block:: pytest\n\n $ pytest -q test_module.py\n FFFF [100%]\n ================================= FAILURES =================================\n ________________________ test_ehlo[smtp.gmail.com] _________________________\n\n smtp_connection = \n\n def test_ehlo(smtp_connection):\n response, msg = smtp_connection.ehlo()\n assert response == 250\n assert b\"smtp.gmail.com\" in msg\n > assert 0 # for demo purposes\n E assert 0\n\n test_module.py:6: AssertionError\n ________________________ test_noop[smtp.gmail.com] _________________________\n\n smtp_connection = \n\n def test_noop(smtp_connection):\n response, msg = smtp_connection.noop()\n assert response == 250\n > assert 0 # for demo purposes\n E assert 0\n\n test_module.py:11: AssertionError\n ________________________ test_ehlo[mail.python.org] ________________________\n\n smtp_connection = \n\n def test_ehlo(smtp_connection):\n response, msg = smtp_connection.ehlo()\n assert response == 250\n > assert b\"smtp.gmail.com\" in msg\n E AssertionError: assert b'smtp.gmail.com' in b'mail.python.org\\nPIPELINING\\nSIZE 51200000\\nETRN\\nSTARTTLS\\nAUTH DIGEST-MD5 NTLM CRAM-MD5\\nENHANCEDSTATUSCODES\\n8BITMIME\\nDSN\\nSMTPUTF8\\nCHUNKING'\n\n test_module.py:5: AssertionError\n -------------------------- Captured stdout setup ---------------------------\n finalizing \n ________________________ test_noop[mail.python.org] ________________________\n\n smtp_connection = \n\n def test_noop(smtp_connection):\n response, msg = smtp_connection.noop()\n assert response == 250\n > assert 0 # for demo purposes\n E assert 0\n\n test_module.py:11: AssertionError\n ------------------------- Captured stdout teardown -------------------------\n finalizing \n 4 failed in 0.12 seconds\n\nWe see that our two test functions each ran twice, against the different\n``smtp_connection`` instances. Note also, that with the ``mail.python.org``\nconnection the second test fails in ``test_ehlo`` because a\ndifferent server string is expected than what arrived.\n\npytest will build a string that is the test ID for each fixture value\nin a parametrized fixture, e.g. ``test_ehlo[smtp.gmail.com]`` and\n``test_ehlo[mail.python.org]`` in the above examples. These IDs can\nbe used with ``-k`` to select specific cases to run, and they will\nalso identify the specific case when one is failing. Running pytest\nwith ``--collect-only`` will show the generated IDs.\n\nNumbers, strings, booleans and None will have their usual string\nrepresentation used in the test ID. For other objects, pytest will\nmake a string based on the argument name. It is possible to customise\nthe string used in a test ID for a certain fixture value by using the\n``ids`` keyword argument::\n\n # content of test_ids.py\n import pytest\n\n @pytest.fixture(params=[0, 1], ids=[\"spam\", \"ham\"])\n def a(request):\n return request.param\n\n def test_a(a):\n pass\n\n def idfn(fixture_value):\n if fixture_value == 0:\n return \"eggs\"\n else:\n return None\n\n @pytest.fixture(params=[0, 1], ids=idfn)\n def b(request):\n return request.param\n\n def test_b(b):\n pass\n\nThe above shows how ``ids`` can be either a list of strings to use or\na function which will be called with the fixture value and then\nhas to return a string to use. In the latter case if the function\nreturn ``None`` then pytest's auto-generated ID will be used.\n\nRunning the above tests results in the following test IDs being used:\n\n.. code-block:: pytest\n\n $ pytest --collect-only\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 10 items\n \n \n \n \n \n \n \n \n \n \n \n \n \n\n ======================= no tests ran in 0.12 seconds =======================\n\n.. _`fixture-parametrize-marks`:\n\nUsing marks with parametrized fixtures\n--------------------------------------\n\n:func:`pytest.param` can be used to apply marks in values sets of parametrized fixtures in the same way\nthat they can be used with :ref:`@pytest.mark.parametrize <@pytest.mark.parametrize>`.\n\nExample::\n\n # content of test_fixture_marks.py\n import pytest\n @pytest.fixture(params=[0, 1, pytest.param(2, marks=pytest.mark.skip)])\n def data_set(request):\n return request.param\n\n def test_data(data_set):\n pass\n\nRunning this test will *skip* the invocation of ``data_set`` with value ``2``:\n\n.. code-block:: pytest\n\n $ pytest test_fixture_marks.py -v\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collecting ... collected 3 items\n\n test_fixture_marks.py::test_data[0] PASSED [ 33%]\n test_fixture_marks.py::test_data[1] PASSED [ 66%]\n test_fixture_marks.py::test_data[2] SKIPPED [100%]\n\n =================== 2 passed, 1 skipped in 0.12 seconds ====================\n\n.. _`interdependent fixtures`:\n\nModularity: using fixtures from a fixture function\n----------------------------------------------------------\n\nYou can not only use fixtures in test functions but fixture functions\ncan use other fixtures themselves. This contributes to a modular design\nof your fixtures and allows re-use of framework-specific fixtures across\nmany projects. As a simple example, we can extend the previous example\nand instantiate an object ``app`` where we stick the already defined\n``smtp_connection`` resource into it::\n\n # content of test_appsetup.py\n\n import pytest\n\n class App(object):\n def __init__(self, smtp_connection):\n self.smtp_connection = smtp_connection\n\n @pytest.fixture(scope=\"module\")\n def app(smtp_connection):\n return App(smtp_connection)\n\n def test_smtp_connection_exists(app):\n assert app.smtp_connection\n\nHere we declare an ``app`` fixture which receives the previously defined\n``smtp_connection`` fixture and instantiates an ``App`` object with it. Let's run it:\n\n.. code-block:: pytest\n\n $ pytest -v test_appsetup.py\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collecting ... collected 2 items\n\n test_appsetup.py::test_smtp_connection_exists[smtp.gmail.com] PASSED [ 50%]\n test_appsetup.py::test_smtp_connection_exists[mail.python.org] PASSED [100%]\n\n ========================= 2 passed in 0.12 seconds =========================\n\nDue to the parametrization of ``smtp_connection``, the test will run twice with two\ndifferent ``App`` instances and respective smtp servers. There is no\nneed for the ``app`` fixture to be aware of the ``smtp_connection``\nparametrization because pytest will fully analyse the fixture dependency graph.\n\nNote that the ``app`` fixture has a scope of ``module`` and uses a\nmodule-scoped ``smtp_connection`` fixture. The example would still work if\n``smtp_connection`` was cached on a ``session`` scope: it is fine for fixtures to use\n\"broader\" scoped fixtures but not the other way round:\nA session-scoped fixture could not use a module-scoped one in a\nmeaningful way.\n\n\n.. _`automatic per-resource grouping`:\n\nAutomatic grouping of tests by fixture instances\n----------------------------------------------------------\n\n.. regendoc: wipe\n\npytest minimizes the number of active fixtures during test runs.\nIf you have a parametrized fixture, then all the tests using it will\nfirst execute with one instance and then finalizers are called\nbefore the next fixture instance is created. Among other things,\nthis eases testing of applications which create and use global state.\n\nThe following example uses two parametrized fixtures, one of which is\nscoped on a per-module basis, and all the functions perform ``print`` calls\nto show the setup/teardown flow::\n\n # content of test_module.py\n import pytest\n\n @pytest.fixture(scope=\"module\", params=[\"mod1\", \"mod2\"])\n def modarg(request):\n param = request.param\n print(\" SETUP modarg %s\" % param)\n yield param\n print(\" TEARDOWN modarg %s\" % param)\n\n @pytest.fixture(scope=\"function\", params=[1,2])\n def otherarg(request):\n param = request.param\n print(\" SETUP otherarg %s\" % param)\n yield param\n print(\" TEARDOWN otherarg %s\" % param)\n\n def test_0(otherarg):\n print(\" RUN test0 with otherarg %s\" % otherarg)\n def test_1(modarg):\n print(\" RUN test1 with modarg %s\" % modarg)\n def test_2(otherarg, modarg):\n print(\" RUN test2 with otherarg %s and modarg %s\" % (otherarg, modarg))\n\n\nLet's run the tests in verbose mode and with looking at the print-output:\n\n.. code-block:: pytest\n\n $ pytest -v -s test_module.py\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collecting ... collected 8 items\n\n test_module.py::test_0[1] SETUP otherarg 1\n RUN test0 with otherarg 1\n PASSED TEARDOWN otherarg 1\n\n test_module.py::test_0[2] SETUP otherarg 2\n RUN test0 with otherarg 2\n PASSED TEARDOWN otherarg 2\n\n test_module.py::test_1[mod1] SETUP modarg mod1\n RUN test1 with modarg mod1\n PASSED\n test_module.py::test_2[mod1-1] SETUP otherarg 1\n RUN test2 with otherarg 1 and modarg mod1\n PASSED TEARDOWN otherarg 1\n\n test_module.py::test_2[mod1-2] SETUP otherarg 2\n RUN test2 with otherarg 2 and modarg mod1\n PASSED TEARDOWN otherarg 2\n\n test_module.py::test_1[mod2] TEARDOWN modarg mod1\n SETUP modarg mod2\n RUN test1 with modarg mod2\n PASSED\n test_module.py::test_2[mod2-1] SETUP otherarg 1\n RUN test2 with otherarg 1 and modarg mod2\n PASSED TEARDOWN otherarg 1\n\n test_module.py::test_2[mod2-2] SETUP otherarg 2\n RUN test2 with otherarg 2 and modarg mod2\n PASSED TEARDOWN otherarg 2\n TEARDOWN modarg mod2\n\n\n ========================= 8 passed in 0.12 seconds =========================\n\nYou can see that the parametrized module-scoped ``modarg`` resource caused an\nordering of test execution that lead to the fewest possible \"active\" resources.\nThe finalizer for the ``mod1`` parametrized resource was executed before the\n``mod2`` resource was setup.\n\nIn particular notice that test_0 is completely independent and finishes first.\nThen test_1 is executed with ``mod1``, then test_2 with ``mod1``, then test_1\nwith ``mod2`` and finally test_2 with ``mod2``.\n\nThe ``otherarg`` parametrized resource (having function scope) was set up before\nand teared down after every test that used it.\n\n\n.. _`usefixtures`:\n\nUsing fixtures from classes, modules or projects\n----------------------------------------------------------------------\n\n.. regendoc:wipe\n\nSometimes test functions do not directly need access to a fixture object.\nFor example, tests may require to operate with an empty directory as the\ncurrent working directory but otherwise do not care for the concrete\ndirectory. Here is how you can use the standard `tempfile\n`_ and pytest fixtures to\nachieve it. We separate the creation of the fixture into a conftest.py\nfile::\n\n # content of conftest.py\n\n import pytest\n import tempfile\n import os\n\n @pytest.fixture()\n def cleandir():\n newpath = tempfile.mkdtemp()\n os.chdir(newpath)\n\nand declare its use in a test module via a ``usefixtures`` marker::\n\n # content of test_setenv.py\n import os\n import pytest\n\n @pytest.mark.usefixtures(\"cleandir\")\n class TestDirectoryInit(object):\n def test_cwd_starts_empty(self):\n assert os.listdir(os.getcwd()) == []\n with open(\"myfile\", \"w\") as f:\n f.write(\"hello\")\n\n def test_cwd_again_starts_empty(self):\n assert os.listdir(os.getcwd()) == []\n\nDue to the ``usefixtures`` marker, the ``cleandir`` fixture\nwill be required for the execution of each test method, just as if\nyou specified a \"cleandir\" function argument to each of them. Let's run it\nto verify our fixture is activated and the tests pass:\n\n.. code-block:: pytest\n\n $ pytest -q\n .. [100%]\n 2 passed in 0.12 seconds\n\nYou can specify multiple fixtures like this:\n\n.. code-block:: python\n\n @pytest.mark.usefixtures(\"cleandir\", \"anotherfixture\")\n def test():\n ...\n\nand you may specify fixture usage at the test module level, using\na generic feature of the mark mechanism:\n\n.. code-block:: python\n\n pytestmark = pytest.mark.usefixtures(\"cleandir\")\n\nNote that the assigned variable *must* be called ``pytestmark``, assigning e.g.\n``foomark`` will not activate the fixtures.\n\nIt is also possible to put fixtures required by all tests in your project\ninto an ini-file:\n\n.. code-block:: ini\n\n # content of pytest.ini\n [pytest]\n usefixtures = cleandir\n\n\n.. warning::\n\n Note this mark has no effect in **fixture functions**. For example,\n this **will not work as expected**:\n\n .. code-block:: python\n\n @pytest.mark.usefixtures(\"my_other_fixture\")\n @pytest.fixture\n def my_fixture_that_sadly_wont_use_my_other_fixture():\n ...\n\n Currently this will not generate any error or warning, but this is intended\n to be handled by `#3664 `_.\n\n\n.. _`autouse`:\n.. _`autouse fixtures`:\n\nAutouse fixtures (xUnit setup on steroids)\n----------------------------------------------------------------------\n\n.. regendoc:wipe\n\nOccasionally, you may want to have fixtures get invoked automatically\nwithout declaring a function argument explicitly or a `usefixtures`_ decorator.\nAs a practical example, suppose we have a database fixture which has a\nbegin/rollback/commit architecture and we want to automatically surround\neach test method by a transaction and a rollback. Here is a dummy\nself-contained implementation of this idea::\n\n # content of test_db_transact.py\n\n import pytest\n\n class DB(object):\n def __init__(self):\n self.intransaction = []\n def begin(self, name):\n self.intransaction.append(name)\n def rollback(self):\n self.intransaction.pop()\n\n @pytest.fixture(scope=\"module\")\n def db():\n return DB()\n\n class TestClass(object):\n @pytest.fixture(autouse=True)\n def transact(self, request, db):\n db.begin(request.function.__name__)\n yield\n db.rollback()\n\n def test_method1(self, db):\n assert db.intransaction == [\"test_method1\"]\n\n def test_method2(self, db):\n assert db.intransaction == [\"test_method2\"]\n\nThe class-level ``transact`` fixture is marked with *autouse=true*\nwhich implies that all test methods in the class will use this fixture\nwithout a need to state it in the test function signature or with a\nclass-level ``usefixtures`` decorator.\n\nIf we run it, we get two passing tests:\n\n.. code-block:: pytest\n\n $ pytest -q\n .. [100%]\n 2 passed in 0.12 seconds\n\nHere is how autouse fixtures work in other scopes:\n\n- autouse fixtures obey the ``scope=`` keyword-argument: if an autouse fixture\n has ``scope='session'`` it will only be run once, no matter where it is\n defined. ``scope='class'`` means it will be run once per class, etc.\n\n- if an autouse fixture is defined in a test module, all its test\n functions automatically use it.\n\n- if an autouse fixture is defined in a conftest.py file then all tests in\n all test modules below its directory will invoke the fixture.\n\n- lastly, and **please use that with care**: if you define an autouse\n fixture in a plugin, it will be invoked for all tests in all projects\n where the plugin is installed. This can be useful if a fixture only\n anyway works in the presence of certain settings e. g. in the ini-file. Such\n a global fixture should always quickly determine if it should do\n any work and avoid otherwise expensive imports or computation.\n\nNote that the above ``transact`` fixture may very well be a fixture that\nyou want to make available in your project without having it generally\nactive. The canonical way to do that is to put the transact definition\ninto a conftest.py file **without** using ``autouse``::\n\n # content of conftest.py\n @pytest.fixture\n def transact(request, db):\n db.begin()\n yield\n db.rollback()\n\nand then e.g. have a TestClass using it by declaring the need::\n\n @pytest.mark.usefixtures(\"transact\")\n class TestClass(object):\n def test_method1(self):\n ...\n\nAll test methods in this TestClass will use the transaction fixture while\nother test classes or functions in the module will not use it unless\nthey also add a ``transact`` reference.\n\nOverriding fixtures on various levels\n-------------------------------------\n\nIn relatively large test suite, you most likely need to ``override`` a ``global`` or ``root`` fixture with a ``locally``\ndefined one, keeping the test code readable and maintainable.\n\nOverride a fixture on a folder (conftest) level\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nGiven the tests file structure is:\n\n::\n\n tests/\n __init__.py\n\n conftest.py\n # content of tests/conftest.py\n import pytest\n\n @pytest.fixture\n def username():\n return 'username'\n\n test_something.py\n # content of tests/test_something.py\n def test_username(username):\n assert username == 'username'\n\n subfolder/\n __init__.py\n\n conftest.py\n # content of tests/subfolder/conftest.py\n import pytest\n\n @pytest.fixture\n def username(username):\n return 'overridden-' + username\n\n test_something.py\n # content of tests/subfolder/test_something.py\n def test_username(username):\n assert username == 'overridden-username'\n\nAs you can see, a fixture with the same name can be overridden for certain test folder level.\nNote that the ``base`` or ``super`` fixture can be accessed from the ``overriding``\nfixture easily - used in the example above.\n\nOverride a fixture on a test module level\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nGiven the tests file structure is:\n\n::\n\n tests/\n __init__.py\n\n conftest.py\n # content of tests/conftest.py\n import pytest\n\n @pytest.fixture\n def username():\n return 'username'\n\n test_something.py\n # content of tests/test_something.py\n import pytest\n\n @pytest.fixture\n def username(username):\n return 'overridden-' + username\n\n def test_username(username):\n assert username == 'overridden-username'\n\n test_something_else.py\n # content of tests/test_something_else.py\n import pytest\n\n @pytest.fixture\n def username(username):\n return 'overridden-else-' + username\n\n def test_username(username):\n assert username == 'overridden-else-username'\n\nIn the example above, a fixture with the same name can be overridden for certain test module.\n\n\nOverride a fixture with direct test parametrization\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nGiven the tests file structure is:\n\n::\n\n tests/\n __init__.py\n\n conftest.py\n # content of tests/conftest.py\n import pytest\n\n @pytest.fixture\n def username():\n return 'username'\n\n @pytest.fixture\n def other_username(username):\n return 'other-' + username\n\n test_something.py\n # content of tests/test_something.py\n import pytest\n\n @pytest.mark.parametrize('username', ['directly-overridden-username'])\n def test_username(username):\n assert username == 'directly-overridden-username'\n\n @pytest.mark.parametrize('username', ['directly-overridden-username-other'])\n def test_username_other(other_username):\n assert other_username == 'other-directly-overridden-username-other'\n\nIn the example above, a fixture value is overridden by the test parameter value. Note that the value of the fixture\ncan be overridden this way even if the test doesn't use it directly (doesn't mention it in the function prototype).\n\n\nOverride a parametrized fixture with non-parametrized one and vice versa\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nGiven the tests file structure is:\n\n::\n\n tests/\n __init__.py\n\n conftest.py\n # content of tests/conftest.py\n import pytest\n\n @pytest.fixture(params=['one', 'two', 'three'])\n def parametrized_username(request):\n return request.param\n\n @pytest.fixture\n def non_parametrized_username(request):\n return 'username'\n\n test_something.py\n # content of tests/test_something.py\n import pytest\n\n @pytest.fixture\n def parametrized_username():\n return 'overridden-username'\n\n @pytest.fixture(params=['one', 'two', 'three'])\n def non_parametrized_username(request):\n return request.param\n\n def test_username(parametrized_username):\n assert parametrized_username == 'overridden-username'\n\n def test_parametrized_username(non_parametrized_username):\n assert non_parametrized_username in ['one', 'two', 'three']\n\n test_something_else.py\n # content of tests/test_something_else.py\n def test_username(parametrized_username):\n assert parametrized_username in ['one', 'two', 'three']\n\n def test_username(non_parametrized_username):\n assert non_parametrized_username == 'username'\n\nIn the example above, a parametrized fixture is overridden with a non-parametrized version, and\na non-parametrized fixture is overridden with a parametrized version for certain test module.\nThe same applies for the test folder level obviously.\n"},{"col":31,"endLoc":1252,"id":3959,"nodeType":"Lambda","startLoc":1252,"text":"lambda f: None"},{"col":47,"endLoc":1252,"id":3960,"nodeType":"Lambda","startLoc":1252,"text":"lambda f: False"},{"col":64,"endLoc":1252,"id":3961,"nodeType":"Lambda","startLoc":1252,"text":"lambda f: True"},{"col":4,"comment":"null","endLoc":104,"header":"def test_maxfail(self, testdir)","id":3962,"name":"test_maxfail","nodeType":"Function","startLoc":93,"text":"def test_maxfail(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n def test_one(): assert 0\n def test_two(): assert 0\n def test_three(): assert 0\n \"\"\",\n \"--maxfail=2\",\n )\n passed, skipped, failed = reprec.countoutcomes()\n assert failed == 2\n assert passed == skipped == 0"},{"col":4,"comment":"null","endLoc":136,"header":"def test_broken_repr(self, testdir)","id":3963,"name":"test_broken_repr","nodeType":"Function","startLoc":106,"text":"def test_broken_repr(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n class BrokenRepr1(object):\n foo=0\n def __repr__(self):\n raise Exception(\"Ha Ha fooled you, I'm a broken repr().\")\n\n class TestBrokenClass(object):\n def test_explicit_bad_repr(self):\n t = BrokenRepr1()\n with pytest.raises(Exception, match=\"I'm a broken repr\"):\n repr(t)\n\n def test_implicit_bad_repr1(self):\n t = BrokenRepr1()\n assert t.foo == 1\n\n \"\"\"\n )\n reprec = testdir.inline_run(p)\n passed, skipped, failed = reprec.listoutcomes()\n assert (len(passed), len(skipped), len(failed)) == (1, 0, 1)\n out = failed[0].longrepr.reprcrash.message\n assert (\n out.find(\n \"\"\"[Exception(\"Ha Ha fooled you, I'm a broken repr().\") raised in repr()]\"\"\"\n )\n != -1\n )"},{"id":3964,"name":"bash-completion.rst","nodeType":"TextFile","path":"doc/en","text":"\n.. _bash_completion:\n\nSetting up bash completion\n==========================\n\nWhen using bash as your shell, ``pytest`` can use argcomplete\n(https://argcomplete.readthedocs.io/) for auto-completion.\nFor this ``argcomplete`` needs to be installed **and** enabled.\n\nInstall argcomplete using:\n\n.. code-block:: bash\n\n sudo pip install 'argcomplete>=0.5.7'\n\nFor global activation of all argcomplete enabled python applications run:\n\n.. code-block:: bash\n\n sudo activate-global-python-argcomplete\n\nFor permanent (but not global) ``pytest`` activation, use:\n\n.. code-block:: bash\n\n register-python-argcomplete pytest >> ~/.bashrc\n\nFor one-time activation of argcomplete for ``pytest`` only, use:\n\n.. code-block:: bash\n\n eval \"$(register-python-argcomplete pytest)\"\n"},{"id":3965,"name":"TIDELIFT.rst","nodeType":"TextFile","path":"","text":"========\nTidelift\n========\n\npytest is a member of `Tidelift`_. This document describes how the core team manages\nTidelift-related activities.\n\nWhat is it\n==========\n\nTidelift aims to make Open Source sustainable by offering subscriptions to companies which rely\non Open Source packages. This subscription allows it to pay maintainers of those Open Source\npackages to aid sustainability of the work.\n\nFunds\n=====\n\nIt was decided in the `mailing list`_ that the Tidelift contribution will be split evenly between\nmembers of the `contributors team`_ interested in receiving funding.\n\nThe current list of contributors receiving funding are:\n\n* `@asottile`_\n* `@blueyed`_\n* `@nicoddemus`_\n\nContributors interested in receiving a part of the funds just need to submit a PR adding their\nname to the list. Contributors that want to stop receiving the funds should also submit a PR\nin the same way.\n\nThe PR should mention `@pytest-dev/tidelift-admins`_ so appropriate changes\ncan be made in the Tidelift platform.\n\nAfter the PR has been accepted and merged, the contributor should register in the `Tidelift`_\nplatform and follow the instructions there, including signing an `agreement`_.\n\nAdmins\n======\n\nA few people have admin access to the Tidelift dashboard to make changes. Those people\nare part of the `@pytest-dev/tidelift-admins`_ team.\n\n`Core contributors`_ interested in helping out with Tidelift maintenance are welcome! We don't\nexpect much work here other than the occasional adding/removal of a contributor from receiving\nfunds. Just drop a line to one of the `@pytest-dev/tidelift-admins`_ or use the mailing list.\n\n\n.. _`Tidelift`: https://tidelift.com\n.. _`mailing list`: https://mail.python.org/pipermail/pytest-dev/2019-May/004716.html\n.. _`contributors team`: https://github.com/orgs/pytest-dev/teams/contributors\n.. _`core contributors`: https://github.com/orgs/pytest-dev/teams/core/members\n.. _`@pytest-dev/tidelift-admins`: https://github.com/orgs/pytest-dev/teams/tidelift-admins/members\n.. _`agreement`: https://tidelift.com/docs/lifting/agreement\n\n.. _`@asottile`: https://github.com/asottile\n.. _`@blueyed`: https://github.com/blueyed\n.. _`@nicoddemus`: https://github.com/nicoddemus\n"},{"col":4,"comment":"null","endLoc":90,"header":"@pytest.fixture\n def pdblist(self, request)","id":3968,"name":"pdblist","nodeType":"Function","startLoc":80,"text":"@pytest.fixture\n def pdblist(self, request):\n monkeypatch = request.getfixturevalue(\"monkeypatch\")\n pdblist = []\n\n def mypdb(*args):\n pdblist.append(args)\n\n plugin = request.config.pluginmanager.getplugin(\"debugging\")\n monkeypatch.setattr(plugin, \"post_mortem\", mypdb)\n return pdblist"},{"id":3969,"name":"release-3.10.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.10.1\n=======================================\n\npytest 3.10.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Boris Feld\n* Bruno Oliveira\n* Daniel Hahler\n* Fabien ZARIFIAN\n* Jon Dufresne\n* Ronny Pfannschmidt\n\n\nHappy testing,\nThe pytest Development Team\n"},{"col":24,"endLoc":363,"id":3970,"nodeType":"Lambda","startLoc":363,"text":"lambda: True"},{"col":4,"comment":"null","endLoc":160,"header":"def test_broken_repr_with_showlocals_verbose(self, testdir)","id":3971,"name":"test_broken_repr_with_showlocals_verbose","nodeType":"Function","startLoc":138,"text":"def test_broken_repr_with_showlocals_verbose(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n class ObjWithErrorInRepr:\n def __repr__(self):\n raise NotImplementedError\n\n def test_repr_error():\n x = ObjWithErrorInRepr()\n assert x == \"value\"\n \"\"\"\n )\n reprec = testdir.inline_run(\"--showlocals\", \"-vv\", p)\n passed, skipped, failed = reprec.listoutcomes()\n assert (len(passed), len(skipped), len(failed)) == (0, 0, 1)\n entries = failed[0].longrepr.reprtraceback.reprentries\n assert len(entries) == 1\n repr_locals = entries[0].reprlocals\n assert repr_locals.lines\n assert len(repr_locals.lines) == 1\n assert repr_locals.lines[0].startswith(\n 'x = <[NotImplementedError(\"\") raised in repr()] ObjWithErrorInRepr'\n )"},{"col":4,"comment":"null","endLoc":378,"header":"def test_short_circuit_evaluation(self)","id":3972,"name":"test_short_circuit_evaluation","nodeType":"Function","startLoc":368,"text":"def test_short_circuit_evaluation(self):\n def f():\n assert True or explode # noqa\n\n getmsg(f, must_pass=True)\n\n def f():\n x = 1\n assert x == 1 or x == 2\n\n getmsg(f, must_pass=True)"},{"col":0,"comment":"","endLoc":2,"header":"warning_types.py#","id":3973,"name":"","nodeType":"Function","startLoc":2,"text":"PYTESTER_COPY_EXAMPLE = PytestExperimentalApiWarning.simple(\"testdir.copy_example\")"},{"col":4,"comment":"null","endLoc":403,"header":"def test_unary_op(self)","id":3974,"name":"test_unary_op","nodeType":"Function","startLoc":380,"text":"def test_unary_op(self):\n def f():\n x = True\n assert not x\n\n assert getmsg(f) == \"assert not True\"\n\n def f():\n x = 0\n assert ~x + 1\n\n assert getmsg(f) == \"assert (~0 + 1)\"\n\n def f():\n x = 3\n assert -x + x\n\n assert getmsg(f) == \"assert (-3 + 3)\"\n\n def f():\n x = 0\n assert +x + x\n\n assert getmsg(f) == \"assert (+0 + 0)\""},{"fileName":"test_warnings.py","filePath":"testing","id":3975,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport sys\nimport warnings\n\nimport six\n\nimport pytest\n\nWARNINGS_SUMMARY_HEADER = \"warnings summary\"\n\n\n@pytest.fixture\ndef pyfile_with_warnings(testdir, request):\n \"\"\"\n Create a test file which calls a function in a module which generates warnings.\n \"\"\"\n testdir.syspathinsert()\n test_name = request.function.__name__\n module_name = test_name.lstrip(\"test_\") + \"_module\"\n testdir.makepyfile(\n **{\n module_name: \"\"\"\n import warnings\n def foo():\n warnings.warn(UserWarning(\"user warning\"))\n warnings.warn(RuntimeWarning(\"runtime warning\"))\n return 1\n \"\"\",\n test_name: \"\"\"\n import {module_name}\n def test_func():\n assert {module_name}.foo() == 1\n \"\"\".format(\n module_name=module_name\n ),\n }\n )\n\n\n@pytest.mark.filterwarnings(\"default\")\ndef test_normal_flow(testdir, pyfile_with_warnings):\n \"\"\"\n Check that the warnings section is displayed.\n \"\"\"\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*== %s ==*\" % WARNINGS_SUMMARY_HEADER,\n \"test_normal_flow.py::test_func\",\n \"*normal_flow_module.py:3: UserWarning: user warning\",\n '* warnings.warn(UserWarning(\"user warning\"))',\n \"*normal_flow_module.py:4: RuntimeWarning: runtime warning\",\n '* warnings.warn(RuntimeWarning(\"runtime warning\"))',\n \"* 1 passed, 2 warnings*\",\n ]\n )\n\n\n@pytest.mark.filterwarnings(\"always\")\ndef test_setup_teardown_warnings(testdir, pyfile_with_warnings):\n testdir.makepyfile(\n \"\"\"\n import warnings\n import pytest\n\n @pytest.fixture\n def fix():\n warnings.warn(UserWarning(\"warning during setup\"))\n yield\n warnings.warn(UserWarning(\"warning during teardown\"))\n\n def test_func(fix):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*== %s ==*\" % WARNINGS_SUMMARY_HEADER,\n \"*test_setup_teardown_warnings.py:6: UserWarning: warning during setup\",\n '*warnings.warn(UserWarning(\"warning during setup\"))',\n \"*test_setup_teardown_warnings.py:8: UserWarning: warning during teardown\",\n '*warnings.warn(UserWarning(\"warning during teardown\"))',\n \"* 1 passed, 2 warnings*\",\n ]\n )\n\n\n@pytest.mark.parametrize(\"method\", [\"cmdline\", \"ini\"])\ndef test_as_errors(testdir, pyfile_with_warnings, method):\n args = (\"-W\", \"error\") if method == \"cmdline\" else ()\n if method == \"ini\":\n testdir.makeini(\n \"\"\"\n [pytest]\n filterwarnings=error\n \"\"\"\n )\n # Use a subprocess, since changing logging level affects other threads\n # (xdist).\n result = testdir.runpytest_subprocess(*args)\n result.stdout.fnmatch_lines(\n [\n \"E UserWarning: user warning\",\n \"as_errors_module.py:3: UserWarning\",\n \"* 1 failed in *\",\n ]\n )\n\n\n@pytest.mark.parametrize(\"method\", [\"cmdline\", \"ini\"])\ndef test_ignore(testdir, pyfile_with_warnings, method):\n args = (\"-W\", \"ignore\") if method == \"cmdline\" else ()\n if method == \"ini\":\n testdir.makeini(\n \"\"\"\n [pytest]\n filterwarnings= ignore\n \"\"\"\n )\n\n result = testdir.runpytest(*args)\n result.stdout.fnmatch_lines([\"* 1 passed in *\"])\n assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()\n\n\n@pytest.mark.skipif(\n sys.version_info < (3, 0), reason=\"warnings message is unicode is ok in python3\"\n)\n@pytest.mark.filterwarnings(\"always\")\ndef test_unicode(testdir, pyfile_with_warnings):\n testdir.makepyfile(\n \"\"\"\n # -*- coding: utf-8 -*-\n import warnings\n import pytest\n\n\n @pytest.fixture\n def fix():\n warnings.warn(u\"测试\")\n yield\n\n def test_func(fix):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*== %s ==*\" % WARNINGS_SUMMARY_HEADER,\n \"*test_unicode.py:8: UserWarning: \\u6d4b\\u8bd5*\",\n \"* 1 passed, 1 warnings*\",\n ]\n )\n\n\n@pytest.mark.skipif(\n sys.version_info >= (3, 0),\n reason=\"warnings message is broken as it is not str instance\",\n)\ndef test_py2_unicode(testdir, pyfile_with_warnings):\n if getattr(sys, \"pypy_version_info\", ())[:2] == (5, 9) and sys.platform.startswith(\n \"win\"\n ):\n pytest.xfail(\"fails with unicode error on PyPy2 5.9 and Windows (#2905)\")\n testdir.makepyfile(\n \"\"\"\n # -*- coding: utf-8 -*-\n import warnings\n import pytest\n\n\n @pytest.fixture\n def fix():\n warnings.warn(u\"测试\")\n yield\n\n @pytest.mark.filterwarnings('always')\n def test_func(fix):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*== %s ==*\" % WARNINGS_SUMMARY_HEADER,\n \"*test_py2_unicode.py:8: UserWarning: \\\\u6d4b\\\\u8bd5\",\n '*warnings.warn(u\"\\u6d4b\\u8bd5\")',\n \"*warnings.py:*: UnicodeWarning: Warning is using unicode non*\",\n \"* 1 passed, 2 warnings*\",\n ]\n )\n\n\ndef test_py2_unicode_ascii(testdir):\n \"\"\"Ensure that our warning about 'unicode warnings containing non-ascii messages'\n does not trigger with ascii-convertible messages\"\"\"\n testdir.makeini(\"[pytest]\")\n testdir.makepyfile(\n \"\"\"\n import pytest\n import warnings\n\n @pytest.mark.filterwarnings('always')\n def test_func():\n warnings.warn(u\"hello\")\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*== %s ==*\" % WARNINGS_SUMMARY_HEADER,\n '*warnings.warn(u\"hello\")',\n \"* 1 passed, 1 warnings in*\",\n ]\n )\n\n\ndef test_works_with_filterwarnings(testdir):\n \"\"\"Ensure our warnings capture does not mess with pre-installed filters (#2430).\"\"\"\n testdir.makepyfile(\n \"\"\"\n import warnings\n\n class MyWarning(Warning):\n pass\n\n warnings.filterwarnings(\"error\", category=MyWarning)\n\n class TestWarnings(object):\n def test_my_warning(self):\n try:\n warnings.warn(MyWarning(\"warn!\"))\n assert False\n except MyWarning:\n assert True\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*== 1 passed in *\"])\n\n\n@pytest.mark.parametrize(\"default_config\", [\"ini\", \"cmdline\"])\ndef test_filterwarnings_mark(testdir, default_config):\n \"\"\"\n Test ``filterwarnings`` mark works and takes precedence over command line and ini options.\n \"\"\"\n if default_config == \"ini\":\n testdir.makeini(\n \"\"\"\n [pytest]\n filterwarnings = always\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import warnings\n import pytest\n\n @pytest.mark.filterwarnings('ignore::RuntimeWarning')\n def test_ignore_runtime_warning():\n warnings.warn(RuntimeWarning())\n\n @pytest.mark.filterwarnings('error')\n def test_warning_error():\n warnings.warn(RuntimeWarning())\n\n def test_show_warning():\n warnings.warn(RuntimeWarning())\n \"\"\"\n )\n result = testdir.runpytest(\"-W always\" if default_config == \"cmdline\" else \"\")\n result.stdout.fnmatch_lines([\"*= 1 failed, 2 passed, 1 warnings in *\"])\n\n\ndef test_non_string_warning_argument(testdir):\n \"\"\"Non-str argument passed to warning breaks pytest (#2956)\"\"\"\n testdir.makepyfile(\n \"\"\"\n import warnings\n import pytest\n\n def test():\n warnings.warn(UserWarning(1, u'foo'))\n \"\"\"\n )\n result = testdir.runpytest(\"-W\", \"always\")\n result.stdout.fnmatch_lines([\"*= 1 passed, 1 warnings in *\"])\n\n\ndef test_filterwarnings_mark_registration(testdir):\n \"\"\"Ensure filterwarnings mark is registered\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.filterwarnings('error')\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--strict-markers\")\n assert result.ret == 0\n\n\n@pytest.mark.filterwarnings(\"always\")\ndef test_warning_captured_hook(testdir):\n testdir.makeconftest(\n \"\"\"\n from _pytest.warnings import _issue_warning_captured\n def pytest_configure(config):\n _issue_warning_captured(UserWarning(\"config warning\"), config.hook, stacklevel=2)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest, warnings\n\n warnings.warn(UserWarning(\"collect warning\"))\n\n @pytest.fixture\n def fix():\n warnings.warn(UserWarning(\"setup warning\"))\n yield 1\n warnings.warn(UserWarning(\"teardown warning\"))\n\n def test_func(fix):\n warnings.warn(UserWarning(\"call warning\"))\n assert fix == 1\n \"\"\"\n )\n\n collected = []\n\n class WarningCollector:\n def pytest_warning_captured(self, warning_message, when, item):\n imge_name = item.name if item is not None else \"\"\n collected.append((str(warning_message.message), when, imge_name))\n\n result = testdir.runpytest(plugins=[WarningCollector()])\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n expected = [\n (\"config warning\", \"config\", \"\"),\n (\"collect warning\", \"collect\", \"\"),\n (\"setup warning\", \"runtest\", \"test_func\"),\n (\"call warning\", \"runtest\", \"test_func\"),\n (\"teardown warning\", \"runtest\", \"test_func\"),\n ]\n assert collected == expected\n\n\n@pytest.mark.filterwarnings(\"always\")\ndef test_collection_warnings(testdir):\n \"\"\"\n Check that we also capture warnings issued during test collection (#3251).\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import warnings\n\n warnings.warn(UserWarning(\"collection warning\"))\n\n def test_foo():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*== %s ==*\" % WARNINGS_SUMMARY_HEADER,\n \" *collection_warnings.py:3: UserWarning: collection warning\",\n ' warnings.warn(UserWarning(\"collection warning\"))',\n \"* 1 passed, 1 warnings*\",\n ]\n )\n\n\n@pytest.mark.filterwarnings(\"always\")\ndef test_mark_regex_escape(testdir):\n \"\"\"@pytest.mark.filterwarnings should not try to escape regex characters (#3936)\"\"\"\n testdir.makepyfile(\n r\"\"\"\n import pytest, warnings\n\n @pytest.mark.filterwarnings(r\"ignore:some \\(warning\\)\")\n def test_foo():\n warnings.warn(UserWarning(\"some (warning)\"))\n \"\"\"\n )\n result = testdir.runpytest()\n assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()\n\n\n@pytest.mark.filterwarnings(\"default\")\n@pytest.mark.parametrize(\"ignore_pytest_warnings\", [\"no\", \"ini\", \"cmdline\"])\ndef test_hide_pytest_internal_warnings(testdir, ignore_pytest_warnings):\n \"\"\"Make sure we can ignore internal pytest warnings using a warnings filter.\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n import warnings\n\n warnings.warn(pytest.PytestWarning(\"some internal warning\"))\n\n def test_bar():\n pass\n \"\"\"\n )\n if ignore_pytest_warnings == \"ini\":\n testdir.makeini(\n \"\"\"\n [pytest]\n filterwarnings = ignore::pytest.PytestWarning\n \"\"\"\n )\n args = (\n [\"-W\", \"ignore::pytest.PytestWarning\"]\n if ignore_pytest_warnings == \"cmdline\"\n else []\n )\n result = testdir.runpytest(*args)\n if ignore_pytest_warnings != \"no\":\n assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()\n else:\n result.stdout.fnmatch_lines(\n [\n \"*== %s ==*\" % WARNINGS_SUMMARY_HEADER,\n \"*test_hide_pytest_internal_warnings.py:4: PytestWarning: some internal warning\",\n \"* 1 passed, 1 warnings *\",\n ]\n )\n\n\n@pytest.mark.parametrize(\"ignore_on_cmdline\", [True, False])\ndef test_option_precedence_cmdline_over_ini(testdir, ignore_on_cmdline):\n \"\"\"filters defined in the command-line should take precedence over filters in ini files (#3946).\"\"\"\n testdir.makeini(\n \"\"\"\n [pytest]\n filterwarnings = error\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import warnings\n def test():\n warnings.warn(UserWarning('hello'))\n \"\"\"\n )\n args = [\"-W\", \"ignore\"] if ignore_on_cmdline else []\n result = testdir.runpytest(*args)\n if ignore_on_cmdline:\n result.stdout.fnmatch_lines([\"* 1 passed in*\"])\n else:\n result.stdout.fnmatch_lines([\"* 1 failed in*\"])\n\n\ndef test_option_precedence_mark(testdir):\n \"\"\"Filters defined by marks should always take precedence (#3946).\"\"\"\n testdir.makeini(\n \"\"\"\n [pytest]\n filterwarnings = ignore\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest, warnings\n @pytest.mark.filterwarnings('error')\n def test():\n warnings.warn(UserWarning('hello'))\n \"\"\"\n )\n result = testdir.runpytest(\"-W\", \"ignore\")\n result.stdout.fnmatch_lines([\"* 1 failed in*\"])\n\n\nclass TestDeprecationWarningsByDefault:\n \"\"\"\n Note: all pytest runs are executed in a subprocess so we don't inherit warning filters\n from pytest's own test suite\n \"\"\"\n\n def create_file(self, testdir, mark=\"\"):\n testdir.makepyfile(\n \"\"\"\n import pytest, warnings\n\n warnings.warn(DeprecationWarning(\"collection\"))\n\n {mark}\n def test_foo():\n warnings.warn(PendingDeprecationWarning(\"test run\"))\n \"\"\".format(\n mark=mark\n )\n )\n\n @pytest.mark.parametrize(\"customize_filters\", [True, False])\n def test_shown_by_default(self, testdir, customize_filters):\n \"\"\"Show deprecation warnings by default, even if user has customized the warnings filters (#4013).\"\"\"\n self.create_file(testdir)\n if customize_filters:\n testdir.makeini(\n \"\"\"\n [pytest]\n filterwarnings =\n once::UserWarning\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines(\n [\n \"*== %s ==*\" % WARNINGS_SUMMARY_HEADER,\n \"*test_shown_by_default.py:3: DeprecationWarning: collection\",\n \"*test_shown_by_default.py:7: PendingDeprecationWarning: test run\",\n \"* 1 passed, 2 warnings*\",\n ]\n )\n\n def test_hidden_by_ini(self, testdir):\n self.create_file(testdir)\n testdir.makeini(\n \"\"\"\n [pytest]\n filterwarnings =\n ignore::DeprecationWarning\n ignore::PendingDeprecationWarning\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()\n\n def test_hidden_by_mark(self, testdir):\n \"\"\"Should hide the deprecation warning from the function, but the warning during collection should\n be displayed normally.\n \"\"\"\n self.create_file(\n testdir,\n mark='@pytest.mark.filterwarnings(\"ignore::PendingDeprecationWarning\")',\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines(\n [\n \"*== %s ==*\" % WARNINGS_SUMMARY_HEADER,\n \"*test_hidden_by_mark.py:3: DeprecationWarning: collection\",\n \"* 1 passed, 1 warnings*\",\n ]\n )\n\n def test_hidden_by_cmdline(self, testdir):\n self.create_file(testdir)\n result = testdir.runpytest_subprocess(\n \"-W\",\n \"ignore::DeprecationWarning\",\n \"-W\",\n \"ignore::PendingDeprecationWarning\",\n )\n assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()\n\n def test_hidden_by_system(self, testdir, monkeypatch):\n self.create_file(testdir)\n monkeypatch.setenv(str(\"PYTHONWARNINGS\"), str(\"once::UserWarning\"))\n result = testdir.runpytest_subprocess()\n assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()\n\n\n@pytest.mark.skipif(not six.PY2, reason=\"Python 2 only issue\")\ndef test_infinite_loop_warning_against_unicode_usage_py2(testdir):\n \"\"\"\n We need to be careful when raising the warning about unicode usage with \"warnings.warn\"\n because it might be overwritten by users and this itself causes another warning (#3691).\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n # -*- coding: utf-8 -*-\n from __future__ import unicode_literals\n import warnings\n import pytest\n\n def _custom_showwarning(message, *a, **b):\n return \"WARNING: {}\".format(message)\n\n warnings.formatwarning = _custom_showwarning\n\n @pytest.mark.filterwarnings(\"default\")\n def test_custom_warning_formatter():\n warnings.warn(\"¥\")\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*1 passed, * warnings in*\"])\n\n\n@pytest.mark.parametrize(\"change_default\", [None, \"ini\", \"cmdline\"])\ndef test_removed_in_pytest4_warning_as_error(testdir, change_default):\n testdir.makepyfile(\n \"\"\"\n import warnings, pytest\n def test():\n warnings.warn(pytest.RemovedInPytest4Warning(\"some warning\"))\n \"\"\"\n )\n if change_default == \"ini\":\n testdir.makeini(\n \"\"\"\n [pytest]\n filterwarnings =\n ignore::pytest.RemovedInPytest4Warning\n \"\"\"\n )\n\n args = (\n (\"-Wignore::pytest.RemovedInPytest4Warning\",)\n if change_default == \"cmdline\"\n else ()\n )\n result = testdir.runpytest(*args)\n if change_default is None:\n result.stdout.fnmatch_lines([\"* 1 failed in *\"])\n else:\n assert change_default in (\"ini\", \"cmdline\")\n result.stdout.fnmatch_lines([\"* 1 passed in *\"])\n\n\nclass TestAssertionWarnings:\n @staticmethod\n def assert_result_warns(result, msg):\n result.stdout.fnmatch_lines([\"*PytestAssertRewriteWarning: %s*\" % msg])\n\n def test_tuple_warning(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert (1,2)\n \"\"\"\n )\n result = testdir.runpytest()\n self.assert_result_warns(\n result, \"assertion is always true, perhaps remove parentheses?\"\n )\n\n @staticmethod\n def create_file(testdir, return_none):\n testdir.makepyfile(\n \"\"\"\n def foo(return_none):\n if return_none:\n return None\n else:\n return False\n\n def test_foo():\n assert foo({return_none})\n \"\"\".format(\n return_none=return_none\n )\n )\n\n def test_none_function_warns(self, testdir):\n self.create_file(testdir, True)\n result = testdir.runpytest()\n self.assert_result_warns(\n result, 'asserting the value None, please use \"assert is None\"'\n )\n\n def test_assert_is_none_no_warn(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def foo():\n return None\n\n def test_foo():\n assert foo() is None\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed in*\"])\n\n def test_false_function_no_warn(self, testdir):\n self.create_file(testdir, False)\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 failed in*\"])\n\n\ndef test_warnings_checker_twice():\n \"\"\"Issue #4617\"\"\"\n expectation = pytest.warns(UserWarning)\n with expectation:\n warnings.warn(\"Message A\", UserWarning)\n with expectation:\n warnings.warn(\"Message B\", UserWarning)\n\n\n@pytest.mark.filterwarnings(\"always\")\ndef test_group_warnings_by_message(testdir):\n testdir.copy_example(\"warnings/test_group_warnings_by_message.py\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"test_group_warnings_by_message.py::test_foo[0]\",\n \"test_group_warnings_by_message.py::test_foo[1]\",\n \"test_group_warnings_by_message.py::test_foo[2]\",\n \"test_group_warnings_by_message.py::test_foo[3]\",\n \"test_group_warnings_by_message.py::test_foo[4]\",\n \"test_group_warnings_by_message.py::test_bar\",\n ]\n )\n warning_code = 'warnings.warn(UserWarning(\"foo\"))'\n assert warning_code in result.stdout.str()\n assert result.stdout.str().count(warning_code) == 1\n"},{"className":"TestDeprecationWarningsByDefault","col":0,"comment":"\n Note: all pytest runs are executed in a subprocess so we don't inherit warning filters\n from pytest's own test suite\n ","endLoc":569,"id":3976,"nodeType":"Class","startLoc":482,"text":"class TestDeprecationWarningsByDefault:\n \"\"\"\n Note: all pytest runs are executed in a subprocess so we don't inherit warning filters\n from pytest's own test suite\n \"\"\"\n\n def create_file(self, testdir, mark=\"\"):\n testdir.makepyfile(\n \"\"\"\n import pytest, warnings\n\n warnings.warn(DeprecationWarning(\"collection\"))\n\n {mark}\n def test_foo():\n warnings.warn(PendingDeprecationWarning(\"test run\"))\n \"\"\".format(\n mark=mark\n )\n )\n\n @pytest.mark.parametrize(\"customize_filters\", [True, False])\n def test_shown_by_default(self, testdir, customize_filters):\n \"\"\"Show deprecation warnings by default, even if user has customized the warnings filters (#4013).\"\"\"\n self.create_file(testdir)\n if customize_filters:\n testdir.makeini(\n \"\"\"\n [pytest]\n filterwarnings =\n once::UserWarning\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines(\n [\n \"*== %s ==*\" % WARNINGS_SUMMARY_HEADER,\n \"*test_shown_by_default.py:3: DeprecationWarning: collection\",\n \"*test_shown_by_default.py:7: PendingDeprecationWarning: test run\",\n \"* 1 passed, 2 warnings*\",\n ]\n )\n\n def test_hidden_by_ini(self, testdir):\n self.create_file(testdir)\n testdir.makeini(\n \"\"\"\n [pytest]\n filterwarnings =\n ignore::DeprecationWarning\n ignore::PendingDeprecationWarning\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()\n\n def test_hidden_by_mark(self, testdir):\n \"\"\"Should hide the deprecation warning from the function, but the warning during collection should\n be displayed normally.\n \"\"\"\n self.create_file(\n testdir,\n mark='@pytest.mark.filterwarnings(\"ignore::PendingDeprecationWarning\")',\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines(\n [\n \"*== %s ==*\" % WARNINGS_SUMMARY_HEADER,\n \"*test_hidden_by_mark.py:3: DeprecationWarning: collection\",\n \"* 1 passed, 1 warnings*\",\n ]\n )\n\n def test_hidden_by_cmdline(self, testdir):\n self.create_file(testdir)\n result = testdir.runpytest_subprocess(\n \"-W\",\n \"ignore::DeprecationWarning\",\n \"-W\",\n \"ignore::PendingDeprecationWarning\",\n )\n assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()\n\n def test_hidden_by_system(self, testdir, monkeypatch):\n self.create_file(testdir)\n monkeypatch.setenv(str(\"PYTHONWARNINGS\"), str(\"once::UserWarning\"))\n result = testdir.runpytest_subprocess()\n assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()"},{"col":4,"comment":"null","endLoc":501,"header":"def create_file(self, testdir, mark=\"\")","id":3977,"name":"create_file","nodeType":"Function","startLoc":488,"text":"def create_file(self, testdir, mark=\"\"):\n testdir.makepyfile(\n \"\"\"\n import pytest, warnings\n\n warnings.warn(DeprecationWarning(\"collection\"))\n\n {mark}\n def test_foo():\n warnings.warn(PendingDeprecationWarning(\"test run\"))\n \"\"\".format(\n mark=mark\n )\n )"},{"col":4,"comment":"null","endLoc":416,"header":"def test_binary_op(self)","id":3979,"name":"test_binary_op","nodeType":"Function","startLoc":405,"text":"def test_binary_op(self):\n def f():\n x = 1\n y = -1\n assert x + y\n\n assert getmsg(f) == \"assert (1 + -1)\"\n\n def f():\n assert not 5 % 4\n\n assert getmsg(f) == \"assert not (5 % 4)\""},{"col":4,"comment":"null","endLoc":427,"header":"def test_boolop_percent(self)","id":3980,"name":"test_boolop_percent","nodeType":"Function","startLoc":418,"text":"def test_boolop_percent(self):\n def f():\n assert 3 % 2 and False\n\n assert getmsg(f) == \"assert ((3 % 2) and False)\"\n\n def f():\n assert False or 4 % 2\n\n assert getmsg(f) == \"assert (False or (4 % 2))\""},{"fileName":"runner.py","filePath":"src/_pytest","id":3981,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\" basic collect and runtest protocol implementations \"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport bdb\nimport os\nimport sys\nfrom time import time\n\nimport attr\nimport six\n\nfrom .reports import CollectErrorRepr\nfrom .reports import CollectReport\nfrom .reports import TestReport\nfrom _pytest._code.code import ExceptionInfo\nfrom _pytest.outcomes import Exit\nfrom _pytest.outcomes import Skipped\nfrom _pytest.outcomes import TEST_OUTCOME\n\n#\n# pytest plugin hooks\n\n\ndef pytest_addoption(parser):\n group = parser.getgroup(\"terminal reporting\", \"reporting\", after=\"general\")\n group.addoption(\n \"--durations\",\n action=\"store\",\n type=int,\n default=None,\n metavar=\"N\",\n help=\"show N slowest setup/test durations (N=0 for all).\",\n ),\n\n\ndef pytest_terminal_summary(terminalreporter):\n durations = terminalreporter.config.option.durations\n verbose = terminalreporter.config.getvalue(\"verbose\")\n if durations is None:\n return\n tr = terminalreporter\n dlist = []\n for replist in tr.stats.values():\n for rep in replist:\n if hasattr(rep, \"duration\"):\n dlist.append(rep)\n if not dlist:\n return\n dlist.sort(key=lambda x: x.duration)\n dlist.reverse()\n if not durations:\n tr.write_sep(\"=\", \"slowest test durations\")\n else:\n tr.write_sep(\"=\", \"slowest %s test durations\" % durations)\n dlist = dlist[:durations]\n\n for rep in dlist:\n if verbose < 2 and rep.duration < 0.005:\n tr.write_line(\"\")\n tr.write_line(\"(0.00 durations hidden. Use -vv to show these durations.)\")\n break\n tr.write_line(\"%02.2fs %-8s %s\" % (rep.duration, rep.when, rep.nodeid))\n\n\ndef pytest_sessionstart(session):\n session._setupstate = SetupState()\n\n\ndef pytest_sessionfinish(session):\n session._setupstate.teardown_all()\n\n\ndef pytest_runtest_protocol(item, nextitem):\n item.ihook.pytest_runtest_logstart(nodeid=item.nodeid, location=item.location)\n runtestprotocol(item, nextitem=nextitem)\n item.ihook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location)\n return True\n\n\ndef runtestprotocol(item, log=True, nextitem=None):\n hasrequest = hasattr(item, \"_request\")\n if hasrequest and not item._request:\n item._initrequest()\n rep = call_and_report(item, \"setup\", log)\n reports = [rep]\n if rep.passed:\n if item.config.getoption(\"setupshow\", False):\n show_test_item(item)\n if not item.config.getoption(\"setuponly\", False):\n reports.append(call_and_report(item, \"call\", log))\n reports.append(call_and_report(item, \"teardown\", log, nextitem=nextitem))\n # after all teardown hooks have been called\n # want funcargs and request info to go away\n if hasrequest:\n item._request = False\n item.funcargs = None\n return reports\n\n\ndef show_test_item(item):\n \"\"\"Show test function, parameters and the fixtures of the test item.\"\"\"\n tw = item.config.get_terminal_writer()\n tw.line()\n tw.write(\" \" * 8)\n tw.write(item._nodeid)\n used_fixtures = sorted(item._fixtureinfo.name2fixturedefs.keys())\n if used_fixtures:\n tw.write(\" (fixtures used: {})\".format(\", \".join(used_fixtures)))\n\n\ndef pytest_runtest_setup(item):\n _update_current_test_var(item, \"setup\")\n item.session._setupstate.prepare(item)\n\n\ndef pytest_runtest_call(item):\n _update_current_test_var(item, \"call\")\n sys.last_type, sys.last_value, sys.last_traceback = (None, None, None)\n try:\n item.runtest()\n except Exception:\n # Store trace info to allow postmortem debugging\n type, value, tb = sys.exc_info()\n tb = tb.tb_next # Skip *this* frame\n sys.last_type = type\n sys.last_value = value\n sys.last_traceback = tb\n del type, value, tb # Get rid of these in this frame\n raise\n\n\ndef pytest_runtest_teardown(item, nextitem):\n _update_current_test_var(item, \"teardown\")\n item.session._setupstate.teardown_exact(item, nextitem)\n _update_current_test_var(item, None)\n\n\ndef _update_current_test_var(item, when):\n \"\"\"\n Update PYTEST_CURRENT_TEST to reflect the current item and stage.\n\n If ``when`` is None, delete PYTEST_CURRENT_TEST from the environment.\n \"\"\"\n var_name = \"PYTEST_CURRENT_TEST\"\n if when:\n value = \"{} ({})\".format(item.nodeid, when)\n # don't allow null bytes on environment variables (see #2644, #2957)\n value = value.replace(\"\\x00\", \"(null)\")\n os.environ[var_name] = value\n else:\n os.environ.pop(var_name)\n\n\ndef pytest_report_teststatus(report):\n if report.when in (\"setup\", \"teardown\"):\n if report.failed:\n # category, shortletter, verbose-word\n return \"error\", \"E\", \"ERROR\"\n elif report.skipped:\n return \"skipped\", \"s\", \"SKIPPED\"\n else:\n return \"\", \"\", \"\"\n\n\n#\n# Implementation\n\n\ndef call_and_report(item, when, log=True, **kwds):\n call = call_runtest_hook(item, when, **kwds)\n hook = item.ihook\n report = hook.pytest_runtest_makereport(item=item, call=call)\n if log:\n hook.pytest_runtest_logreport(report=report)\n if check_interactive_exception(call, report):\n hook.pytest_exception_interact(node=item, call=call, report=report)\n return report\n\n\ndef check_interactive_exception(call, report):\n return call.excinfo and not (\n hasattr(report, \"wasxfail\")\n or call.excinfo.errisinstance(Skipped)\n or call.excinfo.errisinstance(bdb.BdbQuit)\n )\n\n\ndef call_runtest_hook(item, when, **kwds):\n hookname = \"pytest_runtest_\" + when\n ihook = getattr(item.ihook, hookname)\n reraise = (Exit,)\n if not item.config.getoption(\"usepdb\", False):\n reraise += (KeyboardInterrupt,)\n return CallInfo.from_call(\n lambda: ihook(item=item, **kwds), when=when, reraise=reraise\n )\n\n\n@attr.s(repr=False)\nclass CallInfo(object):\n \"\"\" Result/Exception info a function invocation. \"\"\"\n\n _result = attr.ib()\n # Optional[ExceptionInfo]\n excinfo = attr.ib()\n start = attr.ib()\n stop = attr.ib()\n when = attr.ib()\n\n @property\n def result(self):\n if self.excinfo is not None:\n raise AttributeError(\"{!r} has no valid result\".format(self))\n return self._result\n\n @classmethod\n def from_call(cls, func, when, reraise=None):\n #: context of invocation: one of \"setup\", \"call\",\n #: \"teardown\", \"memocollect\"\n start = time()\n excinfo = None\n try:\n result = func()\n except: # noqa\n excinfo = ExceptionInfo.from_current()\n if reraise is not None and excinfo.errisinstance(reraise):\n raise\n result = None\n stop = time()\n return cls(start=start, stop=stop, when=when, result=result, excinfo=excinfo)\n\n def __repr__(self):\n if self.excinfo is not None:\n status = \"exception\"\n value = self.excinfo.value\n else:\n # TODO: investigate unification\n value = repr(self._result)\n status = \"result\"\n return \"\".format(\n when=self.when, value=value, status=status\n )\n\n\ndef pytest_runtest_makereport(item, call):\n return TestReport.from_item_and_call(item, call)\n\n\ndef pytest_make_collect_report(collector):\n call = CallInfo.from_call(lambda: list(collector.collect()), \"collect\")\n longrepr = None\n if not call.excinfo:\n outcome = \"passed\"\n else:\n from _pytest import nose\n\n skip_exceptions = (Skipped,) + nose.get_skip_exceptions()\n if call.excinfo.errisinstance(skip_exceptions):\n outcome = \"skipped\"\n r = collector._repr_failure_py(call.excinfo, \"line\").reprcrash\n longrepr = (str(r.path), r.lineno, r.message)\n else:\n outcome = \"failed\"\n errorinfo = collector.repr_failure(call.excinfo)\n if not hasattr(errorinfo, \"toterminal\"):\n errorinfo = CollectErrorRepr(errorinfo)\n longrepr = errorinfo\n rep = CollectReport(\n collector.nodeid, outcome, longrepr, getattr(call, \"result\", None)\n )\n rep.call = call # see collect_one_node\n return rep\n\n\nclass SetupState(object):\n \"\"\" shared state for setting up/tearing down test items or collectors. \"\"\"\n\n def __init__(self):\n self.stack = []\n self._finalizers = {}\n\n def addfinalizer(self, finalizer, colitem):\n \"\"\" attach a finalizer to the given colitem.\n if colitem is None, this will add a finalizer that\n is called at the end of teardown_all().\n \"\"\"\n assert colitem and not isinstance(colitem, tuple)\n assert callable(finalizer)\n # assert colitem in self.stack # some unit tests don't setup stack :/\n self._finalizers.setdefault(colitem, []).append(finalizer)\n\n def _pop_and_teardown(self):\n colitem = self.stack.pop()\n self._teardown_with_finalization(colitem)\n\n def _callfinalizers(self, colitem):\n finalizers = self._finalizers.pop(colitem, None)\n exc = None\n while finalizers:\n fin = finalizers.pop()\n try:\n fin()\n except TEST_OUTCOME:\n # XXX Only first exception will be seen by user,\n # ideally all should be reported.\n if exc is None:\n exc = sys.exc_info()\n if exc:\n six.reraise(*exc)\n\n def _teardown_with_finalization(self, colitem):\n self._callfinalizers(colitem)\n if hasattr(colitem, \"teardown\"):\n colitem.teardown()\n for colitem in self._finalizers:\n assert (\n colitem is None or colitem in self.stack or isinstance(colitem, tuple)\n )\n\n def teardown_all(self):\n while self.stack:\n self._pop_and_teardown()\n for key in list(self._finalizers):\n self._teardown_with_finalization(key)\n assert not self._finalizers\n\n def teardown_exact(self, item, nextitem):\n needed_collectors = nextitem and nextitem.listchain() or []\n self._teardown_towards(needed_collectors)\n\n def _teardown_towards(self, needed_collectors):\n exc = None\n while self.stack:\n if self.stack == needed_collectors[: len(self.stack)]:\n break\n try:\n self._pop_and_teardown()\n except TEST_OUTCOME:\n # XXX Only first exception will be seen by user,\n # ideally all should be reported.\n if exc is None:\n exc = sys.exc_info()\n if exc:\n six.reraise(*exc)\n\n def prepare(self, colitem):\n \"\"\" setup objects along the collector chain to the test-method\n and teardown previously setup objects.\"\"\"\n needed_collectors = colitem.listchain()\n self._teardown_towards(needed_collectors)\n\n # check if the last collection node has raised an error\n for col in self.stack:\n if hasattr(col, \"_prepare_exc\"):\n six.reraise(*col._prepare_exc)\n for col in needed_collectors[len(self.stack) :]:\n self.stack.append(col)\n try:\n col.setup()\n except TEST_OUTCOME:\n col._prepare_exc = sys.exc_info()\n raise\n\n\ndef collect_one_node(collector):\n ihook = collector.ihook\n ihook.pytest_collectstart(collector=collector)\n rep = ihook.pytest_make_collect_report(collector=collector)\n call = rep.__dict__.pop(\"call\", None)\n if call and check_interactive_exception(call, rep):\n ihook.pytest_exception_interact(node=collector, call=call, report=rep)\n return rep\n"},{"col":4,"comment":"null","endLoc":582,"header":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_setup(self, item)","id":3982,"name":"pytest_runtest_setup","nodeType":"Function","startLoc":579,"text":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_setup(self, item):\n with self._runtest_for(item, \"setup\"):\n yield"},{"col":4,"comment":"null","endLoc":442,"header":"@pytest.mark.skipif(\"sys.version_info < (3,5)\")\n def test_at_operator_issue1290(self, testdir)","id":3983,"name":"test_at_operator_issue1290","nodeType":"Function","startLoc":429,"text":"@pytest.mark.skipif(\"sys.version_info < (3,5)\")\n def test_at_operator_issue1290(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class Matrix(object):\n def __init__(self, num):\n self.num = num\n def __matmul__(self, other):\n return self.num * other.num\n\n def test_multmat_operator():\n assert Matrix(2) @ Matrix(3) == 6\"\"\"\n )\n testdir.runpytest().assert_outcomes(passed=1)"},{"col":0,"comment":"\n time() -> floating point number\n \n Return the current time in seconds since the Epoch.\n Fractions of a second may be present if the system clock provides them.\n ","endLoc":299,"header":"def time()","id":3984,"name":"time","nodeType":"Function","startLoc":292,"text":"def time(): # real signature unknown; restored from __doc__\n \"\"\"\n time() -> floating point number\n \n Return the current time in seconds since the Epoch.\n Fractions of a second may be present if the system clock provides them.\n \"\"\"\n return 0.0"},{"col":4,"comment":"See #4412","endLoc":455,"header":"@pytest.mark.skipif(\"sys.version_info < (3,5)\")\n def test_starred_with_side_effect(self, testdir)","id":3985,"name":"test_starred_with_side_effect","nodeType":"Function","startLoc":444,"text":"@pytest.mark.skipif(\"sys.version_info < (3,5)\")\n def test_starred_with_side_effect(self, testdir):\n \"\"\"See #4412\"\"\"\n testdir.makepyfile(\n \"\"\"\\\n def test():\n f = lambda x: x\n x = iter([1, 2, 3])\n assert 2 * next(x) == f(*[next(x)])\n \"\"\"\n )\n testdir.runpytest().assert_outcomes(passed=1)"},{"col":4,"comment":"null","endLoc":526,"header":"def test_call(self)","id":3986,"name":"test_call","nodeType":"Function","startLoc":457,"text":"def test_call(self):\n def g(a=42, *args, **kwargs):\n return False\n\n ns = {\"g\": g}\n\n def f():\n assert g()\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g()\"\"\"\n )\n\n def f():\n assert g(1)\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g(1)\"\"\"\n )\n\n def f():\n assert g(1, 2)\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g(1, 2)\"\"\"\n )\n\n def f():\n assert g(1, g=42)\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g(1, g=42)\"\"\"\n )\n\n def f():\n assert g(1, 3, g=23)\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g(1, 3, g=23)\"\"\"\n )\n\n def f():\n seq = [1, 2, 3]\n assert g(*seq)\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g(*[1, 2, 3])\"\"\"\n )\n\n def f():\n x = \"a\"\n assert g(**{x: 2})\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = g(**{'a': 2})\"\"\"\n )"},{"className":"CollectErrorRepr","col":0,"comment":"null","endLoc":417,"id":3988,"nodeType":"Class","startLoc":412,"text":"class CollectErrorRepr(TerminalRepr):\n def __init__(self, msg):\n self.longrepr = msg\n\n def toterminal(self, out):\n out.line(self.longrepr, red=True)"},{"col":4,"comment":"null","endLoc":65,"header":"def test_argument_type(self)","id":3989,"name":"test_argument_type","nodeType":"Function","startLoc":52,"text":"def test_argument_type(self):\n argument = parseopt.Argument(\"-t\", dest=\"abc\", type=int)\n assert argument.type is int\n argument = parseopt.Argument(\"-t\", dest=\"abc\", type=str)\n assert argument.type is str\n argument = parseopt.Argument(\"-t\", dest=\"abc\", type=float)\n assert argument.type is float\n with pytest.warns(DeprecationWarning):\n with pytest.raises(KeyError):\n argument = parseopt.Argument(\"-t\", dest=\"abc\", type=\"choice\")\n argument = parseopt.Argument(\n \"-t\", dest=\"abc\", type=str, choices=[\"red\", \"blue\"]\n )\n assert argument.type is str"},{"col":4,"comment":"null","endLoc":414,"header":"def __init__(self, msg)","id":3990,"name":"__init__","nodeType":"Function","startLoc":413,"text":"def __init__(self, msg):\n self.longrepr = msg"},{"col":4,"comment":"null","endLoc":417,"header":"def toterminal(self, out)","id":3991,"name":"toterminal","nodeType":"Function","startLoc":416,"text":"def toterminal(self, out):\n out.line(self.longrepr, red=True)"},{"col":4,"comment":"null","endLoc":179,"header":"def test_skip_file_by_conftest(self, testdir)","id":3992,"name":"test_skip_file_by_conftest","nodeType":"Function","startLoc":162,"text":"def test_skip_file_by_conftest(self, testdir):\n testdir.makepyfile(\n conftest=\"\"\"\n import pytest\n def pytest_collect_file():\n pytest.skip(\"intentional\")\n \"\"\",\n test_file=\"\"\"\n def test_one(): pass\n \"\"\",\n )\n try:\n reprec = testdir.inline_run(testdir.tmpdir)\n except pytest.skip.Exception: # pragma: no cover\n pytest.fail(\"wrong skipped caught\")\n reports = reprec.getreports(\"pytest_collectreport\")\n assert len(reports) == 1\n assert reports[0].skipped"},{"className":"TestNewSession","col":0,"comment":"null","endLoc":251,"id":3993,"nodeType":"Class","startLoc":182,"text":"class TestNewSession(SessionTests):\n def test_order_of_execution(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n values = []\n def test_1():\n values.append(1)\n def test_2():\n values.append(2)\n def test_3():\n assert values == [1,2]\n class Testmygroup(object):\n reslist = values\n def test_1(self):\n self.reslist.append(1)\n def test_2(self):\n self.reslist.append(2)\n def test_3(self):\n self.reslist.append(3)\n def test_4(self):\n assert self.reslist == [1,2,1,2,3]\n \"\"\"\n )\n passed, skipped, failed = reprec.countoutcomes()\n assert failed == skipped == 0\n assert passed == 7\n\n def test_collect_only_with_various_situations(self, testdir):\n p = testdir.makepyfile(\n test_one=\"\"\"\n def test_one():\n raise ValueError()\n\n class TestX(object):\n def test_method_one(self):\n pass\n\n class TestY(TestX):\n pass\n \"\"\",\n test_three=\"xxxdsadsadsadsa\",\n __init__=\"\",\n )\n reprec = testdir.inline_run(\"--collect-only\", p.dirpath())\n\n itemstarted = reprec.getcalls(\"pytest_itemcollected\")\n assert len(itemstarted) == 3\n assert not reprec.getreports(\"pytest_runtest_logreport\")\n started = reprec.getcalls(\"pytest_collectstart\")\n finished = reprec.getreports(\"pytest_collectreport\")\n assert len(started) == len(finished)\n assert len(started) == 8\n colfail = [x for x in finished if x.failed]\n assert len(colfail) == 1\n\n def test_minus_x_import_error(self, testdir):\n testdir.makepyfile(__init__=\"\")\n testdir.makepyfile(test_one=\"xxxx\", test_two=\"yyyy\")\n reprec = testdir.inline_run(\"-x\", testdir.tmpdir)\n finished = reprec.getreports(\"pytest_collectreport\")\n colfail = [x for x in finished if x.failed]\n assert len(colfail) == 1\n\n def test_minus_x_overridden_by_maxfail(self, testdir):\n testdir.makepyfile(__init__=\"\")\n testdir.makepyfile(test_one=\"xxxx\", test_two=\"yyyy\", test_third=\"zzz\")\n reprec = testdir.inline_run(\"-x\", \"--maxfail=2\", testdir.tmpdir)\n finished = reprec.getreports(\"pytest_collectreport\")\n colfail = [x for x in finished if x.failed]\n assert len(colfail) == 2"},{"col":4,"comment":"null","endLoc":207,"header":"def test_order_of_execution(self, testdir)","id":3994,"name":"test_order_of_execution","nodeType":"Function","startLoc":183,"text":"def test_order_of_execution(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n values = []\n def test_1():\n values.append(1)\n def test_2():\n values.append(2)\n def test_3():\n assert values == [1,2]\n class Testmygroup(object):\n reslist = values\n def test_1(self):\n self.reslist.append(1)\n def test_2(self):\n self.reslist.append(2)\n def test_3(self):\n self.reslist.append(3)\n def test_4(self):\n assert self.reslist == [1,2,1,2,3]\n \"\"\"\n )\n passed, skipped, failed = reprec.countoutcomes()\n assert failed == skipped == 0\n assert passed == 7"},{"col":4,"comment":"null","endLoc":587,"header":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_call(self, item)","id":3995,"name":"pytest_runtest_call","nodeType":"Function","startLoc":584,"text":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_call(self, item):\n with self._runtest_for(item, \"call\"):\n yield"},{"attributeType":"null","col":8,"comment":"null","endLoc":414,"id":3996,"name":"longrepr","nodeType":"Attribute","startLoc":414,"text":"self.longrepr"},{"col":4,"comment":"null","endLoc":235,"header":"def test_collect_only_with_various_situations(self, testdir)","id":3997,"name":"test_collect_only_with_various_situations","nodeType":"Function","startLoc":209,"text":"def test_collect_only_with_various_situations(self, testdir):\n p = testdir.makepyfile(\n test_one=\"\"\"\n def test_one():\n raise ValueError()\n\n class TestX(object):\n def test_method_one(self):\n pass\n\n class TestY(TestX):\n pass\n \"\"\",\n test_three=\"xxxdsadsadsadsa\",\n __init__=\"\",\n )\n reprec = testdir.inline_run(\"--collect-only\", p.dirpath())\n\n itemstarted = reprec.getcalls(\"pytest_itemcollected\")\n assert len(itemstarted) == 3\n assert not reprec.getreports(\"pytest_runtest_logreport\")\n started = reprec.getcalls(\"pytest_collectstart\")\n finished = reprec.getreports(\"pytest_collectreport\")\n assert len(started) == len(finished)\n assert len(started) == 8\n colfail = [x for x in finished if x.failed]\n assert len(colfail) == 1"},{"col":4,"comment":"null","endLoc":551,"header":"def test_attribute(self)","id":3998,"name":"test_attribute","nodeType":"Function","startLoc":528,"text":"def test_attribute(self):\n class X(object):\n g = 3\n\n ns = {\"x\": X}\n\n def f():\n assert not x.g # noqa\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert not 3\n + where 3 = x.g\"\"\"\n )\n\n def f():\n x.a = False # noqa\n assert x.a # noqa\n\n assert (\n getmsg(f, ns)\n == \"\"\"assert False\n + where False = x.a\"\"\"\n )"},{"col":4,"comment":"null","endLoc":583,"header":"def test_comparisons(self)","id":3999,"name":"test_comparisons","nodeType":"Function","startLoc":553,"text":"def test_comparisons(self):\n def f():\n a, b = range(2)\n assert b < a\n\n assert getmsg(f) == \"\"\"assert 1 < 0\"\"\"\n\n def f():\n a, b, c = range(3)\n assert a > b > c\n\n assert getmsg(f) == \"\"\"assert 0 > 1\"\"\"\n\n def f():\n a, b, c = range(3)\n assert a < b > c\n\n assert getmsg(f) == \"\"\"assert 1 > 2\"\"\"\n\n def f():\n a, b, c = range(3)\n assert a < b <= c\n\n getmsg(f, must_pass=True)\n\n def f():\n a, b, c = range(3)\n assert a < b\n assert b < c\n\n getmsg(f, must_pass=True)"},{"fileName":"test_cacheprovider.py","filePath":"testing","id":4000,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport shutil\nimport sys\nimport textwrap\n\nimport py\n\nimport pytest\nfrom _pytest.main import EXIT_NOTESTSCOLLECTED\n\npytest_plugins = (\"pytester\",)\n\n\nclass TestNewAPI(object):\n def test_config_cache_makedir(self, testdir):\n testdir.makeini(\"[pytest]\")\n config = testdir.parseconfigure()\n with pytest.raises(ValueError):\n config.cache.makedir(\"key/name\")\n\n p = config.cache.makedir(\"name\")\n assert p.check()\n\n def test_config_cache_dataerror(self, testdir):\n testdir.makeini(\"[pytest]\")\n config = testdir.parseconfigure()\n cache = config.cache\n pytest.raises(TypeError, lambda: cache.set(\"key/name\", cache))\n config.cache.set(\"key/name\", 0)\n config.cache._getvaluepath(\"key/name\").write_bytes(b\"123invalid\")\n val = config.cache.get(\"key/name\", -2)\n assert val == -2\n\n @pytest.mark.filterwarnings(\"default\")\n def test_cache_writefail_cachfile_silent(self, testdir):\n testdir.makeini(\"[pytest]\")\n testdir.tmpdir.join(\".pytest_cache\").write(\"gone wrong\")\n config = testdir.parseconfigure()\n cache = config.cache\n cache.set(\"test/broken\", [])\n\n @pytest.mark.skipif(sys.platform.startswith(\"win\"), reason=\"no chmod on windows\")\n @pytest.mark.filterwarnings(\n \"ignore:could not create cache path:pytest.PytestWarning\"\n )\n def test_cache_writefail_permissions(self, testdir):\n testdir.makeini(\"[pytest]\")\n testdir.tmpdir.ensure_dir(\".pytest_cache\").chmod(0)\n config = testdir.parseconfigure()\n cache = config.cache\n cache.set(\"test/broken\", [])\n\n @pytest.mark.skipif(sys.platform.startswith(\"win\"), reason=\"no chmod on windows\")\n @pytest.mark.filterwarnings(\"default\")\n def test_cache_failure_warns(self, testdir):\n testdir.tmpdir.ensure_dir(\".pytest_cache\").chmod(0)\n testdir.makepyfile(\n \"\"\"\n def test_error():\n raise Exception\n\n \"\"\"\n )\n result = testdir.runpytest(\"-rw\")\n assert result.ret == 1\n # warnings from nodeids, lastfailed, and stepwise\n result.stdout.fnmatch_lines([\"*could not create cache path*\", \"*3 warnings*\"])\n\n def test_config_cache(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_configure(config):\n # see that we get cache information early on\n assert hasattr(config, \"cache\")\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_session(pytestconfig):\n assert hasattr(pytestconfig, \"cache\")\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_cachefuncarg(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_cachefuncarg(cache):\n val = cache.get(\"some/thing\", None)\n assert val is None\n cache.set(\"some/thing\", [1])\n pytest.raises(TypeError, lambda: cache.get(\"some/thing\"))\n val = cache.get(\"some/thing\", [])\n assert val == [1]\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_custom_rel_cache_dir(self, testdir):\n rel_cache_dir = os.path.join(\"custom_cache_dir\", \"subdir\")\n testdir.makeini(\n \"\"\"\n [pytest]\n cache_dir = {cache_dir}\n \"\"\".format(\n cache_dir=rel_cache_dir\n )\n )\n testdir.makepyfile(test_errored=\"def test_error():\\n assert False\")\n testdir.runpytest()\n assert testdir.tmpdir.join(rel_cache_dir).isdir()\n\n def test_custom_abs_cache_dir(self, testdir, tmpdir_factory):\n tmp = str(tmpdir_factory.mktemp(\"tmp\"))\n abs_cache_dir = os.path.join(tmp, \"custom_cache_dir\")\n testdir.makeini(\n \"\"\"\n [pytest]\n cache_dir = {cache_dir}\n \"\"\".format(\n cache_dir=abs_cache_dir\n )\n )\n testdir.makepyfile(test_errored=\"def test_error():\\n assert False\")\n testdir.runpytest()\n assert py.path.local(abs_cache_dir).isdir()\n\n def test_custom_cache_dir_with_env_var(self, testdir, monkeypatch):\n monkeypatch.setenv(\"env_var\", \"custom_cache_dir\")\n testdir.makeini(\n \"\"\"\n [pytest]\n cache_dir = {cache_dir}\n \"\"\".format(\n cache_dir=\"$env_var\"\n )\n )\n testdir.makepyfile(test_errored=\"def test_error():\\n assert False\")\n testdir.runpytest()\n assert testdir.tmpdir.join(\"custom_cache_dir\").isdir()\n\n\n@pytest.mark.parametrize(\"env\", ((), (\"TOX_ENV_DIR\", \"/tox_env_dir\")))\ndef test_cache_reportheader(env, testdir, monkeypatch):\n testdir.makepyfile(\"\"\"def test_foo(): pass\"\"\")\n if env:\n monkeypatch.setenv(*env)\n expected = os.path.join(env[1], \".pytest_cache\")\n else:\n monkeypatch.delenv(\"TOX_ENV_DIR\", raising=False)\n expected = \".pytest_cache\"\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines([\"cachedir: %s\" % expected])\n\n\ndef test_cache_reportheader_external_abspath(testdir, tmpdir_factory):\n external_cache = tmpdir_factory.mktemp(\n \"test_cache_reportheader_external_abspath_abs\"\n )\n\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n pass\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n cache_dir = {abscache}\n \"\"\".format(\n abscache=external_cache\n )\n )\n\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n [\"cachedir: {abscache}\".format(abscache=external_cache)]\n )\n\n\ndef test_cache_show(testdir):\n result = testdir.runpytest(\"--cache-show\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*cache is empty*\"])\n testdir.makeconftest(\n \"\"\"\n def pytest_configure(config):\n config.cache.set(\"my/name\", [1,2,3])\n config.cache.set(\"my/hello\", \"world\")\n config.cache.set(\"other/some\", {1:2})\n dp = config.cache.makedir(\"mydb\")\n dp.ensure(\"hello\")\n dp.ensure(\"world\")\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 5 # no tests executed\n\n result = testdir.runpytest(\"--cache-show\")\n result.stdout.fnmatch_lines(\n [\n \"*cachedir:*\",\n \"*- cache values for '[*]' -*\",\n \"cache/nodeids contains:\",\n \"my/name contains:\",\n \" [1, 2, 3]\",\n \"other/some contains:\",\n \" {*'1': 2}\",\n \"*- cache directories for '[*]' -*\",\n \"*mydb/hello*length 0*\",\n \"*mydb/world*length 0*\",\n ]\n )\n assert result.ret == 0\n\n result = testdir.runpytest(\"--cache-show\", \"*/hello\")\n result.stdout.fnmatch_lines(\n [\n \"*cachedir:*\",\n \"*- cache values for '[*]/hello' -*\",\n \"my/hello contains:\",\n \" *'world'\",\n \"*- cache directories for '[*]/hello' -*\",\n \"d/mydb/hello*length 0*\",\n ]\n )\n stdout = result.stdout.str()\n assert \"other/some\" not in stdout\n assert \"d/mydb/world\" not in stdout\n assert result.ret == 0\n\n\nclass TestLastFailed(object):\n def test_lastfailed_usecase(self, testdir, monkeypatch):\n monkeypatch.setenv(\"PYTHONDONTWRITEBYTECODE\", \"1\")\n p = testdir.makepyfile(\n \"\"\"\n def test_1():\n assert 0\n def test_2():\n assert 0\n def test_3():\n assert 1\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 failed*\"])\n p.write(\n textwrap.dedent(\n \"\"\"\\\n def test_1():\n assert 1\n\n def test_2():\n assert 1\n\n def test_3():\n assert 0\n \"\"\"\n )\n )\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines([\"*2 passed*1 desel*\"])\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 3 items\",\n \"run-last-failure: no previously failed tests, not deselecting items.\",\n \"*1 failed*2 passed*\",\n ]\n )\n result = testdir.runpytest(\"--lf\", \"--cache-clear\")\n result.stdout.fnmatch_lines([\"*1 failed*2 passed*\"])\n\n # Run this again to make sure clear-cache is robust\n if os.path.isdir(\".pytest_cache\"):\n shutil.rmtree(\".pytest_cache\")\n result = testdir.runpytest(\"--lf\", \"--cache-clear\")\n result.stdout.fnmatch_lines([\"*1 failed*2 passed*\"])\n\n def test_failedfirst_order(self, testdir):\n testdir.tmpdir.join(\"test_a.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_always_passes():\n assert 1\n \"\"\"\n )\n )\n testdir.tmpdir.join(\"test_b.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_always_fails():\n assert 0\n \"\"\"\n )\n )\n result = testdir.runpytest()\n # Test order will be collection order; alphabetical\n result.stdout.fnmatch_lines([\"test_a.py*\", \"test_b.py*\"])\n result = testdir.runpytest(\"--ff\")\n # Test order will be failing tests firs\n result.stdout.fnmatch_lines([\"test_b.py*\", \"test_a.py*\"])\n\n def test_lastfailed_failedfirst_order(self, testdir):\n testdir.makepyfile(\n **{\n \"test_a.py\": \"\"\"\\\n def test_always_passes():\n assert 1\n \"\"\",\n \"test_b.py\": \"\"\"\\\n def test_always_fails():\n assert 0\n \"\"\",\n }\n )\n result = testdir.runpytest()\n # Test order will be collection order; alphabetical\n result.stdout.fnmatch_lines([\"test_a.py*\", \"test_b.py*\"])\n result = testdir.runpytest(\"--lf\", \"--ff\")\n # Test order will be failing tests firs\n result.stdout.fnmatch_lines([\"test_b.py*\"])\n assert \"test_a.py\" not in result.stdout.str()\n\n def test_lastfailed_difference_invocations(self, testdir, monkeypatch):\n monkeypatch.setenv(\"PYTHONDONTWRITEBYTECODE\", \"1\")\n testdir.makepyfile(\n test_a=\"\"\"\\\n def test_a1():\n assert 0\n def test_a2():\n assert 1\n \"\"\",\n test_b=\"\"\"\\\n def test_b1():\n assert 0\n \"\"\",\n )\n p = testdir.tmpdir.join(\"test_a.py\")\n p2 = testdir.tmpdir.join(\"test_b.py\")\n\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 failed*\"])\n result = testdir.runpytest(\"--lf\", p2)\n result.stdout.fnmatch_lines([\"*1 failed*\"])\n p2.write(\n textwrap.dedent(\n \"\"\"\\\n def test_b1():\n assert 1\n \"\"\"\n )\n )\n result = testdir.runpytest(\"--lf\", p2)\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest(\"--lf\", p)\n result.stdout.fnmatch_lines([\"*1 failed*1 desel*\"])\n\n def test_lastfailed_usecase_splice(self, testdir, monkeypatch):\n monkeypatch.setenv(\"PYTHONDONTWRITEBYTECODE\", \"1\")\n testdir.makepyfile(\n \"\"\"\\\n def test_1():\n assert 0\n \"\"\"\n )\n p2 = testdir.tmpdir.join(\"test_something.py\")\n p2.write(\n textwrap.dedent(\n \"\"\"\\\n def test_2():\n assert 0\n \"\"\"\n )\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 failed*\"])\n result = testdir.runpytest(\"--lf\", p2)\n result.stdout.fnmatch_lines([\"*1 failed*\"])\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines([\"*2 failed*\"])\n\n def test_lastfailed_xpass(self, testdir):\n testdir.inline_runsource(\n \"\"\"\n import pytest\n @pytest.mark.xfail\n def test_hello():\n assert 1\n \"\"\"\n )\n config = testdir.parseconfigure()\n lastfailed = config.cache.get(\"cache/lastfailed\", -1)\n assert lastfailed == -1\n\n def test_non_serializable_parametrize(self, testdir):\n \"\"\"Test that failed parametrized tests with unmarshable parameters\n don't break pytest-cache.\n \"\"\"\n testdir.makepyfile(\n r\"\"\"\n import pytest\n\n @pytest.mark.parametrize('val', [\n b'\\xac\\x10\\x02G',\n ])\n def test_fail(val):\n assert False\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 failed in*\"])\n\n def test_terminal_report_lastfailed(self, testdir):\n test_a = testdir.makepyfile(\n test_a=\"\"\"\n def test_a1():\n pass\n def test_a2():\n pass\n \"\"\"\n )\n test_b = testdir.makepyfile(\n test_b=\"\"\"\n def test_b1():\n assert 0\n def test_b2():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"collected 4 items\", \"*2 failed, 2 passed in*\"])\n\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items\",\n \"run-last-failure: rerun previous 2 failures (skipped 1 file)\",\n \"*2 failed in*\",\n ]\n )\n\n result = testdir.runpytest(test_a, \"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items\",\n \"run-last-failure: 2 known failures not in selected tests\",\n \"*2 passed in*\",\n ]\n )\n\n result = testdir.runpytest(test_b, \"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items\",\n \"run-last-failure: rerun previous 2 failures\",\n \"*2 failed in*\",\n ]\n )\n\n result = testdir.runpytest(\"test_b.py::test_b1\", \"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 1 item\",\n \"run-last-failure: rerun previous 1 failure\",\n \"*1 failed in*\",\n ]\n )\n\n def test_terminal_report_failedfirst(self, testdir):\n testdir.makepyfile(\n test_a=\"\"\"\n def test_a1():\n assert 0\n def test_a2():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"collected 2 items\", \"*1 failed, 1 passed in*\"])\n\n result = testdir.runpytest(\"--ff\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items\",\n \"run-last-failure: rerun previous 1 failure first\",\n \"*1 failed, 1 passed in*\",\n ]\n )\n\n def test_lastfailed_collectfailure(self, testdir, monkeypatch):\n\n testdir.makepyfile(\n test_maybe=\"\"\"\n import os\n env = os.environ\n if '1' == env['FAILIMPORT']:\n raise ImportError('fail')\n def test_hello():\n assert '0' == env['FAILTEST']\n \"\"\"\n )\n\n def rlf(fail_import, fail_run):\n monkeypatch.setenv(\"FAILIMPORT\", str(fail_import))\n monkeypatch.setenv(\"FAILTEST\", str(fail_run))\n\n testdir.runpytest(\"-q\")\n config = testdir.parseconfigure()\n lastfailed = config.cache.get(\"cache/lastfailed\", -1)\n return lastfailed\n\n lastfailed = rlf(fail_import=0, fail_run=0)\n assert lastfailed == -1\n\n lastfailed = rlf(fail_import=1, fail_run=0)\n assert list(lastfailed) == [\"test_maybe.py\"]\n\n lastfailed = rlf(fail_import=0, fail_run=1)\n assert list(lastfailed) == [\"test_maybe.py::test_hello\"]\n\n def test_lastfailed_failure_subset(self, testdir, monkeypatch):\n\n testdir.makepyfile(\n test_maybe=\"\"\"\n import os\n env = os.environ\n if '1' == env['FAILIMPORT']:\n raise ImportError('fail')\n def test_hello():\n assert '0' == env['FAILTEST']\n \"\"\"\n )\n\n testdir.makepyfile(\n test_maybe2=\"\"\"\n import os\n env = os.environ\n if '1' == env['FAILIMPORT']:\n raise ImportError('fail')\n def test_hello():\n assert '0' == env['FAILTEST']\n\n def test_pass():\n pass\n \"\"\"\n )\n\n def rlf(fail_import, fail_run, args=()):\n monkeypatch.setenv(\"FAILIMPORT\", str(fail_import))\n monkeypatch.setenv(\"FAILTEST\", str(fail_run))\n\n result = testdir.runpytest(\"-q\", \"--lf\", *args)\n config = testdir.parseconfigure()\n lastfailed = config.cache.get(\"cache/lastfailed\", -1)\n return result, lastfailed\n\n result, lastfailed = rlf(fail_import=0, fail_run=0)\n assert lastfailed == -1\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n\n result, lastfailed = rlf(fail_import=1, fail_run=0)\n assert sorted(list(lastfailed)) == [\"test_maybe.py\", \"test_maybe2.py\"]\n\n result, lastfailed = rlf(fail_import=0, fail_run=0, args=(\"test_maybe2.py\",))\n assert list(lastfailed) == [\"test_maybe.py\"]\n\n # edge case of test selection - even if we remember failures\n # from other tests we still need to run all tests if no test\n # matches the failures\n result, lastfailed = rlf(fail_import=0, fail_run=0, args=(\"test_maybe2.py\",))\n assert list(lastfailed) == [\"test_maybe.py\"]\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n def test_lastfailed_creates_cache_when_needed(self, testdir):\n # Issue #1342\n testdir.makepyfile(test_empty=\"\")\n testdir.runpytest(\"-q\", \"--lf\")\n assert not os.path.exists(\".pytest_cache/v/cache/lastfailed\")\n\n testdir.makepyfile(test_successful=\"def test_success():\\n assert True\")\n testdir.runpytest(\"-q\", \"--lf\")\n assert not os.path.exists(\".pytest_cache/v/cache/lastfailed\")\n\n testdir.makepyfile(test_errored=\"def test_error():\\n assert False\")\n testdir.runpytest(\"-q\", \"--lf\")\n assert os.path.exists(\".pytest_cache/v/cache/lastfailed\")\n\n def test_xfail_not_considered_failure(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail\n def test():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 xfailed*\"])\n assert self.get_cached_last_failed(testdir) == []\n\n def test_xfail_strict_considered_failure(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(strict=True)\n def test():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 failed*\"])\n assert self.get_cached_last_failed(testdir) == [\n \"test_xfail_strict_considered_failure.py::test\"\n ]\n\n @pytest.mark.parametrize(\"mark\", [\"mark.xfail\", \"mark.skip\"])\n def test_failed_changed_to_xfail_or_skip(self, testdir, mark):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n assert self.get_cached_last_failed(testdir) == [\n \"test_failed_changed_to_xfail_or_skip.py::test\"\n ]\n assert result.ret == 1\n\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.{mark}\n def test():\n assert 0\n \"\"\".format(\n mark=mark\n )\n )\n result = testdir.runpytest()\n assert result.ret == 0\n assert self.get_cached_last_failed(testdir) == []\n assert result.ret == 0\n\n @pytest.mark.parametrize(\"quiet\", [True, False])\n @pytest.mark.parametrize(\"opt\", [\"--ff\", \"--lf\"])\n def test_lf_and_ff_prints_no_needless_message(self, quiet, opt, testdir):\n # Issue 3853\n testdir.makepyfile(\"def test(): assert 0\")\n args = [opt]\n if quiet:\n args.append(\"-q\")\n result = testdir.runpytest(*args)\n assert \"run all\" not in result.stdout.str()\n\n result = testdir.runpytest(*args)\n if quiet:\n assert \"run all\" not in result.stdout.str()\n else:\n assert \"rerun previous\" in result.stdout.str()\n\n def get_cached_last_failed(self, testdir):\n config = testdir.parseconfigure()\n return sorted(config.cache.get(\"cache/lastfailed\", {}))\n\n def test_cache_cumulative(self, testdir):\n \"\"\"\n Test workflow where user fixes errors gradually file by file using --lf.\n \"\"\"\n # 1. initial run\n test_bar = testdir.makepyfile(\n test_bar=\"\"\"\n def test_bar_1():\n pass\n def test_bar_2():\n assert 0\n \"\"\"\n )\n test_foo = testdir.makepyfile(\n test_foo=\"\"\"\n def test_foo_3():\n pass\n def test_foo_4():\n assert 0\n \"\"\"\n )\n testdir.runpytest()\n assert self.get_cached_last_failed(testdir) == [\n \"test_bar.py::test_bar_2\",\n \"test_foo.py::test_foo_4\",\n ]\n\n # 2. fix test_bar_2, run only test_bar.py\n testdir.makepyfile(\n test_bar=\"\"\"\n def test_bar_1():\n pass\n def test_bar_2():\n pass\n \"\"\"\n )\n result = testdir.runpytest(test_bar)\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n # ensure cache does not forget that test_foo_4 failed once before\n assert self.get_cached_last_failed(testdir) == [\"test_foo.py::test_foo_4\"]\n\n result = testdir.runpytest(\"--last-failed\")\n result.stdout.fnmatch_lines([\"*1 failed, 1 deselected*\"])\n assert self.get_cached_last_failed(testdir) == [\"test_foo.py::test_foo_4\"]\n\n # 3. fix test_foo_4, run only test_foo.py\n test_foo = testdir.makepyfile(\n test_foo=\"\"\"\n def test_foo_3():\n pass\n def test_foo_4():\n pass\n \"\"\"\n )\n result = testdir.runpytest(test_foo, \"--last-failed\")\n result.stdout.fnmatch_lines([\"*1 passed, 1 deselected*\"])\n assert self.get_cached_last_failed(testdir) == []\n\n result = testdir.runpytest(\"--last-failed\")\n result.stdout.fnmatch_lines([\"*4 passed*\"])\n assert self.get_cached_last_failed(testdir) == []\n\n def test_lastfailed_no_failures_behavior_all_passed(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_1():\n assert True\n def test_2():\n assert True\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n result = testdir.runpytest(\"--lf\", \"--lfnf\", \"all\")\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n result = testdir.runpytest(\"--lf\", \"--lfnf\", \"none\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items / 2 deselected\",\n \"run-last-failure: no previously failed tests, deselecting all items.\",\n \"* 2 deselected in *\",\n ]\n )\n assert result.ret == EXIT_NOTESTSCOLLECTED\n\n def test_lastfailed_no_failures_behavior_empty_cache(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_1():\n assert True\n def test_2():\n assert False\n \"\"\"\n )\n result = testdir.runpytest(\"--lf\", \"--cache-clear\")\n result.stdout.fnmatch_lines([\"*1 failed*1 passed*\"])\n result = testdir.runpytest(\"--lf\", \"--cache-clear\", \"--lfnf\", \"all\")\n result.stdout.fnmatch_lines([\"*1 failed*1 passed*\"])\n result = testdir.runpytest(\"--lf\", \"--cache-clear\", \"--lfnf\", \"none\")\n result.stdout.fnmatch_lines([\"*2 desel*\"])\n\n def test_lastfailed_skip_collection(self, testdir):\n \"\"\"\n Test --lf behavior regarding skipping collection of files that are not marked as\n failed in the cache (#5172).\n \"\"\"\n testdir.makepyfile(\n **{\n \"pkg1/test_1.py\": \"\"\"\n import pytest\n\n @pytest.mark.parametrize('i', range(3))\n def test_1(i): pass\n \"\"\",\n \"pkg2/test_2.py\": \"\"\"\n import pytest\n\n @pytest.mark.parametrize('i', range(5))\n def test_1(i):\n assert i not in (1, 3)\n \"\"\",\n }\n )\n # first run: collects 8 items (test_1: 3, test_2: 5)\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"collected 8 items\", \"*2 failed*6 passed*\"])\n # second run: collects only 5 items from test_2, because all tests from test_1 have passed\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 5 items / 3 deselected / 2 selected\",\n \"run-last-failure: rerun previous 2 failures (skipped 1 file)\",\n \"*2 failed*3 deselected*\",\n ]\n )\n\n # add another file and check if message is correct when skipping more than 1 file\n testdir.makepyfile(\n **{\n \"pkg1/test_3.py\": \"\"\"\n def test_3(): pass\n \"\"\"\n }\n )\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 5 items / 3 deselected / 2 selected\",\n \"run-last-failure: rerun previous 2 failures (skipped 2 files)\",\n \"*2 failed*3 deselected*\",\n ]\n )\n\n def test_lastfailed_with_known_failures_not_being_selected(self, testdir):\n testdir.makepyfile(\n **{\n \"pkg1/test_1.py\": \"\"\"def test_1(): assert 0\"\"\",\n \"pkg1/test_2.py\": \"\"\"def test_2(): pass\"\"\",\n }\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"collected 2 items\", \"* 1 failed, 1 passed in *\"])\n\n py.path.local(\"pkg1/test_1.py\").remove()\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 1 item\",\n \"run-last-failure: 1 known failures not in selected tests\",\n \"* 1 passed in *\",\n ]\n )\n\n # Recreate file with known failure.\n testdir.makepyfile(**{\"pkg1/test_1.py\": \"\"\"def test_1(): assert 0\"\"\"})\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 1 item\",\n \"run-last-failure: rerun previous 1 failure (skipped 1 file)\",\n \"* 1 failed in *\",\n ]\n )\n\n # Remove/rename test.\n testdir.makepyfile(**{\"pkg1/test_1.py\": \"\"\"def test_renamed(): assert 0\"\"\"})\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 1 item\",\n \"run-last-failure: 1 known failures not in selected tests (skipped 1 file)\",\n \"* 1 failed in *\",\n ]\n )\n\n\nclass TestNewFirst(object):\n def test_newfirst_usecase(self, testdir):\n testdir.makepyfile(\n **{\n \"test_1/test_1.py\": \"\"\"\n def test_1(): assert 1\n def test_2(): assert 1\n def test_3(): assert 1\n \"\"\",\n \"test_2/test_2.py\": \"\"\"\n def test_1(): assert 1\n def test_2(): assert 1\n def test_3(): assert 1\n \"\"\",\n }\n )\n\n testdir.tmpdir.join(\"test_1/test_1.py\").setmtime(1)\n\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n [\n \"*test_1/test_1.py::test_1 PASSED*\",\n \"*test_1/test_1.py::test_2 PASSED*\",\n \"*test_1/test_1.py::test_3 PASSED*\",\n \"*test_2/test_2.py::test_1 PASSED*\",\n \"*test_2/test_2.py::test_2 PASSED*\",\n \"*test_2/test_2.py::test_3 PASSED*\",\n ]\n )\n\n result = testdir.runpytest(\"-v\", \"--nf\")\n\n result.stdout.fnmatch_lines(\n [\n \"*test_2/test_2.py::test_1 PASSED*\",\n \"*test_2/test_2.py::test_2 PASSED*\",\n \"*test_2/test_2.py::test_3 PASSED*\",\n \"*test_1/test_1.py::test_1 PASSED*\",\n \"*test_1/test_1.py::test_2 PASSED*\",\n \"*test_1/test_1.py::test_3 PASSED*\",\n ]\n )\n\n testdir.tmpdir.join(\"test_1/test_1.py\").write(\n \"def test_1(): assert 1\\n\"\n \"def test_2(): assert 1\\n\"\n \"def test_3(): assert 1\\n\"\n \"def test_4(): assert 1\\n\"\n )\n testdir.tmpdir.join(\"test_1/test_1.py\").setmtime(1)\n\n result = testdir.runpytest(\"-v\", \"--nf\")\n\n result.stdout.fnmatch_lines(\n [\n \"*test_1/test_1.py::test_4 PASSED*\",\n \"*test_2/test_2.py::test_1 PASSED*\",\n \"*test_2/test_2.py::test_2 PASSED*\",\n \"*test_2/test_2.py::test_3 PASSED*\",\n \"*test_1/test_1.py::test_1 PASSED*\",\n \"*test_1/test_1.py::test_2 PASSED*\",\n \"*test_1/test_1.py::test_3 PASSED*\",\n ]\n )\n\n def test_newfirst_parametrize(self, testdir):\n testdir.makepyfile(\n **{\n \"test_1/test_1.py\": \"\"\"\n import pytest\n @pytest.mark.parametrize('num', [1, 2])\n def test_1(num): assert num\n \"\"\",\n \"test_2/test_2.py\": \"\"\"\n import pytest\n @pytest.mark.parametrize('num', [1, 2])\n def test_1(num): assert num\n \"\"\",\n }\n )\n\n testdir.tmpdir.join(\"test_1/test_1.py\").setmtime(1)\n\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n [\n \"*test_1/test_1.py::test_1[1*\",\n \"*test_1/test_1.py::test_1[2*\",\n \"*test_2/test_2.py::test_1[1*\",\n \"*test_2/test_2.py::test_1[2*\",\n ]\n )\n\n result = testdir.runpytest(\"-v\", \"--nf\")\n\n result.stdout.fnmatch_lines(\n [\n \"*test_2/test_2.py::test_1[1*\",\n \"*test_2/test_2.py::test_1[2*\",\n \"*test_1/test_1.py::test_1[1*\",\n \"*test_1/test_1.py::test_1[2*\",\n ]\n )\n\n testdir.tmpdir.join(\"test_1/test_1.py\").write(\n \"import pytest\\n\"\n \"@pytest.mark.parametrize('num', [1, 2, 3])\\n\"\n \"def test_1(num): assert num\\n\"\n )\n testdir.tmpdir.join(\"test_1/test_1.py\").setmtime(1)\n\n result = testdir.runpytest(\"-v\", \"--nf\")\n\n result.stdout.fnmatch_lines(\n [\n \"*test_1/test_1.py::test_1[3*\",\n \"*test_2/test_2.py::test_1[1*\",\n \"*test_2/test_2.py::test_1[2*\",\n \"*test_1/test_1.py::test_1[1*\",\n \"*test_1/test_1.py::test_1[2*\",\n ]\n )\n\n\nclass TestReadme(object):\n def check_readme(self, testdir):\n config = testdir.parseconfigure()\n readme = config.cache._cachedir.joinpath(\"README.md\")\n return readme.is_file()\n\n def test_readme_passed(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_always_passes():\n assert 1\n \"\"\"\n )\n testdir.runpytest()\n assert self.check_readme(testdir) is True\n\n def test_readme_failed(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_always_fails():\n assert 0\n \"\"\"\n )\n testdir.runpytest()\n assert self.check_readme(testdir) is True\n\n\ndef test_gitignore(testdir):\n \"\"\"Ensure we automatically create .gitignore file in the pytest_cache directory (#3286).\"\"\"\n from _pytest.cacheprovider import Cache\n\n config = testdir.parseconfig()\n cache = Cache.for_config(config)\n cache.set(\"foo\", \"bar\")\n msg = \"# Created by pytest automatically.\\n*\"\n gitignore_path = cache._cachedir.joinpath(\".gitignore\")\n assert gitignore_path.read_text(encoding=\"UTF-8\") == msg\n\n # Does not overwrite existing/custom one.\n gitignore_path.write_text(u\"custom\")\n cache.set(\"something\", \"else\")\n assert gitignore_path.read_text(encoding=\"UTF-8\") == \"custom\"\n\n\ndef test_does_not_create_boilerplate_in_existing_dirs(testdir):\n from _pytest.cacheprovider import Cache\n\n testdir.makeini(\n \"\"\"\n [pytest]\n cache_dir = .\n \"\"\"\n )\n config = testdir.parseconfig()\n cache = Cache.for_config(config)\n cache.set(\"foo\", \"bar\")\n\n assert os.path.isdir(\"v\") # cache contents\n assert not os.path.exists(\".gitignore\")\n assert not os.path.exists(\"README.md\")\n\n\ndef test_cachedir_tag(testdir):\n \"\"\"Ensure we automatically create CACHEDIR.TAG file in the pytest_cache directory (#4278).\"\"\"\n from _pytest.cacheprovider import Cache\n from _pytest.cacheprovider import CACHEDIR_TAG_CONTENT\n\n config = testdir.parseconfig()\n cache = Cache.for_config(config)\n cache.set(\"foo\", \"bar\")\n cachedir_tag_path = cache._cachedir.joinpath(\"CACHEDIR.TAG\")\n assert cachedir_tag_path.read_bytes() == CACHEDIR_TAG_CONTENT\n"},{"col":4,"comment":"null","endLoc":243,"header":"def test_minus_x_import_error(self, testdir)","id":4001,"name":"test_minus_x_import_error","nodeType":"Function","startLoc":237,"text":"def test_minus_x_import_error(self, testdir):\n testdir.makepyfile(__init__=\"\")\n testdir.makepyfile(test_one=\"xxxx\", test_two=\"yyyy\")\n reprec = testdir.inline_run(\"-x\", testdir.tmpdir)\n finished = reprec.getreports(\"pytest_collectreport\")\n colfail = [x for x in finished if x.failed]\n assert len(colfail) == 1"},{"className":"TestNewAPI","col":0,"comment":"null","endLoc":150,"id":4002,"nodeType":"Class","startLoc":19,"text":"class TestNewAPI(object):\n def test_config_cache_makedir(self, testdir):\n testdir.makeini(\"[pytest]\")\n config = testdir.parseconfigure()\n with pytest.raises(ValueError):\n config.cache.makedir(\"key/name\")\n\n p = config.cache.makedir(\"name\")\n assert p.check()\n\n def test_config_cache_dataerror(self, testdir):\n testdir.makeini(\"[pytest]\")\n config = testdir.parseconfigure()\n cache = config.cache\n pytest.raises(TypeError, lambda: cache.set(\"key/name\", cache))\n config.cache.set(\"key/name\", 0)\n config.cache._getvaluepath(\"key/name\").write_bytes(b\"123invalid\")\n val = config.cache.get(\"key/name\", -2)\n assert val == -2\n\n @pytest.mark.filterwarnings(\"default\")\n def test_cache_writefail_cachfile_silent(self, testdir):\n testdir.makeini(\"[pytest]\")\n testdir.tmpdir.join(\".pytest_cache\").write(\"gone wrong\")\n config = testdir.parseconfigure()\n cache = config.cache\n cache.set(\"test/broken\", [])\n\n @pytest.mark.skipif(sys.platform.startswith(\"win\"), reason=\"no chmod on windows\")\n @pytest.mark.filterwarnings(\n \"ignore:could not create cache path:pytest.PytestWarning\"\n )\n def test_cache_writefail_permissions(self, testdir):\n testdir.makeini(\"[pytest]\")\n testdir.tmpdir.ensure_dir(\".pytest_cache\").chmod(0)\n config = testdir.parseconfigure()\n cache = config.cache\n cache.set(\"test/broken\", [])\n\n @pytest.mark.skipif(sys.platform.startswith(\"win\"), reason=\"no chmod on windows\")\n @pytest.mark.filterwarnings(\"default\")\n def test_cache_failure_warns(self, testdir):\n testdir.tmpdir.ensure_dir(\".pytest_cache\").chmod(0)\n testdir.makepyfile(\n \"\"\"\n def test_error():\n raise Exception\n\n \"\"\"\n )\n result = testdir.runpytest(\"-rw\")\n assert result.ret == 1\n # warnings from nodeids, lastfailed, and stepwise\n result.stdout.fnmatch_lines([\"*could not create cache path*\", \"*3 warnings*\"])\n\n def test_config_cache(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_configure(config):\n # see that we get cache information early on\n assert hasattr(config, \"cache\")\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_session(pytestconfig):\n assert hasattr(pytestconfig, \"cache\")\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_cachefuncarg(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_cachefuncarg(cache):\n val = cache.get(\"some/thing\", None)\n assert val is None\n cache.set(\"some/thing\", [1])\n pytest.raises(TypeError, lambda: cache.get(\"some/thing\"))\n val = cache.get(\"some/thing\", [])\n assert val == [1]\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_custom_rel_cache_dir(self, testdir):\n rel_cache_dir = os.path.join(\"custom_cache_dir\", \"subdir\")\n testdir.makeini(\n \"\"\"\n [pytest]\n cache_dir = {cache_dir}\n \"\"\".format(\n cache_dir=rel_cache_dir\n )\n )\n testdir.makepyfile(test_errored=\"def test_error():\\n assert False\")\n testdir.runpytest()\n assert testdir.tmpdir.join(rel_cache_dir).isdir()\n\n def test_custom_abs_cache_dir(self, testdir, tmpdir_factory):\n tmp = str(tmpdir_factory.mktemp(\"tmp\"))\n abs_cache_dir = os.path.join(tmp, \"custom_cache_dir\")\n testdir.makeini(\n \"\"\"\n [pytest]\n cache_dir = {cache_dir}\n \"\"\".format(\n cache_dir=abs_cache_dir\n )\n )\n testdir.makepyfile(test_errored=\"def test_error():\\n assert False\")\n testdir.runpytest()\n assert py.path.local(abs_cache_dir).isdir()\n\n def test_custom_cache_dir_with_env_var(self, testdir, monkeypatch):\n monkeypatch.setenv(\"env_var\", \"custom_cache_dir\")\n testdir.makeini(\n \"\"\"\n [pytest]\n cache_dir = {cache_dir}\n \"\"\".format(\n cache_dir=\"$env_var\"\n )\n )\n testdir.makepyfile(test_errored=\"def test_error():\\n assert False\")\n testdir.runpytest()\n assert testdir.tmpdir.join(\"custom_cache_dir\").isdir()"},{"className":"TestReport","col":0,"comment":" Basic test report object (also used for setup and teardown calls if\n they fail).\n ","endLoc":386,"id":4003,"nodeType":"Class","startLoc":281,"text":"class TestReport(BaseReport):\n \"\"\" Basic test report object (also used for setup and teardown calls if\n they fail).\n \"\"\"\n\n __test__ = False\n\n def __init__(\n self,\n nodeid,\n location,\n keywords,\n outcome,\n longrepr,\n when,\n sections=(),\n duration=0,\n user_properties=None,\n **extra\n ):\n #: normalized collection node id\n self.nodeid = nodeid\n\n #: a (filesystempath, lineno, domaininfo) tuple indicating the\n #: actual location of a test item - it might be different from the\n #: collected one e.g. if a method is inherited from a different module.\n self.location = location\n\n #: a name -> value dictionary containing all keywords and\n #: markers associated with a test invocation.\n self.keywords = keywords\n\n #: test outcome, always one of \"passed\", \"failed\", \"skipped\".\n self.outcome = outcome\n\n #: None or a failure representation.\n self.longrepr = longrepr\n\n #: one of 'setup', 'call', 'teardown' to indicate runtest phase.\n self.when = when\n\n #: user properties is a list of tuples (name, value) that holds user\n #: defined properties of the test\n self.user_properties = list(user_properties or [])\n\n #: list of pairs ``(str, str)`` of extra information which needs to\n #: marshallable. Used by pytest to add captured text\n #: from ``stdout`` and ``stderr``, but may be used by other plugins\n #: to add arbitrary information to reports.\n self.sections = list(sections)\n\n #: time it took to run just the test\n self.duration = duration\n\n self.__dict__.update(extra)\n\n def __repr__(self):\n return \"<%s %r when=%r outcome=%r>\" % (\n self.__class__.__name__,\n self.nodeid,\n self.when,\n self.outcome,\n )\n\n @classmethod\n def from_item_and_call(cls, item, call):\n \"\"\"\n Factory method to create and fill a TestReport with standard item and call info.\n \"\"\"\n when = call.when\n duration = call.stop - call.start\n keywords = {x: 1 for x in item.keywords}\n excinfo = call.excinfo\n sections = []\n if not call.excinfo:\n outcome = \"passed\"\n longrepr = None\n else:\n if not isinstance(excinfo, ExceptionInfo):\n outcome = \"failed\"\n longrepr = excinfo\n elif excinfo.errisinstance(skip.Exception):\n outcome = \"skipped\"\n r = excinfo._getreprcrash()\n longrepr = (str(r.path), r.lineno, r.message)\n else:\n outcome = \"failed\"\n if call.when == \"call\":\n longrepr = item.repr_failure(excinfo)\n else: # exception in setup or teardown\n longrepr = item._repr_failure_py(\n excinfo, style=item.config.getoption(\"tbstyle\", \"auto\")\n )\n for rwhen, key, content in item._report_sections:\n sections.append((\"Captured %s %s\" % (key, rwhen), content))\n return cls(\n item.nodeid,\n item.location,\n keywords,\n outcome,\n longrepr,\n when,\n sections,\n duration,\n user_properties=item.user_properties,\n )"},{"col":4,"comment":"null","endLoc":335,"header":"def __init__(\n self,\n nodeid,\n location,\n keywords,\n outcome,\n longrepr,\n when,\n sections=(),\n duration=0,\n user_properties=None,\n **extra\n )","id":4004,"name":"__init__","nodeType":"Function","startLoc":288,"text":"def __init__(\n self,\n nodeid,\n location,\n keywords,\n outcome,\n longrepr,\n when,\n sections=(),\n duration=0,\n user_properties=None,\n **extra\n ):\n #: normalized collection node id\n self.nodeid = nodeid\n\n #: a (filesystempath, lineno, domaininfo) tuple indicating the\n #: actual location of a test item - it might be different from the\n #: collected one e.g. if a method is inherited from a different module.\n self.location = location\n\n #: a name -> value dictionary containing all keywords and\n #: markers associated with a test invocation.\n self.keywords = keywords\n\n #: test outcome, always one of \"passed\", \"failed\", \"skipped\".\n self.outcome = outcome\n\n #: None or a failure representation.\n self.longrepr = longrepr\n\n #: one of 'setup', 'call', 'teardown' to indicate runtest phase.\n self.when = when\n\n #: user properties is a list of tuples (name, value) that holds user\n #: defined properties of the test\n self.user_properties = list(user_properties or [])\n\n #: list of pairs ``(str, str)`` of extra information which needs to\n #: marshallable. Used by pytest to add captured text\n #: from ``stdout`` and ``stderr``, but may be used by other plugins\n #: to add arbitrary information to reports.\n self.sections = list(sections)\n\n #: time it took to run just the test\n self.duration = duration\n\n self.__dict__.update(extra)"},{"col":4,"comment":"null","endLoc":103,"header":"def test_pdb_on_fail(self, testdir, pdblist)","id":4005,"name":"test_pdb_on_fail","nodeType":"Function","startLoc":92,"text":"def test_pdb_on_fail(self, testdir, pdblist):\n rep = runpdb_and_get_report(\n testdir,\n \"\"\"\n def test_func():\n assert 0\n \"\"\",\n )\n assert rep.failed\n assert len(pdblist) == 1\n tb = _pytest._code.Traceback(pdblist[0][0])\n assert tb[-1].name == \"test_func\""},{"col":0,"comment":"null","endLoc":31,"header":"def runpdb_and_get_report(testdir, source)","id":4006,"name":"runpdb_and_get_report","nodeType":"Function","startLoc":26,"text":"def runpdb_and_get_report(testdir, source):\n p = testdir.makepyfile(source)\n result = testdir.runpytest_inprocess(\"--pdb\", p)\n reports = result.reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 3, reports # setup/call/teardown\n return reports[1]"},{"col":4,"comment":"null","endLoc":27,"header":"def test_config_cache_makedir(self, testdir)","id":4007,"name":"test_config_cache_makedir","nodeType":"Function","startLoc":20,"text":"def test_config_cache_makedir(self, testdir):\n testdir.makeini(\"[pytest]\")\n config = testdir.parseconfigure()\n with pytest.raises(ValueError):\n config.cache.makedir(\"key/name\")\n\n p = config.cache.makedir(\"name\")\n assert p.check()"},{"col":4,"comment":"null","endLoc":251,"header":"def test_minus_x_overridden_by_maxfail(self, testdir)","id":4008,"name":"test_minus_x_overridden_by_maxfail","nodeType":"Function","startLoc":245,"text":"def test_minus_x_overridden_by_maxfail(self, testdir):\n testdir.makepyfile(__init__=\"\")\n testdir.makepyfile(test_one=\"xxxx\", test_two=\"yyyy\", test_third=\"zzz\")\n reprec = testdir.inline_run(\"-x\", \"--maxfail=2\", testdir.tmpdir)\n finished = reprec.getreports(\"pytest_collectreport\")\n colfail = [x for x in finished if x.failed]\n assert len(colfail) == 2"},{"col":4,"comment":"null","endLoc":592,"header":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_teardown(self, item)","id":4009,"name":"pytest_runtest_teardown","nodeType":"Function","startLoc":589,"text":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_teardown(self, item):\n with self._runtest_for(item, \"teardown\"):\n yield"},{"col":4,"comment":"null","endLoc":73,"header":"def test_argument_processopt(self)","id":4010,"name":"test_argument_processopt","nodeType":"Function","startLoc":67,"text":"def test_argument_processopt(self):\n argument = parseopt.Argument(\"-t\", type=int)\n argument.default = 42\n argument.dest = \"abc\"\n res = argument.attrs()\n assert res[\"default\"] == 42\n assert res[\"dest\"] == \"abc\""},{"col":0,"comment":"null","endLoc":259,"header":"def test_plugin_specify(testdir)","id":4011,"name":"test_plugin_specify","nodeType":"Function","startLoc":254,"text":"def test_plugin_specify(testdir):\n with pytest.raises(ImportError):\n testdir.parseconfig(\"-p\", \"nqweotexistent\")\n # pytest.raises(ImportError,\n # \"config.do_configure(config)\"\n # )"},{"col":4,"comment":"null","endLoc":37,"header":"def test_config_cache_dataerror(self, testdir)","id":4012,"name":"test_config_cache_dataerror","nodeType":"Function","startLoc":29,"text":"def test_config_cache_dataerror(self, testdir):\n testdir.makeini(\"[pytest]\")\n config = testdir.parseconfigure()\n cache = config.cache\n pytest.raises(TypeError, lambda: cache.set(\"key/name\", cache))\n config.cache.set(\"key/name\", 0)\n config.cache._getvaluepath(\"key/name\").write_bytes(b\"123invalid\")\n val = config.cache.get(\"key/name\", -2)\n assert val == -2"},{"col":4,"comment":"null","endLoc":116,"header":"def test_pdb_on_xfail(self, testdir, pdblist)","id":4013,"name":"test_pdb_on_xfail","nodeType":"Function","startLoc":105,"text":"def test_pdb_on_xfail(self, testdir, pdblist):\n rep = runpdb_and_get_report(\n testdir,\n \"\"\"\n import pytest\n @pytest.mark.xfail\n def test_func():\n assert 0\n \"\"\",\n )\n assert \"xfail\" in rep.keywords\n assert not pdblist"},{"col":4,"comment":"null","endLoc":128,"header":"def test_pdb_on_skip(self, testdir, pdblist)","id":4014,"name":"test_pdb_on_skip","nodeType":"Function","startLoc":118,"text":"def test_pdb_on_skip(self, testdir, pdblist):\n rep = runpdb_and_get_report(\n testdir,\n \"\"\"\n import pytest\n def test_func():\n pytest.skip(\"hello\")\n \"\"\",\n )\n assert rep.skipped\n assert len(pdblist) == 0"},{"col":33,"endLoc":33,"id":4015,"nodeType":"Lambda","startLoc":33,"text":"lambda: cache.set(\"key/name\", cache)"},{"col":4,"comment":"null","endLoc":140,"header":"def test_pdb_on_BdbQuit(self, testdir, pdblist)","id":4016,"name":"test_pdb_on_BdbQuit","nodeType":"Function","startLoc":130,"text":"def test_pdb_on_BdbQuit(self, testdir, pdblist):\n rep = runpdb_and_get_report(\n testdir,\n \"\"\"\n import bdb\n def test_func():\n raise bdb.BdbQuit\n \"\"\",\n )\n assert rep.failed\n assert len(pdblist) == 0"},{"col":4,"comment":"null","endLoc":241,"header":"def attrs(self)","id":4017,"name":"attrs","nodeType":"Function","startLoc":226,"text":"def attrs(self):\n # update any attributes set by processopt\n attrs = \"default dest help\".split()\n if self.dest:\n attrs.append(self.dest)\n for attr in attrs:\n try:\n self._attrs[attr] = getattr(self, attr)\n except AttributeError:\n pass\n if self._attrs.get(\"help\"):\n a = self._attrs[\"help\"]\n a = a.replace(\"%default\", \"%(default)s\")\n # a = a.replace('%prog', '%(prog)s')\n self._attrs[\"help\"] = a\n return self._attrs"},{"col":4,"comment":"null","endLoc":151,"header":"def test_pdb_on_KeyboardInterrupt(self, testdir, pdblist)","id":4018,"name":"test_pdb_on_KeyboardInterrupt","nodeType":"Function","startLoc":142,"text":"def test_pdb_on_KeyboardInterrupt(self, testdir, pdblist):\n rep = runpdb_and_get_report(\n testdir,\n \"\"\"\n def test_func():\n raise KeyboardInterrupt\n \"\"\",\n )\n assert rep.failed\n assert len(pdblist) == 1"},{"col":0,"comment":"null","endLoc":266,"header":"def test_plugin_already_exists(testdir)","id":4019,"name":"test_plugin_already_exists","nodeType":"Function","startLoc":262,"text":"def test_plugin_already_exists(testdir):\n config = testdir.parseconfig(\"-p\", \"terminal\")\n assert config.option.plugins == [\"terminal\"]\n config._do_configure()\n config._ensure_unconfigure()"},{"col":4,"comment":"null","endLoc":45,"header":"@pytest.mark.filterwarnings(\"default\")\n def test_cache_writefail_cachfile_silent(self, testdir)","id":4020,"name":"test_cache_writefail_cachfile_silent","nodeType":"Function","startLoc":39,"text":"@pytest.mark.filterwarnings(\"default\")\n def test_cache_writefail_cachfile_silent(self, testdir):\n testdir.makeini(\"[pytest]\")\n testdir.tmpdir.join(\".pytest_cache\").write(\"gone wrong\")\n config = testdir.parseconfigure()\n cache = config.cache\n cache.set(\"test/broken\", [])"},{"col":4,"comment":"null","endLoc":159,"header":"@staticmethod\n def flush(child)","id":4021,"name":"flush","nodeType":"Function","startLoc":153,"text":"@staticmethod\n def flush(child):\n if child.isalive():\n # Read if the test has not (e.g. test_pdb_unittest_skip).\n child.read()\n child.wait()\n assert not child.isalive()"},{"col":4,"comment":"null","endLoc":179,"header":"def test_pdb_unittest_postmortem(self, testdir)","id":4022,"name":"test_pdb_unittest_postmortem","nodeType":"Function","startLoc":161,"text":"def test_pdb_unittest_postmortem(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import unittest\n class Blub(unittest.TestCase):\n def tearDown(self):\n self.filename = None\n def test_false(self):\n self.filename = 'debug' + '.me'\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdb %s\" % p1)\n child.expect(\"Pdb\")\n child.sendline(\"p self.filename\")\n child.sendeof()\n rest = child.read().decode(\"utf8\")\n assert \"debug.me\" in rest\n self.flush(child)"},{"col":0,"comment":"null","endLoc":277,"header":"def test_exclude(testdir)","id":4023,"name":"test_exclude","nodeType":"Function","startLoc":269,"text":"def test_exclude(testdir):\n hellodir = testdir.mkdir(\"hello\")\n hellodir.join(\"test_hello.py\").write(\"x y syntaxerror\")\n hello2dir = testdir.mkdir(\"hello2\")\n hello2dir.join(\"test_hello2.py\").write(\"x y syntaxerror\")\n testdir.makepyfile(test_ok=\"def test_pass(): pass\")\n result = testdir.runpytest(\"--ignore=hello\", \"--ignore=hello2\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":4,"comment":"null","endLoc":599,"header":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_logstart(self)","id":4024,"name":"pytest_runtest_logstart","nodeType":"Function","startLoc":594,"text":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_logstart(self):\n if self.log_cli_handler:\n self.log_cli_handler.reset()\n with self._runtest_for(None, \"start\"):\n yield"},{"col":4,"comment":"null","endLoc":78,"header":"def test_group_add_and_get(self, parser)","id":4025,"name":"test_group_add_and_get","nodeType":"Function","startLoc":75,"text":"def test_group_add_and_get(self, parser):\n group = parser.getgroup(\"hello\", description=\"desc\")\n assert group.name == \"hello\"\n assert group.description == \"desc\""},{"col":4,"comment":"null","endLoc":56,"header":"@pytest.mark.skipif(sys.platform.startswith(\"win\"), reason=\"no chmod on windows\")\n @pytest.mark.filterwarnings(\n \"ignore","id":4026,"name":"test_cache_writefail_permissions","nodeType":"Function","startLoc":47,"text":"@pytest.mark.skipif(sys.platform.startswith(\"win\"), reason=\"no chmod on windows\")\n @pytest.mark.filterwarnings(\n \"ignore:could not create cache path:pytest.PytestWarning\"\n )\n def test_cache_writefail_permissions(self, testdir):\n testdir.makeini(\"[pytest]\")\n testdir.tmpdir.ensure_dir(\".pytest_cache\").chmod(0)\n config = testdir.parseconfigure()\n cache = config.cache\n cache.set(\"test/broken\", [])"},{"col":4,"comment":"null","endLoc":85,"header":"def test_getgroup_simple(self, parser)","id":4027,"name":"test_getgroup_simple","nodeType":"Function","startLoc":80,"text":"def test_getgroup_simple(self, parser):\n group = parser.getgroup(\"hello\", description=\"desc\")\n assert group.name == \"hello\"\n assert group.description == \"desc\"\n group2 = parser.getgroup(\"hello\")\n assert group2 is group"},{"col":4,"comment":"Test for issue #2137","endLoc":196,"header":"def test_pdb_unittest_skip(self, testdir)","id":4028,"name":"test_pdb_unittest_skip","nodeType":"Function","startLoc":181,"text":"def test_pdb_unittest_skip(self, testdir):\n \"\"\"Test for issue #2137\"\"\"\n p1 = testdir.makepyfile(\n \"\"\"\n import unittest\n @unittest.skipIf(True, 'Skipping also with pdb active')\n class MyTestCase(unittest.TestCase):\n def test_one(self):\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(\"-rs --pdb %s\" % p1)\n child.expect(\"Skipping also with pdb active\")\n child.expect(\"1 skipped in\")\n child.sendeof()\n self.flush(child)"},{"col":4,"comment":"null","endLoc":93,"header":"def test_group_ordering(self, parser)","id":4029,"name":"test_group_ordering","nodeType":"Function","startLoc":87,"text":"def test_group_ordering(self, parser):\n parser.getgroup(\"1\")\n parser.getgroup(\"2\")\n parser.getgroup(\"3\", after=\"1\")\n groups = parser._groups\n groups_names = [x.name for x in groups]\n assert groups_names == list(\"132\")"},{"col":0,"comment":"null","endLoc":292,"header":"def test_exclude_glob(testdir)","id":4030,"name":"test_exclude_glob","nodeType":"Function","startLoc":280,"text":"def test_exclude_glob(testdir):\n hellodir = testdir.mkdir(\"hello\")\n hellodir.join(\"test_hello.py\").write(\"x y syntaxerror\")\n hello2dir = testdir.mkdir(\"hello2\")\n hello2dir.join(\"test_hello2.py\").write(\"x y syntaxerror\")\n hello3dir = testdir.mkdir(\"hallo3\")\n hello3dir.join(\"test_hello3.py\").write(\"x y syntaxerror\")\n subdir = testdir.mkdir(\"sub\")\n subdir.join(\"test_hello4.py\").write(\"x y syntaxerror\")\n testdir.makepyfile(test_ok=\"def test_pass(): pass\")\n result = testdir.runpytest(\"--ignore-glob=*h[ea]llo*\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":4,"comment":"null","endLoc":604,"header":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_logfinish(self)","id":4031,"name":"pytest_runtest_logfinish","nodeType":"Function","startLoc":601,"text":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_logfinish(self):\n with self._runtest_for(None, \"finish\"):\n yield"},{"col":4,"comment":"null","endLoc":225,"header":"def test_pdb_print_captured_stdout_and_stderr(self, testdir)","id":4032,"name":"test_pdb_print_captured_stdout_and_stderr","nodeType":"Function","startLoc":198,"text":"def test_pdb_print_captured_stdout_and_stderr(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1():\n import sys\n sys.stderr.write(\"get\\\\x20rekt\")\n print(\"get\\\\x20rekt\")\n assert False\n\n def test_not_called_due_to_quit():\n pass\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdb %s\" % p1)\n child.expect(\"captured stdout\")\n child.expect(\"get rekt\")\n child.expect(\"captured stderr\")\n child.expect(\"get rekt\")\n child.expect(\"traceback\")\n child.expect(\"def test_1\")\n child.expect(\"Pdb\")\n child.sendeof()\n rest = child.read().decode(\"utf8\")\n assert \"Exit: Quitting debugger\" in rest\n assert \"= 1 failed in\" in rest\n assert \"def test_1\" not in rest\n assert \"get rekt\" not in rest\n self.flush(child)"},{"col":4,"comment":"null","endLoc":609,"header":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_logreport(self)","id":4033,"name":"pytest_runtest_logreport","nodeType":"Function","startLoc":606,"text":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_logreport(self):\n with self._runtest_for(None, \"logreport\"):\n yield"},{"col":4,"comment":"Show deprecation warnings by default, even if user has customized the warnings filters (#4013).","endLoc":523,"header":"@pytest.mark.parametrize(\"customize_filters\", [True, False])\n def test_shown_by_default(self, testdir, customize_filters)","id":4034,"name":"test_shown_by_default","nodeType":"Function","startLoc":503,"text":"@pytest.mark.parametrize(\"customize_filters\", [True, False])\n def test_shown_by_default(self, testdir, customize_filters):\n \"\"\"Show deprecation warnings by default, even if user has customized the warnings filters (#4013).\"\"\"\n self.create_file(testdir)\n if customize_filters:\n testdir.makeini(\n \"\"\"\n [pytest]\n filterwarnings =\n once::UserWarning\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines(\n [\n \"*== %s ==*\" % WARNINGS_SUMMARY_HEADER,\n \"*test_shown_by_default.py:3: DeprecationWarning: collection\",\n \"*test_shown_by_default.py:7: PendingDeprecationWarning: test run\",\n \"* 1 passed, 2 warnings*\",\n ]\n )"},{"col":4,"comment":"\n This was originally the serialize_report() function from xdist (ca03269).\n\n Factory method that returns either a TestReport or CollectReport, depending on the calling\n class. It's the callers responsibility to know which class to pass here.\n\n Experimental method.\n ","endLoc":266,"header":"@classmethod\n def _from_json(cls, reportdict)","id":4035,"name":"_from_json","nodeType":"Function","startLoc":208,"text":"@classmethod\n def _from_json(cls, reportdict):\n \"\"\"\n This was originally the serialize_report() function from xdist (ca03269).\n\n Factory method that returns either a TestReport or CollectReport, depending on the calling\n class. It's the callers responsibility to know which class to pass here.\n\n Experimental method.\n \"\"\"\n if reportdict[\"longrepr\"]:\n if (\n \"reprcrash\" in reportdict[\"longrepr\"]\n and \"reprtraceback\" in reportdict[\"longrepr\"]\n ):\n\n reprtraceback = reportdict[\"longrepr\"][\"reprtraceback\"]\n reprcrash = reportdict[\"longrepr\"][\"reprcrash\"]\n\n unserialized_entries = []\n reprentry = None\n for entry_data in reprtraceback[\"reprentries\"]:\n data = entry_data[\"data\"]\n entry_type = entry_data[\"type\"]\n if entry_type == \"ReprEntry\":\n reprfuncargs = None\n reprfileloc = None\n reprlocals = None\n if data[\"reprfuncargs\"]:\n reprfuncargs = ReprFuncArgs(**data[\"reprfuncargs\"])\n if data[\"reprfileloc\"]:\n reprfileloc = ReprFileLocation(**data[\"reprfileloc\"])\n if data[\"reprlocals\"]:\n reprlocals = ReprLocals(data[\"reprlocals\"][\"lines\"])\n\n reprentry = ReprEntry(\n lines=data[\"lines\"],\n reprfuncargs=reprfuncargs,\n reprlocals=reprlocals,\n filelocrepr=reprfileloc,\n style=data[\"style\"],\n )\n elif entry_type == \"ReprEntryNative\":\n reprentry = ReprEntryNative(data[\"lines\"])\n else:\n _report_unserialization_failure(entry_type, cls, reportdict)\n unserialized_entries.append(reprentry)\n reprtraceback[\"reprentries\"] = unserialized_entries\n\n exception_info = ReprExceptionInfo(\n reprtraceback=ReprTraceback(**reprtraceback),\n reprcrash=ReprFileLocation(**reprcrash),\n )\n\n for section in reportdict[\"longrepr\"][\"sections\"]:\n exception_info.addsection(*section)\n reportdict[\"longrepr\"] = exception_info\n\n return cls(**reportdict)"},{"col":4,"comment":"null","endLoc":627,"header":"@pytest.hookimpl(hookwrapper=True, tryfirst=True)\n def pytest_sessionfinish(self)","id":4036,"name":"pytest_sessionfinish","nodeType":"Function","startLoc":611,"text":"@pytest.hookimpl(hookwrapper=True, tryfirst=True)\n def pytest_sessionfinish(self):\n with self.live_logs_context():\n if self.log_cli_handler:\n self.log_cli_handler.set_when(\"sessionfinish\")\n if self.log_file_handler is not None:\n try:\n with catching_logs(\n self.log_file_handler, level=self.log_file_level\n ):\n yield\n finally:\n # Close the FileHandler explicitly.\n # (logging.shutdown might have lost the weakref?!)\n self.log_file_handler.close()\n else:\n yield"},{"col":0,"comment":"null","endLoc":320,"header":"def test_deselect(testdir)","id":4037,"name":"test_deselect","nodeType":"Function","startLoc":295,"text":"def test_deselect(testdir):\n testdir.makepyfile(\n test_a=\"\"\"\n import pytest\n\n def test_a1(): pass\n\n @pytest.mark.parametrize('b', range(3))\n def test_a2(b): pass\n\n class TestClass:\n def test_c1(self): pass\n\n def test_c2(self): pass\n \"\"\"\n )\n result = testdir.runpytest(\n \"-v\",\n \"--deselect=test_a.py::test_a2[1]\",\n \"--deselect=test_a.py::test_a2[2]\",\n \"--deselect=test_a.py::TestClass::test_c1\",\n )\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*3 passed, 3 deselected*\"])\n for line in result.stdout.lines:\n assert not line.startswith((\"test_a.py::test_a2[1]\", \"test_a.py::test_a2[2]\"))"},{"col":0,"comment":"null","endLoc":338,"header":"def test_sessionfinish_with_start(testdir)","id":4038,"name":"test_sessionfinish_with_start","nodeType":"Function","startLoc":323,"text":"def test_sessionfinish_with_start(testdir):\n testdir.makeconftest(\n \"\"\"\n import os\n values = []\n def pytest_sessionstart():\n values.append(os.getcwd())\n os.chdir(\"..\")\n\n def pytest_sessionfinish():\n assert values[0] == os.getcwd()\n\n \"\"\"\n )\n res = testdir.runpytest(\"--collect-only\")\n assert res.ret == EXIT_NOTESTSCOLLECTED"},{"col":0,"comment":"null","endLoc":363,"header":"@pytest.mark.parametrize(\"path\", [\"root\", \"{relative}/root\", \"{environment}/root\"])\ndef test_rootdir_option_arg(testdir, monkeypatch, path)","id":4039,"name":"test_rootdir_option_arg","nodeType":"Function","startLoc":341,"text":"@pytest.mark.parametrize(\"path\", [\"root\", \"{relative}/root\", \"{environment}/root\"])\ndef test_rootdir_option_arg(testdir, monkeypatch, path):\n monkeypatch.setenv(\"PY_ROOTDIR_PATH\", str(testdir.tmpdir))\n path = path.format(relative=str(testdir.tmpdir), environment=\"$PY_ROOTDIR_PATH\")\n\n rootdir = testdir.mkdir(\"root\")\n rootdir.mkdir(\"tests\")\n testdir.makepyfile(\n \"\"\"\n import os\n def test_one():\n assert 1\n \"\"\"\n )\n\n result = testdir.runpytest(\"--rootdir={}\".format(path))\n result.stdout.fnmatch_lines(\n [\n \"*rootdir: {}/root\".format(testdir.tmpdir),\n \"root/test_rootdir_option_arg.py *\",\n \"*1 passed*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":99,"header":"def test_group_addoption(self)","id":4040,"name":"test_group_addoption","nodeType":"Function","startLoc":95,"text":"def test_group_addoption(self):\n group = parseopt.OptionGroup(\"hello\")\n group.addoption(\"--option1\", action=\"store_true\")\n assert len(group.options) == 1\n assert isinstance(group.options[0], parseopt.Argument)"},{"col":4,"comment":"null","endLoc":638,"header":"@pytest.hookimpl(hookwrapper=True, tryfirst=True)\n def pytest_sessionstart(self)","id":4041,"name":"pytest_sessionstart","nodeType":"Function","startLoc":629,"text":"@pytest.hookimpl(hookwrapper=True, tryfirst=True)\n def pytest_sessionstart(self):\n with self.live_logs_context():\n if self.log_cli_handler:\n self.log_cli_handler.set_when(\"sessionstart\")\n if self.log_file_handler is not None:\n with catching_logs(self.log_file_handler, level=self.log_file_level):\n yield\n else:\n yield"},{"col":4,"comment":" add an option to this group.\n\n if a shortened version of a long option is specified it will\n be suppressed in the help. addoption('--twowords', '--two-words')\n results in help showing '--two-words' only, but --twowords gets\n accepted **and** the automatic destination is in args.twowords\n ","endLoc":306,"header":"def addoption(self, *optnames, **attrs)","id":4042,"name":"addoption","nodeType":"Function","startLoc":292,"text":"def addoption(self, *optnames, **attrs):\n \"\"\" add an option to this group.\n\n if a shortened version of a long option is specified it will\n be suppressed in the help. addoption('--twowords', '--two-words')\n results in help showing '--two-words' only, but --twowords gets\n accepted **and** the automatic destination is in args.twowords\n \"\"\"\n conflict = set(optnames).intersection(\n name for opt in self.options for name in opt.names()\n )\n if conflict:\n raise ValueError(\"option names %s already added\" % conflict)\n option = Argument(*optnames, **attrs)\n self._addoption_instance(option, shortupper=False)"},{"col":4,"comment":"null","endLoc":240,"header":"def test_pdb_dont_print_empty_captured_stdout_and_stderr(self, testdir)","id":4043,"name":"test_pdb_dont_print_empty_captured_stdout_and_stderr","nodeType":"Function","startLoc":227,"text":"def test_pdb_dont_print_empty_captured_stdout_and_stderr(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1():\n assert False\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdb %s\" % p1)\n child.expect(\"Pdb\")\n output = child.before.decode(\"utf8\")\n child.sendeof()\n assert \"captured stdout\" not in output\n assert \"captured stderr\" not in output\n self.flush(child)"},{"col":4,"comment":"null","endLoc":594,"header":"def test_len(self, request)","id":4044,"name":"test_len","nodeType":"Function","startLoc":585,"text":"def test_len(self, request):\n def f():\n values = list(range(10))\n assert len(values) == 11\n\n msg = getmsg(f)\n if request.config.getoption(\"verbose\") > 0:\n assert msg == \"assert 10 == 11\\n -10\\n +11\"\n else:\n assert msg == \"assert 10 == 11\\n + where 10 = len([0, 1, 2, 3, 4, 5, ...])\""},{"col":4,"comment":"null","endLoc":536,"header":"def test_hidden_by_ini(self, testdir)","id":4045,"name":"test_hidden_by_ini","nodeType":"Function","startLoc":525,"text":"def test_hidden_by_ini(self, testdir):\n self.create_file(testdir)\n testdir.makeini(\n \"\"\"\n [pytest]\n filterwarnings =\n ignore::DeprecationWarning\n ignore::PendingDeprecationWarning\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()"},{"col":4,"comment":"Should hide the deprecation warning from the function, but the warning during collection should\n be displayed normally.\n ","endLoc":553,"header":"def test_hidden_by_mark(self, testdir)","id":4046,"name":"test_hidden_by_mark","nodeType":"Function","startLoc":538,"text":"def test_hidden_by_mark(self, testdir):\n \"\"\"Should hide the deprecation warning from the function, but the warning during collection should\n be displayed normally.\n \"\"\"\n self.create_file(\n testdir,\n mark='@pytest.mark.filterwarnings(\"ignore::PendingDeprecationWarning\")',\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines(\n [\n \"*== %s ==*\" % WARNINGS_SUMMARY_HEADER,\n \"*test_hidden_by_mark.py:3: DeprecationWarning: collection\",\n \"* 1 passed, 1 warnings*\",\n ]\n )"},{"col":4,"comment":"Runs all collected test items.","endLoc":657,"header":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtestloop(self, session)","id":4047,"name":"pytest_runtestloop","nodeType":"Function","startLoc":640,"text":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtestloop(self, session):\n \"\"\"Runs all collected test items.\"\"\"\n\n if session.config.option.collectonly:\n yield\n return\n\n if self._log_cli_enabled() and self._config.getoption(\"verbose\") < 1:\n # setting verbose flag is needed to avoid messy test progress output\n self._config.option.verbose = 1\n\n with self.live_logs_context():\n if self.log_file_handler is not None:\n with catching_logs(self.log_file_handler, level=self.log_file_level):\n yield # run all the tests\n else:\n yield # run all the tests"},{"col":0,"comment":"null","endLoc":278,"header":"def _report_unserialization_failure(type_name, report_class, reportdict)","id":4048,"name":"_report_unserialization_failure","nodeType":"Function","startLoc":269,"text":"def _report_unserialization_failure(type_name, report_class, reportdict):\n url = \"https://github.com/pytest-dev/pytest/issues\"\n stream = py.io.TextIO()\n pprint(\"-\" * 100, stream=stream)\n pprint(\"INTERNALERROR: Unknown entry type returned: %s\" % type_name, stream=stream)\n pprint(\"report_name: %s\" % report_class, stream=stream)\n pprint(reportdict, stream=stream)\n pprint(\"Please report this bug at %s\" % url, stream=stream)\n pprint(\"-\" * 100, stream=stream)\n raise RuntimeError(stream.getvalue())"},{"col":4,"comment":"null","endLoc":262,"header":"@pytest.mark.parametrize(\"showcapture\", [\"all\", \"no\", \"log\"])\n def test_pdb_print_captured_logs(self, testdir, showcapture)","id":4049,"name":"test_pdb_print_captured_logs","nodeType":"Function","startLoc":242,"text":"@pytest.mark.parametrize(\"showcapture\", [\"all\", \"no\", \"log\"])\n def test_pdb_print_captured_logs(self, testdir, showcapture):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1():\n import logging\n logging.warn(\"get \" + \"rekt\")\n assert False\n \"\"\"\n )\n child = testdir.spawn_pytest(\n \"--show-capture={} --pdb {}\".format(showcapture, p1)\n )\n if showcapture in (\"all\", \"log\"):\n child.expect(\"captured log\")\n child.expect(\"get rekt\")\n child.expect(\"Pdb\")\n child.sendeof()\n rest = child.read().decode(\"utf8\")\n assert \"1 failed\" in rest\n self.flush(child)"},{"col":4,"comment":"null","endLoc":563,"header":"def test_hidden_by_cmdline(self, testdir)","id":4050,"name":"test_hidden_by_cmdline","nodeType":"Function","startLoc":555,"text":"def test_hidden_by_cmdline(self, testdir):\n self.create_file(testdir)\n result = testdir.runpytest_subprocess(\n \"-W\",\n \"ignore::DeprecationWarning\",\n \"-W\",\n \"ignore::PendingDeprecationWarning\",\n )\n assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()"},{"col":4,"comment":"null","endLoc":569,"header":"def test_hidden_by_system(self, testdir, monkeypatch)","id":4051,"name":"test_hidden_by_system","nodeType":"Function","startLoc":565,"text":"def test_hidden_by_system(self, testdir, monkeypatch):\n self.create_file(testdir)\n monkeypatch.setenv(str(\"PYTHONWARNINGS\"), str(\"once::UserWarning\"))\n result = testdir.runpytest_subprocess()\n assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()"},{"col":4,"comment":"null","endLoc":72,"header":"@pytest.mark.skipif(sys.platform.startswith(\"win\"), reason=\"no chmod on windows\")\n @pytest.mark.filterwarnings(\"default\")\n def test_cache_failure_warns(self, testdir)","id":4052,"name":"test_cache_failure_warns","nodeType":"Function","startLoc":58,"text":"@pytest.mark.skipif(sys.platform.startswith(\"win\"), reason=\"no chmod on windows\")\n @pytest.mark.filterwarnings(\"default\")\n def test_cache_failure_warns(self, testdir):\n testdir.tmpdir.ensure_dir(\".pytest_cache\").chmod(0)\n testdir.makepyfile(\n \"\"\"\n def test_error():\n raise Exception\n\n \"\"\"\n )\n result = testdir.runpytest(\"-rw\")\n assert result.ret == 1\n # warnings from nodeids, lastfailed, and stepwise\n result.stdout.fnmatch_lines([\"*could not create cache path*\", \"*3 warnings*\"])"},{"attributeType":"null","col":4,"comment":"null","endLoc":36,"id":4053,"name":"when","nodeType":"Attribute","startLoc":36,"text":"when"},{"attributeType":"null","col":4,"comment":"null","endLoc":37,"id":4054,"name":"location","nodeType":"Attribute","startLoc":37,"text":"location"},{"attributeType":"null","col":4,"comment":"null","endLoc":107,"id":4055,"name":"passed","nodeType":"Attribute","startLoc":107,"text":"passed"},{"attributeType":"null","col":4,"comment":"null","endLoc":108,"id":4056,"name":"failed","nodeType":"Attribute","startLoc":108,"text":"failed"},{"attributeType":"null","col":4,"comment":"null","endLoc":109,"id":4057,"name":"skipped","nodeType":"Attribute","startLoc":109,"text":"skipped"},{"col":4,"comment":"null","endLoc":398,"header":"def __init__(self, nodeid, outcome, longrepr, result, sections=(), **extra)","id":4058,"name":"__init__","nodeType":"Function","startLoc":392,"text":"def __init__(self, nodeid, outcome, longrepr, result, sections=(), **extra):\n self.nodeid = nodeid\n self.outcome = outcome\n self.longrepr = longrepr\n self.result = result or []\n self.sections = list(sections)\n self.__dict__.update(extra)"},{"col":4,"comment":"null","endLoc":281,"header":"def test_pdb_print_captured_logs_nologging(self, testdir)","id":4059,"name":"test_pdb_print_captured_logs_nologging","nodeType":"Function","startLoc":264,"text":"def test_pdb_print_captured_logs_nologging(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1():\n import logging\n logging.warn(\"get \" + \"rekt\")\n assert False\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--show-capture=all --pdb -p no:logging %s\" % p1)\n child.expect(\"get rekt\")\n output = child.before.decode(\"utf8\")\n assert \"captured log\" not in output\n child.expect(\"Pdb\")\n child.sendeof()\n rest = child.read().decode(\"utf8\")\n assert \"1 failed\" in rest\n self.flush(child)"},{"attributeType":"ColoredLevelFormatter | Formatter","col":8,"comment":"null","endLoc":428,"id":4060,"name":"formatter","nodeType":"Attribute","startLoc":428,"text":"self.formatter"},{"attributeType":"None","col":8,"comment":"null","endLoc":436,"id":4061,"name":"log_file_date_format","nodeType":"Attribute","startLoc":436,"text":"self.log_file_date_format"},{"attributeType":"Formatter","col":8,"comment":"null","endLoc":439,"id":4062,"name":"log_file_formatter","nodeType":"Attribute","startLoc":439,"text":"self.log_file_formatter"},{"attributeType":"None","col":12,"comment":"null","endLoc":450,"id":4063,"name":"log_file_handler","nodeType":"Attribute","startLoc":450,"text":"self.log_file_handler"},{"attributeType":"None","col":8,"comment":"null","endLoc":427,"id":4064,"name":"print_logs","nodeType":"Attribute","startLoc":427,"text":"self.print_logs"},{"attributeType":"int | None","col":8,"comment":"null","endLoc":434,"id":4065,"name":"log_file_level","nodeType":"Attribute","startLoc":434,"text":"self.log_file_level"},{"col":4,"comment":"null","endLoc":615,"header":"def test_custom_reprcompare(self, monkeypatch)","id":4066,"name":"test_custom_reprcompare","nodeType":"Function","startLoc":596,"text":"def test_custom_reprcompare(self, monkeypatch):\n def my_reprcompare(op, left, right):\n return \"42\"\n\n monkeypatch.setattr(util, \"_reprcompare\", my_reprcompare)\n\n def f():\n assert 42 < 3\n\n assert getmsg(f) == \"assert 42\"\n\n def my_reprcompare(op, left, right):\n return \"{} {} {}\".format(left, op, right)\n\n monkeypatch.setattr(util, \"_reprcompare\", my_reprcompare)\n\n def f():\n assert 1 < 3 < 5 <= 4 < 7\n\n assert getmsg(f) == \"assert 5 <= 4\""},{"col":4,"comment":"null","endLoc":301,"header":"def test_pdb_interaction_exception(self, testdir)","id":4067,"name":"test_pdb_interaction_exception","nodeType":"Function","startLoc":283,"text":"def test_pdb_interaction_exception(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def globalfunc():\n pass\n def test_1():\n pytest.raises(ValueError, globalfunc)\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdb %s\" % p1)\n child.expect(\".*def test_1\")\n child.expect(\".*pytest.raises.*globalfunc\")\n child.expect(\"Pdb\")\n child.sendline(\"globalfunc\")\n child.expect(\".*function\")\n child.sendeof()\n child.expect(\"1 failed\")\n self.flush(child)"},{"col":4,"comment":"null","endLoc":343,"header":"def __repr__(self)","id":4068,"name":"__repr__","nodeType":"Function","startLoc":337,"text":"def __repr__(self):\n return \"<%s %r when=%r outcome=%r>\" % (\n self.__class__.__name__,\n self.nodeid,\n self.when,\n self.outcome,\n )"},{"attributeType":"int | None","col":8,"comment":"null","endLoc":432,"id":4069,"name":"log_level","nodeType":"Attribute","startLoc":432,"text":"self.log_level"},{"col":4,"comment":"\n Factory method to create and fill a TestReport with standard item and call info.\n ","endLoc":386,"header":"@classmethod\n def from_item_and_call(cls, item, call)","id":4070,"name":"from_item_and_call","nodeType":"Function","startLoc":345,"text":"@classmethod\n def from_item_and_call(cls, item, call):\n \"\"\"\n Factory method to create and fill a TestReport with standard item and call info.\n \"\"\"\n when = call.when\n duration = call.stop - call.start\n keywords = {x: 1 for x in item.keywords}\n excinfo = call.excinfo\n sections = []\n if not call.excinfo:\n outcome = \"passed\"\n longrepr = None\n else:\n if not isinstance(excinfo, ExceptionInfo):\n outcome = \"failed\"\n longrepr = excinfo\n elif excinfo.errisinstance(skip.Exception):\n outcome = \"skipped\"\n r = excinfo._getreprcrash()\n longrepr = (str(r.path), r.lineno, r.message)\n else:\n outcome = \"failed\"\n if call.when == \"call\":\n longrepr = item.repr_failure(excinfo)\n else: # exception in setup or teardown\n longrepr = item._repr_failure_py(\n excinfo, style=item.config.getoption(\"tbstyle\", \"auto\")\n )\n for rwhen, key, content in item._report_sections:\n sections.append((\"Captured %s %s\" % (key, rwhen), content))\n return cls(\n item.nodeid,\n item.location,\n keywords,\n outcome,\n longrepr,\n when,\n sections,\n duration,\n user_properties=item.user_properties,\n )"},{"attributeType":"None","col":8,"comment":"null","endLoc":452,"id":4071,"name":"log_cli_handler","nodeType":"Attribute","startLoc":452,"text":"self.log_cli_handler"},{"attributeType":"None","col":8,"comment":"null","endLoc":435,"id":4072,"name":"log_file_format","nodeType":"Attribute","startLoc":435,"text":"self.log_file_format"},{"attributeType":"{getoption}","col":8,"comment":"null","endLoc":425,"id":4073,"name":"_config","nodeType":"Attribute","startLoc":425,"text":"self._config"},{"attributeType":"function","col":8,"comment":"null","endLoc":454,"id":4074,"name":"live_logs_context","nodeType":"Attribute","startLoc":454,"text":"self.live_logs_context"},{"className":"_LiveLoggingStreamHandler","col":0,"comment":"\n Custom StreamHandler used by the live logging feature: it will write a newline before the first log message\n in each test.\n\n During live logging we must also explicitly disable stdout/stderr capturing otherwise it will get captured\n and won't appear in the terminal.\n ","endLoc":708,"id":4075,"nodeType":"Class","startLoc":660,"text":"class _LiveLoggingStreamHandler(logging.StreamHandler):\n \"\"\"\n Custom StreamHandler used by the live logging feature: it will write a newline before the first log message\n in each test.\n\n During live logging we must also explicitly disable stdout/stderr capturing otherwise it will get captured\n and won't appear in the terminal.\n \"\"\"\n\n def __init__(self, terminal_reporter, capture_manager):\n \"\"\"\n :param _pytest.terminal.TerminalReporter terminal_reporter:\n :param _pytest.capture.CaptureManager capture_manager:\n \"\"\"\n logging.StreamHandler.__init__(self, stream=terminal_reporter)\n self.capture_manager = capture_manager\n self.reset()\n self.set_when(None)\n self._test_outcome_written = False\n\n def reset(self):\n \"\"\"Reset the handler; should be called before the start of each test\"\"\"\n self._first_record_emitted = False\n\n def set_when(self, when):\n \"\"\"Prepares for the given test phase (setup/call/teardown)\"\"\"\n self._when = when\n self._section_name_shown = False\n if when == \"start\":\n self._test_outcome_written = False\n\n def emit(self, record):\n ctx_manager = (\n self.capture_manager.global_and_fixture_disabled()\n if self.capture_manager\n else dummy_context_manager()\n )\n with ctx_manager:\n if not self._first_record_emitted:\n self.stream.write(\"\\n\")\n self._first_record_emitted = True\n elif self._when in (\"teardown\", \"finish\"):\n if not self._test_outcome_written:\n self._test_outcome_written = True\n self.stream.write(\"\\n\")\n if not self._section_name_shown and self._when:\n self.stream.section(\"live log \" + self._when, sep=\"-\", bold=True)\n self._section_name_shown = True\n logging.StreamHandler.emit(self, record)"},{"col":4,"comment":"null","endLoc":708,"header":"def emit(self, record)","id":4076,"name":"emit","nodeType":"Function","startLoc":691,"text":"def emit(self, record):\n ctx_manager = (\n self.capture_manager.global_and_fixture_disabled()\n if self.capture_manager\n else dummy_context_manager()\n )\n with ctx_manager:\n if not self._first_record_emitted:\n self.stream.write(\"\\n\")\n self._first_record_emitted = True\n elif self._when in (\"teardown\", \"finish\"):\n if not self._test_outcome_written:\n self._test_outcome_written = True\n self.stream.write(\"\\n\")\n if not self._section_name_shown and self._when:\n self.stream.section(\"live log \" + self._when, sep=\"-\", bold=True)\n self._section_name_shown = True\n logging.StreamHandler.emit(self, record)"},{"col":0,"comment":"null","endLoc":378,"header":"def test_rootdir_wrong_option_arg(testdir)","id":4077,"name":"test_rootdir_wrong_option_arg","nodeType":"Function","startLoc":366,"text":"def test_rootdir_wrong_option_arg(testdir):\n testdir.makepyfile(\n \"\"\"\n import os\n def test_one():\n assert 1\n \"\"\"\n )\n\n result = testdir.runpytest(\"--rootdir=wrong_dir\")\n result.stderr.fnmatch_lines(\n [\"*Directory *wrong_dir* not found. Check your '--rootdir' option.*\"]\n )"},{"col":4,"comment":"null","endLoc":634,"header":"def test_assert_raising_nonzero_in_comparison(self)","id":4078,"name":"test_assert_raising_nonzero_in_comparison","nodeType":"Function","startLoc":617,"text":"def test_assert_raising_nonzero_in_comparison(self):\n def f():\n class A(object):\n def __nonzero__(self):\n raise ValueError(42)\n\n def __lt__(self, other):\n return A()\n\n def __repr__(self):\n return \"\"\n\n def myany(x):\n return False\n\n assert myany(A() < 0)\n\n assert \" < 0\" in getmsg(f)"},{"col":4,"comment":"null","endLoc":315,"header":"def test_pdb_interaction_on_collection_issue181(self, testdir)","id":4079,"name":"test_pdb_interaction_on_collection_issue181","nodeType":"Function","startLoc":303,"text":"def test_pdb_interaction_on_collection_issue181(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n xxx\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdb %s\" % p1)\n # child.expect(\".*import pytest.*\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n child.expect(\"1 error\")\n self.flush(child)"},{"col":4,"comment":"null","endLoc":319,"header":"def _addoption_instance(self, option, shortupper=False)","id":4080,"name":"_addoption_instance","nodeType":"Function","startLoc":312,"text":"def _addoption_instance(self, option, shortupper=False):\n if not shortupper:\n for opt in option._short_opts:\n if opt[0] == \"-\" and opt[1].islower():\n raise ValueError(\"lowercase shortoptions reserved\")\n if self.parser:\n self.parser.processoption(option)\n self.options.append(option)"},{"col":4,"comment":"null","endLoc":341,"header":"def test_pdb_interaction_on_internal_error(self, testdir)","id":4081,"name":"test_pdb_interaction_on_internal_error","nodeType":"Function","startLoc":317,"text":"def test_pdb_interaction_on_internal_error(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_runtest_protocol():\n 0/0\n \"\"\"\n )\n p1 = testdir.makepyfile(\"def test_func(): pass\")\n child = testdir.spawn_pytest(\"--pdb %s\" % p1)\n child.expect(\"Pdb\")\n\n # INTERNALERROR is only displayed once via terminal reporter.\n assert (\n len(\n [\n x\n for x in child.before.decode().splitlines()\n if x.startswith(\"INTERNALERROR> Traceback\")\n ]\n )\n == 1\n )\n\n child.sendeof()\n self.flush(child)"},{"col":4,"comment":"null","endLoc":640,"header":"def test_formatchar(self)","id":4083,"name":"test_formatchar","nodeType":"Function","startLoc":636,"text":"def test_formatchar(self):\n def f():\n assert \"%test\" == \"test\"\n\n assert getmsg(f).startswith(\"assert '%test' == 'test'\")"},{"col":4,"comment":"null","endLoc":402,"header":"@property\n def location(self)","id":4084,"name":"location","nodeType":"Function","startLoc":400,"text":"@property\n def location(self):\n return (self.fspath, None, self.fspath)"},{"col":4,"comment":"null","endLoc":409,"header":"def __repr__(self)","id":4085,"name":"__repr__","nodeType":"Function","startLoc":404,"text":"def __repr__(self):\n return \"\" % (\n self.nodeid,\n len(self.result),\n self.outcome,\n )"},{"col":4,"comment":"null","endLoc":657,"header":"def test_custom_repr(self, request)","id":4086,"name":"test_custom_repr","nodeType":"Function","startLoc":642,"text":"def test_custom_repr(self, request):\n def f():\n class Foo(object):\n a = 1\n\n def __repr__(self):\n return \"\\n{ \\n~ \\n}\"\n\n f = Foo()\n assert 0 == f.a\n\n lines = util._format_lines([getmsg(f)])\n if request.config.getoption(\"verbose\") > 0:\n assert lines == [\"assert 0 == 1\\n -0\\n +1\"]\n else:\n assert lines == [\"assert 0 == 1\\n + where 1 = \\\\n{ \\\\n~ \\\\n}.a\"]"},{"attributeType":"null","col":4,"comment":"null","endLoc":390,"id":4087,"name":"when","nodeType":"Attribute","startLoc":390,"text":"when"},{"col":4,"comment":"null","endLoc":365,"header":"def test_pdb_interaction_capturing_simple(self, testdir)","id":4088,"name":"test_pdb_interaction_capturing_simple","nodeType":"Function","startLoc":343,"text":"def test_pdb_interaction_capturing_simple(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1():\n i = 0\n print(\"hello17\")\n pytest.set_trace()\n i == 1\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(r\"test_1\\(\\)\")\n child.expect(\"i == 1\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n rest = child.read().decode(\"utf-8\")\n assert \"AssertionError\" in rest\n assert \"1 failed\" in rest\n assert \"def test_1\" in rest\n assert \"hello17\" in rest # out is captured\n self.flush(child)"},{"attributeType":"null","col":8,"comment":"null","endLoc":396,"id":4089,"name":"result","nodeType":"Attribute","startLoc":396,"text":"self.result"},{"col":4,"comment":"Context manager to temporarily disable global and current fixture capturing.","endLoc":188,"header":"@contextlib.contextmanager\n def global_and_fixture_disabled(self)","id":4090,"name":"global_and_fixture_disabled","nodeType":"Function","startLoc":181,"text":"@contextlib.contextmanager\n def global_and_fixture_disabled(self):\n \"\"\"Context manager to temporarily disable global and current fixture capturing.\"\"\"\n self.suspend()\n try:\n yield\n finally:\n self.resume()"},{"fileName":"main.py","filePath":"src/_pytest","id":4091,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\" core implementation of testing process: init, session, runtest loop. \"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport contextlib\nimport fnmatch\nimport functools\nimport os\nimport pkgutil\nimport sys\nimport warnings\n\nimport attr\nimport py\nimport six\n\nimport _pytest._code\nfrom _pytest import nodes\nfrom _pytest.config import directory_arg\nfrom _pytest.config import hookimpl\nfrom _pytest.config import UsageError\nfrom _pytest.deprecated import PYTEST_CONFIG_GLOBAL\nfrom _pytest.outcomes import exit\nfrom _pytest.runner import collect_one_node\n\n# exitcodes for the command line\nEXIT_OK = 0\nEXIT_TESTSFAILED = 1\nEXIT_INTERRUPTED = 2\nEXIT_INTERNALERROR = 3\nEXIT_USAGEERROR = 4\nEXIT_NOTESTSCOLLECTED = 5\n\n\ndef pytest_addoption(parser):\n parser.addini(\n \"norecursedirs\",\n \"directory patterns to avoid for recursion\",\n type=\"args\",\n default=[\".*\", \"build\", \"dist\", \"CVS\", \"_darcs\", \"{arch}\", \"*.egg\", \"venv\"],\n )\n parser.addini(\n \"testpaths\",\n \"directories to search for tests when no files or directories are given in the \"\n \"command line.\",\n type=\"args\",\n default=[],\n )\n group = parser.getgroup(\"general\", \"running and selection options\")\n group._addoption(\n \"-x\",\n \"--exitfirst\",\n action=\"store_const\",\n dest=\"maxfail\",\n const=1,\n help=\"exit instantly on first error or failed test.\",\n ),\n group._addoption(\n \"--maxfail\",\n metavar=\"num\",\n action=\"store\",\n type=int,\n dest=\"maxfail\",\n default=0,\n help=\"exit after first num failures or errors.\",\n )\n group._addoption(\n \"--strict-markers\",\n \"--strict\",\n action=\"store_true\",\n help=\"markers not registered in the `markers` section of the configuration file raise errors.\",\n )\n group._addoption(\n \"-c\",\n metavar=\"file\",\n type=str,\n dest=\"inifilename\",\n help=\"load configuration from `file` instead of trying to locate one of the implicit \"\n \"configuration files.\",\n )\n group._addoption(\n \"--continue-on-collection-errors\",\n action=\"store_true\",\n default=False,\n dest=\"continue_on_collection_errors\",\n help=\"Force test execution even if collection errors occur.\",\n )\n group._addoption(\n \"--rootdir\",\n action=\"store\",\n dest=\"rootdir\",\n help=\"Define root directory for tests. Can be relative path: 'root_dir', './root_dir', \"\n \"'root_dir/another_dir/'; absolute path: '/home/user/root_dir'; path with variables: \"\n \"'$HOME/root_dir'.\",\n )\n\n group = parser.getgroup(\"collect\", \"collection\")\n group.addoption(\n \"--collectonly\",\n \"--collect-only\",\n action=\"store_true\",\n help=\"only collect tests, don't execute them.\",\n ),\n group.addoption(\n \"--pyargs\",\n action=\"store_true\",\n help=\"try to interpret all arguments as python packages.\",\n )\n group.addoption(\n \"--ignore\",\n action=\"append\",\n metavar=\"path\",\n help=\"ignore path during collection (multi-allowed).\",\n )\n group.addoption(\n \"--ignore-glob\",\n action=\"append\",\n metavar=\"path\",\n help=\"ignore path pattern during collection (multi-allowed).\",\n )\n group.addoption(\n \"--deselect\",\n action=\"append\",\n metavar=\"nodeid_prefix\",\n help=\"deselect item during collection (multi-allowed).\",\n )\n # when changing this to --conf-cut-dir, config.py Conftest.setinitial\n # needs upgrading as well\n group.addoption(\n \"--confcutdir\",\n dest=\"confcutdir\",\n default=None,\n metavar=\"dir\",\n type=functools.partial(directory_arg, optname=\"--confcutdir\"),\n help=\"only load conftest.py's relative to specified dir.\",\n )\n group.addoption(\n \"--noconftest\",\n action=\"store_true\",\n dest=\"noconftest\",\n default=False,\n help=\"Don't load any conftest.py files.\",\n )\n group.addoption(\n \"--keepduplicates\",\n \"--keep-duplicates\",\n action=\"store_true\",\n dest=\"keepduplicates\",\n default=False,\n help=\"Keep duplicate tests.\",\n )\n group.addoption(\n \"--collect-in-virtualenv\",\n action=\"store_true\",\n dest=\"collect_in_virtualenv\",\n default=False,\n help=\"Don't ignore tests in a local virtualenv directory\",\n )\n\n group = parser.getgroup(\"debugconfig\", \"test session debugging and configuration\")\n group.addoption(\n \"--basetemp\",\n dest=\"basetemp\",\n default=None,\n metavar=\"dir\",\n help=(\n \"base temporary directory for this test run.\"\n \"(warning: this directory is removed if it exists)\"\n ),\n )\n\n\nclass _ConfigDeprecated(object):\n def __init__(self, config):\n self.__dict__[\"_config\"] = config\n\n def __getattr__(self, attr):\n warnings.warn(PYTEST_CONFIG_GLOBAL, stacklevel=2)\n return getattr(self._config, attr)\n\n def __setattr__(self, attr, val):\n warnings.warn(PYTEST_CONFIG_GLOBAL, stacklevel=2)\n return setattr(self._config, attr, val)\n\n def __repr__(self):\n return \"{}({!r})\".format(type(self).__name__, self._config)\n\n\ndef pytest_configure(config):\n __import__(\"pytest\").config = _ConfigDeprecated(config) # compatibility\n\n\ndef wrap_session(config, doit):\n \"\"\"Skeleton command line program\"\"\"\n session = Session(config)\n session.exitstatus = EXIT_OK\n initstate = 0\n try:\n try:\n config._do_configure()\n initstate = 1\n config.hook.pytest_sessionstart(session=session)\n initstate = 2\n session.exitstatus = doit(config, session) or 0\n except UsageError:\n session.exitstatus = EXIT_USAGEERROR\n raise\n except Failed:\n session.exitstatus = EXIT_TESTSFAILED\n except (KeyboardInterrupt, exit.Exception):\n excinfo = _pytest._code.ExceptionInfo.from_current()\n exitstatus = EXIT_INTERRUPTED\n if isinstance(excinfo.value, exit.Exception):\n if excinfo.value.returncode is not None:\n exitstatus = excinfo.value.returncode\n if initstate < 2:\n sys.stderr.write(\n \"{}: {}\\n\".format(excinfo.typename, excinfo.value.msg)\n )\n config.hook.pytest_keyboard_interrupt(excinfo=excinfo)\n session.exitstatus = exitstatus\n except: # noqa\n excinfo = _pytest._code.ExceptionInfo.from_current()\n config.notify_exception(excinfo, config.option)\n session.exitstatus = EXIT_INTERNALERROR\n if excinfo.errisinstance(SystemExit):\n sys.stderr.write(\"mainloop: caught unexpected SystemExit!\\n\")\n\n finally:\n excinfo = None # Explicitly break reference cycle.\n session.startdir.chdir()\n if initstate >= 2:\n config.hook.pytest_sessionfinish(\n session=session, exitstatus=session.exitstatus\n )\n config._ensure_unconfigure()\n return session.exitstatus\n\n\ndef pytest_cmdline_main(config):\n return wrap_session(config, _main)\n\n\ndef _main(config, session):\n \"\"\" default command line protocol for initialization, session,\n running tests and reporting. \"\"\"\n config.hook.pytest_collection(session=session)\n config.hook.pytest_runtestloop(session=session)\n\n if session.testsfailed:\n return EXIT_TESTSFAILED\n elif session.testscollected == 0:\n return EXIT_NOTESTSCOLLECTED\n\n\ndef pytest_collection(session):\n return session.perform_collect()\n\n\ndef pytest_runtestloop(session):\n if session.testsfailed and not session.config.option.continue_on_collection_errors:\n raise session.Interrupted(\"%d errors during collection\" % session.testsfailed)\n\n if session.config.option.collectonly:\n return True\n\n for i, item in enumerate(session.items):\n nextitem = session.items[i + 1] if i + 1 < len(session.items) else None\n item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem)\n if session.shouldfail:\n raise session.Failed(session.shouldfail)\n if session.shouldstop:\n raise session.Interrupted(session.shouldstop)\n return True\n\n\ndef _in_venv(path):\n \"\"\"Attempts to detect if ``path`` is the root of a Virtual Environment by\n checking for the existence of the appropriate activate script\"\"\"\n bindir = path.join(\"Scripts\" if sys.platform.startswith(\"win\") else \"bin\")\n if not bindir.isdir():\n return False\n activates = (\n \"activate\",\n \"activate.csh\",\n \"activate.fish\",\n \"Activate\",\n \"Activate.bat\",\n \"Activate.ps1\",\n )\n return any([fname.basename in activates for fname in bindir.listdir()])\n\n\ndef pytest_ignore_collect(path, config):\n ignore_paths = config._getconftest_pathlist(\"collect_ignore\", path=path.dirpath())\n ignore_paths = ignore_paths or []\n excludeopt = config.getoption(\"ignore\")\n if excludeopt:\n ignore_paths.extend([py.path.local(x) for x in excludeopt])\n\n if py.path.local(path) in ignore_paths:\n return True\n\n ignore_globs = config._getconftest_pathlist(\n \"collect_ignore_glob\", path=path.dirpath()\n )\n ignore_globs = ignore_globs or []\n excludeglobopt = config.getoption(\"ignore_glob\")\n if excludeglobopt:\n ignore_globs.extend([py.path.local(x) for x in excludeglobopt])\n\n if any(\n fnmatch.fnmatch(six.text_type(path), six.text_type(glob))\n for glob in ignore_globs\n ):\n return True\n\n allow_in_venv = config.getoption(\"collect_in_virtualenv\")\n if not allow_in_venv and _in_venv(path):\n return True\n\n return False\n\n\ndef pytest_collection_modifyitems(items, config):\n deselect_prefixes = tuple(config.getoption(\"deselect\") or [])\n if not deselect_prefixes:\n return\n\n remaining = []\n deselected = []\n for colitem in items:\n if colitem.nodeid.startswith(deselect_prefixes):\n deselected.append(colitem)\n else:\n remaining.append(colitem)\n\n if deselected:\n config.hook.pytest_deselected(items=deselected)\n items[:] = remaining\n\n\n@contextlib.contextmanager\ndef _patched_find_module():\n \"\"\"Patch bug in pkgutil.ImpImporter.find_module\n\n When using pkgutil.find_loader on python<3.4 it removes symlinks\n from the path due to a call to os.path.realpath. This is not consistent\n with actually doing the import (in these versions, pkgutil and __import__\n did not share the same underlying code). This can break conftest\n discovery for pytest where symlinks are involved.\n\n The only supported python<3.4 by pytest is python 2.7.\n \"\"\"\n if six.PY2: # python 3.4+ uses importlib instead\n\n def find_module_patched(self, fullname, path=None):\n # Note: we ignore 'path' argument since it is only used via meta_path\n subname = fullname.split(\".\")[-1]\n if subname != fullname and self.path is None:\n return None\n if self.path is None:\n path = None\n else:\n # original: path = [os.path.realpath(self.path)]\n path = [self.path]\n try:\n file, filename, etc = pkgutil.imp.find_module(subname, path)\n except ImportError:\n return None\n return pkgutil.ImpLoader(fullname, file, filename, etc)\n\n old_find_module = pkgutil.ImpImporter.find_module\n pkgutil.ImpImporter.find_module = find_module_patched\n try:\n yield\n finally:\n pkgutil.ImpImporter.find_module = old_find_module\n else:\n yield\n\n\nclass FSHookProxy(object):\n def __init__(self, fspath, pm, remove_mods):\n self.fspath = fspath\n self.pm = pm\n self.remove_mods = remove_mods\n\n def __getattr__(self, name):\n x = self.pm.subset_hook_caller(name, remove_plugins=self.remove_mods)\n self.__dict__[name] = x\n return x\n\n\nclass NoMatch(Exception):\n \"\"\" raised if matching cannot locate a matching names. \"\"\"\n\n\nclass Interrupted(KeyboardInterrupt):\n \"\"\" signals an interrupted test run. \"\"\"\n\n __module__ = \"builtins\" # for py3\n\n\nclass Failed(Exception):\n \"\"\" signals a stop as failed test run. \"\"\"\n\n\n@attr.s\nclass _bestrelpath_cache(dict):\n path = attr.ib()\n\n def __missing__(self, path):\n r = self.path.bestrelpath(path)\n self[path] = r\n return r\n\n\nclass Session(nodes.FSCollector):\n Interrupted = Interrupted\n Failed = Failed\n\n def __init__(self, config):\n nodes.FSCollector.__init__(\n self, config.rootdir, parent=None, config=config, session=self, nodeid=\"\"\n )\n self.testsfailed = 0\n self.testscollected = 0\n self.shouldstop = False\n self.shouldfail = False\n self.trace = config.trace.root.get(\"collection\")\n self._norecursepatterns = config.getini(\"norecursedirs\")\n self.startdir = config.invocation_dir\n self._initialpaths = frozenset()\n # Keep track of any collected nodes in here, so we don't duplicate fixtures\n self._node_cache = {}\n self._bestrelpathcache = _bestrelpath_cache(config.rootdir)\n # Dirnames of pkgs with dunder-init files.\n self._pkg_roots = {}\n\n self.config.pluginmanager.register(self, name=\"session\")\n\n def __repr__(self):\n return \"<%s %s exitstatus=%r testsfailed=%d testscollected=%d>\" % (\n self.__class__.__name__,\n self.name,\n getattr(self, \"exitstatus\", \"\"),\n self.testsfailed,\n self.testscollected,\n )\n\n def _node_location_to_relpath(self, node_path):\n # bestrelpath is a quite slow function\n return self._bestrelpathcache[node_path]\n\n @hookimpl(tryfirst=True)\n def pytest_collectstart(self):\n if self.shouldfail:\n raise self.Failed(self.shouldfail)\n if self.shouldstop:\n raise self.Interrupted(self.shouldstop)\n\n @hookimpl(tryfirst=True)\n def pytest_runtest_logreport(self, report):\n if report.failed and not hasattr(report, \"wasxfail\"):\n self.testsfailed += 1\n maxfail = self.config.getvalue(\"maxfail\")\n if maxfail and self.testsfailed >= maxfail:\n self.shouldfail = \"stopping after %d failures\" % (self.testsfailed)\n\n pytest_collectreport = pytest_runtest_logreport\n\n def isinitpath(self, path):\n return path in self._initialpaths\n\n def gethookproxy(self, fspath):\n # check if we have the common case of running\n # hooks with all conftest.py files\n pm = self.config.pluginmanager\n my_conftestmodules = pm._getconftestmodules(fspath)\n remove_mods = pm._conftest_plugins.difference(my_conftestmodules)\n if remove_mods:\n # one or more conftests are not in use at this fspath\n proxy = FSHookProxy(fspath, pm, remove_mods)\n else:\n # all plugis are active for this fspath\n proxy = self.config.hook\n return proxy\n\n def perform_collect(self, args=None, genitems=True):\n hook = self.config.hook\n try:\n items = self._perform_collect(args, genitems)\n self.config.pluginmanager.check_pending()\n hook.pytest_collection_modifyitems(\n session=self, config=self.config, items=items\n )\n finally:\n hook.pytest_collection_finish(session=self)\n self.testscollected = len(items)\n return items\n\n def _perform_collect(self, args, genitems):\n if args is None:\n args = self.config.args\n self.trace(\"perform_collect\", self, args)\n self.trace.root.indent += 1\n self._notfound = []\n initialpaths = []\n self._initialparts = []\n self.items = items = []\n for arg in args:\n parts = self._parsearg(arg)\n self._initialparts.append(parts)\n initialpaths.append(parts[0])\n self._initialpaths = frozenset(initialpaths)\n rep = collect_one_node(self)\n self.ihook.pytest_collectreport(report=rep)\n self.trace.root.indent -= 1\n if self._notfound:\n errors = []\n for arg, exc in self._notfound:\n line = \"(no name %r in any of %r)\" % (arg, exc.args[0])\n errors.append(\"not found: %s\\n%s\" % (arg, line))\n # XXX: test this\n raise UsageError(*errors)\n if not genitems:\n return rep.result\n else:\n if rep.passed:\n for node in rep.result:\n self.items.extend(self.genitems(node))\n return items\n\n def collect(self):\n for initialpart in self._initialparts:\n arg = \"::\".join(map(str, initialpart))\n self.trace(\"processing argument\", arg)\n self.trace.root.indent += 1\n try:\n for x in self._collect(arg):\n yield x\n except NoMatch:\n # we are inside a make_report hook so\n # we cannot directly pass through the exception\n self._notfound.append((arg, sys.exc_info()[1]))\n\n self.trace.root.indent -= 1\n\n def _collect(self, arg):\n from _pytest.python import Package\n\n names = self._parsearg(arg)\n argpath = names.pop(0)\n\n # Start with a Session root, and delve to argpath item (dir or file)\n # and stack all Packages found on the way.\n # No point in finding packages when collecting doctests\n if not self.config.getoption(\"doctestmodules\", False):\n pm = self.config.pluginmanager\n for parent in reversed(argpath.parts()):\n if pm._confcutdir and pm._confcutdir.relto(parent):\n break\n\n if parent.isdir():\n pkginit = parent.join(\"__init__.py\")\n if pkginit.isfile():\n if pkginit not in self._node_cache:\n col = self._collectfile(pkginit, handle_dupes=False)\n if col:\n if isinstance(col[0], Package):\n self._pkg_roots[parent] = col[0]\n # always store a list in the cache, matchnodes expects it\n self._node_cache[col[0].fspath] = [col[0]]\n\n # If it's a directory argument, recurse and look for any Subpackages.\n # Let the Package collector deal with subnodes, don't collect here.\n if argpath.check(dir=1):\n assert not names, \"invalid arg %r\" % (arg,)\n\n seen_dirs = set()\n for path in argpath.visit(\n fil=self._visit_filter, rec=self._recurse, bf=True, sort=True\n ):\n dirpath = path.dirpath()\n if dirpath not in seen_dirs:\n # Collect packages first.\n seen_dirs.add(dirpath)\n pkginit = dirpath.join(\"__init__.py\")\n if pkginit.exists():\n for x in self._collectfile(pkginit):\n yield x\n if isinstance(x, Package):\n self._pkg_roots[dirpath] = x\n if dirpath in self._pkg_roots:\n # Do not collect packages here.\n continue\n\n for x in self._collectfile(path):\n key = (type(x), x.fspath)\n if key in self._node_cache:\n yield self._node_cache[key]\n else:\n self._node_cache[key] = x\n yield x\n else:\n assert argpath.check(file=1)\n\n if argpath in self._node_cache:\n col = self._node_cache[argpath]\n else:\n collect_root = self._pkg_roots.get(argpath.dirname, self)\n col = collect_root._collectfile(argpath, handle_dupes=False)\n if col:\n self._node_cache[argpath] = col\n m = self.matchnodes(col, names)\n # If __init__.py was the only file requested, then the matched node will be\n # the corresponding Package, and the first yielded item will be the __init__\n # Module itself, so just use that. If this special case isn't taken, then all\n # the files in the package will be yielded.\n if argpath.basename == \"__init__.py\":\n try:\n yield next(m[0].collect())\n except StopIteration:\n # The package collects nothing with only an __init__.py\n # file in it, which gets ignored by the default\n # \"python_files\" option.\n pass\n return\n for y in m:\n yield y\n\n def _collectfile(self, path, handle_dupes=True):\n assert path.isfile(), \"%r is not a file (isdir=%r, exists=%r, islink=%r)\" % (\n path,\n path.isdir(),\n path.exists(),\n path.islink(),\n )\n ihook = self.gethookproxy(path)\n if not self.isinitpath(path):\n if ihook.pytest_ignore_collect(path=path, config=self.config):\n return ()\n\n if handle_dupes:\n keepduplicates = self.config.getoption(\"keepduplicates\")\n if not keepduplicates:\n duplicate_paths = self.config.pluginmanager._duplicatepaths\n if path in duplicate_paths:\n return ()\n else:\n duplicate_paths.add(path)\n\n return ihook.pytest_collect_file(path=path, parent=self)\n\n def _recurse(self, dirpath):\n if dirpath.basename == \"__pycache__\":\n return False\n ihook = self.gethookproxy(dirpath.dirpath())\n if ihook.pytest_ignore_collect(path=dirpath, config=self.config):\n return False\n for pat in self._norecursepatterns:\n if dirpath.check(fnmatch=pat):\n return False\n ihook = self.gethookproxy(dirpath)\n ihook.pytest_collect_directory(path=dirpath, parent=self)\n return True\n\n if six.PY2:\n\n @staticmethod\n def _visit_filter(f):\n return f.check(file=1) and not f.strpath.endswith(\"*.pyc\")\n\n else:\n\n @staticmethod\n def _visit_filter(f):\n return f.check(file=1)\n\n def _tryconvertpyarg(self, x):\n \"\"\"Convert a dotted module name to path.\"\"\"\n try:\n with _patched_find_module():\n loader = pkgutil.find_loader(x)\n except ImportError:\n return x\n if loader is None:\n return x\n # This method is sometimes invoked when AssertionRewritingHook, which\n # does not define a get_filename method, is already in place:\n try:\n with _patched_find_module():\n path = loader.get_filename(x)\n except AttributeError:\n # Retrieve path from AssertionRewritingHook:\n path = loader.modules[x][0].co_filename\n if loader.is_package(x):\n path = os.path.dirname(path)\n return path\n\n def _parsearg(self, arg):\n \"\"\" return (fspath, names) tuple after checking the file exists. \"\"\"\n parts = str(arg).split(\"::\")\n if self.config.option.pyargs:\n parts[0] = self._tryconvertpyarg(parts[0])\n relpath = parts[0].replace(\"/\", os.sep)\n path = self.config.invocation_dir.join(relpath, abs=True)\n if not path.check():\n if self.config.option.pyargs:\n raise UsageError(\n \"file or package not found: \" + arg + \" (missing __init__.py?)\"\n )\n raise UsageError(\"file not found: \" + arg)\n parts[0] = path.realpath()\n return parts\n\n def matchnodes(self, matching, names):\n self.trace(\"matchnodes\", matching, names)\n self.trace.root.indent += 1\n nodes = self._matchnodes(matching, names)\n num = len(nodes)\n self.trace(\"matchnodes finished -> \", num, \"nodes\")\n self.trace.root.indent -= 1\n if num == 0:\n raise NoMatch(matching, names[:1])\n return nodes\n\n def _matchnodes(self, matching, names):\n if not matching or not names:\n return matching\n name = names[0]\n assert name\n nextnames = names[1:]\n resultnodes = []\n for node in matching:\n if isinstance(node, nodes.Item):\n if not names:\n resultnodes.append(node)\n continue\n assert isinstance(node, nodes.Collector)\n key = (type(node), node.nodeid)\n if key in self._node_cache:\n rep = self._node_cache[key]\n else:\n rep = collect_one_node(node)\n self._node_cache[key] = rep\n if rep.passed:\n has_matched = False\n for x in rep.result:\n # TODO: remove parametrized workaround once collection structure contains parametrization\n if x.name == name or x.name.split(\"[\")[0] == name:\n resultnodes.extend(self.matchnodes([x], nextnames))\n has_matched = True\n # XXX accept IDs that don't have \"()\" for class instances\n if not has_matched and len(rep.result) == 1 and x.name == \"()\":\n nextnames.insert(0, name)\n resultnodes.extend(self.matchnodes([x], nextnames))\n else:\n # report collection failures here to avoid failing to run some test\n # specified in the command line because the module could not be\n # imported (#134)\n node.ihook.pytest_collectreport(report=rep)\n return resultnodes\n\n def genitems(self, node):\n self.trace(\"genitems\", node)\n if isinstance(node, nodes.Item):\n node.ihook.pytest_itemcollected(item=node)\n yield node\n else:\n assert isinstance(node, nodes.Collector)\n rep = collect_one_node(node)\n if rep.passed:\n for subnode in rep.result:\n for x in self.genitems(subnode):\n yield x\n node.ihook.pytest_collectreport(report=rep)\n"},{"col":0,"comment":"Format the individual lines\n\n This will replace the '{', '}' and '~' characters of our mini\n formatting language with the proper 'where ...', 'and ...' and ' +\n ...' text, taking care of indentation along the way.\n\n Return a list of formatted lines.\n ","endLoc":97,"header":"def _format_lines(lines)","id":4092,"name":"_format_lines","nodeType":"Function","startLoc":65,"text":"def _format_lines(lines):\n \"\"\"Format the individual lines\n\n This will replace the '{', '}' and '~' characters of our mini\n formatting language with the proper 'where ...', 'and ...' and ' +\n ...' text, taking care of indentation along the way.\n\n Return a list of formatted lines.\n \"\"\"\n result = lines[:1]\n stack = [0]\n stackcnt = [0]\n for line in lines[1:]:\n if line.startswith(\"{\"):\n if stackcnt[-1]:\n s = u\"and \"\n else:\n s = u\"where \"\n stack.append(len(result))\n stackcnt[-1] += 1\n stackcnt.append(0)\n result.append(u\" +\" + u\" \" * (len(stack) - 1) + s + line[1:])\n elif line.startswith(\"}\"):\n stack.pop()\n stackcnt.pop()\n result[stack[-1]] += line[1:]\n else:\n assert line[0] in [\"~\", \">\"]\n stack[-1] += 1\n indent = len(stack) if line.startswith(\"~\") else len(stack) - 1\n result.append(u\" \" * indent + line[1:])\n assert len(stack) == 1\n return result"},{"attributeType":"null","col":8,"comment":"null","endLoc":395,"id":4093,"name":"longrepr","nodeType":"Attribute","startLoc":395,"text":"self.longrepr"},{"attributeType":"null","col":8,"comment":"null","endLoc":393,"id":4094,"name":"nodeid","nodeType":"Attribute","startLoc":393,"text":"self.nodeid"},{"className":"_ConfigDeprecated","col":0,"comment":"null","endLoc":188,"id":4095,"nodeType":"Class","startLoc":175,"text":"class _ConfigDeprecated(object):\n def __init__(self, config):\n self.__dict__[\"_config\"] = config\n\n def __getattr__(self, attr):\n warnings.warn(PYTEST_CONFIG_GLOBAL, stacklevel=2)\n return getattr(self._config, attr)\n\n def __setattr__(self, attr, val):\n warnings.warn(PYTEST_CONFIG_GLOBAL, stacklevel=2)\n return setattr(self._config, attr, val)\n\n def __repr__(self):\n return \"{}({!r})\".format(type(self).__name__, self._config)"},{"attributeType":"null","col":8,"comment":"null","endLoc":394,"id":4096,"name":"outcome","nodeType":"Attribute","startLoc":394,"text":"self.outcome"},{"col":4,"comment":"null","endLoc":177,"header":"def __init__(self, config)","id":4097,"name":"__init__","nodeType":"Function","startLoc":176,"text":"def __init__(self, config):\n self.__dict__[\"_config\"] = config"},{"col":4,"comment":"null","endLoc":181,"header":"def __getattr__(self, attr)","id":4098,"name":"__getattr__","nodeType":"Function","startLoc":179,"text":"def __getattr__(self, attr):\n warnings.warn(PYTEST_CONFIG_GLOBAL, stacklevel=2)\n return getattr(self._config, attr)"},{"attributeType":"null","col":8,"comment":"null","endLoc":397,"id":4099,"name":"sections","nodeType":"Attribute","startLoc":397,"text":"self.sections"},{"className":"TestReportSerialization","col":0,"comment":"null","endLoc":244,"id":4100,"nodeType":"Class","startLoc":8,"text":"class TestReportSerialization(object):\n def test_xdist_longrepr_to_str_issue_241(self, testdir):\n \"\"\"\n Regarding issue pytest-xdist#241\n\n This test came originally from test_remote.py in xdist (ca03269).\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n def test_a(): assert False\n def test_b(): pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 6\n test_a_call = reports[1]\n assert test_a_call.when == \"call\"\n assert test_a_call.outcome == \"failed\"\n assert test_a_call._to_json()[\"longrepr\"][\"reprtraceback\"][\"style\"] == \"long\"\n test_b_call = reports[4]\n assert test_b_call.when == \"call\"\n assert test_b_call.outcome == \"passed\"\n assert test_b_call._to_json()[\"longrepr\"] is None\n\n def test_xdist_report_longrepr_reprcrash_130(self, testdir):\n \"\"\"Regarding issue pytest-xdist#130\n\n This test came originally from test_remote.py in xdist (ca03269).\n \"\"\"\n reprec = testdir.inline_runsource(\n \"\"\"\n def test_fail():\n assert False, 'Expected Message'\n \"\"\"\n )\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 3\n rep = reports[1]\n added_section = (\"Failure Metadata\", str(\"metadata metadata\"), \"*\")\n rep.longrepr.sections.append(added_section)\n d = rep._to_json()\n a = TestReport._from_json(d)\n # Check assembled == rep\n assert a.__dict__.keys() == rep.__dict__.keys()\n for key in rep.__dict__.keys():\n if key != \"longrepr\":\n assert getattr(a, key) == getattr(rep, key)\n assert rep.longrepr.reprcrash.lineno == a.longrepr.reprcrash.lineno\n assert rep.longrepr.reprcrash.message == a.longrepr.reprcrash.message\n assert rep.longrepr.reprcrash.path == a.longrepr.reprcrash.path\n assert rep.longrepr.reprtraceback.entrysep == a.longrepr.reprtraceback.entrysep\n assert (\n rep.longrepr.reprtraceback.extraline == a.longrepr.reprtraceback.extraline\n )\n assert rep.longrepr.reprtraceback.style == a.longrepr.reprtraceback.style\n assert rep.longrepr.sections == a.longrepr.sections\n # Missing section attribute PR171\n assert added_section in a.longrepr.sections\n\n def test_reprentries_serialization_170(self, testdir):\n \"\"\"Regarding issue pytest-xdist#170\n\n This test came originally from test_remote.py in xdist (ca03269).\n \"\"\"\n from _pytest._code.code import ReprEntry\n\n reprec = testdir.inline_runsource(\n \"\"\"\n def test_repr_entry():\n x = 0\n assert x\n \"\"\",\n \"--showlocals\",\n )\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 3\n rep = reports[1]\n d = rep._to_json()\n a = TestReport._from_json(d)\n\n rep_entries = rep.longrepr.reprtraceback.reprentries\n a_entries = a.longrepr.reprtraceback.reprentries\n for i in range(len(a_entries)):\n assert isinstance(rep_entries[i], ReprEntry)\n assert rep_entries[i].lines == a_entries[i].lines\n assert rep_entries[i].reprfileloc.lineno == a_entries[i].reprfileloc.lineno\n assert (\n rep_entries[i].reprfileloc.message == a_entries[i].reprfileloc.message\n )\n assert rep_entries[i].reprfileloc.path == a_entries[i].reprfileloc.path\n assert rep_entries[i].reprfuncargs.args == a_entries[i].reprfuncargs.args\n assert rep_entries[i].reprlocals.lines == a_entries[i].reprlocals.lines\n assert rep_entries[i].style == a_entries[i].style\n\n def test_reprentries_serialization_196(self, testdir):\n \"\"\"Regarding issue pytest-xdist#196\n\n This test came originally from test_remote.py in xdist (ca03269).\n \"\"\"\n from _pytest._code.code import ReprEntryNative\n\n reprec = testdir.inline_runsource(\n \"\"\"\n def test_repr_entry_native():\n x = 0\n assert x\n \"\"\",\n \"--tb=native\",\n )\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 3\n rep = reports[1]\n d = rep._to_json()\n a = TestReport._from_json(d)\n\n rep_entries = rep.longrepr.reprtraceback.reprentries\n a_entries = a.longrepr.reprtraceback.reprentries\n for i in range(len(a_entries)):\n assert isinstance(rep_entries[i], ReprEntryNative)\n assert rep_entries[i].lines == a_entries[i].lines\n\n def test_itemreport_outcomes(self, testdir):\n \"\"\"\n This test came originally from test_remote.py in xdist (ca03269).\n \"\"\"\n reprec = testdir.inline_runsource(\n \"\"\"\n import py\n def test_pass(): pass\n def test_fail(): 0/0\n @py.test.mark.skipif(\"True\")\n def test_skip(): pass\n def test_skip_imperative():\n py.test.skip(\"hello\")\n @py.test.mark.xfail(\"True\")\n def test_xfail(): 0/0\n def test_xfail_imperative():\n py.test.xfail(\"hello\")\n \"\"\"\n )\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 17 # with setup/teardown \"passed\" reports\n for rep in reports:\n d = rep._to_json()\n newrep = TestReport._from_json(d)\n assert newrep.passed == rep.passed\n assert newrep.failed == rep.failed\n assert newrep.skipped == rep.skipped\n if newrep.skipped and not hasattr(newrep, \"wasxfail\"):\n assert len(newrep.longrepr) == 3\n assert newrep.outcome == rep.outcome\n assert newrep.when == rep.when\n assert newrep.keywords == rep.keywords\n if rep.failed:\n assert newrep.longreprtext == rep.longreprtext\n\n def test_collectreport_passed(self, testdir):\n \"\"\"This test came originally from test_remote.py in xdist (ca03269).\"\"\"\n reprec = testdir.inline_runsource(\"def test_func(): pass\")\n reports = reprec.getreports(\"pytest_collectreport\")\n for rep in reports:\n d = rep._to_json()\n newrep = CollectReport._from_json(d)\n assert newrep.passed == rep.passed\n assert newrep.failed == rep.failed\n assert newrep.skipped == rep.skipped\n\n def test_collectreport_fail(self, testdir):\n \"\"\"This test came originally from test_remote.py in xdist (ca03269).\"\"\"\n reprec = testdir.inline_runsource(\"qwe abc\")\n reports = reprec.getreports(\"pytest_collectreport\")\n assert reports\n for rep in reports:\n d = rep._to_json()\n newrep = CollectReport._from_json(d)\n assert newrep.passed == rep.passed\n assert newrep.failed == rep.failed\n assert newrep.skipped == rep.skipped\n if rep.failed:\n assert newrep.longrepr == str(rep.longrepr)\n\n def test_extended_report_deserialization(self, testdir):\n \"\"\"This test came originally from test_remote.py in xdist (ca03269).\"\"\"\n reprec = testdir.inline_runsource(\"qwe abc\")\n reports = reprec.getreports(\"pytest_collectreport\")\n assert reports\n for rep in reports:\n rep.extra = True\n d = rep._to_json()\n newrep = CollectReport._from_json(d)\n assert newrep.extra\n assert newrep.passed == rep.passed\n assert newrep.failed == rep.failed\n assert newrep.skipped == rep.skipped\n if rep.failed:\n assert newrep.longrepr == str(rep.longrepr)\n\n def test_paths_support(self, testdir):\n \"\"\"Report attributes which are py.path or pathlib objects should become strings.\"\"\"\n testdir.makepyfile(\n \"\"\"\n def test_a():\n assert False\n \"\"\"\n )\n reprec = testdir.inline_run()\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 3\n test_a_call = reports[1]\n test_a_call.path1 = testdir.tmpdir\n test_a_call.path2 = Path(testdir.tmpdir)\n data = test_a_call._to_json()\n assert data[\"path1\"] == str(testdir.tmpdir)\n assert data[\"path2\"] == str(testdir.tmpdir)\n\n def test_unserialization_failure(self, testdir):\n \"\"\"Check handling of failure during unserialization of report types.\"\"\"\n testdir.makepyfile(\n \"\"\"\n def test_a():\n assert False\n \"\"\"\n )\n reprec = testdir.inline_run()\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 3\n test_a_call = reports[1]\n data = test_a_call._to_json()\n entry = data[\"longrepr\"][\"reprtraceback\"][\"reprentries\"][0]\n assert entry[\"type\"] == \"ReprEntry\"\n\n entry[\"type\"] = \"Unknown\"\n with pytest.raises(\n RuntimeError, match=\"INTERNALERROR: Unknown entry type returned: Unknown\"\n ):\n TestReport._from_json(data)"},{"col":4,"comment":"\n Regarding issue pytest-xdist#241\n\n This test came originally from test_remote.py in xdist (ca03269).\n ","endLoc":31,"header":"def test_xdist_longrepr_to_str_issue_241(self, testdir)","id":4101,"name":"test_xdist_longrepr_to_str_issue_241","nodeType":"Function","startLoc":9,"text":"def test_xdist_longrepr_to_str_issue_241(self, testdir):\n \"\"\"\n Regarding issue pytest-xdist#241\n\n This test came originally from test_remote.py in xdist (ca03269).\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n def test_a(): assert False\n def test_b(): pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 6\n test_a_call = reports[1]\n assert test_a_call.when == \"call\"\n assert test_a_call.outcome == \"failed\"\n assert test_a_call._to_json()[\"longrepr\"][\"reprtraceback\"][\"style\"] == \"long\"\n test_b_call = reports[4]\n assert test_b_call.when == \"call\"\n assert test_b_call.outcome == \"passed\"\n assert test_b_call._to_json()[\"longrepr\"] is None"},{"col":4,"comment":"null","endLoc":185,"header":"def __setattr__(self, attr, val)","id":4102,"name":"__setattr__","nodeType":"Function","startLoc":183,"text":"def __setattr__(self, attr, val):\n warnings.warn(PYTEST_CONFIG_GLOBAL, stacklevel=2)\n return setattr(self._config, attr, val)"},{"col":4,"comment":"null","endLoc":672,"header":"def test_custom_repr_non_ascii(self)","id":4103,"name":"test_custom_repr_non_ascii","nodeType":"Function","startLoc":659,"text":"def test_custom_repr_non_ascii(self):\n def f():\n class A(object):\n name = u\"ä\"\n\n def __repr__(self):\n return self.name.encode(\"UTF-8\") # only legal in python2\n\n a = A()\n assert not a.name\n\n msg = getmsg(f)\n assert \"UnicodeDecodeError\" not in msg\n assert \"UnicodeEncodeError\" not in msg"},{"col":4,"comment":"null","endLoc":188,"header":"def __repr__(self)","id":4104,"name":"__repr__","nodeType":"Function","startLoc":187,"text":"def __repr__(self):\n return \"{}({!r})\".format(type(self).__name__, self._config)"},{"col":4,"comment":"null","endLoc":90,"header":"def test_config_cache(self, testdir)","id":4105,"name":"test_config_cache","nodeType":"Function","startLoc":74,"text":"def test_config_cache(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_configure(config):\n # see that we get cache information early on\n assert hasattr(config, \"cache\")\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_session(pytestconfig):\n assert hasattr(pytestconfig, \"cache\")\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":4,"comment":"Regarding issue pytest-xdist#130\n\n This test came originally from test_remote.py in xdist (ca03269).\n ","endLoc":66,"header":"def test_xdist_report_longrepr_reprcrash_130(self, testdir)","id":4106,"name":"test_xdist_report_longrepr_reprcrash_130","nodeType":"Function","startLoc":33,"text":"def test_xdist_report_longrepr_reprcrash_130(self, testdir):\n \"\"\"Regarding issue pytest-xdist#130\n\n This test came originally from test_remote.py in xdist (ca03269).\n \"\"\"\n reprec = testdir.inline_runsource(\n \"\"\"\n def test_fail():\n assert False, 'Expected Message'\n \"\"\"\n )\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 3\n rep = reports[1]\n added_section = (\"Failure Metadata\", str(\"metadata metadata\"), \"*\")\n rep.longrepr.sections.append(added_section)\n d = rep._to_json()\n a = TestReport._from_json(d)\n # Check assembled == rep\n assert a.__dict__.keys() == rep.__dict__.keys()\n for key in rep.__dict__.keys():\n if key != \"longrepr\":\n assert getattr(a, key) == getattr(rep, key)\n assert rep.longrepr.reprcrash.lineno == a.longrepr.reprcrash.lineno\n assert rep.longrepr.reprcrash.message == a.longrepr.reprcrash.message\n assert rep.longrepr.reprcrash.path == a.longrepr.reprcrash.path\n assert rep.longrepr.reprtraceback.entrysep == a.longrepr.reprtraceback.entrysep\n assert (\n rep.longrepr.reprtraceback.extraline == a.longrepr.reprtraceback.extraline\n )\n assert rep.longrepr.reprtraceback.style == a.longrepr.reprtraceback.style\n assert rep.longrepr.sections == a.longrepr.sections\n # Missing section attribute PR171\n assert added_section in a.longrepr.sections"},{"col":4,"comment":"null","endLoc":106,"header":"def test_group_addoption_conflict(self)","id":4107,"name":"test_group_addoption_conflict","nodeType":"Function","startLoc":101,"text":"def test_group_addoption_conflict(self):\n group = parseopt.OptionGroup(\"hello again\")\n group.addoption(\"--option1\", \"--option-1\", action=\"store_true\")\n with pytest.raises(ValueError) as err:\n group.addoption(\"--option1\", \"--option-one\", action=\"store_true\")\n assert str({\"--option1\"}) in str(err.value)"},{"col":4,"comment":"null","endLoc":107,"header":"def test_cachefuncarg(self, testdir)","id":4108,"name":"test_cachefuncarg","nodeType":"Function","startLoc":92,"text":"def test_cachefuncarg(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_cachefuncarg(cache):\n val = cache.get(\"some/thing\", None)\n assert val is None\n cache.set(\"some/thing\", [1])\n pytest.raises(TypeError, lambda: cache.get(\"some/thing\"))\n val = cache.get(\"some/thing\", [])\n assert val == [1]\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":4,"comment":"null","endLoc":388,"header":"def test_pdb_set_trace_kwargs(self, testdir)","id":4109,"name":"test_pdb_set_trace_kwargs","nodeType":"Function","startLoc":367,"text":"def test_pdb_set_trace_kwargs(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1():\n i = 0\n print(\"hello17\")\n pytest.set_trace(header=\"== my_header ==\")\n x = 3\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"== my_header ==\")\n assert \"PDB set_trace\" not in child.before.decode()\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n rest = child.read().decode(\"utf-8\")\n assert \"1 failed\" in rest\n assert \"def test_1\" in rest\n assert \"hello17\" in rest # out is captured\n self.flush(child)"},{"attributeType":"null","col":4,"comment":"null","endLoc":286,"id":4110,"name":"__test__","nodeType":"Attribute","startLoc":286,"text":"__test__"},{"attributeType":"null","col":8,"comment":"null","endLoc":333,"id":4111,"name":"duration","nodeType":"Attribute","startLoc":333,"text":"self.duration"},{"col":4,"comment":"null","endLoc":121,"header":"def test_custom_rel_cache_dir(self, testdir)","id":4112,"name":"test_custom_rel_cache_dir","nodeType":"Function","startLoc":109,"text":"def test_custom_rel_cache_dir(self, testdir):\n rel_cache_dir = os.path.join(\"custom_cache_dir\", \"subdir\")\n testdir.makeini(\n \"\"\"\n [pytest]\n cache_dir = {cache_dir}\n \"\"\".format(\n cache_dir=rel_cache_dir\n )\n )\n testdir.makepyfile(test_errored=\"def test_error():\\n assert False\")\n testdir.runpytest()\n assert testdir.tmpdir.join(rel_cache_dir).isdir()"},{"className":"FSHookProxy","col":0,"comment":"null","endLoc":394,"id":4113,"nodeType":"Class","startLoc":385,"text":"class FSHookProxy(object):\n def __init__(self, fspath, pm, remove_mods):\n self.fspath = fspath\n self.pm = pm\n self.remove_mods = remove_mods\n\n def __getattr__(self, name):\n x = self.pm.subset_hook_caller(name, remove_plugins=self.remove_mods)\n self.__dict__[name] = x\n return x"},{"col":4,"comment":"null","endLoc":394,"header":"def __getattr__(self, name)","id":4114,"name":"__getattr__","nodeType":"Function","startLoc":391,"text":"def __getattr__(self, name):\n x = self.pm.subset_hook_caller(name, remove_plugins=self.remove_mods)\n self.__dict__[name] = x\n return x"},{"className":"TestRewriteOnImport","col":0,"comment":"null","endLoc":919,"id":4115,"nodeType":"Class","startLoc":675,"text":"class TestRewriteOnImport(object):\n def test_pycache_is_a_file(self, testdir):\n testdir.tmpdir.join(\"__pycache__\").write(\"Hello\")\n testdir.makepyfile(\n \"\"\"\n def test_rewritten():\n assert \"@py_builtins\" in globals()\"\"\"\n )\n assert testdir.runpytest().ret == 0\n\n def test_pycache_is_readonly(self, testdir):\n cache = testdir.tmpdir.mkdir(\"__pycache__\")\n old_mode = cache.stat().mode\n cache.chmod(old_mode ^ stat.S_IWRITE)\n testdir.makepyfile(\n \"\"\"\n def test_rewritten():\n assert \"@py_builtins\" in globals()\"\"\"\n )\n try:\n assert testdir.runpytest().ret == 0\n finally:\n cache.chmod(old_mode)\n\n def test_zipfile(self, testdir):\n z = testdir.tmpdir.join(\"myzip.zip\")\n z_fn = str(z)\n f = zipfile.ZipFile(z_fn, \"w\")\n try:\n f.writestr(\"test_gum/__init__.py\", \"\")\n f.writestr(\"test_gum/test_lizard.py\", \"\")\n finally:\n f.close()\n z.chmod(256)\n testdir.makepyfile(\n \"\"\"\n import sys\n sys.path.append(%r)\n import test_gum.test_lizard\"\"\"\n % (z_fn,)\n )\n assert testdir.runpytest().ret == EXIT_NOTESTSCOLLECTED\n\n def test_readonly(self, testdir):\n sub = testdir.mkdir(\"testing\")\n sub.join(\"test_readonly.py\").write(\n b\"\"\"\ndef test_rewritten():\n assert \"@py_builtins\" in globals()\n \"\"\",\n \"wb\",\n )\n old_mode = sub.stat().mode\n sub.chmod(320)\n try:\n assert testdir.runpytest().ret == 0\n finally:\n sub.chmod(old_mode)\n\n def test_dont_write_bytecode(self, testdir, monkeypatch):\n testdir.makepyfile(\n \"\"\"\n import os\n def test_no_bytecode():\n assert \"__pycache__\" in __cached__\n assert not os.path.exists(__cached__)\n assert not os.path.exists(os.path.dirname(__cached__))\"\"\"\n )\n monkeypatch.setenv(\"PYTHONDONTWRITEBYTECODE\", \"1\")\n assert testdir.runpytest_subprocess().ret == 0\n\n def test_orphaned_pyc_file(self, testdir):\n if sys.version_info < (3, 0) and hasattr(sys, \"pypy_version_info\"):\n pytest.skip(\"pypy2 doesn't run orphaned pyc files\")\n\n testdir.makepyfile(\n \"\"\"\n import orphan\n def test_it():\n assert orphan.value == 17\n \"\"\"\n )\n testdir.makepyfile(\n orphan=\"\"\"\n value = 17\n \"\"\"\n )\n py_compile.compile(\"orphan.py\")\n os.remove(\"orphan.py\")\n\n # Python 3 puts the .pyc files in a __pycache__ directory, and will\n # not import from there without source. It will import a .pyc from\n # the source location though.\n if not os.path.exists(\"orphan.pyc\"):\n pycs = glob.glob(\"__pycache__/orphan.*.pyc\")\n assert len(pycs) == 1\n os.rename(pycs[0], \"orphan.pyc\")\n\n assert testdir.runpytest().ret == 0\n\n @pytest.mark.skipif('\"__pypy__\" in sys.modules')\n def test_pyc_vs_pyo(self, testdir, monkeypatch):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_optimized():\n \"hello\"\n assert test_optimized.__doc__ is None\"\"\"\n )\n p = py.path.local.make_numbered_dir(\n prefix=\"runpytest-\", keep=None, rootdir=testdir.tmpdir\n )\n tmp = \"--basetemp=%s\" % p\n monkeypatch.setenv(\"PYTHONOPTIMIZE\", \"2\")\n monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", raising=False)\n assert testdir.runpytest_subprocess(tmp).ret == 0\n tagged = \"test_pyc_vs_pyo.\" + PYTEST_TAG\n assert tagged + \".pyo\" in os.listdir(\"__pycache__\")\n monkeypatch.undo()\n monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", raising=False)\n assert testdir.runpytest_subprocess(tmp).ret == 1\n assert tagged + \".pyc\" in os.listdir(\"__pycache__\")\n\n def test_package(self, testdir):\n pkg = testdir.tmpdir.join(\"pkg\")\n pkg.mkdir()\n pkg.join(\"__init__.py\").ensure()\n pkg.join(\"test_blah.py\").write(\n \"\"\"\ndef test_rewritten():\n assert \"@py_builtins\" in globals()\"\"\"\n )\n assert testdir.runpytest().ret == 0\n\n def test_translate_newlines(self, testdir):\n content = \"def test_rewritten():\\r\\n assert '@py_builtins' in globals()\"\n b = content.encode(\"utf-8\")\n testdir.tmpdir.join(\"test_newlines.py\").write(b, \"wb\")\n assert testdir.runpytest().ret == 0\n\n @pytest.mark.skipif(\n sys.version_info < (3, 4),\n reason=\"packages without __init__.py not supported on python 2\",\n )\n def test_package_without__init__py(self, testdir):\n pkg = testdir.mkdir(\"a_package_without_init_py\")\n pkg.join(\"module.py\").ensure()\n testdir.makepyfile(\"import a_package_without_init_py.module\")\n assert testdir.runpytest().ret == EXIT_NOTESTSCOLLECTED\n\n def test_rewrite_warning(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n pytest.register_assert_rewrite(\"_pytest\")\n \"\"\"\n )\n # needs to be a subprocess because pytester explicitly disables this warning\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*Module already imported*: _pytest\"])\n\n def test_rewrite_module_imported_from_conftest(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import test_rewrite_module_imported\n \"\"\"\n )\n testdir.makepyfile(\n test_rewrite_module_imported=\"\"\"\n def test_rewritten():\n assert \"@py_builtins\" in globals()\n \"\"\"\n )\n assert testdir.runpytest_subprocess().ret == 0\n\n def test_remember_rewritten_modules(self, pytestconfig, testdir, monkeypatch):\n \"\"\"\n AssertionRewriteHook should remember rewritten modules so it\n doesn't give false positives (#2005).\n \"\"\"\n monkeypatch.syspath_prepend(testdir.tmpdir)\n testdir.makepyfile(test_remember_rewritten_modules=\"\")\n warnings = []\n hook = AssertionRewritingHook(pytestconfig)\n monkeypatch.setattr(\n hook, \"_warn_already_imported\", lambda code, msg: warnings.append(msg)\n )\n hook.find_module(\"test_remember_rewritten_modules\")\n hook.load_module(\"test_remember_rewritten_modules\")\n hook.mark_rewrite(\"test_remember_rewritten_modules\")\n hook.mark_rewrite(\"test_remember_rewritten_modules\")\n assert warnings == []\n\n def test_rewrite_warning_using_pytest_plugins(self, testdir):\n testdir.makepyfile(\n **{\n \"conftest.py\": \"pytest_plugins = ['core', 'gui', 'sci']\",\n \"core.py\": \"\",\n \"gui.py\": \"pytest_plugins = ['core', 'sci']\",\n \"sci.py\": \"pytest_plugins = ['core']\",\n \"test_rewrite_warning_pytest_plugins.py\": \"def test(): pass\",\n }\n )\n testdir.chdir()\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*= 1 passed in *=*\"])\n assert \"pytest-warning summary\" not in result.stdout.str()\n\n def test_rewrite_warning_using_pytest_plugins_env_var(self, testdir, monkeypatch):\n monkeypatch.setenv(\"PYTEST_PLUGINS\", \"plugin\")\n testdir.makepyfile(\n **{\n \"plugin.py\": \"\",\n \"test_rewrite_warning_using_pytest_plugins_env_var.py\": \"\"\"\n import plugin\n pytest_plugins = ['plugin']\n def test():\n pass\n \"\"\",\n }\n )\n testdir.chdir()\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*= 1 passed in *=*\"])\n assert \"pytest-warning summary\" not in result.stdout.str()\n\n @pytest.mark.skipif(sys.version_info[0] > 2, reason=\"python 2 only\")\n def test_rewrite_future_imports(self, testdir):\n \"\"\"Test that rewritten modules don't inherit the __future__ flags\n from the assertrewrite module.\n\n assertion.rewrite imports __future__.division (and others), so\n ensure rewritten modules don't inherit those flags.\n\n The test below will fail if __future__.division is enabled\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n def test():\n x = 1 / 2\n assert type(x) is int\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0"},{"col":4,"comment":"null","endLoc":144,"header":"def suspend(self, in_=False)","id":4116,"name":"suspend","nodeType":"Function","startLoc":141,"text":"def suspend(self, in_=False):\n # Need to undo local capsys-et-al if it exists before disabling global capture.\n self.suspend_fixture(self._current_item)\n self.suspend_global_capture(in_)"},{"col":4,"comment":"null","endLoc":683,"header":"def test_pycache_is_a_file(self, testdir)","id":4117,"name":"test_pycache_is_a_file","nodeType":"Function","startLoc":676,"text":"def test_pycache_is_a_file(self, testdir):\n testdir.tmpdir.join(\"__pycache__\").write(\"Hello\")\n testdir.makepyfile(\n \"\"\"\n def test_rewritten():\n assert \"@py_builtins\" in globals()\"\"\"\n )\n assert testdir.runpytest().ret == 0"},{"attributeType":"null","col":8,"comment":"null","endLoc":311,"id":4118,"name":"keywords","nodeType":"Attribute","startLoc":311,"text":"self.keywords"},{"className":"TestAssertionWarnings","col":0,"comment":"null","endLoc":687,"id":4119,"nodeType":"Class","startLoc":630,"text":"class TestAssertionWarnings:\n @staticmethod\n def assert_result_warns(result, msg):\n result.stdout.fnmatch_lines([\"*PytestAssertRewriteWarning: %s*\" % msg])\n\n def test_tuple_warning(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert (1,2)\n \"\"\"\n )\n result = testdir.runpytest()\n self.assert_result_warns(\n result, \"assertion is always true, perhaps remove parentheses?\"\n )\n\n @staticmethod\n def create_file(testdir, return_none):\n testdir.makepyfile(\n \"\"\"\n def foo(return_none):\n if return_none:\n return None\n else:\n return False\n\n def test_foo():\n assert foo({return_none})\n \"\"\".format(\n return_none=return_none\n )\n )\n\n def test_none_function_warns(self, testdir):\n self.create_file(testdir, True)\n result = testdir.runpytest()\n self.assert_result_warns(\n result, 'asserting the value None, please use \"assert is None\"'\n )\n\n def test_assert_is_none_no_warn(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def foo():\n return None\n\n def test_foo():\n assert foo() is None\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed in*\"])\n\n def test_false_function_no_warn(self, testdir):\n self.create_file(testdir, False)\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 failed in*\"])"},{"col":4,"comment":"null","endLoc":633,"header":"@staticmethod\n def assert_result_warns(result, msg)","id":4120,"name":"assert_result_warns","nodeType":"Function","startLoc":631,"text":"@staticmethod\n def assert_result_warns(result, msg):\n result.stdout.fnmatch_lines([\"*PytestAssertRewriteWarning: %s*\" % msg])"},{"col":4,"comment":"null","endLoc":697,"header":"def test_pycache_is_readonly(self, testdir)","id":4121,"name":"test_pycache_is_readonly","nodeType":"Function","startLoc":685,"text":"def test_pycache_is_readonly(self, testdir):\n cache = testdir.tmpdir.mkdir(\"__pycache__\")\n old_mode = cache.stat().mode\n cache.chmod(old_mode ^ stat.S_IWRITE)\n testdir.makepyfile(\n \"\"\"\n def test_rewritten():\n assert \"@py_builtins\" in globals()\"\"\"\n )\n try:\n assert testdir.runpytest().ret == 0\n finally:\n cache.chmod(old_mode)"},{"attributeType":"null","col":8,"comment":"null","endLoc":389,"id":4122,"name":"remove_mods","nodeType":"Attribute","startLoc":389,"text":"self.remove_mods"},{"col":4,"comment":"null","endLoc":645,"header":"def test_tuple_warning(self, testdir)","id":4123,"name":"test_tuple_warning","nodeType":"Function","startLoc":635,"text":"def test_tuple_warning(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert (1,2)\n \"\"\"\n )\n result = testdir.runpytest()\n self.assert_result_warns(\n result, \"assertion is always true, perhaps remove parentheses?\"\n )"},{"attributeType":"null","col":8,"comment":"null","endLoc":324,"id":4124,"name":"user_properties","nodeType":"Attribute","startLoc":324,"text":"self.user_properties"},{"attributeType":"null","col":8,"comment":"null","endLoc":387,"id":4125,"name":"fspath","nodeType":"Attribute","startLoc":387,"text":"self.fspath"},{"col":4,"comment":"null","endLoc":716,"header":"def test_zipfile(self, testdir)","id":4126,"name":"test_zipfile","nodeType":"Function","startLoc":699,"text":"def test_zipfile(self, testdir):\n z = testdir.tmpdir.join(\"myzip.zip\")\n z_fn = str(z)\n f = zipfile.ZipFile(z_fn, \"w\")\n try:\n f.writestr(\"test_gum/__init__.py\", \"\")\n f.writestr(\"test_gum/test_lizard.py\", \"\")\n finally:\n f.close()\n z.chmod(256)\n testdir.makepyfile(\n \"\"\"\n import sys\n sys.path.append(%r)\n import test_gum.test_lizard\"\"\"\n % (z_fn,)\n )\n assert testdir.runpytest().ret == EXIT_NOTESTSCOLLECTED"},{"attributeType":"null","col":8,"comment":"null","endLoc":317,"id":4127,"name":"longrepr","nodeType":"Attribute","startLoc":317,"text":"self.longrepr"},{"col":4,"comment":"null","endLoc":662,"header":"@staticmethod\n def create_file(testdir, return_none)","id":4128,"name":"create_file","nodeType":"Function","startLoc":647,"text":"@staticmethod\n def create_file(testdir, return_none):\n testdir.makepyfile(\n \"\"\"\n def foo(return_none):\n if return_none:\n return None\n else:\n return False\n\n def test_foo():\n assert foo({return_none})\n \"\"\".format(\n return_none=return_none\n )\n )"},{"attributeType":"null","col":8,"comment":"null","endLoc":388,"id":4129,"name":"pm","nodeType":"Attribute","startLoc":388,"text":"self.pm"},{"className":"NoMatch","col":0,"comment":" raised if matching cannot locate a matching names. ","endLoc":398,"id":4130,"nodeType":"Class","startLoc":397,"text":"class NoMatch(Exception):\n \"\"\" raised if matching cannot locate a matching names. \"\"\""},{"className":"Interrupted","col":0,"comment":" signals an interrupted test run. ","endLoc":404,"id":4131,"nodeType":"Class","startLoc":401,"text":"class Interrupted(KeyboardInterrupt):\n \"\"\" signals an interrupted test run. \"\"\"\n\n __module__ = \"builtins\" # for py3"},{"className":"KeyboardInterrupt","col":0,"comment":"null","endLoc":1942,"id":4132,"nodeType":"Class","startLoc":1942,"text":"class KeyboardInterrupt(BaseException): ..."},{"col":4,"comment":"null","endLoc":172,"header":"def suspend_fixture(self, item)","id":4133,"name":"suspend_fixture","nodeType":"Function","startLoc":169,"text":"def suspend_fixture(self, item):\n fixture = getattr(item, \"_capture_fixture\", None)\n if fixture is not None:\n fixture._suspend()"},{"attributeType":"str","col":4,"comment":"null","endLoc":404,"id":4134,"name":"__module__","nodeType":"Attribute","startLoc":404,"text":"__module__"},{"className":"Failed","col":0,"comment":" signals a stop as failed test run. ","endLoc":408,"id":4135,"nodeType":"Class","startLoc":407,"text":"class Failed(Exception):\n \"\"\" signals a stop as failed test run. \"\"\""},{"col":4,"comment":"null","endLoc":669,"header":"def test_none_function_warns(self, testdir)","id":4136,"name":"test_none_function_warns","nodeType":"Function","startLoc":664,"text":"def test_none_function_warns(self, testdir):\n self.create_file(testdir, True)\n result = testdir.runpytest()\n self.assert_result_warns(\n result, 'asserting the value None, please use \"assert is None\"'\n )"},{"className":"_bestrelpath_cache","col":0,"comment":"null","endLoc":418,"id":4137,"nodeType":"Class","startLoc":411,"text":"@attr.s\nclass _bestrelpath_cache(dict):\n path = attr.ib()\n\n def __missing__(self, path):\n r = self.path.bestrelpath(path)\n self[path] = r\n return r"},{"attributeType":"null","col":8,"comment":"null","endLoc":307,"id":4138,"name":"location","nodeType":"Attribute","startLoc":307,"text":"self.location"},{"className":"dict","col":0,"comment":"null","endLoc":1134,"id":4139,"nodeType":"Class","startLoc":1063,"text":"class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]):\n # __init__ should be kept roughly in line with `collections.UserDict.__init__`, which has similar semantics\n # Also multiprocessing.managers.SyncManager.dict()\n @overload\n def __init__(self) -> None: ...\n @overload\n def __init__(self: dict[str, _VT], **kwargs: _VT) -> None: ...\n @overload\n def __init__(self, __map: SupportsKeysAndGetItem[_KT, _VT]) -> None: ...\n @overload\n def __init__(self: dict[str, _VT], __map: SupportsKeysAndGetItem[str, _VT], **kwargs: _VT) -> None: ...\n @overload\n def __init__(self, __iterable: Iterable[tuple[_KT, _VT]]) -> None: ...\n @overload\n def __init__(self: dict[str, _VT], __iterable: Iterable[tuple[str, _VT]], **kwargs: _VT) -> None: ...\n # Next two overloads are for dict(string.split(sep) for string in iterable)\n # Cannot be Iterable[Sequence[_T]] or otherwise dict([\"foo\", \"bar\", \"baz\"]) is not an error\n @overload\n def __init__(self: dict[str, str], __iterable: Iterable[list[str]]) -> None: ...\n @overload\n def __init__(self: dict[bytes, bytes], __iterable: Iterable[list[bytes]]) -> None: ...\n def __new__(cls, *args: Any, **kwargs: Any) -> Self: ...\n def copy(self) -> dict[_KT, _VT]: ...\n def keys(self) -> dict_keys[_KT, _VT]: ...\n def values(self) -> dict_values[_KT, _VT]: ...\n def items(self) -> dict_items[_KT, _VT]: ...\n # Signature of `dict.fromkeys` should be kept identical to `fromkeys` methods of `OrderedDict`/`ChainMap`/`UserDict` in `collections`\n # TODO: the true signature of `dict.fromkeys` is not expressible in the current type system.\n # See #3800 & https://github.com/python/typing/issues/548#issuecomment-683336963.\n @classmethod\n @overload\n def fromkeys(cls, __iterable: Iterable[_T], __value: None = None) -> dict[_T, Any | None]: ...\n @classmethod\n @overload\n def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> dict[_T, _S]: ...\n # Positional-only in dict, but not in MutableMapping\n @overload # type: ignore[override]\n def get(self, __key: _KT) -> _VT | None: ...\n @overload\n def get(self, __key: _KT, __default: _VT) -> _VT: ...\n @overload\n def get(self, __key: _KT, __default: _T) -> _VT | _T: ...\n @overload\n def pop(self, __key: _KT) -> _VT: ...\n @overload\n def pop(self, __key: _KT, __default: _VT) -> _VT: ...\n @overload\n def pop(self, __key: _KT, __default: _T) -> _VT | _T: ...\n def __len__(self) -> int: ...\n def __getitem__(self, __key: _KT) -> _VT: ...\n def __setitem__(self, __key: _KT, __value: _VT) -> None: ...\n def __delitem__(self, __key: _KT) -> None: ...\n def __iter__(self) -> Iterator[_KT]: ...\n def __eq__(self, __value: object) -> bool: ...\n if sys.version_info >= (3, 8):\n def __reversed__(self) -> Iterator[_KT]: ...\n __hash__: ClassVar[None] # type: ignore[assignment]\n if sys.version_info >= (3, 9):\n def __class_getitem__(cls, __item: Any) -> GenericAlias: ...\n @overload\n def __or__(self, __value: dict[_KT, _VT]) -> dict[_KT, _VT]: ...\n @overload\n def __or__(self, __value: dict[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ...\n @overload\n def __ror__(self, __value: dict[_KT, _VT]) -> dict[_KT, _VT]: ...\n @overload\n def __ror__(self, __value: dict[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ...\n # dict.__ior__ should be kept roughly in line with MutableMapping.update()\n @overload # type: ignore[misc]\n def __ior__(self, __value: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ...\n @overload\n def __ior__(self, __value: Iterable[tuple[_KT, _VT]]) -> Self: ..."},{"attributeType":"null","col":8,"comment":"null","endLoc":302,"id":4140,"name":"nodeid","nodeType":"Attribute","startLoc":302,"text":"self.nodeid"},{"attributeType":"null","col":8,"comment":"null","endLoc":320,"id":4141,"name":"when","nodeType":"Attribute","startLoc":320,"text":"self.when"},{"col":4,"comment":"null","endLoc":682,"header":"def test_assert_is_none_no_warn(self, testdir)","id":4142,"name":"test_assert_is_none_no_warn","nodeType":"Function","startLoc":671,"text":"def test_assert_is_none_no_warn(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def foo():\n return None\n\n def test_foo():\n assert foo() is None\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed in*\"])"},{"attributeType":"null","col":8,"comment":"null","endLoc":314,"id":4143,"name":"outcome","nodeType":"Attribute","startLoc":314,"text":"self.outcome"},{"col":4,"comment":"Regarding issue pytest-xdist#170\n\n This test came originally from test_remote.py in xdist (ca03269).\n ","endLoc":101,"header":"def test_reprentries_serialization_170(self, testdir)","id":4144,"name":"test_reprentries_serialization_170","nodeType":"Function","startLoc":68,"text":"def test_reprentries_serialization_170(self, testdir):\n \"\"\"Regarding issue pytest-xdist#170\n\n This test came originally from test_remote.py in xdist (ca03269).\n \"\"\"\n from _pytest._code.code import ReprEntry\n\n reprec = testdir.inline_runsource(\n \"\"\"\n def test_repr_entry():\n x = 0\n assert x\n \"\"\",\n \"--showlocals\",\n )\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 3\n rep = reports[1]\n d = rep._to_json()\n a = TestReport._from_json(d)\n\n rep_entries = rep.longrepr.reprtraceback.reprentries\n a_entries = a.longrepr.reprtraceback.reprentries\n for i in range(len(a_entries)):\n assert isinstance(rep_entries[i], ReprEntry)\n assert rep_entries[i].lines == a_entries[i].lines\n assert rep_entries[i].reprfileloc.lineno == a_entries[i].reprfileloc.lineno\n assert (\n rep_entries[i].reprfileloc.message == a_entries[i].reprfileloc.message\n )\n assert rep_entries[i].reprfileloc.path == a_entries[i].reprfileloc.path\n assert rep_entries[i].reprfuncargs.args == a_entries[i].reprfuncargs.args\n assert rep_entries[i].reprlocals.lines == a_entries[i].reprlocals.lines\n assert rep_entries[i].style == a_entries[i].style"},{"col":4,"comment":"null","endLoc":687,"header":"def test_false_function_no_warn(self, testdir)","id":4145,"name":"test_false_function_no_warn","nodeType":"Function","startLoc":684,"text":"def test_false_function_no_warn(self, testdir):\n self.create_file(testdir, False)\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 failed in*\"])"},{"attributeType":"null","col":8,"comment":"null","endLoc":330,"id":4146,"name":"sections","nodeType":"Attribute","startLoc":330,"text":"self.sections"},{"col":4,"comment":"null","endLoc":1084,"header":"def __new__(cls, *args: Any, **kwargs: Any) -> Self","id":4147,"name":"__new__","nodeType":"Function","startLoc":1084,"text":"def __new__(cls, *args: Any, **kwargs: Any) -> Self: ..."},{"col":4,"comment":"null","endLoc":1087,"header":"def values(self) -> dict_values[_KT, _VT]","id":4148,"name":"values","nodeType":"Function","startLoc":1087,"text":"def values(self) -> dict_values[_KT, _VT]: ..."},{"col":4,"comment":"null","endLoc":1111,"header":"def __len__(self) -> int","id":4149,"name":"__len__","nodeType":"Function","startLoc":1111,"text":"def __len__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":1112,"header":"def __getitem__(self, __key: _KT) -> _VT","id":4150,"name":"__getitem__","nodeType":"Function","startLoc":1112,"text":"def __getitem__(self, __key: _KT) -> _VT: ..."},{"col":4,"comment":"null","endLoc":1113,"header":"def __setitem__(self, __key: _KT, __value: _VT) -> None","id":4151,"name":"__setitem__","nodeType":"Function","startLoc":1113,"text":"def __setitem__(self, __key: _KT, __value: _VT) -> None: ..."},{"col":4,"comment":"null","endLoc":1114,"header":"def __delitem__(self, __key: _KT) -> None","id":4152,"name":"__delitem__","nodeType":"Function","startLoc":1114,"text":"def __delitem__(self, __key: _KT) -> None: ..."},{"col":4,"comment":"null","endLoc":1115,"header":"def __iter__(self) -> Iterator[_KT]","id":4153,"name":"__iter__","nodeType":"Function","startLoc":1115,"text":"def __iter__(self) -> Iterator[_KT]: ..."},{"col":4,"comment":"null","endLoc":1116,"header":"def __eq__(self, __value: object) -> bool","id":4154,"name":"__eq__","nodeType":"Function","startLoc":1116,"text":"def __eq__(self, __value: object) -> bool: ..."},{"col":8,"comment":"null","endLoc":1118,"header":"def __reversed__(self) -> Iterator[_KT]","id":4155,"name":"__reversed__","nodeType":"Function","startLoc":1118,"text":"def __reversed__(self) -> Iterator[_KT]: ..."},{"col":8,"comment":"null","endLoc":1121,"header":"def __class_getitem__(cls, __item: Any) -> GenericAlias","id":4156,"name":"__class_getitem__","nodeType":"Function","startLoc":1121,"text":"def __class_getitem__(cls, __item: Any) -> GenericAlias: ..."},{"col":8,"comment":"null","endLoc":1123,"header":"@overload\n def __or__(self, __value: dict[_KT, _VT]) -> dict[_KT, _VT]","id":4157,"name":"__or__","nodeType":"Function","startLoc":1122,"text":"@overload\n def __or__(self, __value: dict[_KT, _VT]) -> dict[_KT, _VT]: ..."},{"col":8,"comment":"null","endLoc":1125,"header":"@overload\n def __or__(self, __value: dict[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]","id":4158,"name":"__or__","nodeType":"Function","startLoc":1124,"text":"@overload\n def __or__(self, __value: dict[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ..."},{"col":8,"comment":"null","endLoc":1127,"header":"@overload\n def __ror__(self, __value: dict[_KT, _VT]) -> dict[_KT, _VT]","id":4159,"name":"__ror__","nodeType":"Function","startLoc":1126,"text":"@overload\n def __ror__(self, __value: dict[_KT, _VT]) -> dict[_KT, _VT]: ..."},{"col":8,"comment":"null","endLoc":1129,"header":"@overload\n def __ror__(self, __value: dict[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]","id":4160,"name":"__ror__","nodeType":"Function","startLoc":1128,"text":"@overload\n def __ror__(self, __value: dict[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ..."},{"col":8,"comment":"null","endLoc":1132,"header":"@overload # type: ignore[misc]\n def __ior__(self, __value: SupportsKeysAndGetItem[_KT, _VT]) -> Self","id":4161,"name":"__ior__","nodeType":"Function","startLoc":1131,"text":"@overload # type: ignore[misc]\n def __ior__(self, __value: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ..."},{"col":8,"comment":"null","endLoc":1134,"header":"@overload\n def __ior__(self, __value: Iterable[tuple[_KT, _VT]]) -> Self","id":4162,"name":"__ior__","nodeType":"Function","startLoc":1133,"text":"@overload\n def __ior__(self, __value: Iterable[tuple[_KT, _VT]]) -> Self: ..."},{"attributeType":"None","col":4,"comment":"null","endLoc":1119,"id":4163,"name":"__hash__","nodeType":"Attribute","startLoc":1119,"text":"__hash__"},{"col":0,"comment":"\n Create a test file which calls a function in a module which generates warnings.\n ","endLoc":39,"header":"@pytest.fixture\ndef pyfile_with_warnings(testdir, request)","id":4164,"name":"pyfile_with_warnings","nodeType":"Function","startLoc":14,"text":"@pytest.fixture\ndef pyfile_with_warnings(testdir, request):\n \"\"\"\n Create a test file which calls a function in a module which generates warnings.\n \"\"\"\n testdir.syspathinsert()\n test_name = request.function.__name__\n module_name = test_name.lstrip(\"test_\") + \"_module\"\n testdir.makepyfile(\n **{\n module_name: \"\"\"\n import warnings\n def foo():\n warnings.warn(UserWarning(\"user warning\"))\n warnings.warn(RuntimeWarning(\"runtime warning\"))\n return 1\n \"\"\",\n test_name: \"\"\"\n import {module_name}\n def test_func():\n assert {module_name}.foo() == 1\n \"\"\".format(\n module_name=module_name\n ),\n }\n )"},{"className":"CallInfo","col":0,"comment":" Result/Exception info a function invocation. ","endLoc":245,"id":4165,"nodeType":"Class","startLoc":202,"text":"@attr.s(repr=False)\nclass CallInfo(object):\n \"\"\" Result/Exception info a function invocation. \"\"\"\n\n _result = attr.ib()\n # Optional[ExceptionInfo]\n excinfo = attr.ib()\n start = attr.ib()\n stop = attr.ib()\n when = attr.ib()\n\n @property\n def result(self):\n if self.excinfo is not None:\n raise AttributeError(\"{!r} has no valid result\".format(self))\n return self._result\n\n @classmethod\n def from_call(cls, func, when, reraise=None):\n #: context of invocation: one of \"setup\", \"call\",\n #: \"teardown\", \"memocollect\"\n start = time()\n excinfo = None\n try:\n result = func()\n except: # noqa\n excinfo = ExceptionInfo.from_current()\n if reraise is not None and excinfo.errisinstance(reraise):\n raise\n result = None\n stop = time()\n return cls(start=start, stop=stop, when=when, result=result, excinfo=excinfo)\n\n def __repr__(self):\n if self.excinfo is not None:\n status = \"exception\"\n value = self.excinfo.value\n else:\n # TODO: investigate unification\n value = repr(self._result)\n status = \"result\"\n return \"\".format(\n when=self.when, value=value, status=status\n )"},{"col":4,"comment":"null","endLoc":217,"header":"@property\n def result(self)","id":4166,"name":"result","nodeType":"Function","startLoc":213,"text":"@property\n def result(self):\n if self.excinfo is not None:\n raise AttributeError(\"{!r} has no valid result\".format(self))\n return self._result"},{"col":4,"comment":"null","endLoc":418,"header":"def __missing__(self, path)","id":4167,"name":"__missing__","nodeType":"Function","startLoc":415,"text":"def __missing__(self, path):\n r = self.path.bestrelpath(path)\n self[path] = r\n return r"},{"attributeType":"null","col":4,"comment":"null","endLoc":413,"id":4168,"name":"path","nodeType":"Attribute","startLoc":413,"text":"path"},{"col":0,"comment":"null","endLoc":172,"header":"def pytest_addoption(parser)","id":4169,"name":"pytest_addoption","nodeType":"Function","startLoc":37,"text":"def pytest_addoption(parser):\n parser.addini(\n \"norecursedirs\",\n \"directory patterns to avoid for recursion\",\n type=\"args\",\n default=[\".*\", \"build\", \"dist\", \"CVS\", \"_darcs\", \"{arch}\", \"*.egg\", \"venv\"],\n )\n parser.addini(\n \"testpaths\",\n \"directories to search for tests when no files or directories are given in the \"\n \"command line.\",\n type=\"args\",\n default=[],\n )\n group = parser.getgroup(\"general\", \"running and selection options\")\n group._addoption(\n \"-x\",\n \"--exitfirst\",\n action=\"store_const\",\n dest=\"maxfail\",\n const=1,\n help=\"exit instantly on first error or failed test.\",\n ),\n group._addoption(\n \"--maxfail\",\n metavar=\"num\",\n action=\"store\",\n type=int,\n dest=\"maxfail\",\n default=0,\n help=\"exit after first num failures or errors.\",\n )\n group._addoption(\n \"--strict-markers\",\n \"--strict\",\n action=\"store_true\",\n help=\"markers not registered in the `markers` section of the configuration file raise errors.\",\n )\n group._addoption(\n \"-c\",\n metavar=\"file\",\n type=str,\n dest=\"inifilename\",\n help=\"load configuration from `file` instead of trying to locate one of the implicit \"\n \"configuration files.\",\n )\n group._addoption(\n \"--continue-on-collection-errors\",\n action=\"store_true\",\n default=False,\n dest=\"continue_on_collection_errors\",\n help=\"Force test execution even if collection errors occur.\",\n )\n group._addoption(\n \"--rootdir\",\n action=\"store\",\n dest=\"rootdir\",\n help=\"Define root directory for tests. Can be relative path: 'root_dir', './root_dir', \"\n \"'root_dir/another_dir/'; absolute path: '/home/user/root_dir'; path with variables: \"\n \"'$HOME/root_dir'.\",\n )\n\n group = parser.getgroup(\"collect\", \"collection\")\n group.addoption(\n \"--collectonly\",\n \"--collect-only\",\n action=\"store_true\",\n help=\"only collect tests, don't execute them.\",\n ),\n group.addoption(\n \"--pyargs\",\n action=\"store_true\",\n help=\"try to interpret all arguments as python packages.\",\n )\n group.addoption(\n \"--ignore\",\n action=\"append\",\n metavar=\"path\",\n help=\"ignore path during collection (multi-allowed).\",\n )\n group.addoption(\n \"--ignore-glob\",\n action=\"append\",\n metavar=\"path\",\n help=\"ignore path pattern during collection (multi-allowed).\",\n )\n group.addoption(\n \"--deselect\",\n action=\"append\",\n metavar=\"nodeid_prefix\",\n help=\"deselect item during collection (multi-allowed).\",\n )\n # when changing this to --conf-cut-dir, config.py Conftest.setinitial\n # needs upgrading as well\n group.addoption(\n \"--confcutdir\",\n dest=\"confcutdir\",\n default=None,\n metavar=\"dir\",\n type=functools.partial(directory_arg, optname=\"--confcutdir\"),\n help=\"only load conftest.py's relative to specified dir.\",\n )\n group.addoption(\n \"--noconftest\",\n action=\"store_true\",\n dest=\"noconftest\",\n default=False,\n help=\"Don't load any conftest.py files.\",\n )\n group.addoption(\n \"--keepduplicates\",\n \"--keep-duplicates\",\n action=\"store_true\",\n dest=\"keepduplicates\",\n default=False,\n help=\"Keep duplicate tests.\",\n )\n group.addoption(\n \"--collect-in-virtualenv\",\n action=\"store_true\",\n dest=\"collect_in_virtualenv\",\n default=False,\n help=\"Don't ignore tests in a local virtualenv directory\",\n )\n\n group = parser.getgroup(\"debugconfig\", \"test session debugging and configuration\")\n group.addoption(\n \"--basetemp\",\n dest=\"basetemp\",\n default=None,\n metavar=\"dir\",\n help=(\n \"base temporary directory for this test run.\"\n \"(warning: this directory is removed if it exists)\"\n ),\n )"},{"col":4,"comment":"null","endLoc":139,"header":"def suspend_global_capture(self, in_=False)","id":4170,"name":"suspend_global_capture","nodeType":"Function","startLoc":136,"text":"def suspend_global_capture(self, in_=False):\n cap = getattr(self, \"_global_capturing\", None)\n if cap is not None:\n cap.suspend_capturing(in_=in_)"},{"col":4,"comment":"null","endLoc":136,"header":"def test_custom_abs_cache_dir(self, testdir, tmpdir_factory)","id":4171,"name":"test_custom_abs_cache_dir","nodeType":"Function","startLoc":123,"text":"def test_custom_abs_cache_dir(self, testdir, tmpdir_factory):\n tmp = str(tmpdir_factory.mktemp(\"tmp\"))\n abs_cache_dir = os.path.join(tmp, \"custom_cache_dir\")\n testdir.makeini(\n \"\"\"\n [pytest]\n cache_dir = {cache_dir}\n \"\"\".format(\n cache_dir=abs_cache_dir\n )\n )\n testdir.makepyfile(test_errored=\"def test_error():\\n assert False\")\n testdir.runpytest()\n assert py.path.local(abs_cache_dir).isdir()"},{"col":0,"comment":"\n Check that the warnings section is displayed.\n ","endLoc":58,"header":"@pytest.mark.filterwarnings(\"default\")\ndef test_normal_flow(testdir, pyfile_with_warnings)","id":4172,"name":"test_normal_flow","nodeType":"Function","startLoc":42,"text":"@pytest.mark.filterwarnings(\"default\")\ndef test_normal_flow(testdir, pyfile_with_warnings):\n \"\"\"\n Check that the warnings section is displayed.\n \"\"\"\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*== %s ==*\" % WARNINGS_SUMMARY_HEADER,\n \"test_normal_flow.py::test_func\",\n \"*normal_flow_module.py:3: UserWarning: user warning\",\n '* warnings.warn(UserWarning(\"user warning\"))',\n \"*normal_flow_module.py:4: RuntimeWarning: runtime warning\",\n '* warnings.warn(RuntimeWarning(\"runtime warning\"))',\n \"* 1 passed, 2 warnings*\",\n ]\n )"},{"col":0,"comment":"null","endLoc":88,"header":"@pytest.mark.filterwarnings(\"always\")\ndef test_setup_teardown_warnings(testdir, pyfile_with_warnings)","id":4173,"name":"test_setup_teardown_warnings","nodeType":"Function","startLoc":61,"text":"@pytest.mark.filterwarnings(\"always\")\ndef test_setup_teardown_warnings(testdir, pyfile_with_warnings):\n testdir.makepyfile(\n \"\"\"\n import warnings\n import pytest\n\n @pytest.fixture\n def fix():\n warnings.warn(UserWarning(\"warning during setup\"))\n yield\n warnings.warn(UserWarning(\"warning during teardown\"))\n\n def test_func(fix):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*== %s ==*\" % WARNINGS_SUMMARY_HEADER,\n \"*test_setup_teardown_warnings.py:6: UserWarning: warning during setup\",\n '*warnings.warn(UserWarning(\"warning during setup\"))',\n \"*test_setup_teardown_warnings.py:8: UserWarning: warning during teardown\",\n '*warnings.warn(UserWarning(\"warning during teardown\"))',\n \"* 1 passed, 2 warnings*\",\n ]\n )"},{"col":0,"comment":"null","endLoc":110,"header":"@pytest.mark.parametrize(\"method\", [\"cmdline\", \"ini\"])\ndef test_as_errors(testdir, pyfile_with_warnings, method)","id":4174,"name":"test_as_errors","nodeType":"Function","startLoc":91,"text":"@pytest.mark.parametrize(\"method\", [\"cmdline\", \"ini\"])\ndef test_as_errors(testdir, pyfile_with_warnings, method):\n args = (\"-W\", \"error\") if method == \"cmdline\" else ()\n if method == \"ini\":\n testdir.makeini(\n \"\"\"\n [pytest]\n filterwarnings=error\n \"\"\"\n )\n # Use a subprocess, since changing logging level affects other threads\n # (xdist).\n result = testdir.runpytest_subprocess(*args)\n result.stdout.fnmatch_lines(\n [\n \"E UserWarning: user warning\",\n \"as_errors_module.py:3: UserWarning\",\n \"* 1 failed in *\",\n ]\n )"},{"col":4,"comment":"null","endLoc":148,"header":"def resume(self)","id":4175,"name":"resume","nodeType":"Function","startLoc":146,"text":"def resume(self):\n self.resume_global_capture()\n self.resume_fixture(self._current_item)"},{"col":4,"comment":"null","endLoc":233,"header":"@classmethod\n def from_call(cls, func, when, reraise=None)","id":4176,"name":"from_call","nodeType":"Function","startLoc":219,"text":"@classmethod\n def from_call(cls, func, when, reraise=None):\n #: context of invocation: one of \"setup\", \"call\",\n #: \"teardown\", \"memocollect\"\n start = time()\n excinfo = None\n try:\n result = func()\n except: # noqa\n excinfo = ExceptionInfo.from_current()\n if reraise is not None and excinfo.errisinstance(reraise):\n raise\n result = None\n stop = time()\n return cls(start=start, stop=stop, when=when, result=result, excinfo=excinfo)"},{"col":0,"comment":"null","endLoc":126,"header":"@pytest.mark.parametrize(\"method\", [\"cmdline\", \"ini\"])\ndef test_ignore(testdir, pyfile_with_warnings, method)","id":4177,"name":"test_ignore","nodeType":"Function","startLoc":113,"text":"@pytest.mark.parametrize(\"method\", [\"cmdline\", \"ini\"])\ndef test_ignore(testdir, pyfile_with_warnings, method):\n args = (\"-W\", \"ignore\") if method == \"cmdline\" else ()\n if method == \"ini\":\n testdir.makeini(\n \"\"\"\n [pytest]\n filterwarnings= ignore\n \"\"\"\n )\n\n result = testdir.runpytest(*args)\n result.stdout.fnmatch_lines([\"* 1 passed in *\"])\n assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()"},{"col":0,"comment":"null","endLoc":157,"header":"@pytest.mark.skipif(\n sys.version_info < (3, 0), reason=\"warnings message is unicode is ok in python3\"\n)\n@pytest.mark.filterwarnings(\"always\")\ndef test_unicode(testdir, pyfile_with_warnings)","id":4178,"name":"test_unicode","nodeType":"Function","startLoc":129,"text":"@pytest.mark.skipif(\n sys.version_info < (3, 0), reason=\"warnings message is unicode is ok in python3\"\n)\n@pytest.mark.filterwarnings(\"always\")\ndef test_unicode(testdir, pyfile_with_warnings):\n testdir.makepyfile(\n \"\"\"\n # -*- coding: utf-8 -*-\n import warnings\n import pytest\n\n\n @pytest.fixture\n def fix():\n warnings.warn(u\"测试\")\n yield\n\n def test_func(fix):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*== %s ==*\" % WARNINGS_SUMMARY_HEADER,\n \"*test_unicode.py:8: UserWarning: \\u6d4b\\u8bd5*\",\n \"* 1 passed, 1 warnings*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":406,"header":"def test_pdb_set_trace_interception(self, testdir)","id":4180,"name":"test_pdb_set_trace_interception","nodeType":"Function","startLoc":390,"text":"def test_pdb_set_trace_interception(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pdb\n def test_1():\n pdb.set_trace()\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"test_1\")\n child.expect(\"Pdb\")\n child.sendline(\"q\")\n rest = child.read().decode(\"utf8\")\n assert \"no tests ran\" in rest\n assert \"reading from stdin while output\" not in rest\n assert \"BdbQuit\" not in rest\n self.flush(child)"},{"col":4,"comment":"null","endLoc":134,"header":"def resume_global_capture(self)","id":4181,"name":"resume_global_capture","nodeType":"Function","startLoc":130,"text":"def resume_global_capture(self):\n # During teardown of the python process, and on rare occasions, capture\n # attributes can be `None` while trying to resume global capture.\n if self._global_capturing is not None:\n self._global_capturing.resume_capturing()"},{"col":0,"comment":"null","endLoc":195,"header":"@pytest.mark.skipif(\n sys.version_info >= (3, 0),\n reason=\"warnings message is broken as it is not str instance\",\n)\ndef test_py2_unicode(testdir, pyfile_with_warnings)","id":4182,"name":"test_py2_unicode","nodeType":"Function","startLoc":160,"text":"@pytest.mark.skipif(\n sys.version_info >= (3, 0),\n reason=\"warnings message is broken as it is not str instance\",\n)\ndef test_py2_unicode(testdir, pyfile_with_warnings):\n if getattr(sys, \"pypy_version_info\", ())[:2] == (5, 9) and sys.platform.startswith(\n \"win\"\n ):\n pytest.xfail(\"fails with unicode error on PyPy2 5.9 and Windows (#2905)\")\n testdir.makepyfile(\n \"\"\"\n # -*- coding: utf-8 -*-\n import warnings\n import pytest\n\n\n @pytest.fixture\n def fix():\n warnings.warn(u\"测试\")\n yield\n\n @pytest.mark.filterwarnings('always')\n def test_func(fix):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*== %s ==*\" % WARNINGS_SUMMARY_HEADER,\n \"*test_py2_unicode.py:8: UserWarning: \\\\u6d4b\\\\u8bd5\",\n '*warnings.warn(u\"\\u6d4b\\u8bd5\")',\n \"*warnings.py:*: UnicodeWarning: Warning is using unicode non*\",\n \"* 1 passed, 2 warnings*\",\n ]\n )"},{"col":0,"comment":"null","endLoc":192,"header":"def pytest_configure(config)","id":4183,"name":"pytest_configure","nodeType":"Function","startLoc":191,"text":"def pytest_configure(config):\n __import__(\"pytest\").config = _ConfigDeprecated(config) # compatibility"},{"col":0,"comment":"Skeleton command line program","endLoc":239,"header":"def wrap_session(config, doit)","id":4184,"name":"wrap_session","nodeType":"Function","startLoc":195,"text":"def wrap_session(config, doit):\n \"\"\"Skeleton command line program\"\"\"\n session = Session(config)\n session.exitstatus = EXIT_OK\n initstate = 0\n try:\n try:\n config._do_configure()\n initstate = 1\n config.hook.pytest_sessionstart(session=session)\n initstate = 2\n session.exitstatus = doit(config, session) or 0\n except UsageError:\n session.exitstatus = EXIT_USAGEERROR\n raise\n except Failed:\n session.exitstatus = EXIT_TESTSFAILED\n except (KeyboardInterrupt, exit.Exception):\n excinfo = _pytest._code.ExceptionInfo.from_current()\n exitstatus = EXIT_INTERRUPTED\n if isinstance(excinfo.value, exit.Exception):\n if excinfo.value.returncode is not None:\n exitstatus = excinfo.value.returncode\n if initstate < 2:\n sys.stderr.write(\n \"{}: {}\\n\".format(excinfo.typename, excinfo.value.msg)\n )\n config.hook.pytest_keyboard_interrupt(excinfo=excinfo)\n session.exitstatus = exitstatus\n except: # noqa\n excinfo = _pytest._code.ExceptionInfo.from_current()\n config.notify_exception(excinfo, config.option)\n session.exitstatus = EXIT_INTERNALERROR\n if excinfo.errisinstance(SystemExit):\n sys.stderr.write(\"mainloop: caught unexpected SystemExit!\\n\")\n\n finally:\n excinfo = None # Explicitly break reference cycle.\n session.startdir.chdir()\n if initstate >= 2:\n config.hook.pytest_sessionfinish(\n session=session, exitstatus=session.exitstatus\n )\n config._ensure_unconfigure()\n return session.exitstatus"},{"col":4,"comment":"null","endLoc":245,"header":"def __repr__(self)","id":4185,"name":"__repr__","nodeType":"Function","startLoc":235,"text":"def __repr__(self):\n if self.excinfo is not None:\n status = \"exception\"\n value = self.excinfo.value\n else:\n # TODO: investigate unification\n value = repr(self._result)\n status = \"result\"\n return \"\".format(\n when=self.when, value=value, status=status\n )"},{"attributeType":"null","col":4,"comment":"null","endLoc":206,"id":4186,"name":"_result","nodeType":"Attribute","startLoc":206,"text":"_result"},{"attributeType":"null","col":4,"comment":"null","endLoc":208,"id":4187,"name":"excinfo","nodeType":"Attribute","startLoc":208,"text":"excinfo"},{"attributeType":"null","col":4,"comment":"null","endLoc":209,"id":4188,"name":"start","nodeType":"Attribute","startLoc":209,"text":"start"},{"attributeType":"null","col":4,"comment":"null","endLoc":210,"id":4189,"name":"stop","nodeType":"Attribute","startLoc":210,"text":"stop"},{"attributeType":"null","col":4,"comment":"null","endLoc":211,"id":4190,"name":"when","nodeType":"Attribute","startLoc":211,"text":"when"},{"col":4,"comment":"null","endLoc":150,"header":"def test_custom_cache_dir_with_env_var(self, testdir, monkeypatch)","id":4191,"name":"test_custom_cache_dir_with_env_var","nodeType":"Function","startLoc":138,"text":"def test_custom_cache_dir_with_env_var(self, testdir, monkeypatch):\n monkeypatch.setenv(\"env_var\", \"custom_cache_dir\")\n testdir.makeini(\n \"\"\"\n [pytest]\n cache_dir = {cache_dir}\n \"\"\".format(\n cache_dir=\"$env_var\"\n )\n )\n testdir.makepyfile(test_errored=\"def test_error():\\n assert False\")\n testdir.runpytest()\n assert testdir.tmpdir.join(\"custom_cache_dir\").isdir()"},{"className":"SetupState","col":0,"comment":" shared state for setting up/tearing down test items or collectors. ","endLoc":365,"id":4192,"nodeType":"Class","startLoc":278,"text":"class SetupState(object):\n \"\"\" shared state for setting up/tearing down test items or collectors. \"\"\"\n\n def __init__(self):\n self.stack = []\n self._finalizers = {}\n\n def addfinalizer(self, finalizer, colitem):\n \"\"\" attach a finalizer to the given colitem.\n if colitem is None, this will add a finalizer that\n is called at the end of teardown_all().\n \"\"\"\n assert colitem and not isinstance(colitem, tuple)\n assert callable(finalizer)\n # assert colitem in self.stack # some unit tests don't setup stack :/\n self._finalizers.setdefault(colitem, []).append(finalizer)\n\n def _pop_and_teardown(self):\n colitem = self.stack.pop()\n self._teardown_with_finalization(colitem)\n\n def _callfinalizers(self, colitem):\n finalizers = self._finalizers.pop(colitem, None)\n exc = None\n while finalizers:\n fin = finalizers.pop()\n try:\n fin()\n except TEST_OUTCOME:\n # XXX Only first exception will be seen by user,\n # ideally all should be reported.\n if exc is None:\n exc = sys.exc_info()\n if exc:\n six.reraise(*exc)\n\n def _teardown_with_finalization(self, colitem):\n self._callfinalizers(colitem)\n if hasattr(colitem, \"teardown\"):\n colitem.teardown()\n for colitem in self._finalizers:\n assert (\n colitem is None or colitem in self.stack or isinstance(colitem, tuple)\n )\n\n def teardown_all(self):\n while self.stack:\n self._pop_and_teardown()\n for key in list(self._finalizers):\n self._teardown_with_finalization(key)\n assert not self._finalizers\n\n def teardown_exact(self, item, nextitem):\n needed_collectors = nextitem and nextitem.listchain() or []\n self._teardown_towards(needed_collectors)\n\n def _teardown_towards(self, needed_collectors):\n exc = None\n while self.stack:\n if self.stack == needed_collectors[: len(self.stack)]:\n break\n try:\n self._pop_and_teardown()\n except TEST_OUTCOME:\n # XXX Only first exception will be seen by user,\n # ideally all should be reported.\n if exc is None:\n exc = sys.exc_info()\n if exc:\n six.reraise(*exc)\n\n def prepare(self, colitem):\n \"\"\" setup objects along the collector chain to the test-method\n and teardown previously setup objects.\"\"\"\n needed_collectors = colitem.listchain()\n self._teardown_towards(needed_collectors)\n\n # check if the last collection node has raised an error\n for col in self.stack:\n if hasattr(col, \"_prepare_exc\"):\n six.reraise(*col._prepare_exc)\n for col in needed_collectors[len(self.stack) :]:\n self.stack.append(col)\n try:\n col.setup()\n except TEST_OUTCOME:\n col._prepare_exc = sys.exc_info()\n raise"},{"col":4,"comment":"null","endLoc":283,"header":"def __init__(self)","id":4193,"name":"__init__","nodeType":"Function","startLoc":281,"text":"def __init__(self):\n self.stack = []\n self._finalizers = {}"},{"col":4,"comment":" attach a finalizer to the given colitem.\n if colitem is None, this will add a finalizer that\n is called at the end of teardown_all().\n ","endLoc":293,"header":"def addfinalizer(self, finalizer, colitem)","id":4194,"name":"addfinalizer","nodeType":"Function","startLoc":285,"text":"def addfinalizer(self, finalizer, colitem):\n \"\"\" attach a finalizer to the given colitem.\n if colitem is None, this will add a finalizer that\n is called at the end of teardown_all().\n \"\"\"\n assert colitem and not isinstance(colitem, tuple)\n assert callable(finalizer)\n # assert colitem in self.stack # some unit tests don't setup stack :/\n self._finalizers.setdefault(colitem, []).append(finalizer)"},{"col":4,"comment":"null","endLoc":177,"header":"def resume_fixture(self, item)","id":4195,"name":"resume_fixture","nodeType":"Function","startLoc":174,"text":"def resume_fixture(self, item):\n fixture = getattr(item, \"_capture_fixture\", None)\n if fixture is not None:\n fixture._resume()"},{"className":"TestLastFailed","col":0,"comment":"null","endLoc":875,"id":4196,"nodeType":"Class","startLoc":244,"text":"class TestLastFailed(object):\n def test_lastfailed_usecase(self, testdir, monkeypatch):\n monkeypatch.setenv(\"PYTHONDONTWRITEBYTECODE\", \"1\")\n p = testdir.makepyfile(\n \"\"\"\n def test_1():\n assert 0\n def test_2():\n assert 0\n def test_3():\n assert 1\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 failed*\"])\n p.write(\n textwrap.dedent(\n \"\"\"\\\n def test_1():\n assert 1\n\n def test_2():\n assert 1\n\n def test_3():\n assert 0\n \"\"\"\n )\n )\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines([\"*2 passed*1 desel*\"])\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 3 items\",\n \"run-last-failure: no previously failed tests, not deselecting items.\",\n \"*1 failed*2 passed*\",\n ]\n )\n result = testdir.runpytest(\"--lf\", \"--cache-clear\")\n result.stdout.fnmatch_lines([\"*1 failed*2 passed*\"])\n\n # Run this again to make sure clear-cache is robust\n if os.path.isdir(\".pytest_cache\"):\n shutil.rmtree(\".pytest_cache\")\n result = testdir.runpytest(\"--lf\", \"--cache-clear\")\n result.stdout.fnmatch_lines([\"*1 failed*2 passed*\"])\n\n def test_failedfirst_order(self, testdir):\n testdir.tmpdir.join(\"test_a.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_always_passes():\n assert 1\n \"\"\"\n )\n )\n testdir.tmpdir.join(\"test_b.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_always_fails():\n assert 0\n \"\"\"\n )\n )\n result = testdir.runpytest()\n # Test order will be collection order; alphabetical\n result.stdout.fnmatch_lines([\"test_a.py*\", \"test_b.py*\"])\n result = testdir.runpytest(\"--ff\")\n # Test order will be failing tests firs\n result.stdout.fnmatch_lines([\"test_b.py*\", \"test_a.py*\"])\n\n def test_lastfailed_failedfirst_order(self, testdir):\n testdir.makepyfile(\n **{\n \"test_a.py\": \"\"\"\\\n def test_always_passes():\n assert 1\n \"\"\",\n \"test_b.py\": \"\"\"\\\n def test_always_fails():\n assert 0\n \"\"\",\n }\n )\n result = testdir.runpytest()\n # Test order will be collection order; alphabetical\n result.stdout.fnmatch_lines([\"test_a.py*\", \"test_b.py*\"])\n result = testdir.runpytest(\"--lf\", \"--ff\")\n # Test order will be failing tests firs\n result.stdout.fnmatch_lines([\"test_b.py*\"])\n assert \"test_a.py\" not in result.stdout.str()\n\n def test_lastfailed_difference_invocations(self, testdir, monkeypatch):\n monkeypatch.setenv(\"PYTHONDONTWRITEBYTECODE\", \"1\")\n testdir.makepyfile(\n test_a=\"\"\"\\\n def test_a1():\n assert 0\n def test_a2():\n assert 1\n \"\"\",\n test_b=\"\"\"\\\n def test_b1():\n assert 0\n \"\"\",\n )\n p = testdir.tmpdir.join(\"test_a.py\")\n p2 = testdir.tmpdir.join(\"test_b.py\")\n\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 failed*\"])\n result = testdir.runpytest(\"--lf\", p2)\n result.stdout.fnmatch_lines([\"*1 failed*\"])\n p2.write(\n textwrap.dedent(\n \"\"\"\\\n def test_b1():\n assert 1\n \"\"\"\n )\n )\n result = testdir.runpytest(\"--lf\", p2)\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest(\"--lf\", p)\n result.stdout.fnmatch_lines([\"*1 failed*1 desel*\"])\n\n def test_lastfailed_usecase_splice(self, testdir, monkeypatch):\n monkeypatch.setenv(\"PYTHONDONTWRITEBYTECODE\", \"1\")\n testdir.makepyfile(\n \"\"\"\\\n def test_1():\n assert 0\n \"\"\"\n )\n p2 = testdir.tmpdir.join(\"test_something.py\")\n p2.write(\n textwrap.dedent(\n \"\"\"\\\n def test_2():\n assert 0\n \"\"\"\n )\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 failed*\"])\n result = testdir.runpytest(\"--lf\", p2)\n result.stdout.fnmatch_lines([\"*1 failed*\"])\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines([\"*2 failed*\"])\n\n def test_lastfailed_xpass(self, testdir):\n testdir.inline_runsource(\n \"\"\"\n import pytest\n @pytest.mark.xfail\n def test_hello():\n assert 1\n \"\"\"\n )\n config = testdir.parseconfigure()\n lastfailed = config.cache.get(\"cache/lastfailed\", -1)\n assert lastfailed == -1\n\n def test_non_serializable_parametrize(self, testdir):\n \"\"\"Test that failed parametrized tests with unmarshable parameters\n don't break pytest-cache.\n \"\"\"\n testdir.makepyfile(\n r\"\"\"\n import pytest\n\n @pytest.mark.parametrize('val', [\n b'\\xac\\x10\\x02G',\n ])\n def test_fail(val):\n assert False\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 failed in*\"])\n\n def test_terminal_report_lastfailed(self, testdir):\n test_a = testdir.makepyfile(\n test_a=\"\"\"\n def test_a1():\n pass\n def test_a2():\n pass\n \"\"\"\n )\n test_b = testdir.makepyfile(\n test_b=\"\"\"\n def test_b1():\n assert 0\n def test_b2():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"collected 4 items\", \"*2 failed, 2 passed in*\"])\n\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items\",\n \"run-last-failure: rerun previous 2 failures (skipped 1 file)\",\n \"*2 failed in*\",\n ]\n )\n\n result = testdir.runpytest(test_a, \"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items\",\n \"run-last-failure: 2 known failures not in selected tests\",\n \"*2 passed in*\",\n ]\n )\n\n result = testdir.runpytest(test_b, \"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items\",\n \"run-last-failure: rerun previous 2 failures\",\n \"*2 failed in*\",\n ]\n )\n\n result = testdir.runpytest(\"test_b.py::test_b1\", \"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 1 item\",\n \"run-last-failure: rerun previous 1 failure\",\n \"*1 failed in*\",\n ]\n )\n\n def test_terminal_report_failedfirst(self, testdir):\n testdir.makepyfile(\n test_a=\"\"\"\n def test_a1():\n assert 0\n def test_a2():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"collected 2 items\", \"*1 failed, 1 passed in*\"])\n\n result = testdir.runpytest(\"--ff\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items\",\n \"run-last-failure: rerun previous 1 failure first\",\n \"*1 failed, 1 passed in*\",\n ]\n )\n\n def test_lastfailed_collectfailure(self, testdir, monkeypatch):\n\n testdir.makepyfile(\n test_maybe=\"\"\"\n import os\n env = os.environ\n if '1' == env['FAILIMPORT']:\n raise ImportError('fail')\n def test_hello():\n assert '0' == env['FAILTEST']\n \"\"\"\n )\n\n def rlf(fail_import, fail_run):\n monkeypatch.setenv(\"FAILIMPORT\", str(fail_import))\n monkeypatch.setenv(\"FAILTEST\", str(fail_run))\n\n testdir.runpytest(\"-q\")\n config = testdir.parseconfigure()\n lastfailed = config.cache.get(\"cache/lastfailed\", -1)\n return lastfailed\n\n lastfailed = rlf(fail_import=0, fail_run=0)\n assert lastfailed == -1\n\n lastfailed = rlf(fail_import=1, fail_run=0)\n assert list(lastfailed) == [\"test_maybe.py\"]\n\n lastfailed = rlf(fail_import=0, fail_run=1)\n assert list(lastfailed) == [\"test_maybe.py::test_hello\"]\n\n def test_lastfailed_failure_subset(self, testdir, monkeypatch):\n\n testdir.makepyfile(\n test_maybe=\"\"\"\n import os\n env = os.environ\n if '1' == env['FAILIMPORT']:\n raise ImportError('fail')\n def test_hello():\n assert '0' == env['FAILTEST']\n \"\"\"\n )\n\n testdir.makepyfile(\n test_maybe2=\"\"\"\n import os\n env = os.environ\n if '1' == env['FAILIMPORT']:\n raise ImportError('fail')\n def test_hello():\n assert '0' == env['FAILTEST']\n\n def test_pass():\n pass\n \"\"\"\n )\n\n def rlf(fail_import, fail_run, args=()):\n monkeypatch.setenv(\"FAILIMPORT\", str(fail_import))\n monkeypatch.setenv(\"FAILTEST\", str(fail_run))\n\n result = testdir.runpytest(\"-q\", \"--lf\", *args)\n config = testdir.parseconfigure()\n lastfailed = config.cache.get(\"cache/lastfailed\", -1)\n return result, lastfailed\n\n result, lastfailed = rlf(fail_import=0, fail_run=0)\n assert lastfailed == -1\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n\n result, lastfailed = rlf(fail_import=1, fail_run=0)\n assert sorted(list(lastfailed)) == [\"test_maybe.py\", \"test_maybe2.py\"]\n\n result, lastfailed = rlf(fail_import=0, fail_run=0, args=(\"test_maybe2.py\",))\n assert list(lastfailed) == [\"test_maybe.py\"]\n\n # edge case of test selection - even if we remember failures\n # from other tests we still need to run all tests if no test\n # matches the failures\n result, lastfailed = rlf(fail_import=0, fail_run=0, args=(\"test_maybe2.py\",))\n assert list(lastfailed) == [\"test_maybe.py\"]\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n def test_lastfailed_creates_cache_when_needed(self, testdir):\n # Issue #1342\n testdir.makepyfile(test_empty=\"\")\n testdir.runpytest(\"-q\", \"--lf\")\n assert not os.path.exists(\".pytest_cache/v/cache/lastfailed\")\n\n testdir.makepyfile(test_successful=\"def test_success():\\n assert True\")\n testdir.runpytest(\"-q\", \"--lf\")\n assert not os.path.exists(\".pytest_cache/v/cache/lastfailed\")\n\n testdir.makepyfile(test_errored=\"def test_error():\\n assert False\")\n testdir.runpytest(\"-q\", \"--lf\")\n assert os.path.exists(\".pytest_cache/v/cache/lastfailed\")\n\n def test_xfail_not_considered_failure(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail\n def test():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 xfailed*\"])\n assert self.get_cached_last_failed(testdir) == []\n\n def test_xfail_strict_considered_failure(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(strict=True)\n def test():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 failed*\"])\n assert self.get_cached_last_failed(testdir) == [\n \"test_xfail_strict_considered_failure.py::test\"\n ]\n\n @pytest.mark.parametrize(\"mark\", [\"mark.xfail\", \"mark.skip\"])\n def test_failed_changed_to_xfail_or_skip(self, testdir, mark):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n assert self.get_cached_last_failed(testdir) == [\n \"test_failed_changed_to_xfail_or_skip.py::test\"\n ]\n assert result.ret == 1\n\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.{mark}\n def test():\n assert 0\n \"\"\".format(\n mark=mark\n )\n )\n result = testdir.runpytest()\n assert result.ret == 0\n assert self.get_cached_last_failed(testdir) == []\n assert result.ret == 0\n\n @pytest.mark.parametrize(\"quiet\", [True, False])\n @pytest.mark.parametrize(\"opt\", [\"--ff\", \"--lf\"])\n def test_lf_and_ff_prints_no_needless_message(self, quiet, opt, testdir):\n # Issue 3853\n testdir.makepyfile(\"def test(): assert 0\")\n args = [opt]\n if quiet:\n args.append(\"-q\")\n result = testdir.runpytest(*args)\n assert \"run all\" not in result.stdout.str()\n\n result = testdir.runpytest(*args)\n if quiet:\n assert \"run all\" not in result.stdout.str()\n else:\n assert \"rerun previous\" in result.stdout.str()\n\n def get_cached_last_failed(self, testdir):\n config = testdir.parseconfigure()\n return sorted(config.cache.get(\"cache/lastfailed\", {}))\n\n def test_cache_cumulative(self, testdir):\n \"\"\"\n Test workflow where user fixes errors gradually file by file using --lf.\n \"\"\"\n # 1. initial run\n test_bar = testdir.makepyfile(\n test_bar=\"\"\"\n def test_bar_1():\n pass\n def test_bar_2():\n assert 0\n \"\"\"\n )\n test_foo = testdir.makepyfile(\n test_foo=\"\"\"\n def test_foo_3():\n pass\n def test_foo_4():\n assert 0\n \"\"\"\n )\n testdir.runpytest()\n assert self.get_cached_last_failed(testdir) == [\n \"test_bar.py::test_bar_2\",\n \"test_foo.py::test_foo_4\",\n ]\n\n # 2. fix test_bar_2, run only test_bar.py\n testdir.makepyfile(\n test_bar=\"\"\"\n def test_bar_1():\n pass\n def test_bar_2():\n pass\n \"\"\"\n )\n result = testdir.runpytest(test_bar)\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n # ensure cache does not forget that test_foo_4 failed once before\n assert self.get_cached_last_failed(testdir) == [\"test_foo.py::test_foo_4\"]\n\n result = testdir.runpytest(\"--last-failed\")\n result.stdout.fnmatch_lines([\"*1 failed, 1 deselected*\"])\n assert self.get_cached_last_failed(testdir) == [\"test_foo.py::test_foo_4\"]\n\n # 3. fix test_foo_4, run only test_foo.py\n test_foo = testdir.makepyfile(\n test_foo=\"\"\"\n def test_foo_3():\n pass\n def test_foo_4():\n pass\n \"\"\"\n )\n result = testdir.runpytest(test_foo, \"--last-failed\")\n result.stdout.fnmatch_lines([\"*1 passed, 1 deselected*\"])\n assert self.get_cached_last_failed(testdir) == []\n\n result = testdir.runpytest(\"--last-failed\")\n result.stdout.fnmatch_lines([\"*4 passed*\"])\n assert self.get_cached_last_failed(testdir) == []\n\n def test_lastfailed_no_failures_behavior_all_passed(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_1():\n assert True\n def test_2():\n assert True\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n result = testdir.runpytest(\"--lf\", \"--lfnf\", \"all\")\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n result = testdir.runpytest(\"--lf\", \"--lfnf\", \"none\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items / 2 deselected\",\n \"run-last-failure: no previously failed tests, deselecting all items.\",\n \"* 2 deselected in *\",\n ]\n )\n assert result.ret == EXIT_NOTESTSCOLLECTED\n\n def test_lastfailed_no_failures_behavior_empty_cache(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_1():\n assert True\n def test_2():\n assert False\n \"\"\"\n )\n result = testdir.runpytest(\"--lf\", \"--cache-clear\")\n result.stdout.fnmatch_lines([\"*1 failed*1 passed*\"])\n result = testdir.runpytest(\"--lf\", \"--cache-clear\", \"--lfnf\", \"all\")\n result.stdout.fnmatch_lines([\"*1 failed*1 passed*\"])\n result = testdir.runpytest(\"--lf\", \"--cache-clear\", \"--lfnf\", \"none\")\n result.stdout.fnmatch_lines([\"*2 desel*\"])\n\n def test_lastfailed_skip_collection(self, testdir):\n \"\"\"\n Test --lf behavior regarding skipping collection of files that are not marked as\n failed in the cache (#5172).\n \"\"\"\n testdir.makepyfile(\n **{\n \"pkg1/test_1.py\": \"\"\"\n import pytest\n\n @pytest.mark.parametrize('i', range(3))\n def test_1(i): pass\n \"\"\",\n \"pkg2/test_2.py\": \"\"\"\n import pytest\n\n @pytest.mark.parametrize('i', range(5))\n def test_1(i):\n assert i not in (1, 3)\n \"\"\",\n }\n )\n # first run: collects 8 items (test_1: 3, test_2: 5)\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"collected 8 items\", \"*2 failed*6 passed*\"])\n # second run: collects only 5 items from test_2, because all tests from test_1 have passed\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 5 items / 3 deselected / 2 selected\",\n \"run-last-failure: rerun previous 2 failures (skipped 1 file)\",\n \"*2 failed*3 deselected*\",\n ]\n )\n\n # add another file and check if message is correct when skipping more than 1 file\n testdir.makepyfile(\n **{\n \"pkg1/test_3.py\": \"\"\"\n def test_3(): pass\n \"\"\"\n }\n )\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 5 items / 3 deselected / 2 selected\",\n \"run-last-failure: rerun previous 2 failures (skipped 2 files)\",\n \"*2 failed*3 deselected*\",\n ]\n )\n\n def test_lastfailed_with_known_failures_not_being_selected(self, testdir):\n testdir.makepyfile(\n **{\n \"pkg1/test_1.py\": \"\"\"def test_1(): assert 0\"\"\",\n \"pkg1/test_2.py\": \"\"\"def test_2(): pass\"\"\",\n }\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"collected 2 items\", \"* 1 failed, 1 passed in *\"])\n\n py.path.local(\"pkg1/test_1.py\").remove()\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 1 item\",\n \"run-last-failure: 1 known failures not in selected tests\",\n \"* 1 passed in *\",\n ]\n )\n\n # Recreate file with known failure.\n testdir.makepyfile(**{\"pkg1/test_1.py\": \"\"\"def test_1(): assert 0\"\"\"})\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 1 item\",\n \"run-last-failure: rerun previous 1 failure (skipped 1 file)\",\n \"* 1 failed in *\",\n ]\n )\n\n # Remove/rename test.\n testdir.makepyfile(**{\"pkg1/test_1.py\": \"\"\"def test_renamed(): assert 0\"\"\"})\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 1 item\",\n \"run-last-failure: 1 known failures not in selected tests (skipped 1 file)\",\n \"* 1 failed in *\",\n ]\n )"},{"col":4,"comment":"null","endLoc":290,"header":"def test_lastfailed_usecase(self, testdir, monkeypatch)","id":4197,"name":"test_lastfailed_usecase","nodeType":"Function","startLoc":245,"text":"def test_lastfailed_usecase(self, testdir, monkeypatch):\n monkeypatch.setenv(\"PYTHONDONTWRITEBYTECODE\", \"1\")\n p = testdir.makepyfile(\n \"\"\"\n def test_1():\n assert 0\n def test_2():\n assert 0\n def test_3():\n assert 1\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 failed*\"])\n p.write(\n textwrap.dedent(\n \"\"\"\\\n def test_1():\n assert 1\n\n def test_2():\n assert 1\n\n def test_3():\n assert 0\n \"\"\"\n )\n )\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines([\"*2 passed*1 desel*\"])\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 3 items\",\n \"run-last-failure: no previously failed tests, not deselecting items.\",\n \"*1 failed*2 passed*\",\n ]\n )\n result = testdir.runpytest(\"--lf\", \"--cache-clear\")\n result.stdout.fnmatch_lines([\"*1 failed*2 passed*\"])\n\n # Run this again to make sure clear-cache is robust\n if os.path.isdir(\".pytest_cache\"):\n shutil.rmtree(\".pytest_cache\")\n result = testdir.runpytest(\"--lf\", \"--cache-clear\")\n result.stdout.fnmatch_lines([\"*1 failed*2 passed*\"])"},{"col":4,"comment":"null","endLoc":114,"header":"def test_group_shortopt_lowercase(self, parser)","id":4198,"name":"test_group_shortopt_lowercase","nodeType":"Function","startLoc":108,"text":"def test_group_shortopt_lowercase(self, parser):\n group = parser.getgroup(\"hello\")\n with pytest.raises(ValueError):\n group.addoption(\"-x\", action=\"store_true\")\n assert len(group.options) == 0\n group._addoption(\"-x\", action=\"store_true\")\n assert len(group.options) == 1"},{"col":4,"comment":"null","endLoc":423,"header":"def test_pdb_and_capsys(self, testdir)","id":4199,"name":"test_pdb_and_capsys","nodeType":"Function","startLoc":408,"text":"def test_pdb_and_capsys(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1(capsys):\n print(\"hello1\")\n pytest.set_trace()\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"test_1\")\n child.send(\"capsys.readouterr()\\n\")\n child.expect(\"hello1\")\n child.sendeof()\n child.read()\n self.flush(child)"},{"col":4,"comment":"null","endLoc":120,"header":"def test_parser_addoption(self, parser)","id":4200,"name":"test_parser_addoption","nodeType":"Function","startLoc":116,"text":"def test_parser_addoption(self, parser):\n group = parser.getgroup(\"custom options\")\n assert len(group.options) == 0\n group.addoption(\"--option1\", action=\"store_true\")\n assert len(group.options) == 1"},{"col":4,"comment":"null","endLoc":126,"header":"def test_parse(self, parser)","id":4201,"name":"test_parse","nodeType":"Function","startLoc":122,"text":"def test_parse(self, parser):\n parser.addoption(\"--hello\", dest=\"hello\", action=\"store\")\n args = parser.parse([\"--hello\", \"world\"])\n assert args.hello == \"world\"\n assert not getattr(args, parseopt.FILE_OR_DIR)"},{"col":4,"comment":"null","endLoc":441,"header":"def test_pdb_with_caplog_on_pdb_invocation(self, testdir)","id":4202,"name":"test_pdb_with_caplog_on_pdb_invocation","nodeType":"Function","startLoc":425,"text":"def test_pdb_with_caplog_on_pdb_invocation(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1(capsys, caplog):\n import logging\n logging.getLogger(__name__).warning(\"some_warning\")\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdb %s\" % str(p1))\n child.send(\"caplog.record_tuples\\n\")\n child.expect_exact(\n \"[('test_pdb_with_caplog_on_pdb_invocation', 30, 'some_warning')]\"\n )\n child.sendeof()\n child.read()\n self.flush(child)"},{"col":4,"comment":"null","endLoc":130,"header":"def test_parse2(self, parser)","id":4203,"name":"test_parse2","nodeType":"Function","startLoc":128,"text":"def test_parse2(self, parser):\n args = parser.parse([py.path.local()])\n assert getattr(args, parseopt.FILE_OR_DIR)[0] == py.path.local()"},{"col":4,"comment":"null","endLoc":137,"header":"def test_parse_known_args(self, parser)","id":4204,"name":"test_parse_known_args","nodeType":"Function","startLoc":132,"text":"def test_parse_known_args(self, parser):\n parser.parse_known_args([py.path.local()])\n parser.addoption(\"--hello\", action=\"store_true\")\n ns = parser.parse_known_args([\"x\", \"--y\", \"--hello\", \"this\"])\n assert ns.hello\n assert ns.file_or_dir == [\"x\"]"},{"col":4,"comment":"null","endLoc":146,"header":"def test_parse_known_and_unknown_args(self, parser)","id":4205,"name":"test_parse_known_and_unknown_args","nodeType":"Function","startLoc":139,"text":"def test_parse_known_and_unknown_args(self, parser):\n parser.addoption(\"--hello\", action=\"store_true\")\n ns, unknown = parser.parse_known_and_unknown_args(\n [\"x\", \"--y\", \"--hello\", \"this\"]\n )\n assert ns.hello\n assert ns.file_or_dir == [\"x\"]\n assert unknown == [\"--y\", \"this\"]"},{"col":4,"comment":"Regarding issue pytest-xdist#196\n\n This test came originally from test_remote.py in xdist (ca03269).\n ","endLoc":128,"header":"def test_reprentries_serialization_196(self, testdir)","id":4206,"name":"test_reprentries_serialization_196","nodeType":"Function","startLoc":103,"text":"def test_reprentries_serialization_196(self, testdir):\n \"\"\"Regarding issue pytest-xdist#196\n\n This test came originally from test_remote.py in xdist (ca03269).\n \"\"\"\n from _pytest._code.code import ReprEntryNative\n\n reprec = testdir.inline_runsource(\n \"\"\"\n def test_repr_entry_native():\n x = 0\n assert x\n \"\"\",\n \"--tb=native\",\n )\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 3\n rep = reports[1]\n d = rep._to_json()\n a = TestReport._from_json(d)\n\n rep_entries = rep.longrepr.reprtraceback.reprentries\n a_entries = a.longrepr.reprtraceback.reprentries\n for i in range(len(a_entries)):\n assert isinstance(rep_entries[i], ReprEntryNative)\n assert rep_entries[i].lines == a_entries[i].lines"},{"col":4,"comment":"null","endLoc":462,"header":"def test_set_trace_capturing_afterwards(self, testdir)","id":4207,"name":"test_set_trace_capturing_afterwards","nodeType":"Function","startLoc":443,"text":"def test_set_trace_capturing_afterwards(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pdb\n def test_1():\n pdb.set_trace()\n def test_2():\n print(\"hello\")\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"test_1\")\n child.send(\"c\\n\")\n child.expect(\"test_2\")\n child.expect(\"Captured\")\n child.expect(\"hello\")\n child.sendeof()\n child.read()\n self.flush(child)"},{"col":4,"comment":"null","endLoc":154,"header":"def test_parse_will_set_default(self, parser)","id":4208,"name":"test_parse_will_set_default","nodeType":"Function","startLoc":148,"text":"def test_parse_will_set_default(self, parser):\n parser.addoption(\"--hello\", dest=\"hello\", default=\"x\", action=\"store\")\n option = parser.parse([])\n assert option.hello == \"x\"\n del option.hello\n parser.parse_setoption([], option)\n assert option.hello == \"x\""},{"col":4,"comment":"null","endLoc":167,"header":"def test_parse_setoption(self, parser)","id":4209,"name":"test_parse_setoption","nodeType":"Function","startLoc":156,"text":"def test_parse_setoption(self, parser):\n parser.addoption(\"--hello\", dest=\"hello\", action=\"store\")\n parser.addoption(\"--world\", dest=\"world\", default=42)\n\n class A(object):\n pass\n\n option = A()\n args = parser.parse_setoption([\"--hello\", \"world\"], option)\n assert option.hello == \"world\"\n assert option.world == 42\n assert not args"},{"col":4,"comment":"null","endLoc":314,"header":"def test_failedfirst_order(self, testdir)","id":4212,"name":"test_failedfirst_order","nodeType":"Function","startLoc":292,"text":"def test_failedfirst_order(self, testdir):\n testdir.tmpdir.join(\"test_a.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_always_passes():\n assert 1\n \"\"\"\n )\n )\n testdir.tmpdir.join(\"test_b.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_always_fails():\n assert 0\n \"\"\"\n )\n )\n result = testdir.runpytest()\n # Test order will be collection order; alphabetical\n result.stdout.fnmatch_lines([\"test_a.py*\", \"test_b.py*\"])\n result = testdir.runpytest(\"--ff\")\n # Test order will be failing tests firs\n result.stdout.fnmatch_lines([\"test_b.py*\", \"test_a.py*\"])"},{"col":4,"comment":"null","endLoc":732,"header":"def test_readonly(self, testdir)","id":4213,"name":"test_readonly","nodeType":"Function","startLoc":718,"text":"def test_readonly(self, testdir):\n sub = testdir.mkdir(\"testing\")\n sub.join(\"test_readonly.py\").write(\n b\"\"\"\ndef test_rewritten():\n assert \"@py_builtins\" in globals()\n \"\"\",\n \"wb\",\n )\n old_mode = sub.stat().mode\n sub.chmod(320)\n try:\n assert testdir.runpytest().ret == 0\n finally:\n sub.chmod(old_mode)"},{"col":4,"comment":"null","endLoc":172,"header":"def test_parse_special_destination(self, parser)","id":4214,"name":"test_parse_special_destination","nodeType":"Function","startLoc":169,"text":"def test_parse_special_destination(self, parser):\n parser.addoption(\"--ultimate-answer\", type=int)\n args = parser.parse([\"--ultimate-answer\", \"42\"])\n assert args.ultimate_answer == 42"},{"col":4,"comment":"null","endLoc":186,"header":"def test_parse_split_positional_arguments(self, parser)","id":4215,"name":"test_parse_split_positional_arguments","nodeType":"Function","startLoc":174,"text":"def test_parse_split_positional_arguments(self, parser):\n parser.addoption(\"-R\", action=\"store_true\")\n parser.addoption(\"-S\", action=\"store_false\")\n args = parser.parse([\"-R\", \"4\", \"2\", \"-S\"])\n assert getattr(args, parseopt.FILE_OR_DIR) == [\"4\", \"2\"]\n args = parser.parse([\"-R\", \"-S\", \"4\", \"2\", \"-R\"])\n assert getattr(args, parseopt.FILE_OR_DIR) == [\"4\", \"2\"]\n assert args.R is True\n assert args.S is False\n args = parser.parse([\"-R\", \"4\", \"-S\", \"2\"])\n assert getattr(args, parseopt.FILE_OR_DIR) == [\"4\", \"2\"]\n assert args.R is True\n assert args.S is False"},{"col":4,"comment":"null","endLoc":744,"header":"def test_dont_write_bytecode(self, testdir, monkeypatch)","id":4216,"name":"test_dont_write_bytecode","nodeType":"Function","startLoc":734,"text":"def test_dont_write_bytecode(self, testdir, monkeypatch):\n testdir.makepyfile(\n \"\"\"\n import os\n def test_no_bytecode():\n assert \"__pycache__\" in __cached__\n assert not os.path.exists(__cached__)\n assert not os.path.exists(os.path.dirname(__cached__))\"\"\"\n )\n monkeypatch.setenv(\"PYTHONDONTWRITEBYTECODE\", \"1\")\n assert testdir.runpytest_subprocess().ret == 0"},{"col":4,"comment":"null","endLoc":335,"header":"def test_lastfailed_failedfirst_order(self, testdir)","id":4217,"name":"test_lastfailed_failedfirst_order","nodeType":"Function","startLoc":316,"text":"def test_lastfailed_failedfirst_order(self, testdir):\n testdir.makepyfile(\n **{\n \"test_a.py\": \"\"\"\\\n def test_always_passes():\n assert 1\n \"\"\",\n \"test_b.py\": \"\"\"\\\n def test_always_fails():\n assert 0\n \"\"\",\n }\n )\n result = testdir.runpytest()\n # Test order will be collection order; alphabetical\n result.stdout.fnmatch_lines([\"test_a.py*\", \"test_b.py*\"])\n result = testdir.runpytest(\"--lf\", \"--ff\")\n # Test order will be failing tests firs\n result.stdout.fnmatch_lines([\"test_b.py*\"])\n assert \"test_a.py\" not in result.stdout.str()"},{"col":4,"comment":"null","endLoc":773,"header":"def test_orphaned_pyc_file(self, testdir)","id":4218,"name":"test_orphaned_pyc_file","nodeType":"Function","startLoc":746,"text":"def test_orphaned_pyc_file(self, testdir):\n if sys.version_info < (3, 0) and hasattr(sys, \"pypy_version_info\"):\n pytest.skip(\"pypy2 doesn't run orphaned pyc files\")\n\n testdir.makepyfile(\n \"\"\"\n import orphan\n def test_it():\n assert orphan.value == 17\n \"\"\"\n )\n testdir.makepyfile(\n orphan=\"\"\"\n value = 17\n \"\"\"\n )\n py_compile.compile(\"orphan.py\")\n os.remove(\"orphan.py\")\n\n # Python 3 puts the .pyc files in a __pycache__ directory, and will\n # not import from there without source. It will import a .pyc from\n # the source location though.\n if not os.path.exists(\"orphan.pyc\"):\n pycs = glob.glob(\"__pycache__/orphan.*.pyc\")\n assert len(pycs) == 1\n os.rename(pycs[0], \"orphan.pyc\")\n\n assert testdir.runpytest().ret == 0"},{"col":4,"comment":"null","endLoc":369,"header":"def test_lastfailed_difference_invocations(self, testdir, monkeypatch)","id":4219,"name":"test_lastfailed_difference_invocations","nodeType":"Function","startLoc":337,"text":"def test_lastfailed_difference_invocations(self, testdir, monkeypatch):\n monkeypatch.setenv(\"PYTHONDONTWRITEBYTECODE\", \"1\")\n testdir.makepyfile(\n test_a=\"\"\"\\\n def test_a1():\n assert 0\n def test_a2():\n assert 1\n \"\"\",\n test_b=\"\"\"\\\n def test_b1():\n assert 0\n \"\"\",\n )\n p = testdir.tmpdir.join(\"test_a.py\")\n p2 = testdir.tmpdir.join(\"test_b.py\")\n\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 failed*\"])\n result = testdir.runpytest(\"--lf\", p2)\n result.stdout.fnmatch_lines([\"*1 failed*\"])\n p2.write(\n textwrap.dedent(\n \"\"\"\\\n def test_b1():\n assert 1\n \"\"\"\n )\n )\n result = testdir.runpytest(\"--lf\", p2)\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest(\"--lf\", p)\n result.stdout.fnmatch_lines([\"*1 failed*1 desel*\"])"},{"col":4,"comment":"\n This test came originally from test_remote.py in xdist (ca03269).\n ","endLoc":163,"header":"def test_itemreport_outcomes(self, testdir)","id":4220,"name":"test_itemreport_outcomes","nodeType":"Function","startLoc":130,"text":"def test_itemreport_outcomes(self, testdir):\n \"\"\"\n This test came originally from test_remote.py in xdist (ca03269).\n \"\"\"\n reprec = testdir.inline_runsource(\n \"\"\"\n import py\n def test_pass(): pass\n def test_fail(): 0/0\n @py.test.mark.skipif(\"True\")\n def test_skip(): pass\n def test_skip_imperative():\n py.test.skip(\"hello\")\n @py.test.mark.xfail(\"True\")\n def test_xfail(): 0/0\n def test_xfail_imperative():\n py.test.xfail(\"hello\")\n \"\"\"\n )\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 17 # with setup/teardown \"passed\" reports\n for rep in reports:\n d = rep._to_json()\n newrep = TestReport._from_json(d)\n assert newrep.passed == rep.passed\n assert newrep.failed == rep.failed\n assert newrep.skipped == rep.skipped\n if newrep.skipped and not hasattr(newrep, \"wasxfail\"):\n assert len(newrep.longrepr) == 3\n assert newrep.outcome == rep.outcome\n assert newrep.when == rep.when\n assert newrep.keywords == rep.keywords\n if rep.failed:\n assert newrep.longreprtext == rep.longreprtext"},{"col":4,"comment":"null","endLoc":393,"header":"def test_lastfailed_usecase_splice(self, testdir, monkeypatch)","id":4222,"name":"test_lastfailed_usecase_splice","nodeType":"Function","startLoc":371,"text":"def test_lastfailed_usecase_splice(self, testdir, monkeypatch):\n monkeypatch.setenv(\"PYTHONDONTWRITEBYTECODE\", \"1\")\n testdir.makepyfile(\n \"\"\"\\\n def test_1():\n assert 0\n \"\"\"\n )\n p2 = testdir.tmpdir.join(\"test_something.py\")\n p2.write(\n textwrap.dedent(\n \"\"\"\\\n def test_2():\n assert 0\n \"\"\"\n )\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 failed*\"])\n result = testdir.runpytest(\"--lf\", p2)\n result.stdout.fnmatch_lines([\"*1 failed*\"])\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines([\"*2 failed*\"])"},{"col":4,"comment":"This test came originally from test_remote.py in xdist (ca03269).","endLoc":174,"header":"def test_collectreport_passed(self, testdir)","id":4223,"name":"test_collectreport_passed","nodeType":"Function","startLoc":165,"text":"def test_collectreport_passed(self, testdir):\n \"\"\"This test came originally from test_remote.py in xdist (ca03269).\"\"\"\n reprec = testdir.inline_runsource(\"def test_func(): pass\")\n reports = reprec.getreports(\"pytest_collectreport\")\n for rep in reports:\n d = rep._to_json()\n newrep = CollectReport._from_json(d)\n assert newrep.passed == rep.passed\n assert newrep.failed == rep.failed\n assert newrep.skipped == rep.skipped"},{"col":4,"comment":"This test came originally from test_remote.py in xdist (ca03269).","endLoc":188,"header":"def test_collectreport_fail(self, testdir)","id":4224,"name":"test_collectreport_fail","nodeType":"Function","startLoc":176,"text":"def test_collectreport_fail(self, testdir):\n \"\"\"This test came originally from test_remote.py in xdist (ca03269).\"\"\"\n reprec = testdir.inline_runsource(\"qwe abc\")\n reports = reprec.getreports(\"pytest_collectreport\")\n assert reports\n for rep in reports:\n d = rep._to_json()\n newrep = CollectReport._from_json(d)\n assert newrep.passed == rep.passed\n assert newrep.failed == rep.failed\n assert newrep.skipped == rep.skipped\n if rep.failed:\n assert newrep.longrepr == str(rep.longrepr)"},{"col":4,"comment":"null","endLoc":487,"header":"def test_pdb_interaction_doctest(self, testdir, monkeypatch)","id":4225,"name":"test_pdb_interaction_doctest","nodeType":"Function","startLoc":464,"text":"def test_pdb_interaction_doctest(self, testdir, monkeypatch):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def function_1():\n '''\n >>> i = 0\n >>> assert i == 1\n '''\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--doctest-modules --pdb %s\" % p1)\n child.expect(\"Pdb\")\n\n assert \"UNEXPECTED EXCEPTION: AssertionError()\" in child.before.decode(\"utf8\")\n\n child.sendline(\"'i=%i.' % i\")\n child.expect(\"Pdb\")\n assert \"\\r\\n'i=0.'\\r\\n\" in child.before.decode(\"utf8\")\n\n child.sendeof()\n rest = child.read().decode(\"utf8\")\n assert \"1 failed\" in rest\n self.flush(child)"},{"col":4,"comment":"null","endLoc":297,"header":"def _pop_and_teardown(self)","id":4226,"name":"_pop_and_teardown","nodeType":"Function","startLoc":295,"text":"def _pop_and_teardown(self):\n colitem = self.stack.pop()\n self._teardown_with_finalization(colitem)"},{"col":4,"comment":"null","endLoc":406,"header":"def test_lastfailed_xpass(self, testdir)","id":4227,"name":"test_lastfailed_xpass","nodeType":"Function","startLoc":395,"text":"def test_lastfailed_xpass(self, testdir):\n testdir.inline_runsource(\n \"\"\"\n import pytest\n @pytest.mark.xfail\n def test_hello():\n assert 1\n \"\"\"\n )\n config = testdir.parseconfigure()\n lastfailed = config.cache.get(\"cache/lastfailed\", -1)\n assert lastfailed == -1"},{"col":0,"comment":"Ensure that our warning about 'unicode warnings containing non-ascii messages'\n does not trigger with ascii-convertible messages","endLoc":219,"header":"def test_py2_unicode_ascii(testdir)","id":4228,"name":"test_py2_unicode_ascii","nodeType":"Function","startLoc":198,"text":"def test_py2_unicode_ascii(testdir):\n \"\"\"Ensure that our warning about 'unicode warnings containing non-ascii messages'\n does not trigger with ascii-convertible messages\"\"\"\n testdir.makeini(\"[pytest]\")\n testdir.makepyfile(\n \"\"\"\n import pytest\n import warnings\n\n @pytest.mark.filterwarnings('always')\n def test_func():\n warnings.warn(u\"hello\")\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*== %s ==*\" % WARNINGS_SUMMARY_HEADER,\n '*warnings.warn(u\"hello\")',\n \"* 1 passed, 1 warnings in*\",\n ]\n )"},{"col":4,"comment":"Test that failed parametrized tests with unmarshable parameters\n don't break pytest-cache.\n ","endLoc":424,"header":"def test_non_serializable_parametrize(self, testdir)","id":4229,"name":"test_non_serializable_parametrize","nodeType":"Function","startLoc":408,"text":"def test_non_serializable_parametrize(self, testdir):\n \"\"\"Test that failed parametrized tests with unmarshable parameters\n don't break pytest-cache.\n \"\"\"\n testdir.makepyfile(\n r\"\"\"\n import pytest\n\n @pytest.mark.parametrize('val', [\n b'\\xac\\x10\\x02G',\n ])\n def test_fail(val):\n assert False\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 failed in*\"])"},{"col":4,"comment":"null","endLoc":204,"header":"def test_parse_defaultgetter(self)","id":4230,"name":"test_parse_defaultgetter","nodeType":"Function","startLoc":188,"text":"def test_parse_defaultgetter(self):\n def defaultget(option):\n if not hasattr(option, \"type\"):\n return\n if option.type is int:\n option.default = 42\n elif option.type is str:\n option.default = \"world\"\n\n parser = parseopt.Parser(processopt=defaultget)\n parser.addoption(\"--this\", dest=\"this\", type=int, action=\"store\")\n parser.addoption(\"--hello\", dest=\"hello\", type=str, action=\"store\")\n parser.addoption(\"--no\", dest=\"no\", action=\"store_true\")\n option = parser.parse([])\n assert option.hello == \"world\"\n assert option.this == 42\n assert option.no is False"},{"col":4,"comment":"This test came originally from test_remote.py in xdist (ca03269).","endLoc":204,"header":"def test_extended_report_deserialization(self, testdir)","id":4231,"name":"test_extended_report_deserialization","nodeType":"Function","startLoc":190,"text":"def test_extended_report_deserialization(self, testdir):\n \"\"\"This test came originally from test_remote.py in xdist (ca03269).\"\"\"\n reprec = testdir.inline_runsource(\"qwe abc\")\n reports = reprec.getreports(\"pytest_collectreport\")\n assert reports\n for rep in reports:\n rep.extra = True\n d = rep._to_json()\n newrep = CollectReport._from_json(d)\n assert newrep.extra\n assert newrep.passed == rep.passed\n assert newrep.failed == rep.failed\n assert newrep.skipped == rep.skipped\n if rep.failed:\n assert newrep.longrepr == str(rep.longrepr)"},{"col":4,"comment":"null","endLoc":522,"header":"def test_pdb_interaction_capturing_twice(self, testdir)","id":4232,"name":"test_pdb_interaction_capturing_twice","nodeType":"Function","startLoc":489,"text":"def test_pdb_interaction_capturing_twice(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1():\n i = 0\n print(\"hello17\")\n pytest.set_trace()\n x = 3\n print(\"hello18\")\n pytest.set_trace()\n x = 4\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(r\"PDB set_trace \\(IO-capturing turned off\\)\")\n child.expect(\"test_1\")\n child.expect(\"x = 3\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n child.expect(r\"PDB continue \\(IO-capturing resumed\\)\")\n child.expect(r\"PDB set_trace \\(IO-capturing turned off\\)\")\n child.expect(\"x = 4\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n child.expect(\"_ test_1 _\")\n child.expect(\"def test_1\")\n rest = child.read().decode(\"utf8\")\n assert \"Captured stdout call\" in rest\n assert \"hello17\" in rest # out is captured\n assert \"hello18\" in rest # out is captured\n assert \"1 failed\" in rest\n self.flush(child)"},{"col":4,"comment":"null","endLoc":480,"header":"def test_terminal_report_lastfailed(self, testdir)","id":4233,"name":"test_terminal_report_lastfailed","nodeType":"Function","startLoc":426,"text":"def test_terminal_report_lastfailed(self, testdir):\n test_a = testdir.makepyfile(\n test_a=\"\"\"\n def test_a1():\n pass\n def test_a2():\n pass\n \"\"\"\n )\n test_b = testdir.makepyfile(\n test_b=\"\"\"\n def test_b1():\n assert 0\n def test_b2():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"collected 4 items\", \"*2 failed, 2 passed in*\"])\n\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items\",\n \"run-last-failure: rerun previous 2 failures (skipped 1 file)\",\n \"*2 failed in*\",\n ]\n )\n\n result = testdir.runpytest(test_a, \"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items\",\n \"run-last-failure: 2 known failures not in selected tests\",\n \"*2 passed in*\",\n ]\n )\n\n result = testdir.runpytest(test_b, \"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items\",\n \"run-last-failure: rerun previous 2 failures\",\n \"*2 failed in*\",\n ]\n )\n\n result = testdir.runpytest(\"test_b.py::test_b1\", \"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 1 item\",\n \"run-last-failure: rerun previous 1 failure\",\n \"*1 failed in*\",\n ]\n )"},{"col":0,"comment":"Ensure our warnings capture does not mess with pre-installed filters (#2430).","endLoc":243,"header":"def test_works_with_filterwarnings(testdir)","id":4235,"name":"test_works_with_filterwarnings","nodeType":"Function","startLoc":222,"text":"def test_works_with_filterwarnings(testdir):\n \"\"\"Ensure our warnings capture does not mess with pre-installed filters (#2430).\"\"\"\n testdir.makepyfile(\n \"\"\"\n import warnings\n\n class MyWarning(Warning):\n pass\n\n warnings.filterwarnings(\"error\", category=MyWarning)\n\n class TestWarnings(object):\n def test_my_warning(self):\n try:\n warnings.warn(MyWarning(\"warn!\"))\n assert False\n except MyWarning:\n assert True\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*== 1 passed in *\"])"},{"col":4,"comment":" register a command line option.\n\n :opts: option names, can be short or long options.\n :attrs: same attributes which the ``add_option()`` function of the\n `argparse library\n `_\n accepts.\n\n After command line parsing options are available on the pytest config\n object via ``config.option.NAME`` where ``NAME`` is usually set\n by passing a ``dest`` attribute, for example\n ``addoption(\"--long\", dest=\"NAME\", ...)``.\n ","endLoc":73,"header":"def addoption(self, *opts, **attrs)","id":4236,"name":"addoption","nodeType":"Function","startLoc":59,"text":"def addoption(self, *opts, **attrs):\n \"\"\" register a command line option.\n\n :opts: option names, can be short or long options.\n :attrs: same attributes which the ``add_option()`` function of the\n `argparse library\n `_\n accepts.\n\n After command line parsing options are available on the pytest config\n object via ``config.option.NAME`` where ``NAME`` is usually set\n by passing a ``dest`` attribute, for example\n ``addoption(\"--long\", dest=\"NAME\", ...)``.\n \"\"\"\n self._anonymous.addoption(*opts, **attrs)"},{"col":0,"comment":"\n Test ``filterwarnings`` mark works and takes precedence over command line and ini options.\n ","endLoc":276,"header":"@pytest.mark.parametrize(\"default_config\", [\"ini\", \"cmdline\"])\ndef test_filterwarnings_mark(testdir, default_config)","id":4237,"name":"test_filterwarnings_mark","nodeType":"Function","startLoc":246,"text":"@pytest.mark.parametrize(\"default_config\", [\"ini\", \"cmdline\"])\ndef test_filterwarnings_mark(testdir, default_config):\n \"\"\"\n Test ``filterwarnings`` mark works and takes precedence over command line and ini options.\n \"\"\"\n if default_config == \"ini\":\n testdir.makeini(\n \"\"\"\n [pytest]\n filterwarnings = always\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import warnings\n import pytest\n\n @pytest.mark.filterwarnings('ignore::RuntimeWarning')\n def test_ignore_runtime_warning():\n warnings.warn(RuntimeWarning())\n\n @pytest.mark.filterwarnings('error')\n def test_warning_error():\n warnings.warn(RuntimeWarning())\n\n def test_show_warning():\n warnings.warn(RuntimeWarning())\n \"\"\"\n )\n result = testdir.runpytest(\"-W always\" if default_config == \"cmdline\" else \"\")\n result.stdout.fnmatch_lines([\"*= 1 failed, 2 passed, 1 warnings in *\"])"},{"col":4,"comment":"null","endLoc":501,"header":"def test_terminal_report_failedfirst(self, testdir)","id":4238,"name":"test_terminal_report_failedfirst","nodeType":"Function","startLoc":482,"text":"def test_terminal_report_failedfirst(self, testdir):\n testdir.makepyfile(\n test_a=\"\"\"\n def test_a1():\n assert 0\n def test_a2():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"collected 2 items\", \"*1 failed, 1 passed in*\"])\n\n result = testdir.runpytest(\"--ff\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items\",\n \"run-last-failure: rerun previous 1 failure first\",\n \"*1 failed, 1 passed in*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":241,"header":"def test_drop_short_helper(self)","id":4240,"name":"test_drop_short_helper","nodeType":"Function","startLoc":206,"text":"def test_drop_short_helper(self):\n parser = argparse.ArgumentParser(\n formatter_class=parseopt.DropShorterLongHelpFormatter\n )\n parser.add_argument(\n \"-t\", \"--twoword\", \"--duo\", \"--two-word\", \"--two\", help=\"foo\"\n ).map_long_option = {\"two\": \"two-word\"}\n # throws error on --deux only!\n parser.add_argument(\n \"-d\", \"--deuxmots\", \"--deux-mots\", action=\"store_true\", help=\"foo\"\n ).map_long_option = {\"deux\": \"deux-mots\"}\n parser.add_argument(\"-s\", action=\"store_true\", help=\"single short\")\n parser.add_argument(\"--abc\", \"-a\", action=\"store_true\", help=\"bar\")\n parser.add_argument(\"--klm\", \"-k\", \"--kl-m\", action=\"store_true\", help=\"bar\")\n parser.add_argument(\n \"-P\", \"--pq-r\", \"-p\", \"--pqr\", action=\"store_true\", help=\"bar\"\n )\n parser.add_argument(\n \"--zwei-wort\", \"--zweiwort\", \"--zweiwort\", action=\"store_true\", help=\"bar\"\n )\n parser.add_argument(\n \"-x\", \"--exit-on-first\", \"--exitfirst\", action=\"store_true\", help=\"spam\"\n ).map_long_option = {\"exitfirst\": \"exit-on-first\"}\n parser.add_argument(\"files_and_dirs\", nargs=\"*\")\n args = parser.parse_args([\"-k\", \"--duo\", \"hallo\", \"--exitfirst\"])\n assert args.twoword == \"hallo\"\n assert args.klm is True\n assert args.zwei_wort is False\n assert args.exit_on_first is True\n assert args.s is False\n args = parser.parse_args([\"--deux-mots\"])\n with pytest.raises(AttributeError):\n assert args.deux_mots is True\n assert args.deuxmots is True\n args = parser.parse_args([\"file\", \"dir\"])\n assert \"|\".join(args.files_and_dirs) == \"file|dir\""},{"col":4,"comment":"null","endLoc":532,"header":"def test_lastfailed_collectfailure(self, testdir, monkeypatch)","id":4241,"name":"test_lastfailed_collectfailure","nodeType":"Function","startLoc":503,"text":"def test_lastfailed_collectfailure(self, testdir, monkeypatch):\n\n testdir.makepyfile(\n test_maybe=\"\"\"\n import os\n env = os.environ\n if '1' == env['FAILIMPORT']:\n raise ImportError('fail')\n def test_hello():\n assert '0' == env['FAILTEST']\n \"\"\"\n )\n\n def rlf(fail_import, fail_run):\n monkeypatch.setenv(\"FAILIMPORT\", str(fail_import))\n monkeypatch.setenv(\"FAILTEST\", str(fail_run))\n\n testdir.runpytest(\"-q\")\n config = testdir.parseconfigure()\n lastfailed = config.cache.get(\"cache/lastfailed\", -1)\n return lastfailed\n\n lastfailed = rlf(fail_import=0, fail_run=0)\n assert lastfailed == -1\n\n lastfailed = rlf(fail_import=1, fail_run=0)\n assert list(lastfailed) == [\"test_maybe.py\"]\n\n lastfailed = rlf(fail_import=0, fail_run=1)\n assert list(lastfailed) == [\"test_maybe.py::test_hello\"]"},{"col":4,"comment":"Report attributes which are py.path or pathlib objects should become strings.","endLoc":222,"header":"def test_paths_support(self, testdir)","id":4243,"name":"test_paths_support","nodeType":"Function","startLoc":206,"text":"def test_paths_support(self, testdir):\n \"\"\"Report attributes which are py.path or pathlib objects should become strings.\"\"\"\n testdir.makepyfile(\n \"\"\"\n def test_a():\n assert False\n \"\"\"\n )\n reprec = testdir.inline_run()\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 3\n test_a_call = reports[1]\n test_a_call.path1 = testdir.tmpdir\n test_a_call.path2 = Path(testdir.tmpdir)\n data = test_a_call._to_json()\n assert data[\"path1\"] == str(testdir.tmpdir)\n assert data[\"path2\"] == str(testdir.tmpdir)"},{"col":0,"comment":"Non-str argument passed to warning breaks pytest (#2956)","endLoc":291,"header":"def test_non_string_warning_argument(testdir)","id":4244,"name":"test_non_string_warning_argument","nodeType":"Function","startLoc":279,"text":"def test_non_string_warning_argument(testdir):\n \"\"\"Non-str argument passed to warning breaks pytest (#2956)\"\"\"\n testdir.makepyfile(\n \"\"\"\n import warnings\n import pytest\n\n def test():\n warnings.warn(UserWarning(1, u'foo'))\n \"\"\"\n )\n result = testdir.runpytest(\"-W\", \"always\")\n result.stdout.fnmatch_lines([\"*= 1 passed, 1 warnings in *\"])"},{"col":0,"comment":"Ensure filterwarnings mark is registered","endLoc":306,"header":"def test_filterwarnings_mark_registration(testdir)","id":4245,"name":"test_filterwarnings_mark_registration","nodeType":"Function","startLoc":294,"text":"def test_filterwarnings_mark_registration(testdir):\n \"\"\"Ensure filterwarnings mark is registered\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.filterwarnings('error')\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--strict-markers\")\n assert result.ret == 0"},{"col":0,"comment":"null","endLoc":353,"header":"@pytest.mark.filterwarnings(\"always\")\ndef test_warning_captured_hook(testdir)","id":4246,"name":"test_warning_captured_hook","nodeType":"Function","startLoc":309,"text":"@pytest.mark.filterwarnings(\"always\")\ndef test_warning_captured_hook(testdir):\n testdir.makeconftest(\n \"\"\"\n from _pytest.warnings import _issue_warning_captured\n def pytest_configure(config):\n _issue_warning_captured(UserWarning(\"config warning\"), config.hook, stacklevel=2)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest, warnings\n\n warnings.warn(UserWarning(\"collect warning\"))\n\n @pytest.fixture\n def fix():\n warnings.warn(UserWarning(\"setup warning\"))\n yield 1\n warnings.warn(UserWarning(\"teardown warning\"))\n\n def test_func(fix):\n warnings.warn(UserWarning(\"call warning\"))\n assert fix == 1\n \"\"\"\n )\n\n collected = []\n\n class WarningCollector:\n def pytest_warning_captured(self, warning_message, when, item):\n imge_name = item.name if item is not None else \"\"\n collected.append((str(warning_message.message), when, imge_name))\n\n result = testdir.runpytest(plugins=[WarningCollector()])\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n expected = [\n (\"config warning\", \"config\", \"\"),\n (\"collect warning\", \"collect\", \"\"),\n (\"setup warning\", \"runtest\", \"test_func\"),\n (\"call warning\", \"runtest\", \"test_func\"),\n (\"teardown warning\", \"runtest\", \"test_func\"),\n ]\n assert collected == expected"},{"col":4,"comment":"null","endLoc":41,"header":"def glob(pathname: AnyStr, *, recursive: bool = False) -> list[AnyStr]","id":4247,"name":"glob","nodeType":"Function","startLoc":41,"text":"def glob(pathname: AnyStr, *, recursive: bool = False) -> list[AnyStr]: ..."},{"col":4,"comment":"null","endLoc":796,"header":"@pytest.mark.skipif('\"__pypy__\" in sys.modules')\n def test_pyc_vs_pyo(self, testdir, monkeypatch)","id":4249,"name":"test_pyc_vs_pyo","nodeType":"Function","startLoc":775,"text":"@pytest.mark.skipif('\"__pypy__\" in sys.modules')\n def test_pyc_vs_pyo(self, testdir, monkeypatch):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_optimized():\n \"hello\"\n assert test_optimized.__doc__ is None\"\"\"\n )\n p = py.path.local.make_numbered_dir(\n prefix=\"runpytest-\", keep=None, rootdir=testdir.tmpdir\n )\n tmp = \"--basetemp=%s\" % p\n monkeypatch.setenv(\"PYTHONOPTIMIZE\", \"2\")\n monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", raising=False)\n assert testdir.runpytest_subprocess(tmp).ret == 0\n tagged = \"test_pyc_vs_pyo.\" + PYTEST_TAG\n assert tagged + \".pyo\" in os.listdir(\"__pycache__\")\n monkeypatch.undo()\n monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", raising=False)\n assert testdir.runpytest_subprocess(tmp).ret == 1\n assert tagged + \".pyc\" in os.listdir(\"__pycache__\")"},{"col":0,"comment":"null","endLoc":243,"header":"def pytest_cmdline_main(config)","id":4250,"name":"pytest_cmdline_main","nodeType":"Function","startLoc":242,"text":"def pytest_cmdline_main(config):\n return wrap_session(config, _main)"},{"col":4,"comment":"Simulates pdbpp, which injects Pdb into do_debug, and uses\n self.__class__ in do_continue.\n ","endLoc":600,"header":"def test_pdb_with_injected_do_debug(self, testdir)","id":4251,"name":"test_pdb_with_injected_do_debug","nodeType":"Function","startLoc":524,"text":"def test_pdb_with_injected_do_debug(self, testdir):\n \"\"\"Simulates pdbpp, which injects Pdb into do_debug, and uses\n self.__class__ in do_continue.\n \"\"\"\n p1 = testdir.makepyfile(\n mytest=\"\"\"\n import pdb\n import pytest\n\n count_continue = 0\n\n class CustomPdb(pdb.Pdb, object):\n def do_debug(self, arg):\n import sys\n import types\n\n if sys.version_info < (3, ):\n do_debug_func = pdb.Pdb.do_debug.im_func\n else:\n do_debug_func = pdb.Pdb.do_debug\n\n newglobals = do_debug_func.__globals__.copy()\n newglobals['Pdb'] = self.__class__\n orig_do_debug = types.FunctionType(\n do_debug_func.__code__, newglobals,\n do_debug_func.__name__, do_debug_func.__defaults__,\n )\n return orig_do_debug(self, arg)\n do_debug.__doc__ = pdb.Pdb.do_debug.__doc__\n\n def do_continue(self, *args, **kwargs):\n global count_continue\n count_continue += 1\n return super(CustomPdb, self).do_continue(*args, **kwargs)\n\n def foo():\n print(\"print_from_foo\")\n\n def test_1():\n i = 0\n print(\"hello17\")\n pytest.set_trace()\n x = 3\n print(\"hello18\")\n\n assert count_continue == 2, \"unexpected_failure: %d != 2\" % count_continue\n pytest.fail(\"expected_failure\")\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--pdbcls=mytest:CustomPdb %s\" % str(p1))\n child.expect(r\"PDB set_trace \\(IO-capturing turned off\\)\")\n child.expect(r\"\\n\\(Pdb\")\n child.sendline(\"debug foo()\")\n child.expect(\"ENTERING RECURSIVE DEBUGGER\")\n child.expect(r\"\\n\\(\\(Pdb\")\n child.sendline(\"c\")\n child.expect(\"LEAVING RECURSIVE DEBUGGER\")\n assert b\"PDB continue\" not in child.before\n # No extra newline.\n assert child.before.endswith(b\"c\\r\\nprint_from_foo\\r\\n\")\n\n # set_debug should not raise outcomes.Exit, if used recrursively.\n child.sendline(\"debug 42\")\n child.sendline(\"q\")\n child.expect(\"LEAVING RECURSIVE DEBUGGER\")\n assert b\"ENTERING RECURSIVE DEBUGGER\" in child.before\n assert b\"Quitting debugger\" not in child.before\n\n child.sendline(\"c\")\n child.expect(r\"PDB continue \\(IO-capturing resumed\\)\")\n rest = child.read().decode(\"utf8\")\n assert \"hello17\" in rest # out is captured\n assert \"hello18\" in rest # out is captured\n assert \"1 failed\" in rest\n assert \"Failed: expected_failure\" in rest\n assert \"AssertionError: unexpected_failure\" not in rest\n self.flush(child)"},{"col":0,"comment":"\n Check that we also capture warnings issued during test collection (#3251).\n ","endLoc":379,"header":"@pytest.mark.filterwarnings(\"always\")\ndef test_collection_warnings(testdir)","id":4252,"name":"test_collection_warnings","nodeType":"Function","startLoc":356,"text":"@pytest.mark.filterwarnings(\"always\")\ndef test_collection_warnings(testdir):\n \"\"\"\n Check that we also capture warnings issued during test collection (#3251).\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import warnings\n\n warnings.warn(UserWarning(\"collection warning\"))\n\n def test_foo():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*== %s ==*\" % WARNINGS_SUMMARY_HEADER,\n \" *collection_warnings.py:3: UserWarning: collection warning\",\n ' warnings.warn(UserWarning(\"collection warning\"))',\n \"* 1 passed, 1 warnings*\",\n ]\n )"},{"col":0,"comment":" default command line protocol for initialization, session,\n running tests and reporting. ","endLoc":255,"header":"def _main(config, session)","id":4253,"name":"_main","nodeType":"Function","startLoc":246,"text":"def _main(config, session):\n \"\"\" default command line protocol for initialization, session,\n running tests and reporting. \"\"\"\n config.hook.pytest_collection(session=session)\n config.hook.pytest_runtestloop(session=session)\n\n if session.testsfailed:\n return EXIT_TESTSFAILED\n elif session.testscollected == 0:\n return EXIT_NOTESTSCOLLECTED"},{"attributeType":"CaptureManager","col":8,"comment":"null","endLoc":675,"id":4254,"name":"capture_manager","nodeType":"Attribute","startLoc":675,"text":"self.capture_manager"},{"attributeType":"bool","col":8,"comment":"null","endLoc":678,"id":4255,"name":"_test_outcome_written","nodeType":"Attribute","startLoc":678,"text":"self._test_outcome_written"},{"attributeType":"{__eq__}","col":8,"comment":"null","endLoc":686,"id":4256,"name":"_when","nodeType":"Attribute","startLoc":686,"text":"self._when"},{"attributeType":"bool","col":8,"comment":"null","endLoc":687,"id":4257,"name":"_section_name_shown","nodeType":"Attribute","startLoc":687,"text":"self._section_name_shown"},{"attributeType":"bool","col":8,"comment":"null","endLoc":682,"id":4258,"name":"_first_record_emitted","nodeType":"Attribute","startLoc":682,"text":"self._first_record_emitted"},{"col":0,"comment":"Add options to control log capturing.","endLoc":200,"header":"def pytest_addoption(parser)","id":4259,"name":"pytest_addoption","nodeType":"Function","startLoc":119,"text":"def pytest_addoption(parser):\n \"\"\"Add options to control log capturing.\"\"\"\n group = parser.getgroup(\"logging\")\n\n def add_option_ini(option, dest, default=None, type=None, **kwargs):\n parser.addini(\n dest, default=default, type=type, help=\"default value for \" + option\n )\n group.addoption(option, dest=dest, **kwargs)\n\n add_option_ini(\n \"--no-print-logs\",\n dest=\"log_print\",\n action=\"store_const\",\n const=False,\n default=True,\n type=\"bool\",\n help=\"disable printing caught logs on failed tests.\",\n )\n add_option_ini(\n \"--log-level\",\n dest=\"log_level\",\n default=None,\n help=\"logging level used by the logging module\",\n )\n add_option_ini(\n \"--log-format\",\n dest=\"log_format\",\n default=DEFAULT_LOG_FORMAT,\n help=\"log format as used by the logging module.\",\n )\n add_option_ini(\n \"--log-date-format\",\n dest=\"log_date_format\",\n default=DEFAULT_LOG_DATE_FORMAT,\n help=\"log date format as used by the logging module.\",\n )\n parser.addini(\n \"log_cli\",\n default=False,\n type=\"bool\",\n help='enable log display during test run (also known as \"live logging\").',\n )\n add_option_ini(\n \"--log-cli-level\", dest=\"log_cli_level\", default=None, help=\"cli logging level.\"\n )\n add_option_ini(\n \"--log-cli-format\",\n dest=\"log_cli_format\",\n default=None,\n help=\"log format as used by the logging module.\",\n )\n add_option_ini(\n \"--log-cli-date-format\",\n dest=\"log_cli_date_format\",\n default=None,\n help=\"log date format as used by the logging module.\",\n )\n add_option_ini(\n \"--log-file\",\n dest=\"log_file\",\n default=None,\n help=\"path to a file when logging will be written to.\",\n )\n add_option_ini(\n \"--log-file-level\",\n dest=\"log_file_level\",\n default=None,\n help=\"log file logging level.\",\n )\n add_option_ini(\n \"--log-file-format\",\n dest=\"log_file_format\",\n default=DEFAULT_LOG_FORMAT,\n help=\"log format as used by the logging module.\",\n )\n add_option_ini(\n \"--log-file-date-format\",\n dest=\"log_file_date_format\",\n default=DEFAULT_LOG_DATE_FORMAT,\n help=\"log date format as used by the logging module.\",\n )"},{"col":0,"comment":"null","endLoc":259,"header":"def pytest_collection(session)","id":4260,"name":"pytest_collection","nodeType":"Function","startLoc":258,"text":"def pytest_collection(session):\n return session.perform_collect()"},{"col":0,"comment":"@pytest.mark.filterwarnings should not try to escape regex characters (#3936)","endLoc":395,"header":"@pytest.mark.filterwarnings(\"always\")\ndef test_mark_regex_escape(testdir)","id":4261,"name":"test_mark_regex_escape","nodeType":"Function","startLoc":382,"text":"@pytest.mark.filterwarnings(\"always\")\ndef test_mark_regex_escape(testdir):\n \"\"\"@pytest.mark.filterwarnings should not try to escape regex characters (#3936)\"\"\"\n testdir.makepyfile(\n r\"\"\"\n import pytest, warnings\n\n @pytest.mark.filterwarnings(r\"ignore:some \\(warning\\)\")\n def test_foo():\n warnings.warn(UserWarning(\"some (warning)\"))\n \"\"\"\n )\n result = testdir.runpytest()\n assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()"},{"col":0,"comment":"null","endLoc":276,"header":"def pytest_runtestloop(session)","id":4262,"name":"pytest_runtestloop","nodeType":"Function","startLoc":262,"text":"def pytest_runtestloop(session):\n if session.testsfailed and not session.config.option.continue_on_collection_errors:\n raise session.Interrupted(\"%d errors during collection\" % session.testsfailed)\n\n if session.config.option.collectonly:\n return True\n\n for i, item in enumerate(session.items):\n nextitem = session.items[i + 1] if i + 1 < len(session.items) else None\n item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem)\n if session.shouldfail:\n raise session.Failed(session.shouldfail)\n if session.shouldstop:\n raise session.Interrupted(session.shouldstop)\n return True"},{"col":4,"comment":"null","endLoc":321,"header":"def _teardown_with_finalization(self, colitem)","id":4263,"name":"_teardown_with_finalization","nodeType":"Function","startLoc":314,"text":"def _teardown_with_finalization(self, colitem):\n self._callfinalizers(colitem)\n if hasattr(colitem, \"teardown\"):\n colitem.teardown()\n for colitem in self._finalizers:\n assert (\n colitem is None or colitem in self.stack or isinstance(colitem, tuple)\n )"},{"col":4,"comment":"null","endLoc":312,"header":"def _callfinalizers(self, colitem)","id":4264,"name":"_callfinalizers","nodeType":"Function","startLoc":299,"text":"def _callfinalizers(self, colitem):\n finalizers = self._finalizers.pop(colitem, None)\n exc = None\n while finalizers:\n fin = finalizers.pop()\n try:\n fin()\n except TEST_OUTCOME:\n # XXX Only first exception will be seen by user,\n # ideally all should be reported.\n if exc is None:\n exc = sys.exc_info()\n if exc:\n six.reraise(*exc)"},{"col":4,"comment":"null","endLoc":328,"header":"def teardown_all(self)","id":4269,"name":"teardown_all","nodeType":"Function","startLoc":323,"text":"def teardown_all(self):\n while self.stack:\n self._pop_and_teardown()\n for key in list(self._finalizers):\n self._teardown_with_finalization(key)\n assert not self._finalizers"},{"col":4,"comment":"null","endLoc":807,"header":"def test_package(self, testdir)","id":4270,"name":"test_package","nodeType":"Function","startLoc":798,"text":"def test_package(self, testdir):\n pkg = testdir.tmpdir.join(\"pkg\")\n pkg.mkdir()\n pkg.join(\"__init__.py\").ensure()\n pkg.join(\"test_blah.py\").write(\n \"\"\"\ndef test_rewritten():\n assert \"@py_builtins\" in globals()\"\"\"\n )\n assert testdir.runpytest().ret == 0"},{"col":0,"comment":"Make sure we can ignore internal pytest warnings using a warnings filter.","endLoc":435,"header":"@pytest.mark.filterwarnings(\"default\")\n@pytest.mark.parametrize(\"ignore_pytest_warnings\", [\"no\", \"ini\", \"cmdline\"])\ndef test_hide_pytest_internal_warnings(testdir, ignore_pytest_warnings)","id":4271,"name":"test_hide_pytest_internal_warnings","nodeType":"Function","startLoc":398,"text":"@pytest.mark.filterwarnings(\"default\")\n@pytest.mark.parametrize(\"ignore_pytest_warnings\", [\"no\", \"ini\", \"cmdline\"])\ndef test_hide_pytest_internal_warnings(testdir, ignore_pytest_warnings):\n \"\"\"Make sure we can ignore internal pytest warnings using a warnings filter.\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n import warnings\n\n warnings.warn(pytest.PytestWarning(\"some internal warning\"))\n\n def test_bar():\n pass\n \"\"\"\n )\n if ignore_pytest_warnings == \"ini\":\n testdir.makeini(\n \"\"\"\n [pytest]\n filterwarnings = ignore::pytest.PytestWarning\n \"\"\"\n )\n args = (\n [\"-W\", \"ignore::pytest.PytestWarning\"]\n if ignore_pytest_warnings == \"cmdline\"\n else []\n )\n result = testdir.runpytest(*args)\n if ignore_pytest_warnings != \"no\":\n assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()\n else:\n result.stdout.fnmatch_lines(\n [\n \"*== %s ==*\" % WARNINGS_SUMMARY_HEADER,\n \"*test_hide_pytest_internal_warnings.py:4: PytestWarning: some internal warning\",\n \"* 1 passed, 1 warnings *\",\n ]\n )"},{"col":4,"comment":"null","endLoc":813,"header":"def test_translate_newlines(self, testdir)","id":4272,"name":"test_translate_newlines","nodeType":"Function","startLoc":809,"text":"def test_translate_newlines(self, testdir):\n content = \"def test_rewritten():\\r\\n assert '@py_builtins' in globals()\"\n b = content.encode(\"utf-8\")\n testdir.tmpdir.join(\"test_newlines.py\").write(b, \"wb\")\n assert testdir.runpytest().ret == 0"},{"col":4,"comment":"null","endLoc":823,"header":"@pytest.mark.skipif(\n sys.version_info < (3, 4),\n reason=\"packages without __init__.py not supported on python 2\",\n )\n def test_package_without__init__py(self, testdir)","id":4273,"name":"test_package_without__init__py","nodeType":"Function","startLoc":815,"text":"@pytest.mark.skipif(\n sys.version_info < (3, 4),\n reason=\"packages without __init__.py not supported on python 2\",\n )\n def test_package_without__init__py(self, testdir):\n pkg = testdir.mkdir(\"a_package_without_init_py\")\n pkg.join(\"module.py\").ensure()\n testdir.makepyfile(\"import a_package_without_init_py.module\")\n assert testdir.runpytest().ret == EXIT_NOTESTSCOLLECTED"},{"col":0,"comment":"Context manager that prepares the whole logging machinery properly.","endLoc":228,"header":"@contextmanager\ndef catching_logs(handler, formatter=None, level=None)","id":4274,"name":"catching_logs","nodeType":"Function","startLoc":203,"text":"@contextmanager\ndef catching_logs(handler, formatter=None, level=None):\n \"\"\"Context manager that prepares the whole logging machinery properly.\"\"\"\n root_logger = logging.getLogger()\n\n if formatter is not None:\n handler.setFormatter(formatter)\n if level is not None:\n handler.setLevel(level)\n\n # Adding the same handler twice would confuse logging system.\n # Just don't do that.\n add_new_handler = handler not in root_logger.handlers\n\n if add_new_handler:\n root_logger.addHandler(handler)\n if level is not None:\n orig_level = root_logger.level\n root_logger.setLevel(min(orig_level, level))\n try:\n yield handler\n finally:\n if level is not None:\n root_logger.setLevel(orig_level)\n if add_new_handler:\n root_logger.removeHandler(handler)"},{"col":0,"comment":"Access and control log capturing.\n\n Captured logs are available through the following properties/methods::\n\n * caplog.text -> string containing formatted log output\n * caplog.records -> list of logging.LogRecord instances\n * caplog.record_tuples -> list of (logger_name, level, message) tuples\n * caplog.clear() -> clear captured records and formatted log output string\n ","endLoc":381,"header":"@pytest.fixture\ndef caplog(request)","id":4283,"name":"caplog","nodeType":"Function","startLoc":368,"text":"@pytest.fixture\ndef caplog(request):\n \"\"\"Access and control log capturing.\n\n Captured logs are available through the following properties/methods::\n\n * caplog.text -> string containing formatted log output\n * caplog.records -> list of logging.LogRecord instances\n * caplog.record_tuples -> list of (logger_name, level, message) tuples\n * caplog.clear() -> clear captured records and formatted log output string\n \"\"\"\n result = LogCaptureFixture(request.node)\n yield result\n result._finalize()"},{"col":4,"comment":"null","endLoc":834,"header":"def test_rewrite_warning(self, testdir)","id":4284,"name":"test_rewrite_warning","nodeType":"Function","startLoc":825,"text":"def test_rewrite_warning(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n pytest.register_assert_rewrite(\"_pytest\")\n \"\"\"\n )\n # needs to be a subprocess because pytester explicitly disables this warning\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*Module already imported*: _pytest\"])"},{"col":0,"comment":"null","endLoc":412,"header":"@pytest.hookimpl(trylast=True)\ndef pytest_configure(config)","id":4285,"name":"pytest_configure","nodeType":"Function","startLoc":410,"text":"@pytest.hookimpl(trylast=True)\ndef pytest_configure(config):\n config.pluginmanager.register(LoggingPlugin(config), \"logging-plugin\")"},{"col":4,"comment":"null","endLoc":848,"header":"def test_rewrite_module_imported_from_conftest(self, testdir)","id":4286,"name":"test_rewrite_module_imported_from_conftest","nodeType":"Function","startLoc":836,"text":"def test_rewrite_module_imported_from_conftest(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import test_rewrite_module_imported\n \"\"\"\n )\n testdir.makepyfile(\n test_rewrite_module_imported=\"\"\"\n def test_rewritten():\n assert \"@py_builtins\" in globals()\n \"\"\"\n )\n assert testdir.runpytest_subprocess().ret == 0"},{"attributeType":"str","col":0,"comment":"null","endLoc":19,"id":4287,"name":"DEFAULT_LOG_FORMAT","nodeType":"Attribute","startLoc":19,"text":"DEFAULT_LOG_FORMAT"},{"attributeType":"str","col":0,"comment":"null","endLoc":20,"id":4288,"name":"DEFAULT_LOG_DATE_FORMAT","nodeType":"Attribute","startLoc":20,"text":"DEFAULT_LOG_DATE_FORMAT"},{"attributeType":"Pattern","col":0,"comment":"null","endLoc":21,"id":4289,"name":"_ANSI_ESCAPE_SEQ","nodeType":"Attribute","startLoc":21,"text":"_ANSI_ESCAPE_SEQ"},{"col":0,"comment":"","endLoc":2,"header":"logging.py#","id":4290,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" Access and control log capturing. \"\"\"\n\nDEFAULT_LOG_FORMAT = \"%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s\"\n\nDEFAULT_LOG_DATE_FORMAT = \"%H:%M:%S\"\n\n_ANSI_ESCAPE_SEQ = re.compile(r\"\\x1b\\[[\\d;]+m\")\n\nif not six.PY2:\n # Formatter classes don't support format styles in PY2\n\n class PercentStyleMultiline(logging.PercentStyle):\n \"\"\"A logging style with special support for multiline messages.\n\n If the message of a record consists of multiple lines, this style\n formats the message as if each line were logged separately.\n \"\"\"\n\n @staticmethod\n def _update_message(record_dict, message):\n tmp = record_dict.copy()\n tmp[\"message\"] = message\n return tmp\n\n def format(self, record):\n if \"\\n\" in record.message:\n lines = record.message.splitlines()\n formatted = self._fmt % self._update_message(record.__dict__, lines[0])\n # TODO optimize this by introducing an option that tells the\n # logging framework that the indentation doesn't\n # change. This allows to compute the indentation only once.\n indentation = _remove_ansi_escape_sequences(formatted).find(lines[0])\n lines[0] = formatted\n return (\"\\n\" + \" \" * indentation).join(lines)\n else:\n return self._fmt % record.__dict__"},{"col":4,"comment":"\n AssertionRewriteHook should remember rewritten modules so it\n doesn't give false positives (#2005).\n ","endLoc":866,"header":"def test_remember_rewritten_modules(self, pytestconfig, testdir, monkeypatch)","id":4291,"name":"test_remember_rewritten_modules","nodeType":"Function","startLoc":850,"text":"def test_remember_rewritten_modules(self, pytestconfig, testdir, monkeypatch):\n \"\"\"\n AssertionRewriteHook should remember rewritten modules so it\n doesn't give false positives (#2005).\n \"\"\"\n monkeypatch.syspath_prepend(testdir.tmpdir)\n testdir.makepyfile(test_remember_rewritten_modules=\"\")\n warnings = []\n hook = AssertionRewritingHook(pytestconfig)\n monkeypatch.setattr(\n hook, \"_warn_already_imported\", lambda code, msg: warnings.append(msg)\n )\n hook.find_module(\"test_remember_rewritten_modules\")\n hook.load_module(\"test_remember_rewritten_modules\")\n hook.mark_rewrite(\"test_remember_rewritten_modules\")\n hook.mark_rewrite(\"test_remember_rewritten_modules\")\n assert warnings == []"},{"col":4,"comment":"null","endLoc":616,"header":"def test_pdb_without_capture(self, testdir)","id":4292,"name":"test_pdb_without_capture","nodeType":"Function","startLoc":602,"text":"def test_pdb_without_capture(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1():\n pytest.set_trace()\n \"\"\"\n )\n child = testdir.spawn_pytest(\"-s %s\" % p1)\n child.expect(r\">>> PDB set_trace >>>\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n child.expect(r\">>> PDB continue >>>\")\n child.expect(\"1 passed\")\n self.flush(child)"},{"col":44,"endLoc":860,"id":4293,"nodeType":"Lambda","startLoc":860,"text":"lambda code, msg: warnings.append(msg)"},{"col":4,"comment":"Full coverage for do_debug without capturing.\n\n This is very similar to test_pdb_interaction_continue_recursive in general,\n but mocks out ``pdb.set_trace`` for providing more coverage.\n ","endLoc":707,"header":"@pytest.mark.parametrize(\"capture_arg\", (\"\", \"-s\", \"-p no:capture\"))\n def test_pdb_continue_with_recursive_debug(self, capture_arg, testdir)","id":4295,"name":"test_pdb_continue_with_recursive_debug","nodeType":"Function","startLoc":618,"text":"@pytest.mark.parametrize(\"capture_arg\", (\"\", \"-s\", \"-p no:capture\"))\n def test_pdb_continue_with_recursive_debug(self, capture_arg, testdir):\n \"\"\"Full coverage for do_debug without capturing.\n\n This is very similar to test_pdb_interaction_continue_recursive in general,\n but mocks out ``pdb.set_trace`` for providing more coverage.\n \"\"\"\n p1 = testdir.makepyfile(\n \"\"\"\n try:\n input = raw_input\n except NameError:\n pass\n\n def set_trace():\n __import__('pdb').set_trace()\n\n def test_1(monkeypatch):\n import _pytest.debugging\n\n class pytestPDBTest(_pytest.debugging.pytestPDB):\n @classmethod\n def set_trace(cls, *args, **kwargs):\n # Init PytestPdbWrapper to handle capturing.\n _pdb = cls._init_pdb(\"set_trace\", *args, **kwargs)\n\n # Mock out pdb.Pdb.do_continue.\n import pdb\n pdb.Pdb.do_continue = lambda self, arg: None\n\n print(\"===\" + \" SET_TRACE ===\")\n assert input() == \"debug set_trace()\"\n\n # Simulate PytestPdbWrapper.do_debug\n cls._recursive_debug += 1\n print(\"ENTERING RECURSIVE DEBUGGER\")\n print(\"===\" + \" SET_TRACE_2 ===\")\n\n assert input() == \"c\"\n _pdb.do_continue(\"\")\n print(\"===\" + \" SET_TRACE_3 ===\")\n\n # Simulate PytestPdbWrapper.do_debug\n print(\"LEAVING RECURSIVE DEBUGGER\")\n cls._recursive_debug -= 1\n\n print(\"===\" + \" SET_TRACE_4 ===\")\n assert input() == \"c\"\n _pdb.do_continue(\"\")\n\n def do_continue(self, arg):\n print(\"=== do_continue\")\n\n monkeypatch.setattr(_pytest.debugging, \"pytestPDB\", pytestPDBTest)\n\n import pdb\n monkeypatch.setattr(pdb, \"set_trace\", pytestPDBTest.set_trace)\n\n set_trace()\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--tb=short %s %s\" % (p1, capture_arg))\n child.expect(\"=== SET_TRACE ===\")\n before = child.before.decode(\"utf8\")\n if not capture_arg:\n assert \">>> PDB set_trace (IO-capturing turned off) >>>\" in before\n else:\n assert \">>> PDB set_trace >>>\" in before\n child.sendline(\"debug set_trace()\")\n child.expect(\"=== SET_TRACE_2 ===\")\n before = child.before.decode(\"utf8\")\n assert \"\\r\\nENTERING RECURSIVE DEBUGGER\\r\\n\" in before\n child.sendline(\"c\")\n child.expect(\"=== SET_TRACE_3 ===\")\n\n # No continue message with recursive debugging.\n before = child.before.decode(\"utf8\")\n assert \">>> PDB continue \" not in before\n\n child.sendline(\"c\")\n child.expect(\"=== SET_TRACE_4 ===\")\n before = child.before.decode(\"utf8\")\n assert \"\\r\\nLEAVING RECURSIVE DEBUGGER\\r\\n\" in before\n child.sendline(\"c\")\n rest = child.read().decode(\"utf8\")\n if not capture_arg:\n assert \"> PDB continue (IO-capturing resumed) >\" in rest\n else:\n assert \"> PDB continue >\" in rest\n assert \"1 passed in\" in rest"},{"col":4,"comment":"null","endLoc":721,"header":"def test_pdb_used_outside_test(self, testdir)","id":4296,"name":"test_pdb_used_outside_test","nodeType":"Function","startLoc":709,"text":"def test_pdb_used_outside_test(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n pytest.set_trace()\n x = 5\n \"\"\"\n )\n child = testdir.spawn(\"{} {}\".format(sys.executable, p1))\n child.expect(\"x = 5\")\n child.expect(\"Pdb\")\n child.sendeof()\n self.flush(child)"},{"col":0,"comment":"filters defined in the command-line should take precedence over filters in ini files (#3946).","endLoc":459,"header":"@pytest.mark.parametrize(\"ignore_on_cmdline\", [True, False])\ndef test_option_precedence_cmdline_over_ini(testdir, ignore_on_cmdline)","id":4297,"name":"test_option_precedence_cmdline_over_ini","nodeType":"Function","startLoc":438,"text":"@pytest.mark.parametrize(\"ignore_on_cmdline\", [True, False])\ndef test_option_precedence_cmdline_over_ini(testdir, ignore_on_cmdline):\n \"\"\"filters defined in the command-line should take precedence over filters in ini files (#3946).\"\"\"\n testdir.makeini(\n \"\"\"\n [pytest]\n filterwarnings = error\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import warnings\n def test():\n warnings.warn(UserWarning('hello'))\n \"\"\"\n )\n args = [\"-W\", \"ignore\"] if ignore_on_cmdline else []\n result = testdir.runpytest(*args)\n if ignore_on_cmdline:\n result.stdout.fnmatch_lines([\"* 1 passed in*\"])\n else:\n result.stdout.fnmatch_lines([\"* 1 failed in*\"])"},{"col":4,"comment":"null","endLoc":881,"header":"def test_rewrite_warning_using_pytest_plugins(self, testdir)","id":4298,"name":"test_rewrite_warning_using_pytest_plugins","nodeType":"Function","startLoc":868,"text":"def test_rewrite_warning_using_pytest_plugins(self, testdir):\n testdir.makepyfile(\n **{\n \"conftest.py\": \"pytest_plugins = ['core', 'gui', 'sci']\",\n \"core.py\": \"\",\n \"gui.py\": \"pytest_plugins = ['core', 'sci']\",\n \"sci.py\": \"pytest_plugins = ['core']\",\n \"test_rewrite_warning_pytest_plugins.py\": \"def test(): pass\",\n }\n )\n testdir.chdir()\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*= 1 passed in *=*\"])\n assert \"pytest-warning summary\" not in result.stdout.str()"},{"col":4,"comment":"Check handling of failure during unserialization of report types.","endLoc":244,"header":"def test_unserialization_failure(self, testdir)","id":4299,"name":"test_unserialization_failure","nodeType":"Function","startLoc":224,"text":"def test_unserialization_failure(self, testdir):\n \"\"\"Check handling of failure during unserialization of report types.\"\"\"\n testdir.makepyfile(\n \"\"\"\n def test_a():\n assert False\n \"\"\"\n )\n reprec = testdir.inline_run()\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 3\n test_a_call = reports[1]\n data = test_a_call._to_json()\n entry = data[\"longrepr\"][\"reprtraceback\"][\"reprentries\"][0]\n assert entry[\"type\"] == \"ReprEntry\"\n\n entry[\"type\"] = \"Unknown\"\n with pytest.raises(\n RuntimeError, match=\"INTERNALERROR: Unknown entry type returned: Unknown\"\n ):\n TestReport._from_json(data)"},{"col":4,"comment":"null","endLoc":332,"header":"def teardown_exact(self, item, nextitem)","id":4300,"name":"teardown_exact","nodeType":"Function","startLoc":330,"text":"def teardown_exact(self, item, nextitem):\n needed_collectors = nextitem and nextitem.listchain() or []\n self._teardown_towards(needed_collectors)"},{"col":0,"comment":"Attempts to detect if ``path`` is the root of a Virtual Environment by\n checking for the existence of the appropriate activate script","endLoc":293,"header":"def _in_venv(path)","id":4301,"name":"_in_venv","nodeType":"Function","startLoc":279,"text":"def _in_venv(path):\n \"\"\"Attempts to detect if ``path`` is the root of a Virtual Environment by\n checking for the existence of the appropriate activate script\"\"\"\n bindir = path.join(\"Scripts\" if sys.platform.startswith(\"win\") else \"bin\")\n if not bindir.isdir():\n return False\n activates = (\n \"activate\",\n \"activate.csh\",\n \"activate.fish\",\n \"Activate\",\n \"Activate.bat\",\n \"Activate.ps1\",\n )\n return any([fname.basename in activates for fname in bindir.listdir()])"},{"col":4,"comment":"null","endLoc":738,"header":"def test_pdb_used_in_generate_tests(self, testdir)","id":4302,"name":"test_pdb_used_in_generate_tests","nodeType":"Function","startLoc":723,"text":"def test_pdb_used_in_generate_tests(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n pytest.set_trace()\n x = 5\n def test_foo(a):\n pass\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"x = 5\")\n child.expect(\"Pdb\")\n child.sendeof()\n self.flush(child)"},{"col":4,"comment":"null","endLoc":899,"header":"def test_rewrite_warning_using_pytest_plugins_env_var(self, testdir, monkeypatch)","id":4303,"name":"test_rewrite_warning_using_pytest_plugins_env_var","nodeType":"Function","startLoc":883,"text":"def test_rewrite_warning_using_pytest_plugins_env_var(self, testdir, monkeypatch):\n monkeypatch.setenv(\"PYTEST_PLUGINS\", \"plugin\")\n testdir.makepyfile(\n **{\n \"plugin.py\": \"\",\n \"test_rewrite_warning_using_pytest_plugins_env_var.py\": \"\"\"\n import plugin\n pytest_plugins = ['plugin']\n def test():\n pass\n \"\"\",\n }\n )\n testdir.chdir()\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*= 1 passed in *=*\"])\n assert \"pytest-warning summary\" not in result.stdout.str()"},{"className":"TestHooks","col":0,"comment":"Test that the hooks are working correctly for plugins","endLoc":314,"id":4304,"nodeType":"Class","startLoc":247,"text":"class TestHooks:\n \"\"\"Test that the hooks are working correctly for plugins\"\"\"\n\n def test_test_report(self, testdir, pytestconfig):\n testdir.makepyfile(\n \"\"\"\n def test_a(): assert False\n def test_b(): pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 6\n for rep in reports:\n data = pytestconfig.hook.pytest_report_to_serializable(\n config=pytestconfig, report=rep\n )\n assert data[\"_report_type\"] == \"TestReport\"\n new_rep = pytestconfig.hook.pytest_report_from_serializable(\n config=pytestconfig, data=data\n )\n assert new_rep.nodeid == rep.nodeid\n assert new_rep.when == rep.when\n assert new_rep.outcome == rep.outcome\n\n def test_collect_report(self, testdir, pytestconfig):\n testdir.makepyfile(\n \"\"\"\n def test_a(): assert False\n def test_b(): pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reports = reprec.getreports(\"pytest_collectreport\")\n assert len(reports) == 2\n for rep in reports:\n data = pytestconfig.hook.pytest_report_to_serializable(\n config=pytestconfig, report=rep\n )\n assert data[\"_report_type\"] == \"CollectReport\"\n new_rep = pytestconfig.hook.pytest_report_from_serializable(\n config=pytestconfig, data=data\n )\n assert new_rep.nodeid == rep.nodeid\n assert new_rep.when == \"collect\"\n assert new_rep.outcome == rep.outcome\n\n @pytest.mark.parametrize(\n \"hook_name\", [\"pytest_runtest_logreport\", \"pytest_collectreport\"]\n )\n def test_invalid_report_types(self, testdir, pytestconfig, hook_name):\n testdir.makepyfile(\n \"\"\"\n def test_a(): pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reports = reprec.getreports(hook_name)\n assert reports\n rep = reports[0]\n data = pytestconfig.hook.pytest_report_to_serializable(\n config=pytestconfig, report=rep\n )\n data[\"_report_type\"] = \"Unknown\"\n with pytest.raises(AssertionError):\n _ = pytestconfig.hook.pytest_report_from_serializable(\n config=pytestconfig, data=data\n )"},{"col":4,"comment":"null","endLoc":270,"header":"def test_test_report(self, testdir, pytestconfig)","id":4305,"name":"test_test_report","nodeType":"Function","startLoc":250,"text":"def test_test_report(self, testdir, pytestconfig):\n testdir.makepyfile(\n \"\"\"\n def test_a(): assert False\n def test_b(): pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reports = reprec.getreports(\"pytest_runtest_logreport\")\n assert len(reports) == 6\n for rep in reports:\n data = pytestconfig.hook.pytest_report_to_serializable(\n config=pytestconfig, report=rep\n )\n assert data[\"_report_type\"] == \"TestReport\"\n new_rep = pytestconfig.hook.pytest_report_from_serializable(\n config=pytestconfig, data=data\n )\n assert new_rep.nodeid == rep.nodeid\n assert new_rep.when == rep.when\n assert new_rep.outcome == rep.outcome"},{"col":0,"comment":"Filters defined by marks should always take precedence (#3946).","endLoc":479,"header":"def test_option_precedence_mark(testdir)","id":4306,"name":"test_option_precedence_mark","nodeType":"Function","startLoc":462,"text":"def test_option_precedence_mark(testdir):\n \"\"\"Filters defined by marks should always take precedence (#3946).\"\"\"\n testdir.makeini(\n \"\"\"\n [pytest]\n filterwarnings = ignore\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest, warnings\n @pytest.mark.filterwarnings('error')\n def test():\n warnings.warn(UserWarning('hello'))\n \"\"\"\n )\n result = testdir.runpytest(\"-W\", \"ignore\")\n result.stdout.fnmatch_lines([\"* 1 failed in*\"])"},{"fileName":"terminal.py","filePath":"src/_pytest","id":4307,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\" terminal reporting of the full testing process.\n\nThis is a good source for looking at the various reporting hooks.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport collections\nimport platform\nimport sys\nimport time\nfrom functools import partial\n\nimport attr\nimport pluggy\nimport py\nimport six\nfrom more_itertools import collapse\n\nimport pytest\nfrom _pytest import nodes\nfrom _pytest.main import EXIT_INTERRUPTED\nfrom _pytest.main import EXIT_NOTESTSCOLLECTED\nfrom _pytest.main import EXIT_OK\nfrom _pytest.main import EXIT_TESTSFAILED\nfrom _pytest.main import EXIT_USAGEERROR\n\nREPORT_COLLECTING_RESOLUTION = 0.5\n\n\nclass MoreQuietAction(argparse.Action):\n \"\"\"\n a modified copy of the argparse count action which counts down and updates\n the legacy quiet attribute at the same time\n\n used to unify verbosity handling\n \"\"\"\n\n def __init__(self, option_strings, dest, default=None, required=False, help=None):\n super(MoreQuietAction, self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=0,\n default=default,\n required=required,\n help=help,\n )\n\n def __call__(self, parser, namespace, values, option_string=None):\n new_count = getattr(namespace, self.dest, 0) - 1\n setattr(namespace, self.dest, new_count)\n # todo Deprecate config.quiet\n namespace.quiet = getattr(namespace, \"quiet\", 0) + 1\n\n\ndef pytest_addoption(parser):\n group = parser.getgroup(\"terminal reporting\", \"reporting\", after=\"general\")\n group._addoption(\n \"-v\",\n \"--verbose\",\n action=\"count\",\n default=0,\n dest=\"verbose\",\n help=\"increase verbosity.\",\n ),\n group._addoption(\n \"-q\",\n \"--quiet\",\n action=MoreQuietAction,\n default=0,\n dest=\"verbose\",\n help=\"decrease verbosity.\",\n ),\n group._addoption(\n \"--verbosity\", dest=\"verbose\", type=int, default=0, help=\"set verbosity\"\n )\n group._addoption(\n \"-r\",\n action=\"store\",\n dest=\"reportchars\",\n default=\"\",\n metavar=\"chars\",\n help=\"show extra test summary info as specified by chars: (f)ailed, \"\n \"(E)rror, (s)kipped, (x)failed, (X)passed, \"\n \"(p)assed, (P)assed with output, (a)ll except passed (p/P), or (A)ll. \"\n \"Warnings are displayed at all times except when \"\n \"--disable-warnings is set.\",\n )\n group._addoption(\n \"--disable-warnings\",\n \"--disable-pytest-warnings\",\n default=False,\n dest=\"disable_warnings\",\n action=\"store_true\",\n help=\"disable warnings summary\",\n )\n group._addoption(\n \"-l\",\n \"--showlocals\",\n action=\"store_true\",\n dest=\"showlocals\",\n default=False,\n help=\"show locals in tracebacks (disabled by default).\",\n )\n group._addoption(\n \"--tb\",\n metavar=\"style\",\n action=\"store\",\n dest=\"tbstyle\",\n default=\"auto\",\n choices=[\"auto\", \"long\", \"short\", \"no\", \"line\", \"native\"],\n help=\"traceback print mode (auto/long/short/line/native/no).\",\n )\n group._addoption(\n \"--show-capture\",\n action=\"store\",\n dest=\"showcapture\",\n choices=[\"no\", \"stdout\", \"stderr\", \"log\", \"all\"],\n default=\"all\",\n help=\"Controls how captured stdout/stderr/log is shown on failed tests. \"\n \"Default is 'all'.\",\n )\n group._addoption(\n \"--fulltrace\",\n \"--full-trace\",\n action=\"store_true\",\n default=False,\n help=\"don't cut any tracebacks (default is to cut).\",\n )\n group._addoption(\n \"--color\",\n metavar=\"color\",\n action=\"store\",\n dest=\"color\",\n default=\"auto\",\n choices=[\"yes\", \"no\", \"auto\"],\n help=\"color terminal output (yes/no/auto).\",\n )\n\n parser.addini(\n \"console_output_style\",\n help='console output: \"classic\", or with additional progress information (\"progress\" (percentage) | \"count\").',\n default=\"progress\",\n )\n\n\ndef pytest_configure(config):\n reporter = TerminalReporter(config, sys.stdout)\n config.pluginmanager.register(reporter, \"terminalreporter\")\n if config.option.debug or config.option.traceconfig:\n\n def mywriter(tags, args):\n msg = \" \".join(map(str, args))\n reporter.write_line(\"[traceconfig] \" + msg)\n\n config.trace.root.setprocessor(\"pytest:config\", mywriter)\n\n\ndef getreportopt(config):\n reportopts = \"\"\n reportchars = config.option.reportchars\n if not config.option.disable_warnings and \"w\" not in reportchars:\n reportchars += \"w\"\n elif config.option.disable_warnings and \"w\" in reportchars:\n reportchars = reportchars.replace(\"w\", \"\")\n for char in reportchars:\n if char == \"a\":\n reportopts = \"sxXwEf\"\n elif char == \"A\":\n reportopts = \"PpsxXwEf\"\n break\n elif char not in reportopts:\n reportopts += char\n return reportopts\n\n\n@pytest.hookimpl(trylast=True) # after _pytest.runner\ndef pytest_report_teststatus(report):\n if report.passed:\n letter = \".\"\n elif report.skipped:\n letter = \"s\"\n elif report.failed:\n letter = \"F\"\n if report.when != \"call\":\n letter = \"f\"\n return report.outcome, letter, report.outcome.upper()\n\n\n@attr.s\nclass WarningReport(object):\n \"\"\"\n Simple structure to hold warnings information captured by ``pytest_warning_captured``.\n\n :ivar str message: user friendly message about the warning\n :ivar str|None nodeid: node id that generated the warning (see ``get_location``).\n :ivar tuple|py.path.local fslocation:\n file system location of the source of the warning (see ``get_location``).\n \"\"\"\n\n message = attr.ib()\n nodeid = attr.ib(default=None)\n fslocation = attr.ib(default=None)\n count_towards_summary = True\n\n def get_location(self, config):\n \"\"\"\n Returns the more user-friendly information about the location\n of a warning, or None.\n \"\"\"\n if self.nodeid:\n return self.nodeid\n if self.fslocation:\n if isinstance(self.fslocation, tuple) and len(self.fslocation) >= 2:\n filename, linenum = self.fslocation[:2]\n relpath = py.path.local(filename).relto(config.invocation_dir)\n if not relpath:\n relpath = str(filename)\n return \"%s:%s\" % (relpath, linenum)\n else:\n return str(self.fslocation)\n return None\n\n\nclass TerminalReporter(object):\n def __init__(self, config, file=None):\n import _pytest.config\n\n self.config = config\n self._numcollected = 0\n self._session = None\n self._showfspath = None\n\n self.stats = {}\n self.startdir = config.invocation_dir\n if file is None:\n file = sys.stdout\n self._tw = _pytest.config.create_terminal_writer(config, file)\n # self.writer will be deprecated in pytest-3.4\n self.writer = self._tw\n self._screen_width = self._tw.fullwidth\n self.currentfspath = None\n self.reportchars = getreportopt(config)\n self.hasmarkup = self._tw.hasmarkup\n self.isatty = file.isatty()\n self._progress_nodeids_reported = set()\n self._show_progress_info = self._determine_show_progress_info()\n self._collect_report_last_write = None\n\n def _determine_show_progress_info(self):\n \"\"\"Return True if we should display progress information based on the current config\"\"\"\n # do not show progress if we are not capturing output (#3038)\n if self.config.getoption(\"capture\", \"no\") == \"no\":\n return False\n # do not show progress if we are showing fixture setup/teardown\n if self.config.getoption(\"setupshow\", False):\n return False\n cfg = self.config.getini(\"console_output_style\")\n if cfg in (\"progress\", \"count\"):\n return cfg\n return False\n\n @property\n def verbosity(self):\n return self.config.option.verbose\n\n @property\n def showheader(self):\n return self.verbosity >= 0\n\n @property\n def showfspath(self):\n if self._showfspath is None:\n return self.verbosity >= 0\n return self._showfspath\n\n @showfspath.setter\n def showfspath(self, value):\n self._showfspath = value\n\n @property\n def showlongtestinfo(self):\n return self.verbosity > 0\n\n def hasopt(self, char):\n char = {\"xfailed\": \"x\", \"skipped\": \"s\"}.get(char, char)\n return char in self.reportchars\n\n def write_fspath_result(self, nodeid, res, **markup):\n fspath = self.config.rootdir.join(nodeid.split(\"::\")[0])\n # NOTE: explicitly check for None to work around py bug, and for less\n # overhead in general (https://github.com/pytest-dev/py/pull/207).\n if self.currentfspath is None or fspath != self.currentfspath:\n if self.currentfspath is not None and self._show_progress_info:\n self._write_progress_information_filling_space()\n self.currentfspath = fspath\n fspath = self.startdir.bestrelpath(fspath)\n self._tw.line()\n self._tw.write(fspath + \" \")\n self._tw.write(res, **markup)\n\n def write_ensure_prefix(self, prefix, extra=\"\", **kwargs):\n if self.currentfspath != prefix:\n self._tw.line()\n self.currentfspath = prefix\n self._tw.write(prefix)\n if extra:\n self._tw.write(extra, **kwargs)\n self.currentfspath = -2\n\n def ensure_newline(self):\n if self.currentfspath:\n self._tw.line()\n self.currentfspath = None\n\n def write(self, content, **markup):\n self._tw.write(content, **markup)\n\n def write_line(self, line, **markup):\n if not isinstance(line, six.text_type):\n line = six.text_type(line, errors=\"replace\")\n self.ensure_newline()\n self._tw.line(line, **markup)\n\n def rewrite(self, line, **markup):\n \"\"\"\n Rewinds the terminal cursor to the beginning and writes the given line.\n\n :kwarg erase: if True, will also add spaces until the full terminal width to ensure\n previous lines are properly erased.\n\n The rest of the keyword arguments are markup instructions.\n \"\"\"\n erase = markup.pop(\"erase\", False)\n if erase:\n fill_count = self._tw.fullwidth - len(line) - 1\n fill = \" \" * fill_count\n else:\n fill = \"\"\n line = str(line)\n self._tw.write(\"\\r\" + line + fill, **markup)\n\n def write_sep(self, sep, title=None, **markup):\n self.ensure_newline()\n self._tw.sep(sep, title, **markup)\n\n def section(self, title, sep=\"=\", **kw):\n self._tw.sep(sep, title, **kw)\n\n def line(self, msg, **kw):\n self._tw.line(msg, **kw)\n\n def pytest_internalerror(self, excrepr):\n for line in six.text_type(excrepr).split(\"\\n\"):\n self.write_line(\"INTERNALERROR> \" + line)\n return 1\n\n def pytest_warning_captured(self, warning_message, item):\n # from _pytest.nodes import get_fslocation_from_item\n from _pytest.warnings import warning_record_to_str\n\n warnings = self.stats.setdefault(\"warnings\", [])\n fslocation = warning_message.filename, warning_message.lineno\n message = warning_record_to_str(warning_message)\n\n nodeid = item.nodeid if item is not None else \"\"\n warning_report = WarningReport(\n fslocation=fslocation, message=message, nodeid=nodeid\n )\n warnings.append(warning_report)\n\n def pytest_plugin_registered(self, plugin):\n if self.config.option.traceconfig:\n msg = \"PLUGIN registered: %s\" % (plugin,)\n # XXX this event may happen during setup/teardown time\n # which unfortunately captures our output here\n # which garbles our output if we use self.write_line\n self.write_line(msg)\n\n def pytest_deselected(self, items):\n self.stats.setdefault(\"deselected\", []).extend(items)\n\n def pytest_runtest_logstart(self, nodeid, location):\n # ensure that the path is printed before the\n # 1st test of a module starts running\n if self.showlongtestinfo:\n line = self._locationline(nodeid, *location)\n self.write_ensure_prefix(line, \"\")\n elif self.showfspath:\n fsid = nodeid.split(\"::\")[0]\n self.write_fspath_result(fsid, \"\")\n\n def pytest_runtest_logreport(self, report):\n self._tests_ran = True\n rep = report\n res = self.config.hook.pytest_report_teststatus(report=rep, config=self.config)\n category, letter, word = res\n if isinstance(word, tuple):\n word, markup = word\n else:\n markup = None\n self.stats.setdefault(category, []).append(rep)\n if not letter and not word:\n # probably passed setup/teardown\n return\n running_xdist = hasattr(rep, \"node\")\n if markup is None:\n was_xfail = hasattr(report, \"wasxfail\")\n if rep.passed and not was_xfail:\n markup = {\"green\": True}\n elif rep.passed and was_xfail:\n markup = {\"yellow\": True}\n elif rep.failed:\n markup = {\"red\": True}\n elif rep.skipped:\n markup = {\"yellow\": True}\n else:\n markup = {}\n if self.verbosity <= 0:\n if not running_xdist and self.showfspath:\n self.write_fspath_result(rep.nodeid, letter, **markup)\n else:\n self._tw.write(letter, **markup)\n else:\n self._progress_nodeids_reported.add(rep.nodeid)\n line = self._locationline(rep.nodeid, *rep.location)\n if not running_xdist:\n self.write_ensure_prefix(line, word, **markup)\n if self._show_progress_info:\n self._write_progress_information_filling_space()\n else:\n self.ensure_newline()\n self._tw.write(\"[%s]\" % rep.node.gateway.id)\n if self._show_progress_info:\n self._tw.write(\n self._get_progress_information_message() + \" \", cyan=True\n )\n else:\n self._tw.write(\" \")\n self._tw.write(word, **markup)\n self._tw.write(\" \" + line)\n self.currentfspath = -2\n\n def pytest_runtest_logfinish(self, nodeid):\n if self.verbosity <= 0 and self._show_progress_info:\n if self._show_progress_info == \"count\":\n num_tests = self._session.testscollected\n progress_length = len(\" [{}/{}]\".format(str(num_tests), str(num_tests)))\n else:\n progress_length = len(\" [100%]\")\n\n self._progress_nodeids_reported.add(nodeid)\n is_last_item = (\n len(self._progress_nodeids_reported) == self._session.testscollected\n )\n if is_last_item:\n self._write_progress_information_filling_space()\n else:\n w = self._width_of_current_line\n past_edge = w + progress_length + 1 >= self._screen_width\n if past_edge:\n msg = self._get_progress_information_message()\n self._tw.write(msg + \"\\n\", cyan=True)\n\n def _get_progress_information_message(self):\n collected = self._session.testscollected\n if self._show_progress_info == \"count\":\n if collected:\n progress = self._progress_nodeids_reported\n counter_format = \"{{:{}d}}\".format(len(str(collected)))\n format_string = \" [{}/{{}}]\".format(counter_format)\n return format_string.format(len(progress), collected)\n return \" [ {} / {} ]\".format(collected, collected)\n else:\n if collected:\n progress = len(self._progress_nodeids_reported) * 100 // collected\n return \" [{:3d}%]\".format(progress)\n return \" [100%]\"\n\n def _write_progress_information_filling_space(self):\n msg = self._get_progress_information_message()\n w = self._width_of_current_line\n fill = self._tw.fullwidth - w - 1\n self.write(msg.rjust(fill), cyan=True)\n\n @property\n def _width_of_current_line(self):\n \"\"\"Return the width of current line, using the superior implementation of py-1.6 when available\"\"\"\n try:\n return self._tw.width_of_current_line\n except AttributeError:\n # py < 1.6.0\n return self._tw.chars_on_current_line\n\n def pytest_collection(self):\n if self.isatty:\n if self.config.option.verbose >= 0:\n self.write(\"collecting ... \", bold=True)\n self._collect_report_last_write = time.time()\n elif self.config.option.verbose >= 1:\n self.write(\"collecting ... \", bold=True)\n\n def pytest_collectreport(self, report):\n if report.failed:\n self.stats.setdefault(\"error\", []).append(report)\n elif report.skipped:\n self.stats.setdefault(\"skipped\", []).append(report)\n items = [x for x in report.result if isinstance(x, pytest.Item)]\n self._numcollected += len(items)\n if self.isatty:\n self.report_collect()\n\n def report_collect(self, final=False):\n if self.config.option.verbose < 0:\n return\n\n if not final:\n # Only write \"collecting\" report every 0.5s.\n t = time.time()\n if (\n self._collect_report_last_write is not None\n and self._collect_report_last_write > t - REPORT_COLLECTING_RESOLUTION\n ):\n return\n self._collect_report_last_write = t\n\n errors = len(self.stats.get(\"error\", []))\n skipped = len(self.stats.get(\"skipped\", []))\n deselected = len(self.stats.get(\"deselected\", []))\n selected = self._numcollected - errors - skipped - deselected\n if final:\n line = \"collected \"\n else:\n line = \"collecting \"\n line += (\n str(self._numcollected) + \" item\" + (\"\" if self._numcollected == 1 else \"s\")\n )\n if errors:\n line += \" / %d errors\" % errors\n if deselected:\n line += \" / %d deselected\" % deselected\n if skipped:\n line += \" / %d skipped\" % skipped\n if self._numcollected > selected > 0:\n line += \" / %d selected\" % selected\n if self.isatty:\n self.rewrite(line, bold=True, erase=True)\n if final:\n self.write(\"\\n\")\n else:\n self.write_line(line)\n\n @pytest.hookimpl(trylast=True)\n def pytest_sessionstart(self, session):\n self._session = session\n self._sessionstarttime = time.time()\n if not self.showheader:\n return\n self.write_sep(\"=\", \"test session starts\", bold=True)\n verinfo = platform.python_version()\n msg = \"platform %s -- Python %s\" % (sys.platform, verinfo)\n if hasattr(sys, \"pypy_version_info\"):\n verinfo = \".\".join(map(str, sys.pypy_version_info[:3]))\n msg += \"[pypy-%s-%s]\" % (verinfo, sys.pypy_version_info[3])\n msg += \", pytest-%s, py-%s, pluggy-%s\" % (\n pytest.__version__,\n py.__version__,\n pluggy.__version__,\n )\n if (\n self.verbosity > 0\n or self.config.option.debug\n or getattr(self.config.option, \"pastebin\", None)\n ):\n msg += \" -- \" + str(sys.executable)\n self.write_line(msg)\n lines = self.config.hook.pytest_report_header(\n config=self.config, startdir=self.startdir\n )\n self._write_report_lines_from_hooks(lines)\n\n def _write_report_lines_from_hooks(self, lines):\n lines.reverse()\n for line in collapse(lines):\n self.write_line(line)\n\n def pytest_report_header(self, config):\n line = \"rootdir: %s\" % config.rootdir\n\n if config.inifile:\n line += \", inifile: \" + config.rootdir.bestrelpath(config.inifile)\n\n testpaths = config.getini(\"testpaths\")\n if testpaths and config.args == testpaths:\n rel_paths = [config.rootdir.bestrelpath(x) for x in testpaths]\n line += \", testpaths: {}\".format(\", \".join(rel_paths))\n result = [line]\n\n plugininfo = config.pluginmanager.list_plugin_distinfo()\n if plugininfo:\n result.append(\"plugins: %s\" % \", \".join(_plugin_nameversions(plugininfo)))\n return result\n\n def pytest_collection_finish(self, session):\n self.report_collect(True)\n\n if self.config.getoption(\"collectonly\"):\n self._printcollecteditems(session.items)\n\n lines = self.config.hook.pytest_report_collectionfinish(\n config=self.config, startdir=self.startdir, items=session.items\n )\n self._write_report_lines_from_hooks(lines)\n\n if self.config.getoption(\"collectonly\"):\n if self.stats.get(\"failed\"):\n self._tw.sep(\"!\", \"collection failures\")\n for rep in self.stats.get(\"failed\"):\n rep.toterminal(self._tw)\n\n def _printcollecteditems(self, items):\n # to print out items and their parent collectors\n # we take care to leave out Instances aka ()\n # because later versions are going to get rid of them anyway\n if self.config.option.verbose < 0:\n if self.config.option.verbose < -1:\n counts = {}\n for item in items:\n name = item.nodeid.split(\"::\", 1)[0]\n counts[name] = counts.get(name, 0) + 1\n for name, count in sorted(counts.items()):\n self._tw.line(\"%s: %d\" % (name, count))\n else:\n for item in items:\n self._tw.line(item.nodeid)\n return\n stack = []\n indent = \"\"\n for item in items:\n needed_collectors = item.listchain()[1:] # strip root node\n while stack:\n if stack == needed_collectors[: len(stack)]:\n break\n stack.pop()\n for col in needed_collectors[len(stack) :]:\n stack.append(col)\n if col.name == \"()\": # Skip Instances.\n continue\n indent = (len(stack) - 1) * \" \"\n self._tw.line(\"%s%s\" % (indent, col))\n if self.config.option.verbose >= 1:\n if hasattr(col, \"_obj\") and col._obj.__doc__:\n for line in col._obj.__doc__.strip().splitlines():\n self._tw.line(\"%s%s\" % (indent + \" \", line.strip()))\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_sessionfinish(self, exitstatus):\n outcome = yield\n outcome.get_result()\n self._tw.line(\"\")\n summary_exit_codes = (\n EXIT_OK,\n EXIT_TESTSFAILED,\n EXIT_INTERRUPTED,\n EXIT_USAGEERROR,\n EXIT_NOTESTSCOLLECTED,\n )\n if exitstatus in summary_exit_codes:\n self.config.hook.pytest_terminal_summary(\n terminalreporter=self, exitstatus=exitstatus, config=self.config\n )\n if exitstatus == EXIT_INTERRUPTED:\n self._report_keyboardinterrupt()\n del self._keyboardinterrupt_memo\n self.summary_stats()\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_terminal_summary(self):\n self.summary_errors()\n self.summary_failures()\n self.summary_warnings()\n self.summary_passes()\n yield\n self.short_test_summary()\n # Display any extra warnings from teardown here (if any).\n self.summary_warnings()\n\n def pytest_keyboard_interrupt(self, excinfo):\n self._keyboardinterrupt_memo = excinfo.getrepr(funcargs=True)\n\n def pytest_unconfigure(self):\n if hasattr(self, \"_keyboardinterrupt_memo\"):\n self._report_keyboardinterrupt()\n\n def _report_keyboardinterrupt(self):\n excrepr = self._keyboardinterrupt_memo\n msg = excrepr.reprcrash.message\n self.write_sep(\"!\", msg)\n if \"KeyboardInterrupt\" in msg:\n if self.config.option.fulltrace:\n excrepr.toterminal(self._tw)\n else:\n excrepr.reprcrash.toterminal(self._tw)\n self._tw.line(\n \"(to show a full traceback on KeyboardInterrupt use --fulltrace)\",\n yellow=True,\n )\n\n def _locationline(self, nodeid, fspath, lineno, domain):\n def mkrel(nodeid):\n line = self.config.cwd_relative_nodeid(nodeid)\n if domain and line.endswith(domain):\n line = line[: -len(domain)]\n values = domain.split(\"[\")\n values[0] = values[0].replace(\".\", \"::\") # don't replace '.' in params\n line += \"[\".join(values)\n return line\n\n # collect_fspath comes from testid which has a \"/\"-normalized path\n\n if fspath:\n res = mkrel(nodeid)\n if self.verbosity >= 2 and nodeid.split(\"::\")[0] != fspath.replace(\n \"\\\\\", nodes.SEP\n ):\n res += \" <- \" + self.startdir.bestrelpath(fspath)\n else:\n res = \"[location]\"\n return res + \" \"\n\n def _getfailureheadline(self, rep):\n head_line = rep.head_line\n if head_line:\n return head_line\n return \"test session\" # XXX?\n\n def _getcrashline(self, rep):\n try:\n return str(rep.longrepr.reprcrash)\n except AttributeError:\n try:\n return str(rep.longrepr)[:50]\n except AttributeError:\n return \"\"\n\n #\n # summaries for sessionfinish\n #\n def getreports(self, name):\n values = []\n for x in self.stats.get(name, []):\n if not hasattr(x, \"_pdbshown\"):\n values.append(x)\n return values\n\n def summary_warnings(self):\n if self.hasopt(\"w\"):\n all_warnings = self.stats.get(\"warnings\")\n if not all_warnings:\n return\n\n final = hasattr(self, \"_already_displayed_warnings\")\n if final:\n warning_reports = all_warnings[self._already_displayed_warnings :]\n else:\n warning_reports = all_warnings\n self._already_displayed_warnings = len(warning_reports)\n if not warning_reports:\n return\n\n reports_grouped_by_message = collections.OrderedDict()\n for wr in warning_reports:\n reports_grouped_by_message.setdefault(wr.message, []).append(wr)\n\n title = \"warnings summary (final)\" if final else \"warnings summary\"\n self.write_sep(\"=\", title, yellow=True, bold=False)\n for message, warning_reports in reports_grouped_by_message.items():\n has_any_location = False\n for w in warning_reports:\n location = w.get_location(self.config)\n if location:\n self._tw.line(str(location))\n has_any_location = True\n if has_any_location:\n lines = message.splitlines()\n indented = \"\\n\".join(\" \" + x for x in lines)\n message = indented.rstrip()\n else:\n message = message.rstrip()\n self._tw.line(message)\n self._tw.line()\n self._tw.line(\"-- Docs: https://docs.pytest.org/en/latest/warnings.html\")\n\n def summary_passes(self):\n if self.config.option.tbstyle != \"no\":\n if self.hasopt(\"P\"):\n reports = self.getreports(\"passed\")\n if not reports:\n return\n self.write_sep(\"=\", \"PASSES\")\n for rep in reports:\n if rep.sections:\n msg = self._getfailureheadline(rep)\n self.write_sep(\"_\", msg, green=True, bold=True)\n self._outrep_summary(rep)\n\n def print_teardown_sections(self, rep):\n showcapture = self.config.option.showcapture\n if showcapture == \"no\":\n return\n for secname, content in rep.sections:\n if showcapture != \"all\" and showcapture not in secname:\n continue\n if \"teardown\" in secname:\n self._tw.sep(\"-\", secname)\n if content[-1:] == \"\\n\":\n content = content[:-1]\n self._tw.line(content)\n\n def summary_failures(self):\n if self.config.option.tbstyle != \"no\":\n reports = self.getreports(\"failed\")\n if not reports:\n return\n self.write_sep(\"=\", \"FAILURES\")\n if self.config.option.tbstyle == \"line\":\n for rep in reports:\n line = self._getcrashline(rep)\n self.write_line(line)\n else:\n teardown_sections = {}\n for report in self.getreports(\"\"):\n if report.when == \"teardown\":\n teardown_sections.setdefault(report.nodeid, []).append(report)\n\n for rep in reports:\n msg = self._getfailureheadline(rep)\n self.write_sep(\"_\", msg, red=True, bold=True)\n self._outrep_summary(rep)\n for report in teardown_sections.get(rep.nodeid, []):\n self.print_teardown_sections(report)\n\n def summary_errors(self):\n if self.config.option.tbstyle != \"no\":\n reports = self.getreports(\"error\")\n if not reports:\n return\n self.write_sep(\"=\", \"ERRORS\")\n for rep in self.stats[\"error\"]:\n msg = self._getfailureheadline(rep)\n if rep.when == \"collect\":\n msg = \"ERROR collecting \" + msg\n else:\n msg = \"ERROR at %s of %s\" % (rep.when, msg)\n self.write_sep(\"_\", msg, red=True, bold=True)\n self._outrep_summary(rep)\n\n def _outrep_summary(self, rep):\n rep.toterminal(self._tw)\n showcapture = self.config.option.showcapture\n if showcapture == \"no\":\n return\n for secname, content in rep.sections:\n if showcapture != \"all\" and showcapture not in secname:\n continue\n self._tw.sep(\"-\", secname)\n if content[-1:] == \"\\n\":\n content = content[:-1]\n self._tw.line(content)\n\n def summary_stats(self):\n session_duration = time.time() - self._sessionstarttime\n (line, color) = build_summary_stats_line(self.stats)\n msg = \"%s in %.2f seconds\" % (line, session_duration)\n markup = {color: True, \"bold\": True}\n\n if self.verbosity >= 0:\n self.write_sep(\"=\", msg, **markup)\n if self.verbosity == -1:\n self.write_line(msg, **markup)\n\n def short_test_summary(self):\n if not self.reportchars:\n return\n\n def show_simple(stat, lines):\n failed = self.stats.get(stat, [])\n if not failed:\n return\n termwidth = self.writer.fullwidth\n config = self.config\n for rep in failed:\n line = _get_line_with_reprcrash_message(config, rep, termwidth)\n lines.append(line)\n\n def show_xfailed(lines):\n xfailed = self.stats.get(\"xfailed\", [])\n for rep in xfailed:\n verbose_word = rep._get_verbose_word(self.config)\n pos = _get_pos(self.config, rep)\n lines.append(\"%s %s\" % (verbose_word, pos))\n reason = rep.wasxfail\n if reason:\n lines.append(\" \" + str(reason))\n\n def show_xpassed(lines):\n xpassed = self.stats.get(\"xpassed\", [])\n for rep in xpassed:\n verbose_word = rep._get_verbose_word(self.config)\n pos = _get_pos(self.config, rep)\n reason = rep.wasxfail\n lines.append(\"%s %s %s\" % (verbose_word, pos, reason))\n\n def show_skipped(lines):\n skipped = self.stats.get(\"skipped\", [])\n fskips = _folded_skips(skipped) if skipped else []\n if not fskips:\n return\n verbose_word = skipped[0]._get_verbose_word(self.config)\n for num, fspath, lineno, reason in fskips:\n if reason.startswith(\"Skipped: \"):\n reason = reason[9:]\n if lineno is not None:\n lines.append(\n \"%s [%d] %s:%d: %s\"\n % (verbose_word, num, fspath, lineno + 1, reason)\n )\n else:\n lines.append(\"%s [%d] %s: %s\" % (verbose_word, num, fspath, reason))\n\n REPORTCHAR_ACTIONS = {\n \"x\": show_xfailed,\n \"X\": show_xpassed,\n \"f\": partial(show_simple, \"failed\"),\n \"F\": partial(show_simple, \"failed\"),\n \"s\": show_skipped,\n \"S\": show_skipped,\n \"p\": partial(show_simple, \"passed\"),\n \"E\": partial(show_simple, \"error\"),\n }\n\n lines = []\n for char in self.reportchars:\n action = REPORTCHAR_ACTIONS.get(char)\n if action: # skipping e.g. \"P\" (passed with output) here.\n action(lines)\n\n if lines:\n self.write_sep(\"=\", \"short test summary info\")\n for line in lines:\n self.write_line(line)\n\n\ndef _get_pos(config, rep):\n nodeid = config.cwd_relative_nodeid(rep.nodeid)\n return nodeid\n\n\ndef _get_line_with_reprcrash_message(config, rep, termwidth):\n \"\"\"Get summary line for a report, trying to add reprcrash message.\"\"\"\n from wcwidth import wcswidth\n\n verbose_word = rep._get_verbose_word(config)\n pos = _get_pos(config, rep)\n\n line = \"%s %s\" % (verbose_word, pos)\n len_line = wcswidth(line)\n ellipsis, len_ellipsis = \"...\", 3\n if len_line > termwidth - len_ellipsis:\n # No space for an additional message.\n return line\n\n try:\n msg = rep.longrepr.reprcrash.message\n except AttributeError:\n pass\n else:\n # Only use the first line.\n i = msg.find(\"\\n\")\n if i != -1:\n msg = msg[:i]\n len_msg = wcswidth(msg)\n\n sep, len_sep = \" - \", 3\n max_len_msg = termwidth - len_line - len_sep\n if max_len_msg >= len_ellipsis:\n if len_msg > max_len_msg:\n max_len_msg -= len_ellipsis\n msg = msg[:max_len_msg]\n while wcswidth(msg) > max_len_msg:\n msg = msg[:-1]\n if six.PY2:\n # on python 2 systems with narrow unicode compilation, trying to\n # get a single character out of a multi-byte unicode character such as\n # u'😄' will result in a High Surrogate (U+D83D) character, which is\n # rendered as u'�'; in this case we just strip that character out as it\n # serves no purpose being rendered\n try:\n surrogate = six.unichr(0xD83D)\n msg = msg.rstrip(surrogate)\n except ValueError: # pragma: no cover\n # Jython cannot represent this lone surrogate at all (#5256):\n # ValueError: unichr() arg is a lone surrogate in range\n # (0xD800, 0xDFFF) (Jython UTF-16 encoding)\n # ignore this case as it shouldn't appear in the string anyway\n pass\n msg += ellipsis\n line += sep + msg\n return line\n\n\ndef _folded_skips(skipped):\n d = {}\n for event in skipped:\n key = event.longrepr\n assert len(key) == 3, (event, key)\n keywords = getattr(event, \"keywords\", {})\n # folding reports with global pytestmark variable\n # this is workaround, because for now we cannot identify the scope of a skip marker\n # TODO: revisit after marks scope would be fixed\n if (\n event.when == \"setup\"\n and \"skip\" in keywords\n and \"pytestmark\" not in keywords\n ):\n key = (key[0], None, key[2])\n d.setdefault(key, []).append(event)\n values = []\n for key, events in d.items():\n values.append((len(events),) + key)\n return values\n\n\ndef build_summary_stats_line(stats):\n known_types = (\n \"failed passed skipped deselected xfailed xpassed warnings error\".split()\n )\n unknown_type_seen = False\n for found_type in stats:\n if found_type not in known_types:\n if found_type: # setup/teardown reports have an empty key, ignore them\n known_types.append(found_type)\n unknown_type_seen = True\n parts = []\n for key in known_types:\n reports = stats.get(key, None)\n if reports:\n count = sum(\n 1 for rep in reports if getattr(rep, \"count_towards_summary\", True)\n )\n parts.append(\"%d %s\" % (count, key))\n\n if parts:\n line = \", \".join(parts)\n else:\n line = \"no tests ran\"\n\n if \"failed\" in stats or \"error\" in stats:\n color = \"red\"\n elif \"warnings\" in stats or unknown_type_seen:\n color = \"yellow\"\n elif \"passed\" in stats:\n color = \"green\"\n else:\n color = \"yellow\"\n\n return line, color\n\n\ndef _plugin_nameversions(plugininfo):\n values = []\n for plugin, dist in plugininfo:\n # gets us name and version!\n name = \"{dist.project_name}-{dist.version}\".format(dist=dist)\n # questionable convenience, but it keeps things short\n if name.startswith(\"pytest-\"):\n name = name[7:]\n # we decided to print python package names\n # they can have more than one plugin\n if name not in values:\n values.append(name)\n return values\n"},{"col":4,"comment":"null","endLoc":745,"header":"def test_pdb_collection_failure_is_shown(self, testdir)","id":4308,"name":"test_pdb_collection_failure_is_shown","nodeType":"Function","startLoc":740,"text":"def test_pdb_collection_failure_is_shown(self, testdir):\n p1 = testdir.makepyfile(\"xxx\")\n result = testdir.runpytest_subprocess(\"--pdb\", p1)\n result.stdout.fnmatch_lines(\n [\"E NameError: *xxx*\", \"*! *Exit: Quitting debugger !*\"] # due to EOF\n )"},{"col":4,"comment":"Test that rewritten modules don't inherit the __future__ flags\n from the assertrewrite module.\n\n assertion.rewrite imports __future__.division (and others), so\n ensure rewritten modules don't inherit those flags.\n\n The test below will fail if __future__.division is enabled\n ","endLoc":919,"header":"@pytest.mark.skipif(sys.version_info[0] > 2, reason=\"python 2 only\")\n def test_rewrite_future_imports(self, testdir)","id":4309,"name":"test_rewrite_future_imports","nodeType":"Function","startLoc":901,"text":"@pytest.mark.skipif(sys.version_info[0] > 2, reason=\"python 2 only\")\n def test_rewrite_future_imports(self, testdir):\n \"\"\"Test that rewritten modules don't inherit the __future__ flags\n from the assertrewrite module.\n\n assertion.rewrite imports __future__.division (and others), so\n ensure rewritten modules don't inherit those flags.\n\n The test below will fail if __future__.division is enabled\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n def test():\n x = 1 / 2\n assert type(x) is int\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0"},{"col":4,"comment":"null","endLoc":799,"header":"@pytest.mark.parametrize(\"post_mortem\", (False, True))\n def test_enter_leave_pdb_hooks_are_called(self, post_mortem, testdir)","id":4310,"name":"test_enter_leave_pdb_hooks_are_called","nodeType":"Function","startLoc":747,"text":"@pytest.mark.parametrize(\"post_mortem\", (False, True))\n def test_enter_leave_pdb_hooks_are_called(self, post_mortem, testdir):\n testdir.makeconftest(\n \"\"\"\n mypdb = None\n\n def pytest_configure(config):\n config.testing_verification = 'configured'\n\n def pytest_enter_pdb(config, pdb):\n assert config.testing_verification == 'configured'\n print('enter_pdb_hook')\n\n global mypdb\n mypdb = pdb\n mypdb.set_attribute = \"bar\"\n\n def pytest_leave_pdb(config, pdb):\n assert config.testing_verification == 'configured'\n print('leave_pdb_hook')\n\n global mypdb\n assert mypdb is pdb\n assert mypdb.set_attribute == \"bar\"\n \"\"\"\n )\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n\n def test_set_trace():\n pytest.set_trace()\n assert 0\n\n def test_post_mortem():\n assert 0\n \"\"\"\n )\n if post_mortem:\n child = testdir.spawn_pytest(str(p1) + \" --pdb -s -k test_post_mortem\")\n else:\n child = testdir.spawn_pytest(str(p1) + \" -k test_set_trace\")\n child.expect(\"enter_pdb_hook\")\n child.sendline(\"c\")\n if post_mortem:\n child.expect(r\"PDB continue\")\n else:\n child.expect(r\"PDB continue \\(IO-capturing resumed\\)\")\n child.expect(\"Captured stdout call\")\n rest = child.read().decode(\"utf8\")\n assert \"leave_pdb_hook\" in rest\n assert \"1 failed\" in rest\n self.flush(child)"},{"col":0,"comment":"\n We need to be careful when raising the warning about unicode usage with \"warnings.warn\"\n because it might be overwritten by users and this itself causes another warning (#3691).\n ","endLoc":596,"header":"@pytest.mark.skipif(not six.PY2, reason=\"Python 2 only issue\")\ndef test_infinite_loop_warning_against_unicode_usage_py2(testdir)","id":4311,"name":"test_infinite_loop_warning_against_unicode_usage_py2","nodeType":"Function","startLoc":572,"text":"@pytest.mark.skipif(not six.PY2, reason=\"Python 2 only issue\")\ndef test_infinite_loop_warning_against_unicode_usage_py2(testdir):\n \"\"\"\n We need to be careful when raising the warning about unicode usage with \"warnings.warn\"\n because it might be overwritten by users and this itself causes another warning (#3691).\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n # -*- coding: utf-8 -*-\n from __future__ import unicode_literals\n import warnings\n import pytest\n\n def _custom_showwarning(message, *a, **b):\n return \"WARNING: {}\".format(message)\n\n warnings.formatwarning = _custom_showwarning\n\n @pytest.mark.filterwarnings(\"default\")\n def test_custom_warning_formatter():\n warnings.warn(\"¥\")\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*1 passed, * warnings in*\"])"},{"col":4,"comment":"null","endLoc":292,"header":"def test_collect_report(self, testdir, pytestconfig)","id":4312,"name":"test_collect_report","nodeType":"Function","startLoc":272,"text":"def test_collect_report(self, testdir, pytestconfig):\n testdir.makepyfile(\n \"\"\"\n def test_a(): assert False\n def test_b(): pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reports = reprec.getreports(\"pytest_collectreport\")\n assert len(reports) == 2\n for rep in reports:\n data = pytestconfig.hook.pytest_report_to_serializable(\n config=pytestconfig, report=rep\n )\n assert data[\"_report_type\"] == \"CollectReport\"\n new_rep = pytestconfig.hook.pytest_report_from_serializable(\n config=pytestconfig, data=data\n )\n assert new_rep.nodeid == rep.nodeid\n assert new_rep.when == \"collect\"\n assert new_rep.outcome == rep.outcome"},{"className":"MoreQuietAction","col":0,"comment":"\n a modified copy of the argparse count action which counts down and updates\n the legacy quiet attribute at the same time\n\n used to unify verbosity handling\n ","endLoc":56,"id":4313,"nodeType":"Class","startLoc":34,"text":"class MoreQuietAction(argparse.Action):\n \"\"\"\n a modified copy of the argparse count action which counts down and updates\n the legacy quiet attribute at the same time\n\n used to unify verbosity handling\n \"\"\"\n\n def __init__(self, option_strings, dest, default=None, required=False, help=None):\n super(MoreQuietAction, self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=0,\n default=default,\n required=required,\n help=help,\n )\n\n def __call__(self, parser, namespace, values, option_string=None):\n new_count = getattr(namespace, self.dest, 0) - 1\n setattr(namespace, self.dest, new_count)\n # todo Deprecate config.quiet\n namespace.quiet = getattr(namespace, \"quiet\", 0) + 1"},{"col":4,"comment":"null","endLoc":50,"header":"def __init__(self, option_strings, dest, default=None, required=False, help=None)","id":4314,"name":"__init__","nodeType":"Function","startLoc":42,"text":"def __init__(self, option_strings, dest, default=None, required=False, help=None):\n super(MoreQuietAction, self).__init__(\n option_strings=option_strings,\n dest=dest,\n nargs=0,\n default=default,\n required=required,\n help=help,\n )"},{"col":4,"comment":"null","endLoc":314,"header":"@pytest.mark.parametrize(\n \"hook_name\", [\"pytest_runtest_logreport\", \"pytest_collectreport\"]\n )\n def test_invalid_report_types(self, testdir, pytestconfig, hook_name)","id":4315,"name":"test_invalid_report_types","nodeType":"Function","startLoc":294,"text":"@pytest.mark.parametrize(\n \"hook_name\", [\"pytest_runtest_logreport\", \"pytest_collectreport\"]\n )\n def test_invalid_report_types(self, testdir, pytestconfig, hook_name):\n testdir.makepyfile(\n \"\"\"\n def test_a(): pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reports = reprec.getreports(hook_name)\n assert reports\n rep = reports[0]\n data = pytestconfig.hook.pytest_report_to_serializable(\n config=pytestconfig, report=rep\n )\n data[\"_report_type\"] = \"Unknown\"\n with pytest.raises(AssertionError):\n _ = pytestconfig.hook.pytest_report_from_serializable(\n config=pytestconfig, data=data\n )"},{"col":0,"comment":"null","endLoc":627,"header":"@pytest.mark.parametrize(\"change_default\", [None, \"ini\", \"cmdline\"])\ndef test_removed_in_pytest4_warning_as_error(testdir, change_default)","id":4316,"name":"test_removed_in_pytest4_warning_as_error","nodeType":"Function","startLoc":599,"text":"@pytest.mark.parametrize(\"change_default\", [None, \"ini\", \"cmdline\"])\ndef test_removed_in_pytest4_warning_as_error(testdir, change_default):\n testdir.makepyfile(\n \"\"\"\n import warnings, pytest\n def test():\n warnings.warn(pytest.RemovedInPytest4Warning(\"some warning\"))\n \"\"\"\n )\n if change_default == \"ini\":\n testdir.makeini(\n \"\"\"\n [pytest]\n filterwarnings =\n ignore::pytest.RemovedInPytest4Warning\n \"\"\"\n )\n\n args = (\n (\"-Wignore::pytest.RemovedInPytest4Warning\",)\n if change_default == \"cmdline\"\n else ()\n )\n result = testdir.runpytest(*args)\n if change_default is None:\n result.stdout.fnmatch_lines([\"* 1 failed in *\"])\n else:\n assert change_default in (\"ini\", \"cmdline\")\n result.stdout.fnmatch_lines([\"* 1 passed in *\"])"},{"col":0,"comment":"null","endLoc":324,"header":"def pytest_ignore_collect(path, config)","id":4317,"name":"pytest_ignore_collect","nodeType":"Function","startLoc":296,"text":"def pytest_ignore_collect(path, config):\n ignore_paths = config._getconftest_pathlist(\"collect_ignore\", path=path.dirpath())\n ignore_paths = ignore_paths or []\n excludeopt = config.getoption(\"ignore\")\n if excludeopt:\n ignore_paths.extend([py.path.local(x) for x in excludeopt])\n\n if py.path.local(path) in ignore_paths:\n return True\n\n ignore_globs = config._getconftest_pathlist(\n \"collect_ignore_glob\", path=path.dirpath()\n )\n ignore_globs = ignore_globs or []\n excludeglobopt = config.getoption(\"ignore_glob\")\n if excludeglobopt:\n ignore_globs.extend([py.path.local(x) for x in excludeglobopt])\n\n if any(\n fnmatch.fnmatch(six.text_type(path), six.text_type(glob))\n for glob in ignore_globs\n ):\n return True\n\n allow_in_venv = config.getoption(\"collect_in_virtualenv\")\n if not allow_in_venv and _in_venv(path):\n return True\n\n return False"},{"className":"TestAssertionRewriteHookDetails","col":0,"comment":"null","endLoc":1161,"id":4318,"nodeType":"Class","startLoc":922,"text":"class TestAssertionRewriteHookDetails(object):\n def test_loader_is_package_false_for_module(self, testdir):\n testdir.makepyfile(\n test_fun=\"\"\"\n def test_loader():\n assert not __loader__.is_package(__name__)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 passed*\"])\n\n def test_loader_is_package_true_for_package(self, testdir):\n testdir.makepyfile(\n test_fun=\"\"\"\n def test_loader():\n assert not __loader__.is_package(__name__)\n\n def test_fun():\n assert __loader__.is_package('fun')\n\n def test_missing():\n assert not __loader__.is_package('pytest_not_there')\n \"\"\"\n )\n testdir.mkpydir(\"fun\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 3 passed*\"])\n\n @pytest.mark.skipif(\"sys.version_info[0] >= 3\")\n @pytest.mark.xfail(\"hasattr(sys, 'pypy_translation_info')\")\n def test_assume_ascii(self, testdir):\n content = \"u'\\xe2\\x99\\xa5\\x01\\xfe'\"\n testdir.tmpdir.join(\"test_encoding.py\").write(content, \"wb\")\n res = testdir.runpytest()\n assert res.ret != 0\n assert \"SyntaxError: Non-ASCII character\" in res.stdout.str()\n\n @pytest.mark.skipif(\"sys.version_info[0] >= 3\")\n def test_detect_coding_cookie(self, testdir):\n testdir.makepyfile(\n test_cookie=\"\"\"\n # -*- coding: utf-8 -*-\n u\"St\\xc3\\xa4d\"\n def test_rewritten():\n assert \"@py_builtins\" in globals()\"\"\"\n )\n assert testdir.runpytest().ret == 0\n\n @pytest.mark.skipif(\"sys.version_info[0] >= 3\")\n def test_detect_coding_cookie_second_line(self, testdir):\n testdir.makepyfile(\n test_cookie=\"\"\"\n # -*- coding: utf-8 -*-\n u\"St\\xc3\\xa4d\"\n def test_rewritten():\n assert \"@py_builtins\" in globals()\"\"\"\n )\n assert testdir.runpytest().ret == 0\n\n @pytest.mark.skipif(\"sys.version_info[0] >= 3\")\n def test_detect_coding_cookie_crlf(self, testdir):\n testdir.makepyfile(\n test_cookie=\"\"\"\n # -*- coding: utf-8 -*-\n u\"St\\xc3\\xa4d\"\n def test_rewritten():\n assert \"@py_builtins\" in globals()\"\"\"\n )\n assert testdir.runpytest().ret == 0\n\n def test_sys_meta_path_munged(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_meta_path():\n import sys; sys.meta_path = []\"\"\"\n )\n assert testdir.runpytest().ret == 0\n\n def test_write_pyc(self, testdir, tmpdir, monkeypatch):\n from _pytest.assertion.rewrite import _write_pyc\n from _pytest.assertion import AssertionState\n import atomicwrites\n from contextlib import contextmanager\n\n config = testdir.parseconfig([])\n state = AssertionState(config, \"rewrite\")\n source_path = tmpdir.ensure(\"source.py\")\n pycpath = tmpdir.join(\"pyc\").strpath\n assert _write_pyc(state, [1], source_path.stat(), pycpath)\n\n @contextmanager\n def atomic_write_failed(fn, mode=\"r\", overwrite=False):\n e = IOError()\n e.errno = 10\n raise e\n yield\n\n monkeypatch.setattr(atomicwrites, \"atomic_write\", atomic_write_failed)\n assert not _write_pyc(state, [1], source_path.stat(), pycpath)\n\n def test_resources_provider_for_loader(self, testdir):\n \"\"\"\n Attempts to load resources from a package should succeed normally,\n even when the AssertionRewriteHook is used to load the modules.\n\n See #366 for details.\n \"\"\"\n pytest.importorskip(\"pkg_resources\")\n\n testdir.mkpydir(\"testpkg\")\n contents = {\n \"testpkg/test_pkg\": \"\"\"\n import pkg_resources\n\n import pytest\n from _pytest.assertion.rewrite import AssertionRewritingHook\n\n def test_load_resource():\n assert isinstance(__loader__, AssertionRewritingHook)\n res = pkg_resources.resource_string(__name__, 'resource.txt')\n res = res.decode('ascii')\n assert res == 'Load me please.'\n \"\"\"\n }\n testdir.makepyfile(**contents)\n testdir.maketxtfile(**{\"testpkg/resource\": \"Load me please.\"})\n\n result = testdir.runpytest_subprocess()\n result.assert_outcomes(passed=1)\n\n def test_read_pyc(self, tmpdir):\n \"\"\"\n Ensure that the `_read_pyc` can properly deal with corrupted pyc files.\n In those circumstances it should just give up instead of generating\n an exception that is propagated to the caller.\n \"\"\"\n import py_compile\n from _pytest.assertion.rewrite import _read_pyc\n\n source = tmpdir.join(\"source.py\")\n pyc = source + \"c\"\n\n source.write(\"def test(): pass\")\n py_compile.compile(str(source), str(pyc))\n\n contents = pyc.read(mode=\"rb\")\n strip_bytes = 20 # header is around 8 bytes, strip a little more\n assert len(contents) > strip_bytes\n pyc.write(contents[:strip_bytes], mode=\"wb\")\n\n assert _read_pyc(source, str(pyc)) is None # no error\n\n def test_reload_is_same(self, testdir):\n # A file that will be picked up during collecting.\n testdir.tmpdir.join(\"file.py\").ensure()\n testdir.tmpdir.join(\"pytest.ini\").write(\n textwrap.dedent(\n \"\"\"\n [pytest]\n python_files = *.py\n \"\"\"\n )\n )\n\n testdir.makepyfile(\n test_fun=\"\"\"\n import sys\n try:\n from imp import reload\n except ImportError:\n pass\n\n def test_loader():\n import file\n assert sys.modules[\"file\"] is reload(file)\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines([\"* 1 passed*\"])\n\n def test_reload_reloads(self, testdir):\n \"\"\"Reloading a module after change picks up the change.\"\"\"\n testdir.tmpdir.join(\"file.py\").write(\n textwrap.dedent(\n \"\"\"\n def reloaded():\n return False\n\n def rewrite_self():\n with open(__file__, 'w') as self:\n self.write('def reloaded(): return True')\n \"\"\"\n )\n )\n testdir.tmpdir.join(\"pytest.ini\").write(\n textwrap.dedent(\n \"\"\"\n [pytest]\n python_files = *.py\n \"\"\"\n )\n )\n\n testdir.makepyfile(\n test_fun=\"\"\"\n import sys\n try:\n from imp import reload\n except ImportError:\n pass\n\n def test_loader():\n import file\n assert not file.reloaded()\n file.rewrite_self()\n reload(file)\n assert file.reloaded()\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines([\"* 1 passed*\"])\n\n def test_get_data_support(self, testdir):\n \"\"\"Implement optional PEP302 api (#808).\n \"\"\"\n path = testdir.mkpydir(\"foo\")\n path.join(\"test_foo.py\").write(\n textwrap.dedent(\n \"\"\"\\\n class Test(object):\n def test_foo(self):\n import pkgutil\n data = pkgutil.get_data('foo.test_foo', 'data.txt')\n assert data == b'Hey'\n \"\"\"\n )\n )\n path.join(\"data.txt\").write(\"Hey\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":4,"comment":"null","endLoc":931,"header":"def test_loader_is_package_false_for_module(self, testdir)","id":4319,"name":"test_loader_is_package_false_for_module","nodeType":"Function","startLoc":923,"text":"def test_loader_is_package_false_for_module(self, testdir):\n testdir.makepyfile(\n test_fun=\"\"\"\n def test_loader():\n assert not __loader__.is_package(__name__)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 passed*\"])"},{"col":4,"comment":"null","endLoc":948,"header":"def test_loader_is_package_true_for_package(self, testdir)","id":4320,"name":"test_loader_is_package_true_for_package","nodeType":"Function","startLoc":933,"text":"def test_loader_is_package_true_for_package(self, testdir):\n testdir.makepyfile(\n test_fun=\"\"\"\n def test_loader():\n assert not __loader__.is_package(__name__)\n\n def test_fun():\n assert __loader__.is_package('fun')\n\n def test_missing():\n assert not __loader__.is_package('pytest_not_there')\n \"\"\"\n )\n testdir.mkpydir(\"fun\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 3 passed*\"])"},{"col":4,"comment":"null","endLoc":585,"header":"def test_lastfailed_failure_subset(self, testdir, monkeypatch)","id":4321,"name":"test_lastfailed_failure_subset","nodeType":"Function","startLoc":534,"text":"def test_lastfailed_failure_subset(self, testdir, monkeypatch):\n\n testdir.makepyfile(\n test_maybe=\"\"\"\n import os\n env = os.environ\n if '1' == env['FAILIMPORT']:\n raise ImportError('fail')\n def test_hello():\n assert '0' == env['FAILTEST']\n \"\"\"\n )\n\n testdir.makepyfile(\n test_maybe2=\"\"\"\n import os\n env = os.environ\n if '1' == env['FAILIMPORT']:\n raise ImportError('fail')\n def test_hello():\n assert '0' == env['FAILTEST']\n\n def test_pass():\n pass\n \"\"\"\n )\n\n def rlf(fail_import, fail_run, args=()):\n monkeypatch.setenv(\"FAILIMPORT\", str(fail_import))\n monkeypatch.setenv(\"FAILTEST\", str(fail_run))\n\n result = testdir.runpytest(\"-q\", \"--lf\", *args)\n config = testdir.parseconfigure()\n lastfailed = config.cache.get(\"cache/lastfailed\", -1)\n return result, lastfailed\n\n result, lastfailed = rlf(fail_import=0, fail_run=0)\n assert lastfailed == -1\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n\n result, lastfailed = rlf(fail_import=1, fail_run=0)\n assert sorted(list(lastfailed)) == [\"test_maybe.py\", \"test_maybe2.py\"]\n\n result, lastfailed = rlf(fail_import=0, fail_run=0, args=(\"test_maybe2.py\",))\n assert list(lastfailed) == [\"test_maybe.py\"]\n\n # edge case of test selection - even if we remember failures\n # from other tests we still need to run all tests if no test\n # matches the failures\n result, lastfailed = rlf(fail_import=0, fail_run=0, args=(\"test_maybe2.py\",))\n assert list(lastfailed) == [\"test_maybe.py\"]\n result.stdout.fnmatch_lines([\"*2 passed*\"])"},{"col":4,"comment":"null","endLoc":805,"header":"def test_pdb_custom_cls(self, testdir, custom_pdb_calls)","id":4322,"name":"test_pdb_custom_cls","nodeType":"Function","startLoc":801,"text":"def test_pdb_custom_cls(self, testdir, custom_pdb_calls):\n p1 = testdir.makepyfile(\"\"\"xxx \"\"\")\n result = testdir.runpytest_inprocess(\"--pdb\", \"--pdbcls=_pytest:_CustomPdb\", p1)\n result.stdout.fnmatch_lines([\"*NameError*xxx*\", \"*1 error*\"])\n assert custom_pdb_calls == [\"init\", \"reset\", \"interaction\"]"},{"col":4,"comment":"null","endLoc":957,"header":"@pytest.mark.skipif(\"sys.version_info[0] >= 3\")\n @pytest.mark.xfail(\"hasattr(sys, 'pypy_translation_info')\")\n def test_assume_ascii(self, testdir)","id":4323,"name":"test_assume_ascii","nodeType":"Function","startLoc":950,"text":"@pytest.mark.skipif(\"sys.version_info[0] >= 3\")\n @pytest.mark.xfail(\"hasattr(sys, 'pypy_translation_info')\")\n def test_assume_ascii(self, testdir):\n content = \"u'\\xe2\\x99\\xa5\\x01\\xfe'\"\n testdir.tmpdir.join(\"test_encoding.py\").write(content, \"wb\")\n res = testdir.runpytest()\n assert res.ret != 0\n assert \"SyntaxError: Non-ASCII character\" in res.stdout.str()"},{"id":4324,"name":"release-4.6.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-4.6.0\n=======================================\n\nThe pytest team is proud to announce the 4.6.0 release!\n\npytest is a mature Python testing tool with more than a 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n https://docs.pytest.org/en/latest/changelog.html\n\nFor complete documentation, please visit:\n\n https://docs.pytest.org/en/latest/\n\nAs usual, you can upgrade from pypi via:\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Akiomi Kamakura\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* David Röthlisberger\n* Evan Kepner\n* Jeffrey Rackauckas\n* MyComputer\n* Nikita Krokosh\n* Raul Tambre\n* Thomas Hisch\n* Tim Hoffmann\n* Tomer Keren\n* Victor Maryama\n* danielx123\n* oleg-yegorov\n\n\nHappy testing,\nThe Pytest Development Team\n"},{"id":4325,"name":"_template.rst","nodeType":"TextFile","path":"changelog","text":"{% for section in sections %}\n{% set underline = \"-\" %}\n{% if section %}\n{{section}}\n{{ underline * section|length }}{% set underline = \"~\" %}\n\n{% endif %}\n{% if sections[section] %}\n{% for category, val in definitions.items() if category in sections[section] %}\n\n{{ definitions[category]['name'] }}\n{{ underline * definitions[category]['name']|length }}\n\n{% if definitions[category]['showcontent'] %}\n{% for text, values in sections[section][category]|dictsort(by='value') %}\n{% set issue_joiner = joiner(', ') %}\n- {% for value in values|sort %}{{ issue_joiner() }}`{{ value }} `_{% endfor %}: {{ text }}\n\n\n{% endfor %}\n{% else %}\n- {{ sections[section][category]['']|sort|join(', ') }}\n\n\n{% endif %}\n{% if sections[section][category]|length == 0 %}\n\nNo significant changes.\n\n\n{% else %}\n{% endif %}\n{% endfor %}\n{% else %}\n\nNo significant changes.\n\n\n{% endif %}\n{% endfor %}\n"},{"id":4326,"name":"release-3.5.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.5.0\n=======================================\n\nThe pytest team is proud to announce the 3.5.0 release!\n\npytest is a mature Python testing tool with more than a 1600 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n http://doc.pytest.org/en/latest/changelog.html\n\nFor complete documentation, please visit:\n\n http://docs.pytest.org\n\nAs usual, you can upgrade from pypi via:\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Allan Feldman\n* Brian Maissy\n* Bruno Oliveira\n* Carlos Jenkins\n* Daniel Hahler\n* Florian Bruhin\n* Jason R. Coombs\n* Jeffrey Rackauckas\n* Jordan Speicher\n* Julien Palard\n* Kale Kundert\n* Kostis Anagnostopoulos\n* Kyle Altendorf\n* Maik Figura\n* Pedro Algarvio\n* Ronny Pfannschmidt\n* Tadeu Manoel\n* Tareq Alayan\n* Thomas Hisch\n* William Lee\n* codetriage-readme-bot\n* feuillemorte\n* joshm91\n* mike\n\n\nHappy testing,\nThe Pytest Development Team\n"},{"col":4,"comment":"null","endLoc":813,"header":"def test_pdb_custom_cls_invalid(self, testdir)","id":4327,"name":"test_pdb_custom_cls_invalid","nodeType":"Function","startLoc":807,"text":"def test_pdb_custom_cls_invalid(self, testdir):\n result = testdir.runpytest_inprocess(\"--pdbcls=invalid\")\n result.stderr.fnmatch_lines(\n [\n \"*: error: argument --pdbcls: 'invalid' is not in the format 'modname:classname'\"\n ]\n )"},{"col":4,"comment":"null","endLoc":821,"header":"def test_pdb_validate_usepdb_cls(self, testdir)","id":4328,"name":"test_pdb_validate_usepdb_cls","nodeType":"Function","startLoc":815,"text":"def test_pdb_validate_usepdb_cls(self, testdir):\n assert _validate_usepdb_cls(\"os.path:dirname.__name__\") == (\n \"os.path\",\n \"dirname.__name__\",\n )\n\n assert _validate_usepdb_cls(\"pdb:DoesNotExist\") == (\"pdb\", \"DoesNotExist\")"},{"col":4,"comment":"null","endLoc":827,"header":"def test_pdb_custom_cls_without_pdb(self, testdir, custom_pdb_calls)","id":4329,"name":"test_pdb_custom_cls_without_pdb","nodeType":"Function","startLoc":823,"text":"def test_pdb_custom_cls_without_pdb(self, testdir, custom_pdb_calls):\n p1 = testdir.makepyfile(\"\"\"xxx \"\"\")\n result = testdir.runpytest_inprocess(\"--pdbcls=_pytest:_CustomPdb\", p1)\n result.stdout.fnmatch_lines([\"*NameError*xxx*\", \"*1 error*\"])\n assert custom_pdb_calls == []"},{"col":4,"comment":"null","endLoc":856,"header":"def test_pdb_custom_cls_with_set_trace(self, testdir, monkeypatch)","id":4330,"name":"test_pdb_custom_cls_with_set_trace","nodeType":"Function","startLoc":829,"text":"def test_pdb_custom_cls_with_set_trace(self, testdir, monkeypatch):\n testdir.makepyfile(\n custom_pdb=\"\"\"\n class CustomPdb(object):\n def __init__(self, *args, **kwargs):\n skip = kwargs.pop(\"skip\")\n assert skip == [\"foo.*\"]\n print(\"__init__\")\n super(CustomPdb, self).__init__(*args, **kwargs)\n\n def set_trace(*args, **kwargs):\n print('custom set_trace>')\n \"\"\"\n )\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n\n def test_foo():\n pytest.set_trace(skip=['foo.*'])\n \"\"\"\n )\n monkeypatch.setenv(\"PYTHONPATH\", str(testdir.tmpdir))\n child = testdir.spawn_pytest(\"--pdbcls=custom_pdb:CustomPdb %s\" % str(p1))\n\n child.expect(\"__init__\")\n child.expect(\"custom set_trace>\")\n self.flush(child)"},{"fileName":"flask_theme_support.py","filePath":"doc/en/_themes","id":4331,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n# flasky extensions. flasky pygments style based on tango style\nfrom pygments.style import Style\nfrom pygments.token import Comment\nfrom pygments.token import Error\nfrom pygments.token import Generic\nfrom pygments.token import Keyword\nfrom pygments.token import Literal\nfrom pygments.token import Name\nfrom pygments.token import Number\nfrom pygments.token import Operator\nfrom pygments.token import Other\nfrom pygments.token import Punctuation\nfrom pygments.token import String\nfrom pygments.token import Whitespace\n\n\nclass FlaskyStyle(Style):\n background_color = \"#f8f8f8\"\n default_style = \"\"\n\n styles = {\n # No corresponding class for the following:\n # Text: \"\", # class: ''\n Whitespace: \"underline #f8f8f8\", # class: 'w'\n Error: \"#a40000 border:#ef2929\", # class: 'err'\n Other: \"#000000\", # class 'x'\n Comment: \"italic #8f5902\", # class: 'c'\n Comment.Preproc: \"noitalic\", # class: 'cp'\n Keyword: \"bold #004461\", # class: 'k'\n Keyword.Constant: \"bold #004461\", # class: 'kc'\n Keyword.Declaration: \"bold #004461\", # class: 'kd'\n Keyword.Namespace: \"bold #004461\", # class: 'kn'\n Keyword.Pseudo: \"bold #004461\", # class: 'kp'\n Keyword.Reserved: \"bold #004461\", # class: 'kr'\n Keyword.Type: \"bold #004461\", # class: 'kt'\n Operator: \"#582800\", # class: 'o'\n Operator.Word: \"bold #004461\", # class: 'ow' - like keywords\n Punctuation: \"bold #000000\", # class: 'p'\n # because special names such as Name.Class, Name.Function, etc.\n # are not recognized as such later in the parsing, we choose them\n # to look the same as ordinary variables.\n Name: \"#000000\", # class: 'n'\n Name.Attribute: \"#c4a000\", # class: 'na' - to be revised\n Name.Builtin: \"#004461\", # class: 'nb'\n Name.Builtin.Pseudo: \"#3465a4\", # class: 'bp'\n Name.Class: \"#000000\", # class: 'nc' - to be revised\n Name.Constant: \"#000000\", # class: 'no' - to be revised\n Name.Decorator: \"#888\", # class: 'nd' - to be revised\n Name.Entity: \"#ce5c00\", # class: 'ni'\n Name.Exception: \"bold #cc0000\", # class: 'ne'\n Name.Function: \"#000000\", # class: 'nf'\n Name.Property: \"#000000\", # class: 'py'\n Name.Label: \"#f57900\", # class: 'nl'\n Name.Namespace: \"#000000\", # class: 'nn' - to be revised\n Name.Other: \"#000000\", # class: 'nx'\n Name.Tag: \"bold #004461\", # class: 'nt' - like a keyword\n Name.Variable: \"#000000\", # class: 'nv' - to be revised\n Name.Variable.Class: \"#000000\", # class: 'vc' - to be revised\n Name.Variable.Global: \"#000000\", # class: 'vg' - to be revised\n Name.Variable.Instance: \"#000000\", # class: 'vi' - to be revised\n Number: \"#990000\", # class: 'm'\n Literal: \"#000000\", # class: 'l'\n Literal.Date: \"#000000\", # class: 'ld'\n String: \"#4e9a06\", # class: 's'\n String.Backtick: \"#4e9a06\", # class: 'sb'\n String.Char: \"#4e9a06\", # class: 'sc'\n String.Doc: \"italic #8f5902\", # class: 'sd' - like a comment\n String.Double: \"#4e9a06\", # class: 's2'\n String.Escape: \"#4e9a06\", # class: 'se'\n String.Heredoc: \"#4e9a06\", # class: 'sh'\n String.Interpol: \"#4e9a06\", # class: 'si'\n String.Other: \"#4e9a06\", # class: 'sx'\n String.Regex: \"#4e9a06\", # class: 'sr'\n String.Single: \"#4e9a06\", # class: 's1'\n String.Symbol: \"#4e9a06\", # class: 'ss'\n Generic: \"#000000\", # class: 'g'\n Generic.Deleted: \"#a40000\", # class: 'gd'\n Generic.Emph: \"italic #000000\", # class: 'ge'\n Generic.Error: \"#ef2929\", # class: 'gr'\n Generic.Heading: \"bold #000080\", # class: 'gh'\n Generic.Inserted: \"#00A000\", # class: 'gi'\n Generic.Output: \"#888\", # class: 'go'\n Generic.Prompt: \"#745334\", # class: 'gp'\n Generic.Strong: \"bold #000000\", # class: 'gs'\n Generic.Subheading: \"bold #800080\", # class: 'gu'\n Generic.Traceback: \"bold #a40000\", # class: 'gt'\n }\n"},{"col":4,"comment":"null","endLoc":968,"header":"@pytest.mark.skipif(\"sys.version_info[0] >= 3\")\n def test_detect_coding_cookie(self, testdir)","id":4332,"name":"test_detect_coding_cookie","nodeType":"Function","startLoc":959,"text":"@pytest.mark.skipif(\"sys.version_info[0] >= 3\")\n def test_detect_coding_cookie(self, testdir):\n testdir.makepyfile(\n test_cookie=\"\"\"\n # -*- coding: utf-8 -*-\n u\"St\\xc3\\xa4d\"\n def test_rewritten():\n assert \"@py_builtins\" in globals()\"\"\"\n )\n assert testdir.runpytest().ret == 0"},{"col":4,"comment":"null","endLoc":979,"header":"@pytest.mark.skipif(\"sys.version_info[0] >= 3\")\n def test_detect_coding_cookie_second_line(self, testdir)","id":4333,"name":"test_detect_coding_cookie_second_line","nodeType":"Function","startLoc":970,"text":"@pytest.mark.skipif(\"sys.version_info[0] >= 3\")\n def test_detect_coding_cookie_second_line(self, testdir):\n testdir.makepyfile(\n test_cookie=\"\"\"\n # -*- coding: utf-8 -*-\n u\"St\\xc3\\xa4d\"\n def test_rewritten():\n assert \"@py_builtins\" in globals()\"\"\"\n )\n assert testdir.runpytest().ret == 0"},{"col":4,"comment":"null","endLoc":990,"header":"@pytest.mark.skipif(\"sys.version_info[0] >= 3\")\n def test_detect_coding_cookie_crlf(self, testdir)","id":4334,"name":"test_detect_coding_cookie_crlf","nodeType":"Function","startLoc":981,"text":"@pytest.mark.skipif(\"sys.version_info[0] >= 3\")\n def test_detect_coding_cookie_crlf(self, testdir):\n testdir.makepyfile(\n test_cookie=\"\"\"\n # -*- coding: utf-8 -*-\n u\"St\\xc3\\xa4d\"\n def test_rewritten():\n assert \"@py_builtins\" in globals()\"\"\"\n )\n assert testdir.runpytest().ret == 0"},{"col":4,"comment":"null","endLoc":998,"header":"def test_sys_meta_path_munged(self, testdir)","id":4335,"name":"test_sys_meta_path_munged","nodeType":"Function","startLoc":992,"text":"def test_sys_meta_path_munged(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_meta_path():\n import sys; sys.meta_path = []\"\"\"\n )\n assert testdir.runpytest().ret == 0"},{"col":4,"comment":"null","endLoc":347,"header":"def _teardown_towards(self, needed_collectors)","id":4336,"name":"_teardown_towards","nodeType":"Function","startLoc":334,"text":"def _teardown_towards(self, needed_collectors):\n exc = None\n while self.stack:\n if self.stack == needed_collectors[: len(self.stack)]:\n break\n try:\n self._pop_and_teardown()\n except TEST_OUTCOME:\n # XXX Only first exception will be seen by user,\n # ideally all should be reported.\n if exc is None:\n exc = sys.exc_info()\n if exc:\n six.reraise(*exc)"},{"col":4,"comment":" setup objects along the collector chain to the test-method\n and teardown previously setup objects.","endLoc":365,"header":"def prepare(self, colitem)","id":4337,"name":"prepare","nodeType":"Function","startLoc":349,"text":"def prepare(self, colitem):\n \"\"\" setup objects along the collector chain to the test-method\n and teardown previously setup objects.\"\"\"\n needed_collectors = colitem.listchain()\n self._teardown_towards(needed_collectors)\n\n # check if the last collection node has raised an error\n for col in self.stack:\n if hasattr(col, \"_prepare_exc\"):\n six.reraise(*col._prepare_exc)\n for col in needed_collectors[len(self.stack) :]:\n self.stack.append(col)\n try:\n col.setup()\n except TEST_OUTCOME:\n col._prepare_exc = sys.exc_info()\n raise"},{"col":4,"comment":"null","endLoc":1020,"header":"def test_write_pyc(self, testdir, tmpdir, monkeypatch)","id":4338,"name":"test_write_pyc","nodeType":"Function","startLoc":1000,"text":"def test_write_pyc(self, testdir, tmpdir, monkeypatch):\n from _pytest.assertion.rewrite import _write_pyc\n from _pytest.assertion import AssertionState\n import atomicwrites\n from contextlib import contextmanager\n\n config = testdir.parseconfig([])\n state = AssertionState(config, \"rewrite\")\n source_path = tmpdir.ensure(\"source.py\")\n pycpath = tmpdir.join(\"pyc\").strpath\n assert _write_pyc(state, [1], source_path.stat(), pycpath)\n\n @contextmanager\n def atomic_write_failed(fn, mode=\"r\", overwrite=False):\n e = IOError()\n e.errno = 10\n raise e\n yield\n\n monkeypatch.setattr(atomicwrites, \"atomic_write\", atomic_write_failed)\n assert not _write_pyc(state, [1], source_path.stat(), pycpath)"},{"className":"FlaskyStyle","col":0,"comment":"null","endLoc":88,"id":4339,"nodeType":"Class","startLoc":18,"text":"class FlaskyStyle(Style):\n background_color = \"#f8f8f8\"\n default_style = \"\"\n\n styles = {\n # No corresponding class for the following:\n # Text: \"\", # class: ''\n Whitespace: \"underline #f8f8f8\", # class: 'w'\n Error: \"#a40000 border:#ef2929\", # class: 'err'\n Other: \"#000000\", # class 'x'\n Comment: \"italic #8f5902\", # class: 'c'\n Comment.Preproc: \"noitalic\", # class: 'cp'\n Keyword: \"bold #004461\", # class: 'k'\n Keyword.Constant: \"bold #004461\", # class: 'kc'\n Keyword.Declaration: \"bold #004461\", # class: 'kd'\n Keyword.Namespace: \"bold #004461\", # class: 'kn'\n Keyword.Pseudo: \"bold #004461\", # class: 'kp'\n Keyword.Reserved: \"bold #004461\", # class: 'kr'\n Keyword.Type: \"bold #004461\", # class: 'kt'\n Operator: \"#582800\", # class: 'o'\n Operator.Word: \"bold #004461\", # class: 'ow' - like keywords\n Punctuation: \"bold #000000\", # class: 'p'\n # because special names such as Name.Class, Name.Function, etc.\n # are not recognized as such later in the parsing, we choose them\n # to look the same as ordinary variables.\n Name: \"#000000\", # class: 'n'\n Name.Attribute: \"#c4a000\", # class: 'na' - to be revised\n Name.Builtin: \"#004461\", # class: 'nb'\n Name.Builtin.Pseudo: \"#3465a4\", # class: 'bp'\n Name.Class: \"#000000\", # class: 'nc' - to be revised\n Name.Constant: \"#000000\", # class: 'no' - to be revised\n Name.Decorator: \"#888\", # class: 'nd' - to be revised\n Name.Entity: \"#ce5c00\", # class: 'ni'\n Name.Exception: \"bold #cc0000\", # class: 'ne'\n Name.Function: \"#000000\", # class: 'nf'\n Name.Property: \"#000000\", # class: 'py'\n Name.Label: \"#f57900\", # class: 'nl'\n Name.Namespace: \"#000000\", # class: 'nn' - to be revised\n Name.Other: \"#000000\", # class: 'nx'\n Name.Tag: \"bold #004461\", # class: 'nt' - like a keyword\n Name.Variable: \"#000000\", # class: 'nv' - to be revised\n Name.Variable.Class: \"#000000\", # class: 'vc' - to be revised\n Name.Variable.Global: \"#000000\", # class: 'vg' - to be revised\n Name.Variable.Instance: \"#000000\", # class: 'vi' - to be revised\n Number: \"#990000\", # class: 'm'\n Literal: \"#000000\", # class: 'l'\n Literal.Date: \"#000000\", # class: 'ld'\n String: \"#4e9a06\", # class: 's'\n String.Backtick: \"#4e9a06\", # class: 'sb'\n String.Char: \"#4e9a06\", # class: 'sc'\n String.Doc: \"italic #8f5902\", # class: 'sd' - like a comment\n String.Double: \"#4e9a06\", # class: 's2'\n String.Escape: \"#4e9a06\", # class: 'se'\n String.Heredoc: \"#4e9a06\", # class: 'sh'\n String.Interpol: \"#4e9a06\", # class: 'si'\n String.Other: \"#4e9a06\", # class: 'sx'\n String.Regex: \"#4e9a06\", # class: 'sr'\n String.Single: \"#4e9a06\", # class: 's1'\n String.Symbol: \"#4e9a06\", # class: 'ss'\n Generic: \"#000000\", # class: 'g'\n Generic.Deleted: \"#a40000\", # class: 'gd'\n Generic.Emph: \"italic #000000\", # class: 'ge'\n Generic.Error: \"#ef2929\", # class: 'gr'\n Generic.Heading: \"bold #000080\", # class: 'gh'\n Generic.Inserted: \"#00A000\", # class: 'gi'\n Generic.Output: \"#888\", # class: 'go'\n Generic.Prompt: \"#745334\", # class: 'gp'\n Generic.Strong: \"bold #000000\", # class: 'gs'\n Generic.Subheading: \"bold #800080\", # class: 'gu'\n Generic.Traceback: \"bold #a40000\", # class: 'gt'\n }"},{"attributeType":"str","col":4,"comment":"null","endLoc":19,"id":4340,"name":"background_color","nodeType":"Attribute","startLoc":19,"text":"background_color"},{"attributeType":"str","col":4,"comment":"null","endLoc":20,"id":4341,"name":"default_style","nodeType":"Attribute","startLoc":20,"text":"default_style"},{"attributeType":"dict","col":4,"comment":"null","endLoc":22,"id":4342,"name":"styles","nodeType":"Attribute","startLoc":22,"text":"styles"},{"attributeType":"list","col":8,"comment":"null","endLoc":282,"id":4343,"name":"stack","nodeType":"Attribute","startLoc":282,"text":"self.stack"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":283,"id":4344,"name":"_finalizers","nodeType":"Attribute","startLoc":283,"text":"self._finalizers"},{"col":0,"comment":"null","endLoc":36,"header":"def pytest_addoption(parser)","id":4345,"name":"pytest_addoption","nodeType":"Function","startLoc":27,"text":"def pytest_addoption(parser):\n group = parser.getgroup(\"terminal reporting\", \"reporting\", after=\"general\")\n group.addoption(\n \"--durations\",\n action=\"store\",\n type=int,\n default=None,\n metavar=\"N\",\n help=\"show N slowest setup/test durations (N=0 for all).\",\n ),"},{"col":0,"comment":"Issue #4617","endLoc":696,"header":"def test_warnings_checker_twice()","id":4346,"name":"test_warnings_checker_twice","nodeType":"Function","startLoc":690,"text":"def test_warnings_checker_twice():\n \"\"\"Issue #4617\"\"\"\n expectation = pytest.warns(UserWarning)\n with expectation:\n warnings.warn(\"Message A\", UserWarning)\n with expectation:\n warnings.warn(\"Message B\", UserWarning)"},{"col":0,"comment":"null","endLoc":65,"header":"def pytest_terminal_summary(terminalreporter)","id":4347,"name":"pytest_terminal_summary","nodeType":"Function","startLoc":39,"text":"def pytest_terminal_summary(terminalreporter):\n durations = terminalreporter.config.option.durations\n verbose = terminalreporter.config.getvalue(\"verbose\")\n if durations is None:\n return\n tr = terminalreporter\n dlist = []\n for replist in tr.stats.values():\n for rep in replist:\n if hasattr(rep, \"duration\"):\n dlist.append(rep)\n if not dlist:\n return\n dlist.sort(key=lambda x: x.duration)\n dlist.reverse()\n if not durations:\n tr.write_sep(\"=\", \"slowest test durations\")\n else:\n tr.write_sep(\"=\", \"slowest %s test durations\" % durations)\n dlist = dlist[:durations]\n\n for rep in dlist:\n if verbose < 2 and rep.duration < 0.005:\n tr.write_line(\"\")\n tr.write_line(\"(0.00 durations hidden. Use -vv to show these durations.)\")\n break\n tr.write_line(\"%02.2fs %-8s %s\" % (rep.duration, rep.when, rep.nodeid))"},{"col":0,"comment":"null","endLoc":715,"header":"@pytest.mark.filterwarnings(\"always\")\ndef test_group_warnings_by_message(testdir)","id":4348,"name":"test_group_warnings_by_message","nodeType":"Function","startLoc":699,"text":"@pytest.mark.filterwarnings(\"always\")\ndef test_group_warnings_by_message(testdir):\n testdir.copy_example(\"warnings/test_group_warnings_by_message.py\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"test_group_warnings_by_message.py::test_foo[0]\",\n \"test_group_warnings_by_message.py::test_foo[1]\",\n \"test_group_warnings_by_message.py::test_foo[2]\",\n \"test_group_warnings_by_message.py::test_foo[3]\",\n \"test_group_warnings_by_message.py::test_foo[4]\",\n \"test_group_warnings_by_message.py::test_bar\",\n ]\n )\n warning_code = 'warnings.warn(UserWarning(\"foo\"))'\n assert warning_code in result.stdout.str()\n assert result.stdout.str().count(warning_code) == 1"},{"id":4349,"name":"testing/example_scripts/config/collect_pytest_prefix","nodeType":"Package"},{"fileName":"conftest.py","filePath":"testing/example_scripts/config/collect_pytest_prefix","id":4350,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nclass pytest_something(object):\n pass\n"},{"className":"pytest_something","col":0,"comment":"null","endLoc":3,"id":4351,"nodeType":"Class","startLoc":2,"text":"class pytest_something(object):\n pass"},{"fileName":"test_entry_points.py","filePath":"testing","id":4352,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport importlib_metadata\n\n\ndef test_pytest_entry_points_are_identical():\n dist = importlib_metadata.distribution(\"pytest\")\n entry_map = {ep.name: ep for ep in dist.entry_points}\n assert entry_map[\"pytest\"].value == entry_map[\"py.test\"].value\n"},{"col":0,"comment":"null","endLoc":12,"header":"def test_pytest_entry_points_are_identical()","id":4353,"name":"test_pytest_entry_points_are_identical","nodeType":"Function","startLoc":9,"text":"def test_pytest_entry_points_are_identical():\n dist = importlib_metadata.distribution(\"pytest\")\n entry_map = {ep.name: ep for ep in dist.entry_points}\n assert entry_map[\"pytest\"].value == entry_map[\"py.test\"].value"},{"attributeType":"str","col":0,"comment":"null","endLoc":11,"id":4354,"name":"WARNINGS_SUMMARY_HEADER","nodeType":"Attribute","startLoc":11,"text":"WARNINGS_SUMMARY_HEADER"},{"fileName":"test_marks_as_keywords.py","filePath":"testing/example_scripts/marks/marks_considered_keywords","id":4355,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\n@pytest.mark.foo\ndef test_mark():\n pass\n"},{"col":0,"comment":"","endLoc":2,"header":"test_warnings.py#","id":4356,"name":"","nodeType":"Function","startLoc":2,"text":"WARNINGS_SUMMARY_HEADER = \"warnings summary\""},{"col":0,"comment":"null","endLoc":7,"header":"@pytest.mark.foo\ndef test_mark()","id":4357,"name":"test_mark","nodeType":"Function","startLoc":5,"text":"@pytest.mark.foo\ndef test_mark():\n pass"},{"col":4,"comment":"\n Attempts to load resources from a package should succeed normally,\n even when the AssertionRewriteHook is used to load the modules.\n\n See #366 for details.\n ","endLoc":1050,"header":"def test_resources_provider_for_loader(self, testdir)","id":4358,"name":"test_resources_provider_for_loader","nodeType":"Function","startLoc":1022,"text":"def test_resources_provider_for_loader(self, testdir):\n \"\"\"\n Attempts to load resources from a package should succeed normally,\n even when the AssertionRewriteHook is used to load the modules.\n\n See #366 for details.\n \"\"\"\n pytest.importorskip(\"pkg_resources\")\n\n testdir.mkpydir(\"testpkg\")\n contents = {\n \"testpkg/test_pkg\": \"\"\"\n import pkg_resources\n\n import pytest\n from _pytest.assertion.rewrite import AssertionRewritingHook\n\n def test_load_resource():\n assert isinstance(__loader__, AssertionRewritingHook)\n res = pkg_resources.resource_string(__name__, 'resource.txt')\n res = res.decode('ascii')\n assert res == 'Load me please.'\n \"\"\"\n }\n testdir.makepyfile(**contents)\n testdir.maketxtfile(**{\"testpkg/resource\": \"Load me please.\"})\n\n result = testdir.runpytest_subprocess()\n result.assert_outcomes(passed=1)"},{"className":"TestDebuggingBreakpoints","col":0,"comment":"null","endLoc":996,"id":4359,"nodeType":"Class","startLoc":859,"text":"class TestDebuggingBreakpoints(object):\n def test_supports_breakpoint_module_global(self):\n \"\"\"\n Test that supports breakpoint global marks on Python 3.7+ and not on\n CPython 3.5, 2.7\n \"\"\"\n if sys.version_info.major == 3 and sys.version_info.minor >= 7:\n assert SUPPORTS_BREAKPOINT_BUILTIN is True\n if sys.version_info.major == 3 and sys.version_info.minor == 5:\n assert SUPPORTS_BREAKPOINT_BUILTIN is False\n if sys.version_info.major == 2 and sys.version_info.minor == 7:\n assert SUPPORTS_BREAKPOINT_BUILTIN is False\n\n @pytest.mark.skipif(\n not SUPPORTS_BREAKPOINT_BUILTIN, reason=\"Requires breakpoint() builtin\"\n )\n @pytest.mark.parametrize(\"arg\", [\"--pdb\", \"\"])\n def test_sys_breakpointhook_configure_and_unconfigure(self, testdir, arg):\n \"\"\"\n Test that sys.breakpointhook is set to the custom Pdb class once configured, test that\n hook is reset to system value once pytest has been unconfigured\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import sys\n from pytest import hookimpl\n from _pytest.debugging import pytestPDB\n\n def pytest_configure(config):\n config._cleanup.append(check_restored)\n\n def check_restored():\n assert sys.breakpointhook == sys.__breakpointhook__\n\n def test_check():\n assert sys.breakpointhook == pytestPDB.set_trace\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_nothing(): pass\n \"\"\"\n )\n args = (arg,) if arg else ()\n result = testdir.runpytest_subprocess(*args)\n result.stdout.fnmatch_lines([\"*1 passed in *\"])\n\n @pytest.mark.skipif(\n not SUPPORTS_BREAKPOINT_BUILTIN, reason=\"Requires breakpoint() builtin\"\n )\n def test_pdb_custom_cls(self, testdir, custom_debugger_hook):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_nothing():\n breakpoint()\n \"\"\"\n )\n result = testdir.runpytest_inprocess(\n \"--pdb\", \"--pdbcls=_pytest:_CustomDebugger\", p1\n )\n result.stdout.fnmatch_lines([\"*CustomDebugger*\", \"*1 passed*\"])\n assert custom_debugger_hook == [\"init\", \"set_trace\"]\n\n @pytest.mark.parametrize(\"arg\", [\"--pdb\", \"\"])\n @pytest.mark.skipif(\n not SUPPORTS_BREAKPOINT_BUILTIN, reason=\"Requires breakpoint() builtin\"\n )\n def test_environ_custom_class(self, testdir, custom_debugger_hook, arg):\n testdir.makeconftest(\n \"\"\"\n import os\n import sys\n\n os.environ['PYTHONBREAKPOINT'] = '_pytest._CustomDebugger.set_trace'\n\n def pytest_configure(config):\n config._cleanup.append(check_restored)\n\n def check_restored():\n assert sys.breakpointhook == sys.__breakpointhook__\n\n def test_check():\n import _pytest\n assert sys.breakpointhook is _pytest._CustomDebugger.set_trace\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_nothing(): pass\n \"\"\"\n )\n args = (arg,) if arg else ()\n result = testdir.runpytest_subprocess(*args)\n result.stdout.fnmatch_lines([\"*1 passed in *\"])\n\n @pytest.mark.skipif(\n not SUPPORTS_BREAKPOINT_BUILTIN, reason=\"Requires breakpoint() builtin\"\n )\n @pytest.mark.skipif(\n not _ENVIRON_PYTHONBREAKPOINT == \"\",\n reason=\"Requires breakpoint() default value\",\n )\n def test_sys_breakpoint_interception(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1():\n breakpoint()\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"test_1\")\n child.expect(\"Pdb\")\n child.sendline(\"quit\")\n rest = child.read().decode(\"utf8\")\n assert \"Quitting debugger\" in rest\n assert \"reading from stdin while output\" not in rest\n TestPDB.flush(child)\n\n @pytest.mark.skipif(\n not SUPPORTS_BREAKPOINT_BUILTIN, reason=\"Requires breakpoint() builtin\"\n )\n def test_pdb_not_altered(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pdb\n def test_1():\n pdb.set_trace()\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"test_1\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n rest = child.read().decode(\"utf8\")\n assert \"1 failed\" in rest\n assert \"reading from stdin while output\" not in rest\n TestPDB.flush(child)"},{"col":4,"comment":"\n Test that supports breakpoint global marks on Python 3.7+ and not on\n CPython 3.5, 2.7\n ","endLoc":870,"header":"def test_supports_breakpoint_module_global(self)","id":4360,"name":"test_supports_breakpoint_module_global","nodeType":"Function","startLoc":860,"text":"def test_supports_breakpoint_module_global(self):\n \"\"\"\n Test that supports breakpoint global marks on Python 3.7+ and not on\n CPython 3.5, 2.7\n \"\"\"\n if sys.version_info.major == 3 and sys.version_info.minor >= 7:\n assert SUPPORTS_BREAKPOINT_BUILTIN is True\n if sys.version_info.major == 3 and sys.version_info.minor == 5:\n assert SUPPORTS_BREAKPOINT_BUILTIN is False\n if sys.version_info.major == 2 and sys.version_info.minor == 7:\n assert SUPPORTS_BREAKPOINT_BUILTIN is False"},{"col":4,"comment":"\n Test that sys.breakpointhook is set to the custom Pdb class once configured, test that\n hook is reset to system value once pytest has been unconfigured\n ","endLoc":904,"header":"@pytest.mark.skipif(\n not SUPPORTS_BREAKPOINT_BUILTIN, reason=\"Requires breakpoint() builtin\"\n )\n @pytest.mark.parametrize(\"arg\", [\"--pdb\", \"\"])\n def test_sys_breakpointhook_configure_and_unconfigure(self, testdir, arg)","id":4361,"name":"test_sys_breakpointhook_configure_and_unconfigure","nodeType":"Function","startLoc":872,"text":"@pytest.mark.skipif(\n not SUPPORTS_BREAKPOINT_BUILTIN, reason=\"Requires breakpoint() builtin\"\n )\n @pytest.mark.parametrize(\"arg\", [\"--pdb\", \"\"])\n def test_sys_breakpointhook_configure_and_unconfigure(self, testdir, arg):\n \"\"\"\n Test that sys.breakpointhook is set to the custom Pdb class once configured, test that\n hook is reset to system value once pytest has been unconfigured\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import sys\n from pytest import hookimpl\n from _pytest.debugging import pytestPDB\n\n def pytest_configure(config):\n config._cleanup.append(check_restored)\n\n def check_restored():\n assert sys.breakpointhook == sys.__breakpointhook__\n\n def test_check():\n assert sys.breakpointhook == pytestPDB.set_trace\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_nothing(): pass\n \"\"\"\n )\n args = (arg,) if arg else ()\n result = testdir.runpytest_subprocess(*args)\n result.stdout.fnmatch_lines([\"*1 passed in *\"])"},{"id":4362,"name":"setup.cfg","nodeType":"TextFile","path":"","text":"[metadata]\n\nname = pytest\ndescription = pytest: simple powerful testing with Python\nlong_description = file: README.rst\nurl = https://docs.pytest.org/en/latest/\nproject_urls =\n Source=https://github.com/pytest-dev/pytest\n Tracker=https://github.com/pytest-dev/pytest/issues\n\nauthor = Holger Krekel, Bruno Oliveira, Ronny Pfannschmidt, Floris Bruynooghe, Brianna Laugher, Florian Bruhin and others\n\nlicense = MIT license\nlicense_file = LICENSE\nkeywords = test, unittest\nclassifiers =\n Development Status :: 6 - Mature\n Intended Audience :: Developers\n License :: OSI Approved :: MIT License\n Operating System :: POSIX\n Operating System :: Microsoft :: Windows\n Operating System :: MacOS :: MacOS X\n Topic :: Software Development :: Testing\n Topic :: Software Development :: Libraries\n Topic :: Utilities\n Programming Language :: Python :: 2\n Programming Language :: Python :: 2.7\n Programming Language :: Python :: 3\n Programming Language :: Python :: 3.4\n Programming Language :: Python :: 3.5\n Programming Language :: Python :: 3.6\n Programming Language :: Python :: 3.7\nplatforms = unix, linux, osx, cygwin, win32\n\n[options]\nzip_safe = no\npackages =\n _pytest\n _pytest._code\n _pytest._io\n _pytest.assertion\n _pytest.config\n _pytest.mark\n\npy_modules = pytest\npython_requires = >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*\n\n\n[options.entry_points]\nconsole_scripts =\n\tpytest=pytest:main\n\tpy.test=pytest:main\n\n[build_sphinx]\nsource-dir = doc/en/\nbuild-dir = doc/build\nall_files = 1\n\n[upload_sphinx]\nupload-dir = doc/en/build/html\n\n[bdist_wheel]\nuniversal = 1\n\n[check-manifest]\nignore =\n _pytest/_version.py\n\n\n[devpi:upload]\nformats = sdist.tgz,bdist_wheel\n"},{"col":4,"comment":"\n Ensure that the `_read_pyc` can properly deal with corrupted pyc files.\n In those circumstances it should just give up instead of generating\n an exception that is propagated to the caller.\n ","endLoc":1072,"header":"def test_read_pyc(self, tmpdir)","id":4363,"name":"test_read_pyc","nodeType":"Function","startLoc":1052,"text":"def test_read_pyc(self, tmpdir):\n \"\"\"\n Ensure that the `_read_pyc` can properly deal with corrupted pyc files.\n In those circumstances it should just give up instead of generating\n an exception that is propagated to the caller.\n \"\"\"\n import py_compile\n from _pytest.assertion.rewrite import _read_pyc\n\n source = tmpdir.join(\"source.py\")\n pyc = source + \"c\"\n\n source.write(\"def test(): pass\")\n py_compile.compile(str(source), str(pyc))\n\n contents = pyc.read(mode=\"rb\")\n strip_bytes = 20 # header is around 8 bytes, strip a little more\n assert len(contents) > strip_bytes\n pyc.write(contents[:strip_bytes], mode=\"wb\")\n\n assert _read_pyc(source, str(pyc)) is None # no error"},{"col":19,"endLoc":52,"id":4364,"nodeType":"Lambda","startLoc":52,"text":"lambda x: x.duration"},{"col":4,"comment":"null","endLoc":920,"header":"@pytest.mark.skipif(\n not SUPPORTS_BREAKPOINT_BUILTIN, reason=\"Requires breakpoint() builtin\"\n )\n def test_pdb_custom_cls(self, testdir, custom_debugger_hook)","id":4365,"name":"test_pdb_custom_cls","nodeType":"Function","startLoc":906,"text":"@pytest.mark.skipif(\n not SUPPORTS_BREAKPOINT_BUILTIN, reason=\"Requires breakpoint() builtin\"\n )\n def test_pdb_custom_cls(self, testdir, custom_debugger_hook):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_nothing():\n breakpoint()\n \"\"\"\n )\n result = testdir.runpytest_inprocess(\n \"--pdb\", \"--pdbcls=_pytest:_CustomDebugger\", p1\n )\n result.stdout.fnmatch_lines([\"*CustomDebugger*\", \"*1 passed*\"])\n assert custom_debugger_hook == [\"init\", \"set_trace\"]"},{"col":4,"comment":"null","endLoc":952,"header":"@pytest.mark.parametrize(\"arg\", [\"--pdb\", \"\"])\n @pytest.mark.skipif(\n not SUPPORTS_BREAKPOINT_BUILTIN, reason=\"Requires breakpoint() builtin\"\n )\n def test_environ_custom_class(self, testdir, custom_debugger_hook, arg)","id":4367,"name":"test_environ_custom_class","nodeType":"Function","startLoc":922,"text":"@pytest.mark.parametrize(\"arg\", [\"--pdb\", \"\"])\n @pytest.mark.skipif(\n not SUPPORTS_BREAKPOINT_BUILTIN, reason=\"Requires breakpoint() builtin\"\n )\n def test_environ_custom_class(self, testdir, custom_debugger_hook, arg):\n testdir.makeconftest(\n \"\"\"\n import os\n import sys\n\n os.environ['PYTHONBREAKPOINT'] = '_pytest._CustomDebugger.set_trace'\n\n def pytest_configure(config):\n config._cleanup.append(check_restored)\n\n def check_restored():\n assert sys.breakpointhook == sys.__breakpointhook__\n\n def test_check():\n import _pytest\n assert sys.breakpointhook is _pytest._CustomDebugger.set_trace\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_nothing(): pass\n \"\"\"\n )\n args = (arg,) if arg else ()\n result = testdir.runpytest_subprocess(*args)\n result.stdout.fnmatch_lines([\"*1 passed in *\"])"},{"col":4,"comment":"null","endLoc":975,"header":"@pytest.mark.skipif(\n not SUPPORTS_BREAKPOINT_BUILTIN, reason=\"Requires breakpoint() builtin\"\n )\n @pytest.mark.skipif(\n not _ENVIRON_PYTHONBREAKPOINT == \"\",\n reason=\"Requires breakpoint() default value\",\n )\n def test_sys_breakpoint_interception(self, testdir)","id":4368,"name":"test_sys_breakpoint_interception","nodeType":"Function","startLoc":954,"text":"@pytest.mark.skipif(\n not SUPPORTS_BREAKPOINT_BUILTIN, reason=\"Requires breakpoint() builtin\"\n )\n @pytest.mark.skipif(\n not _ENVIRON_PYTHONBREAKPOINT == \"\",\n reason=\"Requires breakpoint() default value\",\n )\n def test_sys_breakpoint_interception(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1():\n breakpoint()\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"test_1\")\n child.expect(\"Pdb\")\n child.sendline(\"quit\")\n rest = child.read().decode(\"utf8\")\n assert \"Quitting debugger\" in rest\n assert \"reading from stdin while output\" not in rest\n TestPDB.flush(child)"},{"col":4,"comment":"null","endLoc":250,"header":"def test_drop_short_0(self, parser)","id":4369,"name":"test_drop_short_0","nodeType":"Function","startLoc":243,"text":"def test_drop_short_0(self, parser):\n parser.addoption(\"--funcarg\", \"--func-arg\", action=\"store_true\")\n parser.addoption(\"--abc-def\", \"--abc-def\", action=\"store_true\")\n parser.addoption(\"--klm-hij\", action=\"store_true\")\n args = parser.parse([\"--funcarg\", \"--k\"])\n assert args.funcarg is True\n assert args.abc_def is False\n assert args.klm_hij is True"},{"col":4,"comment":"null","endLoc":56,"header":"def __call__(self, parser, namespace, values, option_string=None)","id":4370,"name":"__call__","nodeType":"Function","startLoc":52,"text":"def __call__(self, parser, namespace, values, option_string=None):\n new_count = getattr(namespace, self.dest, 0) - 1\n setattr(namespace, self.dest, new_count)\n # todo Deprecate config.quiet\n namespace.quiet = getattr(namespace, \"quiet\", 0) + 1"},{"col":4,"comment":"null","endLoc":255,"header":"def test_drop_short_2(self, parser)","id":4371,"name":"test_drop_short_2","nodeType":"Function","startLoc":252,"text":"def test_drop_short_2(self, parser):\n parser.addoption(\"--func-arg\", \"--doit\", action=\"store_true\")\n args = parser.parse([\"--doit\"])\n assert args.func_arg is True"},{"col":4,"comment":"null","endLoc":261,"header":"def test_drop_short_3(self, parser)","id":4372,"name":"test_drop_short_3","nodeType":"Function","startLoc":257,"text":"def test_drop_short_3(self, parser):\n parser.addoption(\"--func-arg\", \"--funcarg\", \"--doit\", action=\"store_true\")\n args = parser.parse([\"abcd\"])\n assert args.func_arg is False\n assert args.file_or_dir == [\"abcd\"]"},{"col":4,"comment":"null","endLoc":267,"header":"def test_drop_short_help0(self, parser, capsys)","id":4373,"name":"test_drop_short_help0","nodeType":"Function","startLoc":263,"text":"def test_drop_short_help0(self, parser, capsys):\n parser.addoption(\"--func-args\", \"--doit\", help=\"foo\", action=\"store_true\")\n parser.parse([])\n help = parser.optparser.format_help()\n assert \"--func-args, --doit foo\" in help"},{"col":4,"comment":"null","endLoc":282,"header":"def test_drop_short_help1(self, parser, capsys)","id":4374,"name":"test_drop_short_help1","nodeType":"Function","startLoc":270,"text":"def test_drop_short_help1(self, parser, capsys):\n group = parser.getgroup(\"general\")\n group.addoption(\"--doit\", \"--func-args\", action=\"store_true\", help=\"foo\")\n group._addoption(\n \"-h\",\n \"--help\",\n action=\"store_true\",\n dest=\"help\",\n help=\"show help message and configuration info\",\n )\n parser.parse([\"-h\"])\n help = parser.optparser.format_help()\n assert \"-doit, --func-args foo\" in help"},{"className":"WarningReport","col":0,"comment":"\n Simple structure to hold warnings information captured by ``pytest_warning_captured``.\n\n :ivar str message: user friendly message about the warning\n :ivar str|None nodeid: node id that generated the warning (see ``get_location``).\n :ivar tuple|py.path.local fslocation:\n file system location of the source of the warning (see ``get_location``).\n ","endLoc":225,"id":4375,"nodeType":"Class","startLoc":193,"text":"@attr.s\nclass WarningReport(object):\n \"\"\"\n Simple structure to hold warnings information captured by ``pytest_warning_captured``.\n\n :ivar str message: user friendly message about the warning\n :ivar str|None nodeid: node id that generated the warning (see ``get_location``).\n :ivar tuple|py.path.local fslocation:\n file system location of the source of the warning (see ``get_location``).\n \"\"\"\n\n message = attr.ib()\n nodeid = attr.ib(default=None)\n fslocation = attr.ib(default=None)\n count_towards_summary = True\n\n def get_location(self, config):\n \"\"\"\n Returns the more user-friendly information about the location\n of a warning, or None.\n \"\"\"\n if self.nodeid:\n return self.nodeid\n if self.fslocation:\n if isinstance(self.fslocation, tuple) and len(self.fslocation) >= 2:\n filename, linenum = self.fslocation[:2]\n relpath = py.path.local(filename).relto(config.invocation_dir)\n if not relpath:\n relpath = str(filename)\n return \"%s:%s\" % (relpath, linenum)\n else:\n return str(self.fslocation)\n return None"},{"col":4,"comment":"\n Returns the more user-friendly information about the location\n of a warning, or None.\n ","endLoc":225,"header":"def get_location(self, config)","id":4376,"name":"get_location","nodeType":"Function","startLoc":209,"text":"def get_location(self, config):\n \"\"\"\n Returns the more user-friendly information about the location\n of a warning, or None.\n \"\"\"\n if self.nodeid:\n return self.nodeid\n if self.fslocation:\n if isinstance(self.fslocation, tuple) and len(self.fslocation) >= 2:\n filename, linenum = self.fslocation[:2]\n relpath = py.path.local(filename).relto(config.invocation_dir)\n if not relpath:\n relpath = str(filename)\n return \"%s:%s\" % (relpath, linenum)\n else:\n return str(self.fslocation)\n return None"},{"col":4,"comment":"\n Help text for options with a metavar tuple should display help\n in the form \"--preferences=value1 value2 value3\" (#2004).\n ","endLoc":296,"header":"def test_multiple_metavar_help(self, parser)","id":4377,"name":"test_multiple_metavar_help","nodeType":"Function","startLoc":284,"text":"def test_multiple_metavar_help(self, parser):\n \"\"\"\n Help text for options with a metavar tuple should display help\n in the form \"--preferences=value1 value2 value3\" (#2004).\n \"\"\"\n group = parser.getgroup(\"general\")\n group.addoption(\n \"--preferences\", metavar=(\"value1\", \"value2\", \"value3\"), nargs=3\n )\n group._addoption(\"-h\", \"--help\", action=\"store_true\", dest=\"help\")\n parser.parse([\"-h\"])\n help = parser.optparser.format_help()\n assert \"--preferences=value1 value2 value3\" in help"},{"fileName":"test_runner.py","filePath":"testing","id":4378,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport inspect\nimport os\nimport sys\nimport types\n\nimport py\n\nimport _pytest._code\nimport pytest\nfrom _pytest import main\nfrom _pytest import outcomes\nfrom _pytest import reports\nfrom _pytest import runner\n\n\nclass TestSetupState(object):\n def test_setup(self, testdir):\n ss = runner.SetupState()\n item = testdir.getitem(\"def test_func(): pass\")\n values = [1]\n ss.prepare(item)\n ss.addfinalizer(values.pop, colitem=item)\n assert values\n ss._pop_and_teardown()\n assert not values\n\n def test_teardown_exact_stack_empty(self, testdir):\n item = testdir.getitem(\"def test_func(): pass\")\n ss = runner.SetupState()\n ss.teardown_exact(item, None)\n ss.teardown_exact(item, None)\n ss.teardown_exact(item, None)\n\n def test_setup_fails_and_failure_is_cached(self, testdir):\n item = testdir.getitem(\n \"\"\"\n def setup_module(mod):\n raise ValueError(42)\n def test_func(): pass\n \"\"\"\n )\n ss = runner.SetupState()\n pytest.raises(ValueError, lambda: ss.prepare(item))\n pytest.raises(ValueError, lambda: ss.prepare(item))\n\n def test_teardown_multiple_one_fails(self, testdir):\n r = []\n\n def fin1():\n r.append(\"fin1\")\n\n def fin2():\n raise Exception(\"oops\")\n\n def fin3():\n r.append(\"fin3\")\n\n item = testdir.getitem(\"def test_func(): pass\")\n ss = runner.SetupState()\n ss.addfinalizer(fin1, item)\n ss.addfinalizer(fin2, item)\n ss.addfinalizer(fin3, item)\n with pytest.raises(Exception) as err:\n ss._callfinalizers(item)\n assert err.value.args == (\"oops\",)\n assert r == [\"fin3\", \"fin1\"]\n\n def test_teardown_multiple_fail(self, testdir):\n # Ensure the first exception is the one which is re-raised.\n # Ideally both would be reported however.\n def fin1():\n raise Exception(\"oops1\")\n\n def fin2():\n raise Exception(\"oops2\")\n\n item = testdir.getitem(\"def test_func(): pass\")\n ss = runner.SetupState()\n ss.addfinalizer(fin1, item)\n ss.addfinalizer(fin2, item)\n with pytest.raises(Exception) as err:\n ss._callfinalizers(item)\n assert err.value.args == (\"oops2\",)\n\n def test_teardown_multiple_scopes_one_fails(self, testdir):\n module_teardown = []\n\n def fin_func():\n raise Exception(\"oops1\")\n\n def fin_module():\n module_teardown.append(\"fin_module\")\n\n item = testdir.getitem(\"def test_func(): pass\")\n ss = runner.SetupState()\n ss.addfinalizer(fin_module, item.listchain()[-2])\n ss.addfinalizer(fin_func, item)\n ss.prepare(item)\n with pytest.raises(Exception, match=\"oops1\"):\n ss.teardown_exact(item, None)\n assert module_teardown\n\n\nclass BaseFunctionalTests(object):\n def test_passfunction(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n rep = reports[1]\n assert rep.passed\n assert not rep.failed\n assert rep.outcome == \"passed\"\n assert not rep.longrepr\n\n def test_failfunction(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n assert 0\n \"\"\"\n )\n rep = reports[1]\n assert not rep.passed\n assert not rep.skipped\n assert rep.failed\n assert rep.when == \"call\"\n assert rep.outcome == \"failed\"\n # assert isinstance(rep.longrepr, ReprExceptionInfo)\n\n def test_skipfunction(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n import pytest\n def test_func():\n pytest.skip(\"hello\")\n \"\"\"\n )\n rep = reports[1]\n assert not rep.failed\n assert not rep.passed\n assert rep.skipped\n assert rep.outcome == \"skipped\"\n # assert rep.skipped.when == \"call\"\n # assert rep.skipped.when == \"call\"\n # assert rep.skipped == \"%sreason == \"hello\"\n # assert rep.skipped.location.lineno == 3\n # assert rep.skipped.location.path\n # assert not rep.skipped.failurerepr\n\n def test_skip_in_setup_function(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n import pytest\n def setup_function(func):\n pytest.skip(\"hello\")\n def test_func():\n pass\n \"\"\"\n )\n print(reports)\n rep = reports[0]\n assert not rep.failed\n assert not rep.passed\n assert rep.skipped\n # assert rep.skipped.reason == \"hello\"\n # assert rep.skipped.location.lineno == 3\n # assert rep.skipped.location.lineno == 3\n assert len(reports) == 2\n assert reports[1].passed # teardown\n\n def test_failure_in_setup_function(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n import pytest\n def setup_function(func):\n raise ValueError(42)\n def test_func():\n pass\n \"\"\"\n )\n rep = reports[0]\n assert not rep.skipped\n assert not rep.passed\n assert rep.failed\n assert rep.when == \"setup\"\n assert len(reports) == 2\n\n def test_failure_in_teardown_function(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n import pytest\n def teardown_function(func):\n raise ValueError(42)\n def test_func():\n pass\n \"\"\"\n )\n print(reports)\n assert len(reports) == 3\n rep = reports[2]\n assert not rep.skipped\n assert not rep.passed\n assert rep.failed\n assert rep.when == \"teardown\"\n # assert rep.longrepr.reprcrash.lineno == 3\n # assert rep.longrepr.reprtraceback.reprentries\n\n def test_custom_failure_repr(self, testdir):\n testdir.makepyfile(\n conftest=\"\"\"\n import pytest\n class Function(pytest.Function):\n def repr_failure(self, excinfo):\n return \"hello\"\n \"\"\"\n )\n reports = testdir.runitem(\n \"\"\"\n import pytest\n def test_func():\n assert 0\n \"\"\"\n )\n rep = reports[1]\n assert not rep.skipped\n assert not rep.passed\n assert rep.failed\n # assert rep.outcome.when == \"call\"\n # assert rep.failed.where.lineno == 3\n # assert rep.failed.where.path.basename == \"test_func.py\"\n # assert rep.failed.failurerepr == \"hello\"\n\n def test_teardown_final_returncode(self, testdir):\n rec = testdir.inline_runsource(\n \"\"\"\n def test_func():\n pass\n def teardown_function(func):\n raise ValueError(42)\n \"\"\"\n )\n assert rec.ret == 1\n\n def test_logstart_logfinish_hooks(self, testdir):\n rec = testdir.inline_runsource(\n \"\"\"\n import pytest\n def test_func():\n pass\n \"\"\"\n )\n reps = rec.getcalls(\"pytest_runtest_logstart pytest_runtest_logfinish\")\n assert [x._name for x in reps] == [\n \"pytest_runtest_logstart\",\n \"pytest_runtest_logfinish\",\n ]\n for rep in reps:\n assert rep.nodeid == \"test_logstart_logfinish_hooks.py::test_func\"\n assert rep.location == (\"test_logstart_logfinish_hooks.py\", 1, \"test_func\")\n\n def test_exact_teardown_issue90(self, testdir):\n rec = testdir.inline_runsource(\n \"\"\"\n import pytest\n\n class TestClass(object):\n def test_method(self):\n pass\n def teardown_class(cls):\n raise Exception()\n\n def test_func():\n import sys\n # on python2 exc_info is keept till a function exits\n # so we would end up calling test functions while\n # sys.exc_info would return the indexerror\n # from guessing the lastitem\n excinfo = sys.exc_info()\n import traceback\n assert excinfo[0] is None, \\\n traceback.format_exception(*excinfo)\n def teardown_function(func):\n raise ValueError(42)\n \"\"\"\n )\n reps = rec.getreports(\"pytest_runtest_logreport\")\n print(reps)\n for i in range(2):\n assert reps[i].nodeid.endswith(\"test_method\")\n assert reps[i].passed\n assert reps[2].when == \"teardown\"\n assert reps[2].failed\n assert len(reps) == 6\n for i in range(3, 5):\n assert reps[i].nodeid.endswith(\"test_func\")\n assert reps[i].passed\n assert reps[5].when == \"teardown\"\n assert reps[5].nodeid.endswith(\"test_func\")\n assert reps[5].failed\n\n def test_exact_teardown_issue1206(self, testdir):\n \"\"\"issue shadowing error with wrong number of arguments on teardown_method.\"\"\"\n rec = testdir.inline_runsource(\n \"\"\"\n import pytest\n\n class TestClass(object):\n def teardown_method(self, x, y, z):\n pass\n\n def test_method(self):\n assert True\n \"\"\"\n )\n reps = rec.getreports(\"pytest_runtest_logreport\")\n print(reps)\n assert len(reps) == 3\n #\n assert reps[0].nodeid.endswith(\"test_method\")\n assert reps[0].passed\n assert reps[0].when == \"setup\"\n #\n assert reps[1].nodeid.endswith(\"test_method\")\n assert reps[1].passed\n assert reps[1].when == \"call\"\n #\n assert reps[2].nodeid.endswith(\"test_method\")\n assert reps[2].failed\n assert reps[2].when == \"teardown\"\n assert reps[2].longrepr.reprcrash.message in (\n # python3 error\n \"TypeError: teardown_method() missing 2 required positional arguments: 'y' and 'z'\",\n # python2 error\n \"TypeError: teardown_method() takes exactly 4 arguments (2 given)\",\n )\n\n def test_failure_in_setup_function_ignores_custom_repr(self, testdir):\n testdir.makepyfile(\n conftest=\"\"\"\n import pytest\n class Function(pytest.Function):\n def repr_failure(self, excinfo):\n assert 0\n \"\"\"\n )\n reports = testdir.runitem(\n \"\"\"\n def setup_function(func):\n raise ValueError(42)\n def test_func():\n pass\n \"\"\"\n )\n assert len(reports) == 2\n rep = reports[0]\n print(rep)\n assert not rep.skipped\n assert not rep.passed\n assert rep.failed\n # assert rep.outcome.when == \"setup\"\n # assert rep.outcome.where.lineno == 3\n # assert rep.outcome.where.path.basename == \"test_func.py\"\n # assert instanace(rep.failed.failurerepr, PythonFailureRepr)\n\n def test_systemexit_does_not_bail_out(self, testdir):\n try:\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n raise SystemExit(42)\n \"\"\"\n )\n except SystemExit:\n pytest.fail(\"runner did not catch SystemExit\")\n rep = reports[1]\n assert rep.failed\n assert rep.when == \"call\"\n\n def test_exit_propagates(self, testdir):\n try:\n testdir.runitem(\n \"\"\"\n import pytest\n def test_func():\n raise pytest.exit.Exception()\n \"\"\"\n )\n except pytest.exit.Exception:\n pass\n else:\n pytest.fail(\"did not raise\")\n\n\nclass TestExecutionNonForked(BaseFunctionalTests):\n def getrunner(self):\n def f(item):\n return runner.runtestprotocol(item, log=False)\n\n return f\n\n def test_keyboardinterrupt_propagates(self, testdir):\n try:\n testdir.runitem(\n \"\"\"\n def test_func():\n raise KeyboardInterrupt(\"fake\")\n \"\"\"\n )\n except KeyboardInterrupt:\n pass\n else:\n pytest.fail(\"did not raise\")\n\n\nclass TestExecutionForked(BaseFunctionalTests):\n pytestmark = pytest.mark.skipif(\"not hasattr(os, 'fork')\")\n\n def getrunner(self):\n # XXX re-arrange this test to live in pytest-xdist\n boxed = pytest.importorskip(\"xdist.boxed\")\n return boxed.forked_run_report\n\n def test_suicide(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n import os\n os.kill(os.getpid(), 15)\n \"\"\"\n )\n rep = reports[0]\n assert rep.failed\n assert rep.when == \"???\"\n\n\nclass TestSessionReports(object):\n def test_collect_result(self, testdir):\n col = testdir.getmodulecol(\n \"\"\"\n def test_func1():\n pass\n class TestClass(object):\n pass\n \"\"\"\n )\n rep = runner.collect_one_node(col)\n assert not rep.failed\n assert not rep.skipped\n assert rep.passed\n locinfo = rep.location\n assert locinfo[0] == col.fspath.basename\n assert not locinfo[1]\n assert locinfo[2] == col.fspath.basename\n res = rep.result\n assert len(res) == 2\n assert res[0].name == \"test_func1\"\n assert res[1].name == \"TestClass\"\n\n\nreporttypes = [reports.BaseReport, reports.TestReport, reports.CollectReport]\n\n\n@pytest.mark.parametrize(\n \"reporttype\", reporttypes, ids=[x.__name__ for x in reporttypes]\n)\ndef test_report_extra_parameters(reporttype):\n if hasattr(inspect, \"signature\"):\n args = list(inspect.signature(reporttype.__init__).parameters.keys())[1:]\n else:\n args = inspect.getargspec(reporttype.__init__)[0][1:]\n basekw = dict.fromkeys(args, [])\n report = reporttype(newthing=1, **basekw)\n assert report.newthing == 1\n\n\ndef test_callinfo():\n ci = runner.CallInfo.from_call(lambda: 0, \"123\")\n assert ci.when == \"123\"\n assert ci.result == 0\n assert \"result\" in repr(ci)\n assert repr(ci) == \"\"\n\n ci = runner.CallInfo.from_call(lambda: 0 / 0, \"123\")\n assert ci.when == \"123\"\n assert not hasattr(ci, \"result\")\n assert repr(ci) == \"\"\n assert ci.excinfo\n assert \"exc\" in repr(ci)\n\n\n# design question: do we want general hooks in python files?\n# then something like the following functional tests makes sense\n\n\n@pytest.mark.xfail\ndef test_runtest_in_module_ordering(testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_runtest_setup(item): # runs after class-level!\n item.function.mylist.append(\"module\")\n class TestClass(object):\n def pytest_runtest_setup(self, item):\n assert not hasattr(item.function, 'mylist')\n item.function.mylist = ['class']\n @pytest.fixture\n def mylist(self, request):\n return request.function.mylist\n def pytest_runtest_call(self, item, __multicall__):\n try:\n __multicall__.execute()\n except ValueError:\n pass\n def test_hello1(self, mylist):\n assert mylist == ['class', 'module'], mylist\n raise ValueError()\n def test_hello2(self, mylist):\n assert mylist == ['class', 'module'], mylist\n def pytest_runtest_teardown(item):\n del item.function.mylist\n \"\"\"\n )\n result = testdir.runpytest(p1)\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n\ndef test_outcomeexception_exceptionattributes():\n outcome = outcomes.OutcomeException(\"test\")\n assert outcome.args[0] == outcome.msg\n\n\ndef test_outcomeexception_passes_except_Exception():\n with pytest.raises(outcomes.OutcomeException):\n try:\n raise outcomes.OutcomeException(\"test\")\n except Exception:\n pass\n\n\ndef test_pytest_exit():\n with pytest.raises(pytest.exit.Exception) as excinfo:\n pytest.exit(\"hello\")\n assert excinfo.errisinstance(pytest.exit.Exception)\n\n\ndef test_pytest_fail():\n with pytest.raises(pytest.fail.Exception) as excinfo:\n pytest.fail(\"hello\")\n s = excinfo.exconly(tryshort=True)\n assert s.startswith(\"Failed\")\n\n\ndef test_pytest_exit_msg(testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n def pytest_configure(config):\n pytest.exit('oh noes')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stderr.fnmatch_lines([\"Exit: oh noes\"])\n\n\ndef test_pytest_exit_returncode(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_foo():\n pytest.exit(\"some exit msg\", 99)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*! *Exit: some exit msg !*\"])\n # Assert no output on stderr, except for unreliable ResourceWarnings.\n # (https://github.com/pytest-dev/pytest/issues/5088)\n assert [\n x\n for x in result.stderr.lines\n if not x.startswith(\"Exception ignored in:\")\n and not x.startswith(\"ResourceWarning\")\n ] == [\"\"]\n assert result.ret == 99\n\n # It prints to stderr also in case of exit during pytest_sessionstart.\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n def pytest_sessionstart():\n pytest.exit(\"during_sessionstart\", 98)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*! *Exit: during_sessionstart !*\"])\n assert result.stderr.lines == [\"Exit: during_sessionstart\", \"\"]\n assert result.ret == 98\n\n\ndef test_pytest_fail_notrace_runtest(testdir):\n \"\"\"Test pytest.fail(..., pytrace=False) does not show tracebacks during test run.\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_hello():\n pytest.fail(\"hello\", pytrace=False)\n def teardown_function(function):\n pytest.fail(\"world\", pytrace=False)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"world\", \"hello\"])\n assert \"def teardown_function\" not in result.stdout.str()\n\n\ndef test_pytest_fail_notrace_collection(testdir):\n \"\"\"Test pytest.fail(..., pytrace=False) does not show tracebacks during collection.\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n def some_internal_function():\n pytest.fail(\"hello\", pytrace=False)\n some_internal_function()\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"hello\"])\n assert \"def some_internal_function()\" not in result.stdout.str()\n\n\n@pytest.mark.parametrize(\"str_prefix\", [\"u\", \"\"])\ndef test_pytest_fail_notrace_non_ascii(testdir, str_prefix):\n \"\"\"Fix pytest.fail with pytrace=False with non-ascii characters (#1178).\n\n This tests with native and unicode strings containing non-ascii chars.\n \"\"\"\n testdir.makepyfile(\n u\"\"\"\n # -*- coding: utf-8 -*-\n import pytest\n\n def test_hello():\n pytest.fail(%s'oh oh: ☺', pytrace=False)\n \"\"\"\n % str_prefix\n )\n result = testdir.runpytest()\n if sys.version_info[0] >= 3:\n result.stdout.fnmatch_lines([\"*test_hello*\", \"oh oh: ☺\"])\n else:\n result.stdout.fnmatch_lines([\"*test_hello*\", \"oh oh: *\"])\n assert \"def test_hello\" not in result.stdout.str()\n\n\ndef test_pytest_no_tests_collected_exit_status(testdir):\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*collected 0 items*\"])\n assert result.ret == main.EXIT_NOTESTSCOLLECTED\n\n testdir.makepyfile(\n test_foo=\"\"\"\n def test_foo():\n assert 1\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*collected 1 item*\"])\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n assert result.ret == main.EXIT_OK\n\n result = testdir.runpytest(\"-k nonmatch\")\n result.stdout.fnmatch_lines([\"*collected 1 item*\"])\n result.stdout.fnmatch_lines([\"*1 deselected*\"])\n assert result.ret == main.EXIT_NOTESTSCOLLECTED\n\n\ndef test_exception_printing_skip():\n try:\n pytest.skip(\"hello\")\n except pytest.skip.Exception:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n s = excinfo.exconly(tryshort=True)\n assert s.startswith(\"Skipped\")\n\n\ndef test_importorskip(monkeypatch):\n importorskip = pytest.importorskip\n\n def f():\n importorskip(\"asdlkj\")\n\n try:\n sysmod = importorskip(\"sys\")\n assert sysmod is sys\n # path = pytest.importorskip(\"os.path\")\n # assert path == os.path\n excinfo = pytest.raises(pytest.skip.Exception, f)\n path = py.path.local(excinfo.getrepr().reprcrash.path)\n # check that importorskip reports the actual call\n # in this test the test_runner.py file\n assert path.purebasename == \"test_runner\"\n pytest.raises(SyntaxError, pytest.importorskip, \"x y z\")\n pytest.raises(SyntaxError, pytest.importorskip, \"x=y\")\n mod = types.ModuleType(\"hello123\")\n mod.__version__ = \"1.3\"\n monkeypatch.setitem(sys.modules, \"hello123\", mod)\n with pytest.raises(pytest.skip.Exception):\n pytest.importorskip(\"hello123\", minversion=\"1.3.1\")\n mod2 = pytest.importorskip(\"hello123\", minversion=\"1.3\")\n assert mod2 == mod\n except pytest.skip.Exception:\n print(_pytest._code.ExceptionInfo.from_current())\n pytest.fail(\"spurious skip\")\n\n\ndef test_importorskip_imports_last_module_part():\n ospath = pytest.importorskip(\"os.path\")\n assert os.path == ospath\n\n\ndef test_importorskip_dev_module(monkeypatch):\n try:\n mod = types.ModuleType(\"mockmodule\")\n mod.__version__ = \"0.13.0.dev-43290\"\n monkeypatch.setitem(sys.modules, \"mockmodule\", mod)\n mod2 = pytest.importorskip(\"mockmodule\", minversion=\"0.12.0\")\n assert mod2 == mod\n with pytest.raises(pytest.skip.Exception):\n pytest.importorskip(\"mockmodule1\", minversion=\"0.14.0\")\n except pytest.skip.Exception:\n print(_pytest._code.ExceptionInfo.from_current())\n pytest.fail(\"spurious skip\")\n\n\ndef test_importorskip_module_level(testdir):\n \"\"\"importorskip must be able to skip entire modules when used at module level\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n foobarbaz = pytest.importorskip(\"foobarbaz\")\n\n def test_foo():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*collected 0 items / 1 skipped*\"])\n\n\ndef test_importorskip_custom_reason(testdir):\n \"\"\"make sure custom reasons are used\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n foobarbaz = pytest.importorskip(\"foobarbaz2\", reason=\"just because\")\n\n def test_foo():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-ra\")\n result.stdout.fnmatch_lines([\"*just because*\"])\n result.stdout.fnmatch_lines([\"*collected 0 items / 1 skipped*\"])\n\n\ndef test_pytest_cmdline_main(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_hello():\n assert 1\n if __name__ == '__main__':\n pytest.cmdline.main([__file__])\n \"\"\"\n )\n import subprocess\n\n popen = subprocess.Popen([sys.executable, str(p)], stdout=subprocess.PIPE)\n popen.communicate()\n ret = popen.wait()\n assert ret == 0\n\n\ndef test_unicode_in_longrepr(testdir):\n testdir.makeconftest(\n \"\"\"\n # -*- coding: utf-8 -*-\n import pytest\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_makereport():\n outcome = yield\n rep = outcome.get_result()\n if rep.when == \"call\":\n rep.longrepr = u'ä'\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_out():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n assert \"UnicodeEncodeError\" not in result.stderr.str()\n\n\ndef test_failure_in_setup(testdir):\n testdir.makepyfile(\n \"\"\"\n def setup_module():\n 0/0\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--tb=line\")\n assert \"def setup_module\" not in result.stdout.str()\n\n\ndef test_makereport_getsource(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n if False: pass\n else: assert False\n \"\"\"\n )\n result = testdir.runpytest()\n assert \"INTERNALERROR\" not in result.stdout.str()\n result.stdout.fnmatch_lines([\"*else: assert False*\"])\n\n\ndef test_makereport_getsource_dynamic_code(testdir, monkeypatch):\n \"\"\"Test that exception in dynamically generated code doesn't break getting the source line.\"\"\"\n import inspect\n\n original_findsource = inspect.findsource\n\n def findsource(obj, *args, **kwargs):\n # Can be triggered by dynamically created functions\n if obj.__name__ == \"foo\":\n raise IndexError()\n return original_findsource(obj, *args, **kwargs)\n\n monkeypatch.setattr(inspect, \"findsource\", findsource)\n\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def foo(missing):\n pass\n\n def test_fix(foo):\n assert False\n \"\"\"\n )\n result = testdir.runpytest(\"-vv\")\n assert \"INTERNALERROR\" not in result.stdout.str()\n result.stdout.fnmatch_lines([\"*test_fix*\", \"*fixture*'missing'*not found*\"])\n\n\ndef test_store_except_info_on_error():\n \"\"\" Test that upon test failure, the exception info is stored on\n sys.last_traceback and friends.\n \"\"\"\n # Simulate item that might raise a specific exception, depending on `raise_error` class var\n class ItemMightRaise(object):\n nodeid = \"item_that_raises\"\n raise_error = True\n\n def runtest(self):\n if self.raise_error:\n raise IndexError(\"TEST\")\n\n try:\n runner.pytest_runtest_call(ItemMightRaise())\n except IndexError:\n pass\n # Check that exception info is stored on sys\n assert sys.last_type is IndexError\n assert sys.last_value.args[0] == \"TEST\"\n assert sys.last_traceback\n\n # The next run should clear the exception info stored by the previous run\n ItemMightRaise.raise_error = False\n runner.pytest_runtest_call(ItemMightRaise())\n assert sys.last_type is None\n assert sys.last_value is None\n assert sys.last_traceback is None\n\n\ndef test_current_test_env_var(testdir, monkeypatch):\n pytest_current_test_vars = []\n monkeypatch.setattr(\n sys, \"pytest_current_test_vars\", pytest_current_test_vars, raising=False\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n import sys\n import os\n\n @pytest.fixture\n def fix():\n sys.pytest_current_test_vars.append(('setup', os.environ['PYTEST_CURRENT_TEST']))\n yield\n sys.pytest_current_test_vars.append(('teardown', os.environ['PYTEST_CURRENT_TEST']))\n\n def test(fix):\n sys.pytest_current_test_vars.append(('call', os.environ['PYTEST_CURRENT_TEST']))\n \"\"\"\n )\n result = testdir.runpytest_inprocess()\n assert result.ret == 0\n test_id = \"test_current_test_env_var.py::test\"\n assert pytest_current_test_vars == [\n (\"setup\", test_id + \" (setup)\"),\n (\"call\", test_id + \" (call)\"),\n (\"teardown\", test_id + \" (teardown)\"),\n ]\n assert \"PYTEST_CURRENT_TEST\" not in os.environ\n\n\nclass TestReportContents(object):\n \"\"\"\n Test user-level API of ``TestReport`` objects.\n \"\"\"\n\n def getrunner(self):\n return lambda item: runner.runtestprotocol(item, log=False)\n\n def test_longreprtext_pass(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n rep = reports[1]\n assert rep.longreprtext == \"\"\n\n def test_longreprtext_failure(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n x = 1\n assert x == 4\n \"\"\"\n )\n rep = reports[1]\n assert \"assert 1 == 4\" in rep.longreprtext\n\n def test_captured_text(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n import pytest\n import sys\n\n @pytest.fixture\n def fix():\n sys.stdout.write('setup: stdout\\\\n')\n sys.stderr.write('setup: stderr\\\\n')\n yield\n sys.stdout.write('teardown: stdout\\\\n')\n sys.stderr.write('teardown: stderr\\\\n')\n assert 0\n\n def test_func(fix):\n sys.stdout.write('call: stdout\\\\n')\n sys.stderr.write('call: stderr\\\\n')\n assert 0\n \"\"\"\n )\n setup, call, teardown = reports\n assert setup.capstdout == \"setup: stdout\\n\"\n assert call.capstdout == \"setup: stdout\\ncall: stdout\\n\"\n assert teardown.capstdout == \"setup: stdout\\ncall: stdout\\nteardown: stdout\\n\"\n\n assert setup.capstderr == \"setup: stderr\\n\"\n assert call.capstderr == \"setup: stderr\\ncall: stderr\\n\"\n assert teardown.capstderr == \"setup: stderr\\ncall: stderr\\nteardown: stderr\\n\"\n\n def test_no_captured_text(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n rep = reports[1]\n assert rep.capstdout == \"\"\n assert rep.capstderr == \"\"\n"},{"col":4,"comment":"null","endLoc":1100,"header":"def test_reload_is_same(self, testdir)","id":4379,"name":"test_reload_is_same","nodeType":"Function","startLoc":1074,"text":"def test_reload_is_same(self, testdir):\n # A file that will be picked up during collecting.\n testdir.tmpdir.join(\"file.py\").ensure()\n testdir.tmpdir.join(\"pytest.ini\").write(\n textwrap.dedent(\n \"\"\"\n [pytest]\n python_files = *.py\n \"\"\"\n )\n )\n\n testdir.makepyfile(\n test_fun=\"\"\"\n import sys\n try:\n from imp import reload\n except ImportError:\n pass\n\n def test_loader():\n import file\n assert sys.modules[\"file\"] is reload(file)\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines([\"* 1 passed*\"])"},{"className":"TestSetupState","col":0,"comment":"null","endLoc":106,"id":4380,"nodeType":"Class","startLoc":21,"text":"class TestSetupState(object):\n def test_setup(self, testdir):\n ss = runner.SetupState()\n item = testdir.getitem(\"def test_func(): pass\")\n values = [1]\n ss.prepare(item)\n ss.addfinalizer(values.pop, colitem=item)\n assert values\n ss._pop_and_teardown()\n assert not values\n\n def test_teardown_exact_stack_empty(self, testdir):\n item = testdir.getitem(\"def test_func(): pass\")\n ss = runner.SetupState()\n ss.teardown_exact(item, None)\n ss.teardown_exact(item, None)\n ss.teardown_exact(item, None)\n\n def test_setup_fails_and_failure_is_cached(self, testdir):\n item = testdir.getitem(\n \"\"\"\n def setup_module(mod):\n raise ValueError(42)\n def test_func(): pass\n \"\"\"\n )\n ss = runner.SetupState()\n pytest.raises(ValueError, lambda: ss.prepare(item))\n pytest.raises(ValueError, lambda: ss.prepare(item))\n\n def test_teardown_multiple_one_fails(self, testdir):\n r = []\n\n def fin1():\n r.append(\"fin1\")\n\n def fin2():\n raise Exception(\"oops\")\n\n def fin3():\n r.append(\"fin3\")\n\n item = testdir.getitem(\"def test_func(): pass\")\n ss = runner.SetupState()\n ss.addfinalizer(fin1, item)\n ss.addfinalizer(fin2, item)\n ss.addfinalizer(fin3, item)\n with pytest.raises(Exception) as err:\n ss._callfinalizers(item)\n assert err.value.args == (\"oops\",)\n assert r == [\"fin3\", \"fin1\"]\n\n def test_teardown_multiple_fail(self, testdir):\n # Ensure the first exception is the one which is re-raised.\n # Ideally both would be reported however.\n def fin1():\n raise Exception(\"oops1\")\n\n def fin2():\n raise Exception(\"oops2\")\n\n item = testdir.getitem(\"def test_func(): pass\")\n ss = runner.SetupState()\n ss.addfinalizer(fin1, item)\n ss.addfinalizer(fin2, item)\n with pytest.raises(Exception) as err:\n ss._callfinalizers(item)\n assert err.value.args == (\"oops2\",)\n\n def test_teardown_multiple_scopes_one_fails(self, testdir):\n module_teardown = []\n\n def fin_func():\n raise Exception(\"oops1\")\n\n def fin_module():\n module_teardown.append(\"fin_module\")\n\n item = testdir.getitem(\"def test_func(): pass\")\n ss = runner.SetupState()\n ss.addfinalizer(fin_module, item.listchain()[-2])\n ss.addfinalizer(fin_func, item)\n ss.prepare(item)\n with pytest.raises(Exception, match=\"oops1\"):\n ss.teardown_exact(item, None)\n assert module_teardown"},{"col":0,"comment":"null","endLoc":20,"header":"@pytest.fixture\ndef parser()","id":4381,"name":"parser","nodeType":"Function","startLoc":18,"text":"@pytest.fixture\ndef parser():\n return parseopt.Parser()"},{"col":4,"comment":"null","endLoc":996,"header":"@pytest.mark.skipif(\n not SUPPORTS_BREAKPOINT_BUILTIN, reason=\"Requires breakpoint() builtin\"\n )\n def test_pdb_not_altered(self, testdir)","id":4382,"name":"test_pdb_not_altered","nodeType":"Function","startLoc":977,"text":"@pytest.mark.skipif(\n not SUPPORTS_BREAKPOINT_BUILTIN, reason=\"Requires breakpoint() builtin\"\n )\n def test_pdb_not_altered(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pdb\n def test_1():\n pdb.set_trace()\n assert 0\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"test_1\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n rest = child.read().decode(\"utf8\")\n assert \"1 failed\" in rest\n assert \"reading from stdin while output\" not in rest\n TestPDB.flush(child)"},{"col":4,"comment":"Reloading a module after change picks up the change.","endLoc":1142,"header":"def test_reload_reloads(self, testdir)","id":4383,"name":"test_reload_reloads","nodeType":"Function","startLoc":1102,"text":"def test_reload_reloads(self, testdir):\n \"\"\"Reloading a module after change picks up the change.\"\"\"\n testdir.tmpdir.join(\"file.py\").write(\n textwrap.dedent(\n \"\"\"\n def reloaded():\n return False\n\n def rewrite_self():\n with open(__file__, 'w') as self:\n self.write('def reloaded(): return True')\n \"\"\"\n )\n )\n testdir.tmpdir.join(\"pytest.ini\").write(\n textwrap.dedent(\n \"\"\"\n [pytest]\n python_files = *.py\n \"\"\"\n )\n )\n\n testdir.makepyfile(\n test_fun=\"\"\"\n import sys\n try:\n from imp import reload\n except ImportError:\n pass\n\n def test_loader():\n import file\n assert not file.reloaded()\n file.rewrite_self()\n reload(file)\n assert file.reloaded()\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines([\"* 1 passed*\"])"},{"col":0,"comment":"null","endLoc":336,"header":"def test_argcomplete(testdir, monkeypatch)","id":4384,"name":"test_argcomplete","nodeType":"Function","startLoc":299,"text":"def test_argcomplete(testdir, monkeypatch):\n if not distutils.spawn.find_executable(\"bash\"):\n pytest.skip(\"bash not available\")\n script = str(testdir.tmpdir.join(\"test_argcomplete\"))\n\n with open(str(script), \"w\") as fp:\n # redirect output from argcomplete to stdin and stderr is not trivial\n # http://stackoverflow.com/q/12589419/1307905\n # so we use bash\n fp.write('COMP_WORDBREAKS=\"$COMP_WORDBREAKS\" python -m pytest 8>&1 9>&2')\n # alternative would be exteneded Testdir.{run(),_run(),popen()} to be able\n # to handle a keyword argument env that replaces os.environ in popen or\n # extends the copy, advantage: could not forget to restore\n monkeypatch.setenv(\"_ARGCOMPLETE\", \"1\")\n monkeypatch.setenv(\"_ARGCOMPLETE_IFS\", \"\\x0b\")\n monkeypatch.setenv(\"COMP_WORDBREAKS\", \" \\\\t\\\\n\\\"\\\\'><=;|&(:\")\n\n arg = \"--fu\"\n monkeypatch.setenv(\"COMP_LINE\", \"pytest \" + arg)\n monkeypatch.setenv(\"COMP_POINT\", str(len(\"pytest \" + arg)))\n result = testdir.run(\"bash\", str(script), arg)\n if result.ret == 255:\n # argcomplete not found\n pytest.skip(\"argcomplete not available\")\n elif not result.stdout.str():\n pytest.skip(\n \"bash provided no output on stdout, argcomplete not available? (stderr={!r})\".format(\n result.stderr.str()\n )\n )\n else:\n result.stdout.fnmatch_lines([\"--funcargs\", \"--fulltrace\"])\n os.mkdir(\"test_argcomplete.d\")\n arg = \"test_argc\"\n monkeypatch.setenv(\"COMP_LINE\", \"pytest \" + arg)\n monkeypatch.setenv(\"COMP_POINT\", str(len(\"pytest \" + arg)))\n result = testdir.run(\"bash\", str(script), arg)\n result.stdout.fnmatch_lines([\"test_argcomplete\", \"test_argcomplete.d/\"])"},{"col":0,"comment":"null","endLoc":342,"header":"def pytest_collection_modifyitems(items, config)","id":4385,"name":"pytest_collection_modifyitems","nodeType":"Function","startLoc":327,"text":"def pytest_collection_modifyitems(items, config):\n deselect_prefixes = tuple(config.getoption(\"deselect\") or [])\n if not deselect_prefixes:\n return\n\n remaining = []\n deselected = []\n for colitem in items:\n if colitem.nodeid.startswith(deselect_prefixes):\n deselected.append(colitem)\n else:\n remaining.append(colitem)\n\n if deselected:\n config.hook.pytest_deselected(items=deselected)\n items[:] = remaining"},{"col":4,"comment":"null","endLoc":30,"header":"def test_setup(self, testdir)","id":4386,"name":"test_setup","nodeType":"Function","startLoc":22,"text":"def test_setup(self, testdir):\n ss = runner.SetupState()\n item = testdir.getitem(\"def test_func(): pass\")\n values = [1]\n ss.prepare(item)\n ss.addfinalizer(values.pop, colitem=item)\n assert values\n ss._pop_and_teardown()\n assert not values"},{"col":4,"comment":"Implement optional PEP302 api (#808).\n ","endLoc":1161,"header":"def test_get_data_support(self, testdir)","id":4387,"name":"test_get_data_support","nodeType":"Function","startLoc":1144,"text":"def test_get_data_support(self, testdir):\n \"\"\"Implement optional PEP302 api (#808).\n \"\"\"\n path = testdir.mkpydir(\"foo\")\n path.join(\"test_foo.py\").write(\n textwrap.dedent(\n \"\"\"\\\n class Test(object):\n def test_foo(self):\n import pkgutil\n data = pkgutil.get_data('foo.test_foo', 'data.txt')\n assert data == b'Hey'\n \"\"\"\n )\n )\n path.join(\"data.txt\").write(\"Hey\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":4,"comment":"null","endLoc":37,"header":"def test_teardown_exact_stack_empty(self, testdir)","id":4388,"name":"test_teardown_exact_stack_empty","nodeType":"Function","startLoc":32,"text":"def test_teardown_exact_stack_empty(self, testdir):\n item = testdir.getitem(\"def test_func(): pass\")\n ss = runner.SetupState()\n ss.teardown_exact(item, None)\n ss.teardown_exact(item, None)\n ss.teardown_exact(item, None)"},{"className":"TestIssue925","col":0,"comment":"null","endLoc":1212,"id":4389,"nodeType":"Class","startLoc":1183,"text":"class TestIssue925(object):\n def test_simple_case(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_ternary_display():\n assert (False == False) == False\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*E*assert (False == False) == False\"])\n\n def test_long_case(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_ternary_display():\n assert False == (False == True) == True\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*E*assert (False == True) == True\"])\n\n def test_many_brackets(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_ternary_display():\n assert True == ((False == True) == True)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*E*assert True == ((False == True) == True)\"])"},{"col":4,"comment":"null","endLoc":1192,"header":"def test_simple_case(self, testdir)","id":4390,"name":"test_simple_case","nodeType":"Function","startLoc":1184,"text":"def test_simple_case(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_ternary_display():\n assert (False == False) == False\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*E*assert (False == False) == False\"])"},{"fileName":"test_junitxml.py","filePath":"testing","id":4391,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\nfrom xml.dom import minidom\n\nimport py\n\nimport pytest\nfrom _pytest.junitxml import LogXML\nfrom _pytest.reports import BaseReport\n\n\ndef runandparse(testdir, *args):\n resultpath = testdir.tmpdir.join(\"junit.xml\")\n result = testdir.runpytest(\"--junitxml=%s\" % resultpath, *args)\n xmldoc = minidom.parse(str(resultpath))\n return result, DomNode(xmldoc)\n\n\ndef assert_attr(node, **kwargs):\n __tracebackhide__ = True\n\n def nodeval(node, name):\n anode = node.getAttributeNode(name)\n if anode is not None:\n return anode.value\n\n expected = {name: str(value) for name, value in kwargs.items()}\n on_node = {name: nodeval(node, name) for name in expected}\n assert on_node == expected\n\n\nclass DomNode(object):\n def __init__(self, dom):\n self.__node = dom\n\n def __repr__(self):\n return self.__node.toxml()\n\n def find_first_by_tag(self, tag):\n return self.find_nth_by_tag(tag, 0)\n\n def _by_tag(self, tag):\n return self.__node.getElementsByTagName(tag)\n\n def find_nth_by_tag(self, tag, n):\n items = self._by_tag(tag)\n try:\n nth = items[n]\n except IndexError:\n pass\n else:\n return type(self)(nth)\n\n def find_by_tag(self, tag):\n t = type(self)\n return [t(x) for x in self.__node.getElementsByTagName(tag)]\n\n def __getitem__(self, key):\n node = self.__node.getAttributeNode(key)\n if node is not None:\n return node.value\n\n def assert_attr(self, **kwargs):\n __tracebackhide__ = True\n return assert_attr(self.__node, **kwargs)\n\n def toxml(self):\n return self.__node.toxml()\n\n @property\n def text(self):\n return self.__node.childNodes[0].wholeText\n\n @property\n def tag(self):\n return self.__node.tagName\n\n @property\n def next_siebling(self):\n return type(self)(self.__node.nextSibling)\n\n\nclass TestPython(object):\n def test_summing_simple(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_pass():\n pass\n def test_fail():\n assert 0\n def test_skip():\n pytest.skip(\"\")\n @pytest.mark.xfail\n def test_xfail():\n assert 0\n @pytest.mark.xfail\n def test_xpass():\n assert 1\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(name=\"pytest\", errors=0, failures=1, skipped=2, tests=5)\n\n def test_summing_simple_with_errors(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def fixture():\n raise Exception()\n def test_pass():\n pass\n def test_fail():\n assert 0\n def test_error(fixture):\n pass\n @pytest.mark.xfail\n def test_xfail():\n assert False\n @pytest.mark.xfail(strict=True)\n def test_xpass():\n assert True\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(name=\"pytest\", errors=1, failures=2, skipped=1, tests=5)\n\n def test_timing_function(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import time, pytest\n def setup_module():\n time.sleep(0.01)\n def teardown_module():\n time.sleep(0.01)\n def test_sleep():\n time.sleep(0.01)\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n val = tnode[\"time\"]\n assert round(float(val), 2) >= 0.03\n\n @pytest.mark.parametrize(\"duration_report\", [\"call\", \"total\"])\n def test_junit_duration_report(self, testdir, monkeypatch, duration_report):\n\n # mock LogXML.node_reporter so it always sets a known duration to each test report object\n original_node_reporter = LogXML.node_reporter\n\n def node_reporter_wrapper(s, report):\n report.duration = 1.0\n reporter = original_node_reporter(s, report)\n return reporter\n\n monkeypatch.setattr(LogXML, \"node_reporter\", node_reporter_wrapper)\n\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n pass\n \"\"\"\n )\n result, dom = runandparse(\n testdir, \"-o\", \"junit_duration_report={}\".format(duration_report)\n )\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n val = float(tnode[\"time\"])\n if duration_report == \"total\":\n assert val == 3.0\n else:\n assert duration_report == \"call\"\n assert val == 1.0\n\n def test_setup_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def arg(request):\n raise ValueError()\n def test_function(arg):\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(errors=1, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_setup_error\", name=\"test_function\")\n fnode = tnode.find_first_by_tag(\"error\")\n fnode.assert_attr(message=\"test setup failure\")\n assert \"ValueError\" in fnode.toxml()\n\n def test_teardown_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def arg():\n yield\n raise ValueError()\n def test_function(arg):\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_teardown_error\", name=\"test_function\")\n fnode = tnode.find_first_by_tag(\"error\")\n fnode.assert_attr(message=\"test teardown failure\")\n assert \"ValueError\" in fnode.toxml()\n\n def test_call_failure_teardown_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def arg():\n yield\n raise Exception(\"Teardown Exception\")\n def test_function(arg):\n raise Exception(\"Call Exception\")\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(errors=1, failures=1, tests=1)\n first, second = dom.find_by_tag(\"testcase\")\n if not first or not second or first == second:\n assert 0\n fnode = first.find_first_by_tag(\"failure\")\n fnode.assert_attr(message=\"Exception: Call Exception\")\n snode = second.find_first_by_tag(\"error\")\n snode.assert_attr(message=\"test teardown failure\")\n\n def test_skip_contains_name_reason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_skip():\n pytest.skip(\"hello23\")\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_skip_contains_name_reason\", name=\"test_skip\")\n snode = tnode.find_first_by_tag(\"skipped\")\n snode.assert_attr(type=\"pytest.skip\", message=\"hello23\")\n\n def test_mark_skip_contains_name_reason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip(reason=\"hello24\")\n def test_skip():\n assert True\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(\n classname=\"test_mark_skip_contains_name_reason\", name=\"test_skip\"\n )\n snode = tnode.find_first_by_tag(\"skipped\")\n snode.assert_attr(type=\"pytest.skip\", message=\"hello24\")\n\n def test_mark_skipif_contains_name_reason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n GLOBAL_CONDITION = True\n @pytest.mark.skipif(GLOBAL_CONDITION, reason=\"hello25\")\n def test_skip():\n assert True\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(\n classname=\"test_mark_skipif_contains_name_reason\", name=\"test_skip\"\n )\n snode = tnode.find_first_by_tag(\"skipped\")\n snode.assert_attr(type=\"pytest.skip\", message=\"hello25\")\n\n def test_mark_skip_doesnt_capture_output(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip(reason=\"foo\")\n def test_skip():\n print(\"bar!\")\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node_xml = dom.find_first_by_tag(\"testsuite\").toxml()\n assert \"bar!\" not in node_xml\n\n def test_classname_instance(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class TestClass(object):\n def test_method(self):\n assert 0\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(failures=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(\n classname=\"test_classname_instance.TestClass\", name=\"test_method\"\n )\n\n def test_classname_nested_dir(self, testdir):\n p = testdir.tmpdir.ensure(\"sub\", \"test_hello.py\")\n p.write(\"def test_func(): 0/0\")\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(failures=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"sub.test_hello\", name=\"test_func\")\n\n def test_internal_error(self, testdir):\n testdir.makeconftest(\"def pytest_runtest_protocol(): 0 / 0\")\n testdir.makepyfile(\"def test_function(): pass\")\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(errors=1, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"pytest\", name=\"internal\")\n fnode = tnode.find_first_by_tag(\"error\")\n fnode.assert_attr(message=\"internal error\")\n assert \"Division\" in fnode.toxml()\n\n @pytest.mark.parametrize(\"junit_logging\", [\"no\", \"system-out\", \"system-err\"])\n def test_failure_function(self, testdir, junit_logging):\n testdir.makepyfile(\n \"\"\"\n import logging\n import sys\n\n def test_fail():\n print(\"hello-stdout\")\n sys.stderr.write(\"hello-stderr\\\\n\")\n logging.info('info msg')\n logging.warning('warning msg')\n raise ValueError(42)\n \"\"\"\n )\n\n result, dom = runandparse(testdir, \"-o\", \"junit_logging=%s\" % junit_logging)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(failures=1, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_failure_function\", name=\"test_fail\")\n fnode = tnode.find_first_by_tag(\"failure\")\n fnode.assert_attr(message=\"ValueError: 42\")\n assert \"ValueError\" in fnode.toxml()\n systemout = fnode.next_siebling\n assert systemout.tag == \"system-out\"\n assert \"hello-stdout\" in systemout.toxml()\n assert \"info msg\" not in systemout.toxml()\n systemerr = systemout.next_siebling\n assert systemerr.tag == \"system-err\"\n assert \"hello-stderr\" in systemerr.toxml()\n assert \"info msg\" not in systemerr.toxml()\n\n if junit_logging == \"system-out\":\n assert \"warning msg\" in systemout.toxml()\n assert \"warning msg\" not in systemerr.toxml()\n elif junit_logging == \"system-err\":\n assert \"warning msg\" not in systemout.toxml()\n assert \"warning msg\" in systemerr.toxml()\n elif junit_logging == \"no\":\n assert \"warning msg\" not in systemout.toxml()\n assert \"warning msg\" not in systemerr.toxml()\n\n def test_failure_verbose_message(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n def test_fail():\n assert 0, \"An error\"\n \"\"\"\n )\n\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n fnode = tnode.find_first_by_tag(\"failure\")\n fnode.assert_attr(message=\"AssertionError: An error assert 0\")\n\n def test_failure_escape(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('arg1', \"<&'\", ids=\"<&'\")\n def test_func(arg1):\n print(arg1)\n assert 0\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(failures=3, tests=3)\n\n for index, char in enumerate(\"<&'\"):\n\n tnode = node.find_nth_by_tag(\"testcase\", index)\n tnode.assert_attr(\n classname=\"test_failure_escape\", name=\"test_func[%s]\" % char\n )\n sysout = tnode.find_first_by_tag(\"system-out\")\n text = sysout.text\n assert text == \"%s\\n\" % char\n\n def test_junit_prefixing(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_func():\n assert 0\n class TestHello(object):\n def test_hello(self):\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir, \"--junitprefix=xyz\")\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(failures=1, tests=2)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"xyz.test_junit_prefixing\", name=\"test_func\")\n tnode = node.find_nth_by_tag(\"testcase\", 1)\n tnode.assert_attr(\n classname=\"xyz.test_junit_prefixing.TestHello\", name=\"test_hello\"\n )\n\n def test_xfailure_function(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_xfail():\n pytest.xfail(\"42\")\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert not result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=1, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_xfailure_function\", name=\"test_xfail\")\n fnode = tnode.find_first_by_tag(\"skipped\")\n fnode.assert_attr(type=\"pytest.xfail\", message=\"42\")\n # assert \"ValueError\" in fnode.toxml()\n\n def test_xfailure_marker(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(reason=\"42\")\n def test_xfail():\n assert False\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert not result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=1, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_xfailure_marker\", name=\"test_xfail\")\n fnode = tnode.find_first_by_tag(\"skipped\")\n fnode.assert_attr(type=\"pytest.xfail\", message=\"42\")\n\n def test_xfail_captures_output_once(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n import pytest\n\n @pytest.mark.xfail()\n def test_fail():\n sys.stdout.write('XFAIL This is stdout')\n sys.stderr.write('XFAIL This is stderr')\n assert 0\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n assert len(tnode.find_by_tag(\"system-err\")) == 1\n assert len(tnode.find_by_tag(\"system-out\")) == 1\n\n def test_xfailure_xpass(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail\n def test_xpass():\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n # assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=0, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_xfailure_xpass\", name=\"test_xpass\")\n\n def test_xfailure_xpass_strict(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(strict=True, reason=\"This needs to fail!\")\n def test_xpass():\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n # assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=0, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_xfailure_xpass_strict\", name=\"test_xpass\")\n fnode = tnode.find_first_by_tag(\"failure\")\n fnode.assert_attr(message=\"[XPASS(strict)] This needs to fail!\")\n\n def test_collect_error(self, testdir):\n testdir.makepyfile(\"syntax error\")\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(errors=1, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n fnode = tnode.find_first_by_tag(\"error\")\n fnode.assert_attr(message=\"collection failure\")\n assert \"SyntaxError\" in fnode.toxml()\n\n def test_unicode(self, testdir):\n value = \"hx\\xc4\\x85\\xc4\\x87\\n\"\n testdir.makepyfile(\n \"\"\"\n # coding: latin1\n def test_hello():\n print(%r)\n assert 0\n \"\"\"\n % value\n )\n result, dom = runandparse(testdir)\n assert result.ret == 1\n tnode = dom.find_first_by_tag(\"testcase\")\n fnode = tnode.find_first_by_tag(\"failure\")\n if not sys.platform.startswith(\"java\"):\n assert \"hx\" in fnode.toxml()\n\n def test_assertion_binchars(self, testdir):\n \"\"\"this test did fail when the escaping wasnt strict\"\"\"\n testdir.makepyfile(\n \"\"\"\n\n M1 = '\\x01\\x02\\x03\\x04'\n M2 = '\\x01\\x02\\x03\\x05'\n\n def test_str_compare():\n assert M1 == M2\n \"\"\"\n )\n result, dom = runandparse(testdir)\n print(dom.toxml())\n\n def test_pass_captures_stdout(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_pass():\n print('hello-stdout')\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n pnode = node.find_first_by_tag(\"testcase\")\n systemout = pnode.find_first_by_tag(\"system-out\")\n assert \"hello-stdout\" in systemout.toxml()\n\n def test_pass_captures_stderr(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n def test_pass():\n sys.stderr.write('hello-stderr')\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n pnode = node.find_first_by_tag(\"testcase\")\n systemout = pnode.find_first_by_tag(\"system-err\")\n assert \"hello-stderr\" in systemout.toxml()\n\n def test_setup_error_captures_stdout(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def arg(request):\n print('hello-stdout')\n raise ValueError()\n def test_function(arg):\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n pnode = node.find_first_by_tag(\"testcase\")\n systemout = pnode.find_first_by_tag(\"system-out\")\n assert \"hello-stdout\" in systemout.toxml()\n\n def test_setup_error_captures_stderr(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n import pytest\n\n @pytest.fixture\n def arg(request):\n sys.stderr.write('hello-stderr')\n raise ValueError()\n def test_function(arg):\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n pnode = node.find_first_by_tag(\"testcase\")\n systemout = pnode.find_first_by_tag(\"system-err\")\n assert \"hello-stderr\" in systemout.toxml()\n\n def test_avoid_double_stdout(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n import pytest\n\n @pytest.fixture\n def arg(request):\n yield\n sys.stdout.write('hello-stdout teardown')\n raise ValueError()\n def test_function(arg):\n sys.stdout.write('hello-stdout call')\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n pnode = node.find_first_by_tag(\"testcase\")\n systemout = pnode.find_first_by_tag(\"system-out\")\n assert \"hello-stdout call\" in systemout.toxml()\n assert \"hello-stdout teardown\" in systemout.toxml()\n\n\ndef test_mangle_test_address():\n from _pytest.junitxml import mangle_test_address\n\n address = \"::\".join([\"a/my.py.thing.py\", \"Class\", \"()\", \"method\", \"[a-1-::]\"])\n newnames = mangle_test_address(address)\n assert newnames == [\"a.my.py.thing\", \"Class\", \"method\", \"[a-1-::]\"]\n\n\ndef test_dont_configure_on_slaves(tmpdir):\n gotten = []\n\n class FakeConfig(object):\n def __init__(self):\n self.pluginmanager = self\n self.option = self\n\n def getini(self, name):\n return \"pytest\"\n\n junitprefix = None\n # XXX: shouldnt need tmpdir ?\n xmlpath = str(tmpdir.join(\"junix.xml\"))\n register = gotten.append\n\n fake_config = FakeConfig()\n from _pytest import junitxml\n\n junitxml.pytest_configure(fake_config)\n assert len(gotten) == 1\n FakeConfig.slaveinput = None\n junitxml.pytest_configure(fake_config)\n assert len(gotten) == 1\n\n\nclass TestNonPython(object):\n def test_summing_simple(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_collect_file(path, parent):\n if path.ext == \".xyz\":\n return MyItem(path, parent)\n class MyItem(pytest.Item):\n def __init__(self, path, parent):\n super(MyItem, self).__init__(path.basename, parent)\n self.fspath = path\n def runtest(self):\n raise ValueError(42)\n def repr_failure(self, excinfo):\n return \"custom item runtest failed\"\n \"\"\"\n )\n testdir.tmpdir.join(\"myfile.xyz\").write(\"hello\")\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(errors=0, failures=1, skipped=0, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(name=\"myfile.xyz\")\n fnode = tnode.find_first_by_tag(\"failure\")\n fnode.assert_attr(message=\"custom item runtest failed\")\n assert \"custom item runtest failed\" in fnode.toxml()\n\n\ndef test_nullbyte(testdir):\n # A null byte can not occur in XML (see section 2.2 of the spec)\n testdir.makepyfile(\n \"\"\"\n import sys\n def test_print_nullbyte():\n sys.stdout.write('Here the null -->' + chr(0) + '<--')\n sys.stdout.write('In repr form -->' + repr(chr(0)) + '<--')\n assert False\n \"\"\"\n )\n xmlf = testdir.tmpdir.join(\"junit.xml\")\n testdir.runpytest(\"--junitxml=%s\" % xmlf)\n text = xmlf.read()\n assert \"\\x00\" not in text\n assert \"#x00\" in text\n\n\ndef test_nullbyte_replace(testdir):\n # Check if the null byte gets replaced\n testdir.makepyfile(\n \"\"\"\n import sys\n def test_print_nullbyte():\n sys.stdout.write('Here the null -->' + chr(0) + '<--')\n sys.stdout.write('In repr form -->' + repr(chr(0)) + '<--')\n assert False\n \"\"\"\n )\n xmlf = testdir.tmpdir.join(\"junit.xml\")\n testdir.runpytest(\"--junitxml=%s\" % xmlf)\n text = xmlf.read()\n assert \"#x0\" in text\n\n\ndef test_invalid_xml_escape():\n # Test some more invalid xml chars, the full range should be\n # tested really but let's just thest the edges of the ranges\n # intead.\n # XXX This only tests low unicode character points for now as\n # there are some issues with the testing infrastructure for\n # the higher ones.\n # XXX Testing 0xD (\\r) is tricky as it overwrites the just written\n # line in the output, so we skip it too.\n global unichr\n try:\n unichr(65)\n except NameError:\n unichr = chr\n invalid = (\n 0x00,\n 0x1,\n 0xB,\n 0xC,\n 0xE,\n 0x19,\n 27, # issue #126\n 0xD800,\n 0xDFFF,\n 0xFFFE,\n 0x0FFFF,\n ) # , 0x110000)\n valid = (0x9, 0xA, 0x20)\n # 0xD, 0xD7FF, 0xE000, 0xFFFD, 0x10000, 0x10FFFF)\n\n from _pytest.junitxml import bin_xml_escape\n\n for i in invalid:\n got = bin_xml_escape(unichr(i)).uniobj\n if i <= 0xFF:\n expected = \"#x%02X\" % i\n else:\n expected = \"#x%04X\" % i\n assert got == expected\n for i in valid:\n assert chr(i) == bin_xml_escape(unichr(i)).uniobj\n\n\ndef test_logxml_path_expansion(tmpdir, monkeypatch):\n home_tilde = py.path.local(os.path.expanduser(\"~\")).join(\"test.xml\")\n xml_tilde = LogXML(\"~%stest.xml\" % tmpdir.sep, None)\n assert xml_tilde.logfile == home_tilde\n\n monkeypatch.setenv(\"HOME\", str(tmpdir))\n home_var = os.path.normpath(os.path.expandvars(\"$HOME/test.xml\"))\n xml_var = LogXML(\"$HOME%stest.xml\" % tmpdir.sep, None)\n assert xml_var.logfile == home_var\n\n\ndef test_logxml_changingdir(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_func():\n import os\n os.chdir(\"a\")\n \"\"\"\n )\n testdir.tmpdir.mkdir(\"a\")\n result = testdir.runpytest(\"--junitxml=a/x.xml\")\n assert result.ret == 0\n assert testdir.tmpdir.join(\"a/x.xml\").check()\n\n\ndef test_logxml_makedir(testdir):\n \"\"\"--junitxml should automatically create directories for the xml file\"\"\"\n testdir.makepyfile(\n \"\"\"\n def test_pass():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--junitxml=path/to/results.xml\")\n assert result.ret == 0\n assert testdir.tmpdir.join(\"path/to/results.xml\").check()\n\n\ndef test_logxml_check_isdir(testdir):\n \"\"\"Give an error if --junit-xml is a directory (#2089)\"\"\"\n result = testdir.runpytest(\"--junit-xml=.\")\n result.stderr.fnmatch_lines([\"*--junitxml must be a filename*\"])\n\n\ndef test_escaped_parametrized_names_xml(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('char', [u\"\\\\x00\"])\n def test_func(char):\n assert char\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testcase\")\n node.assert_attr(name=\"test_func[\\\\x00]\")\n\n\ndef test_double_colon_split_function_issue469(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('param', [\"double::colon\"])\n def test_func(param):\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testcase\")\n node.assert_attr(classname=\"test_double_colon_split_function_issue469\")\n node.assert_attr(name=\"test_func[double::colon]\")\n\n\ndef test_double_colon_split_method_issue469(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n class TestClass(object):\n @pytest.mark.parametrize('param', [\"double::colon\"])\n def test_func(self, param):\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testcase\")\n node.assert_attr(classname=\"test_double_colon_split_method_issue469.TestClass\")\n node.assert_attr(name=\"test_func[double::colon]\")\n\n\ndef test_unicode_issue368(testdir):\n path = testdir.tmpdir.join(\"test.xml\")\n log = LogXML(str(path), None)\n ustr = u\"ВНИ!\"\n\n class Report(BaseReport):\n longrepr = ustr\n sections = []\n nodeid = \"something\"\n location = \"tests/filename.py\", 42, \"TestClass.method\"\n\n test_report = Report()\n\n # hopefully this is not too brittle ...\n log.pytest_sessionstart()\n node_reporter = log._opentestcase(test_report)\n node_reporter.append_failure(test_report)\n node_reporter.append_collect_error(test_report)\n node_reporter.append_collect_skipped(test_report)\n node_reporter.append_error(test_report)\n test_report.longrepr = \"filename\", 1, ustr\n node_reporter.append_skipped(test_report)\n test_report.longrepr = \"filename\", 1, \"Skipped: 卡嘣嘣\"\n node_reporter.append_skipped(test_report)\n test_report.wasxfail = ustr\n node_reporter.append_skipped(test_report)\n log.pytest_sessionfinish()\n\n\ndef test_record_property(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def other(record_property):\n record_property(\"bar\", 1)\n def test_record(record_property, other):\n record_property(\"foo\", \"<1\");\n \"\"\"\n )\n result, dom = runandparse(testdir, \"-rwv\")\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n psnode = tnode.find_first_by_tag(\"properties\")\n pnodes = psnode.find_by_tag(\"property\")\n pnodes[0].assert_attr(name=\"bar\", value=\"1\")\n pnodes[1].assert_attr(name=\"foo\", value=\"<1\")\n\n\ndef test_record_property_same_name(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_record_with_same_name(record_property):\n record_property(\"foo\", \"bar\")\n record_property(\"foo\", \"baz\")\n \"\"\"\n )\n result, dom = runandparse(testdir, \"-rw\")\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n psnode = tnode.find_first_by_tag(\"properties\")\n pnodes = psnode.find_by_tag(\"property\")\n pnodes[0].assert_attr(name=\"foo\", value=\"bar\")\n pnodes[1].assert_attr(name=\"foo\", value=\"baz\")\n\n\n@pytest.mark.parametrize(\"fixture_name\", [\"record_property\", \"record_xml_attribute\"])\ndef test_record_fixtures_without_junitxml(testdir, fixture_name):\n testdir.makepyfile(\n \"\"\"\n def test_record({fixture_name}):\n {fixture_name}(\"foo\", \"bar\")\n \"\"\".format(\n fixture_name=fixture_name\n )\n )\n result = testdir.runpytest()\n assert result.ret == 0\n\n\n@pytest.mark.filterwarnings(\"default\")\ndef test_record_attribute(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n junit_family = xunit1\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def other(record_xml_attribute):\n record_xml_attribute(\"bar\", 1)\n def test_record(record_xml_attribute, other):\n record_xml_attribute(\"foo\", \"<1\");\n \"\"\"\n )\n result, dom = runandparse(testdir, \"-rw\")\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(bar=\"1\")\n tnode.assert_attr(foo=\"<1\")\n result.stdout.fnmatch_lines(\n [\"*test_record_attribute.py:6:*record_xml_attribute is an experimental feature\"]\n )\n\n\n@pytest.mark.filterwarnings(\"default\")\n@pytest.mark.parametrize(\"fixture_name\", [\"record_xml_attribute\", \"record_property\"])\ndef test_record_fixtures_xunit2(testdir, fixture_name):\n \"\"\"Ensure record_xml_attribute and record_property drop values when outside of legacy family\n \"\"\"\n testdir.makeini(\n \"\"\"\n [pytest]\n junit_family = xunit2\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def other({fixture_name}):\n {fixture_name}(\"bar\", 1)\n def test_record({fixture_name}, other):\n {fixture_name}(\"foo\", \"<1\");\n \"\"\".format(\n fixture_name=fixture_name\n )\n )\n\n result, dom = runandparse(testdir, \"-rw\")\n expected_lines = []\n if fixture_name == \"record_xml_attribute\":\n expected_lines.append(\n \"*test_record_fixtures_xunit2.py:6:*record_xml_attribute is an experimental feature\"\n )\n expected_lines = [\n \"*test_record_fixtures_xunit2.py:6:*{fixture_name} is incompatible \"\n \"with junit_family 'xunit2' (use 'legacy' or 'xunit1')\".format(\n fixture_name=fixture_name\n )\n ]\n result.stdout.fnmatch_lines(expected_lines)\n\n\ndef test_random_report_log_xdist(testdir, monkeypatch):\n \"\"\"xdist calls pytest_runtest_logreport as they are executed by the slaves,\n with nodes from several nodes overlapping, so junitxml must cope with that\n to produce correct reports. #1064\n \"\"\"\n pytest.importorskip(\"xdist\")\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n testdir.makepyfile(\n \"\"\"\n import pytest, time\n @pytest.mark.parametrize('i', list(range(30)))\n def test_x(i):\n assert i != 22\n \"\"\"\n )\n _, dom = runandparse(testdir, \"-n2\")\n suite_node = dom.find_first_by_tag(\"testsuite\")\n failed = []\n for case_node in suite_node.find_by_tag(\"testcase\"):\n if case_node.find_first_by_tag(\"failure\"):\n failed.append(case_node[\"name\"])\n\n assert failed == [\"test_x[22]\"]\n\n\ndef test_runs_twice(testdir):\n f = testdir.makepyfile(\n \"\"\"\n def test_pass():\n pass\n \"\"\"\n )\n\n result, dom = runandparse(testdir, f, f)\n assert \"INTERNALERROR\" not in result.stdout.str()\n first, second = [x[\"classname\"] for x in dom.find_by_tag(\"testcase\")]\n assert first == second\n\n\n@pytest.mark.xfail(reason=\"hangs\", run=False)\ndef test_runs_twice_xdist(testdir):\n pytest.importorskip(\"xdist\")\n f = testdir.makepyfile(\n \"\"\"\n def test_pass():\n pass\n \"\"\"\n )\n\n result, dom = runandparse(testdir, f, \"--dist\", \"each\", \"--tx\", \"2*popen\")\n assert \"INTERNALERROR\" not in result.stdout.str()\n first, second = [x[\"classname\"] for x in dom.find_by_tag(\"testcase\")]\n assert first == second\n\n\ndef test_fancy_items_regression(testdir):\n # issue 1259\n testdir.makeconftest(\n \"\"\"\n import pytest\n class FunItem(pytest.Item):\n def runtest(self):\n pass\n class NoFunItem(pytest.Item):\n def runtest(self):\n pass\n\n class FunCollector(pytest.File):\n def collect(self):\n return [\n FunItem('a', self),\n NoFunItem('a', self),\n NoFunItem('b', self),\n ]\n\n def pytest_collect_file(path, parent):\n if path.check(ext='.py'):\n return FunCollector(path, parent)\n \"\"\"\n )\n\n testdir.makepyfile(\n \"\"\"\n def test_pass():\n pass\n \"\"\"\n )\n\n result, dom = runandparse(testdir)\n\n assert \"INTERNALERROR\" not in result.stdout.str()\n\n items = sorted(\"%(classname)s %(name)s\" % x for x in dom.find_by_tag(\"testcase\"))\n import pprint\n\n pprint.pprint(items)\n assert items == [\n u\"conftest a\",\n u\"conftest a\",\n u\"conftest b\",\n u\"test_fancy_items_regression a\",\n u\"test_fancy_items_regression a\",\n u\"test_fancy_items_regression b\",\n u\"test_fancy_items_regression test_pass\",\n ]\n\n\ndef test_global_properties(testdir):\n path = testdir.tmpdir.join(\"test_global_properties.xml\")\n log = LogXML(str(path), None)\n\n class Report(BaseReport):\n sections = []\n nodeid = \"test_node_id\"\n\n log.pytest_sessionstart()\n log.add_global_property(\"foo\", 1)\n log.add_global_property(\"bar\", 2)\n log.pytest_sessionfinish()\n\n dom = minidom.parse(str(path))\n\n properties = dom.getElementsByTagName(\"properties\")\n\n assert properties.length == 1, \"There must be one node\"\n\n property_list = dom.getElementsByTagName(\"property\")\n\n assert property_list.length == 2, \"There most be only 2 property nodes\"\n\n expected = {\"foo\": \"1\", \"bar\": \"2\"}\n actual = {}\n\n for p in property_list:\n k = str(p.getAttribute(\"name\"))\n v = str(p.getAttribute(\"value\"))\n actual[k] = v\n\n assert actual == expected\n\n\ndef test_url_property(testdir):\n test_url = \"http://www.github.com/pytest-dev\"\n path = testdir.tmpdir.join(\"test_url_property.xml\")\n log = LogXML(str(path), None)\n\n class Report(BaseReport):\n longrepr = \"FooBarBaz\"\n sections = []\n nodeid = \"something\"\n location = \"tests/filename.py\", 42, \"TestClass.method\"\n url = test_url\n\n test_report = Report()\n\n log.pytest_sessionstart()\n node_reporter = log._opentestcase(test_report)\n node_reporter.append_failure(test_report)\n log.pytest_sessionfinish()\n\n test_case = minidom.parse(str(path)).getElementsByTagName(\"testcase\")[0]\n\n assert (\n test_case.getAttribute(\"url\") == test_url\n ), \"The URL did not get written to the xml\"\n\n\ndef test_record_testsuite_property(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_func1(record_testsuite_property):\n record_testsuite_property(\"stats\", \"all good\")\n\n def test_func2(record_testsuite_property):\n record_testsuite_property(\"stats\", 10)\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testsuite\")\n properties_node = node.find_first_by_tag(\"properties\")\n p1_node = properties_node.find_nth_by_tag(\"property\", 0)\n p2_node = properties_node.find_nth_by_tag(\"property\", 1)\n p1_node.assert_attr(name=\"stats\", value=\"all good\")\n p2_node.assert_attr(name=\"stats\", value=\"10\")\n\n\ndef test_record_testsuite_property_junit_disabled(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_func1(record_testsuite_property):\n record_testsuite_property(\"stats\", \"all good\")\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0\n\n\n@pytest.mark.parametrize(\"junit\", [True, False])\ndef test_record_testsuite_property_type_checking(testdir, junit):\n testdir.makepyfile(\n \"\"\"\n def test_func1(record_testsuite_property):\n record_testsuite_property(1, 2)\n \"\"\"\n )\n args = (\"--junitxml=tests.xml\",) if junit else ()\n result = testdir.runpytest(*args)\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\"*TypeError: name parameter needs to be a string, but int given\"]\n )\n\n\n@pytest.mark.parametrize(\"suite_name\", [\"my_suite\", \"\"])\ndef test_set_suite_name(testdir, suite_name):\n if suite_name:\n testdir.makeini(\n \"\"\"\n [pytest]\n junit_suite_name={}\n \"\"\".format(\n suite_name\n )\n )\n expected = suite_name\n else:\n expected = \"pytest\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n def test_func():\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(name=expected)\n\n\ndef test_escaped_skipreason_issue3533(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip(reason='1 <> 2')\n def test_skip():\n pass\n \"\"\"\n )\n _, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testcase\")\n snode = node.find_first_by_tag(\"skipped\")\n assert \"1 <> 2\" in snode.text\n snode.assert_attr(message=\"1 <> 2\")\n\n\ndef test_logging_passing_tests_disabled_does_not_log_test_output(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n junit_log_passing_tests=False\n junit_logging=system-out\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n import sys\n\n def test_func():\n sys.stdout.write('This is stdout')\n sys.stderr.write('This is stderr')\n logging.warning('hello')\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testcase\")\n assert len(node.find_by_tag(\"system-err\")) == 0\n assert len(node.find_by_tag(\"system-out\")) == 0\n"},{"col":4,"comment":"null","endLoc":599,"header":"def test_lastfailed_creates_cache_when_needed(self, testdir)","id":4392,"name":"test_lastfailed_creates_cache_when_needed","nodeType":"Function","startLoc":587,"text":"def test_lastfailed_creates_cache_when_needed(self, testdir):\n # Issue #1342\n testdir.makepyfile(test_empty=\"\")\n testdir.runpytest(\"-q\", \"--lf\")\n assert not os.path.exists(\".pytest_cache/v/cache/lastfailed\")\n\n testdir.makepyfile(test_successful=\"def test_success():\\n assert True\")\n testdir.runpytest(\"-q\", \"--lf\")\n assert not os.path.exists(\".pytest_cache/v/cache/lastfailed\")\n\n testdir.makepyfile(test_errored=\"def test_error():\\n assert False\")\n testdir.runpytest(\"-q\", \"--lf\")\n assert os.path.exists(\".pytest_cache/v/cache/lastfailed\")"},{"id":4393,"name":"release-3.6.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.6.0\n=======================================\n\nThe pytest team is proud to announce the 3.6.0 release!\n\npytest is a mature Python testing tool with more than a 1600 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n http://doc.pytest.org/en/latest/changelog.html\n\nFor complete documentation, please visit:\n\n http://docs.pytest.org\n\nAs usual, you can upgrade from pypi via:\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Shaw\n* ApaDoctor\n* Brian Maissy\n* Bruno Oliveira\n* Jon Dufresne\n* Katerina Koukiou\n* Miro Hrončok\n* Rachel Kogan\n* Ronny Pfannschmidt\n* Tim Hughes\n* Tyler Goodlet\n* Ville Skyttä\n* aviral1701\n* feuillemorte\n\n\nHappy testing,\nThe Pytest Development Team\n"},{"col":4,"comment":"null","endLoc":49,"header":"def test_setup_fails_and_failure_is_cached(self, testdir)","id":4394,"name":"test_setup_fails_and_failure_is_cached","nodeType":"Function","startLoc":39,"text":"def test_setup_fails_and_failure_is_cached(self, testdir):\n item = testdir.getitem(\n \"\"\"\n def setup_module(mod):\n raise ValueError(42)\n def test_func(): pass\n \"\"\"\n )\n ss = runner.SetupState()\n pytest.raises(ValueError, lambda: ss.prepare(item))\n pytest.raises(ValueError, lambda: ss.prepare(item))"},{"col":4,"comment":"null","endLoc":1202,"header":"def test_long_case(self, testdir)","id":4395,"name":"test_long_case","nodeType":"Function","startLoc":1194,"text":"def test_long_case(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_ternary_display():\n assert False == (False == True) == True\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*E*assert (False == True) == True\"])"},{"col":34,"endLoc":48,"id":4396,"nodeType":"Lambda","startLoc":48,"text":"lambda: ss.prepare(item)"},{"className":"DomNode","col":0,"comment":"null","endLoc":85,"id":4397,"nodeType":"Class","startLoc":37,"text":"class DomNode(object):\n def __init__(self, dom):\n self.__node = dom\n\n def __repr__(self):\n return self.__node.toxml()\n\n def find_first_by_tag(self, tag):\n return self.find_nth_by_tag(tag, 0)\n\n def _by_tag(self, tag):\n return self.__node.getElementsByTagName(tag)\n\n def find_nth_by_tag(self, tag, n):\n items = self._by_tag(tag)\n try:\n nth = items[n]\n except IndexError:\n pass\n else:\n return type(self)(nth)\n\n def find_by_tag(self, tag):\n t = type(self)\n return [t(x) for x in self.__node.getElementsByTagName(tag)]\n\n def __getitem__(self, key):\n node = self.__node.getAttributeNode(key)\n if node is not None:\n return node.value\n\n def assert_attr(self, **kwargs):\n __tracebackhide__ = True\n return assert_attr(self.__node, **kwargs)\n\n def toxml(self):\n return self.__node.toxml()\n\n @property\n def text(self):\n return self.__node.childNodes[0].wholeText\n\n @property\n def tag(self):\n return self.__node.tagName\n\n @property\n def next_siebling(self):\n return type(self)(self.__node.nextSibling)"},{"col":4,"comment":"null","endLoc":39,"header":"def __init__(self, dom)","id":4398,"name":"__init__","nodeType":"Function","startLoc":38,"text":"def __init__(self, dom):\n self.__node = dom"},{"col":4,"comment":"null","endLoc":42,"header":"def __repr__(self)","id":4399,"name":"__repr__","nodeType":"Function","startLoc":41,"text":"def __repr__(self):\n return self.__node.toxml()"},{"col":34,"endLoc":49,"id":4400,"nodeType":"Lambda","startLoc":49,"text":"lambda: ss.prepare(item)"},{"col":4,"comment":"null","endLoc":71,"header":"def test_teardown_multiple_one_fails(self, testdir)","id":4401,"name":"test_teardown_multiple_one_fails","nodeType":"Function","startLoc":51,"text":"def test_teardown_multiple_one_fails(self, testdir):\n r = []\n\n def fin1():\n r.append(\"fin1\")\n\n def fin2():\n raise Exception(\"oops\")\n\n def fin3():\n r.append(\"fin3\")\n\n item = testdir.getitem(\"def test_func(): pass\")\n ss = runner.SetupState()\n ss.addfinalizer(fin1, item)\n ss.addfinalizer(fin2, item)\n ss.addfinalizer(fin3, item)\n with pytest.raises(Exception) as err:\n ss._callfinalizers(item)\n assert err.value.args == (\"oops\",)\n assert r == [\"fin3\", \"fin1\"]"},{"col":4,"comment":"null","endLoc":1212,"header":"def test_many_brackets(self, testdir)","id":4402,"name":"test_many_brackets","nodeType":"Function","startLoc":1204,"text":"def test_many_brackets(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_ternary_display():\n assert True == ((False == True) == True)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*E*assert True == ((False == True) == True)\"])"},{"className":"TestTraceOption","col":0,"comment":"null","endLoc":1029,"id":4403,"nodeType":"Class","startLoc":999,"text":"class TestTraceOption:\n def test_trace_sets_breakpoint(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1():\n assert True\n\n def test_2():\n pass\n\n def test_3():\n pass\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--trace \" + str(p1))\n child.expect(\"test_1\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n child.expect(\"test_2\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n child.expect(\"test_3\")\n child.expect(\"Pdb\")\n child.sendline(\"q\")\n child.expect_exact(\"Exit: Quitting debugger\")\n rest = child.read().decode(\"utf8\")\n assert \"2 passed in\" in rest\n assert \"reading from stdin while output\" not in rest\n # Only printed once - not on stderr.\n assert \"Exit: Quitting debugger\" not in child.before.decode(\"utf8\")\n TestPDB.flush(child)"},{"col":4,"comment":"null","endLoc":1029,"header":"def test_trace_sets_breakpoint(self, testdir)","id":4404,"name":"test_trace_sets_breakpoint","nodeType":"Function","startLoc":1000,"text":"def test_trace_sets_breakpoint(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_1():\n assert True\n\n def test_2():\n pass\n\n def test_3():\n pass\n \"\"\"\n )\n child = testdir.spawn_pytest(\"--trace \" + str(p1))\n child.expect(\"test_1\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n child.expect(\"test_2\")\n child.expect(\"Pdb\")\n child.sendline(\"c\")\n child.expect(\"test_3\")\n child.expect(\"Pdb\")\n child.sendline(\"q\")\n child.expect_exact(\"Exit: Quitting debugger\")\n rest = child.read().decode(\"utf8\")\n assert \"2 passed in\" in rest\n assert \"reading from stdin while output\" not in rest\n # Only printed once - not on stderr.\n assert \"Exit: Quitting debugger\" not in child.before.decode(\"utf8\")\n TestPDB.flush(child)"},{"attributeType":"int","col":0,"comment":"null","endLoc":32,"id":4405,"name":"EXIT_INTERNALERROR","nodeType":"Attribute","startLoc":32,"text":"EXIT_INTERNALERROR"},{"col":0,"comment":"","endLoc":2,"header":"main.py#","id":4406,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" core implementation of testing process: init, session, runtest loop. \"\"\"\n\nEXIT_OK = 0\n\nEXIT_TESTSFAILED = 1\n\nEXIT_INTERRUPTED = 2\n\nEXIT_INTERNALERROR = 3\n\nEXIT_USAGEERROR = 4\n\nEXIT_NOTESTSCOLLECTED = 5"},{"col":4,"comment":"null","endLoc":612,"header":"def test_xfail_not_considered_failure(self, testdir)","id":4407,"name":"test_xfail_not_considered_failure","nodeType":"Function","startLoc":601,"text":"def test_xfail_not_considered_failure(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail\n def test():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 xfailed*\"])\n assert self.get_cached_last_failed(testdir) == []"},{"className":"TestIssue2121","col":0,"comment":"null","endLoc":1232,"id":4408,"nodeType":"Class","startLoc":1215,"text":"class TestIssue2121:\n def test_rewrite_python_files_contain_subdirs(self, testdir):\n testdir.makepyfile(\n **{\n \"tests/file.py\": \"\"\"\n def test_simple_failure():\n assert 1 + 1 == 3\n \"\"\"\n }\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n python_files = tests/**.py\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*E*assert (1 + 1) == 3\"])"},{"col":4,"comment":"null","endLoc":1232,"header":"def test_rewrite_python_files_contain_subdirs(self, testdir)","id":4409,"name":"test_rewrite_python_files_contain_subdirs","nodeType":"Function","startLoc":1216,"text":"def test_rewrite_python_files_contain_subdirs(self, testdir):\n testdir.makepyfile(\n **{\n \"tests/file.py\": \"\"\"\n def test_simple_failure():\n assert 1 + 1 == 3\n \"\"\"\n }\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n python_files = tests/**.py\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*E*assert (1 + 1) == 3\"])"},{"id":4410,"name":"README.rst","nodeType":"TextFile","path":"testing/example_scripts","text":"Example test scripts\n=====================\n\n\nThe files in this folder are not direct tests, but rather example test suites that demonstrate certain issues/behaviours.\n\nIn the future we will move part of the content of the acceptance tests here in order to have directly testable code instead of writing out things and then running them in nested pytest sessions/subprocesses.\n\nThis will aid debugging and comprehension.\n"},{"fileName":"conftest.py","filePath":"doc/en","id":4411,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ncollect_ignore = [\"conf.py\"]\n"},{"attributeType":"list","col":0,"comment":"null","endLoc":2,"id":4412,"name":"collect_ignore","nodeType":"Attribute","startLoc":2,"text":"collect_ignore"},{"col":4,"comment":"null","endLoc":45,"header":"def find_first_by_tag(self, tag)","id":4413,"name":"find_first_by_tag","nodeType":"Function","startLoc":44,"text":"def find_first_by_tag(self, tag):\n return self.find_nth_by_tag(tag, 0)"},{"className":"TestEarlyRewriteBailout","col":0,"comment":"null","endLoc":1397,"id":4414,"nodeType":"Class","startLoc":1290,"text":"class TestEarlyRewriteBailout(object):\n @pytest.fixture\n def hook(self, pytestconfig, monkeypatch, testdir):\n \"\"\"Returns a patched AssertionRewritingHook instance so we can configure its initial paths and track\n if imp.find_module has been called.\n \"\"\"\n import imp\n\n self.find_module_calls = []\n self.initial_paths = set()\n\n class StubSession(object):\n _initialpaths = self.initial_paths\n\n def isinitpath(self, p):\n return p in self._initialpaths\n\n def spy_imp_find_module(name, path):\n self.find_module_calls.append(name)\n return imp.find_module(name, path)\n\n hook = AssertionRewritingHook(pytestconfig)\n # use default patterns, otherwise we inherit pytest's testing config\n hook.fnpats[:] = [\"test_*.py\", \"*_test.py\"]\n monkeypatch.setattr(hook, \"_imp_find_module\", spy_imp_find_module)\n hook.set_session(StubSession())\n testdir.syspathinsert()\n return hook\n\n def test_basic(self, testdir, hook):\n \"\"\"\n Ensure we avoid calling imp.find_module when we know for sure a certain module will not be rewritten\n to optimize assertion rewriting (#3918).\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture\n def fix(): return 1\n \"\"\"\n )\n testdir.makepyfile(test_foo=\"def test_foo(): pass\")\n testdir.makepyfile(bar=\"def bar(): pass\")\n foobar_path = testdir.makepyfile(foobar=\"def foobar(): pass\")\n self.initial_paths.add(foobar_path)\n\n # conftest files should always be rewritten\n assert hook.find_module(\"conftest\") is not None\n assert self.find_module_calls == [\"conftest\"]\n\n # files matching \"python_files\" mask should always be rewritten\n assert hook.find_module(\"test_foo\") is not None\n assert self.find_module_calls == [\"conftest\", \"test_foo\"]\n\n # file does not match \"python_files\": early bailout\n assert hook.find_module(\"bar\") is None\n assert self.find_module_calls == [\"conftest\", \"test_foo\"]\n\n # file is an initial path (passed on the command-line): should be rewritten\n assert hook.find_module(\"foobar\") is not None\n assert self.find_module_calls == [\"conftest\", \"test_foo\", \"foobar\"]\n\n def test_pattern_contains_subdirectories(self, testdir, hook):\n \"\"\"If one of the python_files patterns contain subdirectories (\"tests/**.py\") we can't bailout early\n because we need to match with the full path, which can only be found by calling imp.find_module.\n \"\"\"\n p = testdir.makepyfile(\n **{\n \"tests/file.py\": \"\"\"\n def test_simple_failure():\n assert 1 + 1 == 3\n \"\"\"\n }\n )\n testdir.syspathinsert(p.dirpath())\n hook.fnpats[:] = [\"tests/**.py\"]\n assert hook.find_module(\"file\") is not None\n assert self.find_module_calls == [\"file\"]\n\n @pytest.mark.skipif(\n sys.platform.startswith(\"win32\"), reason=\"cannot remove cwd on Windows\"\n )\n def test_cwd_changed(self, testdir, monkeypatch):\n # Setup conditions for py's fspath trying to import pathlib on py34\n # always (previously triggered via xdist only).\n # Ref: https://github.com/pytest-dev/py/pull/207\n monkeypatch.syspath_prepend(\"\")\n monkeypatch.delitem(sys.modules, \"pathlib\", raising=False)\n\n testdir.makepyfile(\n **{\n \"test_setup_nonexisting_cwd.py\": \"\"\"\n import os\n import shutil\n import tempfile\n\n d = tempfile.mkdtemp()\n os.chdir(d)\n shutil.rmtree(d)\n \"\"\",\n \"test_test.py\": \"\"\"\n def test():\n pass\n \"\"\",\n }\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 passed in *\"])"},{"col":4,"comment":"Returns a patched AssertionRewritingHook instance so we can configure its initial paths and track\n if imp.find_module has been called.\n ","endLoc":1317,"header":"@pytest.fixture\n def hook(self, pytestconfig, monkeypatch, testdir)","id":4415,"name":"hook","nodeType":"Function","startLoc":1291,"text":"@pytest.fixture\n def hook(self, pytestconfig, monkeypatch, testdir):\n \"\"\"Returns a patched AssertionRewritingHook instance so we can configure its initial paths and track\n if imp.find_module has been called.\n \"\"\"\n import imp\n\n self.find_module_calls = []\n self.initial_paths = set()\n\n class StubSession(object):\n _initialpaths = self.initial_paths\n\n def isinitpath(self, p):\n return p in self._initialpaths\n\n def spy_imp_find_module(name, path):\n self.find_module_calls.append(name)\n return imp.find_module(name, path)\n\n hook = AssertionRewritingHook(pytestconfig)\n # use default patterns, otherwise we inherit pytest's testing config\n hook.fnpats[:] = [\"test_*.py\", \"*_test.py\"]\n monkeypatch.setattr(hook, \"_imp_find_module\", spy_imp_find_module)\n hook.set_session(StubSession())\n testdir.syspathinsert()\n return hook"},{"col":0,"comment":"","endLoc":2,"header":"conftest.py#","id":4416,"name":"","nodeType":"Function","startLoc":2,"text":"collect_ignore = [\"conf.py\"]"},{"col":0,"comment":"null","endLoc":52,"header":"@pytest.fixture\ndef custom_pdb_calls()","id":4417,"name":"custom_pdb_calls","nodeType":"Function","startLoc":34,"text":"@pytest.fixture\ndef custom_pdb_calls():\n called = []\n\n # install dummy debugger class and track which methods were called on it\n class _CustomPdb(object):\n quitting = False\n\n def __init__(self, *args, **kwargs):\n called.append(\"init\")\n\n def reset(self):\n called.append(\"reset\")\n\n def interaction(self, *args):\n called.append(\"interaction\")\n\n _pytest._CustomPdb = _CustomPdb\n return called"},{"id":4418,"name":"release-2.2.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"py.test 2.2.0: test marking++, parametrization++ and duration profiling\n===========================================================================\n\npytest-2.2.0 is a test-suite compatible release of the popular\npy.test testing tool. Plugins might need upgrades. It comes\nwith these improvements:\n\n* easier and more powerful parametrization of tests:\n\n - new @pytest.mark.parametrize decorator to run tests with different arguments\n - new metafunc.parametrize() API for parametrizing arguments independently\n - see examples at http://pytest.org/latest/example/parametrize.html\n - NOTE that parametrize() related APIs are still a bit experimental\n and might change in future releases.\n\n* improved handling of test markers and refined marking mechanism:\n\n - \"-m markexpr\" option for selecting tests according to their mark\n - a new \"markers\" ini-variable for registering test markers for your project\n - the new \"--strict\" bails out with an error if using unregistered markers.\n - see examples at http://pytest.org/latest/example/markers.html\n\n* duration profiling: new \"--duration=N\" option showing the N slowest test\n execution or setup/teardown calls. This is most useful if you want to\n find out where your slowest test code is.\n\n* also 2.2.0 performs more eager calling of teardown/finalizers functions\n resulting in better and more accurate reporting when they fail\n\nBesides there is the usual set of bug fixes along with a cleanup of\npytest's own test suite allowing it to run on a wider range of environments.\n\nFor general information, see extensive docs with examples here:\n\n http://pytest.org/\n\nIf you want to install or upgrade pytest you might just type::\n\n pip install -U pytest # or\n easy_install -U pytest\n\nThanks to Ronny Pfannschmidt, David Burns, Jeff Donner, Daniel Nouri, Alfredo Deza and all who gave feedback or sent bug reports.\n\nbest,\nholger krekel\n\n\nnotes on incompatibility\n------------------------------\n\nWhile test suites should work unchanged you might need to upgrade plugins:\n\n* You need a new version of the pytest-xdist plugin (1.7) for distributing\n test runs.\n\n* Other plugins might need an upgrade if they implement\n the ``pytest_runtest_logreport`` hook which now is called unconditionally\n for the setup/teardown fixture phases of a test. You may choose to\n ignore setup/teardown failures by inserting \"if rep.when != 'call': return\"\n or something similar. Note that most code probably \"just\" works because\n the hook was already called for failing setup/teardown phases of a test\n so a plugin should have been ready to grok such reports already.\n\n\nChanges between 2.1.3 and 2.2.0\n----------------------------------------\n\n- fix issue90: introduce eager tearing down of test items so that\n teardown function are called earlier.\n- add an all-powerful metafunc.parametrize function which allows to\n parametrize test function arguments in multiple steps and therefore\n from independent plugins and places.\n- add a @pytest.mark.parametrize helper which allows to easily\n call a test function with different argument values.\n- Add examples to the \"parametrize\" example page, including a quick port\n of Test scenarios and the new parametrize function and decorator.\n- introduce registration for \"pytest.mark.*\" helpers via ini-files\n or through plugin hooks. Also introduce a \"--strict\" option which\n will treat unregistered markers as errors\n allowing to avoid typos and maintain a well described set of markers\n for your test suite. See examples at http://pytest.org/latest/mark.html\n and its links.\n- issue50: introduce \"-m marker\" option to select tests based on markers\n (this is a stricter and more predictable version of \"-k\" in that \"-m\"\n only matches complete markers and has more obvious rules for and/or\n semantics.\n- new feature to help optimizing the speed of your tests:\n --durations=N option for displaying N slowest test calls\n and setup/teardown methods.\n- fix issue87: --pastebin now works with python3\n- fix issue89: --pdb with unexpected exceptions in doctest work more sensibly\n- fix and cleanup pytest's own test suite to not leak FDs\n- fix issue83: link to generated funcarg list\n- fix issue74: pyarg module names are now checked against imp.find_module false positives\n- fix compatibility with twisted/trial-11.1.0 use cases\n"},{"id":4419,"name":"release-3.1.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.1.2\n=======================================\n\npytest 3.1.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Andreas Pelme\n* ApaDoctor\n* Bruno Oliveira\n* Florian Bruhin\n* Ronny Pfannschmidt\n* Segev Finer\n\n\nHappy testing,\nThe pytest Development Team\n"},{"col":0,"comment":"null","endLoc":76,"header":"@pytest.fixture\ndef custom_debugger_hook()","id":4420,"name":"custom_debugger_hook","nodeType":"Function","startLoc":55,"text":"@pytest.fixture\ndef custom_debugger_hook():\n called = []\n\n # install dummy debugger class and track which methods were called on it\n class _CustomDebugger(object):\n def __init__(self, *args, **kwargs):\n called.append(\"init\")\n\n def reset(self):\n called.append(\"reset\")\n\n def interaction(self, *args):\n called.append(\"interaction\")\n\n def set_trace(self, frame):\n print(\"**CustomDebugger**\")\n called.append(\"set_trace\")\n\n _pytest._CustomDebugger = _CustomDebugger\n yield called\n del _pytest._CustomDebugger"},{"id":4421,"name":"release-3.1.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.1.1\n=======================================\n\npytest 3.1.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n* Florian Bruhin\n* Floris Bruynooghe\n* Jason R. Coombs\n* Ronny Pfannschmidt\n* wanghui\n\n\nHappy testing,\nThe pytest Development Team\n"},{"col":4,"comment":"null","endLoc":678,"header":"def get_cached_last_failed(self, testdir)","id":4422,"name":"get_cached_last_failed","nodeType":"Function","startLoc":676,"text":"def get_cached_last_failed(self, testdir):\n config = testdir.parseconfigure()\n return sorted(config.cache.get(\"cache/lastfailed\", {}))"},{"col":4,"comment":"null","endLoc":627,"header":"def test_xfail_strict_considered_failure(self, testdir)","id":4423,"name":"test_xfail_strict_considered_failure","nodeType":"Function","startLoc":614,"text":"def test_xfail_strict_considered_failure(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(strict=True)\n def test():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 failed*\"])\n assert self.get_cached_last_failed(testdir) == [\n \"test_xfail_strict_considered_failure.py::test\"\n ]"},{"id":4424,"name":"release-2.8.4.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.8.4\n============\n\npytest is a mature Python testing tool with more than a 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is supposed to be drop-in compatible to 2.8.2.\n\nSee below for the changes and see docs at:\n\n http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n Bruno Oliveira\n Florian Bruhin\n Jeff Widman\n Mehdy Khoshnoody\n Nicholas Chammas\n Ronny Pfannschmidt\n Tim Chan\n\n\nHappy testing,\nThe py.test Development Team\n\n\n2.8.4 (compared to 2.8.3)\n-----------------------------\n\n- fix #1190: ``deprecated_call()`` now works when the deprecated\n function has been already called by another test in the same\n module. Thanks Mikhail Chernykh for the report and Bruno Oliveira for the\n PR.\n\n- fix #1198: ``--pastebin`` option now works on Python 3. Thanks\n Mehdy Khoshnoody for the PR.\n\n- fix #1219: ``--pastebin`` now works correctly when captured output contains\n non-ascii characters. Thanks Bruno Oliveira for the PR.\n\n- fix #1204: another error when collecting with a nasty __getattr__().\n Thanks Florian Bruhin for the PR.\n\n- fix the summary printed when no tests did run.\n Thanks Florian Bruhin for the PR.\n\n- a number of documentation modernizations wrt good practices.\n Thanks Bruno Oliveira for the PR.\n"},{"id":4425,"name":"pytest.ini","nodeType":"TextFile","path":"doc/en","text":"[pytest]\n# just defined to prevent the root level tox.ini from kicking in\n"},{"col":0,"comment":"Test that debugging's pytest_configure is re-entrant.","endLoc":1060,"header":"def test_trace_after_runpytest(testdir)","id":4426,"name":"test_trace_after_runpytest","nodeType":"Function","startLoc":1032,"text":"def test_trace_after_runpytest(testdir):\n \"\"\"Test that debugging's pytest_configure is re-entrant.\"\"\"\n p1 = testdir.makepyfile(\n \"\"\"\n from _pytest.debugging import pytestPDB\n\n def test_outer(testdir):\n assert len(pytestPDB._saved) == 1\n\n testdir.makepyfile(\n \\\"\"\"\n from _pytest.debugging import pytestPDB\n\n def test_inner():\n assert len(pytestPDB._saved) == 2\n print()\n print(\"test_inner_\" + \"end\")\n \\\"\"\"\n )\n\n result = testdir.runpytest(\"-s\", \"-k\", \"test_inner\")\n assert result.ret == 0\n\n assert len(pytestPDB._saved) == 1\n \"\"\"\n )\n result = testdir.runpytest_subprocess(\"-s\", \"-p\", \"pytester\", str(p1))\n result.stdout.fnmatch_lines([\"test_inner_end\"])\n assert result.ret == 0"},{"attributeType":"null","col":4,"comment":"null","endLoc":204,"id":4427,"name":"message","nodeType":"Attribute","startLoc":204,"text":"message"},{"attributeType":"null","col":4,"comment":"null","endLoc":205,"id":4428,"name":"nodeid","nodeType":"Attribute","startLoc":205,"text":"nodeid"},{"col":4,"comment":"null","endLoc":657,"header":"@pytest.mark.parametrize(\"mark\", [\"mark.xfail\", \"mark.skip\"])\n def test_failed_changed_to_xfail_or_skip(self, testdir, mark)","id":4429,"name":"test_failed_changed_to_xfail_or_skip","nodeType":"Function","startLoc":629,"text":"@pytest.mark.parametrize(\"mark\", [\"mark.xfail\", \"mark.skip\"])\n def test_failed_changed_to_xfail_or_skip(self, testdir, mark):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n assert self.get_cached_last_failed(testdir) == [\n \"test_failed_changed_to_xfail_or_skip.py::test\"\n ]\n assert result.ret == 1\n\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.{mark}\n def test():\n assert 0\n \"\"\".format(\n mark=mark\n )\n )\n result = testdir.runpytest()\n assert result.ret == 0\n assert self.get_cached_last_failed(testdir) == []\n assert result.ret == 0"},{"attributeType":"null","col":4,"comment":"null","endLoc":206,"id":4430,"name":"fslocation","nodeType":"Attribute","startLoc":206,"text":"fslocation"},{"attributeType":"bool","col":4,"comment":"null","endLoc":207,"id":4431,"name":"count_towards_summary","nodeType":"Attribute","startLoc":207,"text":"count_towards_summary"},{"className":"TerminalReporter","col":0,"comment":"null","endLoc":954,"id":4432,"nodeType":"Class","startLoc":228,"text":"class TerminalReporter(object):\n def __init__(self, config, file=None):\n import _pytest.config\n\n self.config = config\n self._numcollected = 0\n self._session = None\n self._showfspath = None\n\n self.stats = {}\n self.startdir = config.invocation_dir\n if file is None:\n file = sys.stdout\n self._tw = _pytest.config.create_terminal_writer(config, file)\n # self.writer will be deprecated in pytest-3.4\n self.writer = self._tw\n self._screen_width = self._tw.fullwidth\n self.currentfspath = None\n self.reportchars = getreportopt(config)\n self.hasmarkup = self._tw.hasmarkup\n self.isatty = file.isatty()\n self._progress_nodeids_reported = set()\n self._show_progress_info = self._determine_show_progress_info()\n self._collect_report_last_write = None\n\n def _determine_show_progress_info(self):\n \"\"\"Return True if we should display progress information based on the current config\"\"\"\n # do not show progress if we are not capturing output (#3038)\n if self.config.getoption(\"capture\", \"no\") == \"no\":\n return False\n # do not show progress if we are showing fixture setup/teardown\n if self.config.getoption(\"setupshow\", False):\n return False\n cfg = self.config.getini(\"console_output_style\")\n if cfg in (\"progress\", \"count\"):\n return cfg\n return False\n\n @property\n def verbosity(self):\n return self.config.option.verbose\n\n @property\n def showheader(self):\n return self.verbosity >= 0\n\n @property\n def showfspath(self):\n if self._showfspath is None:\n return self.verbosity >= 0\n return self._showfspath\n\n @showfspath.setter\n def showfspath(self, value):\n self._showfspath = value\n\n @property\n def showlongtestinfo(self):\n return self.verbosity > 0\n\n def hasopt(self, char):\n char = {\"xfailed\": \"x\", \"skipped\": \"s\"}.get(char, char)\n return char in self.reportchars\n\n def write_fspath_result(self, nodeid, res, **markup):\n fspath = self.config.rootdir.join(nodeid.split(\"::\")[0])\n # NOTE: explicitly check for None to work around py bug, and for less\n # overhead in general (https://github.com/pytest-dev/py/pull/207).\n if self.currentfspath is None or fspath != self.currentfspath:\n if self.currentfspath is not None and self._show_progress_info:\n self._write_progress_information_filling_space()\n self.currentfspath = fspath\n fspath = self.startdir.bestrelpath(fspath)\n self._tw.line()\n self._tw.write(fspath + \" \")\n self._tw.write(res, **markup)\n\n def write_ensure_prefix(self, prefix, extra=\"\", **kwargs):\n if self.currentfspath != prefix:\n self._tw.line()\n self.currentfspath = prefix\n self._tw.write(prefix)\n if extra:\n self._tw.write(extra, **kwargs)\n self.currentfspath = -2\n\n def ensure_newline(self):\n if self.currentfspath:\n self._tw.line()\n self.currentfspath = None\n\n def write(self, content, **markup):\n self._tw.write(content, **markup)\n\n def write_line(self, line, **markup):\n if not isinstance(line, six.text_type):\n line = six.text_type(line, errors=\"replace\")\n self.ensure_newline()\n self._tw.line(line, **markup)\n\n def rewrite(self, line, **markup):\n \"\"\"\n Rewinds the terminal cursor to the beginning and writes the given line.\n\n :kwarg erase: if True, will also add spaces until the full terminal width to ensure\n previous lines are properly erased.\n\n The rest of the keyword arguments are markup instructions.\n \"\"\"\n erase = markup.pop(\"erase\", False)\n if erase:\n fill_count = self._tw.fullwidth - len(line) - 1\n fill = \" \" * fill_count\n else:\n fill = \"\"\n line = str(line)\n self._tw.write(\"\\r\" + line + fill, **markup)\n\n def write_sep(self, sep, title=None, **markup):\n self.ensure_newline()\n self._tw.sep(sep, title, **markup)\n\n def section(self, title, sep=\"=\", **kw):\n self._tw.sep(sep, title, **kw)\n\n def line(self, msg, **kw):\n self._tw.line(msg, **kw)\n\n def pytest_internalerror(self, excrepr):\n for line in six.text_type(excrepr).split(\"\\n\"):\n self.write_line(\"INTERNALERROR> \" + line)\n return 1\n\n def pytest_warning_captured(self, warning_message, item):\n # from _pytest.nodes import get_fslocation_from_item\n from _pytest.warnings import warning_record_to_str\n\n warnings = self.stats.setdefault(\"warnings\", [])\n fslocation = warning_message.filename, warning_message.lineno\n message = warning_record_to_str(warning_message)\n\n nodeid = item.nodeid if item is not None else \"\"\n warning_report = WarningReport(\n fslocation=fslocation, message=message, nodeid=nodeid\n )\n warnings.append(warning_report)\n\n def pytest_plugin_registered(self, plugin):\n if self.config.option.traceconfig:\n msg = \"PLUGIN registered: %s\" % (plugin,)\n # XXX this event may happen during setup/teardown time\n # which unfortunately captures our output here\n # which garbles our output if we use self.write_line\n self.write_line(msg)\n\n def pytest_deselected(self, items):\n self.stats.setdefault(\"deselected\", []).extend(items)\n\n def pytest_runtest_logstart(self, nodeid, location):\n # ensure that the path is printed before the\n # 1st test of a module starts running\n if self.showlongtestinfo:\n line = self._locationline(nodeid, *location)\n self.write_ensure_prefix(line, \"\")\n elif self.showfspath:\n fsid = nodeid.split(\"::\")[0]\n self.write_fspath_result(fsid, \"\")\n\n def pytest_runtest_logreport(self, report):\n self._tests_ran = True\n rep = report\n res = self.config.hook.pytest_report_teststatus(report=rep, config=self.config)\n category, letter, word = res\n if isinstance(word, tuple):\n word, markup = word\n else:\n markup = None\n self.stats.setdefault(category, []).append(rep)\n if not letter and not word:\n # probably passed setup/teardown\n return\n running_xdist = hasattr(rep, \"node\")\n if markup is None:\n was_xfail = hasattr(report, \"wasxfail\")\n if rep.passed and not was_xfail:\n markup = {\"green\": True}\n elif rep.passed and was_xfail:\n markup = {\"yellow\": True}\n elif rep.failed:\n markup = {\"red\": True}\n elif rep.skipped:\n markup = {\"yellow\": True}\n else:\n markup = {}\n if self.verbosity <= 0:\n if not running_xdist and self.showfspath:\n self.write_fspath_result(rep.nodeid, letter, **markup)\n else:\n self._tw.write(letter, **markup)\n else:\n self._progress_nodeids_reported.add(rep.nodeid)\n line = self._locationline(rep.nodeid, *rep.location)\n if not running_xdist:\n self.write_ensure_prefix(line, word, **markup)\n if self._show_progress_info:\n self._write_progress_information_filling_space()\n else:\n self.ensure_newline()\n self._tw.write(\"[%s]\" % rep.node.gateway.id)\n if self._show_progress_info:\n self._tw.write(\n self._get_progress_information_message() + \" \", cyan=True\n )\n else:\n self._tw.write(\" \")\n self._tw.write(word, **markup)\n self._tw.write(\" \" + line)\n self.currentfspath = -2\n\n def pytest_runtest_logfinish(self, nodeid):\n if self.verbosity <= 0 and self._show_progress_info:\n if self._show_progress_info == \"count\":\n num_tests = self._session.testscollected\n progress_length = len(\" [{}/{}]\".format(str(num_tests), str(num_tests)))\n else:\n progress_length = len(\" [100%]\")\n\n self._progress_nodeids_reported.add(nodeid)\n is_last_item = (\n len(self._progress_nodeids_reported) == self._session.testscollected\n )\n if is_last_item:\n self._write_progress_information_filling_space()\n else:\n w = self._width_of_current_line\n past_edge = w + progress_length + 1 >= self._screen_width\n if past_edge:\n msg = self._get_progress_information_message()\n self._tw.write(msg + \"\\n\", cyan=True)\n\n def _get_progress_information_message(self):\n collected = self._session.testscollected\n if self._show_progress_info == \"count\":\n if collected:\n progress = self._progress_nodeids_reported\n counter_format = \"{{:{}d}}\".format(len(str(collected)))\n format_string = \" [{}/{{}}]\".format(counter_format)\n return format_string.format(len(progress), collected)\n return \" [ {} / {} ]\".format(collected, collected)\n else:\n if collected:\n progress = len(self._progress_nodeids_reported) * 100 // collected\n return \" [{:3d}%]\".format(progress)\n return \" [100%]\"\n\n def _write_progress_information_filling_space(self):\n msg = self._get_progress_information_message()\n w = self._width_of_current_line\n fill = self._tw.fullwidth - w - 1\n self.write(msg.rjust(fill), cyan=True)\n\n @property\n def _width_of_current_line(self):\n \"\"\"Return the width of current line, using the superior implementation of py-1.6 when available\"\"\"\n try:\n return self._tw.width_of_current_line\n except AttributeError:\n # py < 1.6.0\n return self._tw.chars_on_current_line\n\n def pytest_collection(self):\n if self.isatty:\n if self.config.option.verbose >= 0:\n self.write(\"collecting ... \", bold=True)\n self._collect_report_last_write = time.time()\n elif self.config.option.verbose >= 1:\n self.write(\"collecting ... \", bold=True)\n\n def pytest_collectreport(self, report):\n if report.failed:\n self.stats.setdefault(\"error\", []).append(report)\n elif report.skipped:\n self.stats.setdefault(\"skipped\", []).append(report)\n items = [x for x in report.result if isinstance(x, pytest.Item)]\n self._numcollected += len(items)\n if self.isatty:\n self.report_collect()\n\n def report_collect(self, final=False):\n if self.config.option.verbose < 0:\n return\n\n if not final:\n # Only write \"collecting\" report every 0.5s.\n t = time.time()\n if (\n self._collect_report_last_write is not None\n and self._collect_report_last_write > t - REPORT_COLLECTING_RESOLUTION\n ):\n return\n self._collect_report_last_write = t\n\n errors = len(self.stats.get(\"error\", []))\n skipped = len(self.stats.get(\"skipped\", []))\n deselected = len(self.stats.get(\"deselected\", []))\n selected = self._numcollected - errors - skipped - deselected\n if final:\n line = \"collected \"\n else:\n line = \"collecting \"\n line += (\n str(self._numcollected) + \" item\" + (\"\" if self._numcollected == 1 else \"s\")\n )\n if errors:\n line += \" / %d errors\" % errors\n if deselected:\n line += \" / %d deselected\" % deselected\n if skipped:\n line += \" / %d skipped\" % skipped\n if self._numcollected > selected > 0:\n line += \" / %d selected\" % selected\n if self.isatty:\n self.rewrite(line, bold=True, erase=True)\n if final:\n self.write(\"\\n\")\n else:\n self.write_line(line)\n\n @pytest.hookimpl(trylast=True)\n def pytest_sessionstart(self, session):\n self._session = session\n self._sessionstarttime = time.time()\n if not self.showheader:\n return\n self.write_sep(\"=\", \"test session starts\", bold=True)\n verinfo = platform.python_version()\n msg = \"platform %s -- Python %s\" % (sys.platform, verinfo)\n if hasattr(sys, \"pypy_version_info\"):\n verinfo = \".\".join(map(str, sys.pypy_version_info[:3]))\n msg += \"[pypy-%s-%s]\" % (verinfo, sys.pypy_version_info[3])\n msg += \", pytest-%s, py-%s, pluggy-%s\" % (\n pytest.__version__,\n py.__version__,\n pluggy.__version__,\n )\n if (\n self.verbosity > 0\n or self.config.option.debug\n or getattr(self.config.option, \"pastebin\", None)\n ):\n msg += \" -- \" + str(sys.executable)\n self.write_line(msg)\n lines = self.config.hook.pytest_report_header(\n config=self.config, startdir=self.startdir\n )\n self._write_report_lines_from_hooks(lines)\n\n def _write_report_lines_from_hooks(self, lines):\n lines.reverse()\n for line in collapse(lines):\n self.write_line(line)\n\n def pytest_report_header(self, config):\n line = \"rootdir: %s\" % config.rootdir\n\n if config.inifile:\n line += \", inifile: \" + config.rootdir.bestrelpath(config.inifile)\n\n testpaths = config.getini(\"testpaths\")\n if testpaths and config.args == testpaths:\n rel_paths = [config.rootdir.bestrelpath(x) for x in testpaths]\n line += \", testpaths: {}\".format(\", \".join(rel_paths))\n result = [line]\n\n plugininfo = config.pluginmanager.list_plugin_distinfo()\n if plugininfo:\n result.append(\"plugins: %s\" % \", \".join(_plugin_nameversions(plugininfo)))\n return result\n\n def pytest_collection_finish(self, session):\n self.report_collect(True)\n\n if self.config.getoption(\"collectonly\"):\n self._printcollecteditems(session.items)\n\n lines = self.config.hook.pytest_report_collectionfinish(\n config=self.config, startdir=self.startdir, items=session.items\n )\n self._write_report_lines_from_hooks(lines)\n\n if self.config.getoption(\"collectonly\"):\n if self.stats.get(\"failed\"):\n self._tw.sep(\"!\", \"collection failures\")\n for rep in self.stats.get(\"failed\"):\n rep.toterminal(self._tw)\n\n def _printcollecteditems(self, items):\n # to print out items and their parent collectors\n # we take care to leave out Instances aka ()\n # because later versions are going to get rid of them anyway\n if self.config.option.verbose < 0:\n if self.config.option.verbose < -1:\n counts = {}\n for item in items:\n name = item.nodeid.split(\"::\", 1)[0]\n counts[name] = counts.get(name, 0) + 1\n for name, count in sorted(counts.items()):\n self._tw.line(\"%s: %d\" % (name, count))\n else:\n for item in items:\n self._tw.line(item.nodeid)\n return\n stack = []\n indent = \"\"\n for item in items:\n needed_collectors = item.listchain()[1:] # strip root node\n while stack:\n if stack == needed_collectors[: len(stack)]:\n break\n stack.pop()\n for col in needed_collectors[len(stack) :]:\n stack.append(col)\n if col.name == \"()\": # Skip Instances.\n continue\n indent = (len(stack) - 1) * \" \"\n self._tw.line(\"%s%s\" % (indent, col))\n if self.config.option.verbose >= 1:\n if hasattr(col, \"_obj\") and col._obj.__doc__:\n for line in col._obj.__doc__.strip().splitlines():\n self._tw.line(\"%s%s\" % (indent + \" \", line.strip()))\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_sessionfinish(self, exitstatus):\n outcome = yield\n outcome.get_result()\n self._tw.line(\"\")\n summary_exit_codes = (\n EXIT_OK,\n EXIT_TESTSFAILED,\n EXIT_INTERRUPTED,\n EXIT_USAGEERROR,\n EXIT_NOTESTSCOLLECTED,\n )\n if exitstatus in summary_exit_codes:\n self.config.hook.pytest_terminal_summary(\n terminalreporter=self, exitstatus=exitstatus, config=self.config\n )\n if exitstatus == EXIT_INTERRUPTED:\n self._report_keyboardinterrupt()\n del self._keyboardinterrupt_memo\n self.summary_stats()\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_terminal_summary(self):\n self.summary_errors()\n self.summary_failures()\n self.summary_warnings()\n self.summary_passes()\n yield\n self.short_test_summary()\n # Display any extra warnings from teardown here (if any).\n self.summary_warnings()\n\n def pytest_keyboard_interrupt(self, excinfo):\n self._keyboardinterrupt_memo = excinfo.getrepr(funcargs=True)\n\n def pytest_unconfigure(self):\n if hasattr(self, \"_keyboardinterrupt_memo\"):\n self._report_keyboardinterrupt()\n\n def _report_keyboardinterrupt(self):\n excrepr = self._keyboardinterrupt_memo\n msg = excrepr.reprcrash.message\n self.write_sep(\"!\", msg)\n if \"KeyboardInterrupt\" in msg:\n if self.config.option.fulltrace:\n excrepr.toterminal(self._tw)\n else:\n excrepr.reprcrash.toterminal(self._tw)\n self._tw.line(\n \"(to show a full traceback on KeyboardInterrupt use --fulltrace)\",\n yellow=True,\n )\n\n def _locationline(self, nodeid, fspath, lineno, domain):\n def mkrel(nodeid):\n line = self.config.cwd_relative_nodeid(nodeid)\n if domain and line.endswith(domain):\n line = line[: -len(domain)]\n values = domain.split(\"[\")\n values[0] = values[0].replace(\".\", \"::\") # don't replace '.' in params\n line += \"[\".join(values)\n return line\n\n # collect_fspath comes from testid which has a \"/\"-normalized path\n\n if fspath:\n res = mkrel(nodeid)\n if self.verbosity >= 2 and nodeid.split(\"::\")[0] != fspath.replace(\n \"\\\\\", nodes.SEP\n ):\n res += \" <- \" + self.startdir.bestrelpath(fspath)\n else:\n res = \"[location]\"\n return res + \" \"\n\n def _getfailureheadline(self, rep):\n head_line = rep.head_line\n if head_line:\n return head_line\n return \"test session\" # XXX?\n\n def _getcrashline(self, rep):\n try:\n return str(rep.longrepr.reprcrash)\n except AttributeError:\n try:\n return str(rep.longrepr)[:50]\n except AttributeError:\n return \"\"\n\n #\n # summaries for sessionfinish\n #\n def getreports(self, name):\n values = []\n for x in self.stats.get(name, []):\n if not hasattr(x, \"_pdbshown\"):\n values.append(x)\n return values\n\n def summary_warnings(self):\n if self.hasopt(\"w\"):\n all_warnings = self.stats.get(\"warnings\")\n if not all_warnings:\n return\n\n final = hasattr(self, \"_already_displayed_warnings\")\n if final:\n warning_reports = all_warnings[self._already_displayed_warnings :]\n else:\n warning_reports = all_warnings\n self._already_displayed_warnings = len(warning_reports)\n if not warning_reports:\n return\n\n reports_grouped_by_message = collections.OrderedDict()\n for wr in warning_reports:\n reports_grouped_by_message.setdefault(wr.message, []).append(wr)\n\n title = \"warnings summary (final)\" if final else \"warnings summary\"\n self.write_sep(\"=\", title, yellow=True, bold=False)\n for message, warning_reports in reports_grouped_by_message.items():\n has_any_location = False\n for w in warning_reports:\n location = w.get_location(self.config)\n if location:\n self._tw.line(str(location))\n has_any_location = True\n if has_any_location:\n lines = message.splitlines()\n indented = \"\\n\".join(\" \" + x for x in lines)\n message = indented.rstrip()\n else:\n message = message.rstrip()\n self._tw.line(message)\n self._tw.line()\n self._tw.line(\"-- Docs: https://docs.pytest.org/en/latest/warnings.html\")\n\n def summary_passes(self):\n if self.config.option.tbstyle != \"no\":\n if self.hasopt(\"P\"):\n reports = self.getreports(\"passed\")\n if not reports:\n return\n self.write_sep(\"=\", \"PASSES\")\n for rep in reports:\n if rep.sections:\n msg = self._getfailureheadline(rep)\n self.write_sep(\"_\", msg, green=True, bold=True)\n self._outrep_summary(rep)\n\n def print_teardown_sections(self, rep):\n showcapture = self.config.option.showcapture\n if showcapture == \"no\":\n return\n for secname, content in rep.sections:\n if showcapture != \"all\" and showcapture not in secname:\n continue\n if \"teardown\" in secname:\n self._tw.sep(\"-\", secname)\n if content[-1:] == \"\\n\":\n content = content[:-1]\n self._tw.line(content)\n\n def summary_failures(self):\n if self.config.option.tbstyle != \"no\":\n reports = self.getreports(\"failed\")\n if not reports:\n return\n self.write_sep(\"=\", \"FAILURES\")\n if self.config.option.tbstyle == \"line\":\n for rep in reports:\n line = self._getcrashline(rep)\n self.write_line(line)\n else:\n teardown_sections = {}\n for report in self.getreports(\"\"):\n if report.when == \"teardown\":\n teardown_sections.setdefault(report.nodeid, []).append(report)\n\n for rep in reports:\n msg = self._getfailureheadline(rep)\n self.write_sep(\"_\", msg, red=True, bold=True)\n self._outrep_summary(rep)\n for report in teardown_sections.get(rep.nodeid, []):\n self.print_teardown_sections(report)\n\n def summary_errors(self):\n if self.config.option.tbstyle != \"no\":\n reports = self.getreports(\"error\")\n if not reports:\n return\n self.write_sep(\"=\", \"ERRORS\")\n for rep in self.stats[\"error\"]:\n msg = self._getfailureheadline(rep)\n if rep.when == \"collect\":\n msg = \"ERROR collecting \" + msg\n else:\n msg = \"ERROR at %s of %s\" % (rep.when, msg)\n self.write_sep(\"_\", msg, red=True, bold=True)\n self._outrep_summary(rep)\n\n def _outrep_summary(self, rep):\n rep.toterminal(self._tw)\n showcapture = self.config.option.showcapture\n if showcapture == \"no\":\n return\n for secname, content in rep.sections:\n if showcapture != \"all\" and showcapture not in secname:\n continue\n self._tw.sep(\"-\", secname)\n if content[-1:] == \"\\n\":\n content = content[:-1]\n self._tw.line(content)\n\n def summary_stats(self):\n session_duration = time.time() - self._sessionstarttime\n (line, color) = build_summary_stats_line(self.stats)\n msg = \"%s in %.2f seconds\" % (line, session_duration)\n markup = {color: True, \"bold\": True}\n\n if self.verbosity >= 0:\n self.write_sep(\"=\", msg, **markup)\n if self.verbosity == -1:\n self.write_line(msg, **markup)\n\n def short_test_summary(self):\n if not self.reportchars:\n return\n\n def show_simple(stat, lines):\n failed = self.stats.get(stat, [])\n if not failed:\n return\n termwidth = self.writer.fullwidth\n config = self.config\n for rep in failed:\n line = _get_line_with_reprcrash_message(config, rep, termwidth)\n lines.append(line)\n\n def show_xfailed(lines):\n xfailed = self.stats.get(\"xfailed\", [])\n for rep in xfailed:\n verbose_word = rep._get_verbose_word(self.config)\n pos = _get_pos(self.config, rep)\n lines.append(\"%s %s\" % (verbose_word, pos))\n reason = rep.wasxfail\n if reason:\n lines.append(\" \" + str(reason))\n\n def show_xpassed(lines):\n xpassed = self.stats.get(\"xpassed\", [])\n for rep in xpassed:\n verbose_word = rep._get_verbose_word(self.config)\n pos = _get_pos(self.config, rep)\n reason = rep.wasxfail\n lines.append(\"%s %s %s\" % (verbose_word, pos, reason))\n\n def show_skipped(lines):\n skipped = self.stats.get(\"skipped\", [])\n fskips = _folded_skips(skipped) if skipped else []\n if not fskips:\n return\n verbose_word = skipped[0]._get_verbose_word(self.config)\n for num, fspath, lineno, reason in fskips:\n if reason.startswith(\"Skipped: \"):\n reason = reason[9:]\n if lineno is not None:\n lines.append(\n \"%s [%d] %s:%d: %s\"\n % (verbose_word, num, fspath, lineno + 1, reason)\n )\n else:\n lines.append(\"%s [%d] %s: %s\" % (verbose_word, num, fspath, reason))\n\n REPORTCHAR_ACTIONS = {\n \"x\": show_xfailed,\n \"X\": show_xpassed,\n \"f\": partial(show_simple, \"failed\"),\n \"F\": partial(show_simple, \"failed\"),\n \"s\": show_skipped,\n \"S\": show_skipped,\n \"p\": partial(show_simple, \"passed\"),\n \"E\": partial(show_simple, \"error\"),\n }\n\n lines = []\n for char in self.reportchars:\n action = REPORTCHAR_ACTIONS.get(char)\n if action: # skipping e.g. \"P\" (passed with output) here.\n action(lines)\n\n if lines:\n self.write_sep(\"=\", \"short test summary info\")\n for line in lines:\n self.write_line(line)"},{"col":4,"comment":"null","endLoc":251,"header":"def __init__(self, config, file=None)","id":4433,"name":"__init__","nodeType":"Function","startLoc":229,"text":"def __init__(self, config, file=None):\n import _pytest.config\n\n self.config = config\n self._numcollected = 0\n self._session = None\n self._showfspath = None\n\n self.stats = {}\n self.startdir = config.invocation_dir\n if file is None:\n file = sys.stdout\n self._tw = _pytest.config.create_terminal_writer(config, file)\n # self.writer will be deprecated in pytest-3.4\n self.writer = self._tw\n self._screen_width = self._tw.fullwidth\n self.currentfspath = None\n self.reportchars = getreportopt(config)\n self.hasmarkup = self._tw.hasmarkup\n self.isatty = file.isatty()\n self._progress_nodeids_reported = set()\n self._show_progress_info = self._determine_show_progress_info()\n self._collect_report_last_write = None"},{"col":0,"comment":"null","endLoc":177,"header":"def getreportopt(config)","id":4434,"name":"getreportopt","nodeType":"Function","startLoc":162,"text":"def getreportopt(config):\n reportopts = \"\"\n reportchars = config.option.reportchars\n if not config.option.disable_warnings and \"w\" not in reportchars:\n reportchars += \"w\"\n elif config.option.disable_warnings and \"w\" in reportchars:\n reportchars = reportchars.replace(\"w\", \"\")\n for char in reportchars:\n if char == \"a\":\n reportopts = \"sxXwEf\"\n elif char == \"A\":\n reportopts = \"PpsxXwEf\"\n break\n elif char not in reportopts:\n reportopts += char\n return reportopts"},{"col":4,"comment":"\n Ensure we avoid calling imp.find_module when we know for sure a certain module will not be rewritten\n to optimize assertion rewriting (#3918).\n ","endLoc":1350,"header":"def test_basic(self, testdir, hook)","id":4435,"name":"test_basic","nodeType":"Function","startLoc":1319,"text":"def test_basic(self, testdir, hook):\n \"\"\"\n Ensure we avoid calling imp.find_module when we know for sure a certain module will not be rewritten\n to optimize assertion rewriting (#3918).\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.fixture\n def fix(): return 1\n \"\"\"\n )\n testdir.makepyfile(test_foo=\"def test_foo(): pass\")\n testdir.makepyfile(bar=\"def bar(): pass\")\n foobar_path = testdir.makepyfile(foobar=\"def foobar(): pass\")\n self.initial_paths.add(foobar_path)\n\n # conftest files should always be rewritten\n assert hook.find_module(\"conftest\") is not None\n assert self.find_module_calls == [\"conftest\"]\n\n # files matching \"python_files\" mask should always be rewritten\n assert hook.find_module(\"test_foo\") is not None\n assert self.find_module_calls == [\"conftest\", \"test_foo\"]\n\n # file does not match \"python_files\": early bailout\n assert hook.find_module(\"bar\") is None\n assert self.find_module_calls == [\"conftest\", \"test_foo\"]\n\n # file is an initial path (passed on the command-line): should be rewritten\n assert hook.find_module(\"foobar\") is not None\n assert self.find_module_calls == [\"conftest\", \"test_foo\", \"foobar\"]"},{"col":0,"comment":"Test that debugging's pytest_configure is re-entrant.","endLoc":1088,"header":"def test_quit_with_swallowed_SystemExit(testdir)","id":4436,"name":"test_quit_with_swallowed_SystemExit","nodeType":"Function","startLoc":1063,"text":"def test_quit_with_swallowed_SystemExit(testdir):\n \"\"\"Test that debugging's pytest_configure is re-entrant.\"\"\"\n p1 = testdir.makepyfile(\n \"\"\"\n def call_pdb_set_trace():\n __import__('pdb').set_trace()\n\n\n def test_1():\n try:\n call_pdb_set_trace()\n except SystemExit:\n pass\n\n\n def test_2():\n pass\n \"\"\"\n )\n child = testdir.spawn_pytest(str(p1))\n child.expect(\"Pdb\")\n child.sendline(\"q\")\n child.expect_exact(\"Exit: Quitting debugger\")\n rest = child.read().decode(\"utf8\")\n assert \"no tests ran\" in rest\n TestPDB.flush(child)"},{"col":0,"comment":"null","endLoc":69,"header":"def pytest_sessionstart(session)","id":4437,"name":"pytest_sessionstart","nodeType":"Function","startLoc":68,"text":"def pytest_sessionstart(session):\n session._setupstate = SetupState()"},{"col":0,"comment":"null","endLoc":73,"header":"def pytest_sessionfinish(session)","id":4438,"name":"pytest_sessionfinish","nodeType":"Function","startLoc":72,"text":"def pytest_sessionfinish(session):\n session._setupstate.teardown_all()"},{"col":0,"comment":"null","endLoc":80,"header":"def pytest_runtest_protocol(item, nextitem)","id":4440,"name":"pytest_runtest_protocol","nodeType":"Function","startLoc":76,"text":"def pytest_runtest_protocol(item, nextitem):\n item.ihook.pytest_runtest_logstart(nodeid=item.nodeid, location=item.location)\n runtestprotocol(item, nextitem=nextitem)\n item.ihook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location)\n return True"},{"col":4,"comment":"null","endLoc":674,"header":"@pytest.mark.parametrize(\"quiet\", [True, False])\n @pytest.mark.parametrize(\"opt\", [\"--ff\", \"--lf\"])\n def test_lf_and_ff_prints_no_needless_message(self, quiet, opt, testdir)","id":4441,"name":"test_lf_and_ff_prints_no_needless_message","nodeType":"Function","startLoc":659,"text":"@pytest.mark.parametrize(\"quiet\", [True, False])\n @pytest.mark.parametrize(\"opt\", [\"--ff\", \"--lf\"])\n def test_lf_and_ff_prints_no_needless_message(self, quiet, opt, testdir):\n # Issue 3853\n testdir.makepyfile(\"def test(): assert 0\")\n args = [opt]\n if quiet:\n args.append(\"-q\")\n result = testdir.runpytest(*args)\n assert \"run all\" not in result.stdout.str()\n\n result = testdir.runpytest(*args)\n if quiet:\n assert \"run all\" not in result.stdout.str()\n else:\n assert \"rerun previous\" in result.stdout.str()"},{"col":4,"comment":"null","endLoc":88,"header":"def test_teardown_multiple_fail(self, testdir)","id":4442,"name":"test_teardown_multiple_fail","nodeType":"Function","startLoc":73,"text":"def test_teardown_multiple_fail(self, testdir):\n # Ensure the first exception is the one which is re-raised.\n # Ideally both would be reported however.\n def fin1():\n raise Exception(\"oops1\")\n\n def fin2():\n raise Exception(\"oops2\")\n\n item = testdir.getitem(\"def test_func(): pass\")\n ss = runner.SetupState()\n ss.addfinalizer(fin1, item)\n ss.addfinalizer(fin2, item)\n with pytest.raises(Exception) as err:\n ss._callfinalizers(item)\n assert err.value.args == (\"oops2\",)"},{"col":0,"comment":"Using \"-s\" with pytest should suspend/resume fixture capturing.","endLoc":1137,"header":"@pytest.mark.parametrize(\"fixture\", (\"capfd\", \"capsys\"))\ndef test_pdb_suspends_fixture_capturing(testdir, fixture)","id":4443,"name":"test_pdb_suspends_fixture_capturing","nodeType":"Function","startLoc":1091,"text":"@pytest.mark.parametrize(\"fixture\", (\"capfd\", \"capsys\"))\ndef test_pdb_suspends_fixture_capturing(testdir, fixture):\n \"\"\"Using \"-s\" with pytest should suspend/resume fixture capturing.\"\"\"\n p1 = testdir.makepyfile(\n \"\"\"\n def test_inner({fixture}):\n import sys\n\n print(\"out_inner_before\")\n sys.stderr.write(\"err_inner_before\\\\n\")\n\n __import__(\"pdb\").set_trace()\n\n print(\"out_inner_after\")\n sys.stderr.write(\"err_inner_after\\\\n\")\n\n out, err = {fixture}.readouterr()\n assert out ==\"out_inner_before\\\\nout_inner_after\\\\n\"\n assert err ==\"err_inner_before\\\\nerr_inner_after\\\\n\"\n \"\"\".format(\n fixture=fixture\n )\n )\n\n child = testdir.spawn_pytest(str(p1) + \" -s\")\n\n child.expect(\"Pdb\")\n before = child.before.decode(\"utf8\")\n assert (\n \"> PDB set_trace (IO-capturing turned off for fixture %s) >\" % (fixture)\n in before\n )\n\n # Test that capturing is really suspended.\n child.sendline(\"p 40 + 2\")\n child.expect(\"Pdb\")\n assert \"\\r\\n42\\r\\n\" in child.before.decode(\"utf8\")\n\n child.sendline(\"c\")\n rest = child.read().decode(\"utf8\")\n assert \"out_inner\" not in rest\n assert \"err_inner\" not in rest\n\n TestPDB.flush(child)\n assert child.exitstatus == 0\n assert \"= 1 passed in \" in rest\n assert \"> PDB continue (IO-capturing resumed for fixture %s) >\" % (fixture) in rest"},{"col":4,"comment":"null","endLoc":57,"header":"def find_nth_by_tag(self, tag, n)","id":4444,"name":"find_nth_by_tag","nodeType":"Function","startLoc":50,"text":"def find_nth_by_tag(self, tag, n):\n items = self._by_tag(tag)\n try:\n nth = items[n]\n except IndexError:\n pass\n else:\n return type(self)(nth)"},{"col":4,"comment":"null","endLoc":48,"header":"def _by_tag(self, tag)","id":4445,"name":"_by_tag","nodeType":"Function","startLoc":47,"text":"def _by_tag(self, tag):\n return self.__node.getElementsByTagName(tag)"},{"col":4,"comment":"null","endLoc":61,"header":"def find_by_tag(self, tag)","id":4446,"name":"find_by_tag","nodeType":"Function","startLoc":59,"text":"def find_by_tag(self, tag):\n t = type(self)\n return [t(x) for x in self.__node.getElementsByTagName(tag)]"},{"col":0,"comment":"null","endLoc":100,"header":"def runtestprotocol(item, log=True, nextitem=None)","id":4447,"name":"runtestprotocol","nodeType":"Function","startLoc":83,"text":"def runtestprotocol(item, log=True, nextitem=None):\n hasrequest = hasattr(item, \"_request\")\n if hasrequest and not item._request:\n item._initrequest()\n rep = call_and_report(item, \"setup\", log)\n reports = [rep]\n if rep.passed:\n if item.config.getoption(\"setupshow\", False):\n show_test_item(item)\n if not item.config.getoption(\"setuponly\", False):\n reports.append(call_and_report(item, \"call\", log))\n reports.append(call_and_report(item, \"teardown\", log, nextitem=nextitem))\n # after all teardown hooks have been called\n # want funcargs and request info to go away\n if hasrequest:\n item._request = False\n item.funcargs = None\n return reports"},{"col":4,"comment":"null","endLoc":106,"header":"def test_teardown_multiple_scopes_one_fails(self, testdir)","id":4448,"name":"test_teardown_multiple_scopes_one_fails","nodeType":"Function","startLoc":90,"text":"def test_teardown_multiple_scopes_one_fails(self, testdir):\n module_teardown = []\n\n def fin_func():\n raise Exception(\"oops1\")\n\n def fin_module():\n module_teardown.append(\"fin_module\")\n\n item = testdir.getitem(\"def test_func(): pass\")\n ss = runner.SetupState()\n ss.addfinalizer(fin_module, item.listchain()[-2])\n ss.addfinalizer(fin_func, item)\n ss.prepare(item)\n with pytest.raises(Exception, match=\"oops1\"):\n ss.teardown_exact(item, None)\n assert module_teardown"},{"col":4,"comment":"If one of the python_files patterns contain subdirectories (\"tests/**.py\") we can't bailout early\n because we need to match with the full path, which can only be found by calling imp.find_module.\n ","endLoc":1367,"header":"def test_pattern_contains_subdirectories(self, testdir, hook)","id":4449,"name":"test_pattern_contains_subdirectories","nodeType":"Function","startLoc":1352,"text":"def test_pattern_contains_subdirectories(self, testdir, hook):\n \"\"\"If one of the python_files patterns contain subdirectories (\"tests/**.py\") we can't bailout early\n because we need to match with the full path, which can only be found by calling imp.find_module.\n \"\"\"\n p = testdir.makepyfile(\n **{\n \"tests/file.py\": \"\"\"\n def test_simple_failure():\n assert 1 + 1 == 3\n \"\"\"\n }\n )\n testdir.syspathinsert(p.dirpath())\n hook.fnpats[:] = [\"tests/**.py\"]\n assert hook.find_module(\"file\") is not None\n assert self.find_module_calls == [\"file\"]"},{"col":4,"comment":"null","endLoc":66,"header":"def __getitem__(self, key)","id":4450,"name":"__getitem__","nodeType":"Function","startLoc":63,"text":"def __getitem__(self, key):\n node = self.__node.getAttributeNode(key)\n if node is not None:\n return node.value"},{"col":4,"comment":"null","endLoc":70,"header":"def assert_attr(self, **kwargs)","id":4451,"name":"assert_attr","nodeType":"Function","startLoc":68,"text":"def assert_attr(self, **kwargs):\n __tracebackhide__ = True\n return assert_attr(self.__node, **kwargs)"},{"col":4,"comment":"null","endLoc":1397,"header":"@pytest.mark.skipif(\n sys.platform.startswith(\"win32\"), reason=\"cannot remove cwd on Windows\"\n )\n def test_cwd_changed(self, testdir, monkeypatch)","id":4452,"name":"test_cwd_changed","nodeType":"Function","startLoc":1369,"text":"@pytest.mark.skipif(\n sys.platform.startswith(\"win32\"), reason=\"cannot remove cwd on Windows\"\n )\n def test_cwd_changed(self, testdir, monkeypatch):\n # Setup conditions for py's fspath trying to import pathlib on py34\n # always (previously triggered via xdist only).\n # Ref: https://github.com/pytest-dev/py/pull/207\n monkeypatch.syspath_prepend(\"\")\n monkeypatch.delitem(sys.modules, \"pathlib\", raising=False)\n\n testdir.makepyfile(\n **{\n \"test_setup_nonexisting_cwd.py\": \"\"\"\n import os\n import shutil\n import tempfile\n\n d = tempfile.mkdtemp()\n os.chdir(d)\n shutil.rmtree(d)\n \"\"\",\n \"test_test.py\": \"\"\"\n def test():\n pass\n \"\"\",\n }\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 passed in *\"])"},{"col":0,"comment":"null","endLoc":34,"header":"def assert_attr(node, **kwargs)","id":4453,"name":"assert_attr","nodeType":"Function","startLoc":24,"text":"def assert_attr(node, **kwargs):\n __tracebackhide__ = True\n\n def nodeval(node, name):\n anode = node.getAttributeNode(name)\n if anode is not None:\n return anode.value\n\n expected = {name: str(value) for name, value in kwargs.items()}\n on_node = {name: nodeval(node, name) for name in expected}\n assert on_node == expected"},{"attributeType":"set","col":8,"comment":"null","endLoc":1299,"id":4454,"name":"initial_paths","nodeType":"Attribute","startLoc":1299,"text":"self.initial_paths"},{"attributeType":"list","col":8,"comment":"null","endLoc":1298,"id":4455,"name":"find_module_calls","nodeType":"Attribute","startLoc":1298,"text":"self.find_module_calls"},{"col":0,"comment":"null","endLoc":33,"header":"def setup_module(mod)","id":4456,"name":"setup_module","nodeType":"Function","startLoc":31,"text":"def setup_module(mod):\n mod._old_reprcompare = util._reprcompare\n _pytest._code._reprcompare = None"},{"col":0,"comment":"null","endLoc":38,"header":"def teardown_module(mod)","id":4457,"name":"teardown_module","nodeType":"Function","startLoc":36,"text":"def teardown_module(mod):\n util._reprcompare = mod._old_reprcompare\n del mod._old_reprcompare"},{"col":0,"comment":"null","endLoc":1180,"header":"def test_issue731(testdir)","id":4458,"name":"test_issue731","nodeType":"Function","startLoc":1164,"text":"def test_issue731(testdir):\n testdir.makepyfile(\n \"\"\"\n class LongReprWithBraces(object):\n def __repr__(self):\n return 'LongReprWithBraces({' + ('a' * 80) + '}' + ('a' * 120) + ')'\n\n def some_method(self):\n return False\n\n def test_long_repr():\n obj = LongReprWithBraces()\n assert obj.some_method()\n \"\"\"\n )\n result = testdir.runpytest()\n assert \"unbalanced braces\" not in result.stdout.str()"},{"fileName":"monkeypatch.py","filePath":"src/_pytest","id":4459,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\" monkeypatching and mocking functionality. \"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport re\nimport sys\nimport warnings\nfrom contextlib import contextmanager\n\nimport six\n\nimport pytest\nfrom _pytest.fixtures import fixture\nfrom _pytest.pathlib import Path\n\nRE_IMPORT_ERROR_NAME = re.compile(r\"^No module named (.*)$\")\n\n\n@fixture\ndef monkeypatch():\n \"\"\"The returned ``monkeypatch`` fixture provides these\n helper methods to modify objects, dictionaries or os.environ::\n\n monkeypatch.setattr(obj, name, value, raising=True)\n monkeypatch.delattr(obj, name, raising=True)\n monkeypatch.setitem(mapping, name, value)\n monkeypatch.delitem(obj, name, raising=True)\n monkeypatch.setenv(name, value, prepend=False)\n monkeypatch.delenv(name, raising=True)\n monkeypatch.syspath_prepend(path)\n monkeypatch.chdir(path)\n\n All modifications will be undone after the requesting\n test function or fixture has finished. The ``raising``\n parameter determines if a KeyError or AttributeError\n will be raised if the set/deletion operation has no target.\n \"\"\"\n mpatch = MonkeyPatch()\n yield mpatch\n mpatch.undo()\n\n\ndef resolve(name):\n # simplified from zope.dottedname\n parts = name.split(\".\")\n\n used = parts.pop(0)\n found = __import__(used)\n for part in parts:\n used += \".\" + part\n try:\n found = getattr(found, part)\n except AttributeError:\n pass\n else:\n continue\n # we use explicit un-nesting of the handling block in order\n # to avoid nested exceptions on python 3\n try:\n __import__(used)\n except ImportError as ex:\n # str is used for py2 vs py3\n expected = str(ex).split()[-1]\n if expected == used:\n raise\n else:\n raise ImportError(\"import error in %s: %s\" % (used, ex))\n found = annotated_getattr(found, part, used)\n return found\n\n\ndef annotated_getattr(obj, name, ann):\n try:\n obj = getattr(obj, name)\n except AttributeError:\n raise AttributeError(\n \"%r object at %s has no attribute %r\" % (type(obj).__name__, ann, name)\n )\n return obj\n\n\ndef derive_importpath(import_path, raising):\n if not isinstance(import_path, six.string_types) or \".\" not in import_path:\n raise TypeError(\"must be absolute import path string, not %r\" % (import_path,))\n module, attr = import_path.rsplit(\".\", 1)\n target = resolve(module)\n if raising:\n annotated_getattr(target, attr, ann=module)\n return attr, target\n\n\nclass Notset(object):\n def __repr__(self):\n return \"\"\n\n\nnotset = Notset()\n\n\nclass MonkeyPatch(object):\n \"\"\" Object returned by the ``monkeypatch`` fixture keeping a record of setattr/item/env/syspath changes.\n \"\"\"\n\n def __init__(self):\n self._setattr = []\n self._setitem = []\n self._cwd = None\n self._savesyspath = None\n\n @contextmanager\n def context(self):\n \"\"\"\n Context manager that returns a new :class:`MonkeyPatch` object which\n undoes any patching done inside the ``with`` block upon exit:\n\n .. code-block:: python\n\n import functools\n def test_partial(monkeypatch):\n with monkeypatch.context() as m:\n m.setattr(functools, \"partial\", 3)\n\n Useful in situations where it is desired to undo some patches before the test ends,\n such as mocking ``stdlib`` functions that might break pytest itself if mocked (for examples\n of this see `#3290 `_.\n \"\"\"\n m = MonkeyPatch()\n try:\n yield m\n finally:\n m.undo()\n\n def setattr(self, target, name, value=notset, raising=True):\n \"\"\" Set attribute value on target, memorizing the old value.\n By default raise AttributeError if the attribute did not exist.\n\n For convenience you can specify a string as ``target`` which\n will be interpreted as a dotted import path, with the last part\n being the attribute name. Example:\n ``monkeypatch.setattr(\"os.getcwd\", lambda: \"/\")``\n would set the ``getcwd`` function of the ``os`` module.\n\n The ``raising`` value determines if the setattr should fail\n if the attribute is not already present (defaults to True\n which means it will raise).\n \"\"\"\n __tracebackhide__ = True\n import inspect\n\n if value is notset:\n if not isinstance(target, six.string_types):\n raise TypeError(\n \"use setattr(target, name, value) or \"\n \"setattr(target, value) with target being a dotted \"\n \"import string\"\n )\n value = name\n name, target = derive_importpath(target, raising)\n\n oldval = getattr(target, name, notset)\n if raising and oldval is notset:\n raise AttributeError(\"%r has no attribute %r\" % (target, name))\n\n # avoid class descriptors like staticmethod/classmethod\n if inspect.isclass(target):\n oldval = target.__dict__.get(name, notset)\n self._setattr.append((target, name, oldval))\n setattr(target, name, value)\n\n def delattr(self, target, name=notset, raising=True):\n \"\"\" Delete attribute ``name`` from ``target``, by default raise\n AttributeError it the attribute did not previously exist.\n\n If no ``name`` is specified and ``target`` is a string\n it will be interpreted as a dotted import path with the\n last part being the attribute name.\n\n If ``raising`` is set to False, no exception will be raised if the\n attribute is missing.\n \"\"\"\n __tracebackhide__ = True\n import inspect\n\n if name is notset:\n if not isinstance(target, six.string_types):\n raise TypeError(\n \"use delattr(target, name) or \"\n \"delattr(target) with target being a dotted \"\n \"import string\"\n )\n name, target = derive_importpath(target, raising)\n\n if not hasattr(target, name):\n if raising:\n raise AttributeError(name)\n else:\n oldval = getattr(target, name, notset)\n # Avoid class descriptors like staticmethod/classmethod.\n if inspect.isclass(target):\n oldval = target.__dict__.get(name, notset)\n self._setattr.append((target, name, oldval))\n delattr(target, name)\n\n def setitem(self, dic, name, value):\n \"\"\" Set dictionary entry ``name`` to value. \"\"\"\n self._setitem.append((dic, name, dic.get(name, notset)))\n dic[name] = value\n\n def delitem(self, dic, name, raising=True):\n \"\"\" Delete ``name`` from dict. Raise KeyError if it doesn't exist.\n\n If ``raising`` is set to False, no exception will be raised if the\n key is missing.\n \"\"\"\n if name not in dic:\n if raising:\n raise KeyError(name)\n else:\n self._setitem.append((dic, name, dic.get(name, notset)))\n del dic[name]\n\n def _warn_if_env_name_is_not_str(self, name):\n \"\"\"On Python 2, warn if the given environment variable name is not a native str (#4056)\"\"\"\n if six.PY2 and not isinstance(name, str):\n warnings.warn(\n pytest.PytestWarning(\n \"Environment variable name {!r} should be str\".format(name)\n )\n )\n\n def setenv(self, name, value, prepend=None):\n \"\"\" Set environment variable ``name`` to ``value``. If ``prepend``\n is a character, read the current environment variable value\n and prepend the ``value`` adjoined with the ``prepend`` character.\"\"\"\n if not isinstance(value, str):\n warnings.warn(\n pytest.PytestWarning(\n \"Value of environment variable {name} type should be str, but got \"\n \"{value!r} (type: {type}); converted to str implicitly\".format(\n name=name, value=value, type=type(value).__name__\n )\n ),\n stacklevel=2,\n )\n value = str(value)\n if prepend and name in os.environ:\n value = value + prepend + os.environ[name]\n self._warn_if_env_name_is_not_str(name)\n self.setitem(os.environ, name, value)\n\n def delenv(self, name, raising=True):\n \"\"\" Delete ``name`` from the environment. Raise KeyError if it does\n not exist.\n\n If ``raising`` is set to False, no exception will be raised if the\n environment variable is missing.\n \"\"\"\n self._warn_if_env_name_is_not_str(name)\n self.delitem(os.environ, name, raising=raising)\n\n def syspath_prepend(self, path):\n \"\"\" Prepend ``path`` to ``sys.path`` list of import locations. \"\"\"\n from pkg_resources import fixup_namespace_packages\n\n if self._savesyspath is None:\n self._savesyspath = sys.path[:]\n sys.path.insert(0, str(path))\n\n # https://github.com/pypa/setuptools/blob/d8b901bc/docs/pkg_resources.txt#L162-L171\n fixup_namespace_packages(str(path))\n\n # A call to syspathinsert() usually means that the caller wants to\n # import some dynamically created files, thus with python3 we\n # invalidate its import caches.\n # This is especially important when any namespace package is in used,\n # since then the mtime based FileFinder cache (that gets created in\n # this case already) gets not invalidated when writing the new files\n # quickly afterwards.\n if sys.version_info >= (3, 3):\n from importlib import invalidate_caches\n\n invalidate_caches()\n\n def chdir(self, path):\n \"\"\" Change the current working directory to the specified path.\n Path can be a string or a py.path.local object.\n \"\"\"\n if self._cwd is None:\n self._cwd = os.getcwd()\n if hasattr(path, \"chdir\"):\n path.chdir()\n elif isinstance(path, Path):\n # modern python uses the fspath protocol here LEGACY\n os.chdir(str(path))\n else:\n os.chdir(path)\n\n def undo(self):\n \"\"\" Undo previous changes. This call consumes the\n undo stack. Calling it a second time has no effect unless\n you do more monkeypatching after the undo call.\n\n There is generally no need to call `undo()`, since it is\n called automatically during tear-down.\n\n Note that the same `monkeypatch` fixture is used across a\n single test function invocation. If `monkeypatch` is used both by\n the test function itself and one of the test fixtures,\n calling `undo()` will undo all of the changes made in\n both functions.\n \"\"\"\n for obj, name, value in reversed(self._setattr):\n if value is not notset:\n setattr(obj, name, value)\n else:\n delattr(obj, name)\n self._setattr[:] = []\n for dictionary, name, value in reversed(self._setitem):\n if value is notset:\n try:\n del dictionary[name]\n except KeyError:\n pass # was already deleted, so we have the desired state\n else:\n dictionary[name] = value\n self._setitem[:] = []\n if self._savesyspath is not None:\n sys.path[:] = self._savesyspath\n self._savesyspath = None\n\n if self._cwd is not None:\n os.chdir(self._cwd)\n self._cwd = None\n"},{"col":4,"comment":"Return True if we should display progress information based on the current config","endLoc":264,"header":"def _determine_show_progress_info(self)","id":4460,"name":"_determine_show_progress_info","nodeType":"Function","startLoc":253,"text":"def _determine_show_progress_info(self):\n \"\"\"Return True if we should display progress information based on the current config\"\"\"\n # do not show progress if we are not capturing output (#3038)\n if self.config.getoption(\"capture\", \"no\") == \"no\":\n return False\n # do not show progress if we are showing fixture setup/teardown\n if self.config.getoption(\"setupshow\", False):\n return False\n cfg = self.config.getini(\"console_output_style\")\n if cfg in (\"progress\", \"count\"):\n return cfg\n return False"},{"col":4,"comment":"null","endLoc":268,"header":"@property\n def verbosity(self)","id":4461,"name":"verbosity","nodeType":"Function","startLoc":266,"text":"@property\n def verbosity(self):\n return self.config.option.verbose"},{"col":4,"comment":"null","endLoc":272,"header":"@property\n def showheader(self)","id":4462,"name":"showheader","nodeType":"Function","startLoc":270,"text":"@property\n def showheader(self):\n return self.verbosity >= 0"},{"col":4,"comment":"null","endLoc":278,"header":"@property\n def showfspath(self)","id":4463,"name":"showfspath","nodeType":"Function","startLoc":274,"text":"@property\n def showfspath(self):\n if self._showfspath is None:\n return self.verbosity >= 0\n return self._showfspath"},{"col":4,"comment":"null","endLoc":282,"header":"@showfspath.setter\n def showfspath(self, value)","id":4464,"name":"showfspath","nodeType":"Function","startLoc":280,"text":"@showfspath.setter\n def showfspath(self, value):\n self._showfspath = value"},{"col":4,"comment":"null","endLoc":286,"header":"@property\n def showlongtestinfo(self)","id":4465,"name":"showlongtestinfo","nodeType":"Function","startLoc":284,"text":"@property\n def showlongtestinfo(self):\n return self.verbosity > 0"},{"col":4,"comment":"null","endLoc":290,"header":"def hasopt(self, char)","id":4466,"name":"hasopt","nodeType":"Function","startLoc":288,"text":"def hasopt(self, char):\n char = {\"xfailed\": \"x\", \"skipped\": \"s\"}.get(char, char)\n return char in self.reportchars"},{"col":0,"comment":"Support modification dates after 2038 in rewritten files (#4903).\n\n pytest would crash with:\n\n fp.write(struct.pack(\"\""},{"col":4,"comment":"null","endLoc":97,"header":"def __repr__(self)","id":4473,"name":"__repr__","nodeType":"Function","startLoc":96,"text":"def __repr__(self):\n return \"\""},{"className":"MonkeyPatch","col":0,"comment":" Object returned by the ``monkeypatch`` fixture keeping a record of setattr/item/env/syspath changes.\n ","endLoc":336,"id":4474,"nodeType":"Class","startLoc":103,"text":"class MonkeyPatch(object):\n \"\"\" Object returned by the ``monkeypatch`` fixture keeping a record of setattr/item/env/syspath changes.\n \"\"\"\n\n def __init__(self):\n self._setattr = []\n self._setitem = []\n self._cwd = None\n self._savesyspath = None\n\n @contextmanager\n def context(self):\n \"\"\"\n Context manager that returns a new :class:`MonkeyPatch` object which\n undoes any patching done inside the ``with`` block upon exit:\n\n .. code-block:: python\n\n import functools\n def test_partial(monkeypatch):\n with monkeypatch.context() as m:\n m.setattr(functools, \"partial\", 3)\n\n Useful in situations where it is desired to undo some patches before the test ends,\n such as mocking ``stdlib`` functions that might break pytest itself if mocked (for examples\n of this see `#3290 `_.\n \"\"\"\n m = MonkeyPatch()\n try:\n yield m\n finally:\n m.undo()\n\n def setattr(self, target, name, value=notset, raising=True):\n \"\"\" Set attribute value on target, memorizing the old value.\n By default raise AttributeError if the attribute did not exist.\n\n For convenience you can specify a string as ``target`` which\n will be interpreted as a dotted import path, with the last part\n being the attribute name. Example:\n ``monkeypatch.setattr(\"os.getcwd\", lambda: \"/\")``\n would set the ``getcwd`` function of the ``os`` module.\n\n The ``raising`` value determines if the setattr should fail\n if the attribute is not already present (defaults to True\n which means it will raise).\n \"\"\"\n __tracebackhide__ = True\n import inspect\n\n if value is notset:\n if not isinstance(target, six.string_types):\n raise TypeError(\n \"use setattr(target, name, value) or \"\n \"setattr(target, value) with target being a dotted \"\n \"import string\"\n )\n value = name\n name, target = derive_importpath(target, raising)\n\n oldval = getattr(target, name, notset)\n if raising and oldval is notset:\n raise AttributeError(\"%r has no attribute %r\" % (target, name))\n\n # avoid class descriptors like staticmethod/classmethod\n if inspect.isclass(target):\n oldval = target.__dict__.get(name, notset)\n self._setattr.append((target, name, oldval))\n setattr(target, name, value)\n\n def delattr(self, target, name=notset, raising=True):\n \"\"\" Delete attribute ``name`` from ``target``, by default raise\n AttributeError it the attribute did not previously exist.\n\n If no ``name`` is specified and ``target`` is a string\n it will be interpreted as a dotted import path with the\n last part being the attribute name.\n\n If ``raising`` is set to False, no exception will be raised if the\n attribute is missing.\n \"\"\"\n __tracebackhide__ = True\n import inspect\n\n if name is notset:\n if not isinstance(target, six.string_types):\n raise TypeError(\n \"use delattr(target, name) or \"\n \"delattr(target) with target being a dotted \"\n \"import string\"\n )\n name, target = derive_importpath(target, raising)\n\n if not hasattr(target, name):\n if raising:\n raise AttributeError(name)\n else:\n oldval = getattr(target, name, notset)\n # Avoid class descriptors like staticmethod/classmethod.\n if inspect.isclass(target):\n oldval = target.__dict__.get(name, notset)\n self._setattr.append((target, name, oldval))\n delattr(target, name)\n\n def setitem(self, dic, name, value):\n \"\"\" Set dictionary entry ``name`` to value. \"\"\"\n self._setitem.append((dic, name, dic.get(name, notset)))\n dic[name] = value\n\n def delitem(self, dic, name, raising=True):\n \"\"\" Delete ``name`` from dict. Raise KeyError if it doesn't exist.\n\n If ``raising`` is set to False, no exception will be raised if the\n key is missing.\n \"\"\"\n if name not in dic:\n if raising:\n raise KeyError(name)\n else:\n self._setitem.append((dic, name, dic.get(name, notset)))\n del dic[name]\n\n def _warn_if_env_name_is_not_str(self, name):\n \"\"\"On Python 2, warn if the given environment variable name is not a native str (#4056)\"\"\"\n if six.PY2 and not isinstance(name, str):\n warnings.warn(\n pytest.PytestWarning(\n \"Environment variable name {!r} should be str\".format(name)\n )\n )\n\n def setenv(self, name, value, prepend=None):\n \"\"\" Set environment variable ``name`` to ``value``. If ``prepend``\n is a character, read the current environment variable value\n and prepend the ``value`` adjoined with the ``prepend`` character.\"\"\"\n if not isinstance(value, str):\n warnings.warn(\n pytest.PytestWarning(\n \"Value of environment variable {name} type should be str, but got \"\n \"{value!r} (type: {type}); converted to str implicitly\".format(\n name=name, value=value, type=type(value).__name__\n )\n ),\n stacklevel=2,\n )\n value = str(value)\n if prepend and name in os.environ:\n value = value + prepend + os.environ[name]\n self._warn_if_env_name_is_not_str(name)\n self.setitem(os.environ, name, value)\n\n def delenv(self, name, raising=True):\n \"\"\" Delete ``name`` from the environment. Raise KeyError if it does\n not exist.\n\n If ``raising`` is set to False, no exception will be raised if the\n environment variable is missing.\n \"\"\"\n self._warn_if_env_name_is_not_str(name)\n self.delitem(os.environ, name, raising=raising)\n\n def syspath_prepend(self, path):\n \"\"\" Prepend ``path`` to ``sys.path`` list of import locations. \"\"\"\n from pkg_resources import fixup_namespace_packages\n\n if self._savesyspath is None:\n self._savesyspath = sys.path[:]\n sys.path.insert(0, str(path))\n\n # https://github.com/pypa/setuptools/blob/d8b901bc/docs/pkg_resources.txt#L162-L171\n fixup_namespace_packages(str(path))\n\n # A call to syspathinsert() usually means that the caller wants to\n # import some dynamically created files, thus with python3 we\n # invalidate its import caches.\n # This is especially important when any namespace package is in used,\n # since then the mtime based FileFinder cache (that gets created in\n # this case already) gets not invalidated when writing the new files\n # quickly afterwards.\n if sys.version_info >= (3, 3):\n from importlib import invalidate_caches\n\n invalidate_caches()\n\n def chdir(self, path):\n \"\"\" Change the current working directory to the specified path.\n Path can be a string or a py.path.local object.\n \"\"\"\n if self._cwd is None:\n self._cwd = os.getcwd()\n if hasattr(path, \"chdir\"):\n path.chdir()\n elif isinstance(path, Path):\n # modern python uses the fspath protocol here LEGACY\n os.chdir(str(path))\n else:\n os.chdir(path)\n\n def undo(self):\n \"\"\" Undo previous changes. This call consumes the\n undo stack. Calling it a second time has no effect unless\n you do more monkeypatching after the undo call.\n\n There is generally no need to call `undo()`, since it is\n called automatically during tear-down.\n\n Note that the same `monkeypatch` fixture is used across a\n single test function invocation. If `monkeypatch` is used both by\n the test function itself and one of the test fixtures,\n calling `undo()` will undo all of the changes made in\n both functions.\n \"\"\"\n for obj, name, value in reversed(self._setattr):\n if value is not notset:\n setattr(obj, name, value)\n else:\n delattr(obj, name)\n self._setattr[:] = []\n for dictionary, name, value in reversed(self._setitem):\n if value is notset:\n try:\n del dictionary[name]\n except KeyError:\n pass # was already deleted, so we have the desired state\n else:\n dictionary[name] = value\n self._setitem[:] = []\n if self._savesyspath is not None:\n sys.path[:] = self._savesyspath\n self._savesyspath = None\n\n if self._cwd is not None:\n os.chdir(self._cwd)\n self._cwd = None"},{"col":4,"comment":"null","endLoc":111,"header":"def __init__(self)","id":4475,"name":"__init__","nodeType":"Function","startLoc":107,"text":"def __init__(self):\n self._setattr = []\n self._setitem = []\n self._cwd = None\n self._savesyspath = None"},{"col":4,"comment":"\n Context manager that returns a new :class:`MonkeyPatch` object which\n undoes any patching done inside the ``with`` block upon exit:\n\n .. code-block:: python\n\n import functools\n def test_partial(monkeypatch):\n with monkeypatch.context() as m:\n m.setattr(functools, \"partial\", 3)\n\n Useful in situations where it is desired to undo some patches before the test ends,\n such as mocking ``stdlib`` functions that might break pytest itself if mocked (for examples\n of this see `#3290 `_.\n ","endLoc":134,"header":"@contextmanager\n def context(self)","id":4476,"name":"context","nodeType":"Function","startLoc":113,"text":"@contextmanager\n def context(self):\n \"\"\"\n Context manager that returns a new :class:`MonkeyPatch` object which\n undoes any patching done inside the ``with`` block upon exit:\n\n .. code-block:: python\n\n import functools\n def test_partial(monkeypatch):\n with monkeypatch.context() as m:\n m.setattr(functools, \"partial\", 3)\n\n Useful in situations where it is desired to undo some patches before the test ends,\n such as mocking ``stdlib`` functions that might break pytest itself if mocked (for examples\n of this see `#3290 `_.\n \"\"\"\n m = MonkeyPatch()\n try:\n yield m\n finally:\n m.undo()"},{"col":4,"comment":" Undo previous changes. This call consumes the\n undo stack. Calling it a second time has no effect unless\n you do more monkeypatching after the undo call.\n\n There is generally no need to call `undo()`, since it is\n called automatically during tear-down.\n\n Note that the same `monkeypatch` fixture is used across a\n single test function invocation. If `monkeypatch` is used both by\n the test function itself and one of the test fixtures,\n calling `undo()` will undo all of the changes made in\n both functions.\n ","endLoc":336,"header":"def undo(self)","id":4477,"name":"undo","nodeType":"Function","startLoc":301,"text":"def undo(self):\n \"\"\" Undo previous changes. This call consumes the\n undo stack. Calling it a second time has no effect unless\n you do more monkeypatching after the undo call.\n\n There is generally no need to call `undo()`, since it is\n called automatically during tear-down.\n\n Note that the same `monkeypatch` fixture is used across a\n single test function invocation. If `monkeypatch` is used both by\n the test function itself and one of the test fixtures,\n calling `undo()` will undo all of the changes made in\n both functions.\n \"\"\"\n for obj, name, value in reversed(self._setattr):\n if value is not notset:\n setattr(obj, name, value)\n else:\n delattr(obj, name)\n self._setattr[:] = []\n for dictionary, name, value in reversed(self._setitem):\n if value is notset:\n try:\n del dictionary[name]\n except KeyError:\n pass # was already deleted, so we have the desired state\n else:\n dictionary[name] = value\n self._setitem[:] = []\n if self._savesyspath is not None:\n sys.path[:] = self._savesyspath\n self._savesyspath = None\n\n if self._cwd is not None:\n os.chdir(self._cwd)\n self._cwd = None"},{"className":"BaseFunctionalTests","col":0,"comment":"null","endLoc":399,"id":4478,"nodeType":"Class","startLoc":109,"text":"class BaseFunctionalTests(object):\n def test_passfunction(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n rep = reports[1]\n assert rep.passed\n assert not rep.failed\n assert rep.outcome == \"passed\"\n assert not rep.longrepr\n\n def test_failfunction(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n assert 0\n \"\"\"\n )\n rep = reports[1]\n assert not rep.passed\n assert not rep.skipped\n assert rep.failed\n assert rep.when == \"call\"\n assert rep.outcome == \"failed\"\n # assert isinstance(rep.longrepr, ReprExceptionInfo)\n\n def test_skipfunction(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n import pytest\n def test_func():\n pytest.skip(\"hello\")\n \"\"\"\n )\n rep = reports[1]\n assert not rep.failed\n assert not rep.passed\n assert rep.skipped\n assert rep.outcome == \"skipped\"\n # assert rep.skipped.when == \"call\"\n # assert rep.skipped.when == \"call\"\n # assert rep.skipped == \"%sreason == \"hello\"\n # assert rep.skipped.location.lineno == 3\n # assert rep.skipped.location.path\n # assert not rep.skipped.failurerepr\n\n def test_skip_in_setup_function(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n import pytest\n def setup_function(func):\n pytest.skip(\"hello\")\n def test_func():\n pass\n \"\"\"\n )\n print(reports)\n rep = reports[0]\n assert not rep.failed\n assert not rep.passed\n assert rep.skipped\n # assert rep.skipped.reason == \"hello\"\n # assert rep.skipped.location.lineno == 3\n # assert rep.skipped.location.lineno == 3\n assert len(reports) == 2\n assert reports[1].passed # teardown\n\n def test_failure_in_setup_function(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n import pytest\n def setup_function(func):\n raise ValueError(42)\n def test_func():\n pass\n \"\"\"\n )\n rep = reports[0]\n assert not rep.skipped\n assert not rep.passed\n assert rep.failed\n assert rep.when == \"setup\"\n assert len(reports) == 2\n\n def test_failure_in_teardown_function(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n import pytest\n def teardown_function(func):\n raise ValueError(42)\n def test_func():\n pass\n \"\"\"\n )\n print(reports)\n assert len(reports) == 3\n rep = reports[2]\n assert not rep.skipped\n assert not rep.passed\n assert rep.failed\n assert rep.when == \"teardown\"\n # assert rep.longrepr.reprcrash.lineno == 3\n # assert rep.longrepr.reprtraceback.reprentries\n\n def test_custom_failure_repr(self, testdir):\n testdir.makepyfile(\n conftest=\"\"\"\n import pytest\n class Function(pytest.Function):\n def repr_failure(self, excinfo):\n return \"hello\"\n \"\"\"\n )\n reports = testdir.runitem(\n \"\"\"\n import pytest\n def test_func():\n assert 0\n \"\"\"\n )\n rep = reports[1]\n assert not rep.skipped\n assert not rep.passed\n assert rep.failed\n # assert rep.outcome.when == \"call\"\n # assert rep.failed.where.lineno == 3\n # assert rep.failed.where.path.basename == \"test_func.py\"\n # assert rep.failed.failurerepr == \"hello\"\n\n def test_teardown_final_returncode(self, testdir):\n rec = testdir.inline_runsource(\n \"\"\"\n def test_func():\n pass\n def teardown_function(func):\n raise ValueError(42)\n \"\"\"\n )\n assert rec.ret == 1\n\n def test_logstart_logfinish_hooks(self, testdir):\n rec = testdir.inline_runsource(\n \"\"\"\n import pytest\n def test_func():\n pass\n \"\"\"\n )\n reps = rec.getcalls(\"pytest_runtest_logstart pytest_runtest_logfinish\")\n assert [x._name for x in reps] == [\n \"pytest_runtest_logstart\",\n \"pytest_runtest_logfinish\",\n ]\n for rep in reps:\n assert rep.nodeid == \"test_logstart_logfinish_hooks.py::test_func\"\n assert rep.location == (\"test_logstart_logfinish_hooks.py\", 1, \"test_func\")\n\n def test_exact_teardown_issue90(self, testdir):\n rec = testdir.inline_runsource(\n \"\"\"\n import pytest\n\n class TestClass(object):\n def test_method(self):\n pass\n def teardown_class(cls):\n raise Exception()\n\n def test_func():\n import sys\n # on python2 exc_info is keept till a function exits\n # so we would end up calling test functions while\n # sys.exc_info would return the indexerror\n # from guessing the lastitem\n excinfo = sys.exc_info()\n import traceback\n assert excinfo[0] is None, \\\n traceback.format_exception(*excinfo)\n def teardown_function(func):\n raise ValueError(42)\n \"\"\"\n )\n reps = rec.getreports(\"pytest_runtest_logreport\")\n print(reps)\n for i in range(2):\n assert reps[i].nodeid.endswith(\"test_method\")\n assert reps[i].passed\n assert reps[2].when == \"teardown\"\n assert reps[2].failed\n assert len(reps) == 6\n for i in range(3, 5):\n assert reps[i].nodeid.endswith(\"test_func\")\n assert reps[i].passed\n assert reps[5].when == \"teardown\"\n assert reps[5].nodeid.endswith(\"test_func\")\n assert reps[5].failed\n\n def test_exact_teardown_issue1206(self, testdir):\n \"\"\"issue shadowing error with wrong number of arguments on teardown_method.\"\"\"\n rec = testdir.inline_runsource(\n \"\"\"\n import pytest\n\n class TestClass(object):\n def teardown_method(self, x, y, z):\n pass\n\n def test_method(self):\n assert True\n \"\"\"\n )\n reps = rec.getreports(\"pytest_runtest_logreport\")\n print(reps)\n assert len(reps) == 3\n #\n assert reps[0].nodeid.endswith(\"test_method\")\n assert reps[0].passed\n assert reps[0].when == \"setup\"\n #\n assert reps[1].nodeid.endswith(\"test_method\")\n assert reps[1].passed\n assert reps[1].when == \"call\"\n #\n assert reps[2].nodeid.endswith(\"test_method\")\n assert reps[2].failed\n assert reps[2].when == \"teardown\"\n assert reps[2].longrepr.reprcrash.message in (\n # python3 error\n \"TypeError: teardown_method() missing 2 required positional arguments: 'y' and 'z'\",\n # python2 error\n \"TypeError: teardown_method() takes exactly 4 arguments (2 given)\",\n )\n\n def test_failure_in_setup_function_ignores_custom_repr(self, testdir):\n testdir.makepyfile(\n conftest=\"\"\"\n import pytest\n class Function(pytest.Function):\n def repr_failure(self, excinfo):\n assert 0\n \"\"\"\n )\n reports = testdir.runitem(\n \"\"\"\n def setup_function(func):\n raise ValueError(42)\n def test_func():\n pass\n \"\"\"\n )\n assert len(reports) == 2\n rep = reports[0]\n print(rep)\n assert not rep.skipped\n assert not rep.passed\n assert rep.failed\n # assert rep.outcome.when == \"setup\"\n # assert rep.outcome.where.lineno == 3\n # assert rep.outcome.where.path.basename == \"test_func.py\"\n # assert instanace(rep.failed.failurerepr, PythonFailureRepr)\n\n def test_systemexit_does_not_bail_out(self, testdir):\n try:\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n raise SystemExit(42)\n \"\"\"\n )\n except SystemExit:\n pytest.fail(\"runner did not catch SystemExit\")\n rep = reports[1]\n assert rep.failed\n assert rep.when == \"call\"\n\n def test_exit_propagates(self, testdir):\n try:\n testdir.runitem(\n \"\"\"\n import pytest\n def test_func():\n raise pytest.exit.Exception()\n \"\"\"\n )\n except pytest.exit.Exception:\n pass\n else:\n pytest.fail(\"did not raise\")"},{"col":4,"comment":"null","endLoc":121,"header":"def test_passfunction(self, testdir)","id":4479,"name":"test_passfunction","nodeType":"Function","startLoc":110,"text":"def test_passfunction(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n rep = reports[1]\n assert rep.passed\n assert not rep.failed\n assert rep.outcome == \"passed\"\n assert not rep.longrepr"},{"col":4,"comment":"null","endLoc":136,"header":"def test_failfunction(self, testdir)","id":4480,"name":"test_failfunction","nodeType":"Function","startLoc":123,"text":"def test_failfunction(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n assert 0\n \"\"\"\n )\n rep = reports[1]\n assert not rep.passed\n assert not rep.skipped\n assert rep.failed\n assert rep.when == \"call\"\n assert rep.outcome == \"failed\"\n # assert isinstance(rep.longrepr, ReprExceptionInfo)"},{"col":4,"comment":"null","endLoc":156,"header":"def test_skipfunction(self, testdir)","id":4481,"name":"test_skipfunction","nodeType":"Function","startLoc":138,"text":"def test_skipfunction(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n import pytest\n def test_func():\n pytest.skip(\"hello\")\n \"\"\"\n )\n rep = reports[1]\n assert not rep.failed\n assert not rep.passed\n assert rep.skipped\n assert rep.outcome == \"skipped\"\n # assert rep.skipped.when == \"call\"\n # assert rep.skipped.when == \"call\"\n # assert rep.skipped == \"%sreason == \"hello\"\n # assert rep.skipped.location.lineno == 3\n # assert rep.skipped.location.path\n # assert not rep.skipped.failurerepr"},{"col":4,"comment":"null","endLoc":177,"header":"def test_skip_in_setup_function(self, testdir)","id":4482,"name":"test_skip_in_setup_function","nodeType":"Function","startLoc":158,"text":"def test_skip_in_setup_function(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n import pytest\n def setup_function(func):\n pytest.skip(\"hello\")\n def test_func():\n pass\n \"\"\"\n )\n print(reports)\n rep = reports[0]\n assert not rep.failed\n assert not rep.passed\n assert rep.skipped\n # assert rep.skipped.reason == \"hello\"\n # assert rep.skipped.location.lineno == 3\n # assert rep.skipped.location.lineno == 3\n assert len(reports) == 2\n assert reports[1].passed # teardown"},{"col":4,"comment":"null","endLoc":194,"header":"def test_failure_in_setup_function(self, testdir)","id":4483,"name":"test_failure_in_setup_function","nodeType":"Function","startLoc":179,"text":"def test_failure_in_setup_function(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n import pytest\n def setup_function(func):\n raise ValueError(42)\n def test_func():\n pass\n \"\"\"\n )\n rep = reports[0]\n assert not rep.skipped\n assert not rep.passed\n assert rep.failed\n assert rep.when == \"setup\"\n assert len(reports) == 2"},{"col":8,"endLoc":198,"id":4484,"nodeType":"Lambda","startLoc":198,"text":"lambda: ihook(item=item, **kwds)"},{"col":0,"comment":"Show test function, parameters and the fixtures of the test item.","endLoc":111,"header":"def show_test_item(item)","id":4485,"name":"show_test_item","nodeType":"Function","startLoc":103,"text":"def show_test_item(item):\n \"\"\"Show test function, parameters and the fixtures of the test item.\"\"\"\n tw = item.config.get_terminal_writer()\n tw.line()\n tw.write(\" \" * 8)\n tw.write(item._nodeid)\n used_fixtures = sorted(item._fixtureinfo.name2fixturedefs.keys())\n if used_fixtures:\n tw.write(\" (fixtures used: {})\".format(\", \".join(used_fixtures)))"},{"col":4,"comment":"null","endLoc":214,"header":"def test_failure_in_teardown_function(self, testdir)","id":4486,"name":"test_failure_in_teardown_function","nodeType":"Function","startLoc":196,"text":"def test_failure_in_teardown_function(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n import pytest\n def teardown_function(func):\n raise ValueError(42)\n def test_func():\n pass\n \"\"\"\n )\n print(reports)\n assert len(reports) == 3\n rep = reports[2]\n assert not rep.skipped\n assert not rep.passed\n assert rep.failed\n assert rep.when == \"teardown\"\n # assert rep.longrepr.reprcrash.lineno == 3\n # assert rep.longrepr.reprtraceback.reprentries"},{"col":4,"comment":"null","endLoc":239,"header":"def test_custom_failure_repr(self, testdir)","id":4487,"name":"test_custom_failure_repr","nodeType":"Function","startLoc":216,"text":"def test_custom_failure_repr(self, testdir):\n testdir.makepyfile(\n conftest=\"\"\"\n import pytest\n class Function(pytest.Function):\n def repr_failure(self, excinfo):\n return \"hello\"\n \"\"\"\n )\n reports = testdir.runitem(\n \"\"\"\n import pytest\n def test_func():\n assert 0\n \"\"\"\n )\n rep = reports[1]\n assert not rep.skipped\n assert not rep.passed\n assert rep.failed\n # assert rep.outcome.when == \"call\"\n # assert rep.failed.where.lineno == 3\n # assert rep.failed.where.path.basename == \"test_func.py\"\n # assert rep.failed.failurerepr == \"hello\""},{"col":4,"comment":"null","endLoc":250,"header":"def test_teardown_final_returncode(self, testdir)","id":4488,"name":"test_teardown_final_returncode","nodeType":"Function","startLoc":241,"text":"def test_teardown_final_returncode(self, testdir):\n rec = testdir.inline_runsource(\n \"\"\"\n def test_func():\n pass\n def teardown_function(func):\n raise ValueError(42)\n \"\"\"\n )\n assert rec.ret == 1"},{"col":4,"comment":"null","endLoc":267,"header":"def test_logstart_logfinish_hooks(self, testdir)","id":4489,"name":"test_logstart_logfinish_hooks","nodeType":"Function","startLoc":252,"text":"def test_logstart_logfinish_hooks(self, testdir):\n rec = testdir.inline_runsource(\n \"\"\"\n import pytest\n def test_func():\n pass\n \"\"\"\n )\n reps = rec.getcalls(\"pytest_runtest_logstart pytest_runtest_logfinish\")\n assert [x._name for x in reps] == [\n \"pytest_runtest_logstart\",\n \"pytest_runtest_logfinish\",\n ]\n for rep in reps:\n assert rep.nodeid == \"test_logstart_logfinish_hooks.py::test_func\"\n assert rep.location == (\"test_logstart_logfinish_hooks.py\", 1, \"test_func\")"},{"col":4,"comment":"null","endLoc":307,"header":"def test_exact_teardown_issue90(self, testdir)","id":4490,"name":"test_exact_teardown_issue90","nodeType":"Function","startLoc":269,"text":"def test_exact_teardown_issue90(self, testdir):\n rec = testdir.inline_runsource(\n \"\"\"\n import pytest\n\n class TestClass(object):\n def test_method(self):\n pass\n def teardown_class(cls):\n raise Exception()\n\n def test_func():\n import sys\n # on python2 exc_info is keept till a function exits\n # so we would end up calling test functions while\n # sys.exc_info would return the indexerror\n # from guessing the lastitem\n excinfo = sys.exc_info()\n import traceback\n assert excinfo[0] is None, \\\n traceback.format_exception(*excinfo)\n def teardown_function(func):\n raise ValueError(42)\n \"\"\"\n )\n reps = rec.getreports(\"pytest_runtest_logreport\")\n print(reps)\n for i in range(2):\n assert reps[i].nodeid.endswith(\"test_method\")\n assert reps[i].passed\n assert reps[2].when == \"teardown\"\n assert reps[2].failed\n assert len(reps) == 6\n for i in range(3, 5):\n assert reps[i].nodeid.endswith(\"test_func\")\n assert reps[i].passed\n assert reps[5].when == \"teardown\"\n assert reps[5].nodeid.endswith(\"test_func\")\n assert reps[5].failed"},{"col":4,"comment":"null","endLoc":765,"header":"def test_lastfailed_no_failures_behavior_all_passed(self, testdir)","id":4491,"name":"test_lastfailed_no_failures_behavior_all_passed","nodeType":"Function","startLoc":742,"text":"def test_lastfailed_no_failures_behavior_all_passed(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_1():\n assert True\n def test_2():\n assert True\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n result = testdir.runpytest(\"--lf\", \"--lfnf\", \"all\")\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n result = testdir.runpytest(\"--lf\", \"--lfnf\", \"none\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items / 2 deselected\",\n \"run-last-failure: no previously failed tests, deselecting all items.\",\n \"* 2 deselected in *\",\n ]\n )\n assert result.ret == EXIT_NOTESTSCOLLECTED"},{"col":4,"comment":"null","endLoc":781,"header":"def test_lastfailed_no_failures_behavior_empty_cache(self, testdir)","id":4492,"name":"test_lastfailed_no_failures_behavior_empty_cache","nodeType":"Function","startLoc":767,"text":"def test_lastfailed_no_failures_behavior_empty_cache(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_1():\n assert True\n def test_2():\n assert False\n \"\"\"\n )\n result = testdir.runpytest(\"--lf\", \"--cache-clear\")\n result.stdout.fnmatch_lines([\"*1 failed*1 passed*\"])\n result = testdir.runpytest(\"--lf\", \"--cache-clear\", \"--lfnf\", \"all\")\n result.stdout.fnmatch_lines([\"*1 failed*1 passed*\"])\n result = testdir.runpytest(\"--lf\", \"--cache-clear\", \"--lfnf\", \"none\")\n result.stdout.fnmatch_lines([\"*2 desel*\"])"},{"col":4,"comment":"\n Test --lf behavior regarding skipping collection of files that are not marked as\n failed in the cache (#5172).\n ","endLoc":833,"header":"def test_lastfailed_skip_collection(self, testdir)","id":4493,"name":"test_lastfailed_skip_collection","nodeType":"Function","startLoc":783,"text":"def test_lastfailed_skip_collection(self, testdir):\n \"\"\"\n Test --lf behavior regarding skipping collection of files that are not marked as\n failed in the cache (#5172).\n \"\"\"\n testdir.makepyfile(\n **{\n \"pkg1/test_1.py\": \"\"\"\n import pytest\n\n @pytest.mark.parametrize('i', range(3))\n def test_1(i): pass\n \"\"\",\n \"pkg2/test_2.py\": \"\"\"\n import pytest\n\n @pytest.mark.parametrize('i', range(5))\n def test_1(i):\n assert i not in (1, 3)\n \"\"\",\n }\n )\n # first run: collects 8 items (test_1: 3, test_2: 5)\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"collected 8 items\", \"*2 failed*6 passed*\"])\n # second run: collects only 5 items from test_2, because all tests from test_1 have passed\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 5 items / 3 deselected / 2 selected\",\n \"run-last-failure: rerun previous 2 failures (skipped 1 file)\",\n \"*2 failed*3 deselected*\",\n ]\n )\n\n # add another file and check if message is correct when skipping more than 1 file\n testdir.makepyfile(\n **{\n \"pkg1/test_3.py\": \"\"\"\n def test_3(): pass\n \"\"\"\n }\n )\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 5 items / 3 deselected / 2 selected\",\n \"run-last-failure: rerun previous 2 failures (skipped 2 files)\",\n \"*2 failed*3 deselected*\",\n ]\n )"},{"col":0,"comment":"Fix infinite recursion when writing pyc files: if an import happens to be triggered when writing the pyc\n file, this would cause another call to the hook, which would trigger another pyc writing, which could\n trigger another import, and so on. (#3506)","endLoc":1287,"header":"def test_rewrite_infinite_recursion(testdir, pytestconfig, monkeypatch)","id":4495,"name":"test_rewrite_infinite_recursion","nodeType":"Function","startLoc":1261,"text":"def test_rewrite_infinite_recursion(testdir, pytestconfig, monkeypatch):\n \"\"\"Fix infinite recursion when writing pyc files: if an import happens to be triggered when writing the pyc\n file, this would cause another call to the hook, which would trigger another pyc writing, which could\n trigger another import, and so on. (#3506)\"\"\"\n from _pytest.assertion import rewrite\n\n testdir.syspathinsert()\n testdir.makepyfile(test_foo=\"def test_foo(): pass\")\n testdir.makepyfile(test_bar=\"def test_bar(): pass\")\n\n original_write_pyc = rewrite._write_pyc\n\n write_pyc_called = []\n\n def spy_write_pyc(*args, **kwargs):\n # make a note that we have called _write_pyc\n write_pyc_called.append(True)\n # try to import a module at this point: we should not try to rewrite this module\n assert hook.find_module(\"test_bar\") is None\n return original_write_pyc(*args, **kwargs)\n\n monkeypatch.setattr(rewrite, \"_write_pyc\", spy_write_pyc)\n monkeypatch.setattr(sys, \"dont_write_bytecode\", False)\n\n hook = AssertionRewritingHook(pytestconfig)\n assert hook.find_module(\"test_foo\") is not None\n assert len(write_pyc_called) == 1"},{"col":4,"comment":"null","endLoc":875,"header":"def test_lastfailed_with_known_failures_not_being_selected(self, testdir)","id":4496,"name":"test_lastfailed_with_known_failures_not_being_selected","nodeType":"Function","startLoc":835,"text":"def test_lastfailed_with_known_failures_not_being_selected(self, testdir):\n testdir.makepyfile(\n **{\n \"pkg1/test_1.py\": \"\"\"def test_1(): assert 0\"\"\",\n \"pkg1/test_2.py\": \"\"\"def test_2(): pass\"\"\",\n }\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"collected 2 items\", \"* 1 failed, 1 passed in *\"])\n\n py.path.local(\"pkg1/test_1.py\").remove()\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 1 item\",\n \"run-last-failure: 1 known failures not in selected tests\",\n \"* 1 passed in *\",\n ]\n )\n\n # Recreate file with known failure.\n testdir.makepyfile(**{\"pkg1/test_1.py\": \"\"\"def test_1(): assert 0\"\"\"})\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 1 item\",\n \"run-last-failure: rerun previous 1 failure (skipped 1 file)\",\n \"* 1 failed in *\",\n ]\n )\n\n # Remove/rename test.\n testdir.makepyfile(**{\"pkg1/test_1.py\": \"\"\"def test_renamed(): assert 0\"\"\"})\n result = testdir.runpytest(\"--lf\")\n result.stdout.fnmatch_lines(\n [\n \"collected 1 item\",\n \"run-last-failure: 1 known failures not in selected tests (skipped 1 file)\",\n \"* 1 failed in *\",\n ]\n )"},{"col":0,"comment":"It should be imported in pytest_configure or later only.","endLoc":1181,"header":"def test_pdbcls_via_local_module(testdir)","id":4497,"name":"test_pdbcls_via_local_module","nodeType":"Function","startLoc":1140,"text":"def test_pdbcls_via_local_module(testdir):\n \"\"\"It should be imported in pytest_configure or later only.\"\"\"\n p1 = testdir.makepyfile(\n \"\"\"\n def test():\n print(\"before_set_trace\")\n __import__(\"pdb\").set_trace()\n \"\"\",\n mypdb=\"\"\"\n class Wrapped:\n class MyPdb:\n def set_trace(self, *args):\n print(\"set_trace_called\", args)\n\n def runcall(self, *args, **kwds):\n print(\"runcall_called\", args, kwds)\n assert \"func\" in kwds\n \"\"\",\n )\n result = testdir.runpytest(\n str(p1), \"--pdbcls=really.invalid:Value\", syspathinsert=True\n )\n result.stdout.fnmatch_lines(\n [\n \"*= FAILURES =*\",\n \"E * --pdbcls: could not import 'really.invalid:Value': No module named *really*\",\n ]\n )\n assert result.ret == 1\n\n result = testdir.runpytest(\n str(p1), \"--pdbcls=mypdb:Wrapped.MyPdb\", syspathinsert=True\n )\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*set_trace_called*\", \"* 1 passed in *\"])\n\n # Ensure that it also works with --trace.\n result = testdir.runpytest(\n str(p1), \"--pdbcls=mypdb:Wrapped.MyPdb\", \"--trace\", syspathinsert=True\n )\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*runcall_called*\", \"* 1 passed in *\"])"},{"attributeType":"null","col":0,"comment":"null","endLoc":25,"id":4498,"name":"ast","nodeType":"Attribute","startLoc":25,"text":"ast"},{"col":0,"comment":"","endLoc":2,"header":"test_assertrewrite.py#","id":4499,"name":"","nodeType":"Function","startLoc":2,"text":"ast = pytest.importorskip(\"ast\")\n\nif sys.platform.startswith(\"java\"):\n # XXX should be xfail\n pytest.skip(\"assert rewrite does currently not work on jython\")"},{"className":"TestNewFirst","col":0,"comment":"null","endLoc":1000,"id":4500,"nodeType":"Class","startLoc":878,"text":"class TestNewFirst(object):\n def test_newfirst_usecase(self, testdir):\n testdir.makepyfile(\n **{\n \"test_1/test_1.py\": \"\"\"\n def test_1(): assert 1\n def test_2(): assert 1\n def test_3(): assert 1\n \"\"\",\n \"test_2/test_2.py\": \"\"\"\n def test_1(): assert 1\n def test_2(): assert 1\n def test_3(): assert 1\n \"\"\",\n }\n )\n\n testdir.tmpdir.join(\"test_1/test_1.py\").setmtime(1)\n\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n [\n \"*test_1/test_1.py::test_1 PASSED*\",\n \"*test_1/test_1.py::test_2 PASSED*\",\n \"*test_1/test_1.py::test_3 PASSED*\",\n \"*test_2/test_2.py::test_1 PASSED*\",\n \"*test_2/test_2.py::test_2 PASSED*\",\n \"*test_2/test_2.py::test_3 PASSED*\",\n ]\n )\n\n result = testdir.runpytest(\"-v\", \"--nf\")\n\n result.stdout.fnmatch_lines(\n [\n \"*test_2/test_2.py::test_1 PASSED*\",\n \"*test_2/test_2.py::test_2 PASSED*\",\n \"*test_2/test_2.py::test_3 PASSED*\",\n \"*test_1/test_1.py::test_1 PASSED*\",\n \"*test_1/test_1.py::test_2 PASSED*\",\n \"*test_1/test_1.py::test_3 PASSED*\",\n ]\n )\n\n testdir.tmpdir.join(\"test_1/test_1.py\").write(\n \"def test_1(): assert 1\\n\"\n \"def test_2(): assert 1\\n\"\n \"def test_3(): assert 1\\n\"\n \"def test_4(): assert 1\\n\"\n )\n testdir.tmpdir.join(\"test_1/test_1.py\").setmtime(1)\n\n result = testdir.runpytest(\"-v\", \"--nf\")\n\n result.stdout.fnmatch_lines(\n [\n \"*test_1/test_1.py::test_4 PASSED*\",\n \"*test_2/test_2.py::test_1 PASSED*\",\n \"*test_2/test_2.py::test_2 PASSED*\",\n \"*test_2/test_2.py::test_3 PASSED*\",\n \"*test_1/test_1.py::test_1 PASSED*\",\n \"*test_1/test_1.py::test_2 PASSED*\",\n \"*test_1/test_1.py::test_3 PASSED*\",\n ]\n )\n\n def test_newfirst_parametrize(self, testdir):\n testdir.makepyfile(\n **{\n \"test_1/test_1.py\": \"\"\"\n import pytest\n @pytest.mark.parametrize('num', [1, 2])\n def test_1(num): assert num\n \"\"\",\n \"test_2/test_2.py\": \"\"\"\n import pytest\n @pytest.mark.parametrize('num', [1, 2])\n def test_1(num): assert num\n \"\"\",\n }\n )\n\n testdir.tmpdir.join(\"test_1/test_1.py\").setmtime(1)\n\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n [\n \"*test_1/test_1.py::test_1[1*\",\n \"*test_1/test_1.py::test_1[2*\",\n \"*test_2/test_2.py::test_1[1*\",\n \"*test_2/test_2.py::test_1[2*\",\n ]\n )\n\n result = testdir.runpytest(\"-v\", \"--nf\")\n\n result.stdout.fnmatch_lines(\n [\n \"*test_2/test_2.py::test_1[1*\",\n \"*test_2/test_2.py::test_1[2*\",\n \"*test_1/test_1.py::test_1[1*\",\n \"*test_1/test_1.py::test_1[2*\",\n ]\n )\n\n testdir.tmpdir.join(\"test_1/test_1.py\").write(\n \"import pytest\\n\"\n \"@pytest.mark.parametrize('num', [1, 2, 3])\\n\"\n \"def test_1(num): assert num\\n\"\n )\n testdir.tmpdir.join(\"test_1/test_1.py\").setmtime(1)\n\n result = testdir.runpytest(\"-v\", \"--nf\")\n\n result.stdout.fnmatch_lines(\n [\n \"*test_1/test_1.py::test_1[3*\",\n \"*test_2/test_2.py::test_1[1*\",\n \"*test_2/test_2.py::test_1[2*\",\n \"*test_1/test_1.py::test_1[1*\",\n \"*test_1/test_1.py::test_1[2*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":942,"header":"def test_newfirst_usecase(self, testdir)","id":4501,"name":"test_newfirst_usecase","nodeType":"Function","startLoc":879,"text":"def test_newfirst_usecase(self, testdir):\n testdir.makepyfile(\n **{\n \"test_1/test_1.py\": \"\"\"\n def test_1(): assert 1\n def test_2(): assert 1\n def test_3(): assert 1\n \"\"\",\n \"test_2/test_2.py\": \"\"\"\n def test_1(): assert 1\n def test_2(): assert 1\n def test_3(): assert 1\n \"\"\",\n }\n )\n\n testdir.tmpdir.join(\"test_1/test_1.py\").setmtime(1)\n\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n [\n \"*test_1/test_1.py::test_1 PASSED*\",\n \"*test_1/test_1.py::test_2 PASSED*\",\n \"*test_1/test_1.py::test_3 PASSED*\",\n \"*test_2/test_2.py::test_1 PASSED*\",\n \"*test_2/test_2.py::test_2 PASSED*\",\n \"*test_2/test_2.py::test_3 PASSED*\",\n ]\n )\n\n result = testdir.runpytest(\"-v\", \"--nf\")\n\n result.stdout.fnmatch_lines(\n [\n \"*test_2/test_2.py::test_1 PASSED*\",\n \"*test_2/test_2.py::test_2 PASSED*\",\n \"*test_2/test_2.py::test_3 PASSED*\",\n \"*test_1/test_1.py::test_1 PASSED*\",\n \"*test_1/test_1.py::test_2 PASSED*\",\n \"*test_1/test_1.py::test_3 PASSED*\",\n ]\n )\n\n testdir.tmpdir.join(\"test_1/test_1.py\").write(\n \"def test_1(): assert 1\\n\"\n \"def test_2(): assert 1\\n\"\n \"def test_3(): assert 1\\n\"\n \"def test_4(): assert 1\\n\"\n )\n testdir.tmpdir.join(\"test_1/test_1.py\").setmtime(1)\n\n result = testdir.runpytest(\"-v\", \"--nf\")\n\n result.stdout.fnmatch_lines(\n [\n \"*test_1/test_1.py::test_4 PASSED*\",\n \"*test_2/test_2.py::test_1 PASSED*\",\n \"*test_2/test_2.py::test_2 PASSED*\",\n \"*test_2/test_2.py::test_3 PASSED*\",\n \"*test_1/test_1.py::test_1 PASSED*\",\n \"*test_1/test_1.py::test_2 PASSED*\",\n \"*test_1/test_1.py::test_3 PASSED*\",\n ]\n )"},{"fileName":"capture.py","filePath":"src/_pytest","id":4502,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"\nper-test stdout/stderr capturing mechanism.\n\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport contextlib\nimport io\nimport os\nimport sys\nfrom io import UnsupportedOperation\nfrom tempfile import TemporaryFile\n\nimport six\n\nimport pytest\nfrom _pytest.compat import _PY3\nfrom _pytest.compat import CaptureIO\n\npatchsysdict = {0: \"stdin\", 1: \"stdout\", 2: \"stderr\"}\n\n\ndef pytest_addoption(parser):\n group = parser.getgroup(\"general\")\n group._addoption(\n \"--capture\",\n action=\"store\",\n default=\"fd\" if hasattr(os, \"dup\") else \"sys\",\n metavar=\"method\",\n choices=[\"fd\", \"sys\", \"no\"],\n help=\"per-test capturing method: one of fd|sys|no.\",\n )\n group._addoption(\n \"-s\",\n action=\"store_const\",\n const=\"no\",\n dest=\"capture\",\n help=\"shortcut for --capture=no.\",\n )\n\n\n@pytest.hookimpl(hookwrapper=True)\ndef pytest_load_initial_conftests(early_config, parser, args):\n ns = early_config.known_args_namespace\n if ns.capture == \"fd\":\n _py36_windowsconsoleio_workaround(sys.stdout)\n _colorama_workaround()\n _readline_workaround()\n pluginmanager = early_config.pluginmanager\n capman = CaptureManager(ns.capture)\n pluginmanager.register(capman, \"capturemanager\")\n\n # make sure that capturemanager is properly reset at final shutdown\n early_config.add_cleanup(capman.stop_global_capturing)\n\n # finally trigger conftest loading but while capturing (issue93)\n capman.start_global_capturing()\n outcome = yield\n capman.suspend_global_capture()\n if outcome.excinfo is not None:\n out, err = capman.read_global_capture()\n sys.stdout.write(out)\n sys.stderr.write(err)\n\n\nclass CaptureManager(object):\n \"\"\"\n Capture plugin, manages that the appropriate capture method is enabled/disabled during collection and each\n test phase (setup, call, teardown). After each of those points, the captured output is obtained and\n attached to the collection/runtest report.\n\n There are two levels of capture:\n * global: which is enabled by default and can be suppressed by the ``-s`` option. This is always enabled/disabled\n during collection and each test phase.\n * fixture: when a test function or one of its fixture depend on the ``capsys`` or ``capfd`` fixtures. In this\n case special handling is needed to ensure the fixtures take precedence over the global capture.\n \"\"\"\n\n def __init__(self, method):\n self._method = method\n self._global_capturing = None\n self._current_item = None\n\n def __repr__(self):\n return \"\" % (\n self._method,\n self._global_capturing,\n self._current_item,\n )\n\n def _getcapture(self, method):\n if method == \"fd\":\n return MultiCapture(out=True, err=True, Capture=FDCapture)\n elif method == \"sys\":\n return MultiCapture(out=True, err=True, Capture=SysCapture)\n elif method == \"no\":\n return MultiCapture(out=False, err=False, in_=False)\n raise ValueError(\"unknown capturing method: %r\" % method) # pragma: no cover\n\n def is_capturing(self):\n if self.is_globally_capturing():\n return \"global\"\n capture_fixture = getattr(self._current_item, \"_capture_fixture\", None)\n if capture_fixture is not None:\n return (\n \"fixture %s\" % self._current_item._capture_fixture.request.fixturename\n )\n return False\n\n # Global capturing control\n\n def is_globally_capturing(self):\n return self._method != \"no\"\n\n def start_global_capturing(self):\n assert self._global_capturing is None\n self._global_capturing = self._getcapture(self._method)\n self._global_capturing.start_capturing()\n\n def stop_global_capturing(self):\n if self._global_capturing is not None:\n self._global_capturing.pop_outerr_to_orig()\n self._global_capturing.stop_capturing()\n self._global_capturing = None\n\n def resume_global_capture(self):\n # During teardown of the python process, and on rare occasions, capture\n # attributes can be `None` while trying to resume global capture.\n if self._global_capturing is not None:\n self._global_capturing.resume_capturing()\n\n def suspend_global_capture(self, in_=False):\n cap = getattr(self, \"_global_capturing\", None)\n if cap is not None:\n cap.suspend_capturing(in_=in_)\n\n def suspend(self, in_=False):\n # Need to undo local capsys-et-al if it exists before disabling global capture.\n self.suspend_fixture(self._current_item)\n self.suspend_global_capture(in_)\n\n def resume(self):\n self.resume_global_capture()\n self.resume_fixture(self._current_item)\n\n def read_global_capture(self):\n return self._global_capturing.readouterr()\n\n # Fixture Control (it's just forwarding, think about removing this later)\n\n def activate_fixture(self, item):\n \"\"\"If the current item is using ``capsys`` or ``capfd``, activate them so they take precedence over\n the global capture.\n \"\"\"\n fixture = getattr(item, \"_capture_fixture\", None)\n if fixture is not None:\n fixture._start()\n\n def deactivate_fixture(self, item):\n \"\"\"Deactivates the ``capsys`` or ``capfd`` fixture of this item, if any.\"\"\"\n fixture = getattr(item, \"_capture_fixture\", None)\n if fixture is not None:\n fixture.close()\n\n def suspend_fixture(self, item):\n fixture = getattr(item, \"_capture_fixture\", None)\n if fixture is not None:\n fixture._suspend()\n\n def resume_fixture(self, item):\n fixture = getattr(item, \"_capture_fixture\", None)\n if fixture is not None:\n fixture._resume()\n\n # Helper context managers\n\n @contextlib.contextmanager\n def global_and_fixture_disabled(self):\n \"\"\"Context manager to temporarily disable global and current fixture capturing.\"\"\"\n self.suspend()\n try:\n yield\n finally:\n self.resume()\n\n @contextlib.contextmanager\n def item_capture(self, when, item):\n self.resume_global_capture()\n self.activate_fixture(item)\n try:\n yield\n finally:\n self.deactivate_fixture(item)\n self.suspend_global_capture(in_=False)\n\n out, err = self.read_global_capture()\n item.add_report_section(when, \"stdout\", out)\n item.add_report_section(when, \"stderr\", err)\n\n # Hooks\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_make_collect_report(self, collector):\n if isinstance(collector, pytest.File):\n self.resume_global_capture()\n outcome = yield\n self.suspend_global_capture()\n out, err = self.read_global_capture()\n rep = outcome.get_result()\n if out:\n rep.sections.append((\"Captured stdout\", out))\n if err:\n rep.sections.append((\"Captured stderr\", err))\n else:\n yield\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_protocol(self, item):\n self._current_item = item\n yield\n self._current_item = None\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_setup(self, item):\n with self.item_capture(\"setup\", item):\n yield\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_call(self, item):\n with self.item_capture(\"call\", item):\n yield\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_teardown(self, item):\n with self.item_capture(\"teardown\", item):\n yield\n\n @pytest.hookimpl(tryfirst=True)\n def pytest_keyboard_interrupt(self, excinfo):\n self.stop_global_capturing()\n\n @pytest.hookimpl(tryfirst=True)\n def pytest_internalerror(self, excinfo):\n self.stop_global_capturing()\n\n\ncapture_fixtures = {\"capfd\", \"capfdbinary\", \"capsys\", \"capsysbinary\"}\n\n\ndef _ensure_only_one_capture_fixture(request, name):\n fixtures = set(request.fixturenames) & capture_fixtures - {name}\n if fixtures:\n fixtures = sorted(fixtures)\n fixtures = fixtures[0] if len(fixtures) == 1 else fixtures\n raise request.raiseerror(\n \"cannot use {} and {} at the same time\".format(fixtures, name)\n )\n\n\n@pytest.fixture\ndef capsys(request):\n \"\"\"Enable text capturing of writes to ``sys.stdout`` and ``sys.stderr``.\n\n The captured output is made available via ``capsys.readouterr()`` method\n calls, which return a ``(out, err)`` namedtuple.\n ``out`` and ``err`` will be ``text`` objects.\n \"\"\"\n _ensure_only_one_capture_fixture(request, \"capsys\")\n with _install_capture_fixture_on_item(request, SysCapture) as fixture:\n yield fixture\n\n\n@pytest.fixture\ndef capsysbinary(request):\n \"\"\"Enable bytes capturing of writes to ``sys.stdout`` and ``sys.stderr``.\n\n The captured output is made available via ``capsysbinary.readouterr()``\n method calls, which return a ``(out, err)`` namedtuple.\n ``out`` and ``err`` will be ``bytes`` objects.\n \"\"\"\n _ensure_only_one_capture_fixture(request, \"capsysbinary\")\n # Currently, the implementation uses the python3 specific `.buffer`\n # property of CaptureIO.\n if sys.version_info < (3,):\n raise request.raiseerror(\"capsysbinary is only supported on Python 3\")\n with _install_capture_fixture_on_item(request, SysCaptureBinary) as fixture:\n yield fixture\n\n\n@pytest.fixture\ndef capfd(request):\n \"\"\"Enable text capturing of writes to file descriptors ``1`` and ``2``.\n\n The captured output is made available via ``capfd.readouterr()`` method\n calls, which return a ``(out, err)`` namedtuple.\n ``out`` and ``err`` will be ``text`` objects.\n \"\"\"\n _ensure_only_one_capture_fixture(request, \"capfd\")\n if not hasattr(os, \"dup\"):\n pytest.skip(\n \"capfd fixture needs os.dup function which is not available in this system\"\n )\n with _install_capture_fixture_on_item(request, FDCapture) as fixture:\n yield fixture\n\n\n@pytest.fixture\ndef capfdbinary(request):\n \"\"\"Enable bytes capturing of writes to file descriptors ``1`` and ``2``.\n\n The captured output is made available via ``capfd.readouterr()`` method\n calls, which return a ``(out, err)`` namedtuple.\n ``out`` and ``err`` will be ``byte`` objects.\n \"\"\"\n _ensure_only_one_capture_fixture(request, \"capfdbinary\")\n if not hasattr(os, \"dup\"):\n pytest.skip(\n \"capfdbinary fixture needs os.dup function which is not available in this system\"\n )\n with _install_capture_fixture_on_item(request, FDCaptureBinary) as fixture:\n yield fixture\n\n\n@contextlib.contextmanager\ndef _install_capture_fixture_on_item(request, capture_class):\n \"\"\"\n Context manager which creates a ``CaptureFixture`` instance and \"installs\" it on\n the item/node of the given request. Used by ``capsys`` and ``capfd``.\n\n The CaptureFixture is added as attribute of the item because it needs to accessed\n by ``CaptureManager`` during its ``pytest_runtest_*`` hooks.\n \"\"\"\n request.node._capture_fixture = fixture = CaptureFixture(capture_class, request)\n capmanager = request.config.pluginmanager.getplugin(\"capturemanager\")\n # Need to active this fixture right away in case it is being used by another fixture (setup phase).\n # If this fixture is being used only by a test function (call phase), then we wouldn't need this\n # activation, but it doesn't hurt.\n capmanager.activate_fixture(request.node)\n yield fixture\n fixture.close()\n del request.node._capture_fixture\n\n\nclass CaptureFixture(object):\n \"\"\"\n Object returned by :py:func:`capsys`, :py:func:`capsysbinary`, :py:func:`capfd` and :py:func:`capfdbinary`\n fixtures.\n \"\"\"\n\n def __init__(self, captureclass, request):\n self.captureclass = captureclass\n self.request = request\n self._capture = None\n self._captured_out = self.captureclass.EMPTY_BUFFER\n self._captured_err = self.captureclass.EMPTY_BUFFER\n\n def _start(self):\n if self._capture is None:\n self._capture = MultiCapture(\n out=True, err=True, in_=False, Capture=self.captureclass\n )\n self._capture.start_capturing()\n\n def close(self):\n if self._capture is not None:\n out, err = self._capture.pop_outerr_to_orig()\n self._captured_out += out\n self._captured_err += err\n self._capture.stop_capturing()\n self._capture = None\n\n def readouterr(self):\n \"\"\"Read and return the captured output so far, resetting the internal buffer.\n\n :return: captured content as a namedtuple with ``out`` and ``err`` string attributes\n \"\"\"\n captured_out, captured_err = self._captured_out, self._captured_err\n if self._capture is not None:\n out, err = self._capture.readouterr()\n captured_out += out\n captured_err += err\n self._captured_out = self.captureclass.EMPTY_BUFFER\n self._captured_err = self.captureclass.EMPTY_BUFFER\n return CaptureResult(captured_out, captured_err)\n\n def _suspend(self):\n \"\"\"Suspends this fixture's own capturing temporarily.\"\"\"\n if self._capture is not None:\n self._capture.suspend_capturing()\n\n def _resume(self):\n \"\"\"Resumes this fixture's own capturing temporarily.\"\"\"\n if self._capture is not None:\n self._capture.resume_capturing()\n\n @contextlib.contextmanager\n def disabled(self):\n \"\"\"Temporarily disables capture while inside the 'with' block.\"\"\"\n capmanager = self.request.config.pluginmanager.getplugin(\"capturemanager\")\n with capmanager.global_and_fixture_disabled():\n yield\n\n\ndef safe_text_dupfile(f, mode, default_encoding=\"UTF8\"):\n \"\"\" return an open text file object that's a duplicate of f on the\n FD-level if possible.\n \"\"\"\n encoding = getattr(f, \"encoding\", None)\n try:\n fd = f.fileno()\n except Exception:\n if \"b\" not in getattr(f, \"mode\", \"\") and hasattr(f, \"encoding\"):\n # we seem to have a text stream, let's just use it\n return f\n else:\n newfd = os.dup(fd)\n if \"b\" not in mode:\n mode += \"b\"\n f = os.fdopen(newfd, mode, 0) # no buffering\n return EncodedFile(f, encoding or default_encoding)\n\n\nclass EncodedFile(object):\n errors = \"strict\" # possibly needed by py3 code (issue555)\n\n def __init__(self, buffer, encoding):\n self.buffer = buffer\n self.encoding = encoding\n\n def write(self, obj):\n if isinstance(obj, six.text_type):\n obj = obj.encode(self.encoding, \"replace\")\n elif _PY3:\n raise TypeError(\n \"write() argument must be str, not {}\".format(type(obj).__name__)\n )\n self.buffer.write(obj)\n\n def writelines(self, linelist):\n data = \"\".join(linelist)\n self.write(data)\n\n @property\n def name(self):\n \"\"\"Ensure that file.name is a string.\"\"\"\n return repr(self.buffer)\n\n @property\n def mode(self):\n return self.buffer.mode.replace(\"b\", \"\")\n\n def __getattr__(self, name):\n return getattr(object.__getattribute__(self, \"buffer\"), name)\n\n\nCaptureResult = collections.namedtuple(\"CaptureResult\", [\"out\", \"err\"])\n\n\nclass MultiCapture(object):\n out = err = in_ = None\n _state = None\n\n def __init__(self, out=True, err=True, in_=True, Capture=None):\n if in_:\n self.in_ = Capture(0)\n if out:\n self.out = Capture(1)\n if err:\n self.err = Capture(2)\n\n def __repr__(self):\n return \"\" % (\n self.out,\n self.err,\n self.in_,\n self._state,\n getattr(self, \"_in_suspended\", \"\"),\n )\n\n def start_capturing(self):\n self._state = \"started\"\n if self.in_:\n self.in_.start()\n if self.out:\n self.out.start()\n if self.err:\n self.err.start()\n\n def pop_outerr_to_orig(self):\n \"\"\" pop current snapshot out/err capture and flush to orig streams. \"\"\"\n out, err = self.readouterr()\n if out:\n self.out.writeorg(out)\n if err:\n self.err.writeorg(err)\n return out, err\n\n def suspend_capturing(self, in_=False):\n self._state = \"suspended\"\n if self.out:\n self.out.suspend()\n if self.err:\n self.err.suspend()\n if in_ and self.in_:\n self.in_.suspend()\n self._in_suspended = True\n\n def resume_capturing(self):\n self._state = \"resumed\"\n if self.out:\n self.out.resume()\n if self.err:\n self.err.resume()\n if hasattr(self, \"_in_suspended\"):\n self.in_.resume()\n del self._in_suspended\n\n def stop_capturing(self):\n \"\"\" stop capturing and reset capturing streams \"\"\"\n if self._state == \"stopped\":\n raise ValueError(\"was already stopped\")\n self._state = \"stopped\"\n if self.out:\n self.out.done()\n if self.err:\n self.err.done()\n if self.in_:\n self.in_.done()\n\n def readouterr(self):\n \"\"\" return snapshot unicode value of stdout/stderr capturings. \"\"\"\n return CaptureResult(\n self.out.snap() if self.out is not None else \"\",\n self.err.snap() if self.err is not None else \"\",\n )\n\n\nclass NoCapture(object):\n EMPTY_BUFFER = None\n __init__ = start = done = suspend = resume = lambda *args: None\n\n\nclass FDCaptureBinary(object):\n \"\"\"Capture IO to/from a given os-level filedescriptor.\n\n snap() produces `bytes`\n \"\"\"\n\n EMPTY_BUFFER = b\"\"\n _state = None\n\n def __init__(self, targetfd, tmpfile=None):\n self.targetfd = targetfd\n try:\n self.targetfd_save = os.dup(self.targetfd)\n except OSError:\n self.start = lambda: None\n self.done = lambda: None\n else:\n if targetfd == 0:\n assert not tmpfile, \"cannot set tmpfile with stdin\"\n tmpfile = open(os.devnull, \"r\")\n self.syscapture = SysCapture(targetfd)\n else:\n if tmpfile is None:\n f = TemporaryFile()\n with f:\n tmpfile = safe_text_dupfile(f, mode=\"wb+\")\n if targetfd in patchsysdict:\n self.syscapture = SysCapture(targetfd, tmpfile)\n else:\n self.syscapture = NoCapture()\n self.tmpfile = tmpfile\n self.tmpfile_fd = tmpfile.fileno()\n\n def __repr__(self):\n return \"\" % (\n self.targetfd,\n getattr(self, \"targetfd_save\", None),\n self._state,\n )\n\n def start(self):\n \"\"\" Start capturing on targetfd using memorized tmpfile. \"\"\"\n try:\n os.fstat(self.targetfd_save)\n except (AttributeError, OSError):\n raise ValueError(\"saved filedescriptor not valid anymore\")\n os.dup2(self.tmpfile_fd, self.targetfd)\n self.syscapture.start()\n self._state = \"started\"\n\n def snap(self):\n self.tmpfile.seek(0)\n res = self.tmpfile.read()\n self.tmpfile.seek(0)\n self.tmpfile.truncate()\n return res\n\n def done(self):\n \"\"\" stop capturing, restore streams, return original capture file,\n seeked to position zero. \"\"\"\n targetfd_save = self.__dict__.pop(\"targetfd_save\")\n os.dup2(targetfd_save, self.targetfd)\n os.close(targetfd_save)\n self.syscapture.done()\n _attempt_to_close_capture_file(self.tmpfile)\n self._state = \"done\"\n\n def suspend(self):\n self.syscapture.suspend()\n os.dup2(self.targetfd_save, self.targetfd)\n self._state = \"suspended\"\n\n def resume(self):\n self.syscapture.resume()\n os.dup2(self.tmpfile_fd, self.targetfd)\n self._state = \"resumed\"\n\n def writeorg(self, data):\n \"\"\" write to original file descriptor. \"\"\"\n if isinstance(data, six.text_type):\n data = data.encode(\"utf8\") # XXX use encoding of original stream\n os.write(self.targetfd_save, data)\n\n\nclass FDCapture(FDCaptureBinary):\n \"\"\"Capture IO to/from a given os-level filedescriptor.\n\n snap() produces text\n \"\"\"\n\n EMPTY_BUFFER = str()\n\n def snap(self):\n res = super(FDCapture, self).snap()\n enc = getattr(self.tmpfile, \"encoding\", None)\n if enc and isinstance(res, bytes):\n res = six.text_type(res, enc, \"replace\")\n return res\n\n\nclass SysCapture(object):\n\n EMPTY_BUFFER = str()\n _state = None\n\n def __init__(self, fd, tmpfile=None):\n name = patchsysdict[fd]\n self._old = getattr(sys, name)\n self.name = name\n if tmpfile is None:\n if name == \"stdin\":\n tmpfile = DontReadFromInput()\n else:\n tmpfile = CaptureIO()\n self.tmpfile = tmpfile\n\n def __repr__(self):\n return \"\" % (\n self.name,\n self._old,\n self.tmpfile,\n self._state,\n )\n\n def start(self):\n setattr(sys, self.name, self.tmpfile)\n self._state = \"started\"\n\n def snap(self):\n res = self.tmpfile.getvalue()\n self.tmpfile.seek(0)\n self.tmpfile.truncate()\n return res\n\n def done(self):\n setattr(sys, self.name, self._old)\n del self._old\n _attempt_to_close_capture_file(self.tmpfile)\n self._state = \"done\"\n\n def suspend(self):\n setattr(sys, self.name, self._old)\n self._state = \"suspended\"\n\n def resume(self):\n setattr(sys, self.name, self.tmpfile)\n self._state = \"resumed\"\n\n def writeorg(self, data):\n self._old.write(data)\n self._old.flush()\n\n\nclass SysCaptureBinary(SysCapture):\n EMPTY_BUFFER = b\"\"\n\n def snap(self):\n res = self.tmpfile.buffer.getvalue()\n self.tmpfile.seek(0)\n self.tmpfile.truncate()\n return res\n\n\nclass DontReadFromInput(six.Iterator):\n \"\"\"Temporary stub class. Ideally when stdin is accessed, the\n capturing should be turned off, with possibly all data captured\n so far sent to the screen. This should be configurable, though,\n because in automated test runs it is better to crash than\n hang indefinitely.\n \"\"\"\n\n encoding = None\n\n def read(self, *args):\n raise IOError(\"reading from stdin while output is captured\")\n\n readline = read\n readlines = read\n __next__ = read\n\n def __iter__(self):\n return self\n\n def fileno(self):\n raise UnsupportedOperation(\"redirected stdin is pseudofile, has no fileno()\")\n\n def isatty(self):\n return False\n\n def close(self):\n pass\n\n @property\n def buffer(self):\n if sys.version_info >= (3, 0):\n return self\n else:\n raise AttributeError(\"redirected stdin has no attribute buffer\")\n\n\ndef _colorama_workaround():\n \"\"\"\n Ensure colorama is imported so that it attaches to the correct stdio\n handles on Windows.\n\n colorama uses the terminal on import time. So if something does the\n first import of colorama while I/O capture is active, colorama will\n fail in various ways.\n \"\"\"\n if sys.platform.startswith(\"win32\"):\n try:\n import colorama # noqa: F401\n except ImportError:\n pass\n\n\ndef _readline_workaround():\n \"\"\"\n Ensure readline is imported so that it attaches to the correct stdio\n handles on Windows.\n\n Pdb uses readline support where available--when not running from the Python\n prompt, the readline module is not imported until running the pdb REPL. If\n running pytest with the --pdb option this means the readline module is not\n imported until after I/O capture has been started.\n\n This is a problem for pyreadline, which is often used to implement readline\n support on Windows, as it does not attach to the correct handles for stdout\n and/or stdin if they have been redirected by the FDCapture mechanism. This\n workaround ensures that readline is imported before I/O capture is setup so\n that it can attach to the actual stdin/out for the console.\n\n See https://github.com/pytest-dev/pytest/pull/1281\n \"\"\"\n if sys.platform.startswith(\"win32\"):\n try:\n import readline # noqa: F401\n except ImportError:\n pass\n\n\ndef _py36_windowsconsoleio_workaround(stream):\n \"\"\"\n Python 3.6 implemented unicode console handling for Windows. This works\n by reading/writing to the raw console handle using\n ``{Read,Write}ConsoleW``.\n\n The problem is that we are going to ``dup2`` over the stdio file\n descriptors when doing ``FDCapture`` and this will ``CloseHandle`` the\n handles used by Python to write to the console. Though there is still some\n weirdness and the console handle seems to only be closed randomly and not\n on the first call to ``CloseHandle``, or maybe it gets reopened with the\n same handle value when we suspend capturing.\n\n The workaround in this case will reopen stdio with a different fd which\n also means a different handle by replicating the logic in\n \"Py_lifecycle.c:initstdio/create_stdio\".\n\n :param stream: in practice ``sys.stdout`` or ``sys.stderr``, but given\n here as parameter for unittesting purposes.\n\n See https://github.com/pytest-dev/py/issues/103\n \"\"\"\n if not sys.platform.startswith(\"win32\") or sys.version_info[:2] < (3, 6):\n return\n\n # bail out if ``stream`` doesn't seem like a proper ``io`` stream (#2666)\n if not hasattr(stream, \"buffer\"):\n return\n\n buffered = hasattr(stream.buffer, \"raw\")\n raw_stdout = stream.buffer.raw if buffered else stream.buffer\n\n if not isinstance(raw_stdout, io._WindowsConsoleIO):\n return\n\n def _reopen_stdio(f, mode):\n if not buffered and mode[0] == \"w\":\n buffering = 0\n else:\n buffering = -1\n\n return io.TextIOWrapper(\n open(os.dup(f.fileno()), mode, buffering),\n f.encoding,\n f.errors,\n f.newlines,\n f.line_buffering,\n )\n\n sys.stdin = _reopen_stdio(sys.stdin, \"rb\")\n sys.stdout = _reopen_stdio(sys.stdout, \"wb\")\n sys.stderr = _reopen_stdio(sys.stderr, \"wb\")\n\n\ndef _attempt_to_close_capture_file(f):\n \"\"\"Suppress IOError when closing the temporary file used for capturing streams in py27 (#2370)\"\"\"\n if six.PY2:\n try:\n f.close()\n except IOError:\n pass\n else:\n f.close()\n"},{"className":"UnsupportedOperation","col":0,"comment":"null","endLoc":51,"id":4503,"nodeType":"Class","startLoc":51,"text":"class UnsupportedOperation(OSError, ValueError): ..."},{"col":4,"comment":"null","endLoc":1000,"header":"def test_newfirst_parametrize(self, testdir)","id":4504,"name":"test_newfirst_parametrize","nodeType":"Function","startLoc":944,"text":"def test_newfirst_parametrize(self, testdir):\n testdir.makepyfile(\n **{\n \"test_1/test_1.py\": \"\"\"\n import pytest\n @pytest.mark.parametrize('num', [1, 2])\n def test_1(num): assert num\n \"\"\",\n \"test_2/test_2.py\": \"\"\"\n import pytest\n @pytest.mark.parametrize('num', [1, 2])\n def test_1(num): assert num\n \"\"\",\n }\n )\n\n testdir.tmpdir.join(\"test_1/test_1.py\").setmtime(1)\n\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n [\n \"*test_1/test_1.py::test_1[1*\",\n \"*test_1/test_1.py::test_1[2*\",\n \"*test_2/test_2.py::test_1[1*\",\n \"*test_2/test_2.py::test_1[2*\",\n ]\n )\n\n result = testdir.runpytest(\"-v\", \"--nf\")\n\n result.stdout.fnmatch_lines(\n [\n \"*test_2/test_2.py::test_1[1*\",\n \"*test_2/test_2.py::test_1[2*\",\n \"*test_1/test_1.py::test_1[1*\",\n \"*test_1/test_1.py::test_1[2*\",\n ]\n )\n\n testdir.tmpdir.join(\"test_1/test_1.py\").write(\n \"import pytest\\n\"\n \"@pytest.mark.parametrize('num', [1, 2, 3])\\n\"\n \"def test_1(num): assert num\\n\"\n )\n testdir.tmpdir.join(\"test_1/test_1.py\").setmtime(1)\n\n result = testdir.runpytest(\"-v\", \"--nf\")\n\n result.stdout.fnmatch_lines(\n [\n \"*test_1/test_1.py::test_1[3*\",\n \"*test_2/test_2.py::test_1[1*\",\n \"*test_2/test_2.py::test_1[2*\",\n \"*test_1/test_1.py::test_1[1*\",\n \"*test_1/test_1.py::test_1[2*\",\n ]\n )"},{"className":"OSError","col":0,"comment":"null","endLoc":1959,"id":4505,"nodeType":"Class","startLoc":1952,"text":"class OSError(Exception):\n errno: int\n strerror: str\n # filename, filename2 are actually str | bytes | None\n filename: Any\n filename2: Any\n if sys.platform == \"win32\":\n winerror: int"},{"attributeType":"int","col":4,"comment":"null","endLoc":1953,"id":4506,"name":"errno","nodeType":"Attribute","startLoc":1953,"text":"errno"},{"className":"TestReadme","col":0,"comment":"null","endLoc":1027,"id":4507,"nodeType":"Class","startLoc":1003,"text":"class TestReadme(object):\n def check_readme(self, testdir):\n config = testdir.parseconfigure()\n readme = config.cache._cachedir.joinpath(\"README.md\")\n return readme.is_file()\n\n def test_readme_passed(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_always_passes():\n assert 1\n \"\"\"\n )\n testdir.runpytest()\n assert self.check_readme(testdir) is True\n\n def test_readme_failed(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_always_fails():\n assert 0\n \"\"\"\n )\n testdir.runpytest()\n assert self.check_readme(testdir) is True"},{"col":0,"comment":"It is not guaranteed that DontReadFromInput's read is called.","endLoc":1207,"header":"def test_raises_bdbquit_with_eoferror(testdir)","id":4508,"name":"test_raises_bdbquit_with_eoferror","nodeType":"Function","startLoc":1184,"text":"def test_raises_bdbquit_with_eoferror(testdir):\n \"\"\"It is not guaranteed that DontReadFromInput's read is called.\"\"\"\n if six.PY2:\n builtin_module = \"__builtin__\"\n input_func = \"raw_input\"\n else:\n builtin_module = \"builtins\"\n input_func = \"input\"\n p1 = testdir.makepyfile(\n \"\"\"\n def input_without_read(*args, **kwargs):\n raise EOFError()\n\n def test(monkeypatch):\n import {builtin_module}\n monkeypatch.setattr({builtin_module}, {input_func!r}, input_without_read)\n __import__('pdb').set_trace()\n \"\"\".format(\n builtin_module=builtin_module, input_func=input_func\n )\n )\n result = testdir.runpytest(str(p1))\n result.stdout.fnmatch_lines([\"E *BdbQuit\", \"*= 1 failed in*\"])\n assert result.ret == 1"},{"attributeType":"str","col":4,"comment":"null","endLoc":1954,"id":4509,"name":"strerror","nodeType":"Attribute","startLoc":1954,"text":"strerror"},{"col":0,"comment":"null","endLoc":116,"header":"def pytest_runtest_setup(item)","id":4510,"name":"pytest_runtest_setup","nodeType":"Function","startLoc":114,"text":"def pytest_runtest_setup(item):\n _update_current_test_var(item, \"setup\")\n item.session._setupstate.prepare(item)"},{"col":0,"comment":"\n Update PYTEST_CURRENT_TEST to reflect the current item and stage.\n\n If ``when`` is None, delete PYTEST_CURRENT_TEST from the environment.\n ","endLoc":154,"header":"def _update_current_test_var(item, when)","id":4511,"name":"_update_current_test_var","nodeType":"Function","startLoc":141,"text":"def _update_current_test_var(item, when):\n \"\"\"\n Update PYTEST_CURRENT_TEST to reflect the current item and stage.\n\n If ``when`` is None, delete PYTEST_CURRENT_TEST from the environment.\n \"\"\"\n var_name = \"PYTEST_CURRENT_TEST\"\n if when:\n value = \"{} ({})\".format(item.nodeid, when)\n # don't allow null bytes on environment variables (see #2644, #2957)\n value = value.replace(\"\\x00\", \"(null)\")\n os.environ[var_name] = value\n else:\n os.environ.pop(var_name)"},{"attributeType":"null","col":4,"comment":"null","endLoc":1956,"id":4512,"name":"filename","nodeType":"Attribute","startLoc":1956,"text":"filename"},{"col":4,"comment":"null","endLoc":1007,"header":"def check_readme(self, testdir)","id":4513,"name":"check_readme","nodeType":"Function","startLoc":1004,"text":"def check_readme(self, testdir):\n config = testdir.parseconfigure()\n readme = config.cache._cachedir.joinpath(\"README.md\")\n return readme.is_file()"},{"attributeType":"null","col":4,"comment":"null","endLoc":1957,"id":4514,"name":"filename2","nodeType":"Attribute","startLoc":1957,"text":"filename2"},{"attributeType":"int","col":8,"comment":"null","endLoc":1959,"id":4515,"name":"winerror","nodeType":"Attribute","startLoc":1959,"text":"winerror"},{"col":0,"comment":"null","endLoc":1237,"header":"def test_pdb_wrapper_class_is_reused(testdir)","id":4516,"name":"test_pdb_wrapper_class_is_reused","nodeType":"Function","startLoc":1210,"text":"def test_pdb_wrapper_class_is_reused(testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test():\n __import__(\"pdb\").set_trace()\n __import__(\"pdb\").set_trace()\n\n import mypdb\n instances = mypdb.instances\n assert len(instances) == 2\n assert instances[0].__class__ is instances[1].__class__\n \"\"\",\n mypdb=\"\"\"\n instances = []\n\n class MyPdb:\n def __init__(self, *args, **kwargs):\n instances.append(self)\n\n def set_trace(self, *args):\n print(\"set_trace_called\", args)\n \"\"\",\n )\n result = testdir.runpytest(str(p1), \"--pdbcls=mypdb:MyPdb\", syspathinsert=True)\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n [\"*set_trace_called*\", \"*set_trace_called*\", \"* 1 passed in *\"]\n )"},{"className":"ValueError","col":0,"comment":"null","endLoc":2011,"id":4517,"nodeType":"Class","startLoc":2011,"text":"class ValueError(Exception): ..."},{"col":4,"comment":"issue shadowing error with wrong number of arguments on teardown_method.","endLoc":343,"header":"def test_exact_teardown_issue1206(self, testdir)","id":4518,"name":"test_exact_teardown_issue1206","nodeType":"Function","startLoc":309,"text":"def test_exact_teardown_issue1206(self, testdir):\n \"\"\"issue shadowing error with wrong number of arguments on teardown_method.\"\"\"\n rec = testdir.inline_runsource(\n \"\"\"\n import pytest\n\n class TestClass(object):\n def teardown_method(self, x, y, z):\n pass\n\n def test_method(self):\n assert True\n \"\"\"\n )\n reps = rec.getreports(\"pytest_runtest_logreport\")\n print(reps)\n assert len(reps) == 3\n #\n assert reps[0].nodeid.endswith(\"test_method\")\n assert reps[0].passed\n assert reps[0].when == \"setup\"\n #\n assert reps[1].nodeid.endswith(\"test_method\")\n assert reps[1].passed\n assert reps[1].when == \"call\"\n #\n assert reps[2].nodeid.endswith(\"test_method\")\n assert reps[2].failed\n assert reps[2].when == \"teardown\"\n assert reps[2].longrepr.reprcrash.message in (\n # python3 error\n \"TypeError: teardown_method() missing 2 required positional arguments: 'y' and 'z'\",\n # python2 error\n \"TypeError: teardown_method() takes exactly 4 arguments (2 given)\",\n )"},{"col":4,"comment":"null","endLoc":371,"header":"def test_failure_in_setup_function_ignores_custom_repr(self, testdir)","id":4519,"name":"test_failure_in_setup_function_ignores_custom_repr","nodeType":"Function","startLoc":345,"text":"def test_failure_in_setup_function_ignores_custom_repr(self, testdir):\n testdir.makepyfile(\n conftest=\"\"\"\n import pytest\n class Function(pytest.Function):\n def repr_failure(self, excinfo):\n assert 0\n \"\"\"\n )\n reports = testdir.runitem(\n \"\"\"\n def setup_function(func):\n raise ValueError(42)\n def test_func():\n pass\n \"\"\"\n )\n assert len(reports) == 2\n rep = reports[0]\n print(rep)\n assert not rep.skipped\n assert not rep.passed\n assert rep.failed\n # assert rep.outcome.when == \"setup\"\n # assert rep.outcome.where.lineno == 3\n # assert rep.outcome.where.path.basename == \"test_func.py\"\n # assert instanace(rep.failed.failurerepr, PythonFailureRepr)"},{"col":4,"comment":"null","endLoc":1017,"header":"def test_readme_passed(self, testdir)","id":4520,"name":"test_readme_passed","nodeType":"Function","startLoc":1009,"text":"def test_readme_passed(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_always_passes():\n assert 1\n \"\"\"\n )\n testdir.runpytest()\n assert self.check_readme(testdir) is True"},{"attributeType":"bool","col":4,"comment":"null","endLoc":20,"id":4521,"name":"SUPPORTS_BREAKPOINT_BUILTIN","nodeType":"Attribute","startLoc":20,"text":"SUPPORTS_BREAKPOINT_BUILTIN"},{"attributeType":"str","col":0,"comment":"null","endLoc":23,"id":4522,"name":"_ENVIRON_PYTHONBREAKPOINT","nodeType":"Attribute","startLoc":23,"text":"_ENVIRON_PYTHONBREAKPOINT"},{"col":4,"comment":"null","endLoc":385,"header":"def test_systemexit_does_not_bail_out(self, testdir)","id":4523,"name":"test_systemexit_does_not_bail_out","nodeType":"Function","startLoc":373,"text":"def test_systemexit_does_not_bail_out(self, testdir):\n try:\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n raise SystemExit(42)\n \"\"\"\n )\n except SystemExit:\n pytest.fail(\"runner did not catch SystemExit\")\n rep = reports[1]\n assert rep.failed\n assert rep.when == \"call\""},{"col":0,"comment":"","endLoc":2,"header":"test_pdb.py#","id":4524,"name":"","nodeType":"Function","startLoc":2,"text":"try:\n breakpoint\nexcept NameError:\n SUPPORTS_BREAKPOINT_BUILTIN = False\nelse:\n SUPPORTS_BREAKPOINT_BUILTIN = True\n\n_ENVIRON_PYTHONBREAKPOINT = os.environ.get(\"PYTHONBREAKPOINT\", \"\")"},{"col":4,"comment":"null","endLoc":1027,"header":"def test_readme_failed(self, testdir)","id":4525,"name":"test_readme_failed","nodeType":"Function","startLoc":1019,"text":"def test_readme_failed(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_always_fails():\n assert 0\n \"\"\"\n )\n testdir.runpytest()\n assert self.check_readme(testdir) is True"},{"id":4526,"name":"release-2.0.3.rst","nodeType":"TextFile","path":"doc/en/announce","text":"py.test 2.0.3: bug fixes and speed ups\n===========================================================================\n\nWelcome to pytest-2.0.3, a maintenance and bug fix release of pytest,\na mature testing tool for Python, supporting CPython 2.4-3.2, Jython\nand latest PyPy interpreters. See the extensive docs with tested examples here:\n\n http://pytest.org/\n\nIf you want to install or upgrade pytest, just type one of::\n\n pip install -U pytest # or\n easy_install -U pytest\n\nThere also is a bugfix release 1.6 of pytest-xdist, the plugin\nthat enables seamless distributed and \"looponfail\" testing for Python.\n\nbest,\nholger krekel\n\nChanges between 2.0.2 and 2.0.3\n----------------------------------------------\n\n- fix issue38: nicer tracebacks on calls to hooks, particularly early\n configure/sessionstart ones\n\n- fix missing skip reason/meta information in junitxml files, reported\n via http://lists.idyll.org/pipermail/testing-in-python/2011-March/003928.html\n\n- fix issue34: avoid collection failure with \"test\" prefixed classes\n deriving from object.\n\n- don't require zlib (and other libs) for genscript plugin without\n --genscript actually being used.\n\n- speed up skips (by not doing a full traceback representation\n internally)\n\n- fix issue37: avoid invalid characters in junitxml's output\n"},{"col":0,"comment":"null","endLoc":163,"header":"@pytest.mark.parametrize(\"env\", ((), (\"TOX_ENV_DIR\", \"/tox_env_dir\")))\ndef test_cache_reportheader(env, testdir, monkeypatch)","id":4527,"name":"test_cache_reportheader","nodeType":"Function","startLoc":153,"text":"@pytest.mark.parametrize(\"env\", ((), (\"TOX_ENV_DIR\", \"/tox_env_dir\")))\ndef test_cache_reportheader(env, testdir, monkeypatch):\n testdir.makepyfile(\"\"\"def test_foo(): pass\"\"\")\n if env:\n monkeypatch.setenv(*env)\n expected = os.path.join(env[1], \".pytest_cache\")\n else:\n monkeypatch.delenv(\"TOX_ENV_DIR\", raising=False)\n expected = \".pytest_cache\"\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines([\"cachedir: %s\" % expected])"},{"fileName":"__init__.py","filePath":"src/_pytest/mark","id":4528,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\" generic mechanism for marking and selecting python functions. \"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom .legacy import matchkeyword\nfrom .legacy import matchmark\nfrom .structures import EMPTY_PARAMETERSET_OPTION\nfrom .structures import get_empty_parameterset_mark\nfrom .structures import Mark\nfrom .structures import MARK_GEN\nfrom .structures import MarkDecorator\nfrom .structures import MarkGenerator\nfrom .structures import ParameterSet\nfrom _pytest.config import UsageError\n\n__all__ = [\"Mark\", \"MarkDecorator\", \"MarkGenerator\", \"get_empty_parameterset_mark\"]\n\n\ndef param(*values, **kw):\n \"\"\"Specify a parameter in `pytest.mark.parametrize`_ calls or\n :ref:`parametrized fixtures `.\n\n .. code-block:: python\n\n @pytest.mark.parametrize(\"test_input,expected\", [\n (\"3+5\", 8),\n pytest.param(\"6*9\", 42, marks=pytest.mark.xfail),\n ])\n def test_eval(test_input, expected):\n assert eval(test_input) == expected\n\n :param values: variable args of the values of the parameter set, in order.\n :keyword marks: a single mark or a list of marks to be applied to this parameter set.\n :keyword str id: the id to attribute to this parameter set.\n \"\"\"\n return ParameterSet.param(*values, **kw)\n\n\ndef pytest_addoption(parser):\n group = parser.getgroup(\"general\")\n group._addoption(\n \"-k\",\n action=\"store\",\n dest=\"keyword\",\n default=\"\",\n metavar=\"EXPRESSION\",\n help=\"only run tests which match the given substring expression. \"\n \"An expression is a python evaluatable expression \"\n \"where all names are substring-matched against test names \"\n \"and their parent classes. Example: -k 'test_method or test_\"\n \"other' matches all test functions and classes whose name \"\n \"contains 'test_method' or 'test_other', while -k 'not test_method' \"\n \"matches those that don't contain 'test_method' in their names. \"\n \"-k 'not test_method and not test_other' will eliminate the matches. \"\n \"Additionally keywords are matched to classes and functions \"\n \"containing extra names in their 'extra_keyword_matches' set, \"\n \"as well as functions which have names assigned directly to them.\",\n )\n\n group._addoption(\n \"-m\",\n action=\"store\",\n dest=\"markexpr\",\n default=\"\",\n metavar=\"MARKEXPR\",\n help=\"only run tests matching given mark expression. \"\n \"example: -m 'mark1 and not mark2'.\",\n )\n\n group.addoption(\n \"--markers\",\n action=\"store_true\",\n help=\"show markers (builtin, plugin and per-project ones).\",\n )\n\n parser.addini(\"markers\", \"markers for test functions\", \"linelist\")\n parser.addini(EMPTY_PARAMETERSET_OPTION, \"default marker for empty parametersets\")\n\n\ndef pytest_cmdline_main(config):\n import _pytest.config\n\n if config.option.markers:\n config._do_configure()\n tw = _pytest.config.create_terminal_writer(config)\n for line in config.getini(\"markers\"):\n parts = line.split(\":\", 1)\n name = parts[0]\n rest = parts[1] if len(parts) == 2 else \"\"\n tw.write(\"@pytest.mark.%s:\" % name, bold=True)\n tw.line(rest)\n tw.line()\n config._ensure_unconfigure()\n return 0\n\n\npytest_cmdline_main.tryfirst = True\n\n\ndef deselect_by_keyword(items, config):\n keywordexpr = config.option.keyword.lstrip()\n if not keywordexpr:\n return\n\n if keywordexpr.startswith(\"-\"):\n keywordexpr = \"not \" + keywordexpr[1:]\n selectuntil = False\n if keywordexpr[-1:] == \":\":\n selectuntil = True\n keywordexpr = keywordexpr[:-1]\n\n remaining = []\n deselected = []\n for colitem in items:\n if keywordexpr and not matchkeyword(colitem, keywordexpr):\n deselected.append(colitem)\n else:\n if selectuntil:\n keywordexpr = None\n remaining.append(colitem)\n\n if deselected:\n config.hook.pytest_deselected(items=deselected)\n items[:] = remaining\n\n\ndef deselect_by_mark(items, config):\n matchexpr = config.option.markexpr\n if not matchexpr:\n return\n\n remaining = []\n deselected = []\n for item in items:\n if matchmark(item, matchexpr):\n remaining.append(item)\n else:\n deselected.append(item)\n\n if deselected:\n config.hook.pytest_deselected(items=deselected)\n items[:] = remaining\n\n\ndef pytest_collection_modifyitems(items, config):\n deselect_by_keyword(items, config)\n deselect_by_mark(items, config)\n\n\ndef pytest_configure(config):\n config._old_mark_config = MARK_GEN._config\n MARK_GEN._config = config\n\n empty_parameterset = config.getini(EMPTY_PARAMETERSET_OPTION)\n\n if empty_parameterset not in (\"skip\", \"xfail\", \"fail_at_collect\", None, \"\"):\n raise UsageError(\n \"{!s} must be one of skip, xfail or fail_at_collect\"\n \" but it is {!r}\".format(EMPTY_PARAMETERSET_OPTION, empty_parameterset)\n )\n\n\ndef pytest_unconfigure(config):\n MARK_GEN._config = getattr(config, \"_old_mark_config\", None)\n"},{"col":0,"comment":"null","endLoc":189,"header":"def test_cache_reportheader_external_abspath(testdir, tmpdir_factory)","id":4529,"name":"test_cache_reportheader_external_abspath","nodeType":"Function","startLoc":166,"text":"def test_cache_reportheader_external_abspath(testdir, tmpdir_factory):\n external_cache = tmpdir_factory.mktemp(\n \"test_cache_reportheader_external_abspath_abs\"\n )\n\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n pass\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n cache_dir = {abscache}\n \"\"\".format(\n abscache=external_cache\n )\n )\n\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n [\"cachedir: {abscache}\".format(abscache=external_cache)]\n )"},{"col":0,"comment":"Tries to match given keyword expression to given collector item.\n\n Will match on the name of colitem, including the names of its parents.\n Only matches names of items which are either a :class:`Class` or a\n :class:`Function`.\n Additionally, matches on names in the 'extra_keyword_matches' set of\n any item, as well as names directly assigned to test functions.\n ","endLoc":103,"header":"def matchkeyword(colitem, keywordexpr)","id":4530,"name":"matchkeyword","nodeType":"Function","startLoc":78,"text":"def matchkeyword(colitem, keywordexpr):\n \"\"\"Tries to match given keyword expression to given collector item.\n\n Will match on the name of colitem, including the names of its parents.\n Only matches names of items which are either a :class:`Class` or a\n :class:`Function`.\n Additionally, matches on names in the 'extra_keyword_matches' set of\n any item, as well as names directly assigned to test functions.\n \"\"\"\n mapping = KeywordMapping.from_item(colitem)\n if \" \" not in keywordexpr:\n # special case to allow for simple \"-k pass\" and \"-k 1.3\"\n return mapping[keywordexpr]\n elif keywordexpr.startswith(\"not \") and \" \" not in keywordexpr[4:]:\n return not mapping[keywordexpr[4:]]\n for kwd in keywordexpr.split():\n if keyword.iskeyword(kwd) and kwd not in python_keywords_allowed_list:\n raise UsageError(\n \"Python keyword '{}' not accepted in expressions passed to '-k'\".format(\n kwd\n )\n )\n try:\n return eval(keywordexpr, {}, mapping)\n except SyntaxError:\n raise UsageError(\"Wrong expression passed to '-k': {}\".format(keywordexpr))"},{"col":4,"comment":"null","endLoc":399,"header":"def test_exit_propagates(self, testdir)","id":4531,"name":"test_exit_propagates","nodeType":"Function","startLoc":387,"text":"def test_exit_propagates(self, testdir):\n try:\n testdir.runitem(\n \"\"\"\n import pytest\n def test_func():\n raise pytest.exit.Exception()\n \"\"\"\n )\n except pytest.exit.Exception:\n pass\n else:\n pytest.fail(\"did not raise\")"},{"className":"TestExecutionNonForked","col":0,"comment":"null","endLoc":420,"id":4532,"nodeType":"Class","startLoc":402,"text":"class TestExecutionNonForked(BaseFunctionalTests):\n def getrunner(self):\n def f(item):\n return runner.runtestprotocol(item, log=False)\n\n return f\n\n def test_keyboardinterrupt_propagates(self, testdir):\n try:\n testdir.runitem(\n \"\"\"\n def test_func():\n raise KeyboardInterrupt(\"fake\")\n \"\"\"\n )\n except KeyboardInterrupt:\n pass\n else:\n pytest.fail(\"did not raise\")"},{"col":4,"comment":"null","endLoc":407,"header":"def getrunner(self)","id":4533,"name":"getrunner","nodeType":"Function","startLoc":403,"text":"def getrunner(self):\n def f(item):\n return runner.runtestprotocol(item, log=False)\n\n return f"},{"attributeType":"function | function | function","col":4,"comment":"null","endLoc":130,"id":4534,"name":"TemporaryFile","nodeType":"Attribute","startLoc":130,"text":"TemporaryFile"},{"col":4,"comment":"null","endLoc":420,"header":"def test_keyboardinterrupt_propagates(self, testdir)","id":4535,"name":"test_keyboardinterrupt_propagates","nodeType":"Function","startLoc":409,"text":"def test_keyboardinterrupt_propagates(self, testdir):\n try:\n testdir.runitem(\n \"\"\"\n def test_func():\n raise KeyboardInterrupt(\"fake\")\n \"\"\"\n )\n except KeyboardInterrupt:\n pass\n else:\n pytest.fail(\"did not raise\")"},{"col":4,"comment":"null","endLoc":58,"header":"@classmethod\n def from_item(cls, item)","id":4536,"name":"from_item","nodeType":"Function","startLoc":37,"text":"@classmethod\n def from_item(cls, item):\n mapped_names = set()\n\n # Add the names of the current item and any parent items\n import pytest\n\n for item in item.listchain():\n if not isinstance(item, pytest.Instance):\n mapped_names.add(item.name)\n\n # Add the names added as extra keywords to current or parent items\n mapped_names.update(item.listextrakeywords())\n\n # Add the names attached to the current function through direct assignment\n if hasattr(item, \"function\"):\n mapped_names.update(item.function.__dict__)\n\n # add the markers to the keywords as we no longer handle them correctly\n mapped_names.update(mark.name for mark in item.iter_markers())\n\n return cls(mapped_names)"},{"className":"TestExecutionForked","col":0,"comment":"null","endLoc":441,"id":4537,"nodeType":"Class","startLoc":423,"text":"class TestExecutionForked(BaseFunctionalTests):\n pytestmark = pytest.mark.skipif(\"not hasattr(os, 'fork')\")\n\n def getrunner(self):\n # XXX re-arrange this test to live in pytest-xdist\n boxed = pytest.importorskip(\"xdist.boxed\")\n return boxed.forked_run_report\n\n def test_suicide(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n import os\n os.kill(os.getpid(), 15)\n \"\"\"\n )\n rep = reports[0]\n assert rep.failed\n assert rep.when == \"???\""},{"col":4,"comment":"null","endLoc":429,"header":"def getrunner(self)","id":4538,"name":"getrunner","nodeType":"Function","startLoc":426,"text":"def getrunner(self):\n # XXX re-arrange this test to live in pytest-xdist\n boxed = pytest.importorskip(\"xdist.boxed\")\n return boxed.forked_run_report"},{"col":4,"comment":"null","endLoc":441,"header":"def test_suicide(self, testdir)","id":4539,"name":"test_suicide","nodeType":"Function","startLoc":431,"text":"def test_suicide(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n import os\n os.kill(os.getpid(), 15)\n \"\"\"\n )\n rep = reports[0]\n assert rep.failed\n assert rep.when == \"???\""},{"attributeType":"null","col":4,"comment":"null","endLoc":424,"id":4540,"name":"pytestmark","nodeType":"Attribute","startLoc":424,"text":"pytestmark"},{"className":"TestSessionReports","col":0,"comment":"null","endLoc":465,"id":4541,"nodeType":"Class","startLoc":444,"text":"class TestSessionReports(object):\n def test_collect_result(self, testdir):\n col = testdir.getmodulecol(\n \"\"\"\n def test_func1():\n pass\n class TestClass(object):\n pass\n \"\"\"\n )\n rep = runner.collect_one_node(col)\n assert not rep.failed\n assert not rep.skipped\n assert rep.passed\n locinfo = rep.location\n assert locinfo[0] == col.fspath.basename\n assert not locinfo[1]\n assert locinfo[2] == col.fspath.basename\n res = rep.result\n assert len(res) == 2\n assert res[0].name == \"test_func1\"\n assert res[1].name == \"TestClass\""},{"col":4,"comment":"null","endLoc":465,"header":"def test_collect_result(self, testdir)","id":4542,"name":"test_collect_result","nodeType":"Function","startLoc":445,"text":"def test_collect_result(self, testdir):\n col = testdir.getmodulecol(\n \"\"\"\n def test_func1():\n pass\n class TestClass(object):\n pass\n \"\"\"\n )\n rep = runner.collect_one_node(col)\n assert not rep.failed\n assert not rep.skipped\n assert rep.passed\n locinfo = rep.location\n assert locinfo[0] == col.fspath.basename\n assert not locinfo[1]\n assert locinfo[2] == col.fspath.basename\n res = rep.result\n assert len(res) == 2\n assert res[0].name == \"test_func1\"\n assert res[1].name == \"TestClass\""},{"col":0,"comment":"null","endLoc":241,"header":"def test_cache_show(testdir)","id":4543,"name":"test_cache_show","nodeType":"Function","startLoc":192,"text":"def test_cache_show(testdir):\n result = testdir.runpytest(\"--cache-show\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*cache is empty*\"])\n testdir.makeconftest(\n \"\"\"\n def pytest_configure(config):\n config.cache.set(\"my/name\", [1,2,3])\n config.cache.set(\"my/hello\", \"world\")\n config.cache.set(\"other/some\", {1:2})\n dp = config.cache.makedir(\"mydb\")\n dp.ensure(\"hello\")\n dp.ensure(\"world\")\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 5 # no tests executed\n\n result = testdir.runpytest(\"--cache-show\")\n result.stdout.fnmatch_lines(\n [\n \"*cachedir:*\",\n \"*- cache values for '[*]' -*\",\n \"cache/nodeids contains:\",\n \"my/name contains:\",\n \" [1, 2, 3]\",\n \"other/some contains:\",\n \" {*'1': 2}\",\n \"*- cache directories for '[*]' -*\",\n \"*mydb/hello*length 0*\",\n \"*mydb/world*length 0*\",\n ]\n )\n assert result.ret == 0\n\n result = testdir.runpytest(\"--cache-show\", \"*/hello\")\n result.stdout.fnmatch_lines(\n [\n \"*cachedir:*\",\n \"*- cache values for '[*]/hello' -*\",\n \"my/hello contains:\",\n \" *'world'\",\n \"*- cache directories for '[*]/hello' -*\",\n \"d/mydb/hello*length 0*\",\n ]\n )\n stdout = result.stdout.str()\n assert \"other/some\" not in stdout\n assert \"d/mydb/world\" not in stdout\n assert result.ret == 0"},{"className":"TestReportContents","col":0,"comment":"\n Test user-level API of ``TestReport`` objects.\n ","endLoc":1004,"id":4544,"nodeType":"Class","startLoc":936,"text":"class TestReportContents(object):\n \"\"\"\n Test user-level API of ``TestReport`` objects.\n \"\"\"\n\n def getrunner(self):\n return lambda item: runner.runtestprotocol(item, log=False)\n\n def test_longreprtext_pass(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n rep = reports[1]\n assert rep.longreprtext == \"\"\n\n def test_longreprtext_failure(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n x = 1\n assert x == 4\n \"\"\"\n )\n rep = reports[1]\n assert \"assert 1 == 4\" in rep.longreprtext\n\n def test_captured_text(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n import pytest\n import sys\n\n @pytest.fixture\n def fix():\n sys.stdout.write('setup: stdout\\\\n')\n sys.stderr.write('setup: stderr\\\\n')\n yield\n sys.stdout.write('teardown: stdout\\\\n')\n sys.stderr.write('teardown: stderr\\\\n')\n assert 0\n\n def test_func(fix):\n sys.stdout.write('call: stdout\\\\n')\n sys.stderr.write('call: stderr\\\\n')\n assert 0\n \"\"\"\n )\n setup, call, teardown = reports\n assert setup.capstdout == \"setup: stdout\\n\"\n assert call.capstdout == \"setup: stdout\\ncall: stdout\\n\"\n assert teardown.capstdout == \"setup: stdout\\ncall: stdout\\nteardown: stdout\\n\"\n\n assert setup.capstderr == \"setup: stderr\\n\"\n assert call.capstderr == \"setup: stderr\\ncall: stderr\\n\"\n assert teardown.capstderr == \"setup: stderr\\ncall: stderr\\nteardown: stderr\\n\"\n\n def test_no_captured_text(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n rep = reports[1]\n assert rep.capstdout == \"\"\n assert rep.capstderr == \"\""},{"col":4,"comment":"null","endLoc":942,"header":"def getrunner(self)","id":4545,"name":"getrunner","nodeType":"Function","startLoc":941,"text":"def getrunner(self):\n return lambda item: runner.runtestprotocol(item, log=False)"},{"col":15,"endLoc":942,"id":4546,"nodeType":"Lambda","startLoc":942,"text":"lambda item: runner.runtestprotocol(item, log=False)"},{"col":4,"comment":"null","endLoc":952,"header":"def test_longreprtext_pass(self, testdir)","id":4547,"name":"test_longreprtext_pass","nodeType":"Function","startLoc":944,"text":"def test_longreprtext_pass(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n rep = reports[1]\n assert rep.longreprtext == \"\""},{"col":4,"comment":"null","endLoc":963,"header":"def test_longreprtext_failure(self, testdir)","id":4548,"name":"test_longreprtext_failure","nodeType":"Function","startLoc":954,"text":"def test_longreprtext_failure(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n x = 1\n assert x == 4\n \"\"\"\n )\n rep = reports[1]\n assert \"assert 1 == 4\" in rep.longreprtext"},{"col":4,"comment":"null","endLoc":993,"header":"def test_captured_text(self, testdir)","id":4549,"name":"test_captured_text","nodeType":"Function","startLoc":965,"text":"def test_captured_text(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n import pytest\n import sys\n\n @pytest.fixture\n def fix():\n sys.stdout.write('setup: stdout\\\\n')\n sys.stderr.write('setup: stderr\\\\n')\n yield\n sys.stdout.write('teardown: stdout\\\\n')\n sys.stderr.write('teardown: stderr\\\\n')\n assert 0\n\n def test_func(fix):\n sys.stdout.write('call: stdout\\\\n')\n sys.stderr.write('call: stderr\\\\n')\n assert 0\n \"\"\"\n )\n setup, call, teardown = reports\n assert setup.capstdout == \"setup: stdout\\n\"\n assert call.capstdout == \"setup: stdout\\ncall: stdout\\n\"\n assert teardown.capstdout == \"setup: stdout\\ncall: stdout\\nteardown: stdout\\n\"\n\n assert setup.capstderr == \"setup: stderr\\n\"\n assert call.capstderr == \"setup: stderr\\ncall: stderr\\n\"\n assert teardown.capstderr == \"setup: stderr\\ncall: stderr\\nteardown: stderr\\n\""},{"col":4,"comment":"null","endLoc":144,"header":"@overload\n def TemporaryFile(\n mode: OpenTextMode,\n buffering: int = -1,\n encoding: str | None = None,\n newline: str | None = None,\n suffix: AnyStr | None = None,\n prefix: AnyStr | None = None,\n dir: GenericPath[AnyStr] | None = None,\n *,\n errors: str | None = None,\n ) -> io.TextIOWrapper","id":4550,"name":"TemporaryFile","nodeType":"Function","startLoc":133,"text":"@overload\n def TemporaryFile(\n mode: OpenTextMode,\n buffering: int = -1,\n encoding: str | None = None,\n newline: str | None = None,\n suffix: AnyStr | None = None,\n prefix: AnyStr | None = None,\n dir: GenericPath[AnyStr] | None = None,\n *,\n errors: str | None = None,\n ) -> io.TextIOWrapper: ..."},{"col":4,"comment":"null","endLoc":156,"header":"@overload\n def TemporaryFile(\n mode: OpenBinaryMode,\n buffering: Literal[0],\n encoding: str | None = None,\n newline: str | None = None,\n suffix: AnyStr | None = None,\n prefix: AnyStr | None = None,\n dir: GenericPath[AnyStr] | None = None,\n *,\n errors: str | None = None,\n ) -> io.FileIO","id":4551,"name":"TemporaryFile","nodeType":"Function","startLoc":145,"text":"@overload\n def TemporaryFile(\n mode: OpenBinaryMode,\n buffering: Literal[0],\n encoding: str | None = None,\n newline: str | None = None,\n suffix: AnyStr | None = None,\n prefix: AnyStr | None = None,\n dir: GenericPath[AnyStr] | None = None,\n *,\n errors: str | None = None,\n ) -> io.FileIO: ..."},{"col":4,"comment":"null","endLoc":167,"header":"@overload\n def TemporaryFile(\n *,\n buffering: Literal[0],\n encoding: str | None = None,\n newline: str | None = None,\n suffix: AnyStr | None = None,\n prefix: AnyStr | None = None,\n dir: GenericPath[AnyStr] | None = None,\n errors: str | None = None,\n ) -> io.FileIO","id":4552,"name":"TemporaryFile","nodeType":"Function","startLoc":157,"text":"@overload\n def TemporaryFile(\n *,\n buffering: Literal[0],\n encoding: str | None = None,\n newline: str | None = None,\n suffix: AnyStr | None = None,\n prefix: AnyStr | None = None,\n dir: GenericPath[AnyStr] | None = None,\n errors: str | None = None,\n ) -> io.FileIO: ..."},{"col":4,"comment":"null","endLoc":179,"header":"@overload\n def TemporaryFile(\n mode: OpenBinaryModeWriting,\n buffering: Literal[-1, 1] = -1,\n encoding: str | None = None,\n newline: str | None = None,\n suffix: AnyStr | None = None,\n prefix: AnyStr | None = None,\n dir: GenericPath[AnyStr] | None = None,\n *,\n errors: str | None = None,\n ) -> io.BufferedWriter","id":4553,"name":"TemporaryFile","nodeType":"Function","startLoc":168,"text":"@overload\n def TemporaryFile(\n mode: OpenBinaryModeWriting,\n buffering: Literal[-1, 1] = -1,\n encoding: str | None = None,\n newline: str | None = None,\n suffix: AnyStr | None = None,\n prefix: AnyStr | None = None,\n dir: GenericPath[AnyStr] | None = None,\n *,\n errors: str | None = None,\n ) -> io.BufferedWriter: ..."},{"col":4,"comment":"null","endLoc":191,"header":"@overload\n def TemporaryFile(\n mode: OpenBinaryModeReading,\n buffering: Literal[-1, 1] = -1,\n encoding: str | None = None,\n newline: str | None = None,\n suffix: AnyStr | None = None,\n prefix: AnyStr | None = None,\n dir: GenericPath[AnyStr] | None = None,\n *,\n errors: str | None = None,\n ) -> io.BufferedReader","id":4554,"name":"TemporaryFile","nodeType":"Function","startLoc":180,"text":"@overload\n def TemporaryFile(\n mode: OpenBinaryModeReading,\n buffering: Literal[-1, 1] = -1,\n encoding: str | None = None,\n newline: str | None = None,\n suffix: AnyStr | None = None,\n prefix: AnyStr | None = None,\n dir: GenericPath[AnyStr] | None = None,\n *,\n errors: str | None = None,\n ) -> io.BufferedReader: ..."},{"col":4,"comment":"null","endLoc":203,"header":"@overload\n def TemporaryFile(\n mode: OpenBinaryModeUpdating = \"w+b\",\n buffering: Literal[-1, 1] = -1,\n encoding: str | None = None,\n newline: str | None = None,\n suffix: AnyStr | None = None,\n prefix: AnyStr | None = None,\n dir: GenericPath[AnyStr] | None = None,\n *,\n errors: str | None = None,\n ) -> io.BufferedRandom","id":4555,"name":"TemporaryFile","nodeType":"Function","startLoc":192,"text":"@overload\n def TemporaryFile(\n mode: OpenBinaryModeUpdating = \"w+b\",\n buffering: Literal[-1, 1] = -1,\n encoding: str | None = None,\n newline: str | None = None,\n suffix: AnyStr | None = None,\n prefix: AnyStr | None = None,\n dir: GenericPath[AnyStr] | None = None,\n *,\n errors: str | None = None,\n ) -> io.BufferedRandom: ..."},{"col":4,"comment":"null","endLoc":215,"header":"@overload\n def TemporaryFile(\n mode: str = \"w+b\",\n buffering: int = -1,\n encoding: str | None = None,\n newline: str | None = None,\n suffix: AnyStr | None = None,\n prefix: AnyStr | None = None,\n dir: GenericPath[AnyStr] | None = None,\n *,\n errors: str | None = None,\n ) -> IO[Any]","id":4556,"name":"TemporaryFile","nodeType":"Function","startLoc":204,"text":"@overload\n def TemporaryFile(\n mode: str = \"w+b\",\n buffering: int = -1,\n encoding: str | None = None,\n newline: str | None = None,\n suffix: AnyStr | None = None,\n prefix: AnyStr | None = None,\n dir: GenericPath[AnyStr] | None = None,\n *,\n errors: str | None = None,\n ) -> IO[Any]: ..."},{"col":0,"comment":"Ensure we automatically create .gitignore file in the pytest_cache directory (#3286).","endLoc":1044,"header":"def test_gitignore(testdir)","id":4557,"name":"test_gitignore","nodeType":"Function","startLoc":1030,"text":"def test_gitignore(testdir):\n \"\"\"Ensure we automatically create .gitignore file in the pytest_cache directory (#3286).\"\"\"\n from _pytest.cacheprovider import Cache\n\n config = testdir.parseconfig()\n cache = Cache.for_config(config)\n cache.set(\"foo\", \"bar\")\n msg = \"# Created by pytest automatically.\\n*\"\n gitignore_path = cache._cachedir.joinpath(\".gitignore\")\n assert gitignore_path.read_text(encoding=\"UTF-8\") == msg\n\n # Does not overwrite existing/custom one.\n gitignore_path.write_text(u\"custom\")\n cache.set(\"something\", \"else\")\n assert gitignore_path.read_text(encoding=\"UTF-8\") == \"custom\""},{"className":"CaptureManager","col":0,"comment":"\n Capture plugin, manages that the appropriate capture method is enabled/disabled during collection and each\n test phase (setup, call, teardown). After each of those points, the captured output is obtained and\n attached to the collection/runtest report.\n\n There are two levels of capture:\n * global: which is enabled by default and can be suppressed by the ``-s`` option. This is always enabled/disabled\n during collection and each test phase.\n * fixture: when a test function or one of its fixture depend on the ``capsys`` or ``capfd`` fixtures. In this\n case special handling is needed to ensure the fixtures take precedence over the global capture.\n ","endLoc":248,"id":4558,"nodeType":"Class","startLoc":70,"text":"class CaptureManager(object):\n \"\"\"\n Capture plugin, manages that the appropriate capture method is enabled/disabled during collection and each\n test phase (setup, call, teardown). After each of those points, the captured output is obtained and\n attached to the collection/runtest report.\n\n There are two levels of capture:\n * global: which is enabled by default and can be suppressed by the ``-s`` option. This is always enabled/disabled\n during collection and each test phase.\n * fixture: when a test function or one of its fixture depend on the ``capsys`` or ``capfd`` fixtures. In this\n case special handling is needed to ensure the fixtures take precedence over the global capture.\n \"\"\"\n\n def __init__(self, method):\n self._method = method\n self._global_capturing = None\n self._current_item = None\n\n def __repr__(self):\n return \"\" % (\n self._method,\n self._global_capturing,\n self._current_item,\n )\n\n def _getcapture(self, method):\n if method == \"fd\":\n return MultiCapture(out=True, err=True, Capture=FDCapture)\n elif method == \"sys\":\n return MultiCapture(out=True, err=True, Capture=SysCapture)\n elif method == \"no\":\n return MultiCapture(out=False, err=False, in_=False)\n raise ValueError(\"unknown capturing method: %r\" % method) # pragma: no cover\n\n def is_capturing(self):\n if self.is_globally_capturing():\n return \"global\"\n capture_fixture = getattr(self._current_item, \"_capture_fixture\", None)\n if capture_fixture is not None:\n return (\n \"fixture %s\" % self._current_item._capture_fixture.request.fixturename\n )\n return False\n\n # Global capturing control\n\n def is_globally_capturing(self):\n return self._method != \"no\"\n\n def start_global_capturing(self):\n assert self._global_capturing is None\n self._global_capturing = self._getcapture(self._method)\n self._global_capturing.start_capturing()\n\n def stop_global_capturing(self):\n if self._global_capturing is not None:\n self._global_capturing.pop_outerr_to_orig()\n self._global_capturing.stop_capturing()\n self._global_capturing = None\n\n def resume_global_capture(self):\n # During teardown of the python process, and on rare occasions, capture\n # attributes can be `None` while trying to resume global capture.\n if self._global_capturing is not None:\n self._global_capturing.resume_capturing()\n\n def suspend_global_capture(self, in_=False):\n cap = getattr(self, \"_global_capturing\", None)\n if cap is not None:\n cap.suspend_capturing(in_=in_)\n\n def suspend(self, in_=False):\n # Need to undo local capsys-et-al if it exists before disabling global capture.\n self.suspend_fixture(self._current_item)\n self.suspend_global_capture(in_)\n\n def resume(self):\n self.resume_global_capture()\n self.resume_fixture(self._current_item)\n\n def read_global_capture(self):\n return self._global_capturing.readouterr()\n\n # Fixture Control (it's just forwarding, think about removing this later)\n\n def activate_fixture(self, item):\n \"\"\"If the current item is using ``capsys`` or ``capfd``, activate them so they take precedence over\n the global capture.\n \"\"\"\n fixture = getattr(item, \"_capture_fixture\", None)\n if fixture is not None:\n fixture._start()\n\n def deactivate_fixture(self, item):\n \"\"\"Deactivates the ``capsys`` or ``capfd`` fixture of this item, if any.\"\"\"\n fixture = getattr(item, \"_capture_fixture\", None)\n if fixture is not None:\n fixture.close()\n\n def suspend_fixture(self, item):\n fixture = getattr(item, \"_capture_fixture\", None)\n if fixture is not None:\n fixture._suspend()\n\n def resume_fixture(self, item):\n fixture = getattr(item, \"_capture_fixture\", None)\n if fixture is not None:\n fixture._resume()\n\n # Helper context managers\n\n @contextlib.contextmanager\n def global_and_fixture_disabled(self):\n \"\"\"Context manager to temporarily disable global and current fixture capturing.\"\"\"\n self.suspend()\n try:\n yield\n finally:\n self.resume()\n\n @contextlib.contextmanager\n def item_capture(self, when, item):\n self.resume_global_capture()\n self.activate_fixture(item)\n try:\n yield\n finally:\n self.deactivate_fixture(item)\n self.suspend_global_capture(in_=False)\n\n out, err = self.read_global_capture()\n item.add_report_section(when, \"stdout\", out)\n item.add_report_section(when, \"stderr\", err)\n\n # Hooks\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_make_collect_report(self, collector):\n if isinstance(collector, pytest.File):\n self.resume_global_capture()\n outcome = yield\n self.suspend_global_capture()\n out, err = self.read_global_capture()\n rep = outcome.get_result()\n if out:\n rep.sections.append((\"Captured stdout\", out))\n if err:\n rep.sections.append((\"Captured stderr\", err))\n else:\n yield\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_protocol(self, item):\n self._current_item = item\n yield\n self._current_item = None\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_setup(self, item):\n with self.item_capture(\"setup\", item):\n yield\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_call(self, item):\n with self.item_capture(\"call\", item):\n yield\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_teardown(self, item):\n with self.item_capture(\"teardown\", item):\n yield\n\n @pytest.hookimpl(tryfirst=True)\n def pytest_keyboard_interrupt(self, excinfo):\n self.stop_global_capturing()\n\n @pytest.hookimpl(tryfirst=True)\n def pytest_internalerror(self, excinfo):\n self.stop_global_capturing()"},{"col":4,"comment":"null","endLoc":86,"header":"def __init__(self, method)","id":4559,"name":"__init__","nodeType":"Function","startLoc":83,"text":"def __init__(self, method):\n self._method = method\n self._global_capturing = None\n self._current_item = None"},{"col":4,"comment":"null","endLoc":93,"header":"def __repr__(self)","id":4560,"name":"__repr__","nodeType":"Function","startLoc":88,"text":"def __repr__(self):\n return \"\" % (\n self._method,\n self._global_capturing,\n self._current_item,\n )"},{"col":4,"comment":"null","endLoc":102,"header":"def _getcapture(self, method)","id":4561,"name":"_getcapture","nodeType":"Function","startLoc":95,"text":"def _getcapture(self, method):\n if method == \"fd\":\n return MultiCapture(out=True, err=True, Capture=FDCapture)\n elif method == \"sys\":\n return MultiCapture(out=True, err=True, Capture=SysCapture)\n elif method == \"no\":\n return MultiCapture(out=False, err=False, in_=False)\n raise ValueError(\"unknown capturing method: %r\" % method) # pragma: no cover"},{"col":0,"comment":"null","endLoc":132,"header":"def pytest_runtest_call(item)","id":4562,"name":"pytest_runtest_call","nodeType":"Function","startLoc":119,"text":"def pytest_runtest_call(item):\n _update_current_test_var(item, \"call\")\n sys.last_type, sys.last_value, sys.last_traceback = (None, None, None)\n try:\n item.runtest()\n except Exception:\n # Store trace info to allow postmortem debugging\n type, value, tb = sys.exc_info()\n tb = tb.tb_next # Skip *this* frame\n sys.last_type = type\n sys.last_value = value\n sys.last_traceback = tb\n del type, value, tb # Get rid of these in this frame\n raise"},{"col":0,"comment":"null","endLoc":138,"header":"def pytest_runtest_teardown(item, nextitem)","id":4564,"name":"pytest_runtest_teardown","nodeType":"Function","startLoc":135,"text":"def pytest_runtest_teardown(item, nextitem):\n _update_current_test_var(item, \"teardown\")\n item.session._setupstate.teardown_exact(item, nextitem)\n _update_current_test_var(item, None)"},{"col":4,"comment":"null","endLoc":473,"header":"def __init__(self, out=True, err=True, in_=True, Capture=None)","id":4565,"name":"__init__","nodeType":"Function","startLoc":467,"text":"def __init__(self, out=True, err=True, in_=True, Capture=None):\n if in_:\n self.in_ = Capture(0)\n if out:\n self.out = Capture(1)\n if err:\n self.err = Capture(2)"},{"col":0,"comment":"null","endLoc":165,"header":"def pytest_report_teststatus(report)","id":4566,"name":"pytest_report_teststatus","nodeType":"Function","startLoc":157,"text":"def pytest_report_teststatus(report):\n if report.when in (\"setup\", \"teardown\"):\n if report.failed:\n # category, shortletter, verbose-word\n return \"error\", \"E\", \"ERROR\"\n elif report.skipped:\n return \"skipped\", \"s\", \"SKIPPED\"\n else:\n return \"\", \"\", \"\""},{"col":0,"comment":"null","endLoc":249,"header":"def pytest_runtest_makereport(item, call)","id":4567,"name":"pytest_runtest_makereport","nodeType":"Function","startLoc":248,"text":"def pytest_runtest_makereport(item, call):\n return TestReport.from_item_and_call(item, call)"},{"col":0,"comment":"null","endLoc":275,"header":"def pytest_make_collect_report(collector)","id":4568,"name":"pytest_make_collect_report","nodeType":"Function","startLoc":252,"text":"def pytest_make_collect_report(collector):\n call = CallInfo.from_call(lambda: list(collector.collect()), \"collect\")\n longrepr = None\n if not call.excinfo:\n outcome = \"passed\"\n else:\n from _pytest import nose\n\n skip_exceptions = (Skipped,) + nose.get_skip_exceptions()\n if call.excinfo.errisinstance(skip_exceptions):\n outcome = \"skipped\"\n r = collector._repr_failure_py(call.excinfo, \"line\").reprcrash\n longrepr = (str(r.path), r.lineno, r.message)\n else:\n outcome = \"failed\"\n errorinfo = collector.repr_failure(call.excinfo)\n if not hasattr(errorinfo, \"toterminal\"):\n errorinfo = CollectErrorRepr(errorinfo)\n longrepr = errorinfo\n rep = CollectReport(\n collector.nodeid, outcome, longrepr, getattr(call, \"result\", None)\n )\n rep.call = call # see collect_one_node\n return rep"},{"col":4,"comment":"null","endLoc":112,"header":"def is_capturing(self)","id":4569,"name":"is_capturing","nodeType":"Function","startLoc":104,"text":"def is_capturing(self):\n if self.is_globally_capturing():\n return \"global\"\n capture_fixture = getattr(self._current_item, \"_capture_fixture\", None)\n if capture_fixture is not None:\n return (\n \"fixture %s\" % self._current_item._capture_fixture.request.fixturename\n )\n return False"},{"col":4,"comment":"null","endLoc":56,"header":"@classmethod\n def for_config(cls, config)","id":4570,"name":"for_config","nodeType":"Function","startLoc":50,"text":"@classmethod\n def for_config(cls, config):\n cachedir = cls.cache_dir_from_config(config)\n if config.getoption(\"cacheclear\") and cachedir.exists():\n rm_rf(cachedir)\n cachedir.mkdir()\n return cls(cachedir, config)"},{"col":4,"comment":"null","endLoc":35,"header":"def __init__(self, names)","id":4571,"name":"__init__","nodeType":"Function","startLoc":34,"text":"def __init__(self, names):\n self._names = names"},{"col":4,"comment":"null","endLoc":73,"header":"def toxml(self)","id":4573,"name":"toxml","nodeType":"Function","startLoc":72,"text":"def toxml(self):\n return self.__node.toxml()"},{"col":4,"comment":"null","endLoc":77,"header":"@property\n def text(self)","id":4574,"name":"text","nodeType":"Function","startLoc":75,"text":"@property\n def text(self):\n return self.__node.childNodes[0].wholeText"},{"col":4,"comment":"null","endLoc":81,"header":"@property\n def tag(self)","id":4575,"name":"tag","nodeType":"Function","startLoc":79,"text":"@property\n def tag(self):\n return self.__node.tagName"},{"col":4,"comment":"null","endLoc":85,"header":"@property\n def next_siebling(self)","id":4576,"name":"next_siebling","nodeType":"Function","startLoc":83,"text":"@property\n def next_siebling(self):\n return type(self)(self.__node.nextSibling)"},{"col":30,"endLoc":253,"id":4577,"nodeType":"Lambda","startLoc":253,"text":"lambda: list(collector.collect())"},{"attributeType":"null","col":8,"comment":"null","endLoc":39,"id":4578,"name":"__node","nodeType":"Attribute","startLoc":39,"text":"self.__node"},{"className":"TestPython","col":0,"comment":"null","endLoc":692,"id":4579,"nodeType":"Class","startLoc":88,"text":"class TestPython(object):\n def test_summing_simple(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_pass():\n pass\n def test_fail():\n assert 0\n def test_skip():\n pytest.skip(\"\")\n @pytest.mark.xfail\n def test_xfail():\n assert 0\n @pytest.mark.xfail\n def test_xpass():\n assert 1\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(name=\"pytest\", errors=0, failures=1, skipped=2, tests=5)\n\n def test_summing_simple_with_errors(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def fixture():\n raise Exception()\n def test_pass():\n pass\n def test_fail():\n assert 0\n def test_error(fixture):\n pass\n @pytest.mark.xfail\n def test_xfail():\n assert False\n @pytest.mark.xfail(strict=True)\n def test_xpass():\n assert True\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(name=\"pytest\", errors=1, failures=2, skipped=1, tests=5)\n\n def test_timing_function(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import time, pytest\n def setup_module():\n time.sleep(0.01)\n def teardown_module():\n time.sleep(0.01)\n def test_sleep():\n time.sleep(0.01)\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n val = tnode[\"time\"]\n assert round(float(val), 2) >= 0.03\n\n @pytest.mark.parametrize(\"duration_report\", [\"call\", \"total\"])\n def test_junit_duration_report(self, testdir, monkeypatch, duration_report):\n\n # mock LogXML.node_reporter so it always sets a known duration to each test report object\n original_node_reporter = LogXML.node_reporter\n\n def node_reporter_wrapper(s, report):\n report.duration = 1.0\n reporter = original_node_reporter(s, report)\n return reporter\n\n monkeypatch.setattr(LogXML, \"node_reporter\", node_reporter_wrapper)\n\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n pass\n \"\"\"\n )\n result, dom = runandparse(\n testdir, \"-o\", \"junit_duration_report={}\".format(duration_report)\n )\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n val = float(tnode[\"time\"])\n if duration_report == \"total\":\n assert val == 3.0\n else:\n assert duration_report == \"call\"\n assert val == 1.0\n\n def test_setup_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def arg(request):\n raise ValueError()\n def test_function(arg):\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(errors=1, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_setup_error\", name=\"test_function\")\n fnode = tnode.find_first_by_tag(\"error\")\n fnode.assert_attr(message=\"test setup failure\")\n assert \"ValueError\" in fnode.toxml()\n\n def test_teardown_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def arg():\n yield\n raise ValueError()\n def test_function(arg):\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_teardown_error\", name=\"test_function\")\n fnode = tnode.find_first_by_tag(\"error\")\n fnode.assert_attr(message=\"test teardown failure\")\n assert \"ValueError\" in fnode.toxml()\n\n def test_call_failure_teardown_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def arg():\n yield\n raise Exception(\"Teardown Exception\")\n def test_function(arg):\n raise Exception(\"Call Exception\")\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(errors=1, failures=1, tests=1)\n first, second = dom.find_by_tag(\"testcase\")\n if not first or not second or first == second:\n assert 0\n fnode = first.find_first_by_tag(\"failure\")\n fnode.assert_attr(message=\"Exception: Call Exception\")\n snode = second.find_first_by_tag(\"error\")\n snode.assert_attr(message=\"test teardown failure\")\n\n def test_skip_contains_name_reason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_skip():\n pytest.skip(\"hello23\")\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_skip_contains_name_reason\", name=\"test_skip\")\n snode = tnode.find_first_by_tag(\"skipped\")\n snode.assert_attr(type=\"pytest.skip\", message=\"hello23\")\n\n def test_mark_skip_contains_name_reason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip(reason=\"hello24\")\n def test_skip():\n assert True\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(\n classname=\"test_mark_skip_contains_name_reason\", name=\"test_skip\"\n )\n snode = tnode.find_first_by_tag(\"skipped\")\n snode.assert_attr(type=\"pytest.skip\", message=\"hello24\")\n\n def test_mark_skipif_contains_name_reason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n GLOBAL_CONDITION = True\n @pytest.mark.skipif(GLOBAL_CONDITION, reason=\"hello25\")\n def test_skip():\n assert True\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(\n classname=\"test_mark_skipif_contains_name_reason\", name=\"test_skip\"\n )\n snode = tnode.find_first_by_tag(\"skipped\")\n snode.assert_attr(type=\"pytest.skip\", message=\"hello25\")\n\n def test_mark_skip_doesnt_capture_output(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip(reason=\"foo\")\n def test_skip():\n print(\"bar!\")\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node_xml = dom.find_first_by_tag(\"testsuite\").toxml()\n assert \"bar!\" not in node_xml\n\n def test_classname_instance(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class TestClass(object):\n def test_method(self):\n assert 0\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(failures=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(\n classname=\"test_classname_instance.TestClass\", name=\"test_method\"\n )\n\n def test_classname_nested_dir(self, testdir):\n p = testdir.tmpdir.ensure(\"sub\", \"test_hello.py\")\n p.write(\"def test_func(): 0/0\")\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(failures=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"sub.test_hello\", name=\"test_func\")\n\n def test_internal_error(self, testdir):\n testdir.makeconftest(\"def pytest_runtest_protocol(): 0 / 0\")\n testdir.makepyfile(\"def test_function(): pass\")\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(errors=1, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"pytest\", name=\"internal\")\n fnode = tnode.find_first_by_tag(\"error\")\n fnode.assert_attr(message=\"internal error\")\n assert \"Division\" in fnode.toxml()\n\n @pytest.mark.parametrize(\"junit_logging\", [\"no\", \"system-out\", \"system-err\"])\n def test_failure_function(self, testdir, junit_logging):\n testdir.makepyfile(\n \"\"\"\n import logging\n import sys\n\n def test_fail():\n print(\"hello-stdout\")\n sys.stderr.write(\"hello-stderr\\\\n\")\n logging.info('info msg')\n logging.warning('warning msg')\n raise ValueError(42)\n \"\"\"\n )\n\n result, dom = runandparse(testdir, \"-o\", \"junit_logging=%s\" % junit_logging)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(failures=1, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_failure_function\", name=\"test_fail\")\n fnode = tnode.find_first_by_tag(\"failure\")\n fnode.assert_attr(message=\"ValueError: 42\")\n assert \"ValueError\" in fnode.toxml()\n systemout = fnode.next_siebling\n assert systemout.tag == \"system-out\"\n assert \"hello-stdout\" in systemout.toxml()\n assert \"info msg\" not in systemout.toxml()\n systemerr = systemout.next_siebling\n assert systemerr.tag == \"system-err\"\n assert \"hello-stderr\" in systemerr.toxml()\n assert \"info msg\" not in systemerr.toxml()\n\n if junit_logging == \"system-out\":\n assert \"warning msg\" in systemout.toxml()\n assert \"warning msg\" not in systemerr.toxml()\n elif junit_logging == \"system-err\":\n assert \"warning msg\" not in systemout.toxml()\n assert \"warning msg\" in systemerr.toxml()\n elif junit_logging == \"no\":\n assert \"warning msg\" not in systemout.toxml()\n assert \"warning msg\" not in systemerr.toxml()\n\n def test_failure_verbose_message(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n def test_fail():\n assert 0, \"An error\"\n \"\"\"\n )\n\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n fnode = tnode.find_first_by_tag(\"failure\")\n fnode.assert_attr(message=\"AssertionError: An error assert 0\")\n\n def test_failure_escape(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('arg1', \"<&'\", ids=\"<&'\")\n def test_func(arg1):\n print(arg1)\n assert 0\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(failures=3, tests=3)\n\n for index, char in enumerate(\"<&'\"):\n\n tnode = node.find_nth_by_tag(\"testcase\", index)\n tnode.assert_attr(\n classname=\"test_failure_escape\", name=\"test_func[%s]\" % char\n )\n sysout = tnode.find_first_by_tag(\"system-out\")\n text = sysout.text\n assert text == \"%s\\n\" % char\n\n def test_junit_prefixing(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_func():\n assert 0\n class TestHello(object):\n def test_hello(self):\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir, \"--junitprefix=xyz\")\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(failures=1, tests=2)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"xyz.test_junit_prefixing\", name=\"test_func\")\n tnode = node.find_nth_by_tag(\"testcase\", 1)\n tnode.assert_attr(\n classname=\"xyz.test_junit_prefixing.TestHello\", name=\"test_hello\"\n )\n\n def test_xfailure_function(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_xfail():\n pytest.xfail(\"42\")\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert not result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=1, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_xfailure_function\", name=\"test_xfail\")\n fnode = tnode.find_first_by_tag(\"skipped\")\n fnode.assert_attr(type=\"pytest.xfail\", message=\"42\")\n # assert \"ValueError\" in fnode.toxml()\n\n def test_xfailure_marker(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(reason=\"42\")\n def test_xfail():\n assert False\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert not result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=1, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_xfailure_marker\", name=\"test_xfail\")\n fnode = tnode.find_first_by_tag(\"skipped\")\n fnode.assert_attr(type=\"pytest.xfail\", message=\"42\")\n\n def test_xfail_captures_output_once(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n import pytest\n\n @pytest.mark.xfail()\n def test_fail():\n sys.stdout.write('XFAIL This is stdout')\n sys.stderr.write('XFAIL This is stderr')\n assert 0\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n assert len(tnode.find_by_tag(\"system-err\")) == 1\n assert len(tnode.find_by_tag(\"system-out\")) == 1\n\n def test_xfailure_xpass(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail\n def test_xpass():\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n # assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=0, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_xfailure_xpass\", name=\"test_xpass\")\n\n def test_xfailure_xpass_strict(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(strict=True, reason=\"This needs to fail!\")\n def test_xpass():\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n # assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=0, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_xfailure_xpass_strict\", name=\"test_xpass\")\n fnode = tnode.find_first_by_tag(\"failure\")\n fnode.assert_attr(message=\"[XPASS(strict)] This needs to fail!\")\n\n def test_collect_error(self, testdir):\n testdir.makepyfile(\"syntax error\")\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(errors=1, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n fnode = tnode.find_first_by_tag(\"error\")\n fnode.assert_attr(message=\"collection failure\")\n assert \"SyntaxError\" in fnode.toxml()\n\n def test_unicode(self, testdir):\n value = \"hx\\xc4\\x85\\xc4\\x87\\n\"\n testdir.makepyfile(\n \"\"\"\n # coding: latin1\n def test_hello():\n print(%r)\n assert 0\n \"\"\"\n % value\n )\n result, dom = runandparse(testdir)\n assert result.ret == 1\n tnode = dom.find_first_by_tag(\"testcase\")\n fnode = tnode.find_first_by_tag(\"failure\")\n if not sys.platform.startswith(\"java\"):\n assert \"hx\" in fnode.toxml()\n\n def test_assertion_binchars(self, testdir):\n \"\"\"this test did fail when the escaping wasnt strict\"\"\"\n testdir.makepyfile(\n \"\"\"\n\n M1 = '\\x01\\x02\\x03\\x04'\n M2 = '\\x01\\x02\\x03\\x05'\n\n def test_str_compare():\n assert M1 == M2\n \"\"\"\n )\n result, dom = runandparse(testdir)\n print(dom.toxml())\n\n def test_pass_captures_stdout(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_pass():\n print('hello-stdout')\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n pnode = node.find_first_by_tag(\"testcase\")\n systemout = pnode.find_first_by_tag(\"system-out\")\n assert \"hello-stdout\" in systemout.toxml()\n\n def test_pass_captures_stderr(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n def test_pass():\n sys.stderr.write('hello-stderr')\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n pnode = node.find_first_by_tag(\"testcase\")\n systemout = pnode.find_first_by_tag(\"system-err\")\n assert \"hello-stderr\" in systemout.toxml()\n\n def test_setup_error_captures_stdout(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def arg(request):\n print('hello-stdout')\n raise ValueError()\n def test_function(arg):\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n pnode = node.find_first_by_tag(\"testcase\")\n systemout = pnode.find_first_by_tag(\"system-out\")\n assert \"hello-stdout\" in systemout.toxml()\n\n def test_setup_error_captures_stderr(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n import pytest\n\n @pytest.fixture\n def arg(request):\n sys.stderr.write('hello-stderr')\n raise ValueError()\n def test_function(arg):\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n pnode = node.find_first_by_tag(\"testcase\")\n systemout = pnode.find_first_by_tag(\"system-err\")\n assert \"hello-stderr\" in systemout.toxml()\n\n def test_avoid_double_stdout(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n import pytest\n\n @pytest.fixture\n def arg(request):\n yield\n sys.stdout.write('hello-stdout teardown')\n raise ValueError()\n def test_function(arg):\n sys.stdout.write('hello-stdout call')\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n pnode = node.find_first_by_tag(\"testcase\")\n systemout = pnode.find_first_by_tag(\"system-out\")\n assert \"hello-stdout call\" in systemout.toxml()\n assert \"hello-stdout teardown\" in systemout.toxml()"},{"col":4,"comment":"null","endLoc":117,"header":"def is_globally_capturing(self)","id":4580,"name":"is_globally_capturing","nodeType":"Function","startLoc":116,"text":"def is_globally_capturing(self):\n return self._method != \"no\""},{"col":4,"comment":"null","endLoc":110,"header":"def test_summing_simple(self, testdir)","id":4581,"name":"test_summing_simple","nodeType":"Function","startLoc":89,"text":"def test_summing_simple(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_pass():\n pass\n def test_fail():\n assert 0\n def test_skip():\n pytest.skip(\"\")\n @pytest.mark.xfail\n def test_xfail():\n assert 0\n @pytest.mark.xfail\n def test_xpass():\n assert 1\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(name=\"pytest\", errors=0, failures=1, skipped=2, tests=5)"},{"col":4,"comment":"null","endLoc":487,"header":"def _write_progress_information_filling_space(self)","id":4583,"name":"_write_progress_information_filling_space","nodeType":"Function","startLoc":483,"text":"def _write_progress_information_filling_space(self):\n msg = self._get_progress_information_message()\n w = self._width_of_current_line\n fill = self._tw.fullwidth - w - 1\n self.write(msg.rjust(fill), cyan=True)"},{"col":4,"comment":"null","endLoc":481,"header":"def _get_progress_information_message(self)","id":4584,"name":"_get_progress_information_message","nodeType":"Function","startLoc":468,"text":"def _get_progress_information_message(self):\n collected = self._session.testscollected\n if self._show_progress_info == \"count\":\n if collected:\n progress = self._progress_nodeids_reported\n counter_format = \"{{:{}d}}\".format(len(str(collected)))\n format_string = \" [{}/{{}}]\".format(counter_format)\n return format_string.format(len(progress), collected)\n return \" [ {} / {} ]\".format(collected, collected)\n else:\n if collected:\n progress = len(self._progress_nodeids_reported) * 100 // collected\n return \" [{:3d}%]\".format(progress)\n return \" [100%]\""},{"col":4,"comment":"null","endLoc":320,"header":"def write(self, content, **markup)","id":4587,"name":"write","nodeType":"Function","startLoc":319,"text":"def write(self, content, **markup):\n self._tw.write(content, **markup)"},{"col":0,"comment":"null","endLoc":21,"header":"def runandparse(testdir, *args)","id":4588,"name":"runandparse","nodeType":"Function","startLoc":17,"text":"def runandparse(testdir, *args):\n resultpath = testdir.tmpdir.join(\"junit.xml\")\n result = testdir.runpytest(\"--junitxml=%s\" % resultpath, *args)\n xmldoc = minidom.parse(str(resultpath))\n return result, DomNode(xmldoc)"},{"col":4,"comment":"null","endLoc":122,"header":"def start_global_capturing(self)","id":4589,"name":"start_global_capturing","nodeType":"Function","startLoc":119,"text":"def start_global_capturing(self):\n assert self._global_capturing is None\n self._global_capturing = self._getcapture(self._method)\n self._global_capturing.start_capturing()"},{"col":0,"comment":"null","endLoc":24,"header":"def get_skip_exceptions()","id":4590,"name":"get_skip_exceptions","nodeType":"Function","startLoc":18,"text":"def get_skip_exceptions():\n skip_classes = set()\n for module_name in (\"unittest\", \"unittest2\", \"nose\"):\n mod = sys.modules.get(module_name)\n if hasattr(mod, \"SkipTest\"):\n skip_classes.add(mod.SkipTest)\n return tuple(skip_classes)"},{"col":4,"comment":" Set attribute value on target, memorizing the old value.\n By default raise AttributeError if the attribute did not exist.\n\n For convenience you can specify a string as ``target`` which\n will be interpreted as a dotted import path, with the last part\n being the attribute name. Example:\n ``monkeypatch.setattr(\"os.getcwd\", lambda: \"/\")``\n would set the ``getcwd`` function of the ``os`` module.\n\n The ``raising`` value determines if the setattr should fail\n if the attribute is not already present (defaults to True\n which means it will raise).\n ","endLoc":171,"header":"def setattr(self, target, name, value=notset, raising=True)","id":4591,"name":"setattr","nodeType":"Function","startLoc":136,"text":"def setattr(self, target, name, value=notset, raising=True):\n \"\"\" Set attribute value on target, memorizing the old value.\n By default raise AttributeError if the attribute did not exist.\n\n For convenience you can specify a string as ``target`` which\n will be interpreted as a dotted import path, with the last part\n being the attribute name. Example:\n ``monkeypatch.setattr(\"os.getcwd\", lambda: \"/\")``\n would set the ``getcwd`` function of the ``os`` module.\n\n The ``raising`` value determines if the setattr should fail\n if the attribute is not already present (defaults to True\n which means it will raise).\n \"\"\"\n __tracebackhide__ = True\n import inspect\n\n if value is notset:\n if not isinstance(target, six.string_types):\n raise TypeError(\n \"use setattr(target, name, value) or \"\n \"setattr(target, value) with target being a dotted \"\n \"import string\"\n )\n value = name\n name, target = derive_importpath(target, raising)\n\n oldval = getattr(target, name, notset)\n if raising and oldval is notset:\n raise AttributeError(\"%r has no attribute %r\" % (target, name))\n\n # avoid class descriptors like staticmethod/classmethod\n if inspect.isclass(target):\n oldval = target.__dict__.get(name, notset)\n self._setattr.append((target, name, oldval))\n setattr(target, name, value)"},{"col":4,"comment":"null","endLoc":60,"header":"@staticmethod\n def cache_dir_from_config(config)","id":4592,"name":"cache_dir_from_config","nodeType":"Function","startLoc":58,"text":"@staticmethod\n def cache_dir_from_config(config):\n return resolve_from_str(config.getini(\"cache_dir\"), config.rootdir)"},{"col":4,"comment":"null","endLoc":1004,"header":"def test_no_captured_text(self, testdir)","id":4594,"name":"test_no_captured_text","nodeType":"Function","startLoc":995,"text":"def test_no_captured_text(self, testdir):\n reports = testdir.runitem(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n rep = reports[1]\n assert rep.capstdout == \"\"\n assert rep.capstderr == \"\""},{"col":0,"comment":"null","endLoc":481,"header":"@pytest.mark.parametrize(\n \"reporttype\", reporttypes, ids=[x.__name__ for x in reporttypes]\n)\ndef test_report_extra_parameters(reporttype)","id":4595,"name":"test_report_extra_parameters","nodeType":"Function","startLoc":471,"text":"@pytest.mark.parametrize(\n \"reporttype\", reporttypes, ids=[x.__name__ for x in reporttypes]\n)\ndef test_report_extra_parameters(reporttype):\n if hasattr(inspect, \"signature\"):\n args = list(inspect.signature(reporttype.__init__).parameters.keys())[1:]\n else:\n args = inspect.getargspec(reporttype.__init__)[0][1:]\n basekw = dict.fromkeys(args, [])\n report = reporttype(newthing=1, **basekw)\n assert report.newthing == 1"},{"col":4,"comment":"null","endLoc":312,"header":"def write_ensure_prefix(self, prefix, extra=\"\", **kwargs)","id":4596,"name":"write_ensure_prefix","nodeType":"Function","startLoc":305,"text":"def write_ensure_prefix(self, prefix, extra=\"\", **kwargs):\n if self.currentfspath != prefix:\n self._tw.line()\n self.currentfspath = prefix\n self._tw.write(prefix)\n if extra:\n self._tw.write(extra, **kwargs)\n self.currentfspath = -2"},{"col":0,"comment":"null","endLoc":92,"header":"def derive_importpath(import_path, raising)","id":4597,"name":"derive_importpath","nodeType":"Function","startLoc":85,"text":"def derive_importpath(import_path, raising):\n if not isinstance(import_path, six.string_types) or \".\" not in import_path:\n raise TypeError(\"must be absolute import path string, not %r\" % (import_path,))\n module, attr = import_path.rsplit(\".\", 1)\n target = resolve(module)\n if raising:\n annotated_getattr(target, attr, ann=module)\n return attr, target"},{"col":4,"comment":"null","endLoc":317,"header":"def ensure_newline(self)","id":4598,"name":"ensure_newline","nodeType":"Function","startLoc":314,"text":"def ensure_newline(self):\n if self.currentfspath:\n self._tw.line()\n self.currentfspath = None"},{"col":4,"comment":"null","endLoc":326,"header":"def write_line(self, line, **markup)","id":4599,"name":"write_line","nodeType":"Function","startLoc":322,"text":"def write_line(self, line, **markup):\n if not isinstance(line, six.text_type):\n line = six.text_type(line, errors=\"replace\")\n self.ensure_newline()\n self._tw.line(line, **markup)"},{"col":0,"comment":"null","endLoc":1062,"header":"def test_does_not_create_boilerplate_in_existing_dirs(testdir)","id":4600,"name":"test_does_not_create_boilerplate_in_existing_dirs","nodeType":"Function","startLoc":1047,"text":"def test_does_not_create_boilerplate_in_existing_dirs(testdir):\n from _pytest.cacheprovider import Cache\n\n testdir.makeini(\n \"\"\"\n [pytest]\n cache_dir = .\n \"\"\"\n )\n config = testdir.parseconfig()\n cache = Cache.for_config(config)\n cache.set(\"foo\", \"bar\")\n\n assert os.path.isdir(\"v\") # cache contents\n assert not os.path.exists(\".gitignore\")\n assert not os.path.exists(\"README.md\")"},{"col":0,"comment":"Ensure we automatically create CACHEDIR.TAG file in the pytest_cache directory (#4278).","endLoc":1074,"header":"def test_cachedir_tag(testdir)","id":4601,"name":"test_cachedir_tag","nodeType":"Function","startLoc":1065,"text":"def test_cachedir_tag(testdir):\n \"\"\"Ensure we automatically create CACHEDIR.TAG file in the pytest_cache directory (#4278).\"\"\"\n from _pytest.cacheprovider import Cache\n from _pytest.cacheprovider import CACHEDIR_TAG_CONTENT\n\n config = testdir.parseconfig()\n cache = Cache.for_config(config)\n cache.set(\"foo\", \"bar\")\n cachedir_tag_path = cache._cachedir.joinpath(\"CACHEDIR.TAG\")\n assert cachedir_tag_path.read_bytes() == CACHEDIR_TAG_CONTENT"},{"col":4,"comment":"null","endLoc":491,"header":"def start_capturing(self)","id":4602,"name":"start_capturing","nodeType":"Function","startLoc":484,"text":"def start_capturing(self):\n self._state = \"started\"\n if self.in_:\n self.in_.start()\n if self.out:\n self.out.start()\n if self.err:\n self.err.start()"},{"col":4,"comment":"null","endLoc":128,"header":"def stop_global_capturing(self)","id":4603,"name":"stop_global_capturing","nodeType":"Function","startLoc":124,"text":"def stop_global_capturing(self):\n if self._global_capturing is not None:\n self._global_capturing.pop_outerr_to_orig()\n self._global_capturing.stop_capturing()\n self._global_capturing = None"},{"attributeType":"(str)","col":0,"comment":"null","endLoc":16,"id":4604,"name":"pytest_plugins","nodeType":"Attribute","startLoc":16,"text":"pytest_plugins"},{"col":0,"comment":"","endLoc":2,"header":"test_cacheprovider.py#","id":4605,"name":"","nodeType":"Function","startLoc":2,"text":"pytest_plugins = (\"pytester\",)"},{"col":4,"comment":"\n Rewinds the terminal cursor to the beginning and writes the given line.\n\n :kwarg erase: if True, will also add spaces until the full terminal width to ensure\n previous lines are properly erased.\n\n The rest of the keyword arguments are markup instructions.\n ","endLoc":344,"header":"def rewrite(self, line, **markup)","id":4606,"name":"rewrite","nodeType":"Function","startLoc":328,"text":"def rewrite(self, line, **markup):\n \"\"\"\n Rewinds the terminal cursor to the beginning and writes the given line.\n\n :kwarg erase: if True, will also add spaces until the full terminal width to ensure\n previous lines are properly erased.\n\n The rest of the keyword arguments are markup instructions.\n \"\"\"\n erase = markup.pop(\"erase\", False)\n if erase:\n fill_count = self._tw.fullwidth - len(line) - 1\n fill = \" \" * fill_count\n else:\n fill = \"\"\n line = str(line)\n self._tw.write(\"\\r\" + line + fill, **markup)"},{"id":4607,"name":"contributing.rst","nodeType":"TextFile","path":"doc/en","text":".. _contributing:\n\n.. include:: ../../CONTRIBUTING.rst\n"},{"fileName":"__init__.py","filePath":"src/_pytest/_io","id":4608,"nodeType":"File","text":""},{"col":4,"comment":"null","endLoc":151,"header":"def read_global_capture(self)","id":4609,"name":"read_global_capture","nodeType":"Function","startLoc":150,"text":"def read_global_capture(self):\n return self._global_capturing.readouterr()"},{"col":4,"comment":"If the current item is using ``capsys`` or ``capfd``, activate them so they take precedence over\n the global capture.\n ","endLoc":161,"header":"def activate_fixture(self, item)","id":4610,"name":"activate_fixture","nodeType":"Function","startLoc":155,"text":"def activate_fixture(self, item):\n \"\"\"If the current item is using ``capsys`` or ``capfd``, activate them so they take precedence over\n the global capture.\n \"\"\"\n fixture = getattr(item, \"_capture_fixture\", None)\n if fixture is not None:\n fixture._start()"},{"id":4611,"name":"testing/example_scripts/deprecated","nodeType":"Package"},{"fileName":"test_fixture_named_request.py","filePath":"testing/example_scripts/deprecated","id":4612,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\n@pytest.fixture\ndef request():\n pass\n\n\ndef test():\n pass\n"},{"col":0,"comment":"null","endLoc":7,"header":"@pytest.fixture\ndef request()","id":4613,"name":"request","nodeType":"Function","startLoc":5,"text":"@pytest.fixture\ndef request():\n pass"},{"col":0,"comment":"null","endLoc":11,"header":"def test()","id":4614,"name":"test","nodeType":"Function","startLoc":10,"text":"def test():\n pass"},{"col":4,"comment":"null","endLoc":136,"header":"def test_summing_simple_with_errors(self, testdir)","id":4615,"name":"test_summing_simple_with_errors","nodeType":"Function","startLoc":112,"text":"def test_summing_simple_with_errors(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def fixture():\n raise Exception()\n def test_pass():\n pass\n def test_fail():\n assert 0\n def test_error(fixture):\n pass\n @pytest.mark.xfail\n def test_xfail():\n assert False\n @pytest.mark.xfail(strict=True)\n def test_xpass():\n assert True\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(name=\"pytest\", errors=1, failures=2, skipped=1, tests=5)"},{"id":4616,"name":"historical-notes.rst","nodeType":"TextFile","path":"doc/en","text":"Historical Notes\n================\n\nThis page lists features or behavior from previous versions of pytest which have changed over the years. They are\nkept here as a historical note so users looking at old code can find documentation related to them.\n\n\n.. _marker-revamp:\n\nMarker revamp and iteration\n---------------------------\n\n.. versionchanged:: 3.6\n\npytest's marker implementation traditionally worked by simply updating the ``__dict__`` attribute of functions to cumulatively add markers. As a result, markers would unintentionally be passed along class hierarchies in surprising ways. Further, the API for retrieving them was inconsistent, as markers from parameterization would be stored differently than markers applied using the ``@pytest.mark`` decorator and markers added via ``node.add_marker``.\n\nThis state of things made it technically next to impossible to use data from markers correctly without having a deep understanding of the internals, leading to subtle and hard to understand bugs in more advanced usages.\n\nDepending on how a marker got declared/changed one would get either a ``MarkerInfo`` which might contain markers from sibling classes,\n``MarkDecorators`` when marks came from parameterization or from a ``node.add_marker`` call, discarding prior marks. Also ``MarkerInfo`` acts like a single mark, when it in fact represents a merged view on multiple marks with the same name.\n\nOn top of that markers were not accessible in the same way for modules, classes, and functions/methods.\nIn fact, markers were only accessible in functions, even if they were declared on classes/modules.\n\nA new API to access markers has been introduced in pytest 3.6 in order to solve the problems with\nthe initial design, providing the :func:`_pytest.nodes.Node.iter_markers` method to iterate over\nmarkers in a consistent manner and reworking the internals, which solved a great deal of problems\nwith the initial design.\n\n\n.. _update marker code:\n\nUpdating code\n~~~~~~~~~~~~~\n\nThe old ``Node.get_marker(name)`` function is considered deprecated because it returns an internal ``MarkerInfo`` object\nwhich contains the merged name, ``*args`` and ``**kwargs`` of all the markers which apply to that node.\n\nIn general there are two scenarios on how markers should be handled:\n\n1. Marks overwrite each other. Order matters but you only want to think of your mark as a single item. E.g.\n``log_level('info')`` at a module level can be overwritten by ``log_level('debug')`` for a specific test.\n\n In this case, use ``Node.get_closest_marker(name)``:\n\n .. code-block:: python\n\n # replace this:\n marker = item.get_marker(\"log_level\")\n if marker:\n level = marker.args[0]\n\n # by this:\n marker = item.get_closest_marker(\"log_level\")\n if marker:\n level = marker.args[0]\n\n2. Marks compose in an additive manner. E.g. ``skipif(condition)`` marks mean you just want to evaluate all of them,\norder doesn't even matter. You probably want to think of your marks as a set here.\n\n In this case iterate over each mark and handle their ``*args`` and ``**kwargs`` individually.\n\n .. code-block:: python\n\n # replace this\n skipif = item.get_marker(\"skipif\")\n if skipif:\n for condition in skipif.args:\n # eval condition\n ...\n\n # by this:\n for skipif in item.iter_markers(\"skipif\"):\n condition = skipif.args[0]\n # eval condition\n\n\nIf you are unsure or have any questions, please consider opening\n`an issue `_.\n\nRelated issues\n~~~~~~~~~~~~~~\n\nHere is a non-exhaustive list of issues fixed by the new implementation:\n\n* Marks don't pick up nested classes (`#199 `_).\n\n* Markers stain on all related classes (`#568 `_).\n\n* Combining marks - args and kwargs calculation (`#2897 `_).\n\n* ``request.node.get_marker('name')`` returns ``None`` for markers applied in classes (`#902 `_).\n\n* Marks applied in parametrize are stored as markdecorator (`#2400 `_).\n\n* Fix marker interaction in a backward incompatible way (`#1670 `_).\n\n* Refactor marks to get rid of the current \"marks transfer\" mechanism (`#2363 `_).\n\n* Introduce FunctionDefinition node, use it in generate_tests (`#2522 `_).\n\n* Remove named marker attributes and collect markers in items (`#891 `_).\n\n* skipif mark from parametrize hides module level skipif mark (`#1540 `_).\n\n* skipif + parametrize not skipping tests (`#1296 `_).\n\n* Marker transfer incompatible with inheritance (`#535 `_).\n\nMore details can be found in the `original PR `_.\n\n.. note::\n\n in a future major relase of pytest we will introduce class based markers,\n at which point markers will no longer be limited to instances of :py:class:`Mark`.\n\n\ncache plugin integrated into the core\n-------------------------------------\n\n\n\nThe functionality of the :ref:`core cache ` plugin was previously distributed\nas a third party plugin named ``pytest-cache``. The core plugin\nis compatible regarding command line options and API usage except that you\ncan only store/receive data between test runs that is json-serializable.\n\n\nfuncargs and ``pytest_funcarg__``\n---------------------------------\n\n\n\nIn versions prior to 2.3 there was no ``@pytest.fixture`` marker\nand you had to use a magic ``pytest_funcarg__NAME`` prefix\nfor the fixture factory. This remains and will remain supported\nbut is not anymore advertised as the primary means of declaring fixture\nfunctions.\n\n\n``@pytest.yield_fixture`` decorator\n-----------------------------------\n\n\n\nPrior to version 2.10, in order to use a ``yield`` statement to execute teardown code one\nhad to mark a fixture using the ``yield_fixture`` marker. From 2.10 onward, normal\nfixtures can use ``yield`` directly so the ``yield_fixture`` decorator is no longer needed\nand considered deprecated.\n\n\n``[pytest]`` header in ``setup.cfg``\n------------------------------------\n\n\n\nPrior to 3.0, the supported section name was ``[pytest]``. Due to how\nthis may collide with some distutils commands, the recommended\nsection name for ``setup.cfg`` files is now ``[tool:pytest]``.\n\nNote that for ``pytest.ini`` and ``tox.ini`` files the section\nname is ``[pytest]``.\n\n\nApplying marks to ``@pytest.mark.parametrize`` parameters\n---------------------------------------------------------\n\n\n\nPrior to version 3.1 the supported mechanism for marking values\nused the syntax:\n\n.. code-block:: python\n\n import pytest\n\n\n @pytest.mark.parametrize(\n \"test_input,expected\", [(\"3+5\", 8), (\"2+4\", 6), pytest.mark.xfail((\"6*9\", 42))]\n )\n def test_eval(test_input, expected):\n assert eval(test_input) == expected\n\n\nThis was an initial hack to support the feature but soon was demonstrated to be incomplete,\nbroken for passing functions or applying multiple marks with the same name but different parameters.\n\nThe old syntax is planned to be removed in pytest-4.0.\n\n\n``@pytest.mark.parametrize`` argument names as a tuple\n------------------------------------------------------\n\n\n\nIn versions prior to 2.4 one needed to specify the argument\nnames as a tuple. This remains valid but the simpler ``\"name1,name2,...\"``\ncomma-separated-string syntax is now advertised first because\nit's easier to write and produces less line noise.\n\n\nsetup: is now an \"autouse fixture\"\n----------------------------------\n\n\n\nDuring development prior to the pytest-2.3 release the name\n``pytest.setup`` was used but before the release it was renamed\nand moved to become part of the general fixture mechanism,\nnamely :ref:`autouse fixtures`\n\n\n.. _string conditions:\n\nConditions as strings instead of booleans\n-----------------------------------------\n\n\n\nPrior to pytest-2.4 the only way to specify skipif/xfail conditions was\nto use strings:\n\n.. code-block:: python\n\n import sys\n\n\n @pytest.mark.skipif(\"sys.version_info >= (3,3)\")\n def test_function():\n ...\n\nDuring test function setup the skipif condition is evaluated by calling\n``eval('sys.version_info >= (3,0)', namespace)``. The namespace contains\nall the module globals, and ``os`` and ``sys`` as a minimum.\n\nSince pytest-2.4 :ref:`boolean conditions ` are considered preferable\nbecause markers can then be freely imported between test modules.\nWith strings you need to import not only the marker but all variables\nused by the marker, which violates encapsulation.\n\nThe reason for specifying the condition as a string was that ``pytest`` can\nreport a summary of skip conditions based purely on the condition string.\nWith conditions as booleans you are required to specify a ``reason`` string.\n\nNote that string conditions will remain fully supported and you are free\nto use them if you have no need for cross-importing markers.\n\nThe evaluation of a condition string in ``pytest.mark.skipif(conditionstring)``\nor ``pytest.mark.xfail(conditionstring)`` takes place in a namespace\ndictionary which is constructed as follows:\n\n* the namespace is initialized by putting the ``sys`` and ``os`` modules\n and the pytest ``config`` object into it.\n\n* updated with the module globals of the test function for which the\n expression is applied.\n\nThe pytest ``config`` object allows you to skip based on a test\nconfiguration value which you might have added:\n\n.. code-block:: python\n\n @pytest.mark.skipif(\"not config.getvalue('db')\")\n def test_function():\n ...\n\nThe equivalent with \"boolean conditions\" is:\n\n.. code-block:: python\n\n @pytest.mark.skipif(not pytest.config.getvalue(\"db\"), reason=\"--db was not specified\")\n def test_function():\n pass\n\n.. note::\n\n You cannot use ``pytest.config.getvalue()`` in code\n imported before pytest's argument parsing takes place. For example,\n ``conftest.py`` files are imported before command line parsing and thus\n ``config.getvalue()`` will not execute correctly.\n\n``pytest.set_trace()``\n----------------------\n\n\n\nPrevious to version 2.4 to set a break point in code one needed to use ``pytest.set_trace()``:\n\n.. code-block:: python\n\n import pytest\n\n\n def test_function():\n ...\n pytest.set_trace() # invoke PDB debugger and tracing\n\n\nThis is no longer needed and one can use the native ``import pdb;pdb.set_trace()`` call directly.\n\nFor more details see :ref:`breakpoints`.\n\n\"compat\" properties\n-------------------\n\n\n\nAccess of ``Module``, ``Function``, ``Class``, ``Instance``, ``File`` and ``Item`` through ``Node`` instances have long\nbeen documented as deprecated, but started to emit warnings from pytest ``3.9`` and onward.\n\nUsers should just ``import pytest`` and access those objects using the ``pytest`` module.\n"},{"col":4,"comment":"null","endLoc":154,"header":"def test_timing_function(self, testdir)","id":4617,"name":"test_timing_function","nodeType":"Function","startLoc":138,"text":"def test_timing_function(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import time, pytest\n def setup_module():\n time.sleep(0.01)\n def teardown_module():\n time.sleep(0.01)\n def test_sleep():\n time.sleep(0.01)\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n val = tnode[\"time\"]\n assert round(float(val), 2) >= 0.03"},{"id":4618,"name":"testing/example_scripts/dataclasses","nodeType":"Package"},{"fileName":"test_compare_two_different_dataclasses.py","filePath":"testing/example_scripts/dataclasses","id":4619,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom dataclasses import dataclass\nfrom dataclasses import field\n\n\ndef test_comparing_two_different_data_classes():\n @dataclass\n class SimpleDataObjectOne(object):\n field_a: int = field()\n field_b: int = field()\n\n @dataclass\n class SimpleDataObjectTwo(object):\n field_a: int = field()\n field_b: int = field()\n\n left = SimpleDataObjectOne(1, \"b\")\n right = SimpleDataObjectTwo(1, \"c\")\n\n assert left != right\n"},{"col":0,"comment":"Tries to match on any marker names, attached to the given colitem.","endLoc":75,"header":"def matchmark(colitem, markexpr)","id":4620,"name":"matchmark","nodeType":"Function","startLoc":70,"text":"def matchmark(colitem, markexpr):\n \"\"\"Tries to match on any marker names, attached to the given colitem.\"\"\"\n try:\n return eval(markexpr, {}, MarkMapping.from_item(colitem))\n except SyntaxError as e:\n raise SyntaxError(str(e) + \"\\nMarker expression must be valid Python!\")"},{"col":0,"comment":"null","endLoc":58,"header":"@overload\ndef dataclass(cls: None, /) -> Callable[[type[_T]], type[_T]]","id":4621,"name":"dataclass","nodeType":"Function","startLoc":57,"text":"@overload\ndef dataclass(cls: None, /) -> Callable[[type[_T]], type[_T]]: ..."},{"col":4,"comment":"null","endLoc":23,"header":"@classmethod\n def from_item(cls, item)","id":4622,"name":"from_item","nodeType":"Function","startLoc":20,"text":"@classmethod\n def from_item(cls, item):\n mark_names = {mark.name for mark in item.iter_markers()}\n return cls(mark_names)"},{"col":0,"comment":"null","endLoc":60,"header":"@overload\ndef dataclass(cls: type[_T], /) -> type[_T]","id":4623,"name":"dataclass","nodeType":"Function","startLoc":59,"text":"@overload\ndef dataclass(cls: type[_T], /) -> type[_T]: ..."},{"col":4,"comment":"null","endLoc":103,"header":"@overload\n def dataclass(\n *,\n init: bool = True,\n repr: bool = True,\n eq: bool = True,\n order: bool = False,\n unsafe_hash: bool = False,\n frozen: bool = False,\n ) -> Callable[[type[_T]], type[_T]]","id":4624,"name":"dataclass","nodeType":"Function","startLoc":94,"text":"@overload\n def dataclass(\n *,\n init: bool = True,\n repr: bool = True,\n eq: bool = True,\n order: bool = False,\n unsafe_hash: bool = False,\n frozen: bool = False,\n ) -> Callable[[type[_T]], type[_T]]: ..."},{"col":4,"comment":"null","endLoc":194,"header":"@overload # `default` and `default_factory` are optional and mutually exclusive.\n def field(\n *,\n default: _T,\n init: bool = True,\n repr: bool = True,\n hash: bool | None = None,\n compare: bool = True,\n metadata: Mapping[Any, Any] | None = None,\n ) -> _T","id":4625,"name":"field","nodeType":"Function","startLoc":185,"text":"@overload # `default` and `default_factory` are optional and mutually exclusive.\n def field(\n *,\n default: _T,\n init: bool = True,\n repr: bool = True,\n hash: bool | None = None,\n compare: bool = True,\n metadata: Mapping[Any, Any] | None = None,\n ) -> _T: ..."},{"col":4,"comment":"null","endLoc":204,"header":"@overload\n def field(\n *,\n default_factory: Callable[[], _T],\n init: bool = True,\n repr: bool = True,\n hash: bool | None = None,\n compare: bool = True,\n metadata: Mapping[Any, Any] | None = None,\n ) -> _T","id":4626,"name":"field","nodeType":"Function","startLoc":195,"text":"@overload\n def field(\n *,\n default_factory: Callable[[], _T],\n init: bool = True,\n repr: bool = True,\n hash: bool | None = None,\n compare: bool = True,\n metadata: Mapping[Any, Any] | None = None,\n ) -> _T: ..."},{"col":4,"comment":"null","endLoc":213,"header":"@overload\n def field(\n *,\n init: bool = True,\n repr: bool = True,\n hash: bool | None = None,\n compare: bool = True,\n metadata: Mapping[Any, Any] | None = None,\n ) -> Any","id":4627,"name":"field","nodeType":"Function","startLoc":205,"text":"@overload\n def field(\n *,\n init: bool = True,\n repr: bool = True,\n hash: bool | None = None,\n compare: bool = True,\n metadata: Mapping[Any, Any] | None = None,\n ) -> Any: ..."},{"col":0,"comment":"null","endLoc":20,"header":"def test_comparing_two_different_data_classes()","id":4628,"name":"test_comparing_two_different_data_classes","nodeType":"Function","startLoc":6,"text":"def test_comparing_two_different_data_classes():\n @dataclass\n class SimpleDataObjectOne(object):\n field_a: int = field()\n field_b: int = field()\n\n @dataclass\n class SimpleDataObjectTwo(object):\n field_a: int = field()\n field_b: int = field()\n\n left = SimpleDataObjectOne(1, \"b\")\n right = SimpleDataObjectTwo(1, \"c\")\n\n assert left != right"},{"col":4,"comment":"Deactivates the ``capsys`` or ``capfd`` fixture of this item, if any.","endLoc":167,"header":"def deactivate_fixture(self, item)","id":4629,"name":"deactivate_fixture","nodeType":"Function","startLoc":163,"text":"def deactivate_fixture(self, item):\n \"\"\"Deactivates the ``capsys`` or ``capfd`` fixture of this item, if any.\"\"\"\n fixture = getattr(item, \"_capture_fixture\", None)\n if fixture is not None:\n fixture.close()"},{"id":4630,"name":"release-4.2.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-4.2.0\n=======================================\n\nThe pytest team is proud to announce the 4.2.0 release!\n\npytest is a mature Python testing tool with more than a 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n https://docs.pytest.org/en/latest/changelog.html\n\nFor complete documentation, please visit:\n\n https://docs.pytest.org/en/latest/\n\nAs usual, you can upgrade from pypi via:\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Adam Uhlir\n* Anthony Sottile\n* Bruno Oliveira\n* Christopher Dignam\n* Daniel Hahler\n* Joseph Hunkeler\n* Kristoffer Nordstroem\n* Ronny Pfannschmidt\n* Thomas Hisch\n* wim glenn\n\n\nHappy testing,\nThe Pytest Development Team\n"},{"fileName":"legacy.py","filePath":"src/_pytest/mark","id":4631,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"\nthis is a place where we put datastructures used by legacy apis\nwe hope ot remove\n\"\"\"\nimport keyword\n\nimport attr\n\nfrom _pytest.config import UsageError\n\n\n@attr.s\nclass MarkMapping(object):\n \"\"\"Provides a local mapping for markers where item access\n resolves to True if the marker is present. \"\"\"\n\n own_mark_names = attr.ib()\n\n @classmethod\n def from_item(cls, item):\n mark_names = {mark.name for mark in item.iter_markers()}\n return cls(mark_names)\n\n def __getitem__(self, name):\n return name in self.own_mark_names\n\n\nclass KeywordMapping(object):\n \"\"\"Provides a local mapping for keywords.\n Given a list of names, map any substring of one of these names to True.\n \"\"\"\n\n def __init__(self, names):\n self._names = names\n\n @classmethod\n def from_item(cls, item):\n mapped_names = set()\n\n # Add the names of the current item and any parent items\n import pytest\n\n for item in item.listchain():\n if not isinstance(item, pytest.Instance):\n mapped_names.add(item.name)\n\n # Add the names added as extra keywords to current or parent items\n mapped_names.update(item.listextrakeywords())\n\n # Add the names attached to the current function through direct assignment\n if hasattr(item, \"function\"):\n mapped_names.update(item.function.__dict__)\n\n # add the markers to the keywords as we no longer handle them correctly\n mapped_names.update(mark.name for mark in item.iter_markers())\n\n return cls(mapped_names)\n\n def __getitem__(self, subname):\n for name in self._names:\n if subname in name:\n return True\n return False\n\n\npython_keywords_allowed_list = [\"or\", \"and\", \"not\"]\n\n\ndef matchmark(colitem, markexpr):\n \"\"\"Tries to match on any marker names, attached to the given colitem.\"\"\"\n try:\n return eval(markexpr, {}, MarkMapping.from_item(colitem))\n except SyntaxError as e:\n raise SyntaxError(str(e) + \"\\nMarker expression must be valid Python!\")\n\n\ndef matchkeyword(colitem, keywordexpr):\n \"\"\"Tries to match given keyword expression to given collector item.\n\n Will match on the name of colitem, including the names of its parents.\n Only matches names of items which are either a :class:`Class` or a\n :class:`Function`.\n Additionally, matches on names in the 'extra_keyword_matches' set of\n any item, as well as names directly assigned to test functions.\n \"\"\"\n mapping = KeywordMapping.from_item(colitem)\n if \" \" not in keywordexpr:\n # special case to allow for simple \"-k pass\" and \"-k 1.3\"\n return mapping[keywordexpr]\n elif keywordexpr.startswith(\"not \") and \" \" not in keywordexpr[4:]:\n return not mapping[keywordexpr[4:]]\n for kwd in keywordexpr.split():\n if keyword.iskeyword(kwd) and kwd not in python_keywords_allowed_list:\n raise UsageError(\n \"Python keyword '{}' not accepted in expressions passed to '-k'\".format(\n kwd\n )\n )\n try:\n return eval(keywordexpr, {}, mapping)\n except SyntaxError:\n raise UsageError(\"Wrong expression passed to '-k': {}\".format(keywordexpr))\n"},{"className":"MarkMapping","col":0,"comment":"Provides a local mapping for markers where item access\n resolves to True if the marker is present. ","endLoc":26,"id":4632,"nodeType":"Class","startLoc":13,"text":"@attr.s\nclass MarkMapping(object):\n \"\"\"Provides a local mapping for markers where item access\n resolves to True if the marker is present. \"\"\"\n\n own_mark_names = attr.ib()\n\n @classmethod\n def from_item(cls, item):\n mark_names = {mark.name for mark in item.iter_markers()}\n return cls(mark_names)\n\n def __getitem__(self, name):\n return name in self.own_mark_names"},{"col":4,"comment":"null","endLoc":26,"header":"def __getitem__(self, name)","id":4633,"name":"__getitem__","nodeType":"Function","startLoc":25,"text":"def __getitem__(self, name):\n return name in self.own_mark_names"},{"attributeType":"null","col":4,"comment":"null","endLoc":18,"id":4634,"name":"own_mark_names","nodeType":"Attribute","startLoc":18,"text":"own_mark_names"},{"className":"KeywordMapping","col":0,"comment":"Provides a local mapping for keywords.\n Given a list of names, map any substring of one of these names to True.\n ","endLoc":64,"id":4635,"nodeType":"Class","startLoc":29,"text":"class KeywordMapping(object):\n \"\"\"Provides a local mapping for keywords.\n Given a list of names, map any substring of one of these names to True.\n \"\"\"\n\n def __init__(self, names):\n self._names = names\n\n @classmethod\n def from_item(cls, item):\n mapped_names = set()\n\n # Add the names of the current item and any parent items\n import pytest\n\n for item in item.listchain():\n if not isinstance(item, pytest.Instance):\n mapped_names.add(item.name)\n\n # Add the names added as extra keywords to current or parent items\n mapped_names.update(item.listextrakeywords())\n\n # Add the names attached to the current function through direct assignment\n if hasattr(item, \"function\"):\n mapped_names.update(item.function.__dict__)\n\n # add the markers to the keywords as we no longer handle them correctly\n mapped_names.update(mark.name for mark in item.iter_markers())\n\n return cls(mapped_names)\n\n def __getitem__(self, subname):\n for name in self._names:\n if subname in name:\n return True\n return False"},{"col":4,"comment":"null","endLoc":64,"header":"def __getitem__(self, subname)","id":4636,"name":"__getitem__","nodeType":"Function","startLoc":60,"text":"def __getitem__(self, subname):\n for name in self._names:\n if subname in name:\n return True\n return False"},{"attributeType":"null","col":8,"comment":"null","endLoc":35,"id":4637,"name":"_names","nodeType":"Attribute","startLoc":35,"text":"self._names"},{"attributeType":"list","col":0,"comment":"null","endLoc":67,"id":4638,"name":"python_keywords_allowed_list","nodeType":"Attribute","startLoc":67,"text":"python_keywords_allowed_list"},{"col":0,"comment":"","endLoc":5,"header":"legacy.py#","id":4639,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"\nthis is a place where we put datastructures used by legacy apis\nwe hope ot remove\n\"\"\"\n\npython_keywords_allowed_list = [\"or\", \"and\", \"not\"]"},{"fileName":"test_compare_dataclasses_verbose.py","filePath":"testing/example_scripts/dataclasses","id":4640,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom dataclasses import dataclass\nfrom dataclasses import field\n\n\ndef test_dataclasses_verbose():\n @dataclass\n class SimpleDataObject(object):\n field_a: int = field()\n field_b: int = field()\n\n left = SimpleDataObject(1, \"b\")\n right = SimpleDataObject(1, \"c\")\n\n assert left == right\n"},{"col":0,"comment":"null","endLoc":15,"header":"def test_dataclasses_verbose()","id":4641,"name":"test_dataclasses_verbose","nodeType":"Function","startLoc":6,"text":"def test_dataclasses_verbose():\n @dataclass\n class SimpleDataObject(object):\n field_a: int = field()\n field_b: int = field()\n\n left = SimpleDataObject(1, \"b\")\n right = SimpleDataObject(1, \"c\")\n\n assert left == right"},{"col":4,"comment":"null","endLoc":202,"header":"@contextlib.contextmanager\n def item_capture(self, when, item)","id":4642,"name":"item_capture","nodeType":"Function","startLoc":190,"text":"@contextlib.contextmanager\n def item_capture(self, when, item):\n self.resume_global_capture()\n self.activate_fixture(item)\n try:\n yield\n finally:\n self.deactivate_fixture(item)\n self.suspend_global_capture(in_=False)\n\n out, err = self.read_global_capture()\n item.add_report_section(when, \"stdout\", out)\n item.add_report_section(when, \"stderr\", err)"},{"col":0,"comment":"null","endLoc":72,"header":"def resolve(name)","id":4646,"name":"resolve","nodeType":"Function","startLoc":46,"text":"def resolve(name):\n # simplified from zope.dottedname\n parts = name.split(\".\")\n\n used = parts.pop(0)\n found = __import__(used)\n for part in parts:\n used += \".\" + part\n try:\n found = getattr(found, part)\n except AttributeError:\n pass\n else:\n continue\n # we use explicit un-nesting of the handling block in order\n # to avoid nested exceptions on python 3\n try:\n __import__(used)\n except ImportError as ex:\n # str is used for py2 vs py3\n expected = str(ex).split()[-1]\n if expected == used:\n raise\n else:\n raise ImportError(\"import error in %s: %s\" % (used, ex))\n found = annotated_getattr(found, part, used)\n return found"},{"col":4,"comment":"null","endLoc":348,"header":"def write_sep(self, sep, title=None, **markup)","id":4647,"name":"write_sep","nodeType":"Function","startLoc":346,"text":"def write_sep(self, sep, title=None, **markup):\n self.ensure_newline()\n self._tw.sep(sep, title, **markup)"},{"col":4,"comment":"null","endLoc":351,"header":"def section(self, title, sep=\"=\", **kw)","id":4648,"name":"section","nodeType":"Function","startLoc":350,"text":"def section(self, title, sep=\"=\", **kw):\n self._tw.sep(sep, title, **kw)"},{"col":4,"comment":"null","endLoc":219,"header":"@pytest.hookimpl(hookwrapper=True)\n def pytest_make_collect_report(self, collector)","id":4649,"name":"pytest_make_collect_report","nodeType":"Function","startLoc":206,"text":"@pytest.hookimpl(hookwrapper=True)\n def pytest_make_collect_report(self, collector):\n if isinstance(collector, pytest.File):\n self.resume_global_capture()\n outcome = yield\n self.suspend_global_capture()\n out, err = self.read_global_capture()\n rep = outcome.get_result()\n if out:\n rep.sections.append((\"Captured stdout\", out))\n if err:\n rep.sections.append((\"Captured stderr\", err))\n else:\n yield"},{"col":4,"comment":"null","endLoc":354,"header":"def line(self, msg, **kw)","id":4650,"name":"line","nodeType":"Function","startLoc":353,"text":"def line(self, msg, **kw):\n self._tw.line(msg, **kw)"},{"col":0,"comment":"null","endLoc":79,"header":"def pytest_addoption(parser)","id":4651,"name":"pytest_addoption","nodeType":"Function","startLoc":41,"text":"def pytest_addoption(parser):\n group = parser.getgroup(\"general\")\n group._addoption(\n \"-k\",\n action=\"store\",\n dest=\"keyword\",\n default=\"\",\n metavar=\"EXPRESSION\",\n help=\"only run tests which match the given substring expression. \"\n \"An expression is a python evaluatable expression \"\n \"where all names are substring-matched against test names \"\n \"and their parent classes. Example: -k 'test_method or test_\"\n \"other' matches all test functions and classes whose name \"\n \"contains 'test_method' or 'test_other', while -k 'not test_method' \"\n \"matches those that don't contain 'test_method' in their names. \"\n \"-k 'not test_method and not test_other' will eliminate the matches. \"\n \"Additionally keywords are matched to classes and functions \"\n \"containing extra names in their 'extra_keyword_matches' set, \"\n \"as well as functions which have names assigned directly to them.\",\n )\n\n group._addoption(\n \"-m\",\n action=\"store\",\n dest=\"markexpr\",\n default=\"\",\n metavar=\"MARKEXPR\",\n help=\"only run tests matching given mark expression. \"\n \"example: -m 'mark1 and not mark2'.\",\n )\n\n group.addoption(\n \"--markers\",\n action=\"store_true\",\n help=\"show markers (builtin, plugin and per-project ones).\",\n )\n\n parser.addini(\"markers\", \"markers for test functions\", \"linelist\")\n parser.addini(EMPTY_PARAMETERSET_OPTION, \"default marker for empty parametersets\")"},{"col":4,"comment":"null","endLoc":359,"header":"def pytest_internalerror(self, excrepr)","id":4652,"name":"pytest_internalerror","nodeType":"Function","startLoc":356,"text":"def pytest_internalerror(self, excrepr):\n for line in six.text_type(excrepr).split(\"\\n\"):\n self.write_line(\"INTERNALERROR> \" + line)\n return 1"},{"col":4,"comment":"null","endLoc":185,"header":"@pytest.mark.parametrize(\"duration_report\", [\"call\", \"total\"])\n def test_junit_duration_report(self, testdir, monkeypatch, duration_report)","id":4655,"name":"test_junit_duration_report","nodeType":"Function","startLoc":156,"text":"@pytest.mark.parametrize(\"duration_report\", [\"call\", \"total\"])\n def test_junit_duration_report(self, testdir, monkeypatch, duration_report):\n\n # mock LogXML.node_reporter so it always sets a known duration to each test report object\n original_node_reporter = LogXML.node_reporter\n\n def node_reporter_wrapper(s, report):\n report.duration = 1.0\n reporter = original_node_reporter(s, report)\n return reporter\n\n monkeypatch.setattr(LogXML, \"node_reporter\", node_reporter_wrapper)\n\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n pass\n \"\"\"\n )\n result, dom = runandparse(\n testdir, \"-o\", \"junit_duration_report={}\".format(duration_report)\n )\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n val = float(tnode[\"time\"])\n if duration_report == \"total\":\n assert val == 3.0\n else:\n assert duration_report == \"call\"\n assert val == 1.0"},{"col":0,"comment":"null","endLoc":96,"header":"def pytest_cmdline_main(config)","id":4656,"name":"pytest_cmdline_main","nodeType":"Function","startLoc":82,"text":"def pytest_cmdline_main(config):\n import _pytest.config\n\n if config.option.markers:\n config._do_configure()\n tw = _pytest.config.create_terminal_writer(config)\n for line in config.getini(\"markers\"):\n parts = line.split(\":\", 1)\n name = parts[0]\n rest = parts[1] if len(parts) == 2 else \"\"\n tw.write(\"@pytest.mark.%s:\" % name, bold=True)\n tw.line(rest)\n tw.line()\n config._ensure_unconfigure()\n return 0"},{"col":4,"comment":"null","endLoc":225,"header":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_protocol(self, item)","id":4657,"name":"pytest_runtest_protocol","nodeType":"Function","startLoc":221,"text":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_protocol(self, item):\n self._current_item = item\n yield\n self._current_item = None"},{"id":4658,"name":"release-4.3.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-4.3.1\n=======================================\n\npytest 4.3.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Andras Mitzki\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Danilo Horta\n* Grygorii Iermolenko\n* Jeff Hale\n* Kyle Altendorf\n* Stephan Hoyer\n* Zac Hatfield-Dodds\n* Zac-HD\n* songbowen\n\n\nHappy testing,\nThe pytest Development Team\n"},{"col":4,"comment":"null","endLoc":230,"header":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_setup(self, item)","id":4659,"name":"pytest_runtest_setup","nodeType":"Function","startLoc":227,"text":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_setup(self, item):\n with self.item_capture(\"setup\", item):\n yield"},{"col":0,"comment":"null","endLoc":126,"header":"def deselect_by_keyword(items, config)","id":4660,"name":"deselect_by_keyword","nodeType":"Function","startLoc":102,"text":"def deselect_by_keyword(items, config):\n keywordexpr = config.option.keyword.lstrip()\n if not keywordexpr:\n return\n\n if keywordexpr.startswith(\"-\"):\n keywordexpr = \"not \" + keywordexpr[1:]\n selectuntil = False\n if keywordexpr[-1:] == \":\":\n selectuntil = True\n keywordexpr = keywordexpr[:-1]\n\n remaining = []\n deselected = []\n for colitem in items:\n if keywordexpr and not matchkeyword(colitem, keywordexpr):\n deselected.append(colitem)\n else:\n if selectuntil:\n keywordexpr = None\n remaining.append(colitem)\n\n if deselected:\n config.hook.pytest_deselected(items=deselected)\n items[:] = remaining"},{"id":4661,"name":"release-2.1.3.rst","nodeType":"TextFile","path":"doc/en/announce","text":"py.test 2.1.3: just some more fixes\n===========================================================================\n\npytest-2.1.3 is a minor backward compatible maintenance release of the\npopular py.test testing tool. It is commonly used for unit, functional-\nand integration testing. See extensive docs with examples here:\n\n http://pytest.org/\n\nThe release contains another fix to the perfected assertions introduced\nwith the 2.1 series as well as the new possibility to customize reporting\nfor assertion expressions on a per-directory level.\n\nIf you want to install or upgrade pytest, just type one of::\n\n pip install -U pytest # or\n easy_install -U pytest\n\nThanks to the bug reporters and to Ronny Pfannschmidt, Benjamin Peterson\nand Floris Bruynooghe who implemented the fixes.\n\nbest,\nholger krekel\n\nChanges between 2.1.2 and 2.1.3\n----------------------------------------\n\n- fix issue79: assertion rewriting failed on some comparisons in boolops,\n- correctly handle zero length arguments (a la pytest '')\n- fix issue67 / junitxml now contains correct test durations\n- fix issue75 / skipping test failure on jython\n- fix issue77 / Allow assertrepr_compare hook to apply to a subset of tests\n"},{"id":4662,"name":"release-4.6.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-4.6.2\n=======================================\n\npytest 4.6.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n\n\nHappy testing,\nThe pytest Development Team\n"},{"id":4663,"name":"release-4.1.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-4.1.0\n=======================================\n\nThe pytest team is proud to announce the 4.1.0 release!\n\npytest is a mature Python testing tool with more than a 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n https://docs.pytest.org/en/latest/changelog.html\n\nFor complete documentation, please visit:\n\n https://docs.pytest.org/en/latest/\n\nAs usual, you can upgrade from pypi via:\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Adam Johnson\n* Aly Sivji\n* Andrey Paramonov\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* David Vo\n* Hyunchel Kim\n* Jeffrey Rackauckas\n* Kanguros\n* Nicholas Devenish\n* Pedro Algarvio\n* Randy Barlow\n* Ronny Pfannschmidt\n* Tomer Keren\n* feuillemorte\n* wim glenn\n\n\nHappy testing,\nThe Pytest Development Team\n"},{"fileName":"test_argcomplete.py","filePath":"testing","id":4664,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport subprocess\nimport sys\n\nimport pytest\n\n# test for _argcomplete but not specific for any application\n\n\ndef equal_with_bash(prefix, ffc, fc, out=None):\n res = ffc(prefix)\n res_bash = set(fc(prefix))\n retval = set(res) == res_bash\n if out:\n out.write(\"equal_with_bash({}) {} {}\\n\".format(prefix, retval, res))\n if not retval:\n out.write(\" python - bash: %s\\n\" % (set(res) - res_bash))\n out.write(\" bash - python: %s\\n\" % (res_bash - set(res)))\n return retval\n\n\n# copied from argcomplete.completers as import from there\n# also pulls in argcomplete.__init__ which opens filedescriptor 9\n# this gives an IOError at the end of testrun\n\n\ndef _wrapcall(*args, **kargs):\n try:\n if sys.version_info > (2, 7):\n return subprocess.check_output(*args, **kargs).decode().splitlines()\n if \"stdout\" in kargs:\n raise ValueError(\"stdout argument not allowed, it will be overridden.\")\n process = subprocess.Popen(stdout=subprocess.PIPE, *args, **kargs)\n output, unused_err = process.communicate()\n retcode = process.poll()\n if retcode:\n cmd = kargs.get(\"args\")\n if cmd is None:\n cmd = args[0]\n raise subprocess.CalledProcessError(retcode, cmd)\n return output.decode().splitlines()\n except subprocess.CalledProcessError:\n return []\n\n\nclass FilesCompleter(object):\n \"File completer class, optionally takes a list of allowed extensions\"\n\n def __init__(self, allowednames=(), directories=True):\n # Fix if someone passes in a string instead of a list\n if type(allowednames) is str:\n allowednames = [allowednames]\n\n self.allowednames = [x.lstrip(\"*\").lstrip(\".\") for x in allowednames]\n self.directories = directories\n\n def __call__(self, prefix, **kwargs):\n completion = []\n if self.allowednames:\n if self.directories:\n files = _wrapcall(\n [\"bash\", \"-c\", \"compgen -A directory -- '{p}'\".format(p=prefix)]\n )\n completion += [f + \"/\" for f in files]\n for x in self.allowednames:\n completion += _wrapcall(\n [\n \"bash\",\n \"-c\",\n \"compgen -A file -X '!*.{0}' -- '{p}'\".format(x, p=prefix),\n ]\n )\n else:\n completion += _wrapcall(\n [\"bash\", \"-c\", \"compgen -A file -- '{p}'\".format(p=prefix)]\n )\n\n anticomp = _wrapcall(\n [\"bash\", \"-c\", \"compgen -A directory -- '{p}'\".format(p=prefix)]\n )\n\n completion = list(set(completion) - set(anticomp))\n\n if self.directories:\n completion += [f + \"/\" for f in anticomp]\n return completion\n\n\nclass TestArgComplete(object):\n @pytest.mark.skipif(\"sys.platform in ('win32', 'darwin')\")\n def test_compare_with_compgen(self, tmpdir):\n from _pytest._argcomplete import FastFilesCompleter\n\n ffc = FastFilesCompleter()\n fc = FilesCompleter()\n\n with tmpdir.as_cwd():\n assert equal_with_bash(\"\", ffc, fc, out=sys.stdout)\n\n tmpdir.ensure(\"data\")\n\n for x in [\"d\", \"data\", \"doesnotexist\", \"\"]:\n assert equal_with_bash(x, ffc, fc, out=sys.stdout)\n\n @pytest.mark.skipif(\"sys.platform in ('win32', 'darwin')\")\n def test_remove_dir_prefix(self):\n \"\"\"this is not compatible with compgen but it is with bash itself:\n ls /usr/\n \"\"\"\n from _pytest._argcomplete import FastFilesCompleter\n\n ffc = FastFilesCompleter()\n fc = FilesCompleter()\n for x in \"/usr/\".split():\n assert not equal_with_bash(x, ffc, fc, out=sys.stdout)\n"},{"className":"FilesCompleter","col":0,"comment":"File completer class, optionally takes a list of allowed extensions","endLoc":90,"id":4665,"nodeType":"Class","startLoc":50,"text":"class FilesCompleter(object):\n \"File completer class, optionally takes a list of allowed extensions\"\n\n def __init__(self, allowednames=(), directories=True):\n # Fix if someone passes in a string instead of a list\n if type(allowednames) is str:\n allowednames = [allowednames]\n\n self.allowednames = [x.lstrip(\"*\").lstrip(\".\") for x in allowednames]\n self.directories = directories\n\n def __call__(self, prefix, **kwargs):\n completion = []\n if self.allowednames:\n if self.directories:\n files = _wrapcall(\n [\"bash\", \"-c\", \"compgen -A directory -- '{p}'\".format(p=prefix)]\n )\n completion += [f + \"/\" for f in files]\n for x in self.allowednames:\n completion += _wrapcall(\n [\n \"bash\",\n \"-c\",\n \"compgen -A file -X '!*.{0}' -- '{p}'\".format(x, p=prefix),\n ]\n )\n else:\n completion += _wrapcall(\n [\"bash\", \"-c\", \"compgen -A file -- '{p}'\".format(p=prefix)]\n )\n\n anticomp = _wrapcall(\n [\"bash\", \"-c\", \"compgen -A directory -- '{p}'\".format(p=prefix)]\n )\n\n completion = list(set(completion) - set(anticomp))\n\n if self.directories:\n completion += [f + \"/\" for f in anticomp]\n return completion"},{"col":4,"comment":"null","endLoc":59,"header":"def __init__(self, allowednames=(), directories=True)","id":4666,"name":"__init__","nodeType":"Function","startLoc":53,"text":"def __init__(self, allowednames=(), directories=True):\n # Fix if someone passes in a string instead of a list\n if type(allowednames) is str:\n allowednames = [allowednames]\n\n self.allowednames = [x.lstrip(\"*\").lstrip(\".\") for x in allowednames]\n self.directories = directories"},{"col":4,"comment":"null","endLoc":373,"header":"def pytest_warning_captured(self, warning_message, item)","id":4667,"name":"pytest_warning_captured","nodeType":"Function","startLoc":361,"text":"def pytest_warning_captured(self, warning_message, item):\n # from _pytest.nodes import get_fslocation_from_item\n from _pytest.warnings import warning_record_to_str\n\n warnings = self.stats.setdefault(\"warnings\", [])\n fslocation = warning_message.filename, warning_message.lineno\n message = warning_record_to_str(warning_message)\n\n nodeid = item.nodeid if item is not None else \"\"\n warning_report = WarningReport(\n fslocation=fslocation, message=message, nodeid=nodeid\n )\n warnings.append(warning_report)"},{"fileName":"python.py","filePath":"src/_pytest","id":4668,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\" Python test discovery, setup and run of test functions. \"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport fnmatch\nimport inspect\nimport os\nimport sys\nimport warnings\nfrom functools import partial\nfrom textwrap import dedent\n\nimport py\nimport six\n\nimport _pytest\nfrom _pytest import deprecated\nfrom _pytest import fixtures\nfrom _pytest import nodes\nfrom _pytest._code import filter_traceback\nfrom _pytest.compat import ascii_escaped\nfrom _pytest.compat import enum\nfrom _pytest.compat import get_default_arg_names\nfrom _pytest.compat import get_real_func\nfrom _pytest.compat import getfslineno\nfrom _pytest.compat import getimfunc\nfrom _pytest.compat import getlocation\nfrom _pytest.compat import is_generator\nfrom _pytest.compat import isclass\nfrom _pytest.compat import isfunction\nfrom _pytest.compat import NOTSET\nfrom _pytest.compat import REGEX_TYPE\nfrom _pytest.compat import safe_getattr\nfrom _pytest.compat import safe_isclass\nfrom _pytest.compat import safe_str\nfrom _pytest.compat import STRING_TYPES\nfrom _pytest.config import hookimpl\nfrom _pytest.main import FSHookProxy\nfrom _pytest.mark import MARK_GEN\nfrom _pytest.mark.structures import get_unpacked_marks\nfrom _pytest.mark.structures import normalize_mark_list\nfrom _pytest.outcomes import fail\nfrom _pytest.outcomes import skip\nfrom _pytest.pathlib import parts\nfrom _pytest.warning_types import PytestCollectionWarning\nfrom _pytest.warning_types import PytestUnhandledCoroutineWarning\n\n\ndef pyobj_property(name):\n def get(self):\n node = self.getparent(getattr(__import__(\"pytest\"), name))\n if node is not None:\n return node.obj\n\n doc = \"python %s object this node was collected from (can be None).\" % (\n name.lower(),\n )\n return property(get, None, None, doc)\n\n\ndef pytest_addoption(parser):\n group = parser.getgroup(\"general\")\n group.addoption(\n \"--fixtures\",\n \"--funcargs\",\n action=\"store_true\",\n dest=\"showfixtures\",\n default=False,\n help=\"show available fixtures, sorted by plugin appearance \"\n \"(fixtures with leading '_' are only shown with '-v')\",\n )\n group.addoption(\n \"--fixtures-per-test\",\n action=\"store_true\",\n dest=\"show_fixtures_per_test\",\n default=False,\n help=\"show fixtures per test\",\n )\n parser.addini(\n \"python_files\",\n type=\"args\",\n # NOTE: default is also used in AssertionRewritingHook.\n default=[\"test_*.py\", \"*_test.py\"],\n help=\"glob-style file patterns for Python test module discovery\",\n )\n parser.addini(\n \"python_classes\",\n type=\"args\",\n default=[\"Test\"],\n help=\"prefixes or glob names for Python test class discovery\",\n )\n parser.addini(\n \"python_functions\",\n type=\"args\",\n default=[\"test\"],\n help=\"prefixes or glob names for Python test function and method discovery\",\n )\n parser.addini(\n \"disable_test_id_escaping_and_forfeit_all_rights_to_community_support\",\n type=\"bool\",\n default=False,\n help=\"disable string escape non-ascii characters, might cause unwanted \"\n \"side effects(use at your own risk)\",\n )\n\n group.addoption(\n \"--import-mode\",\n default=\"prepend\",\n choices=[\"prepend\", \"append\"],\n dest=\"importmode\",\n help=\"prepend/append to sys.path when importing test modules, \"\n \"default is to prepend.\",\n )\n\n\ndef pytest_cmdline_main(config):\n if config.option.showfixtures:\n showfixtures(config)\n return 0\n if config.option.show_fixtures_per_test:\n show_fixtures_per_test(config)\n return 0\n\n\ndef pytest_generate_tests(metafunc):\n # those alternative spellings are common - raise a specific error to alert\n # the user\n alt_spellings = [\"parameterize\", \"parametrise\", \"parameterise\"]\n for mark_name in alt_spellings:\n if metafunc.definition.get_closest_marker(mark_name):\n msg = \"{0} has '{1}' mark, spelling should be 'parametrize'\"\n fail(msg.format(metafunc.function.__name__, mark_name), pytrace=False)\n for marker in metafunc.definition.iter_markers(name=\"parametrize\"):\n metafunc.parametrize(*marker.args, **marker.kwargs)\n\n\ndef pytest_configure(config):\n config.addinivalue_line(\n \"markers\",\n \"parametrize(argnames, argvalues): call a test function multiple \"\n \"times passing in different arguments in turn. argvalues generally \"\n \"needs to be a list of values if argnames specifies only one name \"\n \"or a list of tuples of values if argnames specifies multiple names. \"\n \"Example: @parametrize('arg1', [1,2]) would lead to two calls of the \"\n \"decorated test function, one with arg1=1 and another with arg1=2.\"\n \"see https://docs.pytest.org/en/latest/parametrize.html for more info \"\n \"and examples.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"usefixtures(fixturename1, fixturename2, ...): mark tests as needing \"\n \"all of the specified fixtures. see \"\n \"https://docs.pytest.org/en/latest/fixture.html#usefixtures \",\n )\n\n\n@hookimpl(trylast=True)\ndef pytest_pyfunc_call(pyfuncitem):\n testfunction = pyfuncitem.obj\n iscoroutinefunction = getattr(inspect, \"iscoroutinefunction\", None)\n if iscoroutinefunction is not None and iscoroutinefunction(testfunction):\n msg = \"Coroutine functions are not natively supported and have been skipped.\\n\"\n msg += \"You need to install a suitable plugin for your async framework, for example:\\n\"\n msg += \" - pytest-asyncio\\n\"\n msg += \" - pytest-trio\\n\"\n msg += \" - pytest-tornasync\"\n warnings.warn(PytestUnhandledCoroutineWarning(msg.format(pyfuncitem.nodeid)))\n skip(msg=\"coroutine function and no async plugin installed (see warnings)\")\n funcargs = pyfuncitem.funcargs\n testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames}\n testfunction(**testargs)\n return True\n\n\ndef pytest_collect_file(path, parent):\n ext = path.ext\n if ext == \".py\":\n if not parent.session.isinitpath(path):\n if not path_matches_patterns(\n path, parent.config.getini(\"python_files\") + [\"__init__.py\"]\n ):\n return\n ihook = parent.session.gethookproxy(path)\n return ihook.pytest_pycollect_makemodule(path=path, parent=parent)\n\n\ndef path_matches_patterns(path, patterns):\n \"\"\"Returns True if the given py.path.local matches one of the patterns in the list of globs given\"\"\"\n return any(path.fnmatch(pattern) for pattern in patterns)\n\n\ndef pytest_pycollect_makemodule(path, parent):\n if path.basename == \"__init__.py\":\n return Package(path, parent)\n return Module(path, parent)\n\n\n@hookimpl(hookwrapper=True)\ndef pytest_pycollect_makeitem(collector, name, obj):\n outcome = yield\n res = outcome.get_result()\n if res is not None:\n return\n # nothing was collected elsewhere, let's do it here\n if safe_isclass(obj):\n if collector.istestclass(obj, name):\n outcome.force_result(Class(name, parent=collector))\n elif collector.istestfunction(obj, name):\n # mock seems to store unbound methods (issue473), normalize it\n obj = getattr(obj, \"__func__\", obj)\n # We need to try and unwrap the function if it's a functools.partial\n # or a funtools.wrapped.\n # We musn't if it's been wrapped with mock.patch (python 2 only)\n if not (isfunction(obj) or isfunction(get_real_func(obj))):\n filename, lineno = getfslineno(obj)\n warnings.warn_explicit(\n message=PytestCollectionWarning(\n \"cannot collect %r because it is not a function.\" % name\n ),\n category=None,\n filename=str(filename),\n lineno=lineno + 1,\n )\n elif getattr(obj, \"__test__\", True):\n if is_generator(obj):\n res = Function(name, parent=collector)\n reason = deprecated.YIELD_TESTS.format(name=name)\n res.add_marker(MARK_GEN.xfail(run=False, reason=reason))\n res.warn(PytestCollectionWarning(reason))\n else:\n res = list(collector._genfunctions(name, obj))\n outcome.force_result(res)\n\n\ndef pytest_make_parametrize_id(config, val, argname=None):\n return None\n\n\nclass PyobjContext(object):\n module = pyobj_property(\"Module\")\n cls = pyobj_property(\"Class\")\n instance = pyobj_property(\"Instance\")\n\n\nclass PyobjMixin(PyobjContext):\n _ALLOW_MARKERS = True\n\n def __init__(self, *k, **kw):\n super(PyobjMixin, self).__init__(*k, **kw)\n\n @property\n def obj(self):\n \"\"\"Underlying Python object.\"\"\"\n obj = getattr(self, \"_obj\", None)\n if obj is None:\n self._obj = obj = self._getobj()\n # XXX evil hack\n # used to avoid Instance collector marker duplication\n if self._ALLOW_MARKERS:\n self.own_markers.extend(get_unpacked_marks(self.obj))\n return obj\n\n @obj.setter\n def obj(self, value):\n self._obj = value\n\n def _getobj(self):\n \"\"\"Gets the underlying Python object. May be overwritten by subclasses.\"\"\"\n return getattr(self.parent.obj, self.name)\n\n def getmodpath(self, stopatmodule=True, includemodule=False):\n \"\"\" return python path relative to the containing module. \"\"\"\n chain = self.listchain()\n chain.reverse()\n parts = []\n for node in chain:\n if isinstance(node, Instance):\n continue\n name = node.name\n if isinstance(node, Module):\n name = os.path.splitext(name)[0]\n if stopatmodule:\n if includemodule:\n parts.append(name)\n break\n parts.append(name)\n parts.reverse()\n s = \".\".join(parts)\n return s.replace(\".[\", \"[\")\n\n def reportinfo(self):\n # XXX caching?\n obj = self.obj\n compat_co_firstlineno = getattr(obj, \"compat_co_firstlineno\", None)\n if isinstance(compat_co_firstlineno, int):\n # nose compatibility\n fspath = sys.modules[obj.__module__].__file__\n if fspath.endswith(\".pyc\"):\n fspath = fspath[:-1]\n lineno = compat_co_firstlineno\n else:\n fspath, lineno = getfslineno(obj)\n modpath = self.getmodpath()\n assert isinstance(lineno, int)\n return fspath, lineno, modpath\n\n\nclass PyCollector(PyobjMixin, nodes.Collector):\n def funcnamefilter(self, name):\n return self._matches_prefix_or_glob_option(\"python_functions\", name)\n\n def isnosetest(self, obj):\n \"\"\" Look for the __test__ attribute, which is applied by the\n @nose.tools.istest decorator\n \"\"\"\n # We explicitly check for \"is True\" here to not mistakenly treat\n # classes with a custom __getattr__ returning something truthy (like a\n # function) as test classes.\n return safe_getattr(obj, \"__test__\", False) is True\n\n def classnamefilter(self, name):\n return self._matches_prefix_or_glob_option(\"python_classes\", name)\n\n def istestfunction(self, obj, name):\n if self.funcnamefilter(name) or self.isnosetest(obj):\n if isinstance(obj, staticmethod):\n # static methods need to be unwrapped\n obj = safe_getattr(obj, \"__func__\", False)\n return (\n safe_getattr(obj, \"__call__\", False)\n and fixtures.getfixturemarker(obj) is None\n )\n else:\n return False\n\n def istestclass(self, obj, name):\n return self.classnamefilter(name) or self.isnosetest(obj)\n\n def _matches_prefix_or_glob_option(self, option_name, name):\n \"\"\"\n checks if the given name matches the prefix or glob-pattern defined\n in ini configuration.\n \"\"\"\n for option in self.config.getini(option_name):\n if name.startswith(option):\n return True\n # check that name looks like a glob-string before calling fnmatch\n # because this is called for every name in each collected module,\n # and fnmatch is somewhat expensive to call\n elif (\"*\" in option or \"?\" in option or \"[\" in option) and fnmatch.fnmatch(\n name, option\n ):\n return True\n return False\n\n def collect(self):\n if not getattr(self.obj, \"__test__\", True):\n return []\n\n # NB. we avoid random getattrs and peek in the __dict__ instead\n # (XXX originally introduced from a PyPy need, still true?)\n dicts = [getattr(self.obj, \"__dict__\", {})]\n for basecls in inspect.getmro(self.obj.__class__):\n dicts.append(basecls.__dict__)\n seen = {}\n values = []\n for dic in dicts:\n for name, obj in list(dic.items()):\n if name in seen:\n continue\n seen[name] = True\n res = self._makeitem(name, obj)\n if res is None:\n continue\n if not isinstance(res, list):\n res = [res]\n values.extend(res)\n values.sort(key=lambda item: item.reportinfo()[:2])\n return values\n\n def _makeitem(self, name, obj):\n # assert self.ihook.fspath == self.fspath, self\n return self.ihook.pytest_pycollect_makeitem(collector=self, name=name, obj=obj)\n\n def _genfunctions(self, name, funcobj):\n module = self.getparent(Module).obj\n clscol = self.getparent(Class)\n cls = clscol and clscol.obj or None\n fm = self.session._fixturemanager\n\n definition = FunctionDefinition(name=name, parent=self, callobj=funcobj)\n fixtureinfo = fm.getfixtureinfo(definition, funcobj, cls)\n\n metafunc = Metafunc(\n definition, fixtureinfo, self.config, cls=cls, module=module\n )\n methods = []\n if hasattr(module, \"pytest_generate_tests\"):\n methods.append(module.pytest_generate_tests)\n if hasattr(cls, \"pytest_generate_tests\"):\n methods.append(cls().pytest_generate_tests)\n if methods:\n self.ihook.pytest_generate_tests.call_extra(\n methods, dict(metafunc=metafunc)\n )\n else:\n self.ihook.pytest_generate_tests(metafunc=metafunc)\n\n if not metafunc._calls:\n yield Function(name, parent=self, fixtureinfo=fixtureinfo)\n else:\n # add funcargs() as fixturedefs to fixtureinfo.arg2fixturedefs\n fixtures.add_funcarg_pseudo_fixture_def(self, metafunc, fm)\n\n # add_funcarg_pseudo_fixture_def may have shadowed some fixtures\n # with direct parametrization, so make sure we update what the\n # function really needs.\n fixtureinfo.prune_dependency_tree()\n\n for callspec in metafunc._calls:\n subname = \"%s[%s]\" % (name, callspec.id)\n yield Function(\n name=subname,\n parent=self,\n callspec=callspec,\n callobj=funcobj,\n fixtureinfo=fixtureinfo,\n keywords={callspec.id: True},\n originalname=name,\n )\n\n\nclass Module(nodes.File, PyCollector):\n \"\"\" Collector for test classes and functions. \"\"\"\n\n def _getobj(self):\n return self._importtestmodule()\n\n def collect(self):\n self._inject_setup_module_fixture()\n self._inject_setup_function_fixture()\n self.session._fixturemanager.parsefactories(self)\n return super(Module, self).collect()\n\n def _inject_setup_module_fixture(self):\n \"\"\"Injects a hidden autouse, module scoped fixture into the collected module object\n that invokes setUpModule/tearDownModule if either or both are available.\n\n Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with\n other fixtures (#517).\n \"\"\"\n setup_module = _get_non_fixture_func(self.obj, \"setUpModule\")\n if setup_module is None:\n setup_module = _get_non_fixture_func(self.obj, \"setup_module\")\n\n teardown_module = _get_non_fixture_func(self.obj, \"tearDownModule\")\n if teardown_module is None:\n teardown_module = _get_non_fixture_func(self.obj, \"teardown_module\")\n\n if setup_module is None and teardown_module is None:\n return\n\n @fixtures.fixture(autouse=True, scope=\"module\")\n def xunit_setup_module_fixture(request):\n if setup_module is not None:\n _call_with_optional_argument(setup_module, request.module)\n yield\n if teardown_module is not None:\n _call_with_optional_argument(teardown_module, request.module)\n\n self.obj.__pytest_setup_module = xunit_setup_module_fixture\n\n def _inject_setup_function_fixture(self):\n \"\"\"Injects a hidden autouse, function scoped fixture into the collected module object\n that invokes setup_function/teardown_function if either or both are available.\n\n Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with\n other fixtures (#517).\n \"\"\"\n setup_function = _get_non_fixture_func(self.obj, \"setup_function\")\n teardown_function = _get_non_fixture_func(self.obj, \"teardown_function\")\n if setup_function is None and teardown_function is None:\n return\n\n @fixtures.fixture(autouse=True, scope=\"function\")\n def xunit_setup_function_fixture(request):\n if request.instance is not None:\n # in this case we are bound to an instance, so we need to let\n # setup_method handle this\n yield\n return\n if setup_function is not None:\n _call_with_optional_argument(setup_function, request.function)\n yield\n if teardown_function is not None:\n _call_with_optional_argument(teardown_function, request.function)\n\n self.obj.__pytest_setup_function = xunit_setup_function_fixture\n\n def _importtestmodule(self):\n # we assume we are only called once per module\n importmode = self.config.getoption(\"--import-mode\")\n try:\n mod = self.fspath.pyimport(ensuresyspath=importmode)\n except SyntaxError:\n raise self.CollectError(\n _pytest._code.ExceptionInfo.from_current().getrepr(style=\"short\")\n )\n except self.fspath.ImportMismatchError:\n e = sys.exc_info()[1]\n raise self.CollectError(\n \"import file mismatch:\\n\"\n \"imported module %r has this __file__ attribute:\\n\"\n \" %s\\n\"\n \"which is not the same as the test file we want to collect:\\n\"\n \" %s\\n\"\n \"HINT: remove __pycache__ / .pyc files and/or use a \"\n \"unique basename for your test file modules\" % e.args\n )\n except ImportError:\n from _pytest._code.code import ExceptionInfo\n\n exc_info = ExceptionInfo.from_current()\n if self.config.getoption(\"verbose\") < 2:\n exc_info.traceback = exc_info.traceback.filter(filter_traceback)\n exc_repr = (\n exc_info.getrepr(style=\"short\")\n if exc_info.traceback\n else exc_info.exconly()\n )\n formatted_tb = safe_str(exc_repr)\n raise self.CollectError(\n \"ImportError while importing test module '{fspath}'.\\n\"\n \"Hint: make sure your test modules/packages have valid Python names.\\n\"\n \"Traceback:\\n\"\n \"{traceback}\".format(fspath=self.fspath, traceback=formatted_tb)\n )\n except _pytest.runner.Skipped as e:\n if e.allow_module_level:\n raise\n raise self.CollectError(\n \"Using pytest.skip outside of a test is not allowed. \"\n \"To decorate a test function, use the @pytest.mark.skip \"\n \"or @pytest.mark.skipif decorators instead, and to skip a \"\n \"module use `pytestmark = pytest.mark.{skip,skipif}.\"\n )\n self.config.pluginmanager.consider_module(mod)\n return mod\n\n\nclass Package(Module):\n def __init__(self, fspath, parent=None, config=None, session=None, nodeid=None):\n session = parent.session\n nodes.FSCollector.__init__(\n self, fspath, parent=parent, config=config, session=session, nodeid=nodeid\n )\n self.name = fspath.dirname\n self.trace = session.trace\n self._norecursepatterns = session._norecursepatterns\n self.fspath = fspath\n\n def setup(self):\n # not using fixtures to call setup_module here because autouse fixtures\n # from packages are not called automatically (#4085)\n setup_module = _get_non_fixture_func(self.obj, \"setUpModule\")\n if setup_module is None:\n setup_module = _get_non_fixture_func(self.obj, \"setup_module\")\n if setup_module is not None:\n _call_with_optional_argument(setup_module, self.obj)\n\n teardown_module = _get_non_fixture_func(self.obj, \"tearDownModule\")\n if teardown_module is None:\n teardown_module = _get_non_fixture_func(self.obj, \"teardown_module\")\n if teardown_module is not None:\n func = partial(_call_with_optional_argument, teardown_module, self.obj)\n self.addfinalizer(func)\n\n def _recurse(self, dirpath):\n if dirpath.basename == \"__pycache__\":\n return False\n ihook = self.gethookproxy(dirpath.dirpath())\n if ihook.pytest_ignore_collect(path=dirpath, config=self.config):\n return\n for pat in self._norecursepatterns:\n if dirpath.check(fnmatch=pat):\n return False\n ihook = self.gethookproxy(dirpath)\n ihook.pytest_collect_directory(path=dirpath, parent=self)\n return True\n\n def gethookproxy(self, fspath):\n # check if we have the common case of running\n # hooks with all conftest.py filesall conftest.py\n pm = self.config.pluginmanager\n my_conftestmodules = pm._getconftestmodules(fspath)\n remove_mods = pm._conftest_plugins.difference(my_conftestmodules)\n if remove_mods:\n # one or more conftests are not in use at this fspath\n proxy = FSHookProxy(fspath, pm, remove_mods)\n else:\n # all plugis are active for this fspath\n proxy = self.config.hook\n return proxy\n\n def _collectfile(self, path, handle_dupes=True):\n assert path.isfile(), \"%r is not a file (isdir=%r, exists=%r, islink=%r)\" % (\n path,\n path.isdir(),\n path.exists(),\n path.islink(),\n )\n ihook = self.gethookproxy(path)\n if not self.isinitpath(path):\n if ihook.pytest_ignore_collect(path=path, config=self.config):\n return ()\n\n if handle_dupes:\n keepduplicates = self.config.getoption(\"keepduplicates\")\n if not keepduplicates:\n duplicate_paths = self.config.pluginmanager._duplicatepaths\n if path in duplicate_paths:\n return ()\n else:\n duplicate_paths.add(path)\n\n if self.fspath == path: # __init__.py\n return [self]\n\n return ihook.pytest_collect_file(path=path, parent=self)\n\n def isinitpath(self, path):\n return path in self.session._initialpaths\n\n def collect(self):\n this_path = self.fspath.dirpath()\n init_module = this_path.join(\"__init__.py\")\n if init_module.check(file=1) and path_matches_patterns(\n init_module, self.config.getini(\"python_files\")\n ):\n yield Module(init_module, self)\n pkg_prefixes = set()\n for path in this_path.visit(rec=self._recurse, bf=True, sort=True):\n # We will visit our own __init__.py file, in which case we skip it.\n is_file = path.isfile()\n if is_file:\n if path.basename == \"__init__.py\" and path.dirpath() == this_path:\n continue\n\n parts_ = parts(path.strpath)\n if any(\n pkg_prefix in parts_ and pkg_prefix.join(\"__init__.py\") != path\n for pkg_prefix in pkg_prefixes\n ):\n continue\n\n if is_file:\n for x in self._collectfile(path):\n yield x\n elif not path.isdir():\n # Broken symlink or invalid/missing file.\n continue\n elif path.join(\"__init__.py\").check(file=1):\n pkg_prefixes.add(path)\n\n\ndef _get_xunit_setup_teardown(holder, attr_name, param_obj=None):\n \"\"\"\n Return a callable to perform xunit-style setup or teardown if\n the function exists in the ``holder`` object.\n The ``param_obj`` parameter is the parameter which will be passed to the function\n when the callable is called without arguments, defaults to the ``holder`` object.\n Return ``None`` if a suitable callable is not found.\n \"\"\"\n # TODO: only needed because of Package!\n param_obj = param_obj if param_obj is not None else holder\n result = _get_non_fixture_func(holder, attr_name)\n if result is not None:\n arg_count = result.__code__.co_argcount\n if inspect.ismethod(result):\n arg_count -= 1\n if arg_count:\n return lambda: result(param_obj)\n else:\n return result\n\n\ndef _call_with_optional_argument(func, arg):\n \"\"\"Call the given function with the given argument if func accepts one argument, otherwise\n calls func without arguments\"\"\"\n arg_count = func.__code__.co_argcount\n if inspect.ismethod(func):\n arg_count -= 1\n if arg_count:\n func(arg)\n else:\n func()\n\n\ndef _get_non_fixture_func(obj, name):\n \"\"\"Return the attribute from the given object to be used as a setup/teardown\n xunit-style function, but only if not marked as a fixture to\n avoid calling it twice.\n \"\"\"\n meth = getattr(obj, name, None)\n if fixtures.getfixturemarker(meth) is None:\n return meth\n\n\nclass Class(PyCollector):\n \"\"\" Collector for test methods. \"\"\"\n\n def collect(self):\n if not safe_getattr(self.obj, \"__test__\", True):\n return []\n if hasinit(self.obj):\n self.warn(\n PytestCollectionWarning(\n \"cannot collect test class %r because it has a \"\n \"__init__ constructor (from: %s)\"\n % (self.obj.__name__, self.parent.nodeid)\n )\n )\n return []\n elif hasnew(self.obj):\n self.warn(\n PytestCollectionWarning(\n \"cannot collect test class %r because it has a \"\n \"__new__ constructor (from: %s)\"\n % (self.obj.__name__, self.parent.nodeid)\n )\n )\n return []\n\n self._inject_setup_class_fixture()\n self._inject_setup_method_fixture()\n\n return [Instance(name=\"()\", parent=self)]\n\n def _inject_setup_class_fixture(self):\n \"\"\"Injects a hidden autouse, class scoped fixture into the collected class object\n that invokes setup_class/teardown_class if either or both are available.\n\n Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with\n other fixtures (#517).\n \"\"\"\n setup_class = _get_non_fixture_func(self.obj, \"setup_class\")\n teardown_class = getattr(self.obj, \"teardown_class\", None)\n if setup_class is None and teardown_class is None:\n return\n\n @fixtures.fixture(autouse=True, scope=\"class\")\n def xunit_setup_class_fixture(cls):\n if setup_class is not None:\n func = getimfunc(setup_class)\n _call_with_optional_argument(func, self.obj)\n yield\n if teardown_class is not None:\n func = getimfunc(teardown_class)\n _call_with_optional_argument(func, self.obj)\n\n self.obj.__pytest_setup_class = xunit_setup_class_fixture\n\n def _inject_setup_method_fixture(self):\n \"\"\"Injects a hidden autouse, function scoped fixture into the collected class object\n that invokes setup_method/teardown_method if either or both are available.\n\n Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with\n other fixtures (#517).\n \"\"\"\n setup_method = _get_non_fixture_func(self.obj, \"setup_method\")\n teardown_method = getattr(self.obj, \"teardown_method\", None)\n if setup_method is None and teardown_method is None:\n return\n\n @fixtures.fixture(autouse=True, scope=\"function\")\n def xunit_setup_method_fixture(self, request):\n method = request.function\n if setup_method is not None:\n func = getattr(self, \"setup_method\")\n _call_with_optional_argument(func, method)\n yield\n if teardown_method is not None:\n func = getattr(self, \"teardown_method\")\n _call_with_optional_argument(func, method)\n\n self.obj.__pytest_setup_method = xunit_setup_method_fixture\n\n\nclass Instance(PyCollector):\n _ALLOW_MARKERS = False # hack, destroy later\n # instances share the object with their parents in a way\n # that duplicates markers instances if not taken out\n # can be removed at node structure reorganization time\n\n def _getobj(self):\n return self.parent.obj()\n\n def collect(self):\n self.session._fixturemanager.parsefactories(self)\n return super(Instance, self).collect()\n\n def newinstance(self):\n self.obj = self._getobj()\n return self.obj\n\n\nclass FunctionMixin(PyobjMixin):\n \"\"\" mixin for the code common to Function and Generator.\n \"\"\"\n\n def setup(self):\n \"\"\" perform setup for this test function. \"\"\"\n if isinstance(self.parent, Instance):\n self.parent.newinstance()\n self.obj = self._getobj()\n\n def _prunetraceback(self, excinfo):\n if hasattr(self, \"_obj\") and not self.config.getoption(\"fulltrace\", False):\n code = _pytest._code.Code(get_real_func(self.obj))\n path, firstlineno = code.path, code.firstlineno\n traceback = excinfo.traceback\n ntraceback = traceback.cut(path=path, firstlineno=firstlineno)\n if ntraceback == traceback:\n ntraceback = ntraceback.cut(path=path)\n if ntraceback == traceback:\n ntraceback = ntraceback.filter(filter_traceback)\n if not ntraceback:\n ntraceback = traceback\n\n excinfo.traceback = ntraceback.filter()\n # issue364: mark all but first and last frames to\n # only show a single-line message for each frame\n if self.config.getoption(\"tbstyle\", \"auto\") == \"auto\":\n if len(excinfo.traceback) > 2:\n for entry in excinfo.traceback[1:-1]:\n entry.set_repr_style(\"short\")\n\n def repr_failure(self, excinfo, outerr=None):\n assert outerr is None, \"XXX outerr usage is deprecated\"\n style = self.config.getoption(\"tbstyle\", \"auto\")\n if style == \"auto\":\n style = \"long\"\n return self._repr_failure_py(excinfo, style=style)\n\n\ndef hasinit(obj):\n init = getattr(obj, \"__init__\", None)\n if init:\n return init != object.__init__\n\n\ndef hasnew(obj):\n new = getattr(obj, \"__new__\", None)\n if new:\n return new != object.__new__\n\n\nclass CallSpec2(object):\n def __init__(self, metafunc):\n self.metafunc = metafunc\n self.funcargs = {}\n self._idlist = []\n self.params = {}\n self._globalid = NOTSET\n self._globalparam = NOTSET\n self._arg2scopenum = {} # used for sorting parametrized resources\n self.marks = []\n self.indices = {}\n\n def copy(self):\n cs = CallSpec2(self.metafunc)\n cs.funcargs.update(self.funcargs)\n cs.params.update(self.params)\n cs.marks.extend(self.marks)\n cs.indices.update(self.indices)\n cs._arg2scopenum.update(self._arg2scopenum)\n cs._idlist = list(self._idlist)\n cs._globalid = self._globalid\n cs._globalparam = self._globalparam\n return cs\n\n def _checkargnotcontained(self, arg):\n if arg in self.params or arg in self.funcargs:\n raise ValueError(\"duplicate %r\" % (arg,))\n\n def getparam(self, name):\n try:\n return self.params[name]\n except KeyError:\n if self._globalparam is NOTSET:\n raise ValueError(name)\n return self._globalparam\n\n @property\n def id(self):\n return \"-\".join(map(str, filter(None, self._idlist)))\n\n def setmulti2(self, valtypes, argnames, valset, id, marks, scopenum, param_index):\n for arg, val in zip(argnames, valset):\n self._checkargnotcontained(arg)\n valtype_for_arg = valtypes[arg]\n getattr(self, valtype_for_arg)[arg] = val\n self.indices[arg] = param_index\n self._arg2scopenum[arg] = scopenum\n self._idlist.append(id)\n self.marks.extend(normalize_mark_list(marks))\n\n def setall(self, funcargs, id, param):\n for x in funcargs:\n self._checkargnotcontained(x)\n self.funcargs.update(funcargs)\n if id is not NOTSET:\n self._idlist.append(id)\n if param is not NOTSET:\n assert self._globalparam is NOTSET\n self._globalparam = param\n for arg in funcargs:\n self._arg2scopenum[arg] = fixtures.scopenum_function\n\n\nclass Metafunc(fixtures.FuncargnamesCompatAttr):\n \"\"\"\n Metafunc objects are passed to the :func:`pytest_generate_tests <_pytest.hookspec.pytest_generate_tests>` hook.\n They help to inspect a test function and to generate tests according to\n test configuration or values specified in the class or module where a\n test function is defined.\n \"\"\"\n\n def __init__(self, definition, fixtureinfo, config, cls=None, module=None):\n assert (\n isinstance(definition, FunctionDefinition)\n or type(definition).__name__ == \"DefinitionMock\"\n )\n self.definition = definition\n\n #: access to the :class:`_pytest.config.Config` object for the test session\n self.config = config\n\n #: the module object where the test function is defined in.\n self.module = module\n\n #: underlying python test function\n self.function = definition.obj\n\n #: set of fixture names required by the test function\n self.fixturenames = fixtureinfo.names_closure\n\n #: class object where the test function is defined in or ``None``.\n self.cls = cls\n\n self._calls = []\n self._ids = set()\n self._arg2fixturedefs = fixtureinfo.name2fixturedefs\n\n def parametrize(self, argnames, argvalues, indirect=False, ids=None, scope=None):\n \"\"\" Add new invocations to the underlying test function using the list\n of argvalues for the given argnames. Parametrization is performed\n during the collection phase. If you need to setup expensive resources\n see about setting indirect to do it rather at test setup time.\n\n :arg argnames: a comma-separated string denoting one or more argument\n names, or a list/tuple of argument strings.\n\n :arg argvalues: The list of argvalues determines how often a\n test is invoked with different argument values. If only one\n argname was specified argvalues is a list of values. If N\n argnames were specified, argvalues must be a list of N-tuples,\n where each tuple-element specifies a value for its respective\n argname.\n\n :arg indirect: The list of argnames or boolean. A list of arguments'\n names (subset of argnames). If True the list contains all names from\n the argnames. Each argvalue corresponding to an argname in this list will\n be passed as request.param to its respective argname fixture\n function so that it can perform more expensive setups during the\n setup phase of a test rather than at collection time.\n\n :arg ids: list of string ids, or a callable.\n If strings, each is corresponding to the argvalues so that they are\n part of the test id. If None is given as id of specific test, the\n automatically generated id for that argument will be used.\n If callable, it should take one argument (a single argvalue) and return\n a string or return None. If None, the automatically generated id for that\n argument will be used.\n If no ids are provided they will be generated automatically from\n the argvalues.\n\n :arg scope: if specified it denotes the scope of the parameters.\n The scope is used for grouping tests by parameter instances.\n It will also override any fixture-function defined scope, allowing\n to set a dynamic scope using test context or configuration.\n \"\"\"\n from _pytest.fixtures import scope2index\n from _pytest.mark import ParameterSet\n\n argnames, parameters = ParameterSet._for_parametrize(\n argnames,\n argvalues,\n self.function,\n self.config,\n function_definition=self.definition,\n )\n del argvalues\n\n if scope is None:\n scope = _find_parametrized_scope(argnames, self._arg2fixturedefs, indirect)\n\n self._validate_if_using_arg_names(argnames, indirect)\n\n arg_values_types = self._resolve_arg_value_types(argnames, indirect)\n\n ids = self._resolve_arg_ids(argnames, ids, parameters, item=self.definition)\n\n scopenum = scope2index(\n scope, descr=\"parametrize() call in {}\".format(self.function.__name__)\n )\n\n # create the new calls: if we are parametrize() multiple times (by applying the decorator\n # more than once) then we accumulate those calls generating the cartesian product\n # of all calls\n newcalls = []\n for callspec in self._calls or [CallSpec2(self)]:\n for param_index, (param_id, param_set) in enumerate(zip(ids, parameters)):\n newcallspec = callspec.copy()\n newcallspec.setmulti2(\n arg_values_types,\n argnames,\n param_set.values,\n param_id,\n param_set.marks,\n scopenum,\n param_index,\n )\n newcalls.append(newcallspec)\n self._calls = newcalls\n\n def _resolve_arg_ids(self, argnames, ids, parameters, item):\n \"\"\"Resolves the actual ids for the given argnames, based on the ``ids`` parameter given\n to ``parametrize``.\n\n :param List[str] argnames: list of argument names passed to ``parametrize()``.\n :param ids: the ids parameter of the parametrized call (see docs).\n :param List[ParameterSet] parameters: the list of parameter values, same size as ``argnames``.\n :param Item item: the item that generated this parametrized call.\n :rtype: List[str]\n :return: the list of ids for each argname given\n \"\"\"\n from _pytest._io.saferepr import saferepr\n\n idfn = None\n if callable(ids):\n idfn = ids\n ids = None\n if ids:\n func_name = self.function.__name__\n if len(ids) != len(parameters):\n msg = \"In {}: {} parameter sets specified, with different number of ids: {}\"\n fail(msg.format(func_name, len(parameters), len(ids)), pytrace=False)\n for id_value in ids:\n if id_value is not None and not isinstance(id_value, six.string_types):\n msg = \"In {}: ids must be list of strings, found: {} (type: {!r})\"\n fail(\n msg.format(func_name, saferepr(id_value), type(id_value)),\n pytrace=False,\n )\n ids = idmaker(argnames, parameters, idfn, ids, self.config, item=item)\n return ids\n\n def _resolve_arg_value_types(self, argnames, indirect):\n \"\"\"Resolves if each parametrized argument must be considered a parameter to a fixture or a \"funcarg\"\n to the function, based on the ``indirect`` parameter of the parametrized() call.\n\n :param List[str] argnames: list of argument names passed to ``parametrize()``.\n :param indirect: same ``indirect`` parameter of ``parametrize()``.\n :rtype: Dict[str, str]\n A dict mapping each arg name to either:\n * \"params\" if the argname should be the parameter of a fixture of the same name.\n * \"funcargs\" if the argname should be a parameter to the parametrized test function.\n \"\"\"\n valtypes = {}\n if indirect is True:\n valtypes = dict.fromkeys(argnames, \"params\")\n elif indirect is False:\n valtypes = dict.fromkeys(argnames, \"funcargs\")\n elif isinstance(indirect, (tuple, list)):\n valtypes = dict.fromkeys(argnames, \"funcargs\")\n for arg in indirect:\n if arg not in argnames:\n fail(\n \"In {}: indirect fixture '{}' doesn't exist\".format(\n self.function.__name__, arg\n ),\n pytrace=False,\n )\n valtypes[arg] = \"params\"\n return valtypes\n\n def _validate_if_using_arg_names(self, argnames, indirect):\n \"\"\"\n Check if all argnames are being used, by default values, or directly/indirectly.\n\n :param List[str] argnames: list of argument names passed to ``parametrize()``.\n :param indirect: same ``indirect`` parameter of ``parametrize()``.\n :raise ValueError: if validation fails.\n \"\"\"\n default_arg_names = set(get_default_arg_names(self.function))\n func_name = self.function.__name__\n for arg in argnames:\n if arg not in self.fixturenames:\n if arg in default_arg_names:\n fail(\n \"In {}: function already takes an argument '{}' with a default value\".format(\n func_name, arg\n ),\n pytrace=False,\n )\n else:\n if isinstance(indirect, (tuple, list)):\n name = \"fixture\" if arg in indirect else \"argument\"\n else:\n name = \"fixture\" if indirect else \"argument\"\n fail(\n \"In {}: function uses no {} '{}'\".format(func_name, name, arg),\n pytrace=False,\n )\n\n\ndef _find_parametrized_scope(argnames, arg2fixturedefs, indirect):\n \"\"\"Find the most appropriate scope for a parametrized call based on its arguments.\n\n When there's at least one direct argument, always use \"function\" scope.\n\n When a test function is parametrized and all its arguments are indirect\n (e.g. fixtures), return the most narrow scope based on the fixtures used.\n\n Related to issue #1832, based on code posted by @Kingdread.\n \"\"\"\n from _pytest.fixtures import scopes\n\n if isinstance(indirect, (list, tuple)):\n all_arguments_are_fixtures = len(indirect) == len(argnames)\n else:\n all_arguments_are_fixtures = bool(indirect)\n\n if all_arguments_are_fixtures:\n fixturedefs = arg2fixturedefs or {}\n used_scopes = [\n fixturedef[0].scope\n for name, fixturedef in fixturedefs.items()\n if name in argnames\n ]\n if used_scopes:\n # Takes the most narrow scope from used fixtures\n for scope in reversed(scopes):\n if scope in used_scopes:\n return scope\n\n return \"function\"\n\n\ndef _ascii_escaped_by_config(val, config):\n if config is None:\n escape_option = False\n else:\n escape_option = config.getini(\n \"disable_test_id_escaping_and_forfeit_all_rights_to_community_support\"\n )\n return val if escape_option else ascii_escaped(val)\n\n\ndef _idval(val, argname, idx, idfn, item, config):\n if idfn:\n try:\n generated_id = idfn(val)\n if generated_id is not None:\n val = generated_id\n except Exception as e:\n # See issue https://github.com/pytest-dev/pytest/issues/2169\n msg = \"{}: error raised while trying to determine id of parameter '{}' at position {}\\n\"\n msg = msg.format(item.nodeid, argname, idx)\n # we only append the exception type and message because on Python 2 reraise does nothing\n msg += \" {}: {}\\n\".format(type(e).__name__, e)\n six.raise_from(ValueError(msg), e)\n elif config:\n hook_id = config.hook.pytest_make_parametrize_id(\n config=config, val=val, argname=argname\n )\n if hook_id:\n return hook_id\n\n if isinstance(val, STRING_TYPES):\n return _ascii_escaped_by_config(val, config)\n elif val is None or isinstance(val, (float, int, bool)):\n return str(val)\n elif isinstance(val, REGEX_TYPE):\n return ascii_escaped(val.pattern)\n elif enum is not None and isinstance(val, enum.Enum):\n return str(val)\n elif (isclass(val) or isfunction(val)) and hasattr(val, \"__name__\"):\n return val.__name__\n return str(argname) + str(idx)\n\n\ndef _idvalset(idx, parameterset, argnames, idfn, ids, item, config):\n if parameterset.id is not None:\n return parameterset.id\n if ids is None or (idx >= len(ids) or ids[idx] is None):\n this_id = [\n _idval(val, argname, idx, idfn, item=item, config=config)\n for val, argname in zip(parameterset.values, argnames)\n ]\n return \"-\".join(this_id)\n else:\n return _ascii_escaped_by_config(ids[idx], config)\n\n\ndef idmaker(argnames, parametersets, idfn=None, ids=None, config=None, item=None):\n ids = [\n _idvalset(valindex, parameterset, argnames, idfn, ids, config=config, item=item)\n for valindex, parameterset in enumerate(parametersets)\n ]\n if len(set(ids)) != len(ids):\n # The ids are not unique\n duplicates = [testid for testid in ids if ids.count(testid) > 1]\n counters = collections.defaultdict(lambda: 0)\n for index, testid in enumerate(ids):\n if testid in duplicates:\n ids[index] = testid + str(counters[testid])\n counters[testid] += 1\n return ids\n\n\ndef show_fixtures_per_test(config):\n from _pytest.main import wrap_session\n\n return wrap_session(config, _show_fixtures_per_test)\n\n\ndef _show_fixtures_per_test(config, session):\n import _pytest.config\n\n session.perform_collect()\n curdir = py.path.local()\n tw = _pytest.config.create_terminal_writer(config)\n verbose = config.getvalue(\"verbose\")\n\n def get_best_relpath(func):\n loc = getlocation(func, curdir)\n return curdir.bestrelpath(loc)\n\n def write_fixture(fixture_def):\n argname = fixture_def.argname\n if verbose <= 0 and argname.startswith(\"_\"):\n return\n if verbose > 0:\n bestrel = get_best_relpath(fixture_def.func)\n funcargspec = \"{} -- {}\".format(argname, bestrel)\n else:\n funcargspec = argname\n tw.line(funcargspec, green=True)\n fixture_doc = fixture_def.func.__doc__\n if fixture_doc:\n write_docstring(tw, fixture_doc)\n else:\n tw.line(\" no docstring available\", red=True)\n\n def write_item(item):\n try:\n info = item._fixtureinfo\n except AttributeError:\n # doctests items have no _fixtureinfo attribute\n return\n if not info.name2fixturedefs:\n # this test item does not use any fixtures\n return\n tw.line()\n tw.sep(\"-\", \"fixtures used by {}\".format(item.name))\n tw.sep(\"-\", \"({})\".format(get_best_relpath(item.function)))\n # dict key not used in loop but needed for sorting\n for _, fixturedefs in sorted(info.name2fixturedefs.items()):\n assert fixturedefs is not None\n if not fixturedefs:\n continue\n # last item is expected to be the one used by the test item\n write_fixture(fixturedefs[-1])\n\n for session_item in session.items:\n write_item(session_item)\n\n\ndef showfixtures(config):\n from _pytest.main import wrap_session\n\n return wrap_session(config, _showfixtures_main)\n\n\ndef _showfixtures_main(config, session):\n import _pytest.config\n\n session.perform_collect()\n curdir = py.path.local()\n tw = _pytest.config.create_terminal_writer(config)\n verbose = config.getvalue(\"verbose\")\n\n fm = session._fixturemanager\n\n available = []\n seen = set()\n\n for argname, fixturedefs in fm._arg2fixturedefs.items():\n assert fixturedefs is not None\n if not fixturedefs:\n continue\n for fixturedef in fixturedefs:\n loc = getlocation(fixturedef.func, curdir)\n if (fixturedef.argname, loc) in seen:\n continue\n seen.add((fixturedef.argname, loc))\n available.append(\n (\n len(fixturedef.baseid),\n fixturedef.func.__module__,\n curdir.bestrelpath(loc),\n fixturedef.argname,\n fixturedef,\n )\n )\n\n available.sort()\n currentmodule = None\n for baseid, module, bestrel, argname, fixturedef in available:\n if currentmodule != module:\n if not module.startswith(\"_pytest.\"):\n tw.line()\n tw.sep(\"-\", \"fixtures defined from %s\" % (module,))\n currentmodule = module\n if verbose <= 0 and argname[0] == \"_\":\n continue\n tw.write(argname, green=True)\n if fixturedef.scope != \"function\":\n tw.write(\" [%s scope]\" % fixturedef.scope, cyan=True)\n if verbose > 0:\n tw.write(\" -- %s\" % bestrel, yellow=True)\n tw.write(\"\\n\")\n loc = getlocation(fixturedef.func, curdir)\n doc = fixturedef.func.__doc__ or \"\"\n if doc:\n write_docstring(tw, doc)\n else:\n tw.line(\" %s: no docstring available\" % (loc,), red=True)\n tw.line()\n\n\ndef write_docstring(tw, doc, indent=\" \"):\n doc = doc.rstrip()\n if \"\\n\" in doc:\n firstline, rest = doc.split(\"\\n\", 1)\n else:\n firstline, rest = doc, \"\"\n\n if firstline.strip():\n tw.line(indent + firstline.strip())\n\n if rest:\n for line in dedent(rest).split(\"\\n\"):\n tw.write(indent + line + \"\\n\")\n\n\nclass Function(FunctionMixin, nodes.Item, fixtures.FuncargnamesCompatAttr):\n \"\"\" a Function Item is responsible for setting up and executing a\n Python test function.\n \"\"\"\n\n # disable since functions handle it themselves\n _ALLOW_MARKERS = False\n\n def __init__(\n self,\n name,\n parent,\n args=None,\n config=None,\n callspec=None,\n callobj=NOTSET,\n keywords=None,\n session=None,\n fixtureinfo=None,\n originalname=None,\n ):\n super(Function, self).__init__(name, parent, config=config, session=session)\n self._args = args\n if callobj is not NOTSET:\n self.obj = callobj\n\n self.keywords.update(self.obj.__dict__)\n self.own_markers.extend(get_unpacked_marks(self.obj))\n if callspec:\n self.callspec = callspec\n # this is total hostile and a mess\n # keywords are broken by design by now\n # this will be redeemed later\n for mark in callspec.marks:\n # feel free to cry, this was broken for years before\n # and keywords cant fix it per design\n self.keywords[mark.name] = mark\n self.own_markers.extend(normalize_mark_list(callspec.marks))\n if keywords:\n self.keywords.update(keywords)\n\n # todo: this is a hell of a hack\n # https://github.com/pytest-dev/pytest/issues/4569\n\n self.keywords.update(\n dict.fromkeys(\n [\n mark.name\n for mark in self.iter_markers()\n if mark.name not in self.keywords\n ],\n True,\n )\n )\n\n if fixtureinfo is None:\n fixtureinfo = self.session._fixturemanager.getfixtureinfo(\n self, self.obj, self.cls, funcargs=True\n )\n self._fixtureinfo = fixtureinfo\n self.fixturenames = fixtureinfo.names_closure\n self._initrequest()\n\n #: original function name, without any decorations (for example\n #: parametrization adds a ``\"[...]\"`` suffix to function names).\n #:\n #: .. versionadded:: 3.0\n self.originalname = originalname\n\n def _initrequest(self):\n self.funcargs = {}\n self._request = fixtures.FixtureRequest(self)\n\n @property\n def function(self):\n \"underlying python 'function' object\"\n return getimfunc(self.obj)\n\n def _getobj(self):\n name = self.name\n i = name.find(\"[\") # parametrization\n if i != -1:\n name = name[:i]\n return getattr(self.parent.obj, name)\n\n @property\n def _pyfuncitem(self):\n \"(compatonly) for code expecting pytest-2.2 style request objects\"\n return self\n\n def runtest(self):\n \"\"\" execute the underlying test function. \"\"\"\n self.ihook.pytest_pyfunc_call(pyfuncitem=self)\n\n def setup(self):\n super(Function, self).setup()\n fixtures.fillfixtures(self)\n\n\nclass FunctionDefinition(Function):\n \"\"\"\n internal hack until we get actual definition nodes instead of the\n crappy metafunc hack\n \"\"\"\n\n def runtest(self):\n raise RuntimeError(\"function definitions are not supposed to be used\")\n\n setup = runtest\n"},{"attributeType":"null","col":4,"comment":"null","endLoc":29,"id":4669,"name":"enum","nodeType":"Attribute","startLoc":29,"text":"enum"},{"className":"CallSpec2","col":0,"comment":"null","endLoc":921,"id":4671,"nodeType":"Class","startLoc":861,"text":"class CallSpec2(object):\n def __init__(self, metafunc):\n self.metafunc = metafunc\n self.funcargs = {}\n self._idlist = []\n self.params = {}\n self._globalid = NOTSET\n self._globalparam = NOTSET\n self._arg2scopenum = {} # used for sorting parametrized resources\n self.marks = []\n self.indices = {}\n\n def copy(self):\n cs = CallSpec2(self.metafunc)\n cs.funcargs.update(self.funcargs)\n cs.params.update(self.params)\n cs.marks.extend(self.marks)\n cs.indices.update(self.indices)\n cs._arg2scopenum.update(self._arg2scopenum)\n cs._idlist = list(self._idlist)\n cs._globalid = self._globalid\n cs._globalparam = self._globalparam\n return cs\n\n def _checkargnotcontained(self, arg):\n if arg in self.params or arg in self.funcargs:\n raise ValueError(\"duplicate %r\" % (arg,))\n\n def getparam(self, name):\n try:\n return self.params[name]\n except KeyError:\n if self._globalparam is NOTSET:\n raise ValueError(name)\n return self._globalparam\n\n @property\n def id(self):\n return \"-\".join(map(str, filter(None, self._idlist)))\n\n def setmulti2(self, valtypes, argnames, valset, id, marks, scopenum, param_index):\n for arg, val in zip(argnames, valset):\n self._checkargnotcontained(arg)\n valtype_for_arg = valtypes[arg]\n getattr(self, valtype_for_arg)[arg] = val\n self.indices[arg] = param_index\n self._arg2scopenum[arg] = scopenum\n self._idlist.append(id)\n self.marks.extend(normalize_mark_list(marks))\n\n def setall(self, funcargs, id, param):\n for x in funcargs:\n self._checkargnotcontained(x)\n self.funcargs.update(funcargs)\n if id is not NOTSET:\n self._idlist.append(id)\n if param is not NOTSET:\n assert self._globalparam is NOTSET\n self._globalparam = param\n for arg in funcargs:\n self._arg2scopenum[arg] = fixtures.scopenum_function"},{"col":4,"comment":"null","endLoc":883,"header":"def copy(self)","id":4672,"name":"copy","nodeType":"Function","startLoc":873,"text":"def copy(self):\n cs = CallSpec2(self.metafunc)\n cs.funcargs.update(self.funcargs)\n cs.params.update(self.params)\n cs.marks.extend(self.marks)\n cs.indices.update(self.indices)\n cs._arg2scopenum.update(self._arg2scopenum)\n cs._idlist = list(self._idlist)\n cs._globalid = self._globalid\n cs._globalparam = self._globalparam\n return cs"},{"col":4,"comment":"null","endLoc":207,"header":"def test_setup_error(self, testdir)","id":4673,"name":"test_setup_error","nodeType":"Function","startLoc":187,"text":"def test_setup_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def arg(request):\n raise ValueError()\n def test_function(arg):\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(errors=1, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_setup_error\", name=\"test_function\")\n fnode = tnode.find_first_by_tag(\"error\")\n fnode.assert_attr(message=\"test setup failure\")\n assert \"ValueError\" in fnode.toxml()"},{"col":4,"comment":"null","endLoc":229,"header":"def test_teardown_error(self, testdir)","id":4674,"name":"test_teardown_error","nodeType":"Function","startLoc":209,"text":"def test_teardown_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def arg():\n yield\n raise ValueError()\n def test_function(arg):\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_teardown_error\", name=\"test_function\")\n fnode = tnode.find_first_by_tag(\"error\")\n fnode.assert_attr(message=\"test teardown failure\")\n assert \"ValueError\" in fnode.toxml()"},{"col":4,"comment":"null","endLoc":235,"header":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_call(self, item)","id":4675,"name":"pytest_runtest_call","nodeType":"Function","startLoc":232,"text":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_call(self, item):\n with self.item_capture(\"call\", item):\n yield"},{"col":4,"comment":"null","endLoc":254,"header":"def test_call_failure_teardown_error(self, testdir)","id":4676,"name":"test_call_failure_teardown_error","nodeType":"Function","startLoc":231,"text":"def test_call_failure_teardown_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def arg():\n yield\n raise Exception(\"Teardown Exception\")\n def test_function(arg):\n raise Exception(\"Call Exception\")\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(errors=1, failures=1, tests=1)\n first, second = dom.find_by_tag(\"testcase\")\n if not first or not second or first == second:\n assert 0\n fnode = first.find_first_by_tag(\"failure\")\n fnode.assert_attr(message=\"Exception: Call Exception\")\n snode = second.find_first_by_tag(\"error\")\n snode.assert_attr(message=\"test teardown failure\")"},{"col":4,"comment":"null","endLoc":240,"header":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_teardown(self, item)","id":4677,"name":"pytest_runtest_teardown","nodeType":"Function","startLoc":237,"text":"@pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_teardown(self, item):\n with self.item_capture(\"teardown\", item):\n yield"},{"col":0,"comment":"","endLoc":2,"header":"runner.py#","id":4678,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" basic collect and runtest protocol implementations \"\"\""},{"col":4,"comment":"null","endLoc":244,"header":"@pytest.hookimpl(tryfirst=True)\n def pytest_keyboard_interrupt(self, excinfo)","id":4679,"name":"pytest_keyboard_interrupt","nodeType":"Function","startLoc":242,"text":"@pytest.hookimpl(tryfirst=True)\n def pytest_keyboard_interrupt(self, excinfo):\n self.stop_global_capturing()"},{"id":4680,"name":"release-4.5.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-4.5.0\n=======================================\n\nThe pytest team is proud to announce the 4.5.0 release!\n\npytest is a mature Python testing tool with more than a 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n https://docs.pytest.org/en/latest/changelog.html\n\nFor complete documentation, please visit:\n\n https://docs.pytest.org/en/latest/\n\nAs usual, you can upgrade from pypi via:\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Floris Bruynooghe\n* Pulkit Goyal\n* Samuel Searles-Bryant\n* Zac Hatfield-Dodds\n* Zac-HD\n\n\nHappy testing,\nThe Pytest Development Team\n"},{"col":4,"comment":"null","endLoc":248,"header":"@pytest.hookimpl(tryfirst=True)\n def pytest_internalerror(self, excinfo)","id":4681,"name":"pytest_internalerror","nodeType":"Function","startLoc":246,"text":"@pytest.hookimpl(tryfirst=True)\n def pytest_internalerror(self, excinfo):\n self.stop_global_capturing()"},{"col":0,"comment":"null","endLoc":496,"header":"def test_callinfo()","id":4682,"name":"test_callinfo","nodeType":"Function","startLoc":484,"text":"def test_callinfo():\n ci = runner.CallInfo.from_call(lambda: 0, \"123\")\n assert ci.when == \"123\"\n assert ci.result == 0\n assert \"result\" in repr(ci)\n assert repr(ci) == \"\"\n\n ci = runner.CallInfo.from_call(lambda: 0 / 0, \"123\")\n assert ci.when == \"123\"\n assert not hasattr(ci, \"result\")\n assert repr(ci) == \"\"\n assert ci.excinfo\n assert \"exc\" in repr(ci)"},{"col":35,"endLoc":485,"id":4683,"nodeType":"Lambda","startLoc":485,"text":"lambda: 0"},{"col":35,"endLoc":491,"id":4684,"nodeType":"Lambda","startLoc":491,"text":"lambda: 0 / 0"},{"col":0,"comment":"null","endLoc":532,"header":"@pytest.mark.xfail\ndef test_runtest_in_module_ordering(testdir)","id":4685,"name":"test_runtest_in_module_ordering","nodeType":"Function","startLoc":503,"text":"@pytest.mark.xfail\ndef test_runtest_in_module_ordering(testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n import pytest\n def pytest_runtest_setup(item): # runs after class-level!\n item.function.mylist.append(\"module\")\n class TestClass(object):\n def pytest_runtest_setup(self, item):\n assert not hasattr(item.function, 'mylist')\n item.function.mylist = ['class']\n @pytest.fixture\n def mylist(self, request):\n return request.function.mylist\n def pytest_runtest_call(self, item, __multicall__):\n try:\n __multicall__.execute()\n except ValueError:\n pass\n def test_hello1(self, mylist):\n assert mylist == ['class', 'module'], mylist\n raise ValueError()\n def test_hello2(self, mylist):\n assert mylist == ['class', 'module'], mylist\n def pytest_runtest_teardown(item):\n del item.function.mylist\n \"\"\"\n )\n result = testdir.runpytest(p1)\n result.stdout.fnmatch_lines([\"*2 passed*\"])"},{"attributeType":"None","col":8,"comment":"null","endLoc":86,"id":4686,"name":"_current_item","nodeType":"Attribute","startLoc":86,"text":"self._current_item"},{"col":0,"comment":"null","endLoc":537,"header":"def test_outcomeexception_exceptionattributes()","id":4687,"name":"test_outcomeexception_exceptionattributes","nodeType":"Function","startLoc":535,"text":"def test_outcomeexception_exceptionattributes():\n outcome = outcomes.OutcomeException(\"test\")\n assert outcome.args[0] == outcome.msg"},{"col":0,"comment":"null","endLoc":144,"header":"def deselect_by_mark(items, config)","id":4688,"name":"deselect_by_mark","nodeType":"Function","startLoc":129,"text":"def deselect_by_mark(items, config):\n matchexpr = config.option.markexpr\n if not matchexpr:\n return\n\n remaining = []\n deselected = []\n for item in items:\n if matchmark(item, matchexpr):\n remaining.append(item)\n else:\n deselected.append(item)\n\n if deselected:\n config.hook.pytest_deselected(items=deselected)\n items[:] = remaining"},{"col":0,"comment":"null","endLoc":149,"header":"def pytest_collection_modifyitems(items, config)","id":4689,"name":"pytest_collection_modifyitems","nodeType":"Function","startLoc":147,"text":"def pytest_collection_modifyitems(items, config):\n deselect_by_keyword(items, config)\n deselect_by_mark(items, config)"},{"col":4,"comment":"null","endLoc":271,"header":"def test_skip_contains_name_reason(self, testdir)","id":4690,"name":"test_skip_contains_name_reason","nodeType":"Function","startLoc":256,"text":"def test_skip_contains_name_reason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_skip():\n pytest.skip(\"hello23\")\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_skip_contains_name_reason\", name=\"test_skip\")\n snode = tnode.find_first_by_tag(\"skipped\")\n snode.assert_attr(type=\"pytest.skip\", message=\"hello23\")"},{"fileName":"test_capture.py","filePath":"testing","id":4691,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport contextlib\nimport io\nimport os\nimport pickle\nimport subprocess\nimport sys\nimport textwrap\nfrom io import UnsupportedOperation\n\nimport py\nfrom six import text_type\n\nimport pytest\nfrom _pytest import capture\nfrom _pytest.capture import CaptureManager\nfrom _pytest.compat import _PY3\nfrom _pytest.main import EXIT_NOTESTSCOLLECTED\n\n# note: py.io capture tests where copied from\n# pylib 1.4.20.dev2 (rev 13d9af95547e)\n\n\nneedsosdup = pytest.mark.skipif(\n not hasattr(os, \"dup\"), reason=\"test needs os.dup, not available on this platform\"\n)\n\n\ndef StdCaptureFD(out=True, err=True, in_=True):\n return capture.MultiCapture(out, err, in_, Capture=capture.FDCapture)\n\n\ndef StdCapture(out=True, err=True, in_=True):\n return capture.MultiCapture(out, err, in_, Capture=capture.SysCapture)\n\n\nclass TestCaptureManager(object):\n def test_getmethod_default_no_fd(self, monkeypatch):\n from _pytest.capture import pytest_addoption\n from _pytest.config.argparsing import Parser\n\n parser = Parser()\n pytest_addoption(parser)\n default = parser._groups[0].options[0].default\n assert default == \"fd\" if hasattr(os, \"dup\") else \"sys\"\n parser = Parser()\n monkeypatch.delattr(os, \"dup\", raising=False)\n pytest_addoption(parser)\n assert parser._groups[0].options[0].default == \"sys\"\n\n @pytest.mark.parametrize(\n \"method\", [\"no\", \"sys\", pytest.param(\"fd\", marks=needsosdup)]\n )\n def test_capturing_basic_api(self, method):\n capouter = StdCaptureFD()\n old = sys.stdout, sys.stderr, sys.stdin\n try:\n capman = CaptureManager(method)\n capman.start_global_capturing()\n capman.suspend_global_capture()\n outerr = capman.read_global_capture()\n assert outerr == (\"\", \"\")\n capman.suspend_global_capture()\n outerr = capman.read_global_capture()\n assert outerr == (\"\", \"\")\n print(\"hello\")\n capman.suspend_global_capture()\n out, err = capman.read_global_capture()\n if method == \"no\":\n assert old == (sys.stdout, sys.stderr, sys.stdin)\n else:\n assert not out\n capman.resume_global_capture()\n print(\"hello\")\n capman.suspend_global_capture()\n out, err = capman.read_global_capture()\n if method != \"no\":\n assert out == \"hello\\n\"\n capman.stop_global_capturing()\n finally:\n capouter.stop_capturing()\n\n @needsosdup\n def test_init_capturing(self):\n capouter = StdCaptureFD()\n try:\n capman = CaptureManager(\"fd\")\n capman.start_global_capturing()\n pytest.raises(AssertionError, capman.start_global_capturing)\n capman.stop_global_capturing()\n finally:\n capouter.stop_capturing()\n\n\n@pytest.mark.parametrize(\"method\", [\"fd\", \"sys\"])\ndef test_capturing_unicode(testdir, method):\n if hasattr(sys, \"pypy_version_info\") and sys.pypy_version_info < (2, 2):\n pytest.xfail(\"does not work on pypy < 2.2\")\n if sys.version_info >= (3, 0):\n obj = \"'b\\u00f6y'\"\n else:\n obj = \"u'\\u00f6y'\"\n testdir.makepyfile(\n \"\"\"\n # -*- coding: utf-8 -*-\n # taken from issue 227 from nosetests\n def test_unicode():\n import sys\n print(sys.stdout)\n print(%s)\n \"\"\"\n % obj\n )\n result = testdir.runpytest(\"--capture=%s\" % method)\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\n@pytest.mark.parametrize(\"method\", [\"fd\", \"sys\"])\ndef test_capturing_bytes_in_utf8_encoding(testdir, method):\n testdir.makepyfile(\n \"\"\"\n def test_unicode():\n print('b\\\\u00f6y')\n \"\"\"\n )\n result = testdir.runpytest(\"--capture=%s\" % method)\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_collect_capturing(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import sys\n\n print(\"collect %s failure\" % 13)\n sys.stderr.write(\"collect %s_stderr failure\" % 13)\n import xyz42123\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n \"*Captured stdout*\",\n \"collect 13 failure\",\n \"*Captured stderr*\",\n \"collect 13_stderr failure\",\n ]\n )\n\n\nclass TestPerTestCapturing(object):\n def test_capture_and_fixtures(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def setup_module(mod):\n print(\"setup module\")\n def setup_function(function):\n print(\"setup \" + function.__name__)\n def test_func1():\n print(\"in func1\")\n assert 0\n def test_func2():\n print(\"in func2\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n \"setup module*\",\n \"setup test_func1*\",\n \"in func1*\",\n \"setup test_func2*\",\n \"in func2*\",\n ]\n )\n\n @pytest.mark.xfail(reason=\"unimplemented feature\")\n def test_capture_scope_cache(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import sys\n def setup_module(func):\n print(\"module-setup\")\n def setup_function(func):\n print(\"function-setup\")\n def test_func():\n print(\"in function\")\n assert 0\n def teardown_function(func):\n print(\"in teardown\")\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n \"*test_func():*\",\n \"*Captured stdout during setup*\",\n \"module-setup*\",\n \"function-setup*\",\n \"*Captured stdout*\",\n \"in teardown*\",\n ]\n )\n\n def test_no_carry_over(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_func1():\n print(\"in func1\")\n def test_func2():\n print(\"in func2\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p)\n s = result.stdout.str()\n assert \"in func1\" not in s\n assert \"in func2\" in s\n\n def test_teardown_capturing(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def setup_function(function):\n print(\"setup func1\")\n def teardown_function(function):\n print(\"teardown func1\")\n assert 0\n def test_func1():\n print(\"in func1\")\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n \"*teardown_function*\",\n \"*Captured stdout*\",\n \"setup func1*\",\n \"in func1*\",\n \"teardown func1*\",\n # \"*1 fixture failure*\"\n ]\n )\n\n def test_teardown_capturing_final(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def teardown_module(mod):\n print(\"teardown module\")\n assert 0\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n \"*def teardown_module(mod):*\",\n \"*Captured stdout*\",\n \"*teardown module*\",\n \"*1 error*\",\n ]\n )\n\n def test_capturing_outerr(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\\\n import sys\n def test_capturing():\n print(42)\n sys.stderr.write(str(23))\n def test_capturing_error():\n print(1)\n sys.stderr.write(str(2))\n raise ValueError\n \"\"\"\n )\n result = testdir.runpytest(p1)\n result.stdout.fnmatch_lines(\n [\n \"*test_capturing_outerr.py .F*\",\n \"====* FAILURES *====\",\n \"____*____\",\n \"*test_capturing_outerr.py:8: ValueError\",\n \"*--- Captured stdout *call*\",\n \"1\",\n \"*--- Captured stderr *call*\",\n \"2\",\n ]\n )\n\n\nclass TestLoggingInteraction(object):\n def test_logging_stream_ownership(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n def test_logging():\n import logging\n import pytest\n stream = capture.CaptureIO()\n logging.basicConfig(stream=stream)\n stream.close() # to free memory/release resources\n \"\"\"\n )\n result = testdir.runpytest_subprocess(p)\n assert result.stderr.str().find(\"atexit\") == -1\n\n def test_logging_and_immediate_setupteardown(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n import logging\n def setup_function(function):\n logging.warning(\"hello1\")\n\n def test_logging():\n logging.warning(\"hello2\")\n assert 0\n\n def teardown_function(function):\n logging.warning(\"hello3\")\n assert 0\n \"\"\"\n )\n for optargs in ((\"--capture=sys\",), (\"--capture=fd\",)):\n print(optargs)\n result = testdir.runpytest_subprocess(p, *optargs)\n s = result.stdout.str()\n result.stdout.fnmatch_lines(\n [\"*WARN*hello3\", \"*WARN*hello1\", \"*WARN*hello2\"] # errors show first!\n )\n # verify proper termination\n assert \"closed\" not in s\n\n def test_logging_and_crossscope_fixtures(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n import logging\n def setup_module(function):\n logging.warning(\"hello1\")\n\n def test_logging():\n logging.warning(\"hello2\")\n assert 0\n\n def teardown_module(function):\n logging.warning(\"hello3\")\n assert 0\n \"\"\"\n )\n for optargs in ((\"--capture=sys\",), (\"--capture=fd\",)):\n print(optargs)\n result = testdir.runpytest_subprocess(p, *optargs)\n s = result.stdout.str()\n result.stdout.fnmatch_lines(\n [\"*WARN*hello3\", \"*WARN*hello1\", \"*WARN*hello2\"] # errors come first\n )\n # verify proper termination\n assert \"closed\" not in s\n\n def test_conftestlogging_is_shown(self, testdir):\n testdir.makeconftest(\n \"\"\"\\\n import logging\n logging.basicConfig()\n logging.warning(\"hello435\")\n \"\"\"\n )\n # make sure that logging is still captured in tests\n result = testdir.runpytest_subprocess(\"-s\", \"-p\", \"no:capturelog\")\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result.stderr.fnmatch_lines([\"WARNING*hello435*\"])\n assert \"operation on closed file\" not in result.stderr.str()\n\n def test_conftestlogging_and_test_logging(self, testdir):\n testdir.makeconftest(\n \"\"\"\\\n import logging\n logging.basicConfig()\n \"\"\"\n )\n # make sure that logging is still captured in tests\n p = testdir.makepyfile(\n \"\"\"\\\n def test_hello():\n import logging\n logging.warning(\"hello433\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest_subprocess(p, \"-p\", \"no:capturelog\")\n assert result.ret != 0\n result.stdout.fnmatch_lines([\"WARNING*hello433*\"])\n assert \"something\" not in result.stderr.str()\n assert \"operation on closed file\" not in result.stderr.str()\n\n def test_logging_after_cap_stopped(self, testdir):\n testdir.makeconftest(\n \"\"\"\\\n import pytest\n import logging\n\n log = logging.getLogger(__name__)\n\n @pytest.fixture\n def log_on_teardown():\n yield\n log.warning('Logging on teardown')\n \"\"\"\n )\n # make sure that logging is still captured in tests\n p = testdir.makepyfile(\n \"\"\"\\\n def test_hello(log_on_teardown):\n import logging\n logging.warning(\"hello433\")\n assert 1\n raise KeyboardInterrupt()\n \"\"\"\n )\n result = testdir.runpytest_subprocess(p, \"--log-cli-level\", \"info\")\n assert result.ret != 0\n result.stdout.fnmatch_lines(\n [\"*WARNING*hello433*\", \"*WARNING*Logging on teardown*\"]\n )\n assert (\n \"AttributeError: 'NoneType' object has no attribute 'resume_capturing'\"\n not in result.stderr.str()\n )\n\n\nclass TestCaptureFixture(object):\n @pytest.mark.parametrize(\"opt\", [[], [\"-s\"]])\n def test_std_functional(self, testdir, opt):\n reprec = testdir.inline_runsource(\n \"\"\"\\\n def test_hello(capsys):\n print(42)\n out, err = capsys.readouterr()\n assert out.startswith(\"42\")\n \"\"\",\n *opt\n )\n reprec.assertoutcome(passed=1)\n\n def test_capsyscapfd(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n def test_one(capsys, capfd):\n pass\n def test_two(capfd, capsys):\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n \"*ERROR*setup*test_one*\",\n \"E*capfd*capsys*same*time*\",\n \"*ERROR*setup*test_two*\",\n \"E*capsys*capfd*same*time*\",\n \"*2 error*\",\n ]\n )\n\n def test_capturing_getfixturevalue(self, testdir):\n \"\"\"Test that asking for \"capfd\" and \"capsys\" using request.getfixturevalue\n in the same test is an error.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\\\n def test_one(capsys, request):\n request.getfixturevalue(\"capfd\")\n def test_two(capfd, request):\n request.getfixturevalue(\"capsys\")\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*test_one*\",\n \"*capsys*capfd*same*time*\",\n \"*test_two*\",\n \"*capfd*capsys*same*time*\",\n \"*2 failed in*\",\n ]\n )\n\n def test_capsyscapfdbinary(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n def test_one(capsys, capfdbinary):\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\"*ERROR*setup*test_one*\", \"E*capfdbinary*capsys*same*time*\", \"*1 error*\"]\n )\n\n @pytest.mark.parametrize(\"method\", [\"sys\", \"fd\"])\n def test_capture_is_represented_on_failure_issue128(self, testdir, method):\n p = testdir.makepyfile(\n \"\"\"\\\n def test_hello(cap{}):\n print(\"xxx42xxx\")\n assert 0\n \"\"\".format(\n method\n )\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"xxx42xxx\"])\n\n @needsosdup\n def test_stdfd_functional(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\\\n def test_hello(capfd):\n import os\n os.write(1, \"42\".encode('ascii'))\n out, err = capfd.readouterr()\n assert out.startswith(\"42\")\n capfd.close()\n \"\"\"\n )\n reprec.assertoutcome(passed=1)\n\n @needsosdup\n def test_capfdbinary(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\\\n def test_hello(capfdbinary):\n import os\n # some likely un-decodable bytes\n os.write(1, b'\\\\xfe\\\\x98\\\\x20')\n out, err = capfdbinary.readouterr()\n assert out == b'\\\\xfe\\\\x98\\\\x20'\n assert err == b''\n \"\"\"\n )\n reprec.assertoutcome(passed=1)\n\n @pytest.mark.skipif(\n sys.version_info < (3,), reason=\"only have capsysbinary in python 3\"\n )\n def test_capsysbinary(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\\\n def test_hello(capsysbinary):\n import sys\n # some likely un-decodable bytes\n sys.stdout.buffer.write(b'\\\\xfe\\\\x98\\\\x20')\n out, err = capsysbinary.readouterr()\n assert out == b'\\\\xfe\\\\x98\\\\x20'\n assert err == b''\n \"\"\"\n )\n reprec.assertoutcome(passed=1)\n\n @pytest.mark.skipif(\n sys.version_info >= (3,), reason=\"only have capsysbinary in python 3\"\n )\n def test_capsysbinary_forbidden_in_python2(self, testdir):\n testdir.makepyfile(\n \"\"\"\\\n def test_hello(capsysbinary):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*test_hello*\",\n \"*capsysbinary is only supported on Python 3*\",\n \"*1 error in*\",\n ]\n )\n\n def test_partial_setup_failure(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n def test_hello(capsys, missingarg):\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*test_partial_setup_failure*\", \"*1 error*\"])\n\n @needsosdup\n def test_keyboardinterrupt_disables_capturing(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n def test_hello(capfd):\n import os\n os.write(1, str(42).encode('ascii'))\n raise KeyboardInterrupt()\n \"\"\"\n )\n result = testdir.runpytest_subprocess(p)\n result.stdout.fnmatch_lines([\"*KeyboardInterrupt*\"])\n assert result.ret == 2\n\n def test_capture_and_logging(self, testdir):\n \"\"\"#14\"\"\"\n p = testdir.makepyfile(\n \"\"\"\\\n import logging\n def test_log(capsys):\n logging.error('x')\n \"\"\"\n )\n result = testdir.runpytest_subprocess(p)\n assert \"closed\" not in result.stderr.str()\n\n @pytest.mark.parametrize(\"fixture\", [\"capsys\", \"capfd\"])\n @pytest.mark.parametrize(\"no_capture\", [True, False])\n def test_disabled_capture_fixture(self, testdir, fixture, no_capture):\n testdir.makepyfile(\n \"\"\"\\\n def test_disabled({fixture}):\n print('captured before')\n with {fixture}.disabled():\n print('while capture is disabled')\n print('captured after')\n assert {fixture}.readouterr() == ('captured before\\\\ncaptured after\\\\n', '')\n\n def test_normal():\n print('test_normal executed')\n \"\"\".format(\n fixture=fixture\n )\n )\n args = (\"-s\",) if no_capture else ()\n result = testdir.runpytest_subprocess(*args)\n result.stdout.fnmatch_lines(\n \"\"\"\n *while capture is disabled*\n \"\"\"\n )\n assert \"captured before\" not in result.stdout.str()\n assert \"captured after\" not in result.stdout.str()\n if no_capture:\n assert \"test_normal executed\" in result.stdout.str()\n else:\n assert \"test_normal executed\" not in result.stdout.str()\n\n @pytest.mark.parametrize(\"fixture\", [\"capsys\", \"capfd\"])\n def test_fixture_use_by_other_fixtures(self, testdir, fixture):\n \"\"\"\n Ensure that capsys and capfd can be used by other fixtures during setup and teardown.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\\\n from __future__ import print_function\n import sys\n import pytest\n\n @pytest.fixture\n def captured_print({fixture}):\n print('stdout contents begin')\n print('stderr contents begin', file=sys.stderr)\n out, err = {fixture}.readouterr()\n\n yield out, err\n\n print('stdout contents end')\n print('stderr contents end', file=sys.stderr)\n out, err = {fixture}.readouterr()\n assert out == 'stdout contents end\\\\n'\n assert err == 'stderr contents end\\\\n'\n\n def test_captured_print(captured_print):\n out, err = captured_print\n assert out == 'stdout contents begin\\\\n'\n assert err == 'stderr contents begin\\\\n'\n \"\"\".format(\n fixture=fixture\n )\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n assert \"stdout contents begin\" not in result.stdout.str()\n assert \"stderr contents begin\" not in result.stdout.str()\n\n @pytest.mark.parametrize(\"cap\", [\"capsys\", \"capfd\"])\n def test_fixture_use_by_other_fixtures_teardown(self, testdir, cap):\n \"\"\"Ensure we can access setup and teardown buffers from teardown when using capsys/capfd (##3033)\"\"\"\n testdir.makepyfile(\n \"\"\"\\\n import sys\n import pytest\n import os\n\n @pytest.fixture()\n def fix({cap}):\n print(\"setup out\")\n sys.stderr.write(\"setup err\\\\n\")\n yield\n out, err = {cap}.readouterr()\n assert out == 'setup out\\\\ncall out\\\\n'\n assert err == 'setup err\\\\ncall err\\\\n'\n\n def test_a(fix):\n print(\"call out\")\n sys.stderr.write(\"call err\\\\n\")\n \"\"\".format(\n cap=cap\n )\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n\ndef test_setup_failure_does_not_kill_capturing(testdir):\n sub1 = testdir.mkpydir(\"sub1\")\n sub1.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def pytest_runtest_setup(item):\n raise ValueError(42)\n \"\"\"\n )\n )\n sub1.join(\"test_mod.py\").write(\"def test_func1(): pass\")\n result = testdir.runpytest(testdir.tmpdir, \"--traceconfig\")\n result.stdout.fnmatch_lines([\"*ValueError(42)*\", \"*1 error*\"])\n\n\ndef test_fdfuncarg_skips_on_no_osdup(testdir):\n testdir.makepyfile(\n \"\"\"\n import os\n if hasattr(os, 'dup'):\n del os.dup\n def test_hello(capfd):\n pass\n \"\"\"\n )\n result = testdir.runpytest_subprocess(\"--capture=no\")\n result.stdout.fnmatch_lines([\"*1 skipped*\"])\n\n\ndef test_capture_conftest_runtest_setup(testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_runtest_setup():\n print(\"hello19\")\n \"\"\"\n )\n testdir.makepyfile(\"def test_func(): pass\")\n result = testdir.runpytest()\n assert result.ret == 0\n assert \"hello19\" not in result.stdout.str()\n\n\ndef test_capture_badoutput_issue412(testdir):\n testdir.makepyfile(\n \"\"\"\n import os\n\n def test_func():\n omg = bytearray([1,129,1])\n os.write(1, omg)\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"--cap=fd\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *def test_func*\n *assert 0*\n *Captured*\n *1 failed*\n \"\"\"\n )\n\n\ndef test_capture_early_option_parsing(testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_runtest_setup():\n print(\"hello19\")\n \"\"\"\n )\n testdir.makepyfile(\"def test_func(): pass\")\n result = testdir.runpytest(\"-vs\")\n assert result.ret == 0\n assert \"hello19\" in result.stdout.str()\n\n\ndef test_capture_binary_output(testdir):\n testdir.makepyfile(\n r\"\"\"\n import pytest\n\n def test_a():\n import sys\n import subprocess\n subprocess.call([sys.executable, __file__])\n\n def test_foo():\n import os;os.write(1, b'\\xc3')\n\n if __name__ == '__main__':\n test_foo()\n \"\"\"\n )\n result = testdir.runpytest(\"--assert=plain\")\n result.assert_outcomes(passed=2)\n\n\ndef test_error_during_readouterr(testdir):\n \"\"\"Make sure we suspend capturing if errors occur during readouterr\"\"\"\n testdir.makepyfile(\n pytest_xyz=\"\"\"\n from _pytest.capture import FDCapture\n\n def bad_snap(self):\n raise Exception('boom')\n\n assert FDCapture.snap\n FDCapture.snap = bad_snap\n \"\"\"\n )\n result = testdir.runpytest_subprocess(\"-p\", \"pytest_xyz\", \"--version\")\n result.stderr.fnmatch_lines(\n [\"*in bad_snap\", \" raise Exception('boom')\", \"Exception: boom\"]\n )\n\n\nclass TestCaptureIO(object):\n def test_text(self):\n f = capture.CaptureIO()\n f.write(\"hello\")\n s = f.getvalue()\n assert s == \"hello\"\n f.close()\n\n def test_unicode_and_str_mixture(self):\n f = capture.CaptureIO()\n if sys.version_info >= (3, 0):\n f.write(\"\\u00f6\")\n pytest.raises(TypeError, f.write, b\"hello\")\n else:\n f.write(u\"\\u00f6\")\n f.write(b\"hello\")\n s = f.getvalue()\n f.close()\n assert isinstance(s, text_type)\n\n @pytest.mark.skipif(sys.version_info[0] == 2, reason=\"python 3 only behaviour\")\n def test_write_bytes_to_buffer(self):\n \"\"\"In python3, stdout / stderr are text io wrappers (exposing a buffer\n property of the underlying bytestream). See issue #1407\n \"\"\"\n f = capture.CaptureIO()\n f.buffer.write(b\"foo\\r\\n\")\n assert f.getvalue() == \"foo\\r\\n\"\n\n\ndef test_dontreadfrominput():\n from _pytest.capture import DontReadFromInput\n\n f = DontReadFromInput()\n assert not f.isatty()\n pytest.raises(IOError, f.read)\n pytest.raises(IOError, f.readlines)\n iter_f = iter(f)\n pytest.raises(IOError, next, iter_f)\n pytest.raises(UnsupportedOperation, f.fileno)\n f.close() # just for completeness\n\n\n@pytest.mark.skipif(\"sys.version_info < (3,)\", reason=\"python2 has no buffer\")\ndef test_dontreadfrominput_buffer_python3():\n from _pytest.capture import DontReadFromInput\n\n f = DontReadFromInput()\n fb = f.buffer\n assert not fb.isatty()\n pytest.raises(IOError, fb.read)\n pytest.raises(IOError, fb.readlines)\n iter_f = iter(f)\n pytest.raises(IOError, next, iter_f)\n pytest.raises(ValueError, fb.fileno)\n f.close() # just for completeness\n\n\n@pytest.mark.skipif(\"sys.version_info >= (3,)\", reason=\"python2 has no buffer\")\ndef test_dontreadfrominput_buffer_python2():\n from _pytest.capture import DontReadFromInput\n\n f = DontReadFromInput()\n with pytest.raises(AttributeError):\n f.buffer\n f.close() # just for completeness\n\n\n@pytest.yield_fixture\ndef tmpfile(testdir):\n f = testdir.makepyfile(\"\").open(\"wb+\")\n yield f\n if not f.closed:\n f.close()\n\n\n@needsosdup\ndef test_dupfile(tmpfile):\n flist = []\n for i in range(5):\n nf = capture.safe_text_dupfile(tmpfile, \"wb\")\n assert nf != tmpfile\n assert nf.fileno() != tmpfile.fileno()\n assert nf not in flist\n print(i, end=\"\", file=nf)\n flist.append(nf)\n\n fname_open = flist[0].name\n assert fname_open == repr(flist[0].buffer)\n\n for i in range(5):\n f = flist[i]\n f.close()\n fname_closed = flist[0].name\n assert fname_closed == repr(flist[0].buffer)\n assert fname_closed != fname_open\n tmpfile.seek(0)\n s = tmpfile.read()\n assert \"01234\" in repr(s)\n tmpfile.close()\n assert fname_closed == repr(flist[0].buffer)\n\n\ndef test_dupfile_on_bytesio():\n bio = io.BytesIO()\n f = capture.safe_text_dupfile(bio, \"wb\")\n f.write(\"hello\")\n assert bio.getvalue() == b\"hello\"\n assert \"BytesIO object\" in f.name\n\n\ndef test_dupfile_on_textio():\n tio = py.io.TextIO()\n f = capture.safe_text_dupfile(tio, \"wb\")\n f.write(\"hello\")\n assert tio.getvalue() == \"hello\"\n assert not hasattr(f, \"name\")\n\n\n@contextlib.contextmanager\ndef lsof_check():\n pid = os.getpid()\n try:\n out = subprocess.check_output((\"lsof\", \"-p\", str(pid))).decode()\n except (OSError, subprocess.CalledProcessError, UnicodeDecodeError):\n # about UnicodeDecodeError, see note on pytester\n pytest.skip(\"could not run 'lsof'\")\n yield\n out2 = subprocess.check_output((\"lsof\", \"-p\", str(pid))).decode()\n len1 = len([x for x in out.split(\"\\n\") if \"REG\" in x])\n len2 = len([x for x in out2.split(\"\\n\") if \"REG\" in x])\n assert len2 < len1 + 3, out2\n\n\nclass TestFDCapture(object):\n pytestmark = needsosdup\n\n def test_simple(self, tmpfile):\n fd = tmpfile.fileno()\n cap = capture.FDCapture(fd)\n data = b\"hello\"\n os.write(fd, data)\n s = cap.snap()\n cap.done()\n assert not s\n cap = capture.FDCapture(fd)\n cap.start()\n os.write(fd, data)\n s = cap.snap()\n cap.done()\n assert s == \"hello\"\n\n def test_simple_many(self, tmpfile):\n for i in range(10):\n self.test_simple(tmpfile)\n\n def test_simple_many_check_open_files(self, testdir):\n with lsof_check():\n with testdir.makepyfile(\"\").open(\"wb+\") as tmpfile:\n self.test_simple_many(tmpfile)\n\n def test_simple_fail_second_start(self, tmpfile):\n fd = tmpfile.fileno()\n cap = capture.FDCapture(fd)\n cap.done()\n pytest.raises(ValueError, cap.start)\n\n def test_stderr(self):\n cap = capture.FDCapture(2)\n cap.start()\n print(\"hello\", file=sys.stderr)\n s = cap.snap()\n cap.done()\n assert s == \"hello\\n\"\n\n def test_stdin(self, tmpfile):\n cap = capture.FDCapture(0)\n cap.start()\n x = os.read(0, 100).strip()\n cap.done()\n assert x == b\"\"\n\n def test_writeorg(self, tmpfile):\n data1, data2 = b\"foo\", b\"bar\"\n cap = capture.FDCapture(tmpfile.fileno())\n cap.start()\n tmpfile.write(data1)\n tmpfile.flush()\n cap.writeorg(data2)\n scap = cap.snap()\n cap.done()\n assert scap == data1.decode(\"ascii\")\n with open(tmpfile.name, \"rb\") as stmp_file:\n stmp = stmp_file.read()\n assert stmp == data2\n\n def test_simple_resume_suspend(self, tmpfile):\n with saved_fd(1):\n cap = capture.FDCapture(1)\n cap.start()\n data = b\"hello\"\n os.write(1, data)\n sys.stdout.write(\"whatever\")\n s = cap.snap()\n assert s == \"hellowhatever\"\n cap.suspend()\n os.write(1, b\"world\")\n sys.stdout.write(\"qlwkej\")\n assert not cap.snap()\n cap.resume()\n os.write(1, b\"but now\")\n sys.stdout.write(\" yes\\n\")\n s = cap.snap()\n assert s == \"but now yes\\n\"\n cap.suspend()\n cap.done()\n pytest.raises(AttributeError, cap.suspend)\n\n def test_capfd_sys_stdout_mode(self, capfd):\n assert \"b\" not in sys.stdout.mode\n\n\n@contextlib.contextmanager\ndef saved_fd(fd):\n new_fd = os.dup(fd)\n try:\n yield\n finally:\n os.dup2(new_fd, fd)\n os.close(new_fd)\n\n\nclass TestStdCapture(object):\n captureclass = staticmethod(StdCapture)\n\n @contextlib.contextmanager\n def getcapture(self, **kw):\n cap = self.__class__.captureclass(**kw)\n cap.start_capturing()\n try:\n yield cap\n finally:\n cap.stop_capturing()\n\n def test_capturing_done_simple(self):\n with self.getcapture() as cap:\n sys.stdout.write(\"hello\")\n sys.stderr.write(\"world\")\n out, err = cap.readouterr()\n assert out == \"hello\"\n assert err == \"world\"\n\n def test_capturing_reset_simple(self):\n with self.getcapture() as cap:\n print(\"hello world\")\n sys.stderr.write(\"hello error\\n\")\n out, err = cap.readouterr()\n assert out == \"hello world\\n\"\n assert err == \"hello error\\n\"\n\n def test_capturing_readouterr(self):\n with self.getcapture() as cap:\n print(\"hello world\")\n sys.stderr.write(\"hello error\\n\")\n out, err = cap.readouterr()\n assert out == \"hello world\\n\"\n assert err == \"hello error\\n\"\n sys.stderr.write(\"error2\")\n out, err = cap.readouterr()\n assert err == \"error2\"\n\n def test_capture_results_accessible_by_attribute(self):\n with self.getcapture() as cap:\n sys.stdout.write(\"hello\")\n sys.stderr.write(\"world\")\n capture_result = cap.readouterr()\n assert capture_result.out == \"hello\"\n assert capture_result.err == \"world\"\n\n def test_capturing_readouterr_unicode(self):\n with self.getcapture() as cap:\n print(\"hxąć\")\n out, err = cap.readouterr()\n assert out == u\"hxąć\\n\"\n\n @pytest.mark.skipif(\n \"sys.version_info >= (3,)\", reason=\"text output different for bytes on python3\"\n )\n def test_capturing_readouterr_decode_error_handling(self):\n with self.getcapture() as cap:\n # triggered an internal error in pytest\n print(\"\\xa6\")\n out, err = cap.readouterr()\n assert out == u\"\\ufffd\\n\"\n\n def test_reset_twice_error(self):\n with self.getcapture() as cap:\n print(\"hello\")\n out, err = cap.readouterr()\n pytest.raises(ValueError, cap.stop_capturing)\n assert out == \"hello\\n\"\n assert not err\n\n def test_capturing_modify_sysouterr_in_between(self):\n oldout = sys.stdout\n olderr = sys.stderr\n with self.getcapture() as cap:\n sys.stdout.write(\"hello\")\n sys.stderr.write(\"world\")\n sys.stdout = capture.CaptureIO()\n sys.stderr = capture.CaptureIO()\n print(\"not seen\")\n sys.stderr.write(\"not seen\\n\")\n out, err = cap.readouterr()\n assert out == \"hello\"\n assert err == \"world\"\n assert sys.stdout == oldout\n assert sys.stderr == olderr\n\n def test_capturing_error_recursive(self):\n with self.getcapture() as cap1:\n print(\"cap1\")\n with self.getcapture() as cap2:\n print(\"cap2\")\n out2, err2 = cap2.readouterr()\n out1, err1 = cap1.readouterr()\n assert out1 == \"cap1\\n\"\n assert out2 == \"cap2\\n\"\n\n def test_just_out_capture(self):\n with self.getcapture(out=True, err=False) as cap:\n sys.stdout.write(\"hello\")\n sys.stderr.write(\"world\")\n out, err = cap.readouterr()\n assert out == \"hello\"\n assert not err\n\n def test_just_err_capture(self):\n with self.getcapture(out=False, err=True) as cap:\n sys.stdout.write(\"hello\")\n sys.stderr.write(\"world\")\n out, err = cap.readouterr()\n assert err == \"world\"\n assert not out\n\n def test_stdin_restored(self):\n old = sys.stdin\n with self.getcapture(in_=True):\n newstdin = sys.stdin\n assert newstdin != sys.stdin\n assert sys.stdin is old\n\n def test_stdin_nulled_by_default(self):\n print(\"XXX this test may well hang instead of crashing\")\n print(\"XXX which indicates an error in the underlying capturing\")\n print(\"XXX mechanisms\")\n with self.getcapture():\n pytest.raises(IOError, sys.stdin.read)\n\n\nclass TestStdCaptureFD(TestStdCapture):\n pytestmark = needsosdup\n captureclass = staticmethod(StdCaptureFD)\n\n def test_simple_only_fd(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import os\n def test_x():\n os.write(1, \"hello\\\\n\".encode(\"ascii\"))\n assert 0\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines(\n \"\"\"\n *test_x*\n *assert 0*\n *Captured stdout*\n \"\"\"\n )\n\n def test_intermingling(self):\n with self.getcapture() as cap:\n os.write(1, b\"1\")\n sys.stdout.write(str(2))\n sys.stdout.flush()\n os.write(1, b\"3\")\n os.write(2, b\"a\")\n sys.stderr.write(\"b\")\n sys.stderr.flush()\n os.write(2, b\"c\")\n out, err = cap.readouterr()\n assert out == \"123\"\n assert err == \"abc\"\n\n def test_many(self, capfd):\n with lsof_check():\n for i in range(10):\n cap = StdCaptureFD()\n cap.stop_capturing()\n\n\nclass TestStdCaptureFDinvalidFD(object):\n pytestmark = needsosdup\n\n def test_stdcapture_fd_invalid_fd(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import os\n from _pytest import capture\n\n def StdCaptureFD(out=True, err=True, in_=True):\n return capture.MultiCapture(out, err, in_, Capture=capture.FDCapture)\n\n def test_stdout():\n os.close(1)\n cap = StdCaptureFD(out=True, err=False, in_=False)\n assert repr(cap.out) == \"\"\n cap.stop_capturing()\n\n def test_stderr():\n os.close(2)\n cap = StdCaptureFD(out=False, err=True, in_=False)\n assert repr(cap.err) == \"\"\n cap.stop_capturing()\n\n def test_stdin():\n os.close(0)\n cap = StdCaptureFD(out=False, err=False, in_=True)\n assert repr(cap.in_) == \"\"\n cap.stop_capturing()\n \"\"\"\n )\n result = testdir.runpytest_subprocess(\"--capture=fd\")\n assert result.ret == 0\n assert result.parseoutcomes()[\"passed\"] == 3\n\n\ndef test_capture_not_started_but_reset():\n capsys = StdCapture()\n capsys.stop_capturing()\n\n\ndef test_using_capsys_fixture_works_with_sys_stdout_encoding(capsys):\n test_text = \"test text\"\n\n print(test_text.encode(sys.stdout.encoding, \"replace\"))\n (out, err) = capsys.readouterr()\n assert out\n assert err == \"\"\n\n\ndef test_capsys_results_accessible_by_attribute(capsys):\n sys.stdout.write(\"spam\")\n sys.stderr.write(\"eggs\")\n capture_result = capsys.readouterr()\n assert capture_result.out == \"spam\"\n assert capture_result.err == \"eggs\"\n\n\n@needsosdup\n@pytest.mark.parametrize(\"use\", [True, False])\ndef test_fdcapture_tmpfile_remains_the_same(tmpfile, use):\n if not use:\n tmpfile = True\n cap = StdCaptureFD(out=False, err=tmpfile)\n try:\n cap.start_capturing()\n capfile = cap.err.tmpfile\n cap.readouterr()\n finally:\n cap.stop_capturing()\n capfile2 = cap.err.tmpfile\n assert capfile2 == capfile\n\n\n@needsosdup\ndef test_close_and_capture_again(testdir):\n testdir.makepyfile(\n \"\"\"\n import os\n def test_close():\n os.close(1)\n def test_capture_again():\n os.write(1, b\"hello\\\\n\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines(\n \"\"\"\n *test_capture_again*\n *assert 0*\n *stdout*\n *hello*\n \"\"\"\n )\n\n\n@pytest.mark.parametrize(\"method\", [\"SysCapture\", \"FDCapture\"])\ndef test_capturing_and_logging_fundamentals(testdir, method):\n if method == \"StdCaptureFD\" and not hasattr(os, \"dup\"):\n pytest.skip(\"need os.dup\")\n # here we check a fundamental feature\n p = testdir.makepyfile(\n \"\"\"\n import sys, os\n import py, logging\n from _pytest import capture\n cap = capture.MultiCapture(out=False, in_=False,\n Capture=capture.%s)\n cap.start_capturing()\n\n logging.warning(\"hello1\")\n outerr = cap.readouterr()\n print(\"suspend, captured %%s\" %%(outerr,))\n logging.warning(\"hello2\")\n\n cap.pop_outerr_to_orig()\n logging.warning(\"hello3\")\n\n outerr = cap.readouterr()\n print(\"suspend2, captured %%s\" %% (outerr,))\n \"\"\"\n % (method,)\n )\n result = testdir.runpython(p)\n result.stdout.fnmatch_lines(\n \"\"\"\n suspend, captured*hello1*\n suspend2, captured*WARNING:root:hello3*\n \"\"\"\n )\n result.stderr.fnmatch_lines(\n \"\"\"\n WARNING:root:hello2\n \"\"\"\n )\n assert \"atexit\" not in result.stderr.str()\n\n\ndef test_error_attribute_issue555(testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n def test_capattr():\n assert sys.stdout.errors == \"strict\"\n assert sys.stderr.errors == \"strict\"\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n\n@pytest.mark.skipif(\n not sys.platform.startswith(\"win\") and sys.version_info[:2] >= (3, 6),\n reason=\"only py3.6+ on windows\",\n)\ndef test_py36_windowsconsoleio_workaround_non_standard_streams():\n \"\"\"\n Ensure _py36_windowsconsoleio_workaround function works with objects that\n do not implement the full ``io``-based stream protocol, for example execnet channels (#2666).\n \"\"\"\n from _pytest.capture import _py36_windowsconsoleio_workaround\n\n class DummyStream(object):\n def write(self, s):\n pass\n\n stream = DummyStream()\n _py36_windowsconsoleio_workaround(stream)\n\n\ndef test_dontreadfrominput_has_encoding(testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n def test_capattr():\n # should not raise AttributeError\n assert sys.stdout.encoding\n assert sys.stderr.encoding\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n\ndef test_crash_on_closing_tmpfile_py27(testdir):\n p = testdir.makepyfile(\n \"\"\"\n from __future__ import print_function\n import threading\n import sys\n\n printing = threading.Event()\n\n def spam():\n f = sys.stderr\n print('SPAMBEFORE', end='', file=f)\n printing.set()\n\n while True:\n try:\n f.flush()\n except (OSError, ValueError):\n break\n\n def test_spam_in_thread():\n t = threading.Thread(target=spam)\n t.daemon = True\n t.start()\n\n printing.wait()\n \"\"\"\n )\n result = testdir.runpytest_subprocess(str(p))\n assert result.ret == 0\n assert result.stderr.str() == \"\"\n assert \"IOError\" not in result.stdout.str()\n\n\ndef test_pickling_and_unpickling_encoded_file():\n # See https://bitbucket.org/pytest-dev/pytest/pull-request/194\n # pickle.loads() raises infinite recursion if\n # EncodedFile.__getattr__ is not implemented properly\n ef = capture.EncodedFile(None, None)\n ef_as_str = pickle.dumps(ef)\n pickle.loads(ef_as_str)\n\n\ndef test_global_capture_with_live_logging(testdir):\n # Issue 3819\n # capture should work with live cli logging\n\n # Teardown report seems to have the capture for the whole process (setup, capture, teardown)\n testdir.makeconftest(\n \"\"\"\n def pytest_runtest_logreport(report):\n if \"test_global\" in report.nodeid:\n if report.when == \"teardown\":\n with open(\"caplog\", \"w\") as f:\n f.write(report.caplog)\n with open(\"capstdout\", \"w\") as f:\n f.write(report.capstdout)\n \"\"\"\n )\n\n testdir.makepyfile(\n \"\"\"\n import logging\n import sys\n import pytest\n\n logger = logging.getLogger(__name__)\n\n @pytest.fixture\n def fix1():\n print(\"fix setup\")\n logging.info(\"fix setup\")\n yield\n logging.info(\"fix teardown\")\n print(\"fix teardown\")\n\n def test_global(fix1):\n print(\"begin test\")\n logging.info(\"something in test\")\n print(\"end test\")\n \"\"\"\n )\n result = testdir.runpytest_subprocess(\"--log-cli-level=INFO\")\n assert result.ret == 0\n\n with open(\"caplog\", \"r\") as f:\n caplog = f.read()\n\n assert \"fix setup\" in caplog\n assert \"something in test\" in caplog\n assert \"fix teardown\" in caplog\n\n with open(\"capstdout\", \"r\") as f:\n capstdout = f.read()\n\n assert \"fix setup\" in capstdout\n assert \"begin test\" in capstdout\n assert \"end test\" in capstdout\n assert \"fix teardown\" in capstdout\n\n\n@pytest.mark.parametrize(\"capture_fixture\", [\"capsys\", \"capfd\"])\ndef test_capture_with_live_logging(testdir, capture_fixture):\n # Issue 3819\n # capture should work with live cli logging\n\n testdir.makepyfile(\n \"\"\"\n import logging\n import sys\n\n logger = logging.getLogger(__name__)\n\n def test_capture({0}):\n print(\"hello\")\n sys.stderr.write(\"world\\\\n\")\n captured = {0}.readouterr()\n assert captured.out == \"hello\\\\n\"\n assert captured.err == \"world\\\\n\"\n\n logging.info(\"something\")\n print(\"next\")\n logging.info(\"something\")\n\n captured = {0}.readouterr()\n assert captured.out == \"next\\\\n\"\n \"\"\".format(\n capture_fixture\n )\n )\n\n result = testdir.runpytest_subprocess(\"--log-cli-level=INFO\")\n assert result.ret == 0\n\n\ndef test_typeerror_encodedfile_write(testdir):\n \"\"\"It should behave the same with and without output capturing (#4861).\"\"\"\n p = testdir.makepyfile(\n \"\"\"\n def test_fails():\n import sys\n sys.stdout.write(b\"foo\")\n \"\"\"\n )\n result_without_capture = testdir.runpytest(\"-s\", str(p))\n\n result_with_capture = testdir.runpytest(str(p))\n\n assert result_with_capture.ret == result_without_capture.ret\n\n if _PY3:\n result_with_capture.stdout.fnmatch_lines(\n [\"E TypeError: write() argument must be str, not bytes\"]\n )\n else:\n assert result_with_capture.ret == 0\n"},{"col":0,"comment":"null","endLoc":166,"header":"def pytest_unconfigure(config)","id":4692,"name":"pytest_unconfigure","nodeType":"Function","startLoc":165,"text":"def pytest_unconfigure(config):\n MARK_GEN._config = getattr(config, \"_old_mark_config\", None)"},{"col":0,"comment":"null","endLoc":545,"header":"def test_outcomeexception_passes_except_Exception()","id":4693,"name":"test_outcomeexception_passes_except_Exception","nodeType":"Function","startLoc":540,"text":"def test_outcomeexception_passes_except_Exception():\n with pytest.raises(outcomes.OutcomeException):\n try:\n raise outcomes.OutcomeException(\"test\")\n except Exception:\n pass"},{"attributeType":"null","col":0,"comment":"null","endLoc":18,"id":4694,"name":"__all__","nodeType":"Attribute","startLoc":18,"text":"__all__"},{"col":0,"comment":"","endLoc":2,"header":"__init__.py#","id":4695,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" generic mechanism for marking and selecting python functions. \"\"\"\n\n__all__ = [\"Mark\", \"MarkDecorator\", \"MarkGenerator\", \"get_empty_parameterset_mark\"]\n\npytest_cmdline_main.tryfirst = True"},{"attributeType":"None","col":8,"comment":"null","endLoc":85,"id":4696,"name":"_global_capturing","nodeType":"Attribute","startLoc":85,"text":"self._global_capturing"},{"attributeType":"null","col":8,"comment":"null","endLoc":84,"id":4697,"name":"_method","nodeType":"Attribute","startLoc":84,"text":"self._method"},{"className":"CaptureFixture","col":0,"comment":"\n Object returned by :py:func:`capsys`, :py:func:`capsysbinary`, :py:func:`capfd` and :py:func:`capfdbinary`\n fixtures.\n ","endLoc":405,"id":4698,"nodeType":"Class","startLoc":348,"text":"class CaptureFixture(object):\n \"\"\"\n Object returned by :py:func:`capsys`, :py:func:`capsysbinary`, :py:func:`capfd` and :py:func:`capfdbinary`\n fixtures.\n \"\"\"\n\n def __init__(self, captureclass, request):\n self.captureclass = captureclass\n self.request = request\n self._capture = None\n self._captured_out = self.captureclass.EMPTY_BUFFER\n self._captured_err = self.captureclass.EMPTY_BUFFER\n\n def _start(self):\n if self._capture is None:\n self._capture = MultiCapture(\n out=True, err=True, in_=False, Capture=self.captureclass\n )\n self._capture.start_capturing()\n\n def close(self):\n if self._capture is not None:\n out, err = self._capture.pop_outerr_to_orig()\n self._captured_out += out\n self._captured_err += err\n self._capture.stop_capturing()\n self._capture = None\n\n def readouterr(self):\n \"\"\"Read and return the captured output so far, resetting the internal buffer.\n\n :return: captured content as a namedtuple with ``out`` and ``err`` string attributes\n \"\"\"\n captured_out, captured_err = self._captured_out, self._captured_err\n if self._capture is not None:\n out, err = self._capture.readouterr()\n captured_out += out\n captured_err += err\n self._captured_out = self.captureclass.EMPTY_BUFFER\n self._captured_err = self.captureclass.EMPTY_BUFFER\n return CaptureResult(captured_out, captured_err)\n\n def _suspend(self):\n \"\"\"Suspends this fixture's own capturing temporarily.\"\"\"\n if self._capture is not None:\n self._capture.suspend_capturing()\n\n def _resume(self):\n \"\"\"Resumes this fixture's own capturing temporarily.\"\"\"\n if self._capture is not None:\n self._capture.resume_capturing()\n\n @contextlib.contextmanager\n def disabled(self):\n \"\"\"Temporarily disables capture while inside the 'with' block.\"\"\"\n capmanager = self.request.config.pluginmanager.getplugin(\"capturemanager\")\n with capmanager.global_and_fixture_disabled():\n yield"},{"id":4699,"name":"sprint2016.rst","nodeType":"TextFile","path":"doc/en/announce","text":"python testing sprint June 20th-26th 2016\n======================================================\n\n.. image:: ../img/freiburg2.jpg\n :width: 400\n\nThe pytest core group held the biggest sprint\nin its history in June 2016, taking place in the black forest town Freiburg\nin Germany. In February 2016 we started a `funding\ncampaign on Indiegogo to cover expenses\n`_ The page also mentions\nsome preliminary topics:\n\n- improving pytest-xdist test scheduling to take into account\n fixture setups and explicit user hints.\n\n- provide info on fixture dependencies during --collect-only\n\n- tying pytest-xdist to tox so that you can do \"py.test -e py34\"\n to run tests in a particular tox-managed virtualenv. Also\n look into making pytest-xdist use tox environments on\n remote ssh-sides so that remote dependency management becomes\n easier.\n\n- refactoring the fixture system so more people understand it :)\n\n- integrating PyUnit setup methods as autouse fixtures.\n possibly adding ways to influence ordering of same-scoped\n fixtures (so you can make a choice of which fixtures come\n before others)\n\n- fixing bugs and issues from the tracker, really an endless source :)\n\n\nParticipants\n--------------\n\nOver 20 participants took part from 4 continents, including employees\nfrom Splunk, Personalkollen, Cobe.io, FanDuel and Dolby. Some newcomers\nmixed with developers who have worked on pytest since its beginning, and\nof course everyone in between.\n\n\nSprint organisation, schedule\n-------------------------------\n\nPeople arrived in Freiburg on the 19th, with sprint development taking\nplace on 20th, 21st, 22nd, 24th and 25th. On the 23rd we took a break\nday for some hot hiking in the Black Forest.\n\nSprint activity was organised heavily around pairing, with plenty of group\ndiscusssions to take advantage of the high bandwidth, and lightning talks\nas well.\n\n\nMoney / funding\n---------------\n\n\nThe Indiegogo campaign aimed for 11000 USD and in the end raised over\n12000, to reimburse travel costs, pay for a sprint venue and catering.\n\nExcess money is reserved for further sprint/travel funding for pytest/tox\ncontributors.\n"},{"col":4,"comment":"null","endLoc":291,"header":"def test_mark_skip_contains_name_reason(self, testdir)","id":4700,"name":"test_mark_skip_contains_name_reason","nodeType":"Function","startLoc":273,"text":"def test_mark_skip_contains_name_reason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip(reason=\"hello24\")\n def test_skip():\n assert True\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(\n classname=\"test_mark_skip_contains_name_reason\", name=\"test_skip\"\n )\n snode = tnode.find_first_by_tag(\"skipped\")\n snode.assert_attr(type=\"pytest.skip\", message=\"hello24\")"},{"col":4,"comment":"null","endLoc":359,"header":"def __init__(self, captureclass, request)","id":4701,"name":"__init__","nodeType":"Function","startLoc":354,"text":"def __init__(self, captureclass, request):\n self.captureclass = captureclass\n self.request = request\n self._capture = None\n self._captured_out = self.captureclass.EMPTY_BUFFER\n self._captured_err = self.captureclass.EMPTY_BUFFER"},{"col":4,"comment":"null","endLoc":366,"header":"def _start(self)","id":4702,"name":"_start","nodeType":"Function","startLoc":361,"text":"def _start(self):\n if self._capture is None:\n self._capture = MultiCapture(\n out=True, err=True, in_=False, Capture=self.captureclass\n )\n self._capture.start_capturing()"},{"col":4,"comment":"null","endLoc":381,"header":"def pytest_plugin_registered(self, plugin)","id":4703,"name":"pytest_plugin_registered","nodeType":"Function","startLoc":375,"text":"def pytest_plugin_registered(self, plugin):\n if self.config.option.traceconfig:\n msg = \"PLUGIN registered: %s\" % (plugin,)\n # XXX this event may happen during setup/teardown time\n # which unfortunately captures our output here\n # which garbles our output if we use self.write_line\n self.write_line(msg)"},{"col":4,"comment":"null","endLoc":384,"header":"def pytest_deselected(self, items)","id":4704,"name":"pytest_deselected","nodeType":"Function","startLoc":383,"text":"def pytest_deselected(self, items):\n self.stats.setdefault(\"deselected\", []).extend(items)"},{"col":0,"comment":"null","endLoc":551,"header":"def test_pytest_exit()","id":4705,"name":"test_pytest_exit","nodeType":"Function","startLoc":548,"text":"def test_pytest_exit():\n with pytest.raises(pytest.exit.Exception) as excinfo:\n pytest.exit(\"hello\")\n assert excinfo.errisinstance(pytest.exit.Exception)"},{"fileName":"deprecated_test.py","filePath":"testing","id":4706,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nimport pytest\nfrom _pytest.warning_types import PytestDeprecationWarning\nfrom _pytest.warnings import SHOW_PYTEST_WARNINGS_ARG\n\npytestmark = pytest.mark.pytester_example_path(\"deprecated\")\n\n\ndef test_pytest_setup_cfg_unsupported(testdir):\n testdir.makefile(\n \".cfg\",\n setup=\"\"\"\n [pytest]\n addopts = --verbose\n \"\"\",\n )\n with pytest.raises(pytest.fail.Exception):\n testdir.runpytest()\n\n\ndef test_pytest_custom_cfg_unsupported(testdir):\n testdir.makefile(\n \".cfg\",\n custom=\"\"\"\n [pytest]\n addopts = --verbose\n \"\"\",\n )\n with pytest.raises(pytest.fail.Exception):\n testdir.runpytest(\"-c\", \"custom.cfg\")\n\n\ndef test_getfuncargvalue_is_deprecated(request):\n pytest.deprecated_call(request.getfuncargvalue, \"tmpdir\")\n\n\n@pytest.mark.filterwarnings(\"default\")\ndef test_resultlog_is_deprecated(testdir):\n result = testdir.runpytest(\"--help\")\n result.stdout.fnmatch_lines([\"*DEPRECATED path for machine-readable result log*\"])\n\n testdir.makepyfile(\n \"\"\"\n def test():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--result-log=%s\" % testdir.tmpdir.join(\"result.log\"))\n result.stdout.fnmatch_lines(\n [\n \"*--result-log is deprecated and scheduled for removal in pytest 5.0*\",\n \"*See https://docs.pytest.org/en/latest/deprecations.html#result-log-result-log for more information*\",\n ]\n )\n\n\ndef test_terminal_reporter_writer_attr(pytestconfig):\n \"\"\"Check that TerminalReporter._tw is also available as 'writer' (#2984)\n This attribute is planned to be deprecated in 3.4.\n \"\"\"\n try:\n import xdist # noqa\n\n pytest.skip(\"xdist workers disable the terminal reporter plugin\")\n except ImportError:\n pass\n terminal_reporter = pytestconfig.pluginmanager.get_plugin(\"terminalreporter\")\n assert terminal_reporter.writer is terminal_reporter._tw\n\n\n@pytest.mark.parametrize(\"plugin\", [\"catchlog\", \"capturelog\"])\n@pytest.mark.filterwarnings(\"default\")\ndef test_pytest_catchlog_deprecated(testdir, plugin):\n testdir.makepyfile(\n \"\"\"\n def test_func(pytestconfig):\n pytestconfig.pluginmanager.register(None, 'pytest_{}')\n \"\"\".format(\n plugin\n )\n )\n res = testdir.runpytest()\n assert res.ret == 0\n res.stdout.fnmatch_lines(\n [\"*pytest-*log plugin has been merged into the core*\", \"*1 passed, 1 warnings*\"]\n )\n\n\ndef test_raises_message_argument_deprecated():\n with pytest.warns(pytest.PytestDeprecationWarning):\n with pytest.raises(RuntimeError, message=\"foobar\"):\n raise RuntimeError\n\n\ndef test_pytest_plugins_in_non_top_level_conftest_deprecated(testdir):\n from _pytest.deprecated import PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST\n\n testdir.makepyfile(\n **{\n \"subdirectory/conftest.py\": \"\"\"\n pytest_plugins=['capture']\n \"\"\"\n }\n )\n testdir.makepyfile(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n res = testdir.runpytest(SHOW_PYTEST_WARNINGS_ARG)\n assert res.ret == 2\n msg = str(PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST).splitlines()[0]\n res.stdout.fnmatch_lines(\n [\"*{msg}*\".format(msg=msg), \"*subdirectory{sep}conftest.py*\".format(sep=os.sep)]\n )\n\n\n@pytest.mark.parametrize(\"use_pyargs\", [True, False])\ndef test_pytest_plugins_in_non_top_level_conftest_unsupported_pyargs(\n testdir, use_pyargs\n):\n \"\"\"When using --pyargs, do not emit the warning about non-top-level conftest warnings (#4039, #4044)\"\"\"\n from _pytest.deprecated import PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST\n\n files = {\n \"src/pkg/__init__.py\": \"\",\n \"src/pkg/conftest.py\": \"\",\n \"src/pkg/test_root.py\": \"def test(): pass\",\n \"src/pkg/sub/__init__.py\": \"\",\n \"src/pkg/sub/conftest.py\": \"pytest_plugins=['capture']\",\n \"src/pkg/sub/test_bar.py\": \"def test(): pass\",\n }\n testdir.makepyfile(**files)\n testdir.syspathinsert(testdir.tmpdir.join(\"src\"))\n\n args = (\"--pyargs\", \"pkg\") if use_pyargs else ()\n args += (SHOW_PYTEST_WARNINGS_ARG,)\n res = testdir.runpytest(*args)\n assert res.ret == (0 if use_pyargs else 2)\n msg = str(PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST).splitlines()[0]\n if use_pyargs:\n assert msg not in res.stdout.str()\n else:\n res.stdout.fnmatch_lines([\"*{msg}*\".format(msg=msg)])\n\n\ndef test_pytest_plugins_in_non_top_level_conftest_unsupported_no_top_level_conftest(\n testdir\n):\n from _pytest.deprecated import PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST\n\n subdirectory = testdir.tmpdir.join(\"subdirectory\")\n subdirectory.mkdir()\n testdir.makeconftest(\n \"\"\"\n pytest_plugins=['capture']\n \"\"\"\n )\n testdir.tmpdir.join(\"conftest.py\").move(subdirectory.join(\"conftest.py\"))\n\n testdir.makepyfile(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n\n res = testdir.runpytest_subprocess()\n assert res.ret == 2\n msg = str(PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST).splitlines()[0]\n res.stdout.fnmatch_lines(\n [\"*{msg}*\".format(msg=msg), \"*subdirectory{sep}conftest.py*\".format(sep=os.sep)]\n )\n\n\ndef test_pytest_plugins_in_non_top_level_conftest_unsupported_no_false_positives(\n testdir\n):\n from _pytest.deprecated import PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST\n\n subdirectory = testdir.tmpdir.join(\"subdirectory\")\n subdirectory.mkdir()\n testdir.makeconftest(\n \"\"\"\n pass\n \"\"\"\n )\n testdir.tmpdir.join(\"conftest.py\").move(subdirectory.join(\"conftest.py\"))\n\n testdir.makeconftest(\n \"\"\"\n import warnings\n warnings.filterwarnings('always', category=DeprecationWarning)\n pytest_plugins=['capture']\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n res = testdir.runpytest_subprocess()\n assert res.ret == 0\n msg = str(PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST).splitlines()[0]\n assert msg not in res.stdout.str()\n\n\ndef test_fixture_named_request(testdir):\n testdir.copy_example()\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*'request' is a reserved name for fixtures and will raise an error in future versions\"\n ]\n )\n\n\ndef test_pytest_warns_unknown_kwargs():\n with pytest.warns(\n PytestDeprecationWarning,\n match=r\"pytest.warns\\(\\) got unexpected keyword arguments: \\['foo'\\]\",\n ):\n pytest.warns(UserWarning, foo=\"hello\")\n"},{"col":0,"comment":"null","endLoc":24,"header":"def test_pytest_setup_cfg_unsupported(testdir)","id":4707,"name":"test_pytest_setup_cfg_unsupported","nodeType":"Function","startLoc":15,"text":"def test_pytest_setup_cfg_unsupported(testdir):\n testdir.makefile(\n \".cfg\",\n setup=\"\"\"\n [pytest]\n addopts = --verbose\n \"\"\",\n )\n with pytest.raises(pytest.fail.Exception):\n testdir.runpytest()"},{"col":4,"comment":"null","endLoc":312,"header":"def test_mark_skipif_contains_name_reason(self, testdir)","id":4708,"name":"test_mark_skipif_contains_name_reason","nodeType":"Function","startLoc":293,"text":"def test_mark_skipif_contains_name_reason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n GLOBAL_CONDITION = True\n @pytest.mark.skipif(GLOBAL_CONDITION, reason=\"hello25\")\n def test_skip():\n assert True\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(\n classname=\"test_mark_skipif_contains_name_reason\", name=\"test_skip\"\n )\n snode = tnode.find_first_by_tag(\"skipped\")\n snode.assert_attr(type=\"pytest.skip\", message=\"hello25\")"},{"col":0,"comment":"null","endLoc":36,"header":"def test_pytest_custom_cfg_unsupported(testdir)","id":4709,"name":"test_pytest_custom_cfg_unsupported","nodeType":"Function","startLoc":27,"text":"def test_pytest_custom_cfg_unsupported(testdir):\n testdir.makefile(\n \".cfg\",\n custom=\"\"\"\n [pytest]\n addopts = --verbose\n \"\"\",\n )\n with pytest.raises(pytest.fail.Exception):\n testdir.runpytest(\"-c\", \"custom.cfg\")"},{"col":0,"comment":"null","endLoc":558,"header":"def test_pytest_fail()","id":4710,"name":"test_pytest_fail","nodeType":"Function","startLoc":554,"text":"def test_pytest_fail():\n with pytest.raises(pytest.fail.Exception) as excinfo:\n pytest.fail(\"hello\")\n s = excinfo.exconly(tryshort=True)\n assert s.startswith(\"Failed\")"},{"col":0,"comment":"null","endLoc":40,"header":"def test_getfuncargvalue_is_deprecated(request)","id":4711,"name":"test_getfuncargvalue_is_deprecated","nodeType":"Function","startLoc":39,"text":"def test_getfuncargvalue_is_deprecated(request):\n pytest.deprecated_call(request.getfuncargvalue, \"tmpdir\")"},{"col":0,"comment":"null","endLoc":60,"header":"@pytest.mark.filterwarnings(\"default\")\ndef test_resultlog_is_deprecated(testdir)","id":4712,"name":"test_resultlog_is_deprecated","nodeType":"Function","startLoc":43,"text":"@pytest.mark.filterwarnings(\"default\")\ndef test_resultlog_is_deprecated(testdir):\n result = testdir.runpytest(\"--help\")\n result.stdout.fnmatch_lines([\"*DEPRECATED path for machine-readable result log*\"])\n\n testdir.makepyfile(\n \"\"\"\n def test():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--result-log=%s\" % testdir.tmpdir.join(\"result.log\"))\n result.stdout.fnmatch_lines(\n [\n \"*--result-log is deprecated and scheduled for removal in pytest 5.0*\",\n \"*See https://docs.pytest.org/en/latest/deprecations.html#result-log-result-log for more information*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":374,"header":"def close(self)","id":4713,"name":"close","nodeType":"Function","startLoc":368,"text":"def close(self):\n if self._capture is not None:\n out, err = self._capture.pop_outerr_to_orig()\n self._captured_out += out\n self._captured_err += err\n self._capture.stop_capturing()\n self._capture = None"},{"col":4,"comment":"null","endLoc":394,"header":"def pytest_runtest_logstart(self, nodeid, location)","id":4714,"name":"pytest_runtest_logstart","nodeType":"Function","startLoc":386,"text":"def pytest_runtest_logstart(self, nodeid, location):\n # ensure that the path is printed before the\n # 1st test of a module starts running\n if self.showlongtestinfo:\n line = self._locationline(nodeid, *location)\n self.write_ensure_prefix(line, \"\")\n elif self.showfspath:\n fsid = nodeid.split(\"::\")[0]\n self.write_fspath_result(fsid, \"\")"},{"col":4,"comment":"null","endLoc":326,"header":"def test_mark_skip_doesnt_capture_output(self, testdir)","id":4715,"name":"test_mark_skip_doesnt_capture_output","nodeType":"Function","startLoc":314,"text":"def test_mark_skip_doesnt_capture_output(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip(reason=\"foo\")\n def test_skip():\n print(\"bar!\")\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node_xml = dom.find_first_by_tag(\"testsuite\").toxml()\n assert \"bar!\" not in node_xml"},{"col":0,"comment":"null","endLoc":571,"header":"def test_pytest_exit_msg(testdir)","id":4716,"name":"test_pytest_exit_msg","nodeType":"Function","startLoc":561,"text":"def test_pytest_exit_msg(testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n def pytest_configure(config):\n pytest.exit('oh noes')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stderr.fnmatch_lines([\"Exit: oh noes\"])"},{"fileName":"test_collection.py","filePath":"testing","id":4717,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport pprint\nimport sys\nimport textwrap\n\nimport py\n\nimport pytest\nfrom _pytest.main import _in_venv\nfrom _pytest.main import EXIT_INTERRUPTED\nfrom _pytest.main import EXIT_NOTESTSCOLLECTED\nfrom _pytest.main import Session\n\n\nclass TestCollector(object):\n def test_collect_versus_item(self):\n from pytest import Collector, Item\n\n assert not issubclass(Collector, Item)\n assert not issubclass(Item, Collector)\n\n def test_check_equality(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n def test_pass(): pass\n def test_fail(): assert 0\n \"\"\"\n )\n fn1 = testdir.collect_by_name(modcol, \"test_pass\")\n assert isinstance(fn1, pytest.Function)\n fn2 = testdir.collect_by_name(modcol, \"test_pass\")\n assert isinstance(fn2, pytest.Function)\n\n assert fn1 == fn2\n assert fn1 != modcol\n if sys.version_info < (3, 0):\n assert cmp(fn1, fn2) == 0 # NOQA\n assert hash(fn1) == hash(fn2)\n\n fn3 = testdir.collect_by_name(modcol, \"test_fail\")\n assert isinstance(fn3, pytest.Function)\n assert not (fn1 == fn3)\n assert fn1 != fn3\n\n for fn in fn1, fn2, fn3:\n assert fn != 3\n assert fn != modcol\n assert fn != [1, 2, 3]\n assert [1, 2, 3] != fn\n assert modcol != fn\n\n def test_getparent(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n class TestClass(object):\n def test_foo():\n pass\n \"\"\"\n )\n cls = testdir.collect_by_name(modcol, \"TestClass\")\n fn = testdir.collect_by_name(testdir.collect_by_name(cls, \"()\"), \"test_foo\")\n\n parent = fn.getparent(pytest.Module)\n assert parent is modcol\n\n parent = fn.getparent(pytest.Function)\n assert parent is fn\n\n parent = fn.getparent(pytest.Class)\n assert parent is cls\n\n def test_getcustomfile_roundtrip(self, testdir):\n hello = testdir.makefile(\".xxx\", hello=\"world\")\n testdir.makepyfile(\n conftest=\"\"\"\n import pytest\n class CustomFile(pytest.File):\n pass\n def pytest_collect_file(path, parent):\n if path.ext == \".xxx\":\n return CustomFile(path, parent=parent)\n \"\"\"\n )\n node = testdir.getpathnode(hello)\n assert isinstance(node, pytest.File)\n assert node.name == \"hello.xxx\"\n nodes = node.session.perform_collect([node.nodeid], genitems=False)\n assert len(nodes) == 1\n assert isinstance(nodes[0], pytest.File)\n\n def test_can_skip_class_with_test_attr(self, testdir):\n \"\"\"Assure test class is skipped when using `__test__=False` (See #2007).\"\"\"\n testdir.makepyfile(\n \"\"\"\n class TestFoo(object):\n __test__ = False\n def __init__(self):\n pass\n def test_foo():\n assert True\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"collected 0 items\", \"*no tests ran in*\"])\n\n\nclass TestCollectFS(object):\n def test_ignored_certain_directories(self, testdir):\n tmpdir = testdir.tmpdir\n tmpdir.ensure(\"build\", \"test_notfound.py\")\n tmpdir.ensure(\"dist\", \"test_notfound.py\")\n tmpdir.ensure(\"_darcs\", \"test_notfound.py\")\n tmpdir.ensure(\"CVS\", \"test_notfound.py\")\n tmpdir.ensure(\"{arch}\", \"test_notfound.py\")\n tmpdir.ensure(\".whatever\", \"test_notfound.py\")\n tmpdir.ensure(\".bzr\", \"test_notfound.py\")\n tmpdir.ensure(\"normal\", \"test_found.py\")\n for x in tmpdir.visit(\"test_*.py\"):\n x.write(\"def test_hello(): pass\")\n\n result = testdir.runpytest(\"--collect-only\")\n s = result.stdout.str()\n assert \"test_notfound\" not in s\n assert \"test_found\" in s\n\n @pytest.mark.parametrize(\n \"fname\",\n (\n \"activate\",\n \"activate.csh\",\n \"activate.fish\",\n \"Activate\",\n \"Activate.bat\",\n \"Activate.ps1\",\n ),\n )\n def test_ignored_virtualenvs(self, testdir, fname):\n bindir = \"Scripts\" if sys.platform.startswith(\"win\") else \"bin\"\n testdir.tmpdir.ensure(\"virtual\", bindir, fname)\n testfile = testdir.tmpdir.ensure(\"virtual\", \"test_invenv.py\")\n testfile.write(\"def test_hello(): pass\")\n\n # by default, ignore tests inside a virtualenv\n result = testdir.runpytest()\n assert \"test_invenv\" not in result.stdout.str()\n # allow test collection if user insists\n result = testdir.runpytest(\"--collect-in-virtualenv\")\n assert \"test_invenv\" in result.stdout.str()\n # allow test collection if user directly passes in the directory\n result = testdir.runpytest(\"virtual\")\n assert \"test_invenv\" in result.stdout.str()\n\n @pytest.mark.parametrize(\n \"fname\",\n (\n \"activate\",\n \"activate.csh\",\n \"activate.fish\",\n \"Activate\",\n \"Activate.bat\",\n \"Activate.ps1\",\n ),\n )\n def test_ignored_virtualenvs_norecursedirs_precedence(self, testdir, fname):\n bindir = \"Scripts\" if sys.platform.startswith(\"win\") else \"bin\"\n # norecursedirs takes priority\n testdir.tmpdir.ensure(\".virtual\", bindir, fname)\n testfile = testdir.tmpdir.ensure(\".virtual\", \"test_invenv.py\")\n testfile.write(\"def test_hello(): pass\")\n result = testdir.runpytest(\"--collect-in-virtualenv\")\n assert \"test_invenv\" not in result.stdout.str()\n # ...unless the virtualenv is explicitly given on the CLI\n result = testdir.runpytest(\"--collect-in-virtualenv\", \".virtual\")\n assert \"test_invenv\" in result.stdout.str()\n\n @pytest.mark.parametrize(\n \"fname\",\n (\n \"activate\",\n \"activate.csh\",\n \"activate.fish\",\n \"Activate\",\n \"Activate.bat\",\n \"Activate.ps1\",\n ),\n )\n def test__in_venv(self, testdir, fname):\n \"\"\"Directly test the virtual env detection function\"\"\"\n bindir = \"Scripts\" if sys.platform.startswith(\"win\") else \"bin\"\n # no bin/activate, not a virtualenv\n base_path = testdir.tmpdir.mkdir(\"venv\")\n assert _in_venv(base_path) is False\n # with bin/activate, totally a virtualenv\n base_path.ensure(bindir, fname)\n assert _in_venv(base_path) is True\n\n def test_custom_norecursedirs(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n norecursedirs = mydir xyz*\n \"\"\"\n )\n tmpdir = testdir.tmpdir\n tmpdir.ensure(\"mydir\", \"test_hello.py\").write(\"def test_1(): pass\")\n tmpdir.ensure(\"xyz123\", \"test_2.py\").write(\"def test_2(): 0/0\")\n tmpdir.ensure(\"xy\", \"test_ok.py\").write(\"def test_3(): pass\")\n rec = testdir.inline_run()\n rec.assertoutcome(passed=1)\n rec = testdir.inline_run(\"xyz123/test_2.py\")\n rec.assertoutcome(failed=1)\n\n def test_testpaths_ini(self, testdir, monkeypatch):\n testdir.makeini(\n \"\"\"\n [pytest]\n testpaths = gui uts\n \"\"\"\n )\n tmpdir = testdir.tmpdir\n tmpdir.ensure(\"env\", \"test_1.py\").write(\"def test_env(): pass\")\n tmpdir.ensure(\"gui\", \"test_2.py\").write(\"def test_gui(): pass\")\n tmpdir.ensure(\"uts\", \"test_3.py\").write(\"def test_uts(): pass\")\n\n # executing from rootdir only tests from `testpaths` directories\n # are collected\n items, reprec = testdir.inline_genitems(\"-v\")\n assert [x.name for x in items] == [\"test_gui\", \"test_uts\"]\n\n # check that explicitly passing directories in the command-line\n # collects the tests\n for dirname in (\"env\", \"gui\", \"uts\"):\n items, reprec = testdir.inline_genitems(tmpdir.join(dirname))\n assert [x.name for x in items] == [\"test_%s\" % dirname]\n\n # changing cwd to each subdirectory and running pytest without\n # arguments collects the tests in that directory normally\n for dirname in (\"env\", \"gui\", \"uts\"):\n monkeypatch.chdir(testdir.tmpdir.join(dirname))\n items, reprec = testdir.inline_genitems()\n assert [x.name for x in items] == [\"test_%s\" % dirname]\n\n\nclass TestCollectPluginHookRelay(object):\n def test_pytest_collect_file(self, testdir):\n wascalled = []\n\n class Plugin(object):\n def pytest_collect_file(self, path, parent):\n if not path.basename.startswith(\".\"):\n # Ignore hidden files, e.g. .testmondata.\n wascalled.append(path)\n\n testdir.makefile(\".abc\", \"xyz\")\n pytest.main([testdir.tmpdir], plugins=[Plugin()])\n assert len(wascalled) == 1\n assert wascalled[0].ext == \".abc\"\n\n def test_pytest_collect_directory(self, testdir):\n wascalled = []\n\n class Plugin(object):\n def pytest_collect_directory(self, path, parent):\n wascalled.append(path.basename)\n\n testdir.mkdir(\"hello\")\n testdir.mkdir(\"world\")\n pytest.main(testdir.tmpdir, plugins=[Plugin()])\n assert \"hello\" in wascalled\n assert \"world\" in wascalled\n\n\nclass TestPrunetraceback(object):\n def test_custom_repr_failure(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import not_exists\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_collect_file(path, parent):\n return MyFile(path, parent)\n class MyError(Exception):\n pass\n class MyFile(pytest.File):\n def collect(self):\n raise MyError()\n def repr_failure(self, excinfo):\n if excinfo.errisinstance(MyError):\n return \"hello world\"\n return pytest.File.repr_failure(self, excinfo)\n \"\"\"\n )\n\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*ERROR collecting*\", \"*hello world*\"])\n\n @pytest.mark.xfail(reason=\"other mechanism for adding to reporting needed\")\n def test_collect_report_postprocessing(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import not_exists\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.hookimpl(hookwrapper=True)\n def pytest_make_collect_report():\n outcome = yield\n rep = outcome.get_result()\n rep.headerlines += [\"header1\"]\n outcome.force_result(rep)\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*ERROR collecting*\", \"*header1*\"])\n\n\nclass TestCustomConftests(object):\n def test_ignore_collect_path(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_ignore_collect(path, config):\n return path.basename.startswith(\"x\") or \\\n path.basename == \"test_one.py\"\n \"\"\"\n )\n sub = testdir.mkdir(\"xy123\")\n sub.ensure(\"test_hello.py\").write(\"syntax error\")\n sub.join(\"conftest.py\").write(\"syntax error\")\n testdir.makepyfile(\"def test_hello(): pass\")\n testdir.makepyfile(test_one=\"syntax error\")\n result = testdir.runpytest(\"--fulltrace\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_ignore_collect_not_called_on_argument(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_ignore_collect(path, config):\n return True\n \"\"\"\n )\n p = testdir.makepyfile(\"def test_hello(): pass\")\n result = testdir.runpytest(p)\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result.stdout.fnmatch_lines([\"*collected 0 items*\"])\n\n def test_collectignore_exclude_on_option(self, testdir):\n testdir.makeconftest(\n \"\"\"\n collect_ignore = ['hello', 'test_world.py']\n def pytest_addoption(parser):\n parser.addoption(\"--XX\", action=\"store_true\", default=False)\n def pytest_configure(config):\n if config.getvalue(\"XX\"):\n collect_ignore[:] = []\n \"\"\"\n )\n testdir.mkdir(\"hello\")\n testdir.makepyfile(test_world=\"def test_hello(): pass\")\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n assert \"passed\" not in result.stdout.str()\n result = testdir.runpytest(\"--XX\")\n assert result.ret == 0\n assert \"passed\" in result.stdout.str()\n\n def test_collectignoreglob_exclude_on_option(self, testdir):\n testdir.makeconftest(\n \"\"\"\n collect_ignore_glob = ['*w*l[dt]*']\n def pytest_addoption(parser):\n parser.addoption(\"--XX\", action=\"store_true\", default=False)\n def pytest_configure(config):\n if config.getvalue(\"XX\"):\n collect_ignore_glob[:] = []\n \"\"\"\n )\n testdir.makepyfile(test_world=\"def test_hello(): pass\")\n testdir.makepyfile(test_welt=\"def test_hallo(): pass\")\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result.stdout.fnmatch_lines([\"*collected 0 items*\"])\n result = testdir.runpytest(\"--XX\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n def test_pytest_fs_collect_hooks_are_seen(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n class MyModule(pytest.Module):\n pass\n def pytest_collect_file(path, parent):\n if path.ext == \".py\":\n return MyModule(path, parent)\n \"\"\"\n )\n testdir.mkdir(\"sub\")\n testdir.makepyfile(\"def test_x(): pass\")\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*MyModule*\", \"*test_x*\"])\n\n def test_pytest_collect_file_from_sister_dir(self, testdir):\n sub1 = testdir.mkpydir(\"sub1\")\n sub2 = testdir.mkpydir(\"sub2\")\n conf1 = testdir.makeconftest(\n \"\"\"\n import pytest\n class MyModule1(pytest.Module):\n pass\n def pytest_collect_file(path, parent):\n if path.ext == \".py\":\n return MyModule1(path, parent)\n \"\"\"\n )\n conf1.move(sub1.join(conf1.basename))\n conf2 = testdir.makeconftest(\n \"\"\"\n import pytest\n class MyModule2(pytest.Module):\n pass\n def pytest_collect_file(path, parent):\n if path.ext == \".py\":\n return MyModule2(path, parent)\n \"\"\"\n )\n conf2.move(sub2.join(conf2.basename))\n p = testdir.makepyfile(\"def test_x(): pass\")\n p.copy(sub1.join(p.basename))\n p.copy(sub2.join(p.basename))\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*MyModule1*\", \"*MyModule2*\", \"*test_x*\"])\n\n\nclass TestSession(object):\n def test_parsearg(self, testdir):\n p = testdir.makepyfile(\"def test_func(): pass\")\n subdir = testdir.mkdir(\"sub\")\n subdir.ensure(\"__init__.py\")\n target = subdir.join(p.basename)\n p.move(target)\n subdir.chdir()\n config = testdir.parseconfig(p.basename)\n rcol = Session(config=config)\n assert rcol.fspath == subdir\n parts = rcol._parsearg(p.basename)\n\n assert parts[0] == target\n assert len(parts) == 1\n parts = rcol._parsearg(p.basename + \"::test_func\")\n assert parts[0] == target\n assert parts[1] == \"test_func\"\n assert len(parts) == 2\n\n def test_collect_topdir(self, testdir):\n p = testdir.makepyfile(\"def test_func(): pass\")\n id = \"::\".join([p.basename, \"test_func\"])\n # XXX migrate to collectonly? (see below)\n config = testdir.parseconfig(id)\n topdir = testdir.tmpdir\n rcol = Session(config)\n assert topdir == rcol.fspath\n # rootid = rcol.nodeid\n # root2 = rcol.perform_collect([rcol.nodeid], genitems=False)[0]\n # assert root2 == rcol, rootid\n colitems = rcol.perform_collect([rcol.nodeid], genitems=False)\n assert len(colitems) == 1\n assert colitems[0].fspath == p\n\n def get_reported_items(self, hookrec):\n \"\"\"Return pytest.Item instances reported by the pytest_collectreport hook\"\"\"\n calls = hookrec.getcalls(\"pytest_collectreport\")\n return [\n x\n for call in calls\n for x in call.report.result\n if isinstance(x, pytest.Item)\n ]\n\n def test_collect_protocol_single_function(self, testdir):\n p = testdir.makepyfile(\"def test_func(): pass\")\n id = \"::\".join([p.basename, \"test_func\"])\n items, hookrec = testdir.inline_genitems(id)\n item, = items\n assert item.name == \"test_func\"\n newid = item.nodeid\n assert newid == id\n pprint.pprint(hookrec.calls)\n topdir = testdir.tmpdir # noqa\n hookrec.assert_contains(\n [\n (\"pytest_collectstart\", \"collector.fspath == topdir\"),\n (\"pytest_make_collect_report\", \"collector.fspath == topdir\"),\n (\"pytest_collectstart\", \"collector.fspath == p\"),\n (\"pytest_make_collect_report\", \"collector.fspath == p\"),\n (\"pytest_pycollect_makeitem\", \"name == 'test_func'\"),\n (\"pytest_collectreport\", \"report.result[0].name == 'test_func'\"),\n ]\n )\n # ensure we are reporting the collection of the single test item (#2464)\n assert [x.name for x in self.get_reported_items(hookrec)] == [\"test_func\"]\n\n def test_collect_protocol_method(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n class TestClass(object):\n def test_method(self):\n pass\n \"\"\"\n )\n normid = p.basename + \"::TestClass::test_method\"\n for id in [p.basename, p.basename + \"::TestClass\", normid]:\n items, hookrec = testdir.inline_genitems(id)\n assert len(items) == 1\n assert items[0].name == \"test_method\"\n newid = items[0].nodeid\n assert newid == normid\n # ensure we are reporting the collection of the single test item (#2464)\n assert [x.name for x in self.get_reported_items(hookrec)] == [\"test_method\"]\n\n def test_collect_custom_nodes_multi_id(self, testdir):\n p = testdir.makepyfile(\"def test_func(): pass\")\n testdir.makeconftest(\n \"\"\"\n import pytest\n class SpecialItem(pytest.Item):\n def runtest(self):\n return # ok\n class SpecialFile(pytest.File):\n def collect(self):\n return [SpecialItem(name=\"check\", parent=self)]\n def pytest_collect_file(path, parent):\n if path.basename == %r:\n return SpecialFile(fspath=path, parent=parent)\n \"\"\"\n % p.basename\n )\n id = p.basename\n\n items, hookrec = testdir.inline_genitems(id)\n pprint.pprint(hookrec.calls)\n assert len(items) == 2\n hookrec.assert_contains(\n [\n (\"pytest_collectstart\", \"collector.fspath == collector.session.fspath\"),\n (\n \"pytest_collectstart\",\n \"collector.__class__.__name__ == 'SpecialFile'\",\n ),\n (\"pytest_collectstart\", \"collector.__class__.__name__ == 'Module'\"),\n (\"pytest_pycollect_makeitem\", \"name == 'test_func'\"),\n (\"pytest_collectreport\", \"report.nodeid.startswith(p.basename)\"),\n ]\n )\n assert len(self.get_reported_items(hookrec)) == 2\n\n def test_collect_subdir_event_ordering(self, testdir):\n p = testdir.makepyfile(\"def test_func(): pass\")\n aaa = testdir.mkpydir(\"aaa\")\n test_aaa = aaa.join(\"test_aaa.py\")\n p.move(test_aaa)\n\n items, hookrec = testdir.inline_genitems()\n assert len(items) == 1\n pprint.pprint(hookrec.calls)\n hookrec.assert_contains(\n [\n (\"pytest_collectstart\", \"collector.fspath == test_aaa\"),\n (\"pytest_pycollect_makeitem\", \"name == 'test_func'\"),\n (\"pytest_collectreport\", \"report.nodeid.startswith('aaa/test_aaa.py')\"),\n ]\n )\n\n def test_collect_two_commandline_args(self, testdir):\n p = testdir.makepyfile(\"def test_func(): pass\")\n aaa = testdir.mkpydir(\"aaa\")\n bbb = testdir.mkpydir(\"bbb\")\n test_aaa = aaa.join(\"test_aaa.py\")\n p.copy(test_aaa)\n test_bbb = bbb.join(\"test_bbb.py\")\n p.move(test_bbb)\n\n id = \".\"\n\n items, hookrec = testdir.inline_genitems(id)\n assert len(items) == 2\n pprint.pprint(hookrec.calls)\n hookrec.assert_contains(\n [\n (\"pytest_collectstart\", \"collector.fspath == test_aaa\"),\n (\"pytest_pycollect_makeitem\", \"name == 'test_func'\"),\n (\"pytest_collectreport\", \"report.nodeid == 'aaa/test_aaa.py'\"),\n (\"pytest_collectstart\", \"collector.fspath == test_bbb\"),\n (\"pytest_pycollect_makeitem\", \"name == 'test_func'\"),\n (\"pytest_collectreport\", \"report.nodeid == 'bbb/test_bbb.py'\"),\n ]\n )\n\n def test_serialization_byid(self, testdir):\n testdir.makepyfile(\"def test_func(): pass\")\n items, hookrec = testdir.inline_genitems()\n assert len(items) == 1\n item, = items\n items2, hookrec = testdir.inline_genitems(item.nodeid)\n item2, = items2\n assert item2.name == item.name\n assert item2.fspath == item.fspath\n\n def test_find_byid_without_instance_parents(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n class TestClass(object):\n def test_method(self):\n pass\n \"\"\"\n )\n arg = p.basename + \"::TestClass::test_method\"\n items, hookrec = testdir.inline_genitems(arg)\n assert len(items) == 1\n item, = items\n assert item.nodeid.endswith(\"TestClass::test_method\")\n # ensure we are reporting the collection of the single test item (#2464)\n assert [x.name for x in self.get_reported_items(hookrec)] == [\"test_method\"]\n\n\nclass Test_getinitialnodes(object):\n def test_global_file(self, testdir, tmpdir):\n x = tmpdir.ensure(\"x.py\")\n with tmpdir.as_cwd():\n config = testdir.parseconfigure(x)\n col = testdir.getnode(config, x)\n assert isinstance(col, pytest.Module)\n assert col.name == \"x.py\"\n assert col.parent.parent is None\n for col in col.listchain():\n assert col.config is config\n\n def test_pkgfile(self, testdir):\n \"\"\"Verify nesting when a module is within a package.\n The parent chain should match: Module -> Package -> Session.\n Session's parent should always be None.\n \"\"\"\n tmpdir = testdir.tmpdir\n subdir = tmpdir.join(\"subdir\")\n x = subdir.ensure(\"x.py\")\n subdir.ensure(\"__init__.py\")\n with subdir.as_cwd():\n config = testdir.parseconfigure(x)\n col = testdir.getnode(config, x)\n assert col.name == \"x.py\"\n assert isinstance(col, pytest.Module)\n assert isinstance(col.parent, pytest.Package)\n assert isinstance(col.parent.parent, pytest.Session)\n # session is batman (has no parents)\n assert col.parent.parent.parent is None\n for col in col.listchain():\n assert col.config is config\n\n\nclass Test_genitems(object):\n def test_check_collect_hashes(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_1():\n pass\n\n def test_2():\n pass\n \"\"\"\n )\n p.copy(p.dirpath(p.purebasename + \"2\" + \".py\"))\n items, reprec = testdir.inline_genitems(p.dirpath())\n assert len(items) == 4\n for numi, i in enumerate(items):\n for numj, j in enumerate(items):\n if numj != numi:\n assert hash(i) != hash(j)\n assert i != j\n\n def test_example_items1(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def testone():\n pass\n\n class TestX(object):\n def testmethod_one(self):\n pass\n\n class TestY(TestX):\n pass\n \"\"\"\n )\n items, reprec = testdir.inline_genitems(p)\n assert len(items) == 3\n assert items[0].name == \"testone\"\n assert items[1].name == \"testmethod_one\"\n assert items[2].name == \"testmethod_one\"\n\n # let's also test getmodpath here\n assert items[0].getmodpath() == \"testone\"\n assert items[1].getmodpath() == \"TestX.testmethod_one\"\n assert items[2].getmodpath() == \"TestY.testmethod_one\"\n\n s = items[0].getmodpath(stopatmodule=False)\n assert s.endswith(\"test_example_items1.testone\")\n print(s)\n\n def test_class_and_functions_discovery_using_glob(self, testdir):\n \"\"\"\n tests that python_classes and python_functions config options work\n as prefixes and glob-like patterns (issue #600).\n \"\"\"\n testdir.makeini(\n \"\"\"\n [pytest]\n python_classes = *Suite Test\n python_functions = *_test test\n \"\"\"\n )\n p = testdir.makepyfile(\n \"\"\"\n class MyTestSuite(object):\n def x_test(self):\n pass\n\n class TestCase(object):\n def test_y(self):\n pass\n \"\"\"\n )\n items, reprec = testdir.inline_genitems(p)\n ids = [x.getmodpath() for x in items]\n assert ids == [\"MyTestSuite.x_test\", \"TestCase.test_y\"]\n\n\ndef test_matchnodes_two_collections_same_file(testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_configure(config):\n config.pluginmanager.register(Plugin2())\n\n class Plugin2(object):\n def pytest_collect_file(self, path, parent):\n if path.ext == \".abc\":\n return MyFile2(path, parent)\n\n def pytest_collect_file(path, parent):\n if path.ext == \".abc\":\n return MyFile1(path, parent)\n\n class MyFile1(pytest.Item, pytest.File):\n def runtest(self):\n pass\n class MyFile2(pytest.File):\n def collect(self):\n return [Item2(\"hello\", parent=self)]\n\n class Item2(pytest.Item):\n def runtest(self):\n pass\n \"\"\"\n )\n p = testdir.makefile(\".abc\", \"\")\n result = testdir.runpytest()\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n res = testdir.runpytest(\"%s::hello\" % p.basename)\n res.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\nclass TestNodekeywords(object):\n def test_no_under(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n def test_pass(): pass\n def test_fail(): assert 0\n \"\"\"\n )\n values = list(modcol.keywords)\n assert modcol.name in values\n for x in values:\n assert not x.startswith(\"_\")\n assert modcol.name in repr(modcol.keywords)\n\n def test_issue345(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_should_not_be_selected():\n assert False, 'I should not have been selected to run'\n\n def test___repr__():\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(\"-k repr\")\n reprec.assertoutcome(passed=1, failed=0)\n\n\nCOLLECTION_ERROR_PY_FILES = dict(\n test_01_failure=\"\"\"\n def test_1():\n assert False\n \"\"\",\n test_02_import_error=\"\"\"\n import asdfasdfasdf\n def test_2():\n assert True\n \"\"\",\n test_03_import_error=\"\"\"\n import asdfasdfasdf\n def test_3():\n assert True\n \"\"\",\n test_04_success=\"\"\"\n def test_4():\n assert True\n \"\"\",\n)\n\n\ndef test_exit_on_collection_error(testdir):\n \"\"\"Verify that all collection errors are collected and no tests executed\"\"\"\n testdir.makepyfile(**COLLECTION_ERROR_PY_FILES)\n\n res = testdir.runpytest()\n assert res.ret == 2\n\n res.stdout.fnmatch_lines(\n [\n \"collected 2 items / 2 errors\",\n \"*ERROR collecting test_02_import_error.py*\",\n \"*No module named *asdfa*\",\n \"*ERROR collecting test_03_import_error.py*\",\n \"*No module named *asdfa*\",\n ]\n )\n\n\ndef test_exit_on_collection_with_maxfail_smaller_than_n_errors(testdir):\n \"\"\"\n Verify collection is aborted once maxfail errors are encountered ignoring\n further modules which would cause more collection errors.\n \"\"\"\n testdir.makepyfile(**COLLECTION_ERROR_PY_FILES)\n\n res = testdir.runpytest(\"--maxfail=1\")\n assert res.ret == 1\n\n res.stdout.fnmatch_lines(\n [\"*ERROR collecting test_02_import_error.py*\", \"*No module named *asdfa*\"]\n )\n\n assert \"test_03\" not in res.stdout.str()\n\n\ndef test_exit_on_collection_with_maxfail_bigger_than_n_errors(testdir):\n \"\"\"\n Verify the test run aborts due to collection errors even if maxfail count of\n errors was not reached.\n \"\"\"\n testdir.makepyfile(**COLLECTION_ERROR_PY_FILES)\n\n res = testdir.runpytest(\"--maxfail=4\")\n assert res.ret == 2\n\n res.stdout.fnmatch_lines(\n [\n \"collected 2 items / 2 errors\",\n \"*ERROR collecting test_02_import_error.py*\",\n \"*No module named *asdfa*\",\n \"*ERROR collecting test_03_import_error.py*\",\n \"*No module named *asdfa*\",\n ]\n )\n\n\ndef test_continue_on_collection_errors(testdir):\n \"\"\"\n Verify tests are executed even when collection errors occur when the\n --continue-on-collection-errors flag is set\n \"\"\"\n testdir.makepyfile(**COLLECTION_ERROR_PY_FILES)\n\n res = testdir.runpytest(\"--continue-on-collection-errors\")\n assert res.ret == 1\n\n res.stdout.fnmatch_lines(\n [\"collected 2 items / 2 errors\", \"*1 failed, 1 passed, 2 error*\"]\n )\n\n\ndef test_continue_on_collection_errors_maxfail(testdir):\n \"\"\"\n Verify tests are executed even when collection errors occur and that maxfail\n is honoured (including the collection error count).\n 4 tests: 2 collection errors + 1 failure + 1 success\n test_4 is never executed because the test run is with --maxfail=3 which\n means it is interrupted after the 2 collection errors + 1 failure.\n \"\"\"\n testdir.makepyfile(**COLLECTION_ERROR_PY_FILES)\n\n res = testdir.runpytest(\"--continue-on-collection-errors\", \"--maxfail=3\")\n assert res.ret == 1\n\n res.stdout.fnmatch_lines([\"collected 2 items / 2 errors\", \"*1 failed, 2 error*\"])\n\n\ndef test_fixture_scope_sibling_conftests(testdir):\n \"\"\"Regression test case for https://github.com/pytest-dev/pytest/issues/2836\"\"\"\n foo_path = testdir.mkdir(\"foo\")\n foo_path.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def fix():\n return 1\n \"\"\"\n )\n )\n foo_path.join(\"test_foo.py\").write(\"def test_foo(fix): assert fix == 1\")\n\n # Tests in `food/` should not see the conftest fixture from `foo/`\n food_path = testdir.mkpydir(\"food\")\n food_path.join(\"test_food.py\").write(\"def test_food(fix): assert fix == 1\")\n\n res = testdir.runpytest()\n assert res.ret == 1\n\n res.stdout.fnmatch_lines(\n [\n \"*ERROR at setup of test_food*\",\n \"E*fixture 'fix' not found\",\n \"*1 passed, 1 error*\",\n ]\n )\n\n\ndef test_collect_init_tests(testdir):\n \"\"\"Check that we collect files from __init__.py files when they patch the 'python_files' (#3773)\"\"\"\n p = testdir.copy_example(\"collect/collect_init_tests\")\n result = testdir.runpytest(p, \"--collect-only\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items\",\n \"\",\n \" \",\n \" \",\n \" \",\n ]\n )\n result = testdir.runpytest(\"./tests\", \"--collect-only\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items\",\n \"\",\n \" \",\n \" \",\n \" \",\n ]\n )\n # Ignores duplicates with \".\" and pkginit (#4310).\n result = testdir.runpytest(\"./tests\", \".\", \"--collect-only\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items\",\n \"\",\n \" \",\n \" \",\n \" \",\n \" \",\n ]\n )\n # Same as before, but different order.\n result = testdir.runpytest(\".\", \"tests\", \"--collect-only\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items\",\n \"\",\n \" \",\n \" \",\n \" \",\n \" \",\n ]\n )\n result = testdir.runpytest(\"./tests/test_foo.py\", \"--collect-only\")\n result.stdout.fnmatch_lines(\n [\"\", \" \", \" \"]\n )\n assert \"test_init\" not in result.stdout.str()\n result = testdir.runpytest(\"./tests/__init__.py\", \"--collect-only\")\n result.stdout.fnmatch_lines(\n [\"\", \" \", \" \"]\n )\n assert \"test_foo\" not in result.stdout.str()\n\n\ndef test_collect_invalid_signature_message(testdir):\n \"\"\"Check that we issue a proper message when we can't determine the signature of a test\n function (#4026).\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n class TestCase:\n @pytest.fixture\n def fix():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"Could not determine arguments of *.fix *: invalid method signature\"]\n )\n\n\ndef test_collect_handles_raising_on_dunder_class(testdir):\n \"\"\"Handle proxy classes like Django's LazySettings that might raise on\n ``isinstance`` (#4266).\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n class ImproperlyConfigured(Exception):\n pass\n\n class RaisesOnGetAttr(object):\n def raises(self):\n raise ImproperlyConfigured\n\n __class__ = property(raises)\n\n raises = RaisesOnGetAttr()\n\n\n def test_1():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed in*\"])\n assert result.ret == 0\n\n\ndef test_collect_with_chdir_during_import(testdir):\n subdir = testdir.tmpdir.mkdir(\"sub\")\n testdir.tmpdir.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\n import os\n os.chdir(%r)\n \"\"\"\n % (str(subdir),)\n )\n )\n testdir.makepyfile(\n \"\"\"\n def test_1():\n import os\n assert os.getcwd() == %r\n \"\"\"\n % (str(subdir),)\n )\n with testdir.tmpdir.as_cwd():\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed in*\"])\n assert result.ret == 0\n\n # Handles relative testpaths.\n testdir.makeini(\n \"\"\"\n [pytest]\n testpaths = .\n \"\"\"\n )\n with testdir.tmpdir.as_cwd():\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"collected 1 item\"])\n\n\ndef test_collect_pyargs_with_testpaths(testdir, monkeypatch):\n testmod = testdir.mkdir(\"testmod\")\n # NOTE: __init__.py is not collected since it does not match python_files.\n testmod.ensure(\"__init__.py\").write(\"def test_func(): pass\")\n testmod.ensure(\"test_file.py\").write(\"def test_func(): pass\")\n\n root = testdir.mkdir(\"root\")\n root.ensure(\"pytest.ini\").write(\n textwrap.dedent(\n \"\"\"\n [pytest]\n addopts = --pyargs\n testpaths = testmod\n \"\"\"\n )\n )\n monkeypatch.setenv(\"PYTHONPATH\", str(testdir.tmpdir), prepend=os.pathsep)\n with root.as_cwd():\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*1 passed in*\"])\n\n\n@pytest.mark.skipif(\n not hasattr(py.path.local, \"mksymlinkto\"),\n reason=\"symlink not available on this platform\",\n)\ndef test_collect_symlink_file_arg(testdir):\n \"\"\"Test that collecting a direct symlink, where the target does not match python_files works (#4325).\"\"\"\n real = testdir.makepyfile(\n real=\"\"\"\n def test_nodeid(request):\n assert request.node.nodeid == \"real.py::test_nodeid\"\n \"\"\"\n )\n symlink = testdir.tmpdir.join(\"symlink.py\")\n symlink.mksymlinkto(real)\n result = testdir.runpytest(\"-v\", symlink)\n result.stdout.fnmatch_lines([\"real.py::test_nodeid PASSED*\", \"*1 passed in*\"])\n assert result.ret == 0\n\n\n@pytest.mark.skipif(\n not hasattr(py.path.local, \"mksymlinkto\"),\n reason=\"symlink not available on this platform\",\n)\ndef test_collect_symlink_out_of_tree(testdir):\n \"\"\"Test collection of symlink via out-of-tree rootdir.\"\"\"\n sub = testdir.tmpdir.join(\"sub\")\n real = sub.join(\"test_real.py\")\n real.write(\n textwrap.dedent(\n \"\"\"\n def test_nodeid(request):\n # Should not contain sub/ prefix.\n assert request.node.nodeid == \"test_real.py::test_nodeid\"\n \"\"\"\n ),\n ensure=True,\n )\n\n out_of_tree = testdir.tmpdir.join(\"out_of_tree\").ensure(dir=True)\n symlink_to_sub = out_of_tree.join(\"symlink_to_sub\")\n symlink_to_sub.mksymlinkto(sub)\n sub.chdir()\n result = testdir.runpytest(\"-vs\", \"--rootdir=%s\" % sub, symlink_to_sub)\n result.stdout.fnmatch_lines(\n [\n # Should not contain \"sub/\"!\n \"test_real.py::test_nodeid PASSED\"\n ]\n )\n assert result.ret == 0\n\n\ndef test_collectignore_via_conftest(testdir, monkeypatch):\n \"\"\"collect_ignore in parent conftest skips importing child (issue #4592).\"\"\"\n tests = testdir.mkpydir(\"tests\")\n tests.ensure(\"conftest.py\").write(\"collect_ignore = ['ignore_me']\")\n\n ignore_me = tests.mkdir(\"ignore_me\")\n ignore_me.ensure(\"__init__.py\")\n ignore_me.ensure(\"conftest.py\").write(\"assert 0, 'should_not_be_called'\")\n\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n\n\ndef test_collect_pkg_init_and_file_in_args(testdir):\n subdir = testdir.mkdir(\"sub\")\n init = subdir.ensure(\"__init__.py\")\n init.write(\"def test_init(): pass\")\n p = subdir.ensure(\"test_file.py\")\n p.write(\"def test_file(): pass\")\n\n # NOTE: without \"-o python_files=*.py\" this collects test_file.py twice.\n # This changed/broke with \"Add package scoped fixtures #2283\" (2b1410895)\n # initially (causing a RecursionError).\n result = testdir.runpytest(\"-v\", str(init), str(p))\n result.stdout.fnmatch_lines(\n [\n \"sub/test_file.py::test_file PASSED*\",\n \"sub/test_file.py::test_file PASSED*\",\n \"*2 passed in*\",\n ]\n )\n\n result = testdir.runpytest(\"-v\", \"-o\", \"python_files=*.py\", str(init), str(p))\n result.stdout.fnmatch_lines(\n [\n \"sub/__init__.py::test_init PASSED*\",\n \"sub/test_file.py::test_file PASSED*\",\n \"*2 passed in*\",\n ]\n )\n\n\ndef test_collect_pkg_init_only(testdir):\n subdir = testdir.mkdir(\"sub\")\n init = subdir.ensure(\"__init__.py\")\n init.write(\"def test_init(): pass\")\n\n result = testdir.runpytest(str(init))\n result.stdout.fnmatch_lines([\"*no tests ran in*\"])\n\n result = testdir.runpytest(\"-v\", \"-o\", \"python_files=*.py\", str(init))\n result.stdout.fnmatch_lines([\"sub/__init__.py::test_init PASSED*\", \"*1 passed in*\"])\n\n\n@pytest.mark.skipif(\n not hasattr(py.path.local, \"mksymlinkto\"),\n reason=\"symlink not available on this platform\",\n)\n@pytest.mark.parametrize(\"use_pkg\", (True, False))\ndef test_collect_sub_with_symlinks(use_pkg, testdir):\n sub = testdir.mkdir(\"sub\")\n if use_pkg:\n sub.ensure(\"__init__.py\")\n sub.ensure(\"test_file.py\").write(\"def test_file(): pass\")\n\n # Create a broken symlink.\n sub.join(\"test_broken.py\").mksymlinkto(\"test_doesnotexist.py\")\n\n # Symlink that gets collected.\n sub.join(\"test_symlink.py\").mksymlinkto(\"test_file.py\")\n\n result = testdir.runpytest(\"-v\", str(sub))\n result.stdout.fnmatch_lines(\n [\n \"sub/test_file.py::test_file PASSED*\",\n \"sub/test_symlink.py::test_file PASSED*\",\n \"*2 passed in*\",\n ]\n )\n\n\ndef test_collector_respects_tbstyle(testdir):\n p1 = testdir.makepyfile(\"assert 0\")\n result = testdir.runpytest(p1, \"--tb=native\")\n assert result.ret == EXIT_INTERRUPTED\n result.stdout.fnmatch_lines(\n [\n \"*_ ERROR collecting test_collector_respects_tbstyle.py _*\",\n \"Traceback (most recent call last):\",\n ' File \"*/test_collector_respects_tbstyle.py\", line 1, in ',\n \" assert 0\",\n \"AssertionError: assert 0\",\n \"*! Interrupted: 1 errors during collection !*\",\n \"*= 1 error in *\",\n ]\n )\n"},{"col":0,"comment":"null","endLoc":606,"header":"def test_pytest_exit_returncode(testdir)","id":4718,"name":"test_pytest_exit_returncode","nodeType":"Function","startLoc":574,"text":"def test_pytest_exit_returncode(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_foo():\n pytest.exit(\"some exit msg\", 99)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*! *Exit: some exit msg !*\"])\n # Assert no output on stderr, except for unreliable ResourceWarnings.\n # (https://github.com/pytest-dev/pytest/issues/5088)\n assert [\n x\n for x in result.stderr.lines\n if not x.startswith(\"Exception ignored in:\")\n and not x.startswith(\"ResourceWarning\")\n ] == [\"\"]\n assert result.ret == 99\n\n # It prints to stderr also in case of exit during pytest_sessionstart.\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n def pytest_sessionstart():\n pytest.exit(\"during_sessionstart\", 98)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*! *Exit: during_sessionstart !*\"])\n assert result.stderr.lines == [\"Exit: during_sessionstart\", \"\"]\n assert result.ret == 98"},{"className":"TestCollector","col":0,"comment":"null","endLoc":109,"id":4719,"nodeType":"Class","startLoc":20,"text":"class TestCollector(object):\n def test_collect_versus_item(self):\n from pytest import Collector, Item\n\n assert not issubclass(Collector, Item)\n assert not issubclass(Item, Collector)\n\n def test_check_equality(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n def test_pass(): pass\n def test_fail(): assert 0\n \"\"\"\n )\n fn1 = testdir.collect_by_name(modcol, \"test_pass\")\n assert isinstance(fn1, pytest.Function)\n fn2 = testdir.collect_by_name(modcol, \"test_pass\")\n assert isinstance(fn2, pytest.Function)\n\n assert fn1 == fn2\n assert fn1 != modcol\n if sys.version_info < (3, 0):\n assert cmp(fn1, fn2) == 0 # NOQA\n assert hash(fn1) == hash(fn2)\n\n fn3 = testdir.collect_by_name(modcol, \"test_fail\")\n assert isinstance(fn3, pytest.Function)\n assert not (fn1 == fn3)\n assert fn1 != fn3\n\n for fn in fn1, fn2, fn3:\n assert fn != 3\n assert fn != modcol\n assert fn != [1, 2, 3]\n assert [1, 2, 3] != fn\n assert modcol != fn\n\n def test_getparent(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n class TestClass(object):\n def test_foo():\n pass\n \"\"\"\n )\n cls = testdir.collect_by_name(modcol, \"TestClass\")\n fn = testdir.collect_by_name(testdir.collect_by_name(cls, \"()\"), \"test_foo\")\n\n parent = fn.getparent(pytest.Module)\n assert parent is modcol\n\n parent = fn.getparent(pytest.Function)\n assert parent is fn\n\n parent = fn.getparent(pytest.Class)\n assert parent is cls\n\n def test_getcustomfile_roundtrip(self, testdir):\n hello = testdir.makefile(\".xxx\", hello=\"world\")\n testdir.makepyfile(\n conftest=\"\"\"\n import pytest\n class CustomFile(pytest.File):\n pass\n def pytest_collect_file(path, parent):\n if path.ext == \".xxx\":\n return CustomFile(path, parent=parent)\n \"\"\"\n )\n node = testdir.getpathnode(hello)\n assert isinstance(node, pytest.File)\n assert node.name == \"hello.xxx\"\n nodes = node.session.perform_collect([node.nodeid], genitems=False)\n assert len(nodes) == 1\n assert isinstance(nodes[0], pytest.File)\n\n def test_can_skip_class_with_test_attr(self, testdir):\n \"\"\"Assure test class is skipped when using `__test__=False` (See #2007).\"\"\"\n testdir.makepyfile(\n \"\"\"\n class TestFoo(object):\n __test__ = False\n def __init__(self):\n pass\n def test_foo():\n assert True\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"collected 0 items\", \"*no tests ran in*\"])"},{"col":4,"comment":"null","endLoc":25,"header":"def test_collect_versus_item(self)","id":4720,"name":"test_collect_versus_item","nodeType":"Function","startLoc":21,"text":"def test_collect_versus_item(self):\n from pytest import Collector, Item\n\n assert not issubclass(Collector, Item)\n assert not issubclass(Item, Collector)"},{"col":0,"comment":"Check that TerminalReporter._tw is also available as 'writer' (#2984)\n This attribute is planned to be deprecated in 3.4.\n ","endLoc":74,"header":"def test_terminal_reporter_writer_attr(pytestconfig)","id":4721,"name":"test_terminal_reporter_writer_attr","nodeType":"Function","startLoc":63,"text":"def test_terminal_reporter_writer_attr(pytestconfig):\n \"\"\"Check that TerminalReporter._tw is also available as 'writer' (#2984)\n This attribute is planned to be deprecated in 3.4.\n \"\"\"\n try:\n import xdist # noqa\n\n pytest.skip(\"xdist workers disable the terminal reporter plugin\")\n except ImportError:\n pass\n terminal_reporter = pytestconfig.pluginmanager.get_plugin(\"terminalreporter\")\n assert terminal_reporter.writer is terminal_reporter._tw"},{"className":"TestCaptureManager","col":0,"comment":"null","endLoc":96,"id":4722,"nodeType":"Class","startLoc":41,"text":"class TestCaptureManager(object):\n def test_getmethod_default_no_fd(self, monkeypatch):\n from _pytest.capture import pytest_addoption\n from _pytest.config.argparsing import Parser\n\n parser = Parser()\n pytest_addoption(parser)\n default = parser._groups[0].options[0].default\n assert default == \"fd\" if hasattr(os, \"dup\") else \"sys\"\n parser = Parser()\n monkeypatch.delattr(os, \"dup\", raising=False)\n pytest_addoption(parser)\n assert parser._groups[0].options[0].default == \"sys\"\n\n @pytest.mark.parametrize(\n \"method\", [\"no\", \"sys\", pytest.param(\"fd\", marks=needsosdup)]\n )\n def test_capturing_basic_api(self, method):\n capouter = StdCaptureFD()\n old = sys.stdout, sys.stderr, sys.stdin\n try:\n capman = CaptureManager(method)\n capman.start_global_capturing()\n capman.suspend_global_capture()\n outerr = capman.read_global_capture()\n assert outerr == (\"\", \"\")\n capman.suspend_global_capture()\n outerr = capman.read_global_capture()\n assert outerr == (\"\", \"\")\n print(\"hello\")\n capman.suspend_global_capture()\n out, err = capman.read_global_capture()\n if method == \"no\":\n assert old == (sys.stdout, sys.stderr, sys.stdin)\n else:\n assert not out\n capman.resume_global_capture()\n print(\"hello\")\n capman.suspend_global_capture()\n out, err = capman.read_global_capture()\n if method != \"no\":\n assert out == \"hello\\n\"\n capman.stop_global_capturing()\n finally:\n capouter.stop_capturing()\n\n @needsosdup\n def test_init_capturing(self):\n capouter = StdCaptureFD()\n try:\n capman = CaptureManager(\"fd\")\n capman.start_global_capturing()\n pytest.raises(AssertionError, capman.start_global_capturing)\n capman.stop_global_capturing()\n finally:\n capouter.stop_capturing()"},{"col":4,"comment":"null","endLoc":55,"header":"def test_check_equality(self, testdir)","id":4723,"name":"test_check_equality","nodeType":"Function","startLoc":27,"text":"def test_check_equality(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n def test_pass(): pass\n def test_fail(): assert 0\n \"\"\"\n )\n fn1 = testdir.collect_by_name(modcol, \"test_pass\")\n assert isinstance(fn1, pytest.Function)\n fn2 = testdir.collect_by_name(modcol, \"test_pass\")\n assert isinstance(fn2, pytest.Function)\n\n assert fn1 == fn2\n assert fn1 != modcol\n if sys.version_info < (3, 0):\n assert cmp(fn1, fn2) == 0 # NOQA\n assert hash(fn1) == hash(fn2)\n\n fn3 = testdir.collect_by_name(modcol, \"test_fail\")\n assert isinstance(fn3, pytest.Function)\n assert not (fn1 == fn3)\n assert fn1 != fn3\n\n for fn in fn1, fn2, fn3:\n assert fn != 3\n assert fn != modcol\n assert fn != [1, 2, 3]\n assert [1, 2, 3] != fn\n assert modcol != fn"},{"col":4,"comment":"null","endLoc":343,"header":"def test_classname_instance(self, testdir)","id":4724,"name":"test_classname_instance","nodeType":"Function","startLoc":328,"text":"def test_classname_instance(self, testdir):\n testdir.makepyfile(\n \"\"\"\n class TestClass(object):\n def test_method(self):\n assert 0\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(failures=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(\n classname=\"test_classname_instance.TestClass\", name=\"test_method\"\n )"},{"col":4,"comment":"null","endLoc":53,"header":"def test_getmethod_default_no_fd(self, monkeypatch)","id":4725,"name":"test_getmethod_default_no_fd","nodeType":"Function","startLoc":42,"text":"def test_getmethod_default_no_fd(self, monkeypatch):\n from _pytest.capture import pytest_addoption\n from _pytest.config.argparsing import Parser\n\n parser = Parser()\n pytest_addoption(parser)\n default = parser._groups[0].options[0].default\n assert default == \"fd\" if hasattr(os, \"dup\") else \"sys\"\n parser = Parser()\n monkeypatch.delattr(os, \"dup\", raising=False)\n pytest_addoption(parser)\n assert parser._groups[0].options[0].default == \"sys\""},{"col":4,"comment":"null","endLoc":732,"header":"def _locationline(self, nodeid, fspath, lineno, domain)","id":4726,"name":"_locationline","nodeType":"Function","startLoc":712,"text":"def _locationline(self, nodeid, fspath, lineno, domain):\n def mkrel(nodeid):\n line = self.config.cwd_relative_nodeid(nodeid)\n if domain and line.endswith(domain):\n line = line[: -len(domain)]\n values = domain.split(\"[\")\n values[0] = values[0].replace(\".\", \"::\") # don't replace '.' in params\n line += \"[\".join(values)\n return line\n\n # collect_fspath comes from testid which has a \"/\"-normalized path\n\n if fspath:\n res = mkrel(nodeid)\n if self.verbosity >= 2 and nodeid.split(\"::\")[0] != fspath.replace(\n \"\\\\\", nodes.SEP\n ):\n res += \" <- \" + self.startdir.bestrelpath(fspath)\n else:\n res = \"[location]\"\n return res + \" \""},{"col":4,"comment":"Read and return the captured output so far, resetting the internal buffer.\n\n :return: captured content as a namedtuple with ``out`` and ``err`` string attributes\n ","endLoc":388,"header":"def readouterr(self)","id":4727,"name":"readouterr","nodeType":"Function","startLoc":376,"text":"def readouterr(self):\n \"\"\"Read and return the captured output so far, resetting the internal buffer.\n\n :return: captured content as a namedtuple with ``out`` and ``err`` string attributes\n \"\"\"\n captured_out, captured_err = self._captured_out, self._captured_err\n if self._capture is not None:\n out, err = self._capture.readouterr()\n captured_out += out\n captured_err += err\n self._captured_out = self.captureclass.EMPTY_BUFFER\n self._captured_err = self.captureclass.EMPTY_BUFFER\n return CaptureResult(captured_out, captured_err)"},{"col":0,"comment":"null","endLoc":92,"header":"@pytest.mark.parametrize(\"plugin\", [\"catchlog\", \"capturelog\"])\n@pytest.mark.filterwarnings(\"default\")\ndef test_pytest_catchlog_deprecated(testdir, plugin)","id":4728,"name":"test_pytest_catchlog_deprecated","nodeType":"Function","startLoc":77,"text":"@pytest.mark.parametrize(\"plugin\", [\"catchlog\", \"capturelog\"])\n@pytest.mark.filterwarnings(\"default\")\ndef test_pytest_catchlog_deprecated(testdir, plugin):\n testdir.makepyfile(\n \"\"\"\n def test_func(pytestconfig):\n pytestconfig.pluginmanager.register(None, 'pytest_{}')\n \"\"\".format(\n plugin\n )\n )\n res = testdir.runpytest()\n assert res.ret == 0\n res.stdout.fnmatch_lines(\n [\"*pytest-*log plugin has been merged into the core*\", \"*1 passed, 1 warnings*\"]\n )"},{"col":0,"comment":"null","endLoc":82,"header":"def annotated_getattr(obj, name, ann)","id":4729,"name":"annotated_getattr","nodeType":"Function","startLoc":75,"text":"def annotated_getattr(obj, name, ann):\n try:\n obj = getattr(obj, name)\n except AttributeError:\n raise AttributeError(\n \"%r object at %s has no attribute %r\" % (type(obj).__name__, ann, name)\n )\n return obj"},{"col":0,"comment":"Test pytest.fail(..., pytrace=False) does not show tracebacks during test run.","endLoc":622,"header":"def test_pytest_fail_notrace_runtest(testdir)","id":4730,"name":"test_pytest_fail_notrace_runtest","nodeType":"Function","startLoc":609,"text":"def test_pytest_fail_notrace_runtest(testdir):\n \"\"\"Test pytest.fail(..., pytrace=False) does not show tracebacks during test run.\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_hello():\n pytest.fail(\"hello\", pytrace=False)\n def teardown_function(function):\n pytest.fail(\"world\", pytrace=False)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"world\", \"hello\"])\n assert \"def teardown_function\" not in result.stdout.str()"},{"col":0,"comment":"Test pytest.fail(..., pytrace=False) does not show tracebacks during collection.","endLoc":637,"header":"def test_pytest_fail_notrace_collection(testdir)","id":4731,"name":"test_pytest_fail_notrace_collection","nodeType":"Function","startLoc":625,"text":"def test_pytest_fail_notrace_collection(testdir):\n \"\"\"Test pytest.fail(..., pytrace=False) does not show tracebacks during collection.\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n def some_internal_function():\n pytest.fail(\"hello\", pytrace=False)\n some_internal_function()\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"hello\"])\n assert \"def some_internal_function()\" not in result.stdout.str()"},{"col":0,"comment":"Fix pytest.fail with pytrace=False with non-ascii characters (#1178).\n\n This tests with native and unicode strings containing non-ascii chars.\n ","endLoc":661,"header":"@pytest.mark.parametrize(\"str_prefix\", [\"u\", \"\"])\ndef test_pytest_fail_notrace_non_ascii(testdir, str_prefix)","id":4732,"name":"test_pytest_fail_notrace_non_ascii","nodeType":"Function","startLoc":640,"text":"@pytest.mark.parametrize(\"str_prefix\", [\"u\", \"\"])\ndef test_pytest_fail_notrace_non_ascii(testdir, str_prefix):\n \"\"\"Fix pytest.fail with pytrace=False with non-ascii characters (#1178).\n\n This tests with native and unicode strings containing non-ascii chars.\n \"\"\"\n testdir.makepyfile(\n u\"\"\"\n # -*- coding: utf-8 -*-\n import pytest\n\n def test_hello():\n pytest.fail(%s'oh oh: ☺', pytrace=False)\n \"\"\"\n % str_prefix\n )\n result = testdir.runpytest()\n if sys.version_info[0] >= 3:\n result.stdout.fnmatch_lines([\"*test_hello*\", \"oh oh: ☺\"])\n else:\n result.stdout.fnmatch_lines([\"*test_hello*\", \"oh oh: *\"])\n assert \"def test_hello\" not in result.stdout.str()"},{"col":0,"comment":"null","endLoc":43,"header":"def pytest_addoption(parser)","id":4733,"name":"pytest_addoption","nodeType":"Function","startLoc":27,"text":"def pytest_addoption(parser):\n group = parser.getgroup(\"general\")\n group._addoption(\n \"--capture\",\n action=\"store\",\n default=\"fd\" if hasattr(os, \"dup\") else \"sys\",\n metavar=\"method\",\n choices=[\"fd\", \"sys\", \"no\"],\n help=\"per-test capturing method: one of fd|sys|no.\",\n )\n group._addoption(\n \"-s\",\n action=\"store_const\",\n const=\"no\",\n dest=\"capture\",\n help=\"shortcut for --capture=no.\",\n )"},{"col":4,"comment":"null","endLoc":90,"header":"def __call__(self, prefix, **kwargs)","id":4734,"name":"__call__","nodeType":"Function","startLoc":61,"text":"def __call__(self, prefix, **kwargs):\n completion = []\n if self.allowednames:\n if self.directories:\n files = _wrapcall(\n [\"bash\", \"-c\", \"compgen -A directory -- '{p}'\".format(p=prefix)]\n )\n completion += [f + \"/\" for f in files]\n for x in self.allowednames:\n completion += _wrapcall(\n [\n \"bash\",\n \"-c\",\n \"compgen -A file -X '!*.{0}' -- '{p}'\".format(x, p=prefix),\n ]\n )\n else:\n completion += _wrapcall(\n [\"bash\", \"-c\", \"compgen -A file -- '{p}'\".format(p=prefix)]\n )\n\n anticomp = _wrapcall(\n [\"bash\", \"-c\", \"compgen -A directory -- '{p}'\".format(p=prefix)]\n )\n\n completion = list(set(completion) - set(anticomp))\n\n if self.directories:\n completion += [f + \"/\" for f in anticomp]\n return completion"},{"col":4,"comment":"Suspends this fixture's own capturing temporarily.","endLoc":393,"header":"def _suspend(self)","id":4735,"name":"_suspend","nodeType":"Function","startLoc":390,"text":"def _suspend(self):\n \"\"\"Suspends this fixture's own capturing temporarily.\"\"\"\n if self._capture is not None:\n self._capture.suspend_capturing()"},{"col":4,"comment":"Resumes this fixture's own capturing temporarily.","endLoc":398,"header":"def _resume(self)","id":4736,"name":"_resume","nodeType":"Function","startLoc":395,"text":"def _resume(self):\n \"\"\"Resumes this fixture's own capturing temporarily.\"\"\"\n if self._capture is not None:\n self._capture.resume_capturing()"},{"col":4,"comment":"Temporarily disables capture while inside the 'with' block.","endLoc":405,"header":"@contextlib.contextmanager\n def disabled(self)","id":4737,"name":"disabled","nodeType":"Function","startLoc":400,"text":"@contextlib.contextmanager\n def disabled(self):\n \"\"\"Temporarily disables capture while inside the 'with' block.\"\"\"\n capmanager = self.request.config.pluginmanager.getplugin(\"capturemanager\")\n with capmanager.global_and_fixture_disabled():\n yield"},{"col":4,"comment":"null","endLoc":353,"header":"def test_classname_nested_dir(self, testdir)","id":4738,"name":"test_classname_nested_dir","nodeType":"Function","startLoc":345,"text":"def test_classname_nested_dir(self, testdir):\n p = testdir.tmpdir.ensure(\"sub\", \"test_hello.py\")\n p.write(\"def test_func(): 0/0\")\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(failures=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"sub.test_hello\", name=\"test_func\")"},{"col":4,"comment":"null","endLoc":85,"header":"@pytest.mark.parametrize(\n \"method\", [\"no\", \"sys\", pytest.param(\"fd\", marks=needsosdup)]\n )\n def test_capturing_basic_api(self, method)","id":4739,"name":"test_capturing_basic_api","nodeType":"Function","startLoc":55,"text":"@pytest.mark.parametrize(\n \"method\", [\"no\", \"sys\", pytest.param(\"fd\", marks=needsosdup)]\n )\n def test_capturing_basic_api(self, method):\n capouter = StdCaptureFD()\n old = sys.stdout, sys.stderr, sys.stdin\n try:\n capman = CaptureManager(method)\n capman.start_global_capturing()\n capman.suspend_global_capture()\n outerr = capman.read_global_capture()\n assert outerr == (\"\", \"\")\n capman.suspend_global_capture()\n outerr = capman.read_global_capture()\n assert outerr == (\"\", \"\")\n print(\"hello\")\n capman.suspend_global_capture()\n out, err = capman.read_global_capture()\n if method == \"no\":\n assert old == (sys.stdout, sys.stderr, sys.stdin)\n else:\n assert not out\n capman.resume_global_capture()\n print(\"hello\")\n capman.suspend_global_capture()\n out, err = capman.read_global_capture()\n if method != \"no\":\n assert out == \"hello\\n\"\n capman.stop_global_capturing()\n finally:\n capouter.stop_capturing()"},{"col":0,"comment":"null","endLoc":47,"header":"def _wrapcall(*args, **kargs)","id":4740,"name":"_wrapcall","nodeType":"Function","startLoc":31,"text":"def _wrapcall(*args, **kargs):\n try:\n if sys.version_info > (2, 7):\n return subprocess.check_output(*args, **kargs).decode().splitlines()\n if \"stdout\" in kargs:\n raise ValueError(\"stdout argument not allowed, it will be overridden.\")\n process = subprocess.Popen(stdout=subprocess.PIPE, *args, **kargs)\n output, unused_err = process.communicate()\n retcode = process.poll()\n if retcode:\n cmd = kargs.get(\"args\")\n if cmd is None:\n cmd = args[0]\n raise subprocess.CalledProcessError(retcode, cmd)\n return output.decode().splitlines()\n except subprocess.CalledProcessError:\n return []"},{"attributeType":"null","col":8,"comment":"null","endLoc":356,"id":4741,"name":"request","nodeType":"Attribute","startLoc":356,"text":"self.request"},{"attributeType":"null","col":8,"comment":"null","endLoc":359,"id":4742,"name":"_captured_err","nodeType":"Attribute","startLoc":359,"text":"self._captured_err"},{"col":0,"comment":"null","endLoc":34,"header":"def StdCaptureFD(out=True, err=True, in_=True)","id":4743,"name":"StdCaptureFD","nodeType":"Function","startLoc":33,"text":"def StdCaptureFD(out=True, err=True, in_=True):\n return capture.MultiCapture(out, err, in_, Capture=capture.FDCapture)"},{"attributeType":"None","col":8,"comment":"null","endLoc":357,"id":4745,"name":"_capture","nodeType":"Attribute","startLoc":357,"text":"self._capture"},{"attributeType":"null","col":8,"comment":"null","endLoc":358,"id":4746,"name":"_captured_out","nodeType":"Attribute","startLoc":358,"text":"self._captured_out"},{"attributeType":"null","col":8,"comment":"null","endLoc":355,"id":4747,"name":"captureclass","nodeType":"Attribute","startLoc":355,"text":"self.captureclass"},{"className":"EncodedFile","col":0,"comment":"null","endLoc":457,"id":4748,"nodeType":"Class","startLoc":427,"text":"class EncodedFile(object):\n errors = \"strict\" # possibly needed by py3 code (issue555)\n\n def __init__(self, buffer, encoding):\n self.buffer = buffer\n self.encoding = encoding\n\n def write(self, obj):\n if isinstance(obj, six.text_type):\n obj = obj.encode(self.encoding, \"replace\")\n elif _PY3:\n raise TypeError(\n \"write() argument must be str, not {}\".format(type(obj).__name__)\n )\n self.buffer.write(obj)\n\n def writelines(self, linelist):\n data = \"\".join(linelist)\n self.write(data)\n\n @property\n def name(self):\n \"\"\"Ensure that file.name is a string.\"\"\"\n return repr(self.buffer)\n\n @property\n def mode(self):\n return self.buffer.mode.replace(\"b\", \"\")\n\n def __getattr__(self, name):\n return getattr(object.__getattribute__(self, \"buffer\"), name)"},{"col":4,"comment":"null","endLoc":432,"header":"def __init__(self, buffer, encoding)","id":4749,"name":"__init__","nodeType":"Function","startLoc":430,"text":"def __init__(self, buffer, encoding):\n self.buffer = buffer\n self.encoding = encoding"},{"col":4,"comment":"null","endLoc":441,"header":"def write(self, obj)","id":4750,"name":"write","nodeType":"Function","startLoc":434,"text":"def write(self, obj):\n if isinstance(obj, six.text_type):\n obj = obj.encode(self.encoding, \"replace\")\n elif _PY3:\n raise TypeError(\n \"write() argument must be str, not {}\".format(type(obj).__name__)\n )\n self.buffer.write(obj)"},{"col":4,"comment":"null","endLoc":366,"header":"def test_internal_error(self, testdir)","id":4751,"name":"test_internal_error","nodeType":"Function","startLoc":355,"text":"def test_internal_error(self, testdir):\n testdir.makeconftest(\"def pytest_runtest_protocol(): 0 / 0\")\n testdir.makepyfile(\"def test_function(): pass\")\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(errors=1, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"pytest\", name=\"internal\")\n fnode = tnode.find_first_by_tag(\"error\")\n fnode.assert_attr(message=\"internal error\")\n assert \"Division\" in fnode.toxml()"},{"col":4,"comment":"null","endLoc":445,"header":"def pytest_runtest_logreport(self, report)","id":4752,"name":"pytest_runtest_logreport","nodeType":"Function","startLoc":396,"text":"def pytest_runtest_logreport(self, report):\n self._tests_ran = True\n rep = report\n res = self.config.hook.pytest_report_teststatus(report=rep, config=self.config)\n category, letter, word = res\n if isinstance(word, tuple):\n word, markup = word\n else:\n markup = None\n self.stats.setdefault(category, []).append(rep)\n if not letter and not word:\n # probably passed setup/teardown\n return\n running_xdist = hasattr(rep, \"node\")\n if markup is None:\n was_xfail = hasattr(report, \"wasxfail\")\n if rep.passed and not was_xfail:\n markup = {\"green\": True}\n elif rep.passed and was_xfail:\n markup = {\"yellow\": True}\n elif rep.failed:\n markup = {\"red\": True}\n elif rep.skipped:\n markup = {\"yellow\": True}\n else:\n markup = {}\n if self.verbosity <= 0:\n if not running_xdist and self.showfspath:\n self.write_fspath_result(rep.nodeid, letter, **markup)\n else:\n self._tw.write(letter, **markup)\n else:\n self._progress_nodeids_reported.add(rep.nodeid)\n line = self._locationline(rep.nodeid, *rep.location)\n if not running_xdist:\n self.write_ensure_prefix(line, word, **markup)\n if self._show_progress_info:\n self._write_progress_information_filling_space()\n else:\n self.ensure_newline()\n self._tw.write(\"[%s]\" % rep.node.gateway.id)\n if self._show_progress_info:\n self._tw.write(\n self._get_progress_information_message() + \" \", cyan=True\n )\n else:\n self._tw.write(\" \")\n self._tw.write(word, **markup)\n self._tw.write(\" \" + line)\n self.currentfspath = -2"},{"col":4,"comment":"null","endLoc":410,"header":"@pytest.mark.parametrize(\"junit_logging\", [\"no\", \"system-out\", \"system-err\"])\n def test_failure_function(self, testdir, junit_logging)","id":4753,"name":"test_failure_function","nodeType":"Function","startLoc":368,"text":"@pytest.mark.parametrize(\"junit_logging\", [\"no\", \"system-out\", \"system-err\"])\n def test_failure_function(self, testdir, junit_logging):\n testdir.makepyfile(\n \"\"\"\n import logging\n import sys\n\n def test_fail():\n print(\"hello-stdout\")\n sys.stderr.write(\"hello-stderr\\\\n\")\n logging.info('info msg')\n logging.warning('warning msg')\n raise ValueError(42)\n \"\"\"\n )\n\n result, dom = runandparse(testdir, \"-o\", \"junit_logging=%s\" % junit_logging)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(failures=1, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_failure_function\", name=\"test_fail\")\n fnode = tnode.find_first_by_tag(\"failure\")\n fnode.assert_attr(message=\"ValueError: 42\")\n assert \"ValueError\" in fnode.toxml()\n systemout = fnode.next_siebling\n assert systemout.tag == \"system-out\"\n assert \"hello-stdout\" in systemout.toxml()\n assert \"info msg\" not in systemout.toxml()\n systemerr = systemout.next_siebling\n assert systemerr.tag == \"system-err\"\n assert \"hello-stderr\" in systemerr.toxml()\n assert \"info msg\" not in systemerr.toxml()\n\n if junit_logging == \"system-out\":\n assert \"warning msg\" in systemout.toxml()\n assert \"warning msg\" not in systemerr.toxml()\n elif junit_logging == \"system-err\":\n assert \"warning msg\" not in systemout.toxml()\n assert \"warning msg\" in systemerr.toxml()\n elif junit_logging == \"no\":\n assert \"warning msg\" not in systemout.toxml()\n assert \"warning msg\" not in systemerr.toxml()"},{"col":4,"comment":"null","endLoc":887,"header":"def _checkargnotcontained(self, arg)","id":4754,"name":"_checkargnotcontained","nodeType":"Function","startLoc":885,"text":"def _checkargnotcontained(self, arg):\n if arg in self.params or arg in self.funcargs:\n raise ValueError(\"duplicate %r\" % (arg,))"},{"col":0,"comment":"null","endLoc":98,"header":"def test_raises_message_argument_deprecated()","id":4755,"name":"test_raises_message_argument_deprecated","nodeType":"Function","startLoc":95,"text":"def test_raises_message_argument_deprecated():\n with pytest.warns(pytest.PytestDeprecationWarning):\n with pytest.raises(RuntimeError, message=\"foobar\"):\n raise RuntimeError"},{"col":0,"comment":"null","endLoc":122,"header":"def test_pytest_plugins_in_non_top_level_conftest_deprecated(testdir)","id":4756,"name":"test_pytest_plugins_in_non_top_level_conftest_deprecated","nodeType":"Function","startLoc":101,"text":"def test_pytest_plugins_in_non_top_level_conftest_deprecated(testdir):\n from _pytest.deprecated import PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST\n\n testdir.makepyfile(\n **{\n \"subdirectory/conftest.py\": \"\"\"\n pytest_plugins=['capture']\n \"\"\"\n }\n )\n testdir.makepyfile(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n res = testdir.runpytest(SHOW_PYTEST_WARNINGS_ARG)\n assert res.ret == 2\n msg = str(PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST).splitlines()[0]\n res.stdout.fnmatch_lines(\n [\"*{msg}*\".format(msg=msg), \"*subdirectory{sep}conftest.py*\".format(sep=os.sep)]\n )"},{"col":4,"comment":"null","endLoc":895,"header":"def getparam(self, name)","id":4757,"name":"getparam","nodeType":"Function","startLoc":889,"text":"def getparam(self, name):\n try:\n return self.params[name]\n except KeyError:\n if self._globalparam is NOTSET:\n raise ValueError(name)\n return self._globalparam"},{"col":4,"comment":"null","endLoc":899,"header":"@property\n def id(self)","id":4758,"name":"id","nodeType":"Function","startLoc":897,"text":"@property\n def id(self):\n return \"-\".join(map(str, filter(None, self._idlist)))"},{"col":0,"comment":"null","endLoc":683,"header":"def test_pytest_no_tests_collected_exit_status(testdir)","id":4759,"name":"test_pytest_no_tests_collected_exit_status","nodeType":"Function","startLoc":664,"text":"def test_pytest_no_tests_collected_exit_status(testdir):\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*collected 0 items*\"])\n assert result.ret == main.EXIT_NOTESTSCOLLECTED\n\n testdir.makepyfile(\n test_foo=\"\"\"\n def test_foo():\n assert 1\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*collected 1 item*\"])\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n assert result.ret == main.EXIT_OK\n\n result = testdir.runpytest(\"-k nonmatch\")\n result.stdout.fnmatch_lines([\"*collected 1 item*\"])\n result.stdout.fnmatch_lines([\"*1 deselected*\"])\n assert result.ret == main.EXIT_NOTESTSCOLLECTED"},{"col":0,"comment":"null","endLoc":692,"header":"def test_exception_printing_skip()","id":4760,"name":"test_exception_printing_skip","nodeType":"Function","startLoc":686,"text":"def test_exception_printing_skip():\n try:\n pytest.skip(\"hello\")\n except pytest.skip.Exception:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n s = excinfo.exconly(tryshort=True)\n assert s.startswith(\"Skipped\")"},{"col":0,"comment":"null","endLoc":722,"header":"def test_importorskip(monkeypatch)","id":4761,"name":"test_importorskip","nodeType":"Function","startLoc":695,"text":"def test_importorskip(monkeypatch):\n importorskip = pytest.importorskip\n\n def f():\n importorskip(\"asdlkj\")\n\n try:\n sysmod = importorskip(\"sys\")\n assert sysmod is sys\n # path = pytest.importorskip(\"os.path\")\n # assert path == os.path\n excinfo = pytest.raises(pytest.skip.Exception, f)\n path = py.path.local(excinfo.getrepr().reprcrash.path)\n # check that importorskip reports the actual call\n # in this test the test_runner.py file\n assert path.purebasename == \"test_runner\"\n pytest.raises(SyntaxError, pytest.importorskip, \"x y z\")\n pytest.raises(SyntaxError, pytest.importorskip, \"x=y\")\n mod = types.ModuleType(\"hello123\")\n mod.__version__ = \"1.3\"\n monkeypatch.setitem(sys.modules, \"hello123\", mod)\n with pytest.raises(pytest.skip.Exception):\n pytest.importorskip(\"hello123\", minversion=\"1.3.1\")\n mod2 = pytest.importorskip(\"hello123\", minversion=\"1.3\")\n assert mod2 == mod\n except pytest.skip.Exception:\n print(_pytest._code.ExceptionInfo.from_current())\n pytest.fail(\"spurious skip\")"},{"col":4,"comment":" stop capturing and reset capturing streams ","endLoc":532,"header":"def stop_capturing(self)","id":4762,"name":"stop_capturing","nodeType":"Function","startLoc":522,"text":"def stop_capturing(self):\n \"\"\" stop capturing and reset capturing streams \"\"\"\n if self._state == \"stopped\":\n raise ValueError(\"was already stopped\")\n self._state = \"stopped\"\n if self.out:\n self.out.done()\n if self.err:\n self.err.done()\n if self.in_:\n self.in_.done()"},{"col":4,"comment":"null","endLoc":425,"header":"def test_failure_verbose_message(self, testdir)","id":4763,"name":"test_failure_verbose_message","nodeType":"Function","startLoc":412,"text":"def test_failure_verbose_message(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n def test_fail():\n assert 0, \"An error\"\n \"\"\"\n )\n\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n fnode = tnode.find_first_by_tag(\"failure\")\n fnode.assert_attr(message=\"AssertionError: An error assert 0\")"},{"col":4,"comment":"null","endLoc":450,"header":"def test_failure_escape(self, testdir)","id":4764,"name":"test_failure_escape","nodeType":"Function","startLoc":427,"text":"def test_failure_escape(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('arg1', \"<&'\", ids=\"<&'\")\n def test_func(arg1):\n print(arg1)\n assert 0\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(failures=3, tests=3)\n\n for index, char in enumerate(\"<&'\"):\n\n tnode = node.find_nth_by_tag(\"testcase\", index)\n tnode.assert_attr(\n classname=\"test_failure_escape\", name=\"test_func[%s]\" % char\n )\n sysout = tnode.find_first_by_tag(\"system-out\")\n text = sysout.text\n assert text == \"%s\\n\" % char"},{"col":4,"comment":"null","endLoc":445,"header":"def writelines(self, linelist)","id":4765,"name":"writelines","nodeType":"Function","startLoc":443,"text":"def writelines(self, linelist):\n data = \"\".join(linelist)\n self.write(data)"},{"col":4,"comment":"null","endLoc":96,"header":"@needsosdup\n def test_init_capturing(self)","id":4766,"name":"test_init_capturing","nodeType":"Function","startLoc":87,"text":"@needsosdup\n def test_init_capturing(self):\n capouter = StdCaptureFD()\n try:\n capman = CaptureManager(\"fd\")\n capman.start_global_capturing()\n pytest.raises(AssertionError, capman.start_global_capturing)\n capman.stop_global_capturing()\n finally:\n capouter.stop_capturing()"},{"className":"TestPerTestCapturing","col":0,"comment":"null","endLoc":295,"id":4767,"nodeType":"Class","startLoc":155,"text":"class TestPerTestCapturing(object):\n def test_capture_and_fixtures(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def setup_module(mod):\n print(\"setup module\")\n def setup_function(function):\n print(\"setup \" + function.__name__)\n def test_func1():\n print(\"in func1\")\n assert 0\n def test_func2():\n print(\"in func2\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n \"setup module*\",\n \"setup test_func1*\",\n \"in func1*\",\n \"setup test_func2*\",\n \"in func2*\",\n ]\n )\n\n @pytest.mark.xfail(reason=\"unimplemented feature\")\n def test_capture_scope_cache(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import sys\n def setup_module(func):\n print(\"module-setup\")\n def setup_function(func):\n print(\"function-setup\")\n def test_func():\n print(\"in function\")\n assert 0\n def teardown_function(func):\n print(\"in teardown\")\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n \"*test_func():*\",\n \"*Captured stdout during setup*\",\n \"module-setup*\",\n \"function-setup*\",\n \"*Captured stdout*\",\n \"in teardown*\",\n ]\n )\n\n def test_no_carry_over(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_func1():\n print(\"in func1\")\n def test_func2():\n print(\"in func2\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p)\n s = result.stdout.str()\n assert \"in func1\" not in s\n assert \"in func2\" in s\n\n def test_teardown_capturing(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def setup_function(function):\n print(\"setup func1\")\n def teardown_function(function):\n print(\"teardown func1\")\n assert 0\n def test_func1():\n print(\"in func1\")\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n \"*teardown_function*\",\n \"*Captured stdout*\",\n \"setup func1*\",\n \"in func1*\",\n \"teardown func1*\",\n # \"*1 fixture failure*\"\n ]\n )\n\n def test_teardown_capturing_final(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def teardown_module(mod):\n print(\"teardown module\")\n assert 0\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n \"*def teardown_module(mod):*\",\n \"*Captured stdout*\",\n \"*teardown module*\",\n \"*1 error*\",\n ]\n )\n\n def test_capturing_outerr(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\\\n import sys\n def test_capturing():\n print(42)\n sys.stderr.write(str(23))\n def test_capturing_error():\n print(1)\n sys.stderr.write(str(2))\n raise ValueError\n \"\"\"\n )\n result = testdir.runpytest(p1)\n result.stdout.fnmatch_lines(\n [\n \"*test_capturing_outerr.py .F*\",\n \"====* FAILURES *====\",\n \"____*____\",\n \"*test_capturing_outerr.py:8: ValueError\",\n \"*--- Captured stdout *call*\",\n \"1\",\n \"*--- Captured stderr *call*\",\n \"2\",\n ]\n )"},{"col":0,"comment":"null","endLoc":727,"header":"def test_importorskip_imports_last_module_part()","id":4768,"name":"test_importorskip_imports_last_module_part","nodeType":"Function","startLoc":725,"text":"def test_importorskip_imports_last_module_part():\n ospath = pytest.importorskip(\"os.path\")\n assert os.path == ospath"},{"col":4,"comment":"null","endLoc":180,"header":"def test_capture_and_fixtures(self, testdir)","id":4769,"name":"test_capture_and_fixtures","nodeType":"Function","startLoc":156,"text":"def test_capture_and_fixtures(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def setup_module(mod):\n print(\"setup module\")\n def setup_function(function):\n print(\"setup \" + function.__name__)\n def test_func1():\n print(\"in func1\")\n assert 0\n def test_func2():\n print(\"in func2\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n \"setup module*\",\n \"setup test_func1*\",\n \"in func1*\",\n \"setup test_func2*\",\n \"in func2*\",\n ]\n )"},{"col":0,"comment":"null","endLoc":741,"header":"def test_importorskip_dev_module(monkeypatch)","id":4770,"name":"test_importorskip_dev_module","nodeType":"Function","startLoc":730,"text":"def test_importorskip_dev_module(monkeypatch):\n try:\n mod = types.ModuleType(\"mockmodule\")\n mod.__version__ = \"0.13.0.dev-43290\"\n monkeypatch.setitem(sys.modules, \"mockmodule\", mod)\n mod2 = pytest.importorskip(\"mockmodule\", minversion=\"0.12.0\")\n assert mod2 == mod\n with pytest.raises(pytest.skip.Exception):\n pytest.importorskip(\"mockmodule1\", minversion=\"0.14.0\")\n except pytest.skip.Exception:\n print(_pytest._code.ExceptionInfo.from_current())\n pytest.fail(\"spurious skip\")"},{"col":4,"comment":"null","endLoc":208,"header":"@pytest.mark.xfail(reason=\"unimplemented feature\")\n def test_capture_scope_cache(self, testdir)","id":4771,"name":"test_capture_scope_cache","nodeType":"Function","startLoc":182,"text":"@pytest.mark.xfail(reason=\"unimplemented feature\")\n def test_capture_scope_cache(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import sys\n def setup_module(func):\n print(\"module-setup\")\n def setup_function(func):\n print(\"function-setup\")\n def test_func():\n print(\"in function\")\n assert 0\n def teardown_function(func):\n print(\"in teardown\")\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n \"*test_func():*\",\n \"*Captured stdout during setup*\",\n \"module-setup*\",\n \"function-setup*\",\n \"*Captured stdout*\",\n \"in teardown*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":223,"header":"def test_no_carry_over(self, testdir)","id":4772,"name":"test_no_carry_over","nodeType":"Function","startLoc":210,"text":"def test_no_carry_over(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_func1():\n print(\"in func1\")\n def test_func2():\n print(\"in func2\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p)\n s = result.stdout.str()\n assert \"in func1\" not in s\n assert \"in func2\" in s"},{"col":4,"comment":"Ensure that file.name is a string.","endLoc":450,"header":"@property\n def name(self)","id":4773,"name":"name","nodeType":"Function","startLoc":447,"text":"@property\n def name(self):\n \"\"\"Ensure that file.name is a string.\"\"\"\n return repr(self.buffer)"},{"col":4,"comment":"null","endLoc":454,"header":"@property\n def mode(self)","id":4774,"name":"mode","nodeType":"Function","startLoc":452,"text":"@property\n def mode(self):\n return self.buffer.mode.replace(\"b\", \"\")"},{"col":4,"comment":"null","endLoc":248,"header":"def test_teardown_capturing(self, testdir)","id":4775,"name":"test_teardown_capturing","nodeType":"Function","startLoc":225,"text":"def test_teardown_capturing(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def setup_function(function):\n print(\"setup func1\")\n def teardown_function(function):\n print(\"teardown func1\")\n assert 0\n def test_func1():\n print(\"in func1\")\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n \"*teardown_function*\",\n \"*Captured stdout*\",\n \"setup func1*\",\n \"in func1*\",\n \"teardown func1*\",\n # \"*1 fixture failure*\"\n ]\n )"},{"col":0,"comment":"importorskip must be able to skip entire modules when used at module level","endLoc":756,"header":"def test_importorskip_module_level(testdir)","id":4776,"name":"test_importorskip_module_level","nodeType":"Function","startLoc":744,"text":"def test_importorskip_module_level(testdir):\n \"\"\"importorskip must be able to skip entire modules when used at module level\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n foobarbaz = pytest.importorskip(\"foobarbaz\")\n\n def test_foo():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*collected 0 items / 1 skipped*\"])"},{"col":4,"comment":"null","endLoc":457,"header":"def __getattr__(self, name)","id":4777,"name":"__getattr__","nodeType":"Function","startLoc":456,"text":"def __getattr__(self, name):\n return getattr(object.__getattribute__(self, \"buffer\"), name)"},{"col":4,"comment":"null","endLoc":268,"header":"def test_teardown_capturing_final(self, testdir)","id":4778,"name":"test_teardown_capturing_final","nodeType":"Function","startLoc":250,"text":"def test_teardown_capturing_final(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def teardown_module(mod):\n print(\"teardown module\")\n assert 0\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n \"*def teardown_module(mod):*\",\n \"*Captured stdout*\",\n \"*teardown module*\",\n \"*1 error*\",\n ]\n )"},{"col":0,"comment":"make sure custom reasons are used","endLoc":772,"header":"def test_importorskip_custom_reason(testdir)","id":4779,"name":"test_importorskip_custom_reason","nodeType":"Function","startLoc":759,"text":"def test_importorskip_custom_reason(testdir):\n \"\"\"make sure custom reasons are used\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n foobarbaz = pytest.importorskip(\"foobarbaz2\", reason=\"just because\")\n\n def test_foo():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-ra\")\n result.stdout.fnmatch_lines([\"*just because*\"])\n result.stdout.fnmatch_lines([\"*collected 0 items / 1 skipped*\"])"},{"col":4,"comment":"null","endLoc":295,"header":"def test_capturing_outerr(self, testdir)","id":4780,"name":"test_capturing_outerr","nodeType":"Function","startLoc":270,"text":"def test_capturing_outerr(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\\\n import sys\n def test_capturing():\n print(42)\n sys.stderr.write(str(23))\n def test_capturing_error():\n print(1)\n sys.stderr.write(str(2))\n raise ValueError\n \"\"\"\n )\n result = testdir.runpytest(p1)\n result.stdout.fnmatch_lines(\n [\n \"*test_capturing_outerr.py .F*\",\n \"====* FAILURES *====\",\n \"____*____\",\n \"*test_capturing_outerr.py:8: ValueError\",\n \"*--- Captured stdout *call*\",\n \"1\",\n \"*--- Captured stderr *call*\",\n \"2\",\n ]\n )"},{"col":0,"comment":"null","endLoc":790,"header":"def test_pytest_cmdline_main(testdir)","id":4781,"name":"test_pytest_cmdline_main","nodeType":"Function","startLoc":775,"text":"def test_pytest_cmdline_main(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_hello():\n assert 1\n if __name__ == '__main__':\n pytest.cmdline.main([__file__])\n \"\"\"\n )\n import subprocess\n\n popen = subprocess.Popen([sys.executable, str(p)], stdout=subprocess.PIPE)\n popen.communicate()\n ret = popen.wait()\n assert ret == 0"},{"className":"TestLoggingInteraction","col":0,"comment":"null","endLoc":433,"id":4782,"nodeType":"Class","startLoc":298,"text":"class TestLoggingInteraction(object):\n def test_logging_stream_ownership(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n def test_logging():\n import logging\n import pytest\n stream = capture.CaptureIO()\n logging.basicConfig(stream=stream)\n stream.close() # to free memory/release resources\n \"\"\"\n )\n result = testdir.runpytest_subprocess(p)\n assert result.stderr.str().find(\"atexit\") == -1\n\n def test_logging_and_immediate_setupteardown(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n import logging\n def setup_function(function):\n logging.warning(\"hello1\")\n\n def test_logging():\n logging.warning(\"hello2\")\n assert 0\n\n def teardown_function(function):\n logging.warning(\"hello3\")\n assert 0\n \"\"\"\n )\n for optargs in ((\"--capture=sys\",), (\"--capture=fd\",)):\n print(optargs)\n result = testdir.runpytest_subprocess(p, *optargs)\n s = result.stdout.str()\n result.stdout.fnmatch_lines(\n [\"*WARN*hello3\", \"*WARN*hello1\", \"*WARN*hello2\"] # errors show first!\n )\n # verify proper termination\n assert \"closed\" not in s\n\n def test_logging_and_crossscope_fixtures(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n import logging\n def setup_module(function):\n logging.warning(\"hello1\")\n\n def test_logging():\n logging.warning(\"hello2\")\n assert 0\n\n def teardown_module(function):\n logging.warning(\"hello3\")\n assert 0\n \"\"\"\n )\n for optargs in ((\"--capture=sys\",), (\"--capture=fd\",)):\n print(optargs)\n result = testdir.runpytest_subprocess(p, *optargs)\n s = result.stdout.str()\n result.stdout.fnmatch_lines(\n [\"*WARN*hello3\", \"*WARN*hello1\", \"*WARN*hello2\"] # errors come first\n )\n # verify proper termination\n assert \"closed\" not in s\n\n def test_conftestlogging_is_shown(self, testdir):\n testdir.makeconftest(\n \"\"\"\\\n import logging\n logging.basicConfig()\n logging.warning(\"hello435\")\n \"\"\"\n )\n # make sure that logging is still captured in tests\n result = testdir.runpytest_subprocess(\"-s\", \"-p\", \"no:capturelog\")\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result.stderr.fnmatch_lines([\"WARNING*hello435*\"])\n assert \"operation on closed file\" not in result.stderr.str()\n\n def test_conftestlogging_and_test_logging(self, testdir):\n testdir.makeconftest(\n \"\"\"\\\n import logging\n logging.basicConfig()\n \"\"\"\n )\n # make sure that logging is still captured in tests\n p = testdir.makepyfile(\n \"\"\"\\\n def test_hello():\n import logging\n logging.warning(\"hello433\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest_subprocess(p, \"-p\", \"no:capturelog\")\n assert result.ret != 0\n result.stdout.fnmatch_lines([\"WARNING*hello433*\"])\n assert \"something\" not in result.stderr.str()\n assert \"operation on closed file\" not in result.stderr.str()\n\n def test_logging_after_cap_stopped(self, testdir):\n testdir.makeconftest(\n \"\"\"\\\n import pytest\n import logging\n\n log = logging.getLogger(__name__)\n\n @pytest.fixture\n def log_on_teardown():\n yield\n log.warning('Logging on teardown')\n \"\"\"\n )\n # make sure that logging is still captured in tests\n p = testdir.makepyfile(\n \"\"\"\\\n def test_hello(log_on_teardown):\n import logging\n logging.warning(\"hello433\")\n assert 1\n raise KeyboardInterrupt()\n \"\"\"\n )\n result = testdir.runpytest_subprocess(p, \"--log-cli-level\", \"info\")\n assert result.ret != 0\n result.stdout.fnmatch_lines(\n [\"*WARNING*hello433*\", \"*WARNING*Logging on teardown*\"]\n )\n assert (\n \"AttributeError: 'NoneType' object has no attribute 'resume_capturing'\"\n not in result.stderr.str()\n )"},{"col":4,"comment":"null","endLoc":311,"header":"def test_logging_stream_ownership(self, testdir)","id":4783,"name":"test_logging_stream_ownership","nodeType":"Function","startLoc":299,"text":"def test_logging_stream_ownership(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n def test_logging():\n import logging\n import pytest\n stream = capture.CaptureIO()\n logging.basicConfig(stream=stream)\n stream.close() # to free memory/release resources\n \"\"\"\n )\n result = testdir.runpytest_subprocess(p)\n assert result.stderr.str().find(\"atexit\") == -1"},{"attributeType":"str","col":4,"comment":"null","endLoc":428,"id":4784,"name":"errors","nodeType":"Attribute","startLoc":428,"text":"errors"},{"attributeType":"null","col":8,"comment":"null","endLoc":431,"id":4785,"name":"buffer","nodeType":"Attribute","startLoc":431,"text":"self.buffer"},{"attributeType":"null","col":8,"comment":"null","endLoc":432,"id":4786,"name":"encoding","nodeType":"Attribute","startLoc":432,"text":"self.encoding"},{"col":4,"comment":"null","endLoc":337,"header":"def test_logging_and_immediate_setupteardown(self, testdir)","id":4787,"name":"test_logging_and_immediate_setupteardown","nodeType":"Function","startLoc":313,"text":"def test_logging_and_immediate_setupteardown(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n import logging\n def setup_function(function):\n logging.warning(\"hello1\")\n\n def test_logging():\n logging.warning(\"hello2\")\n assert 0\n\n def teardown_function(function):\n logging.warning(\"hello3\")\n assert 0\n \"\"\"\n )\n for optargs in ((\"--capture=sys\",), (\"--capture=fd\",)):\n print(optargs)\n result = testdir.runpytest_subprocess(p, *optargs)\n s = result.stdout.str()\n result.stdout.fnmatch_lines(\n [\"*WARN*hello3\", \"*WARN*hello1\", \"*WARN*hello2\"] # errors show first!\n )\n # verify proper termination\n assert \"closed\" not in s"},{"className":"MultiCapture","col":0,"comment":"null","endLoc":539,"id":4788,"nodeType":"Class","startLoc":463,"text":"class MultiCapture(object):\n out = err = in_ = None\n _state = None\n\n def __init__(self, out=True, err=True, in_=True, Capture=None):\n if in_:\n self.in_ = Capture(0)\n if out:\n self.out = Capture(1)\n if err:\n self.err = Capture(2)\n\n def __repr__(self):\n return \"\" % (\n self.out,\n self.err,\n self.in_,\n self._state,\n getattr(self, \"_in_suspended\", \"\"),\n )\n\n def start_capturing(self):\n self._state = \"started\"\n if self.in_:\n self.in_.start()\n if self.out:\n self.out.start()\n if self.err:\n self.err.start()\n\n def pop_outerr_to_orig(self):\n \"\"\" pop current snapshot out/err capture and flush to orig streams. \"\"\"\n out, err = self.readouterr()\n if out:\n self.out.writeorg(out)\n if err:\n self.err.writeorg(err)\n return out, err\n\n def suspend_capturing(self, in_=False):\n self._state = \"suspended\"\n if self.out:\n self.out.suspend()\n if self.err:\n self.err.suspend()\n if in_ and self.in_:\n self.in_.suspend()\n self._in_suspended = True\n\n def resume_capturing(self):\n self._state = \"resumed\"\n if self.out:\n self.out.resume()\n if self.err:\n self.err.resume()\n if hasattr(self, \"_in_suspended\"):\n self.in_.resume()\n del self._in_suspended\n\n def stop_capturing(self):\n \"\"\" stop capturing and reset capturing streams \"\"\"\n if self._state == \"stopped\":\n raise ValueError(\"was already stopped\")\n self._state = \"stopped\"\n if self.out:\n self.out.done()\n if self.err:\n self.err.done()\n if self.in_:\n self.in_.done()\n\n def readouterr(self):\n \"\"\" return snapshot unicode value of stdout/stderr capturings. \"\"\"\n return CaptureResult(\n self.out.snap() if self.out is not None else \"\",\n self.err.snap() if self.err is not None else \"\",\n )"},{"col":4,"comment":"null","endLoc":482,"header":"def __repr__(self)","id":4789,"name":"__repr__","nodeType":"Function","startLoc":475,"text":"def __repr__(self):\n return \"\" % (\n self.out,\n self.err,\n self.in_,\n self._state,\n getattr(self, \"_in_suspended\", \"\"),\n )"},{"col":4,"comment":"null","endLoc":363,"header":"def test_logging_and_crossscope_fixtures(self, testdir)","id":4790,"name":"test_logging_and_crossscope_fixtures","nodeType":"Function","startLoc":339,"text":"def test_logging_and_crossscope_fixtures(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n import logging\n def setup_module(function):\n logging.warning(\"hello1\")\n\n def test_logging():\n logging.warning(\"hello2\")\n assert 0\n\n def teardown_module(function):\n logging.warning(\"hello3\")\n assert 0\n \"\"\"\n )\n for optargs in ((\"--capture=sys\",), (\"--capture=fd\",)):\n print(optargs)\n result = testdir.runpytest_subprocess(p, *optargs)\n s = result.stdout.str()\n result.stdout.fnmatch_lines(\n [\"*WARN*hello3\", \"*WARN*hello1\", \"*WARN*hello2\"] # errors come first\n )\n # verify proper termination\n assert \"closed\" not in s"},{"col":4,"comment":" pop current snapshot out/err capture and flush to orig streams. ","endLoc":500,"header":"def pop_outerr_to_orig(self)","id":4791,"name":"pop_outerr_to_orig","nodeType":"Function","startLoc":493,"text":"def pop_outerr_to_orig(self):\n \"\"\" pop current snapshot out/err capture and flush to orig streams. \"\"\"\n out, err = self.readouterr()\n if out:\n self.out.writeorg(out)\n if err:\n self.err.writeorg(err)\n return out, err"},{"col":4,"comment":"null","endLoc":75,"header":"def test_getparent(self, testdir)","id":4792,"name":"test_getparent","nodeType":"Function","startLoc":57,"text":"def test_getparent(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n class TestClass(object):\n def test_foo():\n pass\n \"\"\"\n )\n cls = testdir.collect_by_name(modcol, \"TestClass\")\n fn = testdir.collect_by_name(testdir.collect_by_name(cls, \"()\"), \"test_foo\")\n\n parent = fn.getparent(pytest.Module)\n assert parent is modcol\n\n parent = fn.getparent(pytest.Function)\n assert parent is fn\n\n parent = fn.getparent(pytest.Class)\n assert parent is cls"},{"col":4,"comment":"null","endLoc":377,"header":"def test_conftestlogging_is_shown(self, testdir)","id":4793,"name":"test_conftestlogging_is_shown","nodeType":"Function","startLoc":365,"text":"def test_conftestlogging_is_shown(self, testdir):\n testdir.makeconftest(\n \"\"\"\\\n import logging\n logging.basicConfig()\n logging.warning(\"hello435\")\n \"\"\"\n )\n # make sure that logging is still captured in tests\n result = testdir.runpytest_subprocess(\"-s\", \"-p\", \"no:capturelog\")\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result.stderr.fnmatch_lines([\"WARNING*hello435*\"])\n assert \"operation on closed file\" not in result.stderr.str()"},{"col":4,"comment":"null","endLoc":94,"header":"def test_getcustomfile_roundtrip(self, testdir)","id":4794,"name":"test_getcustomfile_roundtrip","nodeType":"Function","startLoc":77,"text":"def test_getcustomfile_roundtrip(self, testdir):\n hello = testdir.makefile(\".xxx\", hello=\"world\")\n testdir.makepyfile(\n conftest=\"\"\"\n import pytest\n class CustomFile(pytest.File):\n pass\n def pytest_collect_file(path, parent):\n if path.ext == \".xxx\":\n return CustomFile(path, parent=parent)\n \"\"\"\n )\n node = testdir.getpathnode(hello)\n assert isinstance(node, pytest.File)\n assert node.name == \"hello.xxx\"\n nodes = node.session.perform_collect([node.nodeid], genitems=False)\n assert len(nodes) == 1\n assert isinstance(nodes[0], pytest.File)"},{"col":4,"comment":" return snapshot unicode value of stdout/stderr capturings. ","endLoc":539,"header":"def readouterr(self)","id":4795,"name":"readouterr","nodeType":"Function","startLoc":534,"text":"def readouterr(self):\n \"\"\" return snapshot unicode value of stdout/stderr capturings. \"\"\"\n return CaptureResult(\n self.out.snap() if self.out is not None else \"\",\n self.err.snap() if self.err is not None else \"\",\n )"},{"col":4,"comment":"Assure test class is skipped when using `__test__=False` (See #2007).","endLoc":109,"header":"def test_can_skip_class_with_test_attr(self, testdir)","id":4796,"name":"test_can_skip_class_with_test_attr","nodeType":"Function","startLoc":96,"text":"def test_can_skip_class_with_test_attr(self, testdir):\n \"\"\"Assure test class is skipped when using `__test__=False` (See #2007).\"\"\"\n testdir.makepyfile(\n \"\"\"\n class TestFoo(object):\n __test__ = False\n def __init__(self):\n pass\n def test_foo():\n assert True\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"collected 0 items\", \"*no tests ran in*\"])"},{"className":"TestCollectFS","col":0,"comment":"null","endLoc":246,"id":4797,"nodeType":"Class","startLoc":112,"text":"class TestCollectFS(object):\n def test_ignored_certain_directories(self, testdir):\n tmpdir = testdir.tmpdir\n tmpdir.ensure(\"build\", \"test_notfound.py\")\n tmpdir.ensure(\"dist\", \"test_notfound.py\")\n tmpdir.ensure(\"_darcs\", \"test_notfound.py\")\n tmpdir.ensure(\"CVS\", \"test_notfound.py\")\n tmpdir.ensure(\"{arch}\", \"test_notfound.py\")\n tmpdir.ensure(\".whatever\", \"test_notfound.py\")\n tmpdir.ensure(\".bzr\", \"test_notfound.py\")\n tmpdir.ensure(\"normal\", \"test_found.py\")\n for x in tmpdir.visit(\"test_*.py\"):\n x.write(\"def test_hello(): pass\")\n\n result = testdir.runpytest(\"--collect-only\")\n s = result.stdout.str()\n assert \"test_notfound\" not in s\n assert \"test_found\" in s\n\n @pytest.mark.parametrize(\n \"fname\",\n (\n \"activate\",\n \"activate.csh\",\n \"activate.fish\",\n \"Activate\",\n \"Activate.bat\",\n \"Activate.ps1\",\n ),\n )\n def test_ignored_virtualenvs(self, testdir, fname):\n bindir = \"Scripts\" if sys.platform.startswith(\"win\") else \"bin\"\n testdir.tmpdir.ensure(\"virtual\", bindir, fname)\n testfile = testdir.tmpdir.ensure(\"virtual\", \"test_invenv.py\")\n testfile.write(\"def test_hello(): pass\")\n\n # by default, ignore tests inside a virtualenv\n result = testdir.runpytest()\n assert \"test_invenv\" not in result.stdout.str()\n # allow test collection if user insists\n result = testdir.runpytest(\"--collect-in-virtualenv\")\n assert \"test_invenv\" in result.stdout.str()\n # allow test collection if user directly passes in the directory\n result = testdir.runpytest(\"virtual\")\n assert \"test_invenv\" in result.stdout.str()\n\n @pytest.mark.parametrize(\n \"fname\",\n (\n \"activate\",\n \"activate.csh\",\n \"activate.fish\",\n \"Activate\",\n \"Activate.bat\",\n \"Activate.ps1\",\n ),\n )\n def test_ignored_virtualenvs_norecursedirs_precedence(self, testdir, fname):\n bindir = \"Scripts\" if sys.platform.startswith(\"win\") else \"bin\"\n # norecursedirs takes priority\n testdir.tmpdir.ensure(\".virtual\", bindir, fname)\n testfile = testdir.tmpdir.ensure(\".virtual\", \"test_invenv.py\")\n testfile.write(\"def test_hello(): pass\")\n result = testdir.runpytest(\"--collect-in-virtualenv\")\n assert \"test_invenv\" not in result.stdout.str()\n # ...unless the virtualenv is explicitly given on the CLI\n result = testdir.runpytest(\"--collect-in-virtualenv\", \".virtual\")\n assert \"test_invenv\" in result.stdout.str()\n\n @pytest.mark.parametrize(\n \"fname\",\n (\n \"activate\",\n \"activate.csh\",\n \"activate.fish\",\n \"Activate\",\n \"Activate.bat\",\n \"Activate.ps1\",\n ),\n )\n def test__in_venv(self, testdir, fname):\n \"\"\"Directly test the virtual env detection function\"\"\"\n bindir = \"Scripts\" if sys.platform.startswith(\"win\") else \"bin\"\n # no bin/activate, not a virtualenv\n base_path = testdir.tmpdir.mkdir(\"venv\")\n assert _in_venv(base_path) is False\n # with bin/activate, totally a virtualenv\n base_path.ensure(bindir, fname)\n assert _in_venv(base_path) is True\n\n def test_custom_norecursedirs(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n norecursedirs = mydir xyz*\n \"\"\"\n )\n tmpdir = testdir.tmpdir\n tmpdir.ensure(\"mydir\", \"test_hello.py\").write(\"def test_1(): pass\")\n tmpdir.ensure(\"xyz123\", \"test_2.py\").write(\"def test_2(): 0/0\")\n tmpdir.ensure(\"xy\", \"test_ok.py\").write(\"def test_3(): pass\")\n rec = testdir.inline_run()\n rec.assertoutcome(passed=1)\n rec = testdir.inline_run(\"xyz123/test_2.py\")\n rec.assertoutcome(failed=1)\n\n def test_testpaths_ini(self, testdir, monkeypatch):\n testdir.makeini(\n \"\"\"\n [pytest]\n testpaths = gui uts\n \"\"\"\n )\n tmpdir = testdir.tmpdir\n tmpdir.ensure(\"env\", \"test_1.py\").write(\"def test_env(): pass\")\n tmpdir.ensure(\"gui\", \"test_2.py\").write(\"def test_gui(): pass\")\n tmpdir.ensure(\"uts\", \"test_3.py\").write(\"def test_uts(): pass\")\n\n # executing from rootdir only tests from `testpaths` directories\n # are collected\n items, reprec = testdir.inline_genitems(\"-v\")\n assert [x.name for x in items] == [\"test_gui\", \"test_uts\"]\n\n # check that explicitly passing directories in the command-line\n # collects the tests\n for dirname in (\"env\", \"gui\", \"uts\"):\n items, reprec = testdir.inline_genitems(tmpdir.join(dirname))\n assert [x.name for x in items] == [\"test_%s\" % dirname]\n\n # changing cwd to each subdirectory and running pytest without\n # arguments collects the tests in that directory normally\n for dirname in (\"env\", \"gui\", \"uts\"):\n monkeypatch.chdir(testdir.tmpdir.join(dirname))\n items, reprec = testdir.inline_genitems()\n assert [x.name for x in items] == [\"test_%s\" % dirname]"},{"col":4,"comment":"null","endLoc":129,"header":"def test_ignored_certain_directories(self, testdir)","id":4798,"name":"test_ignored_certain_directories","nodeType":"Function","startLoc":113,"text":"def test_ignored_certain_directories(self, testdir):\n tmpdir = testdir.tmpdir\n tmpdir.ensure(\"build\", \"test_notfound.py\")\n tmpdir.ensure(\"dist\", \"test_notfound.py\")\n tmpdir.ensure(\"_darcs\", \"test_notfound.py\")\n tmpdir.ensure(\"CVS\", \"test_notfound.py\")\n tmpdir.ensure(\"{arch}\", \"test_notfound.py\")\n tmpdir.ensure(\".whatever\", \"test_notfound.py\")\n tmpdir.ensure(\".bzr\", \"test_notfound.py\")\n tmpdir.ensure(\"normal\", \"test_found.py\")\n for x in tmpdir.visit(\"test_*.py\"):\n x.write(\"def test_hello(): pass\")\n\n result = testdir.runpytest(\"--collect-only\")\n s = result.stdout.str()\n assert \"test_notfound\" not in s\n assert \"test_found\" in s"},{"col":4,"comment":"null","endLoc":399,"header":"def test_conftestlogging_and_test_logging(self, testdir)","id":4799,"name":"test_conftestlogging_and_test_logging","nodeType":"Function","startLoc":379,"text":"def test_conftestlogging_and_test_logging(self, testdir):\n testdir.makeconftest(\n \"\"\"\\\n import logging\n logging.basicConfig()\n \"\"\"\n )\n # make sure that logging is still captured in tests\n p = testdir.makepyfile(\n \"\"\"\\\n def test_hello():\n import logging\n logging.warning(\"hello433\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest_subprocess(p, \"-p\", \"no:capturelog\")\n assert result.ret != 0\n result.stdout.fnmatch_lines([\"WARNING*hello433*\"])\n assert \"something\" not in result.stderr.str()\n assert \"operation on closed file\" not in result.stderr.str()"},{"col":4,"comment":"null","endLoc":471,"header":"def test_junit_prefixing(self, testdir)","id":4800,"name":"test_junit_prefixing","nodeType":"Function","startLoc":452,"text":"def test_junit_prefixing(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_func():\n assert 0\n class TestHello(object):\n def test_hello(self):\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir, \"--junitprefix=xyz\")\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(failures=1, tests=2)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"xyz.test_junit_prefixing\", name=\"test_func\")\n tnode = node.find_nth_by_tag(\"testcase\", 1)\n tnode.assert_attr(\n classname=\"xyz.test_junit_prefixing.TestHello\", name=\"test_hello\"\n )"},{"col":4,"comment":"null","endLoc":466,"header":"def pytest_runtest_logfinish(self, nodeid)","id":4801,"name":"pytest_runtest_logfinish","nodeType":"Function","startLoc":447,"text":"def pytest_runtest_logfinish(self, nodeid):\n if self.verbosity <= 0 and self._show_progress_info:\n if self._show_progress_info == \"count\":\n num_tests = self._session.testscollected\n progress_length = len(\" [{}/{}]\".format(str(num_tests), str(num_tests)))\n else:\n progress_length = len(\" [100%]\")\n\n self._progress_nodeids_reported.add(nodeid)\n is_last_item = (\n len(self._progress_nodeids_reported) == self._session.testscollected\n )\n if is_last_item:\n self._write_progress_information_filling_space()\n else:\n w = self._width_of_current_line\n past_edge = w + progress_length + 1 >= self._screen_width\n if past_edge:\n msg = self._get_progress_information_message()\n self._tw.write(msg + \"\\n\", cyan=True)"},{"col":4,"comment":"null","endLoc":156,"header":"@pytest.mark.parametrize(\n \"fname\",\n (\n \"activate\",\n \"activate.csh\",\n \"activate.fish\",\n \"Activate\",\n \"Activate.bat\",\n \"Activate.ps1\",\n ),\n )\n def test_ignored_virtualenvs(self, testdir, fname)","id":4802,"name":"test_ignored_virtualenvs","nodeType":"Function","startLoc":131,"text":"@pytest.mark.parametrize(\n \"fname\",\n (\n \"activate\",\n \"activate.csh\",\n \"activate.fish\",\n \"Activate\",\n \"Activate.bat\",\n \"Activate.ps1\",\n ),\n )\n def test_ignored_virtualenvs(self, testdir, fname):\n bindir = \"Scripts\" if sys.platform.startswith(\"win\") else \"bin\"\n testdir.tmpdir.ensure(\"virtual\", bindir, fname)\n testfile = testdir.tmpdir.ensure(\"virtual\", \"test_invenv.py\")\n testfile.write(\"def test_hello(): pass\")\n\n # by default, ignore tests inside a virtualenv\n result = testdir.runpytest()\n assert \"test_invenv\" not in result.stdout.str()\n # allow test collection if user insists\n result = testdir.runpytest(\"--collect-in-virtualenv\")\n assert \"test_invenv\" in result.stdout.str()\n # allow test collection if user directly passes in the directory\n result = testdir.runpytest(\"virtual\")\n assert \"test_invenv\" in result.stdout.str()"},{"col":4,"comment":"null","endLoc":433,"header":"def test_logging_after_cap_stopped(self, testdir)","id":4803,"name":"test_logging_after_cap_stopped","nodeType":"Function","startLoc":401,"text":"def test_logging_after_cap_stopped(self, testdir):\n testdir.makeconftest(\n \"\"\"\\\n import pytest\n import logging\n\n log = logging.getLogger(__name__)\n\n @pytest.fixture\n def log_on_teardown():\n yield\n log.warning('Logging on teardown')\n \"\"\"\n )\n # make sure that logging is still captured in tests\n p = testdir.makepyfile(\n \"\"\"\\\n def test_hello(log_on_teardown):\n import logging\n logging.warning(\"hello433\")\n assert 1\n raise KeyboardInterrupt()\n \"\"\"\n )\n result = testdir.runpytest_subprocess(p, \"--log-cli-level\", \"info\")\n assert result.ret != 0\n result.stdout.fnmatch_lines(\n [\"*WARNING*hello433*\", \"*WARNING*Logging on teardown*\"]\n )\n assert (\n \"AttributeError: 'NoneType' object has no attribute 'resume_capturing'\"\n not in result.stderr.str()\n )"},{"col":4,"comment":"null","endLoc":510,"header":"def suspend_capturing(self, in_=False)","id":4804,"name":"suspend_capturing","nodeType":"Function","startLoc":502,"text":"def suspend_capturing(self, in_=False):\n self._state = \"suspended\"\n if self.out:\n self.out.suspend()\n if self.err:\n self.err.suspend()\n if in_ and self.in_:\n self.in_.suspend()\n self._in_suspended = True"},{"col":4,"comment":"null","endLoc":489,"header":"def test_xfailure_function(self, testdir)","id":4805,"name":"test_xfailure_function","nodeType":"Function","startLoc":473,"text":"def test_xfailure_function(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_xfail():\n pytest.xfail(\"42\")\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert not result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=1, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_xfailure_function\", name=\"test_xfail\")\n fnode = tnode.find_first_by_tag(\"skipped\")\n fnode.assert_attr(type=\"pytest.xfail\", message=\"42\")\n # assert \"ValueError\" in fnode.toxml()"},{"className":"TestCaptureFixture","col":0,"comment":"null","endLoc":716,"id":4806,"nodeType":"Class","startLoc":436,"text":"class TestCaptureFixture(object):\n @pytest.mark.parametrize(\"opt\", [[], [\"-s\"]])\n def test_std_functional(self, testdir, opt):\n reprec = testdir.inline_runsource(\n \"\"\"\\\n def test_hello(capsys):\n print(42)\n out, err = capsys.readouterr()\n assert out.startswith(\"42\")\n \"\"\",\n *opt\n )\n reprec.assertoutcome(passed=1)\n\n def test_capsyscapfd(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n def test_one(capsys, capfd):\n pass\n def test_two(capfd, capsys):\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n \"*ERROR*setup*test_one*\",\n \"E*capfd*capsys*same*time*\",\n \"*ERROR*setup*test_two*\",\n \"E*capsys*capfd*same*time*\",\n \"*2 error*\",\n ]\n )\n\n def test_capturing_getfixturevalue(self, testdir):\n \"\"\"Test that asking for \"capfd\" and \"capsys\" using request.getfixturevalue\n in the same test is an error.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\\\n def test_one(capsys, request):\n request.getfixturevalue(\"capfd\")\n def test_two(capfd, request):\n request.getfixturevalue(\"capsys\")\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*test_one*\",\n \"*capsys*capfd*same*time*\",\n \"*test_two*\",\n \"*capfd*capsys*same*time*\",\n \"*2 failed in*\",\n ]\n )\n\n def test_capsyscapfdbinary(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n def test_one(capsys, capfdbinary):\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\"*ERROR*setup*test_one*\", \"E*capfdbinary*capsys*same*time*\", \"*1 error*\"]\n )\n\n @pytest.mark.parametrize(\"method\", [\"sys\", \"fd\"])\n def test_capture_is_represented_on_failure_issue128(self, testdir, method):\n p = testdir.makepyfile(\n \"\"\"\\\n def test_hello(cap{}):\n print(\"xxx42xxx\")\n assert 0\n \"\"\".format(\n method\n )\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"xxx42xxx\"])\n\n @needsosdup\n def test_stdfd_functional(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\\\n def test_hello(capfd):\n import os\n os.write(1, \"42\".encode('ascii'))\n out, err = capfd.readouterr()\n assert out.startswith(\"42\")\n capfd.close()\n \"\"\"\n )\n reprec.assertoutcome(passed=1)\n\n @needsosdup\n def test_capfdbinary(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\\\n def test_hello(capfdbinary):\n import os\n # some likely un-decodable bytes\n os.write(1, b'\\\\xfe\\\\x98\\\\x20')\n out, err = capfdbinary.readouterr()\n assert out == b'\\\\xfe\\\\x98\\\\x20'\n assert err == b''\n \"\"\"\n )\n reprec.assertoutcome(passed=1)\n\n @pytest.mark.skipif(\n sys.version_info < (3,), reason=\"only have capsysbinary in python 3\"\n )\n def test_capsysbinary(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\\\n def test_hello(capsysbinary):\n import sys\n # some likely un-decodable bytes\n sys.stdout.buffer.write(b'\\\\xfe\\\\x98\\\\x20')\n out, err = capsysbinary.readouterr()\n assert out == b'\\\\xfe\\\\x98\\\\x20'\n assert err == b''\n \"\"\"\n )\n reprec.assertoutcome(passed=1)\n\n @pytest.mark.skipif(\n sys.version_info >= (3,), reason=\"only have capsysbinary in python 3\"\n )\n def test_capsysbinary_forbidden_in_python2(self, testdir):\n testdir.makepyfile(\n \"\"\"\\\n def test_hello(capsysbinary):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*test_hello*\",\n \"*capsysbinary is only supported on Python 3*\",\n \"*1 error in*\",\n ]\n )\n\n def test_partial_setup_failure(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n def test_hello(capsys, missingarg):\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*test_partial_setup_failure*\", \"*1 error*\"])\n\n @needsosdup\n def test_keyboardinterrupt_disables_capturing(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n def test_hello(capfd):\n import os\n os.write(1, str(42).encode('ascii'))\n raise KeyboardInterrupt()\n \"\"\"\n )\n result = testdir.runpytest_subprocess(p)\n result.stdout.fnmatch_lines([\"*KeyboardInterrupt*\"])\n assert result.ret == 2\n\n def test_capture_and_logging(self, testdir):\n \"\"\"#14\"\"\"\n p = testdir.makepyfile(\n \"\"\"\\\n import logging\n def test_log(capsys):\n logging.error('x')\n \"\"\"\n )\n result = testdir.runpytest_subprocess(p)\n assert \"closed\" not in result.stderr.str()\n\n @pytest.mark.parametrize(\"fixture\", [\"capsys\", \"capfd\"])\n @pytest.mark.parametrize(\"no_capture\", [True, False])\n def test_disabled_capture_fixture(self, testdir, fixture, no_capture):\n testdir.makepyfile(\n \"\"\"\\\n def test_disabled({fixture}):\n print('captured before')\n with {fixture}.disabled():\n print('while capture is disabled')\n print('captured after')\n assert {fixture}.readouterr() == ('captured before\\\\ncaptured after\\\\n', '')\n\n def test_normal():\n print('test_normal executed')\n \"\"\".format(\n fixture=fixture\n )\n )\n args = (\"-s\",) if no_capture else ()\n result = testdir.runpytest_subprocess(*args)\n result.stdout.fnmatch_lines(\n \"\"\"\n *while capture is disabled*\n \"\"\"\n )\n assert \"captured before\" not in result.stdout.str()\n assert \"captured after\" not in result.stdout.str()\n if no_capture:\n assert \"test_normal executed\" in result.stdout.str()\n else:\n assert \"test_normal executed\" not in result.stdout.str()\n\n @pytest.mark.parametrize(\"fixture\", [\"capsys\", \"capfd\"])\n def test_fixture_use_by_other_fixtures(self, testdir, fixture):\n \"\"\"\n Ensure that capsys and capfd can be used by other fixtures during setup and teardown.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\\\n from __future__ import print_function\n import sys\n import pytest\n\n @pytest.fixture\n def captured_print({fixture}):\n print('stdout contents begin')\n print('stderr contents begin', file=sys.stderr)\n out, err = {fixture}.readouterr()\n\n yield out, err\n\n print('stdout contents end')\n print('stderr contents end', file=sys.stderr)\n out, err = {fixture}.readouterr()\n assert out == 'stdout contents end\\\\n'\n assert err == 'stderr contents end\\\\n'\n\n def test_captured_print(captured_print):\n out, err = captured_print\n assert out == 'stdout contents begin\\\\n'\n assert err == 'stderr contents begin\\\\n'\n \"\"\".format(\n fixture=fixture\n )\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n assert \"stdout contents begin\" not in result.stdout.str()\n assert \"stderr contents begin\" not in result.stdout.str()\n\n @pytest.mark.parametrize(\"cap\", [\"capsys\", \"capfd\"])\n def test_fixture_use_by_other_fixtures_teardown(self, testdir, cap):\n \"\"\"Ensure we can access setup and teardown buffers from teardown when using capsys/capfd (##3033)\"\"\"\n testdir.makepyfile(\n \"\"\"\\\n import sys\n import pytest\n import os\n\n @pytest.fixture()\n def fix({cap}):\n print(\"setup out\")\n sys.stderr.write(\"setup err\\\\n\")\n yield\n out, err = {cap}.readouterr()\n assert out == 'setup out\\\\ncall out\\\\n'\n assert err == 'setup err\\\\ncall err\\\\n'\n\n def test_a(fix):\n print(\"call out\")\n sys.stderr.write(\"call err\\\\n\")\n \"\"\".format(\n cap=cap\n )\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":"null","endLoc":448,"header":"@pytest.mark.parametrize(\"opt\", [[], [\"-s\"]])\n def test_std_functional(self, testdir, opt)","id":4807,"name":"test_std_functional","nodeType":"Function","startLoc":437,"text":"@pytest.mark.parametrize(\"opt\", [[], [\"-s\"]])\n def test_std_functional(self, testdir, opt):\n reprec = testdir.inline_runsource(\n \"\"\"\\\n def test_hello(capsys):\n print(42)\n out, err = capsys.readouterr()\n assert out.startswith(\"42\")\n \"\"\",\n *opt\n )\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":"null","endLoc":507,"header":"def test_xfailure_marker(self, testdir)","id":4808,"name":"test_xfailure_marker","nodeType":"Function","startLoc":491,"text":"def test_xfailure_marker(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(reason=\"42\")\n def test_xfail():\n assert False\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert not result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=1, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_xfailure_marker\", name=\"test_xfail\")\n fnode = tnode.find_first_by_tag(\"skipped\")\n fnode.assert_attr(type=\"pytest.xfail\", message=\"42\")"},{"col":4,"comment":"null","endLoc":468,"header":"def test_capsyscapfd(self, testdir)","id":4809,"name":"test_capsyscapfd","nodeType":"Function","startLoc":450,"text":"def test_capsyscapfd(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n def test_one(capsys, capfd):\n pass\n def test_two(capfd, capsys):\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n \"*ERROR*setup*test_one*\",\n \"E*capfd*capsys*same*time*\",\n \"*ERROR*setup*test_two*\",\n \"E*capsys*capfd*same*time*\",\n \"*2 error*\",\n ]\n )"},{"col":0,"comment":"When using --pyargs, do not emit the warning about non-top-level conftest warnings (#4039, #4044)","endLoc":151,"header":"@pytest.mark.parametrize(\"use_pyargs\", [True, False])\ndef test_pytest_plugins_in_non_top_level_conftest_unsupported_pyargs(\n testdir, use_pyargs\n)","id":4810,"name":"test_pytest_plugins_in_non_top_level_conftest_unsupported_pyargs","nodeType":"Function","startLoc":125,"text":"@pytest.mark.parametrize(\"use_pyargs\", [True, False])\ndef test_pytest_plugins_in_non_top_level_conftest_unsupported_pyargs(\n testdir, use_pyargs\n):\n \"\"\"When using --pyargs, do not emit the warning about non-top-level conftest warnings (#4039, #4044)\"\"\"\n from _pytest.deprecated import PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST\n\n files = {\n \"src/pkg/__init__.py\": \"\",\n \"src/pkg/conftest.py\": \"\",\n \"src/pkg/test_root.py\": \"def test(): pass\",\n \"src/pkg/sub/__init__.py\": \"\",\n \"src/pkg/sub/conftest.py\": \"pytest_plugins=['capture']\",\n \"src/pkg/sub/test_bar.py\": \"def test(): pass\",\n }\n testdir.makepyfile(**files)\n testdir.syspathinsert(testdir.tmpdir.join(\"src\"))\n\n args = (\"--pyargs\", \"pkg\") if use_pyargs else ()\n args += (SHOW_PYTEST_WARNINGS_ARG,)\n res = testdir.runpytest(*args)\n assert res.ret == (0 if use_pyargs else 2)\n msg = str(PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST).splitlines()[0]\n if use_pyargs:\n assert msg not in res.stdout.str()\n else:\n res.stdout.fnmatch_lines([\"*{msg}*\".format(msg=msg)])"},{"col":4,"comment":"Test that asking for \"capfd\" and \"capsys\" using request.getfixturevalue\n in the same test is an error.\n ","endLoc":491,"header":"def test_capturing_getfixturevalue(self, testdir)","id":4811,"name":"test_capturing_getfixturevalue","nodeType":"Function","startLoc":470,"text":"def test_capturing_getfixturevalue(self, testdir):\n \"\"\"Test that asking for \"capfd\" and \"capsys\" using request.getfixturevalue\n in the same test is an error.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\\\n def test_one(capsys, request):\n request.getfixturevalue(\"capfd\")\n def test_two(capfd, request):\n request.getfixturevalue(\"capsys\")\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*test_one*\",\n \"*capsys*capfd*same*time*\",\n \"*test_two*\",\n \"*capfd*capsys*same*time*\",\n \"*2 failed in*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":503,"header":"def test_capsyscapfdbinary(self, testdir)","id":4814,"name":"test_capsyscapfdbinary","nodeType":"Function","startLoc":493,"text":"def test_capsyscapfdbinary(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n def test_one(capsys, capfdbinary):\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\"*ERROR*setup*test_one*\", \"E*capfdbinary*capsys*same*time*\", \"*1 error*\"]\n )"},{"col":4,"comment":"null","endLoc":517,"header":"@pytest.mark.parametrize(\"method\", [\"sys\", \"fd\"])\n def test_capture_is_represented_on_failure_issue128(self, testdir, method)","id":4815,"name":"test_capture_is_represented_on_failure_issue128","nodeType":"Function","startLoc":505,"text":"@pytest.mark.parametrize(\"method\", [\"sys\", \"fd\"])\n def test_capture_is_represented_on_failure_issue128(self, testdir, method):\n p = testdir.makepyfile(\n \"\"\"\\\n def test_hello(cap{}):\n print(\"xxx42xxx\")\n assert 0\n \"\"\".format(\n method\n )\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"xxx42xxx\"])"},{"col":4,"comment":"null","endLoc":520,"header":"def resume_capturing(self)","id":4816,"name":"resume_capturing","nodeType":"Function","startLoc":512,"text":"def resume_capturing(self):\n self._state = \"resumed\"\n if self.out:\n self.out.resume()\n if self.err:\n self.err.resume()\n if hasattr(self, \"_in_suspended\"):\n self.in_.resume()\n del self._in_suspended"},{"col":4,"comment":" Delete attribute ``name`` from ``target``, by default raise\n AttributeError it the attribute did not previously exist.\n\n If no ``name`` is specified and ``target`` is a string\n it will be interpreted as a dotted import path with the\n last part being the attribute name.\n\n If ``raising`` is set to False, no exception will be raised if the\n attribute is missing.\n ","endLoc":205,"header":"def delattr(self, target, name=notset, raising=True)","id":4817,"name":"delattr","nodeType":"Function","startLoc":173,"text":"def delattr(self, target, name=notset, raising=True):\n \"\"\" Delete attribute ``name`` from ``target``, by default raise\n AttributeError it the attribute did not previously exist.\n\n If no ``name`` is specified and ``target`` is a string\n it will be interpreted as a dotted import path with the\n last part being the attribute name.\n\n If ``raising`` is set to False, no exception will be raised if the\n attribute is missing.\n \"\"\"\n __tracebackhide__ = True\n import inspect\n\n if name is notset:\n if not isinstance(target, six.string_types):\n raise TypeError(\n \"use delattr(target, name) or \"\n \"delattr(target) with target being a dotted \"\n \"import string\"\n )\n name, target = derive_importpath(target, raising)\n\n if not hasattr(target, name):\n if raising:\n raise AttributeError(name)\n else:\n oldval = getattr(target, name, notset)\n # Avoid class descriptors like staticmethod/classmethod.\n if inspect.isclass(target):\n oldval = target.__dict__.get(name, notset)\n self._setattr.append((target, name, oldval))\n delattr(target, name)"},{"col":4,"comment":"null","endLoc":526,"header":"def test_xfail_captures_output_once(self, testdir)","id":4818,"name":"test_xfail_captures_output_once","nodeType":"Function","startLoc":509,"text":"def test_xfail_captures_output_once(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n import pytest\n\n @pytest.mark.xfail()\n def test_fail():\n sys.stdout.write('XFAIL This is stdout')\n sys.stderr.write('XFAIL This is stderr')\n assert 0\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n assert len(tnode.find_by_tag(\"system-err\")) == 1\n assert len(tnode.find_by_tag(\"system-out\")) == 1"},{"attributeType":"None","col":4,"comment":"null","endLoc":464,"id":4819,"name":"out","nodeType":"Attribute","startLoc":464,"text":"out"},{"attributeType":"None","col":10,"comment":"null","endLoc":464,"id":4820,"name":"err","nodeType":"Attribute","startLoc":464,"text":"err"},{"attributeType":"None","col":16,"comment":"null","endLoc":464,"id":4821,"name":"in_","nodeType":"Attribute","startLoc":464,"text":"in_"},{"attributeType":"None","col":4,"comment":"null","endLoc":465,"id":4822,"name":"_state","nodeType":"Attribute","startLoc":465,"text":"_state"},{"attributeType":"null","col":12,"comment":"null","endLoc":473,"id":4823,"name":"err","nodeType":"Attribute","startLoc":473,"text":"self.err"},{"attributeType":"str","col":8,"comment":"null","endLoc":485,"id":4824,"name":"_state","nodeType":"Attribute","startLoc":485,"text":"self._state"},{"col":4,"comment":"null","endLoc":531,"header":"@needsosdup\n def test_stdfd_functional(self, testdir)","id":4825,"name":"test_stdfd_functional","nodeType":"Function","startLoc":519,"text":"@needsosdup\n def test_stdfd_functional(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\\\n def test_hello(capfd):\n import os\n os.write(1, \"42\".encode('ascii'))\n out, err = capfd.readouterr()\n assert out.startswith(\"42\")\n capfd.close()\n \"\"\"\n )\n reprec.assertoutcome(passed=1)"},{"attributeType":"bool","col":12,"comment":"null","endLoc":510,"id":4826,"name":"_in_suspended","nodeType":"Attribute","startLoc":510,"text":"self._in_suspended"},{"col":4,"comment":"null","endLoc":546,"header":"@needsosdup\n def test_capfdbinary(self, testdir)","id":4827,"name":"test_capfdbinary","nodeType":"Function","startLoc":533,"text":"@needsosdup\n def test_capfdbinary(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\\\n def test_hello(capfdbinary):\n import os\n # some likely un-decodable bytes\n os.write(1, b'\\\\xfe\\\\x98\\\\x20')\n out, err = capfdbinary.readouterr()\n assert out == b'\\\\xfe\\\\x98\\\\x20'\n assert err == b''\n \"\"\"\n )\n reprec.assertoutcome(passed=1)"},{"attributeType":"null","col":12,"comment":"null","endLoc":469,"id":4828,"name":"in_","nodeType":"Attribute","startLoc":469,"text":"self.in_"},{"attributeType":"null","col":12,"comment":"null","endLoc":471,"id":4829,"name":"out","nodeType":"Attribute","startLoc":471,"text":"self.out"},{"className":"NoCapture","col":0,"comment":"null","endLoc":544,"id":4830,"nodeType":"Class","startLoc":542,"text":"class NoCapture(object):\n EMPTY_BUFFER = None\n __init__ = start = done = suspend = resume = lambda *args: None"},{"attributeType":"None","col":4,"comment":"null","endLoc":543,"id":4831,"name":"EMPTY_BUFFER","nodeType":"Attribute","startLoc":543,"text":"EMPTY_BUFFER"},{"col":0,"comment":"null","endLoc":180,"header":"def test_pytest_plugins_in_non_top_level_conftest_unsupported_no_top_level_conftest(\n testdir\n)","id":4832,"name":"test_pytest_plugins_in_non_top_level_conftest_unsupported_no_top_level_conftest","nodeType":"Function","startLoc":154,"text":"def test_pytest_plugins_in_non_top_level_conftest_unsupported_no_top_level_conftest(\n testdir\n):\n from _pytest.deprecated import PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST\n\n subdirectory = testdir.tmpdir.join(\"subdirectory\")\n subdirectory.mkdir()\n testdir.makeconftest(\n \"\"\"\n pytest_plugins=['capture']\n \"\"\"\n )\n testdir.tmpdir.join(\"conftest.py\").move(subdirectory.join(\"conftest.py\"))\n\n testdir.makepyfile(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n\n res = testdir.runpytest_subprocess()\n assert res.ret == 2\n msg = str(PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST).splitlines()[0]\n res.stdout.fnmatch_lines(\n [\"*{msg}*\".format(msg=msg), \"*subdirectory{sep}conftest.py*\".format(sep=os.sep)]\n )"},{"attributeType":"function","col":4,"comment":"null","endLoc":544,"id":4833,"name":"__init__","nodeType":"Attribute","startLoc":544,"text":"__init__"},{"col":4,"comment":"null","endLoc":563,"header":"@pytest.mark.skipif(\n sys.version_info < (3,), reason=\"only have capsysbinary in python 3\"\n )\n def test_capsysbinary(self, testdir)","id":4834,"name":"test_capsysbinary","nodeType":"Function","startLoc":548,"text":"@pytest.mark.skipif(\n sys.version_info < (3,), reason=\"only have capsysbinary in python 3\"\n )\n def test_capsysbinary(self, testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\\\n def test_hello(capsysbinary):\n import sys\n # some likely un-decodable bytes\n sys.stdout.buffer.write(b'\\\\xfe\\\\x98\\\\x20')\n out, err = capsysbinary.readouterr()\n assert out == b'\\\\xfe\\\\x98\\\\x20'\n assert err == b''\n \"\"\"\n )\n reprec.assertoutcome(passed=1)"},{"attributeType":"function","col":15,"comment":"null","endLoc":544,"id":4835,"name":"start","nodeType":"Attribute","startLoc":544,"text":"start"},{"attributeType":"function","col":23,"comment":"null","endLoc":544,"id":4836,"name":"done","nodeType":"Attribute","startLoc":544,"text":"done"},{"attributeType":"function","col":30,"comment":"null","endLoc":544,"id":4837,"name":"suspend","nodeType":"Attribute","startLoc":544,"text":"suspend"},{"attributeType":"function","col":40,"comment":"null","endLoc":544,"id":4838,"name":"resume","nodeType":"Attribute","startLoc":544,"text":"resume"},{"className":"FDCaptureBinary","col":0,"comment":"Capture IO to/from a given os-level filedescriptor.\n\n snap() produces `bytes`\n ","endLoc":628,"id":4839,"nodeType":"Class","startLoc":547,"text":"class FDCaptureBinary(object):\n \"\"\"Capture IO to/from a given os-level filedescriptor.\n\n snap() produces `bytes`\n \"\"\"\n\n EMPTY_BUFFER = b\"\"\n _state = None\n\n def __init__(self, targetfd, tmpfile=None):\n self.targetfd = targetfd\n try:\n self.targetfd_save = os.dup(self.targetfd)\n except OSError:\n self.start = lambda: None\n self.done = lambda: None\n else:\n if targetfd == 0:\n assert not tmpfile, \"cannot set tmpfile with stdin\"\n tmpfile = open(os.devnull, \"r\")\n self.syscapture = SysCapture(targetfd)\n else:\n if tmpfile is None:\n f = TemporaryFile()\n with f:\n tmpfile = safe_text_dupfile(f, mode=\"wb+\")\n if targetfd in patchsysdict:\n self.syscapture = SysCapture(targetfd, tmpfile)\n else:\n self.syscapture = NoCapture()\n self.tmpfile = tmpfile\n self.tmpfile_fd = tmpfile.fileno()\n\n def __repr__(self):\n return \"\" % (\n self.targetfd,\n getattr(self, \"targetfd_save\", None),\n self._state,\n )\n\n def start(self):\n \"\"\" Start capturing on targetfd using memorized tmpfile. \"\"\"\n try:\n os.fstat(self.targetfd_save)\n except (AttributeError, OSError):\n raise ValueError(\"saved filedescriptor not valid anymore\")\n os.dup2(self.tmpfile_fd, self.targetfd)\n self.syscapture.start()\n self._state = \"started\"\n\n def snap(self):\n self.tmpfile.seek(0)\n res = self.tmpfile.read()\n self.tmpfile.seek(0)\n self.tmpfile.truncate()\n return res\n\n def done(self):\n \"\"\" stop capturing, restore streams, return original capture file,\n seeked to position zero. \"\"\"\n targetfd_save = self.__dict__.pop(\"targetfd_save\")\n os.dup2(targetfd_save, self.targetfd)\n os.close(targetfd_save)\n self.syscapture.done()\n _attempt_to_close_capture_file(self.tmpfile)\n self._state = \"done\"\n\n def suspend(self):\n self.syscapture.suspend()\n os.dup2(self.targetfd_save, self.targetfd)\n self._state = \"suspended\"\n\n def resume(self):\n self.syscapture.resume()\n os.dup2(self.tmpfile_fd, self.targetfd)\n self._state = \"resumed\"\n\n def writeorg(self, data):\n \"\"\" write to original file descriptor. \"\"\"\n if isinstance(data, six.text_type):\n data = data.encode(\"utf8\") # XXX use encoding of original stream\n os.write(self.targetfd_save, data)"},{"col":4,"comment":"null","endLoc":582,"header":"@pytest.mark.skipif(\n sys.version_info >= (3,), reason=\"only have capsysbinary in python 3\"\n )\n def test_capsysbinary_forbidden_in_python2(self, testdir)","id":4840,"name":"test_capsysbinary_forbidden_in_python2","nodeType":"Function","startLoc":565,"text":"@pytest.mark.skipif(\n sys.version_info >= (3,), reason=\"only have capsysbinary in python 3\"\n )\n def test_capsysbinary_forbidden_in_python2(self, testdir):\n testdir.makepyfile(\n \"\"\"\\\n def test_hello(capsysbinary):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*test_hello*\",\n \"*capsysbinary is only supported on Python 3*\",\n \"*1 error in*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":578,"header":"def __init__(self, targetfd, tmpfile=None)","id":4841,"name":"__init__","nodeType":"Function","startLoc":556,"text":"def __init__(self, targetfd, tmpfile=None):\n self.targetfd = targetfd\n try:\n self.targetfd_save = os.dup(self.targetfd)\n except OSError:\n self.start = lambda: None\n self.done = lambda: None\n else:\n if targetfd == 0:\n assert not tmpfile, \"cannot set tmpfile with stdin\"\n tmpfile = open(os.devnull, \"r\")\n self.syscapture = SysCapture(targetfd)\n else:\n if tmpfile is None:\n f = TemporaryFile()\n with f:\n tmpfile = safe_text_dupfile(f, mode=\"wb+\")\n if targetfd in patchsysdict:\n self.syscapture = SysCapture(targetfd, tmpfile)\n else:\n self.syscapture = NoCapture()\n self.tmpfile = tmpfile\n self.tmpfile_fd = tmpfile.fileno()"},{"col":4,"comment":"null","endLoc":542,"header":"def test_xfailure_xpass(self, testdir)","id":4842,"name":"test_xfailure_xpass","nodeType":"Function","startLoc":528,"text":"def test_xfailure_xpass(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail\n def test_xpass():\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n # assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=0, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_xfailure_xpass\", name=\"test_xpass\")"},{"col":4,"comment":"null","endLoc":592,"header":"def test_partial_setup_failure(self, testdir)","id":4843,"name":"test_partial_setup_failure","nodeType":"Function","startLoc":584,"text":"def test_partial_setup_failure(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n def test_hello(capsys, missingarg):\n pass\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*test_partial_setup_failure*\", \"*1 error*\"])"},{"col":4,"comment":"null","endLoc":606,"header":"@needsosdup\n def test_keyboardinterrupt_disables_capturing(self, testdir)","id":4844,"name":"test_keyboardinterrupt_disables_capturing","nodeType":"Function","startLoc":594,"text":"@needsosdup\n def test_keyboardinterrupt_disables_capturing(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\\\n def test_hello(capfd):\n import os\n os.write(1, str(42).encode('ascii'))\n raise KeyboardInterrupt()\n \"\"\"\n )\n result = testdir.runpytest_subprocess(p)\n result.stdout.fnmatch_lines([\"*KeyboardInterrupt*\"])\n assert result.ret == 2"},{"col":25,"endLoc":561,"id":4846,"nodeType":"Lambda","startLoc":561,"text":"lambda: None"},{"col":24,"endLoc":562,"id":4847,"nodeType":"Lambda","startLoc":562,"text":"lambda: None"},{"col":4,"comment":"null","endLoc":560,"header":"def test_xfailure_xpass_strict(self, testdir)","id":4848,"name":"test_xfailure_xpass_strict","nodeType":"Function","startLoc":544,"text":"def test_xfailure_xpass_strict(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(strict=True, reason=\"This needs to fail!\")\n def test_xpass():\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n # assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(skipped=0, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(classname=\"test_xfailure_xpass_strict\", name=\"test_xpass\")\n fnode = tnode.find_first_by_tag(\"failure\")\n fnode.assert_attr(message=\"[XPASS(strict)] This needs to fail!\")"},{"col":4,"comment":"#14","endLoc":618,"header":"def test_capture_and_logging(self, testdir)","id":4849,"name":"test_capture_and_logging","nodeType":"Function","startLoc":608,"text":"def test_capture_and_logging(self, testdir):\n \"\"\"#14\"\"\"\n p = testdir.makepyfile(\n \"\"\"\\\n import logging\n def test_log(capsys):\n logging.error('x')\n \"\"\"\n )\n result = testdir.runpytest_subprocess(p)\n assert \"closed\" not in result.stderr.str()"},{"col":4,"comment":"null","endLoc":650,"header":"@pytest.mark.parametrize(\"fixture\", [\"capsys\", \"capfd\"])\n @pytest.mark.parametrize(\"no_capture\", [True, False])\n def test_disabled_capture_fixture(self, testdir, fixture, no_capture)","id":4850,"name":"test_disabled_capture_fixture","nodeType":"Function","startLoc":620,"text":"@pytest.mark.parametrize(\"fixture\", [\"capsys\", \"capfd\"])\n @pytest.mark.parametrize(\"no_capture\", [True, False])\n def test_disabled_capture_fixture(self, testdir, fixture, no_capture):\n testdir.makepyfile(\n \"\"\"\\\n def test_disabled({fixture}):\n print('captured before')\n with {fixture}.disabled():\n print('while capture is disabled')\n print('captured after')\n assert {fixture}.readouterr() == ('captured before\\\\ncaptured after\\\\n', '')\n\n def test_normal():\n print('test_normal executed')\n \"\"\".format(\n fixture=fixture\n )\n )\n args = (\"-s\",) if no_capture else ()\n result = testdir.runpytest_subprocess(*args)\n result.stdout.fnmatch_lines(\n \"\"\"\n *while capture is disabled*\n \"\"\"\n )\n assert \"captured before\" not in result.stdout.str()\n assert \"captured after\" not in result.stdout.str()\n if no_capture:\n assert \"test_normal executed\" in result.stdout.str()\n else:\n assert \"test_normal executed\" not in result.stdout.str()"},{"col":0,"comment":"null","endLoc":213,"header":"def test_pytest_plugins_in_non_top_level_conftest_unsupported_no_false_positives(\n testdir\n)","id":4851,"name":"test_pytest_plugins_in_non_top_level_conftest_unsupported_no_false_positives","nodeType":"Function","startLoc":183,"text":"def test_pytest_plugins_in_non_top_level_conftest_unsupported_no_false_positives(\n testdir\n):\n from _pytest.deprecated import PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST\n\n subdirectory = testdir.tmpdir.join(\"subdirectory\")\n subdirectory.mkdir()\n testdir.makeconftest(\n \"\"\"\n pass\n \"\"\"\n )\n testdir.tmpdir.join(\"conftest.py\").move(subdirectory.join(\"conftest.py\"))\n\n testdir.makeconftest(\n \"\"\"\n import warnings\n warnings.filterwarnings('always', category=DeprecationWarning)\n pytest_plugins=['capture']\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n res = testdir.runpytest_subprocess()\n assert res.ret == 0\n msg = str(PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST).splitlines()[0]\n assert msg not in res.stdout.str()"},{"col":4,"comment":"null","endLoc":571,"header":"def test_collect_error(self, testdir)","id":4852,"name":"test_collect_error","nodeType":"Function","startLoc":562,"text":"def test_collect_error(self, testdir):\n testdir.makepyfile(\"syntax error\")\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(errors=1, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n fnode = tnode.find_first_by_tag(\"error\")\n fnode.assert_attr(message=\"collection failure\")\n assert \"SyntaxError\" in fnode.toxml()"},{"col":4,"comment":" Set dictionary entry ``name`` to value. ","endLoc":210,"header":"def setitem(self, dic, name, value)","id":4853,"name":"setitem","nodeType":"Function","startLoc":207,"text":"def setitem(self, dic, name, value):\n \"\"\" Set dictionary entry ``name`` to value. \"\"\"\n self._setitem.append((dic, name, dic.get(name, notset)))\n dic[name] = value"},{"col":0,"comment":"null","endLoc":223,"header":"def test_fixture_named_request(testdir)","id":4854,"name":"test_fixture_named_request","nodeType":"Function","startLoc":216,"text":"def test_fixture_named_request(testdir):\n testdir.copy_example()\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*'request' is a reserved name for fixtures and will raise an error in future versions\"\n ]\n )"},{"col":4,"comment":"\n Ensure that capsys and capfd can be used by other fixtures during setup and teardown.\n ","endLoc":688,"header":"@pytest.mark.parametrize(\"fixture\", [\"capsys\", \"capfd\"])\n def test_fixture_use_by_other_fixtures(self, testdir, fixture)","id":4855,"name":"test_fixture_use_by_other_fixtures","nodeType":"Function","startLoc":652,"text":"@pytest.mark.parametrize(\"fixture\", [\"capsys\", \"capfd\"])\n def test_fixture_use_by_other_fixtures(self, testdir, fixture):\n \"\"\"\n Ensure that capsys and capfd can be used by other fixtures during setup and teardown.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\\\n from __future__ import print_function\n import sys\n import pytest\n\n @pytest.fixture\n def captured_print({fixture}):\n print('stdout contents begin')\n print('stderr contents begin', file=sys.stderr)\n out, err = {fixture}.readouterr()\n\n yield out, err\n\n print('stdout contents end')\n print('stderr contents end', file=sys.stderr)\n out, err = {fixture}.readouterr()\n assert out == 'stdout contents end\\\\n'\n assert err == 'stderr contents end\\\\n'\n\n def test_captured_print(captured_print):\n out, err = captured_print\n assert out == 'stdout contents begin\\\\n'\n assert err == 'stderr contents begin\\\\n'\n \"\"\".format(\n fixture=fixture\n )\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n assert \"stdout contents begin\" not in result.stdout.str()\n assert \"stderr contents begin\" not in result.stdout.str()"},{"col":0,"comment":"null","endLoc":231,"header":"def test_pytest_warns_unknown_kwargs()","id":4856,"name":"test_pytest_warns_unknown_kwargs","nodeType":"Function","startLoc":226,"text":"def test_pytest_warns_unknown_kwargs():\n with pytest.warns(\n PytestDeprecationWarning,\n match=r\"pytest.warns\\(\\) got unexpected keyword arguments: \\['foo'\\]\",\n ):\n pytest.warns(UserWarning, foo=\"hello\")"},{"attributeType":"null","col":0,"comment":"null","endLoc":12,"id":4857,"name":"pytestmark","nodeType":"Attribute","startLoc":12,"text":"pytestmark"},{"col":0,"comment":"","endLoc":2,"header":"deprecated_test.py#","id":4858,"name":"","nodeType":"Function","startLoc":2,"text":"pytestmark = pytest.mark.pytester_example_path(\"deprecated\")"},{"col":4,"comment":"null","endLoc":179,"header":"@pytest.mark.parametrize(\n \"fname\",\n (\n \"activate\",\n \"activate.csh\",\n \"activate.fish\",\n \"Activate\",\n \"Activate.bat\",\n \"Activate.ps1\",\n ),\n )\n def test_ignored_virtualenvs_norecursedirs_precedence(self, testdir, fname)","id":4859,"name":"test_ignored_virtualenvs_norecursedirs_precedence","nodeType":"Function","startLoc":158,"text":"@pytest.mark.parametrize(\n \"fname\",\n (\n \"activate\",\n \"activate.csh\",\n \"activate.fish\",\n \"Activate\",\n \"Activate.bat\",\n \"Activate.ps1\",\n ),\n )\n def test_ignored_virtualenvs_norecursedirs_precedence(self, testdir, fname):\n bindir = \"Scripts\" if sys.platform.startswith(\"win\") else \"bin\"\n # norecursedirs takes priority\n testdir.tmpdir.ensure(\".virtual\", bindir, fname)\n testfile = testdir.tmpdir.ensure(\".virtual\", \"test_invenv.py\")\n testfile.write(\"def test_hello(): pass\")\n result = testdir.runpytest(\"--collect-in-virtualenv\")\n assert \"test_invenv\" not in result.stdout.str()\n # ...unless the virtualenv is explicitly given on the CLI\n result = testdir.runpytest(\"--collect-in-virtualenv\", \".virtual\")\n assert \"test_invenv\" in result.stdout.str()"},{"col":4,"comment":" Delete ``name`` from dict. Raise KeyError if it doesn't exist.\n\n If ``raising`` is set to False, no exception will be raised if the\n key is missing.\n ","endLoc":223,"header":"def delitem(self, dic, name, raising=True)","id":4860,"name":"delitem","nodeType":"Function","startLoc":212,"text":"def delitem(self, dic, name, raising=True):\n \"\"\" Delete ``name`` from dict. Raise KeyError if it doesn't exist.\n\n If ``raising`` is set to False, no exception will be raised if the\n key is missing.\n \"\"\"\n if name not in dic:\n if raising:\n raise KeyError(name)\n else:\n self._setitem.append((dic, name, dic.get(name, notset)))\n del dic[name]"},{"id":4861,"name":"pythoncollection.rst","nodeType":"TextFile","path":"doc/en/example","text":"Changing standard (Python) test discovery\n===============================================\n\nIgnore paths during test collection\n-----------------------------------\n\nYou can easily ignore certain test directories and modules during collection\nby passing the ``--ignore=path`` option on the cli. ``pytest`` allows multiple\n``--ignore`` options. Example:\n\n.. code-block:: text\n\n tests/\n |-- example\n | |-- test_example_01.py\n | |-- test_example_02.py\n | '-- test_example_03.py\n |-- foobar\n | |-- test_foobar_01.py\n | |-- test_foobar_02.py\n | '-- test_foobar_03.py\n '-- hello\n '-- world\n |-- test_world_01.py\n |-- test_world_02.py\n '-- test_world_03.py\n\nNow if you invoke ``pytest`` with ``--ignore=tests/foobar/test_foobar_03.py --ignore=tests/hello/``,\nyou will see that ``pytest`` only collects test-modules, which do not match the patterns specified:\n\n.. code-block:: pytest\n\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n rootdir: $REGENDOC_TMPDIR, inifile:\n collected 5 items\n\n tests/example/test_example_01.py . [ 20%]\n tests/example/test_example_02.py . [ 40%]\n tests/example/test_example_03.py . [ 60%]\n tests/foobar/test_foobar_01.py . [ 80%]\n tests/foobar/test_foobar_02.py . [100%]\n\n ========================= 5 passed in 0.02 seconds =========================\n\nThe ``--ignore-glob`` option allows to ignore test file paths based on Unix shell-style wildcards.\nIf you want to exclude test-modules that end with ``_01.py``, execute ``pytest`` with ``--ignore-glob='*_01.py'``.\n\nDeselect tests during test collection\n-------------------------------------\n\nTests can individually be deselected during collection by passing the ``--deselect=item`` option.\nFor example, say ``tests/foobar/test_foobar_01.py`` contains ``test_a`` and ``test_b``.\nYou can run all of the tests within ``tests/`` *except* for ``tests/foobar/test_foobar_01.py::test_a``\nby invoking ``pytest`` with ``--deselect tests/foobar/test_foobar_01.py::test_a``.\n``pytest`` allows multiple ``--deselect`` options.\n\nKeeping duplicate paths specified from command line\n----------------------------------------------------\n\nDefault behavior of ``pytest`` is to ignore duplicate paths specified from the command line.\nExample:\n\n.. code-block:: pytest\n\n pytest path_a path_a\n\n ...\n collected 1 item\n ...\n\nJust collect tests once.\n\nTo collect duplicate tests, use the ``--keep-duplicates`` option on the cli.\nExample:\n\n.. code-block:: pytest\n\n pytest --keep-duplicates path_a path_a\n\n ...\n collected 2 items\n ...\n\nAs the collector just works on directories, if you specify twice a single test file, ``pytest`` will\nstill collect it twice, no matter if the ``--keep-duplicates`` is not specified.\nExample:\n\n.. code-block:: pytest\n\n pytest test_a.py test_a.py\n\n ...\n collected 2 items\n ...\n\n\nChanging directory recursion\n-----------------------------------------------------\n\nYou can set the :confval:`norecursedirs` option in an ini-file, for example your ``pytest.ini`` in the project root directory:\n\n.. code-block:: ini\n\n # content of pytest.ini\n [pytest]\n norecursedirs = .svn _build tmp*\n\nThis would tell ``pytest`` to not recurse into typical subversion or sphinx-build directories or into any ``tmp`` prefixed directory.\n\n.. _`change naming conventions`:\n\nChanging naming conventions\n-----------------------------------------------------\n\nYou can configure different naming conventions by setting\nthe :confval:`python_files`, :confval:`python_classes` and\n:confval:`python_functions` configuration options.\nHere is an example:\n\n.. code-block:: ini\n\n # content of pytest.ini\n # Example 1: have pytest look for \"check\" instead of \"test\"\n # can also be defined in tox.ini or setup.cfg file, although the section\n # name in setup.cfg files should be \"tool:pytest\"\n [pytest]\n python_files = check_*.py\n python_classes = Check\n python_functions = *_check\n\nThis would make ``pytest`` look for tests in files that match the ``check_*\n.py`` glob-pattern, ``Check`` prefixes in classes, and functions and methods\nthat match ``*_check``. For example, if we have::\n\n # content of check_myapp.py\n class CheckMyApp(object):\n def simple_check(self):\n pass\n def complex_check(self):\n pass\n\nThe test collection would look like this:\n\n.. code-block:: pytest\n\n $ pytest --collect-only\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR, inifile: pytest.ini\n collected 2 items\n \n \n \n \n\n ======================= no tests ran in 0.12 seconds =======================\n\nYou can check for multiple glob patterns by adding a space between the patterns:\n\n.. code-block:: ini\n\n # Example 2: have pytest look for files with \"test\" and \"example\"\n # content of pytest.ini, tox.ini, or setup.cfg file (replace \"pytest\"\n # with \"tool:pytest\" for setup.cfg)\n [pytest]\n python_files = test_*.py example_*.py\n\n.. note::\n\n the ``python_functions`` and ``python_classes`` options has no effect\n for ``unittest.TestCase`` test discovery because pytest delegates\n discovery of test case methods to unittest code.\n\nInterpreting cmdline arguments as Python packages\n-----------------------------------------------------\n\nYou can use the ``--pyargs`` option to make ``pytest`` try\ninterpreting arguments as python package names, deriving\ntheir file system path and then running the test. For\nexample if you have unittest2 installed you can type:\n\n.. code-block:: bash\n\n pytest --pyargs unittest2.test.test_skipping -q\n\nwhich would run the respective test module. Like with\nother options, through an ini-file and the :confval:`addopts` option you\ncan make this change more permanently:\n\n.. code-block:: ini\n\n # content of pytest.ini\n [pytest]\n addopts = --pyargs\n\nNow a simple invocation of ``pytest NAME`` will check\nif NAME exists as an importable package/module and otherwise\ntreat it as a filesystem path.\n\nFinding out what is collected\n-----------------------------------------------\n\nYou can always peek at the collection tree without running tests like this:\n\n.. code-block:: pytest\n\n . $ pytest --collect-only pythoncollection.py\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR, inifile: pytest.ini\n collected 3 items\n \n \n \n \n \n\n ======================= no tests ran in 0.12 seconds =======================\n\n.. _customizing-test-collection:\n\nCustomizing test collection\n---------------------------\n\n.. regendoc:wipe\n\nYou can easily instruct ``pytest`` to discover tests from every Python file:\n\n.. code-block:: ini\n\n # content of pytest.ini\n [pytest]\n python_files = *.py\n\nHowever, many projects will have a ``setup.py`` which they don't want to be\nimported. Moreover, there may files only importable by a specific python\nversion. For such cases you can dynamically define files to be ignored by\nlisting them in a ``conftest.py`` file::\n\n # content of conftest.py\n import sys\n\n collect_ignore = [\"setup.py\"]\n if sys.version_info[0] > 2:\n collect_ignore.append(\"pkg/module_py2.py\")\n\nand then if you have a module file like this::\n\n # content of pkg/module_py2.py\n def test_only_on_python2():\n try:\n assert 0\n except Exception, e:\n pass\n\nand a ``setup.py`` dummy file like this::\n\n # content of setup.py\n 0/0 # will raise exception if imported\n\nIf you run with a Python 2 interpreter then you will find the one test and will\nleave out the ``setup.py`` file:\n\n.. code-block:: pytest\n\n #$ pytest --collect-only\n ====== test session starts ======\n platform linux2 -- Python 2.7.10, pytest-2.9.1, py-1.4.31, pluggy-0.3.1\n rootdir: $REGENDOC_TMPDIR, inifile: pytest.ini\n collected 1 items\n \n \n\n ====== no tests ran in 0.04 seconds ======\n\nIf you run with a Python 3 interpreter both the one test and the ``setup.py``\nfile will be left out:\n\n.. code-block:: pytest\n\n $ pytest --collect-only\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR, inifile: pytest.ini\n collected 0 items\n\n ======================= no tests ran in 0.12 seconds =======================\n\nIt's also possible to ignore files based on Unix shell-style wildcards by adding\npatterns to ``collect_ignore_glob``.\n\nThe following example ``conftest.py`` ignores the file ``setup.py`` and in\naddition all files that end with ``*_py2.py`` when executed with a Python 3\ninterpreter::\n\n # content of conftest.py\n import sys\n\n collect_ignore = [\"setup.py\"]\n if sys.version_info[0] > 2:\n collect_ignore_glob = [\"*_py2.py\"]\n"},{"id":4862,"name":"release-2.5.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.5.0: now down to ZERO reported bugs!\n===========================================================================\n\npytest-2.5.0 is a big fixing release, the result of two community bug\nfixing days plus numerous additional works from many people and\nreporters. The release should be fully compatible to 2.4.2, existing\nplugins and test suites. We aim at maintaining this level of ZERO reported\nbugs because it's no fun if your testing tool has bugs, is it? Under a\ncondition, though: when submitting a bug report please provide\nclear information about the circumstances and a simple example which\nreproduces the problem.\n\nThe issue tracker is of course not empty now. We have many remaining\n\"enhacement\" issues which we'll hopefully can tackle in 2014 with your\nhelp.\n\nFor those who use older Python versions, please note that pytest is not\nautomatically tested on python2.5 due to virtualenv, setuptools and tox\nnot supporting it anymore. Manual verification shows that it mostly\nworks fine but it's not going to be part of the automated release\nprocess and thus likely to break in the future.\n\nAs usual, current docs are at\n\n http://pytest.org\n\nand you can upgrade from pypi via::\n\n pip install -U pytest\n\nParticular thanks for helping with this release go to Anatoly Bubenkoff,\nFloris Bruynooghe, Marc Abramowitz, Ralph Schmitt, Ronny Pfannschmidt,\nDonald Stufft, James Lan, Rob Dennis, Jason R. Coombs, Mathieu Agopian,\nVirgil Dupras, Bruno Oliveira, Alex Gaynor and others.\n\nhave fun,\nholger krekel\n\n\n2.5.0\n-----------------------------------\n\n- dropped python2.5 from automated release testing of pytest itself\n which means it's probably going to break soon (but still works\n with this release we believe).\n\n- simplified and fixed implementation for calling finalizers when\n parametrized fixtures or function arguments are involved. finalization\n is now performed lazily at setup time instead of in the \"teardown phase\".\n While this might sound odd at first, it helps to ensure that we are\n correctly handling setup/teardown even in complex code. User-level code\n should not be affected unless it's implementing the pytest_runtest_teardown\n hook and expecting certain fixture instances are torn down within (very\n unlikely and would have been unreliable anyway).\n\n- PR90: add --color=yes|no|auto option to force terminal coloring\n mode (\"auto\" is default). Thanks Marc Abramowitz.\n\n- fix issue319 - correctly show unicode in assertion errors. Many\n thanks to Floris Bruynooghe for the complete PR. Also means\n we depend on py>=1.4.19 now.\n\n- fix issue396 - correctly sort and finalize class-scoped parametrized\n tests independently from number of methods on the class.\n\n- refix issue323 in a better way -- parametrization should now never\n cause Runtime Recursion errors because the underlying algorithm\n for re-ordering tests per-scope/per-fixture is not recursive\n anymore (it was tail-call recursive before which could lead\n to problems for more than >966 non-function scoped parameters).\n\n- fix issue290 - there is preliminary support now for parametrizing\n with repeated same values (sometimes useful to test if calling\n a second time works as with the first time).\n\n- close issue240 - document precisely how pytest module importing\n works, discuss the two common test directory layouts, and how it\n interacts with PEP420-namespace packages.\n\n- fix issue246 fix finalizer order to be LIFO on independent fixtures\n depending on a parametrized higher-than-function scoped fixture.\n (was quite some effort so please bear with the complexity of this sentence :)\n Thanks Ralph Schmitt for the precise failure example.\n\n- fix issue244 by implementing special index for parameters to only use\n indices for paramentrized test ids\n\n- fix issue287 by running all finalizers but saving the exception\n from the first failing finalizer and re-raising it so teardown will\n still have failed. We reraise the first failing exception because\n it might be the cause for other finalizers to fail.\n\n- fix ordering when mock.patch or other standard decorator-wrappings\n are used with test methods. This fixues issue346 and should\n help with random \"xdist\" collection failures. Thanks to\n Ronny Pfannschmidt and Donald Stufft for helping to isolate it.\n\n- fix issue357 - special case \"-k\" expressions to allow for\n filtering with simple strings that are not valid python expressions.\n Examples: \"-k 1.3\" matches all tests parametrized with 1.3.\n \"-k None\" filters all tests that have \"None\" in their name\n and conversely \"-k 'not None'\".\n Previously these examples would raise syntax errors.\n\n- fix issue384 by removing the trial support code\n since the unittest compat enhancements allow\n trial to handle it on its own\n\n- don't hide an ImportError when importing a plugin produces one.\n fixes issue375.\n\n- fix issue275 - allow usefixtures and autouse fixtures\n for running doctest text files.\n\n- fix issue380 by making --resultlog only rely on longrepr instead\n of the \"reprcrash\" attribute which only exists sometimes.\n\n- address issue122: allow @pytest.fixture(params=iterator) by exploding\n into a list early on.\n\n- fix pexpect-3.0 compatibility for pytest's own tests.\n (fixes issue386)\n\n- allow nested parametrize-value markers, thanks James Lan for the PR.\n\n- fix unicode handling with new monkeypatch.setattr(import_path, value)\n API. Thanks Rob Dennis. Fixes issue371.\n\n- fix unicode handling with junitxml, fixes issue368.\n\n- In assertion rewriting mode on Python 2, fix the detection of coding\n cookies. See issue #330.\n\n- make \"--runxfail\" turn imperative pytest.xfail calls into no ops\n (it already did neutralize pytest.mark.xfail markers)\n\n- refine pytest / pkg_resources interactions: The AssertionRewritingHook\n PEP302 compliant loader now registers itself with setuptools/pkg_resources\n properly so that the pkg_resources.resource_stream method works properly.\n Fixes issue366. Thanks for the investigations and full PR to Jason R. Coombs.\n\n- pytestconfig fixture is now session-scoped as it is the same object during the\n whole test run. Fixes issue370.\n\n- avoid one surprising case of marker malfunction/confusion::\n\n @pytest.mark.some(lambda arg: ...)\n def test_function():\n\n would not work correctly because pytest assumes @pytest.mark.some\n gets a function to be decorated already. We now at least detect if this\n arg is a lambda and thus the example will work. Thanks Alex Gaynor\n for bringing it up.\n\n- xfail a test on pypy that checks wrong encoding/ascii (pypy does\n not error out). fixes issue385.\n\n- internally make varnames() deal with classes's __init__,\n although it's not needed by pytest itself atm. Also\n fix caching. Fixes issue376.\n\n- fix issue221 - handle importing of namespace-package with no\n __init__.py properly.\n\n- refactor internal FixtureRequest handling to avoid monkeypatching.\n One of the positive user-facing effects is that the \"request\" object\n can now be used in closures.\n\n- fixed version comparison in pytest.importskip(modname, minverstring)\n\n- fix issue377 by clarifying in the nose-compat docs that pytest\n does not duplicate the unittest-API into the \"plain\" namespace.\n\n- fix verbose reporting for @mock'd test functions\n"},{"col":4,"comment":"null","endLoc":661,"header":"def __init__(self, fd, tmpfile=None)","id":4863,"name":"__init__","nodeType":"Function","startLoc":652,"text":"def __init__(self, fd, tmpfile=None):\n name = patchsysdict[fd]\n self._old = getattr(sys, name)\n self.name = name\n if tmpfile is None:\n if name == \"stdin\":\n tmpfile = DontReadFromInput()\n else:\n tmpfile = CaptureIO()\n self.tmpfile = tmpfile"},{"col":4,"comment":"On Python 2, warn if the given environment variable name is not a native str (#4056)","endLoc":232,"header":"def _warn_if_env_name_is_not_str(self, name)","id":4864,"name":"_warn_if_env_name_is_not_str","nodeType":"Function","startLoc":225,"text":"def _warn_if_env_name_is_not_str(self, name):\n \"\"\"On Python 2, warn if the given environment variable name is not a native str (#4056)\"\"\"\n if six.PY2 and not isinstance(name, str):\n warnings.warn(\n pytest.PytestWarning(\n \"Environment variable name {!r} should be str\".format(name)\n )\n )"},{"col":4,"comment":"Directly test the virtual env detection function","endLoc":200,"header":"@pytest.mark.parametrize(\n \"fname\",\n (\n \"activate\",\n \"activate.csh\",\n \"activate.fish\",\n \"Activate\",\n \"Activate.bat\",\n \"Activate.ps1\",\n ),\n )\n def test__in_venv(self, testdir, fname)","id":4865,"name":"test__in_venv","nodeType":"Function","startLoc":181,"text":"@pytest.mark.parametrize(\n \"fname\",\n (\n \"activate\",\n \"activate.csh\",\n \"activate.fish\",\n \"Activate\",\n \"Activate.bat\",\n \"Activate.ps1\",\n ),\n )\n def test__in_venv(self, testdir, fname):\n \"\"\"Directly test the virtual env detection function\"\"\"\n bindir = \"Scripts\" if sys.platform.startswith(\"win\") else \"bin\"\n # no bin/activate, not a virtualenv\n base_path = testdir.tmpdir.mkdir(\"venv\")\n assert _in_venv(base_path) is False\n # with bin/activate, totally a virtualenv\n base_path.ensure(bindir, fname)\n assert _in_venv(base_path) is True"},{"col":4,"comment":"Return the width of current line, using the superior implementation of py-1.6 when available","endLoc":496,"header":"@property\n def _width_of_current_line(self)","id":4866,"name":"_width_of_current_line","nodeType":"Function","startLoc":489,"text":"@property\n def _width_of_current_line(self):\n \"\"\"Return the width of current line, using the superior implementation of py-1.6 when available\"\"\"\n try:\n return self._tw.width_of_current_line\n except AttributeError:\n # py < 1.6.0\n return self._tw.chars_on_current_line"},{"col":4,"comment":"null","endLoc":504,"header":"def pytest_collection(self)","id":4867,"name":"pytest_collection","nodeType":"Function","startLoc":498,"text":"def pytest_collection(self):\n if self.isatty:\n if self.config.option.verbose >= 0:\n self.write(\"collecting ... \", bold=True)\n self._collect_report_last_write = time.time()\n elif self.config.option.verbose >= 1:\n self.write(\"collecting ... \", bold=True)"},{"col":4,"comment":"null","endLoc":589,"header":"def test_unicode(self, testdir)","id":4868,"name":"test_unicode","nodeType":"Function","startLoc":573,"text":"def test_unicode(self, testdir):\n value = \"hx\\xc4\\x85\\xc4\\x87\\n\"\n testdir.makepyfile(\n \"\"\"\n # coding: latin1\n def test_hello():\n print(%r)\n assert 0\n \"\"\"\n % value\n )\n result, dom = runandparse(testdir)\n assert result.ret == 1\n tnode = dom.find_first_by_tag(\"testcase\")\n fnode = tnode.find_first_by_tag(\"failure\")\n if not sys.platform.startswith(\"java\"):\n assert \"hx\" in fnode.toxml()"},{"col":4,"comment":"null","endLoc":216,"header":"def test_custom_norecursedirs(self, testdir)","id":4869,"name":"test_custom_norecursedirs","nodeType":"Function","startLoc":202,"text":"def test_custom_norecursedirs(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n norecursedirs = mydir xyz*\n \"\"\"\n )\n tmpdir = testdir.tmpdir\n tmpdir.ensure(\"mydir\", \"test_hello.py\").write(\"def test_1(): pass\")\n tmpdir.ensure(\"xyz123\", \"test_2.py\").write(\"def test_2(): 0/0\")\n tmpdir.ensure(\"xy\", \"test_ok.py\").write(\"def test_3(): pass\")\n rec = testdir.inline_run()\n rec.assertoutcome(passed=1)\n rec = testdir.inline_run(\"xyz123/test_2.py\")\n rec.assertoutcome(failed=1)"},{"col":4,"comment":"null","endLoc":246,"header":"def test_testpaths_ini(self, testdir, monkeypatch)","id":4870,"name":"test_testpaths_ini","nodeType":"Function","startLoc":218,"text":"def test_testpaths_ini(self, testdir, monkeypatch):\n testdir.makeini(\n \"\"\"\n [pytest]\n testpaths = gui uts\n \"\"\"\n )\n tmpdir = testdir.tmpdir\n tmpdir.ensure(\"env\", \"test_1.py\").write(\"def test_env(): pass\")\n tmpdir.ensure(\"gui\", \"test_2.py\").write(\"def test_gui(): pass\")\n tmpdir.ensure(\"uts\", \"test_3.py\").write(\"def test_uts(): pass\")\n\n # executing from rootdir only tests from `testpaths` directories\n # are collected\n items, reprec = testdir.inline_genitems(\"-v\")\n assert [x.name for x in items] == [\"test_gui\", \"test_uts\"]\n\n # check that explicitly passing directories in the command-line\n # collects the tests\n for dirname in (\"env\", \"gui\", \"uts\"):\n items, reprec = testdir.inline_genitems(tmpdir.join(dirname))\n assert [x.name for x in items] == [\"test_%s\" % dirname]\n\n # changing cwd to each subdirectory and running pytest without\n # arguments collects the tests in that directory normally\n for dirname in (\"env\", \"gui\", \"uts\"):\n monkeypatch.chdir(testdir.tmpdir.join(dirname))\n items, reprec = testdir.inline_genitems()\n assert [x.name for x in items] == [\"test_%s\" % dirname]"},{"col":4,"comment":"Ensure we can access setup and teardown buffers from teardown when using capsys/capfd (##3033)","endLoc":716,"header":"@pytest.mark.parametrize(\"cap\", [\"capsys\", \"capfd\"])\n def test_fixture_use_by_other_fixtures_teardown(self, testdir, cap)","id":4871,"name":"test_fixture_use_by_other_fixtures_teardown","nodeType":"Function","startLoc":690,"text":"@pytest.mark.parametrize(\"cap\", [\"capsys\", \"capfd\"])\n def test_fixture_use_by_other_fixtures_teardown(self, testdir, cap):\n \"\"\"Ensure we can access setup and teardown buffers from teardown when using capsys/capfd (##3033)\"\"\"\n testdir.makepyfile(\n \"\"\"\\\n import sys\n import pytest\n import os\n\n @pytest.fixture()\n def fix({cap}):\n print(\"setup out\")\n sys.stderr.write(\"setup err\\\\n\")\n yield\n out, err = {cap}.readouterr()\n assert out == 'setup out\\\\ncall out\\\\n'\n assert err == 'setup err\\\\ncall err\\\\n'\n\n def test_a(fix):\n print(\"call out\")\n sys.stderr.write(\"call err\\\\n\")\n \"\"\".format(\n cap=cap\n )\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":"null","endLoc":514,"header":"def pytest_collectreport(self, report)","id":4872,"name":"pytest_collectreport","nodeType":"Function","startLoc":506,"text":"def pytest_collectreport(self, report):\n if report.failed:\n self.stats.setdefault(\"error\", []).append(report)\n elif report.skipped:\n self.stats.setdefault(\"skipped\", []).append(report)\n items = [x for x in report.result if isinstance(x, pytest.Item)]\n self._numcollected += len(items)\n if self.isatty:\n self.report_collect()"},{"className":"TestCaptureIO","col":0,"comment":"null","endLoc":863,"id":4873,"nodeType":"Class","startLoc":836,"text":"class TestCaptureIO(object):\n def test_text(self):\n f = capture.CaptureIO()\n f.write(\"hello\")\n s = f.getvalue()\n assert s == \"hello\"\n f.close()\n\n def test_unicode_and_str_mixture(self):\n f = capture.CaptureIO()\n if sys.version_info >= (3, 0):\n f.write(\"\\u00f6\")\n pytest.raises(TypeError, f.write, b\"hello\")\n else:\n f.write(u\"\\u00f6\")\n f.write(b\"hello\")\n s = f.getvalue()\n f.close()\n assert isinstance(s, text_type)\n\n @pytest.mark.skipif(sys.version_info[0] == 2, reason=\"python 3 only behaviour\")\n def test_write_bytes_to_buffer(self):\n \"\"\"In python3, stdout / stderr are text io wrappers (exposing a buffer\n property of the underlying bytestream). See issue #1407\n \"\"\"\n f = capture.CaptureIO()\n f.buffer.write(b\"foo\\r\\n\")\n assert f.getvalue() == \"foo\\r\\n\""},{"col":4,"comment":"null","endLoc":842,"header":"def test_text(self)","id":4874,"name":"test_text","nodeType":"Function","startLoc":837,"text":"def test_text(self):\n f = capture.CaptureIO()\n f.write(\"hello\")\n s = f.getvalue()\n assert s == \"hello\"\n f.close()"},{"className":"TestCollectPluginHookRelay","col":0,"comment":"null","endLoc":275,"id":4875,"nodeType":"Class","startLoc":249,"text":"class TestCollectPluginHookRelay(object):\n def test_pytest_collect_file(self, testdir):\n wascalled = []\n\n class Plugin(object):\n def pytest_collect_file(self, path, parent):\n if not path.basename.startswith(\".\"):\n # Ignore hidden files, e.g. .testmondata.\n wascalled.append(path)\n\n testdir.makefile(\".abc\", \"xyz\")\n pytest.main([testdir.tmpdir], plugins=[Plugin()])\n assert len(wascalled) == 1\n assert wascalled[0].ext == \".abc\"\n\n def test_pytest_collect_directory(self, testdir):\n wascalled = []\n\n class Plugin(object):\n def pytest_collect_directory(self, path, parent):\n wascalled.append(path.basename)\n\n testdir.mkdir(\"hello\")\n testdir.mkdir(\"world\")\n pytest.main(testdir.tmpdir, plugins=[Plugin()])\n assert \"hello\" in wascalled\n assert \"world\" in wascalled"},{"col":4,"comment":"null","endLoc":262,"header":"def test_pytest_collect_file(self, testdir)","id":4876,"name":"test_pytest_collect_file","nodeType":"Function","startLoc":250,"text":"def test_pytest_collect_file(self, testdir):\n wascalled = []\n\n class Plugin(object):\n def pytest_collect_file(self, path, parent):\n if not path.basename.startswith(\".\"):\n # Ignore hidden files, e.g. .testmondata.\n wascalled.append(path)\n\n testdir.makefile(\".abc\", \"xyz\")\n pytest.main([testdir.tmpdir], plugins=[Plugin()])\n assert len(wascalled) == 1\n assert wascalled[0].ext == \".abc\""},{"col":4,"comment":"this test did fail when the escaping wasnt strict","endLoc":604,"header":"def test_assertion_binchars(self, testdir)","id":4877,"name":"test_assertion_binchars","nodeType":"Function","startLoc":591,"text":"def test_assertion_binchars(self, testdir):\n \"\"\"this test did fail when the escaping wasnt strict\"\"\"\n testdir.makepyfile(\n \"\"\"\n\n M1 = '\\x01\\x02\\x03\\x04'\n M2 = '\\x01\\x02\\x03\\x05'\n\n def test_str_compare():\n assert M1 == M2\n \"\"\"\n )\n result, dom = runandparse(testdir)\n print(dom.toxml())"},{"col":4,"comment":"null","endLoc":275,"header":"def test_pytest_collect_directory(self, testdir)","id":4878,"name":"test_pytest_collect_directory","nodeType":"Function","startLoc":264,"text":"def test_pytest_collect_directory(self, testdir):\n wascalled = []\n\n class Plugin(object):\n def pytest_collect_directory(self, path, parent):\n wascalled.append(path.basename)\n\n testdir.mkdir(\"hello\")\n testdir.mkdir(\"world\")\n pytest.main(testdir.tmpdir, plugins=[Plugin()])\n assert \"hello\" in wascalled\n assert \"world\" in wascalled"},{"col":4,"comment":"null","endLoc":617,"header":"def test_pass_captures_stdout(self, testdir)","id":4879,"name":"test_pass_captures_stdout","nodeType":"Function","startLoc":606,"text":"def test_pass_captures_stdout(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_pass():\n print('hello-stdout')\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n pnode = node.find_first_by_tag(\"testcase\")\n systemout = pnode.find_first_by_tag(\"system-out\")\n assert \"hello-stdout\" in systemout.toxml()"},{"col":4,"comment":"null","endLoc":854,"header":"def test_unicode_and_str_mixture(self)","id":4880,"name":"test_unicode_and_str_mixture","nodeType":"Function","startLoc":844,"text":"def test_unicode_and_str_mixture(self):\n f = capture.CaptureIO()\n if sys.version_info >= (3, 0):\n f.write(\"\\u00f6\")\n pytest.raises(TypeError, f.write, b\"hello\")\n else:\n f.write(u\"\\u00f6\")\n f.write(b\"hello\")\n s = f.getvalue()\n f.close()\n assert isinstance(s, text_type)"},{"col":4,"comment":" Set environment variable ``name`` to ``value``. If ``prepend``\n is a character, read the current environment variable value\n and prepend the ``value`` adjoined with the ``prepend`` character.","endLoc":252,"header":"def setenv(self, name, value, prepend=None)","id":4881,"name":"setenv","nodeType":"Function","startLoc":234,"text":"def setenv(self, name, value, prepend=None):\n \"\"\" Set environment variable ``name`` to ``value``. If ``prepend``\n is a character, read the current environment variable value\n and prepend the ``value`` adjoined with the ``prepend`` character.\"\"\"\n if not isinstance(value, str):\n warnings.warn(\n pytest.PytestWarning(\n \"Value of environment variable {name} type should be str, but got \"\n \"{value!r} (type: {type}); converted to str implicitly\".format(\n name=name, value=value, type=type(value).__name__\n )\n ),\n stacklevel=2,\n )\n value = str(value)\n if prepend and name in os.environ:\n value = value + prepend + os.environ[name]\n self._warn_if_env_name_is_not_str(name)\n self.setitem(os.environ, name, value)"},{"className":"TestPrunetraceback","col":0,"comment":"null","endLoc":324,"id":4882,"nodeType":"Class","startLoc":278,"text":"class TestPrunetraceback(object):\n def test_custom_repr_failure(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import not_exists\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_collect_file(path, parent):\n return MyFile(path, parent)\n class MyError(Exception):\n pass\n class MyFile(pytest.File):\n def collect(self):\n raise MyError()\n def repr_failure(self, excinfo):\n if excinfo.errisinstance(MyError):\n return \"hello world\"\n return pytest.File.repr_failure(self, excinfo)\n \"\"\"\n )\n\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*ERROR collecting*\", \"*hello world*\"])\n\n @pytest.mark.xfail(reason=\"other mechanism for adding to reporting needed\")\n def test_collect_report_postprocessing(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import not_exists\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.hookimpl(hookwrapper=True)\n def pytest_make_collect_report():\n outcome = yield\n rep = outcome.get_result()\n rep.headerlines += [\"header1\"]\n outcome.force_result(rep)\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*ERROR collecting*\", \"*header1*\"])"},{"col":4,"comment":"null","endLoc":303,"header":"def test_custom_repr_failure(self, testdir)","id":4883,"name":"test_custom_repr_failure","nodeType":"Function","startLoc":279,"text":"def test_custom_repr_failure(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import not_exists\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_collect_file(path, parent):\n return MyFile(path, parent)\n class MyError(Exception):\n pass\n class MyFile(pytest.File):\n def collect(self):\n raise MyError()\n def repr_failure(self, excinfo):\n if excinfo.errisinstance(MyError):\n return \"hello world\"\n return pytest.File.repr_failure(self, excinfo)\n \"\"\"\n )\n\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*ERROR collecting*\", \"*hello world*\"])"},{"col":4,"comment":"null","endLoc":324,"header":"@pytest.mark.xfail(reason=\"other mechanism for adding to reporting needed\")\n def test_collect_report_postprocessing(self, testdir)","id":4884,"name":"test_collect_report_postprocessing","nodeType":"Function","startLoc":305,"text":"@pytest.mark.xfail(reason=\"other mechanism for adding to reporting needed\")\n def test_collect_report_postprocessing(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import not_exists\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.hookimpl(hookwrapper=True)\n def pytest_make_collect_report():\n outcome = yield\n rep = outcome.get_result()\n rep.headerlines += [\"header1\"]\n outcome.force_result(rep)\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*ERROR collecting*\", \"*header1*\"])"},{"col":4,"comment":"null","endLoc":631,"header":"def test_pass_captures_stderr(self, testdir)","id":4885,"name":"test_pass_captures_stderr","nodeType":"Function","startLoc":619,"text":"def test_pass_captures_stderr(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n def test_pass():\n sys.stderr.write('hello-stderr')\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n pnode = node.find_first_by_tag(\"testcase\")\n systemout = pnode.find_first_by_tag(\"system-err\")\n assert \"hello-stderr\" in systemout.toxml()"},{"className":"TestCustomConftests","col":0,"comment":"null","endLoc":445,"id":4886,"nodeType":"Class","startLoc":327,"text":"class TestCustomConftests(object):\n def test_ignore_collect_path(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_ignore_collect(path, config):\n return path.basename.startswith(\"x\") or \\\n path.basename == \"test_one.py\"\n \"\"\"\n )\n sub = testdir.mkdir(\"xy123\")\n sub.ensure(\"test_hello.py\").write(\"syntax error\")\n sub.join(\"conftest.py\").write(\"syntax error\")\n testdir.makepyfile(\"def test_hello(): pass\")\n testdir.makepyfile(test_one=\"syntax error\")\n result = testdir.runpytest(\"--fulltrace\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_ignore_collect_not_called_on_argument(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_ignore_collect(path, config):\n return True\n \"\"\"\n )\n p = testdir.makepyfile(\"def test_hello(): pass\")\n result = testdir.runpytest(p)\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result.stdout.fnmatch_lines([\"*collected 0 items*\"])\n\n def test_collectignore_exclude_on_option(self, testdir):\n testdir.makeconftest(\n \"\"\"\n collect_ignore = ['hello', 'test_world.py']\n def pytest_addoption(parser):\n parser.addoption(\"--XX\", action=\"store_true\", default=False)\n def pytest_configure(config):\n if config.getvalue(\"XX\"):\n collect_ignore[:] = []\n \"\"\"\n )\n testdir.mkdir(\"hello\")\n testdir.makepyfile(test_world=\"def test_hello(): pass\")\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n assert \"passed\" not in result.stdout.str()\n result = testdir.runpytest(\"--XX\")\n assert result.ret == 0\n assert \"passed\" in result.stdout.str()\n\n def test_collectignoreglob_exclude_on_option(self, testdir):\n testdir.makeconftest(\n \"\"\"\n collect_ignore_glob = ['*w*l[dt]*']\n def pytest_addoption(parser):\n parser.addoption(\"--XX\", action=\"store_true\", default=False)\n def pytest_configure(config):\n if config.getvalue(\"XX\"):\n collect_ignore_glob[:] = []\n \"\"\"\n )\n testdir.makepyfile(test_world=\"def test_hello(): pass\")\n testdir.makepyfile(test_welt=\"def test_hallo(): pass\")\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result.stdout.fnmatch_lines([\"*collected 0 items*\"])\n result = testdir.runpytest(\"--XX\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n def test_pytest_fs_collect_hooks_are_seen(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n class MyModule(pytest.Module):\n pass\n def pytest_collect_file(path, parent):\n if path.ext == \".py\":\n return MyModule(path, parent)\n \"\"\"\n )\n testdir.mkdir(\"sub\")\n testdir.makepyfile(\"def test_x(): pass\")\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*MyModule*\", \"*test_x*\"])\n\n def test_pytest_collect_file_from_sister_dir(self, testdir):\n sub1 = testdir.mkpydir(\"sub1\")\n sub2 = testdir.mkpydir(\"sub2\")\n conf1 = testdir.makeconftest(\n \"\"\"\n import pytest\n class MyModule1(pytest.Module):\n pass\n def pytest_collect_file(path, parent):\n if path.ext == \".py\":\n return MyModule1(path, parent)\n \"\"\"\n )\n conf1.move(sub1.join(conf1.basename))\n conf2 = testdir.makeconftest(\n \"\"\"\n import pytest\n class MyModule2(pytest.Module):\n pass\n def pytest_collect_file(path, parent):\n if path.ext == \".py\":\n return MyModule2(path, parent)\n \"\"\"\n )\n conf2.move(sub2.join(conf2.basename))\n p = testdir.makepyfile(\"def test_x(): pass\")\n p.copy(sub1.join(p.basename))\n p.copy(sub2.join(p.basename))\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*MyModule1*\", \"*MyModule2*\", \"*test_x*\"])"},{"col":4,"comment":"null","endLoc":343,"header":"def test_ignore_collect_path(self, testdir)","id":4887,"name":"test_ignore_collect_path","nodeType":"Function","startLoc":328,"text":"def test_ignore_collect_path(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_ignore_collect(path, config):\n return path.basename.startswith(\"x\") or \\\n path.basename == \"test_one.py\"\n \"\"\"\n )\n sub = testdir.mkdir(\"xy123\")\n sub.ensure(\"test_hello.py\").write(\"syntax error\")\n sub.join(\"conftest.py\").write(\"syntax error\")\n testdir.makepyfile(\"def test_hello(): pass\")\n testdir.makepyfile(test_one=\"syntax error\")\n result = testdir.runpytest(\"--fulltrace\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":4,"comment":"null","endLoc":358,"header":"def test_ignore_collect_not_called_on_argument(self, testdir)","id":4888,"name":"test_ignore_collect_not_called_on_argument","nodeType":"Function","startLoc":345,"text":"def test_ignore_collect_not_called_on_argument(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_ignore_collect(path, config):\n return True\n \"\"\"\n )\n p = testdir.makepyfile(\"def test_hello(): pass\")\n result = testdir.runpytest(p)\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result.stdout.fnmatch_lines([\"*collected 0 items*\"])"},{"col":0,"comment":" return an open text file object that's a duplicate of f on the\n FD-level if possible.\n ","endLoc":424,"header":"def safe_text_dupfile(f, mode, default_encoding=\"UTF8\")","id":4892,"name":"safe_text_dupfile","nodeType":"Function","startLoc":408,"text":"def safe_text_dupfile(f, mode, default_encoding=\"UTF8\"):\n \"\"\" return an open text file object that's a duplicate of f on the\n FD-level if possible.\n \"\"\"\n encoding = getattr(f, \"encoding\", None)\n try:\n fd = f.fileno()\n except Exception:\n if \"b\" not in getattr(f, \"mode\", \"\") and hasattr(f, \"encoding\"):\n # we seem to have a text stream, let's just use it\n return f\n else:\n newfd = os.dup(fd)\n if \"b\" not in mode:\n mode += \"b\"\n f = os.fdopen(newfd, mode, 0) # no buffering\n return EncodedFile(f, encoding or default_encoding)"},{"col":4,"comment":"null","endLoc":378,"header":"def test_collectignore_exclude_on_option(self, testdir)","id":4893,"name":"test_collectignore_exclude_on_option","nodeType":"Function","startLoc":360,"text":"def test_collectignore_exclude_on_option(self, testdir):\n testdir.makeconftest(\n \"\"\"\n collect_ignore = ['hello', 'test_world.py']\n def pytest_addoption(parser):\n parser.addoption(\"--XX\", action=\"store_true\", default=False)\n def pytest_configure(config):\n if config.getvalue(\"XX\"):\n collect_ignore[:] = []\n \"\"\"\n )\n testdir.mkdir(\"hello\")\n testdir.makepyfile(test_world=\"def test_hello(): pass\")\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n assert \"passed\" not in result.stdout.str()\n result = testdir.runpytest(\"--XX\")\n assert result.ret == 0\n assert \"passed\" in result.stdout.str()"},{"col":4,"comment":"null","endLoc":398,"header":"def test_collectignoreglob_exclude_on_option(self, testdir)","id":4894,"name":"test_collectignoreglob_exclude_on_option","nodeType":"Function","startLoc":380,"text":"def test_collectignoreglob_exclude_on_option(self, testdir):\n testdir.makeconftest(\n \"\"\"\n collect_ignore_glob = ['*w*l[dt]*']\n def pytest_addoption(parser):\n parser.addoption(\"--XX\", action=\"store_true\", default=False)\n def pytest_configure(config):\n if config.getvalue(\"XX\"):\n collect_ignore_glob[:] = []\n \"\"\"\n )\n testdir.makepyfile(test_world=\"def test_hello(): pass\")\n testdir.makepyfile(test_welt=\"def test_hallo(): pass\")\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result.stdout.fnmatch_lines([\"*collected 0 items*\"])\n result = testdir.runpytest(\"--XX\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*2 passed*\"])"},{"col":4,"comment":"null","endLoc":414,"header":"def test_pytest_fs_collect_hooks_are_seen(self, testdir)","id":4895,"name":"test_pytest_fs_collect_hooks_are_seen","nodeType":"Function","startLoc":400,"text":"def test_pytest_fs_collect_hooks_are_seen(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n class MyModule(pytest.Module):\n pass\n def pytest_collect_file(path, parent):\n if path.ext == \".py\":\n return MyModule(path, parent)\n \"\"\"\n )\n testdir.mkdir(\"sub\")\n testdir.makepyfile(\"def test_x(): pass\")\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*MyModule*\", \"*test_x*\"])"},{"col":4,"comment":"null","endLoc":650,"header":"def test_setup_error_captures_stdout(self, testdir)","id":4896,"name":"test_setup_error_captures_stdout","nodeType":"Function","startLoc":633,"text":"def test_setup_error_captures_stdout(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def arg(request):\n print('hello-stdout')\n raise ValueError()\n def test_function(arg):\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n pnode = node.find_first_by_tag(\"testcase\")\n systemout = pnode.find_first_by_tag(\"system-out\")\n assert \"hello-stdout\" in systemout.toxml()"},{"col":4,"comment":"null","endLoc":445,"header":"def test_pytest_collect_file_from_sister_dir(self, testdir)","id":4897,"name":"test_pytest_collect_file_from_sister_dir","nodeType":"Function","startLoc":416,"text":"def test_pytest_collect_file_from_sister_dir(self, testdir):\n sub1 = testdir.mkpydir(\"sub1\")\n sub2 = testdir.mkpydir(\"sub2\")\n conf1 = testdir.makeconftest(\n \"\"\"\n import pytest\n class MyModule1(pytest.Module):\n pass\n def pytest_collect_file(path, parent):\n if path.ext == \".py\":\n return MyModule1(path, parent)\n \"\"\"\n )\n conf1.move(sub1.join(conf1.basename))\n conf2 = testdir.makeconftest(\n \"\"\"\n import pytest\n class MyModule2(pytest.Module):\n pass\n def pytest_collect_file(path, parent):\n if path.ext == \".py\":\n return MyModule2(path, parent)\n \"\"\"\n )\n conf2.move(sub2.join(conf2.basename))\n p = testdir.makepyfile(\"def test_x(): pass\")\n p.copy(sub1.join(p.basename))\n p.copy(sub2.join(p.basename))\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*MyModule1*\", \"*MyModule2*\", \"*test_x*\"])"},{"className":"TestSession","col":0,"comment":"null","endLoc":636,"id":4898,"nodeType":"Class","startLoc":448,"text":"class TestSession(object):\n def test_parsearg(self, testdir):\n p = testdir.makepyfile(\"def test_func(): pass\")\n subdir = testdir.mkdir(\"sub\")\n subdir.ensure(\"__init__.py\")\n target = subdir.join(p.basename)\n p.move(target)\n subdir.chdir()\n config = testdir.parseconfig(p.basename)\n rcol = Session(config=config)\n assert rcol.fspath == subdir\n parts = rcol._parsearg(p.basename)\n\n assert parts[0] == target\n assert len(parts) == 1\n parts = rcol._parsearg(p.basename + \"::test_func\")\n assert parts[0] == target\n assert parts[1] == \"test_func\"\n assert len(parts) == 2\n\n def test_collect_topdir(self, testdir):\n p = testdir.makepyfile(\"def test_func(): pass\")\n id = \"::\".join([p.basename, \"test_func\"])\n # XXX migrate to collectonly? (see below)\n config = testdir.parseconfig(id)\n topdir = testdir.tmpdir\n rcol = Session(config)\n assert topdir == rcol.fspath\n # rootid = rcol.nodeid\n # root2 = rcol.perform_collect([rcol.nodeid], genitems=False)[0]\n # assert root2 == rcol, rootid\n colitems = rcol.perform_collect([rcol.nodeid], genitems=False)\n assert len(colitems) == 1\n assert colitems[0].fspath == p\n\n def get_reported_items(self, hookrec):\n \"\"\"Return pytest.Item instances reported by the pytest_collectreport hook\"\"\"\n calls = hookrec.getcalls(\"pytest_collectreport\")\n return [\n x\n for call in calls\n for x in call.report.result\n if isinstance(x, pytest.Item)\n ]\n\n def test_collect_protocol_single_function(self, testdir):\n p = testdir.makepyfile(\"def test_func(): pass\")\n id = \"::\".join([p.basename, \"test_func\"])\n items, hookrec = testdir.inline_genitems(id)\n item, = items\n assert item.name == \"test_func\"\n newid = item.nodeid\n assert newid == id\n pprint.pprint(hookrec.calls)\n topdir = testdir.tmpdir # noqa\n hookrec.assert_contains(\n [\n (\"pytest_collectstart\", \"collector.fspath == topdir\"),\n (\"pytest_make_collect_report\", \"collector.fspath == topdir\"),\n (\"pytest_collectstart\", \"collector.fspath == p\"),\n (\"pytest_make_collect_report\", \"collector.fspath == p\"),\n (\"pytest_pycollect_makeitem\", \"name == 'test_func'\"),\n (\"pytest_collectreport\", \"report.result[0].name == 'test_func'\"),\n ]\n )\n # ensure we are reporting the collection of the single test item (#2464)\n assert [x.name for x in self.get_reported_items(hookrec)] == [\"test_func\"]\n\n def test_collect_protocol_method(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n class TestClass(object):\n def test_method(self):\n pass\n \"\"\"\n )\n normid = p.basename + \"::TestClass::test_method\"\n for id in [p.basename, p.basename + \"::TestClass\", normid]:\n items, hookrec = testdir.inline_genitems(id)\n assert len(items) == 1\n assert items[0].name == \"test_method\"\n newid = items[0].nodeid\n assert newid == normid\n # ensure we are reporting the collection of the single test item (#2464)\n assert [x.name for x in self.get_reported_items(hookrec)] == [\"test_method\"]\n\n def test_collect_custom_nodes_multi_id(self, testdir):\n p = testdir.makepyfile(\"def test_func(): pass\")\n testdir.makeconftest(\n \"\"\"\n import pytest\n class SpecialItem(pytest.Item):\n def runtest(self):\n return # ok\n class SpecialFile(pytest.File):\n def collect(self):\n return [SpecialItem(name=\"check\", parent=self)]\n def pytest_collect_file(path, parent):\n if path.basename == %r:\n return SpecialFile(fspath=path, parent=parent)\n \"\"\"\n % p.basename\n )\n id = p.basename\n\n items, hookrec = testdir.inline_genitems(id)\n pprint.pprint(hookrec.calls)\n assert len(items) == 2\n hookrec.assert_contains(\n [\n (\"pytest_collectstart\", \"collector.fspath == collector.session.fspath\"),\n (\n \"pytest_collectstart\",\n \"collector.__class__.__name__ == 'SpecialFile'\",\n ),\n (\"pytest_collectstart\", \"collector.__class__.__name__ == 'Module'\"),\n (\"pytest_pycollect_makeitem\", \"name == 'test_func'\"),\n (\"pytest_collectreport\", \"report.nodeid.startswith(p.basename)\"),\n ]\n )\n assert len(self.get_reported_items(hookrec)) == 2\n\n def test_collect_subdir_event_ordering(self, testdir):\n p = testdir.makepyfile(\"def test_func(): pass\")\n aaa = testdir.mkpydir(\"aaa\")\n test_aaa = aaa.join(\"test_aaa.py\")\n p.move(test_aaa)\n\n items, hookrec = testdir.inline_genitems()\n assert len(items) == 1\n pprint.pprint(hookrec.calls)\n hookrec.assert_contains(\n [\n (\"pytest_collectstart\", \"collector.fspath == test_aaa\"),\n (\"pytest_pycollect_makeitem\", \"name == 'test_func'\"),\n (\"pytest_collectreport\", \"report.nodeid.startswith('aaa/test_aaa.py')\"),\n ]\n )\n\n def test_collect_two_commandline_args(self, testdir):\n p = testdir.makepyfile(\"def test_func(): pass\")\n aaa = testdir.mkpydir(\"aaa\")\n bbb = testdir.mkpydir(\"bbb\")\n test_aaa = aaa.join(\"test_aaa.py\")\n p.copy(test_aaa)\n test_bbb = bbb.join(\"test_bbb.py\")\n p.move(test_bbb)\n\n id = \".\"\n\n items, hookrec = testdir.inline_genitems(id)\n assert len(items) == 2\n pprint.pprint(hookrec.calls)\n hookrec.assert_contains(\n [\n (\"pytest_collectstart\", \"collector.fspath == test_aaa\"),\n (\"pytest_pycollect_makeitem\", \"name == 'test_func'\"),\n (\"pytest_collectreport\", \"report.nodeid == 'aaa/test_aaa.py'\"),\n (\"pytest_collectstart\", \"collector.fspath == test_bbb\"),\n (\"pytest_pycollect_makeitem\", \"name == 'test_func'\"),\n (\"pytest_collectreport\", \"report.nodeid == 'bbb/test_bbb.py'\"),\n ]\n )\n\n def test_serialization_byid(self, testdir):\n testdir.makepyfile(\"def test_func(): pass\")\n items, hookrec = testdir.inline_genitems()\n assert len(items) == 1\n item, = items\n items2, hookrec = testdir.inline_genitems(item.nodeid)\n item2, = items2\n assert item2.name == item.name\n assert item2.fspath == item.fspath\n\n def test_find_byid_without_instance_parents(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n class TestClass(object):\n def test_method(self):\n pass\n \"\"\"\n )\n arg = p.basename + \"::TestClass::test_method\"\n items, hookrec = testdir.inline_genitems(arg)\n assert len(items) == 1\n item, = items\n assert item.nodeid.endswith(\"TestClass::test_method\")\n # ensure we are reporting the collection of the single test item (#2464)\n assert [x.name for x in self.get_reported_items(hookrec)] == [\"test_method\"]"},{"col":4,"comment":"null","endLoc":466,"header":"def test_parsearg(self, testdir)","id":4899,"name":"test_parsearg","nodeType":"Function","startLoc":449,"text":"def test_parsearg(self, testdir):\n p = testdir.makepyfile(\"def test_func(): pass\")\n subdir = testdir.mkdir(\"sub\")\n subdir.ensure(\"__init__.py\")\n target = subdir.join(p.basename)\n p.move(target)\n subdir.chdir()\n config = testdir.parseconfig(p.basename)\n rcol = Session(config=config)\n assert rcol.fspath == subdir\n parts = rcol._parsearg(p.basename)\n\n assert parts[0] == target\n assert len(parts) == 1\n parts = rcol._parsearg(p.basename + \"::test_func\")\n assert parts[0] == target\n assert parts[1] == \"test_func\"\n assert len(parts) == 2"},{"col":4,"comment":" Delete ``name`` from the environment. Raise KeyError if it does\n not exist.\n\n If ``raising`` is set to False, no exception will be raised if the\n environment variable is missing.\n ","endLoc":262,"header":"def delenv(self, name, raising=True)","id":4900,"name":"delenv","nodeType":"Function","startLoc":254,"text":"def delenv(self, name, raising=True):\n \"\"\" Delete ``name`` from the environment. Raise KeyError if it does\n not exist.\n\n If ``raising`` is set to False, no exception will be raised if the\n environment variable is missing.\n \"\"\"\n self._warn_if_env_name_is_not_str(name)\n self.delitem(os.environ, name, raising=raising)"},{"col":4,"comment":"In python3, stdout / stderr are text io wrappers (exposing a buffer\n property of the underlying bytestream). See issue #1407\n ","endLoc":863,"header":"@pytest.mark.skipif(sys.version_info[0] == 2, reason=\"python 3 only behaviour\")\n def test_write_bytes_to_buffer(self)","id":4901,"name":"test_write_bytes_to_buffer","nodeType":"Function","startLoc":856,"text":"@pytest.mark.skipif(sys.version_info[0] == 2, reason=\"python 3 only behaviour\")\n def test_write_bytes_to_buffer(self):\n \"\"\"In python3, stdout / stderr are text io wrappers (exposing a buffer\n property of the underlying bytestream). See issue #1407\n \"\"\"\n f = capture.CaptureIO()\n f.buffer.write(b\"foo\\r\\n\")\n assert f.getvalue() == \"foo\\r\\n\""},{"col":4,"comment":" Prepend ``path`` to ``sys.path`` list of import locations. ","endLoc":285,"header":"def syspath_prepend(self, path)","id":4902,"name":"syspath_prepend","nodeType":"Function","startLoc":264,"text":"def syspath_prepend(self, path):\n \"\"\" Prepend ``path`` to ``sys.path`` list of import locations. \"\"\"\n from pkg_resources import fixup_namespace_packages\n\n if self._savesyspath is None:\n self._savesyspath = sys.path[:]\n sys.path.insert(0, str(path))\n\n # https://github.com/pypa/setuptools/blob/d8b901bc/docs/pkg_resources.txt#L162-L171\n fixup_namespace_packages(str(path))\n\n # A call to syspathinsert() usually means that the caller wants to\n # import some dynamically created files, thus with python3 we\n # invalidate its import caches.\n # This is especially important when any namespace package is in used,\n # since then the mtime based FileFinder cache (that gets created in\n # this case already) gets not invalidated when writing the new files\n # quickly afterwards.\n if sys.version_info >= (3, 3):\n from importlib import invalidate_caches\n\n invalidate_caches()"},{"col":4,"comment":"null","endLoc":670,"header":"def test_setup_error_captures_stderr(self, testdir)","id":4910,"name":"test_setup_error_captures_stderr","nodeType":"Function","startLoc":652,"text":"def test_setup_error_captures_stderr(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n import pytest\n\n @pytest.fixture\n def arg(request):\n sys.stderr.write('hello-stderr')\n raise ValueError()\n def test_function(arg):\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n pnode = node.find_first_by_tag(\"testcase\")\n systemout = pnode.find_first_by_tag(\"system-err\")\n assert \"hello-stderr\" in systemout.toxml()"},{"col":4,"comment":"null","endLoc":692,"header":"def test_avoid_double_stdout(self, testdir)","id":4911,"name":"test_avoid_double_stdout","nodeType":"Function","startLoc":672,"text":"def test_avoid_double_stdout(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n import pytest\n\n @pytest.fixture\n def arg(request):\n yield\n sys.stdout.write('hello-stdout teardown')\n raise ValueError()\n def test_function(arg):\n sys.stdout.write('hello-stdout call')\n \"\"\"\n )\n result, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testsuite\")\n pnode = node.find_first_by_tag(\"testcase\")\n systemout = pnode.find_first_by_tag(\"system-out\")\n assert \"hello-stdout call\" in systemout.toxml()\n assert \"hello-stdout teardown\" in systemout.toxml()"},{"col":4,"comment":"null","endLoc":909,"header":"def setmulti2(self, valtypes, argnames, valset, id, marks, scopenum, param_index)","id":4912,"name":"setmulti2","nodeType":"Function","startLoc":901,"text":"def setmulti2(self, valtypes, argnames, valset, id, marks, scopenum, param_index):\n for arg, val in zip(argnames, valset):\n self._checkargnotcontained(arg)\n valtype_for_arg = valtypes[arg]\n getattr(self, valtype_for_arg)[arg] = val\n self.indices[arg] = param_index\n self._arg2scopenum[arg] = scopenum\n self._idlist.append(id)\n self.marks.extend(normalize_mark_list(marks))"},{"className":"TestNonPython","col":0,"comment":"null","endLoc":756,"id":4913,"nodeType":"Class","startLoc":729,"text":"class TestNonPython(object):\n def test_summing_simple(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_collect_file(path, parent):\n if path.ext == \".xyz\":\n return MyItem(path, parent)\n class MyItem(pytest.Item):\n def __init__(self, path, parent):\n super(MyItem, self).__init__(path.basename, parent)\n self.fspath = path\n def runtest(self):\n raise ValueError(42)\n def repr_failure(self, excinfo):\n return \"custom item runtest failed\"\n \"\"\"\n )\n testdir.tmpdir.join(\"myfile.xyz\").write(\"hello\")\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(errors=0, failures=1, skipped=0, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(name=\"myfile.xyz\")\n fnode = tnode.find_first_by_tag(\"failure\")\n fnode.assert_attr(message=\"custom item runtest failed\")\n assert \"custom item runtest failed\" in fnode.toxml()"},{"col":4,"comment":"null","endLoc":756,"header":"def test_summing_simple(self, testdir)","id":4914,"name":"test_summing_simple","nodeType":"Function","startLoc":730,"text":"def test_summing_simple(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_collect_file(path, parent):\n if path.ext == \".xyz\":\n return MyItem(path, parent)\n class MyItem(pytest.Item):\n def __init__(self, path, parent):\n super(MyItem, self).__init__(path.basename, parent)\n self.fspath = path\n def runtest(self):\n raise ValueError(42)\n def repr_failure(self, excinfo):\n return \"custom item runtest failed\"\n \"\"\"\n )\n testdir.tmpdir.join(\"myfile.xyz\").write(\"hello\")\n result, dom = runandparse(testdir)\n assert result.ret\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(errors=0, failures=1, skipped=0, tests=1)\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(name=\"myfile.xyz\")\n fnode = tnode.find_first_by_tag(\"failure\")\n fnode.assert_attr(message=\"custom item runtest failed\")\n assert \"custom item runtest failed\" in fnode.toxml()"},{"col":4,"comment":"null","endLoc":481,"header":"def test_collect_topdir(self, testdir)","id":4915,"name":"test_collect_topdir","nodeType":"Function","startLoc":468,"text":"def test_collect_topdir(self, testdir):\n p = testdir.makepyfile(\"def test_func(): pass\")\n id = \"::\".join([p.basename, \"test_func\"])\n # XXX migrate to collectonly? (see below)\n config = testdir.parseconfig(id)\n topdir = testdir.tmpdir\n rcol = Session(config)\n assert topdir == rcol.fspath\n # rootid = rcol.nodeid\n # root2 = rcol.perform_collect([rcol.nodeid], genitems=False)[0]\n # assert root2 == rcol, rootid\n colitems = rcol.perform_collect([rcol.nodeid], genitems=False)\n assert len(colitems) == 1\n assert colitems[0].fspath == p"},{"col":0,"comment":"null","endLoc":700,"header":"def test_mangle_test_address()","id":4916,"name":"test_mangle_test_address","nodeType":"Function","startLoc":695,"text":"def test_mangle_test_address():\n from _pytest.junitxml import mangle_test_address\n\n address = \"::\".join([\"a/my.py.thing.py\", \"Class\", \"()\", \"method\", \"[a-1-::]\"])\n newnames = mangle_test_address(address)\n assert newnames == [\"a.my.py.thing\", \"Class\", \"method\", \"[a-1-::]\"]"},{"col":0,"comment":"null","endLoc":726,"header":"def test_dont_configure_on_slaves(tmpdir)","id":4917,"name":"test_dont_configure_on_slaves","nodeType":"Function","startLoc":703,"text":"def test_dont_configure_on_slaves(tmpdir):\n gotten = []\n\n class FakeConfig(object):\n def __init__(self):\n self.pluginmanager = self\n self.option = self\n\n def getini(self, name):\n return \"pytest\"\n\n junitprefix = None\n # XXX: shouldnt need tmpdir ?\n xmlpath = str(tmpdir.join(\"junix.xml\"))\n register = gotten.append\n\n fake_config = FakeConfig()\n from _pytest import junitxml\n\n junitxml.pytest_configure(fake_config)\n assert len(gotten) == 1\n FakeConfig.slaveinput = None\n junitxml.pytest_configure(fake_config)\n assert len(gotten) == 1"},{"col":4,"comment":"Return pytest.Item instances reported by the pytest_collectreport hook","endLoc":491,"header":"def get_reported_items(self, hookrec)","id":4918,"name":"get_reported_items","nodeType":"Function","startLoc":483,"text":"def get_reported_items(self, hookrec):\n \"\"\"Return pytest.Item instances reported by the pytest_collectreport hook\"\"\"\n calls = hookrec.getcalls(\"pytest_collectreport\")\n return [\n x\n for call in calls\n for x in call.report.result\n if isinstance(x, pytest.Item)\n ]"},{"col":4,"comment":"null","endLoc":514,"header":"def test_collect_protocol_single_function(self, testdir)","id":4919,"name":"test_collect_protocol_single_function","nodeType":"Function","startLoc":493,"text":"def test_collect_protocol_single_function(self, testdir):\n p = testdir.makepyfile(\"def test_func(): pass\")\n id = \"::\".join([p.basename, \"test_func\"])\n items, hookrec = testdir.inline_genitems(id)\n item, = items\n assert item.name == \"test_func\"\n newid = item.nodeid\n assert newid == id\n pprint.pprint(hookrec.calls)\n topdir = testdir.tmpdir # noqa\n hookrec.assert_contains(\n [\n (\"pytest_collectstart\", \"collector.fspath == topdir\"),\n (\"pytest_make_collect_report\", \"collector.fspath == topdir\"),\n (\"pytest_collectstart\", \"collector.fspath == p\"),\n (\"pytest_make_collect_report\", \"collector.fspath == p\"),\n (\"pytest_pycollect_makeitem\", \"name == 'test_func'\"),\n (\"pytest_collectreport\", \"report.result[0].name == 'test_func'\"),\n ]\n )\n # ensure we are reporting the collection of the single test item (#2464)\n assert [x.name for x in self.get_reported_items(hookrec)] == [\"test_func\"]"},{"className":"TestFDCapture","col":0,"comment":"null","endLoc":1055,"id":4921,"nodeType":"Class","startLoc":970,"text":"class TestFDCapture(object):\n pytestmark = needsosdup\n\n def test_simple(self, tmpfile):\n fd = tmpfile.fileno()\n cap = capture.FDCapture(fd)\n data = b\"hello\"\n os.write(fd, data)\n s = cap.snap()\n cap.done()\n assert not s\n cap = capture.FDCapture(fd)\n cap.start()\n os.write(fd, data)\n s = cap.snap()\n cap.done()\n assert s == \"hello\"\n\n def test_simple_many(self, tmpfile):\n for i in range(10):\n self.test_simple(tmpfile)\n\n def test_simple_many_check_open_files(self, testdir):\n with lsof_check():\n with testdir.makepyfile(\"\").open(\"wb+\") as tmpfile:\n self.test_simple_many(tmpfile)\n\n def test_simple_fail_second_start(self, tmpfile):\n fd = tmpfile.fileno()\n cap = capture.FDCapture(fd)\n cap.done()\n pytest.raises(ValueError, cap.start)\n\n def test_stderr(self):\n cap = capture.FDCapture(2)\n cap.start()\n print(\"hello\", file=sys.stderr)\n s = cap.snap()\n cap.done()\n assert s == \"hello\\n\"\n\n def test_stdin(self, tmpfile):\n cap = capture.FDCapture(0)\n cap.start()\n x = os.read(0, 100).strip()\n cap.done()\n assert x == b\"\"\n\n def test_writeorg(self, tmpfile):\n data1, data2 = b\"foo\", b\"bar\"\n cap = capture.FDCapture(tmpfile.fileno())\n cap.start()\n tmpfile.write(data1)\n tmpfile.flush()\n cap.writeorg(data2)\n scap = cap.snap()\n cap.done()\n assert scap == data1.decode(\"ascii\")\n with open(tmpfile.name, \"rb\") as stmp_file:\n stmp = stmp_file.read()\n assert stmp == data2\n\n def test_simple_resume_suspend(self, tmpfile):\n with saved_fd(1):\n cap = capture.FDCapture(1)\n cap.start()\n data = b\"hello\"\n os.write(1, data)\n sys.stdout.write(\"whatever\")\n s = cap.snap()\n assert s == \"hellowhatever\"\n cap.suspend()\n os.write(1, b\"world\")\n sys.stdout.write(\"qlwkej\")\n assert not cap.snap()\n cap.resume()\n os.write(1, b\"but now\")\n sys.stdout.write(\" yes\\n\")\n s = cap.snap()\n assert s == \"but now yes\\n\"\n cap.suspend()\n cap.done()\n pytest.raises(AttributeError, cap.suspend)\n\n def test_capfd_sys_stdout_mode(self, capfd):\n assert \"b\" not in sys.stdout.mode"},{"col":4,"comment":"null","endLoc":986,"header":"def test_simple(self, tmpfile)","id":4922,"name":"test_simple","nodeType":"Function","startLoc":973,"text":"def test_simple(self, tmpfile):\n fd = tmpfile.fileno()\n cap = capture.FDCapture(fd)\n data = b\"hello\"\n os.write(fd, data)\n s = cap.snap()\n cap.done()\n assert not s\n cap = capture.FDCapture(fd)\n cap.start()\n os.write(fd, data)\n s = cap.snap()\n cap.done()\n assert s == \"hello\""},{"col":4,"comment":"null","endLoc":532,"header":"def test_collect_protocol_method(self, testdir)","id":4923,"name":"test_collect_protocol_method","nodeType":"Function","startLoc":516,"text":"def test_collect_protocol_method(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n class TestClass(object):\n def test_method(self):\n pass\n \"\"\"\n )\n normid = p.basename + \"::TestClass::test_method\"\n for id in [p.basename, p.basename + \"::TestClass\", normid]:\n items, hookrec = testdir.inline_genitems(id)\n assert len(items) == 1\n assert items[0].name == \"test_method\"\n newid = items[0].nodeid\n assert newid == normid\n # ensure we are reporting the collection of the single test item (#2464)\n assert [x.name for x in self.get_reported_items(hookrec)] == [\"test_method\"]"},{"col":4,"comment":"null","endLoc":568,"header":"def test_collect_custom_nodes_multi_id(self, testdir)","id":4925,"name":"test_collect_custom_nodes_multi_id","nodeType":"Function","startLoc":534,"text":"def test_collect_custom_nodes_multi_id(self, testdir):\n p = testdir.makepyfile(\"def test_func(): pass\")\n testdir.makeconftest(\n \"\"\"\n import pytest\n class SpecialItem(pytest.Item):\n def runtest(self):\n return # ok\n class SpecialFile(pytest.File):\n def collect(self):\n return [SpecialItem(name=\"check\", parent=self)]\n def pytest_collect_file(path, parent):\n if path.basename == %r:\n return SpecialFile(fspath=path, parent=parent)\n \"\"\"\n % p.basename\n )\n id = p.basename\n\n items, hookrec = testdir.inline_genitems(id)\n pprint.pprint(hookrec.calls)\n assert len(items) == 2\n hookrec.assert_contains(\n [\n (\"pytest_collectstart\", \"collector.fspath == collector.session.fspath\"),\n (\n \"pytest_collectstart\",\n \"collector.__class__.__name__ == 'SpecialFile'\",\n ),\n (\"pytest_collectstart\", \"collector.__class__.__name__ == 'Module'\"),\n (\"pytest_pycollect_makeitem\", \"name == 'test_func'\"),\n (\"pytest_collectreport\", \"report.nodeid.startswith(p.basename)\"),\n ]\n )\n assert len(self.get_reported_items(hookrec)) == 2"},{"col":4,"comment":"null","endLoc":644,"header":"def snap(self)","id":4926,"name":"snap","nodeType":"Function","startLoc":639,"text":"def snap(self):\n res = super(FDCapture, self).snap()\n enc = getattr(self.tmpfile, \"encoding\", None)\n if enc and isinstance(res, bytes):\n res = six.text_type(res, enc, \"replace\")\n return res"},{"col":0,"comment":"null","endLoc":774,"header":"def test_nullbyte(testdir)","id":4927,"name":"test_nullbyte","nodeType":"Function","startLoc":759,"text":"def test_nullbyte(testdir):\n # A null byte can not occur in XML (see section 2.2 of the spec)\n testdir.makepyfile(\n \"\"\"\n import sys\n def test_print_nullbyte():\n sys.stdout.write('Here the null -->' + chr(0) + '<--')\n sys.stdout.write('In repr form -->' + repr(chr(0)) + '<--')\n assert False\n \"\"\"\n )\n xmlf = testdir.tmpdir.join(\"junit.xml\")\n testdir.runpytest(\"--junitxml=%s\" % xmlf)\n text = xmlf.read()\n assert \"\\x00\" not in text\n assert \"#x00\" in text"},{"col":4,"comment":"null","endLoc":602,"header":"def snap(self)","id":4928,"name":"snap","nodeType":"Function","startLoc":597,"text":"def snap(self):\n self.tmpfile.seek(0)\n res = self.tmpfile.read()\n self.tmpfile.seek(0)\n self.tmpfile.truncate()\n return res"},{"col":0,"comment":"null","endLoc":791,"header":"def test_nullbyte_replace(testdir)","id":4929,"name":"test_nullbyte_replace","nodeType":"Function","startLoc":777,"text":"def test_nullbyte_replace(testdir):\n # Check if the null byte gets replaced\n testdir.makepyfile(\n \"\"\"\n import sys\n def test_print_nullbyte():\n sys.stdout.write('Here the null -->' + chr(0) + '<--')\n sys.stdout.write('In repr form -->' + repr(chr(0)) + '<--')\n assert False\n \"\"\"\n )\n xmlf = testdir.tmpdir.join(\"junit.xml\")\n testdir.runpytest(\"--junitxml=%s\" % xmlf)\n text = xmlf.read()\n assert \"#x0\" in text"},{"col":4,"comment":"null","endLoc":585,"header":"def test_collect_subdir_event_ordering(self, testdir)","id":4930,"name":"test_collect_subdir_event_ordering","nodeType":"Function","startLoc":570,"text":"def test_collect_subdir_event_ordering(self, testdir):\n p = testdir.makepyfile(\"def test_func(): pass\")\n aaa = testdir.mkpydir(\"aaa\")\n test_aaa = aaa.join(\"test_aaa.py\")\n p.move(test_aaa)\n\n items, hookrec = testdir.inline_genitems()\n assert len(items) == 1\n pprint.pprint(hookrec.calls)\n hookrec.assert_contains(\n [\n (\"pytest_collectstart\", \"collector.fspath == test_aaa\"),\n (\"pytest_pycollect_makeitem\", \"name == 'test_func'\"),\n (\"pytest_collectreport\", \"report.nodeid.startswith('aaa/test_aaa.py')\"),\n ]\n )"},{"col":0,"comment":"null","endLoc":834,"header":"def test_invalid_xml_escape()","id":4931,"name":"test_invalid_xml_escape","nodeType":"Function","startLoc":794,"text":"def test_invalid_xml_escape():\n # Test some more invalid xml chars, the full range should be\n # tested really but let's just thest the edges of the ranges\n # intead.\n # XXX This only tests low unicode character points for now as\n # there are some issues with the testing infrastructure for\n # the higher ones.\n # XXX Testing 0xD (\\r) is tricky as it overwrites the just written\n # line in the output, so we skip it too.\n global unichr\n try:\n unichr(65)\n except NameError:\n unichr = chr\n invalid = (\n 0x00,\n 0x1,\n 0xB,\n 0xC,\n 0xE,\n 0x19,\n 27, # issue #126\n 0xD800,\n 0xDFFF,\n 0xFFFE,\n 0x0FFFF,\n ) # , 0x110000)\n valid = (0x9, 0xA, 0x20)\n # 0xD, 0xD7FF, 0xE000, 0xFFFD, 0x10000, 0x10FFFF)\n\n from _pytest.junitxml import bin_xml_escape\n\n for i in invalid:\n got = bin_xml_escape(unichr(i)).uniobj\n if i <= 0xFF:\n expected = \"#x%02X\" % i\n else:\n expected = \"#x%04X\" % i\n assert got == expected\n for i in valid:\n assert chr(i) == bin_xml_escape(unichr(i)).uniobj"},{"col":4,"comment":"null","endLoc":554,"header":"def report_collect(self, final=False)","id":4932,"name":"report_collect","nodeType":"Function","startLoc":516,"text":"def report_collect(self, final=False):\n if self.config.option.verbose < 0:\n return\n\n if not final:\n # Only write \"collecting\" report every 0.5s.\n t = time.time()\n if (\n self._collect_report_last_write is not None\n and self._collect_report_last_write > t - REPORT_COLLECTING_RESOLUTION\n ):\n return\n self._collect_report_last_write = t\n\n errors = len(self.stats.get(\"error\", []))\n skipped = len(self.stats.get(\"skipped\", []))\n deselected = len(self.stats.get(\"deselected\", []))\n selected = self._numcollected - errors - skipped - deselected\n if final:\n line = \"collected \"\n else:\n line = \"collecting \"\n line += (\n str(self._numcollected) + \" item\" + (\"\" if self._numcollected == 1 else \"s\")\n )\n if errors:\n line += \" / %d errors\" % errors\n if deselected:\n line += \" / %d deselected\" % deselected\n if skipped:\n line += \" / %d skipped\" % skipped\n if self._numcollected > selected > 0:\n line += \" / %d selected\" % selected\n if self.isatty:\n self.rewrite(line, bold=True, erase=True)\n if final:\n self.write(\"\\n\")\n else:\n self.write_line(line)"},{"col":4,"comment":"null","endLoc":583,"header":"@pytest.hookimpl(trylast=True)\n def pytest_sessionstart(self, session)","id":4933,"name":"pytest_sessionstart","nodeType":"Function","startLoc":556,"text":"@pytest.hookimpl(trylast=True)\n def pytest_sessionstart(self, session):\n self._session = session\n self._sessionstarttime = time.time()\n if not self.showheader:\n return\n self.write_sep(\"=\", \"test session starts\", bold=True)\n verinfo = platform.python_version()\n msg = \"platform %s -- Python %s\" % (sys.platform, verinfo)\n if hasattr(sys, \"pypy_version_info\"):\n verinfo = \".\".join(map(str, sys.pypy_version_info[:3]))\n msg += \"[pypy-%s-%s]\" % (verinfo, sys.pypy_version_info[3])\n msg += \", pytest-%s, py-%s, pluggy-%s\" % (\n pytest.__version__,\n py.__version__,\n pluggy.__version__,\n )\n if (\n self.verbosity > 0\n or self.config.option.debug\n or getattr(self.config.option, \"pastebin\", None)\n ):\n msg += \" -- \" + str(sys.executable)\n self.write_line(msg)\n lines = self.config.hook.pytest_report_header(\n config=self.config, startdir=self.startdir\n )\n self._write_report_lines_from_hooks(lines)"},{"col":0,"comment":"null","endLoc":845,"header":"def test_logxml_path_expansion(tmpdir, monkeypatch)","id":4934,"name":"test_logxml_path_expansion","nodeType":"Function","startLoc":837,"text":"def test_logxml_path_expansion(tmpdir, monkeypatch):\n home_tilde = py.path.local(os.path.expanduser(\"~\")).join(\"test.xml\")\n xml_tilde = LogXML(\"~%stest.xml\" % tmpdir.sep, None)\n assert xml_tilde.logfile == home_tilde\n\n monkeypatch.setenv(\"HOME\", str(tmpdir))\n home_var = os.path.normpath(os.path.expandvars(\"$HOME/test.xml\"))\n xml_var = LogXML(\"$HOME%stest.xml\" % tmpdir.sep, None)\n assert xml_var.logfile == home_var"},{"col":4,"comment":"null","endLoc":610,"header":"def test_collect_two_commandline_args(self, testdir)","id":4935,"name":"test_collect_two_commandline_args","nodeType":"Function","startLoc":587,"text":"def test_collect_two_commandline_args(self, testdir):\n p = testdir.makepyfile(\"def test_func(): pass\")\n aaa = testdir.mkpydir(\"aaa\")\n bbb = testdir.mkpydir(\"bbb\")\n test_aaa = aaa.join(\"test_aaa.py\")\n p.copy(test_aaa)\n test_bbb = bbb.join(\"test_bbb.py\")\n p.move(test_bbb)\n\n id = \".\"\n\n items, hookrec = testdir.inline_genitems(id)\n assert len(items) == 2\n pprint.pprint(hookrec.calls)\n hookrec.assert_contains(\n [\n (\"pytest_collectstart\", \"collector.fspath == test_aaa\"),\n (\"pytest_pycollect_makeitem\", \"name == 'test_func'\"),\n (\"pytest_collectreport\", \"report.nodeid == 'aaa/test_aaa.py'\"),\n (\"pytest_collectstart\", \"collector.fspath == test_bbb\"),\n (\"pytest_pycollect_makeitem\", \"name == 'test_func'\"),\n (\"pytest_collectreport\", \"report.nodeid == 'bbb/test_bbb.py'\"),\n ]\n )"},{"col":4,"comment":"null","endLoc":620,"header":"def test_serialization_byid(self, testdir)","id":4937,"name":"test_serialization_byid","nodeType":"Function","startLoc":612,"text":"def test_serialization_byid(self, testdir):\n testdir.makepyfile(\"def test_func(): pass\")\n items, hookrec = testdir.inline_genitems()\n assert len(items) == 1\n item, = items\n items2, hookrec = testdir.inline_genitems(item.nodeid)\n item2, = items2\n assert item2.name == item.name\n assert item2.fspath == item.fspath"},{"col":4,"comment":"null","endLoc":990,"header":"def test_simple_many(self, tmpfile)","id":4938,"name":"test_simple_many","nodeType":"Function","startLoc":988,"text":"def test_simple_many(self, tmpfile):\n for i in range(10):\n self.test_simple(tmpfile)"},{"col":4,"comment":"null","endLoc":636,"header":"def test_find_byid_without_instance_parents(self, testdir)","id":4939,"name":"test_find_byid_without_instance_parents","nodeType":"Function","startLoc":622,"text":"def test_find_byid_without_instance_parents(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n class TestClass(object):\n def test_method(self):\n pass\n \"\"\"\n )\n arg = p.basename + \"::TestClass::test_method\"\n items, hookrec = testdir.inline_genitems(arg)\n assert len(items) == 1\n item, = items\n assert item.nodeid.endswith(\"TestClass::test_method\")\n # ensure we are reporting the collection of the single test item (#2464)\n assert [x.name for x in self.get_reported_items(hookrec)] == [\"test_method\"]"},{"className":"Test_getinitialnodes","col":0,"comment":"null","endLoc":670,"id":4940,"nodeType":"Class","startLoc":639,"text":"class Test_getinitialnodes(object):\n def test_global_file(self, testdir, tmpdir):\n x = tmpdir.ensure(\"x.py\")\n with tmpdir.as_cwd():\n config = testdir.parseconfigure(x)\n col = testdir.getnode(config, x)\n assert isinstance(col, pytest.Module)\n assert col.name == \"x.py\"\n assert col.parent.parent is None\n for col in col.listchain():\n assert col.config is config\n\n def test_pkgfile(self, testdir):\n \"\"\"Verify nesting when a module is within a package.\n The parent chain should match: Module -> Package -> Session.\n Session's parent should always be None.\n \"\"\"\n tmpdir = testdir.tmpdir\n subdir = tmpdir.join(\"subdir\")\n x = subdir.ensure(\"x.py\")\n subdir.ensure(\"__init__.py\")\n with subdir.as_cwd():\n config = testdir.parseconfigure(x)\n col = testdir.getnode(config, x)\n assert col.name == \"x.py\"\n assert isinstance(col, pytest.Module)\n assert isinstance(col.parent, pytest.Package)\n assert isinstance(col.parent.parent, pytest.Session)\n # session is batman (has no parents)\n assert col.parent.parent.parent is None\n for col in col.listchain():\n assert col.config is config"},{"col":4,"comment":"null","endLoc":649,"header":"def test_global_file(self, testdir, tmpdir)","id":4941,"name":"test_global_file","nodeType":"Function","startLoc":640,"text":"def test_global_file(self, testdir, tmpdir):\n x = tmpdir.ensure(\"x.py\")\n with tmpdir.as_cwd():\n config = testdir.parseconfigure(x)\n col = testdir.getnode(config, x)\n assert isinstance(col, pytest.Module)\n assert col.name == \"x.py\"\n assert col.parent.parent is None\n for col in col.listchain():\n assert col.config is config"},{"col":4,"comment":"Verify nesting when a module is within a package.\n The parent chain should match: Module -> Package -> Session.\n Session's parent should always be None.\n ","endLoc":670,"header":"def test_pkgfile(self, testdir)","id":4942,"name":"test_pkgfile","nodeType":"Function","startLoc":651,"text":"def test_pkgfile(self, testdir):\n \"\"\"Verify nesting when a module is within a package.\n The parent chain should match: Module -> Package -> Session.\n Session's parent should always be None.\n \"\"\"\n tmpdir = testdir.tmpdir\n subdir = tmpdir.join(\"subdir\")\n x = subdir.ensure(\"x.py\")\n subdir.ensure(\"__init__.py\")\n with subdir.as_cwd():\n config = testdir.parseconfigure(x)\n col = testdir.getnode(config, x)\n assert col.name == \"x.py\"\n assert isinstance(col, pytest.Module)\n assert isinstance(col.parent, pytest.Package)\n assert isinstance(col.parent.parent, pytest.Session)\n # session is batman (has no parents)\n assert col.parent.parent.parent is None\n for col in col.listchain():\n assert col.config is config"},{"className":"Test_genitems","col":0,"comment":"null","endLoc":747,"id":4943,"nodeType":"Class","startLoc":673,"text":"class Test_genitems(object):\n def test_check_collect_hashes(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_1():\n pass\n\n def test_2():\n pass\n \"\"\"\n )\n p.copy(p.dirpath(p.purebasename + \"2\" + \".py\"))\n items, reprec = testdir.inline_genitems(p.dirpath())\n assert len(items) == 4\n for numi, i in enumerate(items):\n for numj, j in enumerate(items):\n if numj != numi:\n assert hash(i) != hash(j)\n assert i != j\n\n def test_example_items1(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def testone():\n pass\n\n class TestX(object):\n def testmethod_one(self):\n pass\n\n class TestY(TestX):\n pass\n \"\"\"\n )\n items, reprec = testdir.inline_genitems(p)\n assert len(items) == 3\n assert items[0].name == \"testone\"\n assert items[1].name == \"testmethod_one\"\n assert items[2].name == \"testmethod_one\"\n\n # let's also test getmodpath here\n assert items[0].getmodpath() == \"testone\"\n assert items[1].getmodpath() == \"TestX.testmethod_one\"\n assert items[2].getmodpath() == \"TestY.testmethod_one\"\n\n s = items[0].getmodpath(stopatmodule=False)\n assert s.endswith(\"test_example_items1.testone\")\n print(s)\n\n def test_class_and_functions_discovery_using_glob(self, testdir):\n \"\"\"\n tests that python_classes and python_functions config options work\n as prefixes and glob-like patterns (issue #600).\n \"\"\"\n testdir.makeini(\n \"\"\"\n [pytest]\n python_classes = *Suite Test\n python_functions = *_test test\n \"\"\"\n )\n p = testdir.makepyfile(\n \"\"\"\n class MyTestSuite(object):\n def x_test(self):\n pass\n\n class TestCase(object):\n def test_y(self):\n pass\n \"\"\"\n )\n items, reprec = testdir.inline_genitems(p)\n ids = [x.getmodpath() for x in items]\n assert ids == [\"MyTestSuite.x_test\", \"TestCase.test_y\"]"},{"col":4,"comment":"null","endLoc":691,"header":"def test_check_collect_hashes(self, testdir)","id":4944,"name":"test_check_collect_hashes","nodeType":"Function","startLoc":674,"text":"def test_check_collect_hashes(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_1():\n pass\n\n def test_2():\n pass\n \"\"\"\n )\n p.copy(p.dirpath(p.purebasename + \"2\" + \".py\"))\n items, reprec = testdir.inline_genitems(p.dirpath())\n assert len(items) == 4\n for numi, i in enumerate(items):\n for numj, j in enumerate(items):\n if numj != numi:\n assert hash(i) != hash(j)\n assert i != j"},{"col":0,"comment":"null","endLoc":859,"header":"def test_logxml_changingdir(testdir)","id":4945,"name":"test_logxml_changingdir","nodeType":"Function","startLoc":848,"text":"def test_logxml_changingdir(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_func():\n import os\n os.chdir(\"a\")\n \"\"\"\n )\n testdir.tmpdir.mkdir(\"a\")\n result = testdir.runpytest(\"--junitxml=a/x.xml\")\n assert result.ret == 0\n assert testdir.tmpdir.join(\"a/x.xml\").check()"},{"col":0,"comment":"--junitxml should automatically create directories for the xml file","endLoc":872,"header":"def test_logxml_makedir(testdir)","id":4946,"name":"test_logxml_makedir","nodeType":"Function","startLoc":862,"text":"def test_logxml_makedir(testdir):\n \"\"\"--junitxml should automatically create directories for the xml file\"\"\"\n testdir.makepyfile(\n \"\"\"\n def test_pass():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--junitxml=path/to/results.xml\")\n assert result.ret == 0\n assert testdir.tmpdir.join(\"path/to/results.xml\").check()"},{"col":4,"comment":"null","endLoc":995,"header":"def test_simple_many_check_open_files(self, testdir)","id":4947,"name":"test_simple_many_check_open_files","nodeType":"Function","startLoc":992,"text":"def test_simple_many_check_open_files(self, testdir):\n with lsof_check():\n with testdir.makepyfile(\"\").open(\"wb+\") as tmpfile:\n self.test_simple_many(tmpfile)"},{"col":0,"comment":"Give an error if --junit-xml is a directory (#2089)","endLoc":878,"header":"def test_logxml_check_isdir(testdir)","id":4948,"name":"test_logxml_check_isdir","nodeType":"Function","startLoc":875,"text":"def test_logxml_check_isdir(testdir):\n \"\"\"Give an error if --junit-xml is a directory (#2089)\"\"\"\n result = testdir.runpytest(\"--junit-xml=.\")\n result.stderr.fnmatch_lines([\"*--junitxml must be a filename*\"])"},{"col":0,"comment":"null","endLoc":893,"header":"def test_escaped_parametrized_names_xml(testdir)","id":4949,"name":"test_escaped_parametrized_names_xml","nodeType":"Function","startLoc":881,"text":"def test_escaped_parametrized_names_xml(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('char', [u\"\\\\x00\"])\n def test_func(char):\n assert char\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testcase\")\n node.assert_attr(name=\"test_func[\\\\x00]\")"},{"col":0,"comment":"null","endLoc":909,"header":"def test_double_colon_split_function_issue469(testdir)","id":4950,"name":"test_double_colon_split_function_issue469","nodeType":"Function","startLoc":896,"text":"def test_double_colon_split_function_issue469(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('param', [\"double::colon\"])\n def test_func(param):\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testcase\")\n node.assert_attr(classname=\"test_double_colon_split_function_issue469\")\n node.assert_attr(name=\"test_func[double::colon]\")"},{"col":0,"comment":"null","endLoc":926,"header":"def test_double_colon_split_method_issue469(testdir)","id":4951,"name":"test_double_colon_split_method_issue469","nodeType":"Function","startLoc":912,"text":"def test_double_colon_split_method_issue469(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n class TestClass(object):\n @pytest.mark.parametrize('param', [\"double::colon\"])\n def test_func(self, param):\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testcase\")\n node.assert_attr(classname=\"test_double_colon_split_method_issue469.TestClass\")\n node.assert_attr(name=\"test_func[double::colon]\")"},{"col":4,"comment":"null","endLoc":720,"header":"def test_example_items1(self, testdir)","id":4952,"name":"test_example_items1","nodeType":"Function","startLoc":693,"text":"def test_example_items1(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def testone():\n pass\n\n class TestX(object):\n def testmethod_one(self):\n pass\n\n class TestY(TestX):\n pass\n \"\"\"\n )\n items, reprec = testdir.inline_genitems(p)\n assert len(items) == 3\n assert items[0].name == \"testone\"\n assert items[1].name == \"testmethod_one\"\n assert items[2].name == \"testmethod_one\"\n\n # let's also test getmodpath here\n assert items[0].getmodpath() == \"testone\"\n assert items[1].getmodpath() == \"TestX.testmethod_one\"\n assert items[2].getmodpath() == \"TestY.testmethod_one\"\n\n s = items[0].getmodpath(stopatmodule=False)\n assert s.endswith(\"test_example_items1.testone\")\n print(s)"},{"col":0,"comment":"null","endLoc":955,"header":"def test_unicode_issue368(testdir)","id":4953,"name":"test_unicode_issue368","nodeType":"Function","startLoc":929,"text":"def test_unicode_issue368(testdir):\n path = testdir.tmpdir.join(\"test.xml\")\n log = LogXML(str(path), None)\n ustr = u\"ВНИ!\"\n\n class Report(BaseReport):\n longrepr = ustr\n sections = []\n nodeid = \"something\"\n location = \"tests/filename.py\", 42, \"TestClass.method\"\n\n test_report = Report()\n\n # hopefully this is not too brittle ...\n log.pytest_sessionstart()\n node_reporter = log._opentestcase(test_report)\n node_reporter.append_failure(test_report)\n node_reporter.append_collect_error(test_report)\n node_reporter.append_collect_skipped(test_report)\n node_reporter.append_error(test_report)\n test_report.longrepr = \"filename\", 1, ustr\n node_reporter.append_skipped(test_report)\n test_report.longrepr = \"filename\", 1, \"Skipped: 卡嘣嘣\"\n node_reporter.append_skipped(test_report)\n test_report.wasxfail = ustr\n node_reporter.append_skipped(test_report)\n log.pytest_sessionfinish()"},{"col":4,"comment":"null","endLoc":1001,"header":"def test_simple_fail_second_start(self, tmpfile)","id":4954,"name":"test_simple_fail_second_start","nodeType":"Function","startLoc":997,"text":"def test_simple_fail_second_start(self, tmpfile):\n fd = tmpfile.fileno()\n cap = capture.FDCapture(fd)\n cap.done()\n pytest.raises(ValueError, cap.start)"},{"col":4,"comment":"\n tests that python_classes and python_functions config options work\n as prefixes and glob-like patterns (issue #600).\n ","endLoc":747,"header":"def test_class_and_functions_discovery_using_glob(self, testdir)","id":4955,"name":"test_class_and_functions_discovery_using_glob","nodeType":"Function","startLoc":722,"text":"def test_class_and_functions_discovery_using_glob(self, testdir):\n \"\"\"\n tests that python_classes and python_functions config options work\n as prefixes and glob-like patterns (issue #600).\n \"\"\"\n testdir.makeini(\n \"\"\"\n [pytest]\n python_classes = *Suite Test\n python_functions = *_test test\n \"\"\"\n )\n p = testdir.makepyfile(\n \"\"\"\n class MyTestSuite(object):\n def x_test(self):\n pass\n\n class TestCase(object):\n def test_y(self):\n pass\n \"\"\"\n )\n items, reprec = testdir.inline_genitems(p)\n ids = [x.getmodpath() for x in items]\n assert ids == [\"MyTestSuite.x_test\", \"TestCase.test_y\"]"},{"col":4,"comment":"null","endLoc":1009,"header":"def test_stderr(self)","id":4956,"name":"test_stderr","nodeType":"Function","startLoc":1003,"text":"def test_stderr(self):\n cap = capture.FDCapture(2)\n cap.start()\n print(\"hello\", file=sys.stderr)\n s = cap.snap()\n cap.done()\n assert s == \"hello\\n\""},{"className":"TestNodekeywords","col":0,"comment":"null","endLoc":811,"id":4957,"nodeType":"Class","startLoc":786,"text":"class TestNodekeywords(object):\n def test_no_under(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n def test_pass(): pass\n def test_fail(): assert 0\n \"\"\"\n )\n values = list(modcol.keywords)\n assert modcol.name in values\n for x in values:\n assert not x.startswith(\"_\")\n assert modcol.name in repr(modcol.keywords)\n\n def test_issue345(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_should_not_be_selected():\n assert False, 'I should not have been selected to run'\n\n def test___repr__():\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(\"-k repr\")\n reprec.assertoutcome(passed=1, failed=0)"},{"col":4,"comment":"null","endLoc":798,"header":"def test_no_under(self, testdir)","id":4958,"name":"test_no_under","nodeType":"Function","startLoc":787,"text":"def test_no_under(self, testdir):\n modcol = testdir.getmodulecol(\n \"\"\"\n def test_pass(): pass\n def test_fail(): assert 0\n \"\"\"\n )\n values = list(modcol.keywords)\n assert modcol.name in values\n for x in values:\n assert not x.startswith(\"_\")\n assert modcol.name in repr(modcol.keywords)"},{"col":0,"comment":"null","endLoc":976,"header":"def test_record_property(testdir)","id":4959,"name":"test_record_property","nodeType":"Function","startLoc":958,"text":"def test_record_property(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def other(record_property):\n record_property(\"bar\", 1)\n def test_record(record_property, other):\n record_property(\"foo\", \"<1\");\n \"\"\"\n )\n result, dom = runandparse(testdir, \"-rwv\")\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n psnode = tnode.find_first_by_tag(\"properties\")\n pnodes = psnode.find_by_tag(\"property\")\n pnodes[0].assert_attr(name=\"bar\", value=\"1\")\n pnodes[1].assert_attr(name=\"foo\", value=\"<1\")"},{"col":4,"comment":"null","endLoc":1016,"header":"def test_stdin(self, tmpfile)","id":4960,"name":"test_stdin","nodeType":"Function","startLoc":1011,"text":"def test_stdin(self, tmpfile):\n cap = capture.FDCapture(0)\n cap.start()\n x = os.read(0, 100).strip()\n cap.done()\n assert x == b\"\""},{"col":4,"comment":"null","endLoc":1030,"header":"def test_writeorg(self, tmpfile)","id":4963,"name":"test_writeorg","nodeType":"Function","startLoc":1018,"text":"def test_writeorg(self, tmpfile):\n data1, data2 = b\"foo\", b\"bar\"\n cap = capture.FDCapture(tmpfile.fileno())\n cap.start()\n tmpfile.write(data1)\n tmpfile.flush()\n cap.writeorg(data2)\n scap = cap.snap()\n cap.done()\n assert scap == data1.decode(\"ascii\")\n with open(tmpfile.name, \"rb\") as stmp_file:\n stmp = stmp_file.read()\n assert stmp == data2"},{"col":4,"comment":"null","endLoc":811,"header":"def test_issue345(self, testdir)","id":4964,"name":"test_issue345","nodeType":"Function","startLoc":800,"text":"def test_issue345(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_should_not_be_selected():\n assert False, 'I should not have been selected to run'\n\n def test___repr__():\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(\"-k repr\")\n reprec.assertoutcome(passed=1, failed=0)"},{"col":0,"comment":"null","endLoc":783,"header":"def test_matchnodes_two_collections_same_file(testdir)","id":4965,"name":"test_matchnodes_two_collections_same_file","nodeType":"Function","startLoc":750,"text":"def test_matchnodes_two_collections_same_file(testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_configure(config):\n config.pluginmanager.register(Plugin2())\n\n class Plugin2(object):\n def pytest_collect_file(self, path, parent):\n if path.ext == \".abc\":\n return MyFile2(path, parent)\n\n def pytest_collect_file(path, parent):\n if path.ext == \".abc\":\n return MyFile1(path, parent)\n\n class MyFile1(pytest.Item, pytest.File):\n def runtest(self):\n pass\n class MyFile2(pytest.File):\n def collect(self):\n return [Item2(\"hello\", parent=self)]\n\n class Item2(pytest.Item):\n def runtest(self):\n pass\n \"\"\"\n )\n p = testdir.makefile(\".abc\", \"\")\n result = testdir.runpytest()\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n res = testdir.runpytest(\"%s::hello\" % p.basename)\n res.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":4,"comment":"null","endLoc":585,"header":"def __repr__(self)","id":4967,"name":"__repr__","nodeType":"Function","startLoc":580,"text":"def __repr__(self):\n return \"\" % (\n self.targetfd,\n getattr(self, \"targetfd_save\", None),\n self._state,\n )"},{"col":4,"comment":" Start capturing on targetfd using memorized tmpfile. ","endLoc":595,"header":"def start(self)","id":4968,"name":"start","nodeType":"Function","startLoc":587,"text":"def start(self):\n \"\"\" Start capturing on targetfd using memorized tmpfile. \"\"\"\n try:\n os.fstat(self.targetfd_save)\n except (AttributeError, OSError):\n raise ValueError(\"saved filedescriptor not valid anymore\")\n os.dup2(self.tmpfile_fd, self.targetfd)\n self.syscapture.start()\n self._state = \"started\""},{"col":4,"comment":"null","endLoc":921,"header":"def setall(self, funcargs, id, param)","id":4970,"name":"setall","nodeType":"Function","startLoc":911,"text":"def setall(self, funcargs, id, param):\n for x in funcargs:\n self._checkargnotcontained(x)\n self.funcargs.update(funcargs)\n if id is not NOTSET:\n self._idlist.append(id)\n if param is not NOTSET:\n assert self._globalparam is NOTSET\n self._globalparam = param\n for arg in funcargs:\n self._arg2scopenum[arg] = fixtures.scopenum_function"},{"col":0,"comment":"Verify that all collection errors are collected and no tests executed","endLoc":851,"header":"def test_exit_on_collection_error(testdir)","id":4971,"name":"test_exit_on_collection_error","nodeType":"Function","startLoc":836,"text":"def test_exit_on_collection_error(testdir):\n \"\"\"Verify that all collection errors are collected and no tests executed\"\"\"\n testdir.makepyfile(**COLLECTION_ERROR_PY_FILES)\n\n res = testdir.runpytest()\n assert res.ret == 2\n\n res.stdout.fnmatch_lines(\n [\n \"collected 2 items / 2 errors\",\n \"*ERROR collecting test_02_import_error.py*\",\n \"*No module named *asdfa*\",\n \"*ERROR collecting test_03_import_error.py*\",\n \"*No module named *asdfa*\",\n ]\n )"},{"col":4,"comment":" write to original file descriptor. ","endLoc":628,"header":"def writeorg(self, data)","id":4973,"name":"writeorg","nodeType":"Function","startLoc":624,"text":"def writeorg(self, data):\n \"\"\" write to original file descriptor. \"\"\"\n if isinstance(data, six.text_type):\n data = data.encode(\"utf8\") # XXX use encoding of original stream\n os.write(self.targetfd_save, data)"},{"col":0,"comment":"\n Verify collection is aborted once maxfail errors are encountered ignoring\n further modules which would cause more collection errors.\n ","endLoc":868,"header":"def test_exit_on_collection_with_maxfail_smaller_than_n_errors(testdir)","id":4974,"name":"test_exit_on_collection_with_maxfail_smaller_than_n_errors","nodeType":"Function","startLoc":854,"text":"def test_exit_on_collection_with_maxfail_smaller_than_n_errors(testdir):\n \"\"\"\n Verify collection is aborted once maxfail errors are encountered ignoring\n further modules which would cause more collection errors.\n \"\"\"\n testdir.makepyfile(**COLLECTION_ERROR_PY_FILES)\n\n res = testdir.runpytest(\"--maxfail=1\")\n assert res.ret == 1\n\n res.stdout.fnmatch_lines(\n [\"*ERROR collecting test_02_import_error.py*\", \"*No module named *asdfa*\"]\n )\n\n assert \"test_03\" not in res.stdout.str()"},{"col":4,"comment":" stop capturing, restore streams, return original capture file,\n seeked to position zero. ","endLoc":612,"header":"def done(self)","id":4976,"name":"done","nodeType":"Function","startLoc":604,"text":"def done(self):\n \"\"\" stop capturing, restore streams, return original capture file,\n seeked to position zero. \"\"\"\n targetfd_save = self.__dict__.pop(\"targetfd_save\")\n os.dup2(targetfd_save, self.targetfd)\n os.close(targetfd_save)\n self.syscapture.done()\n _attempt_to_close_capture_file(self.tmpfile)\n self._state = \"done\""},{"attributeType":"null","col":8,"comment":"null","endLoc":868,"id":4977,"name":"_globalparam","nodeType":"Attribute","startLoc":868,"text":"self._globalparam"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":871,"id":4978,"name":"indices","nodeType":"Attribute","startLoc":871,"text":"self.indices"},{"attributeType":"null","col":8,"comment":"null","endLoc":867,"id":4979,"name":"_globalid","nodeType":"Attribute","startLoc":867,"text":"self._globalid"},{"col":0,"comment":"\n Verify the test run aborts due to collection errors even if maxfail count of\n errors was not reached.\n ","endLoc":889,"header":"def test_exit_on_collection_with_maxfail_bigger_than_n_errors(testdir)","id":4980,"name":"test_exit_on_collection_with_maxfail_bigger_than_n_errors","nodeType":"Function","startLoc":871,"text":"def test_exit_on_collection_with_maxfail_bigger_than_n_errors(testdir):\n \"\"\"\n Verify the test run aborts due to collection errors even if maxfail count of\n errors was not reached.\n \"\"\"\n testdir.makepyfile(**COLLECTION_ERROR_PY_FILES)\n\n res = testdir.runpytest(\"--maxfail=4\")\n assert res.ret == 2\n\n res.stdout.fnmatch_lines(\n [\n \"collected 2 items / 2 errors\",\n \"*ERROR collecting test_02_import_error.py*\",\n \"*No module named *asdfa*\",\n \"*ERROR collecting test_03_import_error.py*\",\n \"*No module named *asdfa*\",\n ]\n )"},{"attributeType":"null","col":8,"comment":"null","endLoc":863,"id":4981,"name":"metafunc","nodeType":"Attribute","startLoc":863,"text":"self.metafunc"},{"col":0,"comment":"null","endLoc":993,"header":"def test_record_property_same_name(testdir)","id":4982,"name":"test_record_property_same_name","nodeType":"Function","startLoc":979,"text":"def test_record_property_same_name(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_record_with_same_name(record_property):\n record_property(\"foo\", \"bar\")\n record_property(\"foo\", \"baz\")\n \"\"\"\n )\n result, dom = runandparse(testdir, \"-rw\")\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n psnode = tnode.find_first_by_tag(\"properties\")\n pnodes = psnode.find_by_tag(\"property\")\n pnodes[0].assert_attr(name=\"foo\", value=\"bar\")\n pnodes[1].assert_attr(name=\"foo\", value=\"baz\")"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":864,"id":4983,"name":"funcargs","nodeType":"Attribute","startLoc":864,"text":"self.funcargs"},{"attributeType":"list","col":8,"comment":"null","endLoc":865,"id":4984,"name":"_idlist","nodeType":"Attribute","startLoc":865,"text":"self._idlist"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":869,"id":4985,"name":"_arg2scopenum","nodeType":"Attribute","startLoc":869,"text":"self._arg2scopenum"},{"attributeType":"list","col":8,"comment":"null","endLoc":870,"id":4986,"name":"marks","nodeType":"Attribute","startLoc":870,"text":"self.marks"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":866,"id":4987,"name":"params","nodeType":"Attribute","startLoc":866,"text":"self.params"},{"className":"Metafunc","col":0,"comment":"\n Metafunc objects are passed to the :func:`pytest_generate_tests <_pytest.hookspec.pytest_generate_tests>` hook.\n They help to inspect a test function and to generate tests according to\n test configuration or values specified in the class or module where a\n test function is defined.\n ","endLoc":1128,"id":4988,"nodeType":"Class","startLoc":924,"text":"class Metafunc(fixtures.FuncargnamesCompatAttr):\n \"\"\"\n Metafunc objects are passed to the :func:`pytest_generate_tests <_pytest.hookspec.pytest_generate_tests>` hook.\n They help to inspect a test function and to generate tests according to\n test configuration or values specified in the class or module where a\n test function is defined.\n \"\"\"\n\n def __init__(self, definition, fixtureinfo, config, cls=None, module=None):\n assert (\n isinstance(definition, FunctionDefinition)\n or type(definition).__name__ == \"DefinitionMock\"\n )\n self.definition = definition\n\n #: access to the :class:`_pytest.config.Config` object for the test session\n self.config = config\n\n #: the module object where the test function is defined in.\n self.module = module\n\n #: underlying python test function\n self.function = definition.obj\n\n #: set of fixture names required by the test function\n self.fixturenames = fixtureinfo.names_closure\n\n #: class object where the test function is defined in or ``None``.\n self.cls = cls\n\n self._calls = []\n self._ids = set()\n self._arg2fixturedefs = fixtureinfo.name2fixturedefs\n\n def parametrize(self, argnames, argvalues, indirect=False, ids=None, scope=None):\n \"\"\" Add new invocations to the underlying test function using the list\n of argvalues for the given argnames. Parametrization is performed\n during the collection phase. If you need to setup expensive resources\n see about setting indirect to do it rather at test setup time.\n\n :arg argnames: a comma-separated string denoting one or more argument\n names, or a list/tuple of argument strings.\n\n :arg argvalues: The list of argvalues determines how often a\n test is invoked with different argument values. If only one\n argname was specified argvalues is a list of values. If N\n argnames were specified, argvalues must be a list of N-tuples,\n where each tuple-element specifies a value for its respective\n argname.\n\n :arg indirect: The list of argnames or boolean. A list of arguments'\n names (subset of argnames). If True the list contains all names from\n the argnames. Each argvalue corresponding to an argname in this list will\n be passed as request.param to its respective argname fixture\n function so that it can perform more expensive setups during the\n setup phase of a test rather than at collection time.\n\n :arg ids: list of string ids, or a callable.\n If strings, each is corresponding to the argvalues so that they are\n part of the test id. If None is given as id of specific test, the\n automatically generated id for that argument will be used.\n If callable, it should take one argument (a single argvalue) and return\n a string or return None. If None, the automatically generated id for that\n argument will be used.\n If no ids are provided they will be generated automatically from\n the argvalues.\n\n :arg scope: if specified it denotes the scope of the parameters.\n The scope is used for grouping tests by parameter instances.\n It will also override any fixture-function defined scope, allowing\n to set a dynamic scope using test context or configuration.\n \"\"\"\n from _pytest.fixtures import scope2index\n from _pytest.mark import ParameterSet\n\n argnames, parameters = ParameterSet._for_parametrize(\n argnames,\n argvalues,\n self.function,\n self.config,\n function_definition=self.definition,\n )\n del argvalues\n\n if scope is None:\n scope = _find_parametrized_scope(argnames, self._arg2fixturedefs, indirect)\n\n self._validate_if_using_arg_names(argnames, indirect)\n\n arg_values_types = self._resolve_arg_value_types(argnames, indirect)\n\n ids = self._resolve_arg_ids(argnames, ids, parameters, item=self.definition)\n\n scopenum = scope2index(\n scope, descr=\"parametrize() call in {}\".format(self.function.__name__)\n )\n\n # create the new calls: if we are parametrize() multiple times (by applying the decorator\n # more than once) then we accumulate those calls generating the cartesian product\n # of all calls\n newcalls = []\n for callspec in self._calls or [CallSpec2(self)]:\n for param_index, (param_id, param_set) in enumerate(zip(ids, parameters)):\n newcallspec = callspec.copy()\n newcallspec.setmulti2(\n arg_values_types,\n argnames,\n param_set.values,\n param_id,\n param_set.marks,\n scopenum,\n param_index,\n )\n newcalls.append(newcallspec)\n self._calls = newcalls\n\n def _resolve_arg_ids(self, argnames, ids, parameters, item):\n \"\"\"Resolves the actual ids for the given argnames, based on the ``ids`` parameter given\n to ``parametrize``.\n\n :param List[str] argnames: list of argument names passed to ``parametrize()``.\n :param ids: the ids parameter of the parametrized call (see docs).\n :param List[ParameterSet] parameters: the list of parameter values, same size as ``argnames``.\n :param Item item: the item that generated this parametrized call.\n :rtype: List[str]\n :return: the list of ids for each argname given\n \"\"\"\n from _pytest._io.saferepr import saferepr\n\n idfn = None\n if callable(ids):\n idfn = ids\n ids = None\n if ids:\n func_name = self.function.__name__\n if len(ids) != len(parameters):\n msg = \"In {}: {} parameter sets specified, with different number of ids: {}\"\n fail(msg.format(func_name, len(parameters), len(ids)), pytrace=False)\n for id_value in ids:\n if id_value is not None and not isinstance(id_value, six.string_types):\n msg = \"In {}: ids must be list of strings, found: {} (type: {!r})\"\n fail(\n msg.format(func_name, saferepr(id_value), type(id_value)),\n pytrace=False,\n )\n ids = idmaker(argnames, parameters, idfn, ids, self.config, item=item)\n return ids\n\n def _resolve_arg_value_types(self, argnames, indirect):\n \"\"\"Resolves if each parametrized argument must be considered a parameter to a fixture or a \"funcarg\"\n to the function, based on the ``indirect`` parameter of the parametrized() call.\n\n :param List[str] argnames: list of argument names passed to ``parametrize()``.\n :param indirect: same ``indirect`` parameter of ``parametrize()``.\n :rtype: Dict[str, str]\n A dict mapping each arg name to either:\n * \"params\" if the argname should be the parameter of a fixture of the same name.\n * \"funcargs\" if the argname should be a parameter to the parametrized test function.\n \"\"\"\n valtypes = {}\n if indirect is True:\n valtypes = dict.fromkeys(argnames, \"params\")\n elif indirect is False:\n valtypes = dict.fromkeys(argnames, \"funcargs\")\n elif isinstance(indirect, (tuple, list)):\n valtypes = dict.fromkeys(argnames, \"funcargs\")\n for arg in indirect:\n if arg not in argnames:\n fail(\n \"In {}: indirect fixture '{}' doesn't exist\".format(\n self.function.__name__, arg\n ),\n pytrace=False,\n )\n valtypes[arg] = \"params\"\n return valtypes\n\n def _validate_if_using_arg_names(self, argnames, indirect):\n \"\"\"\n Check if all argnames are being used, by default values, or directly/indirectly.\n\n :param List[str] argnames: list of argument names passed to ``parametrize()``.\n :param indirect: same ``indirect`` parameter of ``parametrize()``.\n :raise ValueError: if validation fails.\n \"\"\"\n default_arg_names = set(get_default_arg_names(self.function))\n func_name = self.function.__name__\n for arg in argnames:\n if arg not in self.fixturenames:\n if arg in default_arg_names:\n fail(\n \"In {}: function already takes an argument '{}' with a default value\".format(\n func_name, arg\n ),\n pytrace=False,\n )\n else:\n if isinstance(indirect, (tuple, list)):\n name = \"fixture\" if arg in indirect else \"argument\"\n else:\n name = \"fixture\" if indirect else \"argument\"\n fail(\n \"In {}: function uses no {} '{}'\".format(func_name, name, arg),\n pytrace=False,\n )"},{"col":0,"comment":"\n Verify tests are executed even when collection errors occur when the\n --continue-on-collection-errors flag is set\n ","endLoc":904,"header":"def test_continue_on_collection_errors(testdir)","id":4989,"name":"test_continue_on_collection_errors","nodeType":"Function","startLoc":892,"text":"def test_continue_on_collection_errors(testdir):\n \"\"\"\n Verify tests are executed even when collection errors occur when the\n --continue-on-collection-errors flag is set\n \"\"\"\n testdir.makepyfile(**COLLECTION_ERROR_PY_FILES)\n\n res = testdir.runpytest(\"--continue-on-collection-errors\")\n assert res.ret == 1\n\n res.stdout.fnmatch_lines(\n [\"collected 2 items / 2 errors\", \"*1 failed, 1 passed, 2 error*\"]\n )"},{"attributeType":"null","col":8,"comment":"null","endLoc":956,"id":4990,"name":"_arg2fixturedefs","nodeType":"Attribute","startLoc":956,"text":"self._arg2fixturedefs"},{"col":0,"comment":"\n Verify tests are executed even when collection errors occur and that maxfail\n is honoured (including the collection error count).\n 4 tests: 2 collection errors + 1 failure + 1 success\n test_4 is never executed because the test run is with --maxfail=3 which\n means it is interrupted after the 2 collection errors + 1 failure.\n ","endLoc":920,"header":"def test_continue_on_collection_errors_maxfail(testdir)","id":4991,"name":"test_continue_on_collection_errors_maxfail","nodeType":"Function","startLoc":907,"text":"def test_continue_on_collection_errors_maxfail(testdir):\n \"\"\"\n Verify tests are executed even when collection errors occur and that maxfail\n is honoured (including the collection error count).\n 4 tests: 2 collection errors + 1 failure + 1 success\n test_4 is never executed because the test run is with --maxfail=3 which\n means it is interrupted after the 2 collection errors + 1 failure.\n \"\"\"\n testdir.makepyfile(**COLLECTION_ERROR_PY_FILES)\n\n res = testdir.runpytest(\"--continue-on-collection-errors\", \"--maxfail=3\")\n assert res.ret == 1\n\n res.stdout.fnmatch_lines([\"collected 2 items / 2 errors\", \"*1 failed, 2 error*\"])"},{"col":0,"comment":"null","endLoc":1007,"header":"@pytest.mark.parametrize(\"fixture_name\", [\"record_property\", \"record_xml_attribute\"])\ndef test_record_fixtures_without_junitxml(testdir, fixture_name)","id":4992,"name":"test_record_fixtures_without_junitxml","nodeType":"Function","startLoc":996,"text":"@pytest.mark.parametrize(\"fixture_name\", [\"record_property\", \"record_xml_attribute\"])\ndef test_record_fixtures_without_junitxml(testdir, fixture_name):\n testdir.makepyfile(\n \"\"\"\n def test_record({fixture_name}):\n {fixture_name}(\"foo\", \"bar\")\n \"\"\".format(\n fixture_name=fixture_name\n )\n )\n result = testdir.runpytest()\n assert result.ret == 0"},{"col":0,"comment":"null","endLoc":1036,"header":"@pytest.mark.filterwarnings(\"default\")\ndef test_record_attribute(testdir)","id":4993,"name":"test_record_attribute","nodeType":"Function","startLoc":1010,"text":"@pytest.mark.filterwarnings(\"default\")\ndef test_record_attribute(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n junit_family = xunit1\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def other(record_xml_attribute):\n record_xml_attribute(\"bar\", 1)\n def test_record(record_xml_attribute, other):\n record_xml_attribute(\"foo\", \"<1\");\n \"\"\"\n )\n result, dom = runandparse(testdir, \"-rw\")\n node = dom.find_first_by_tag(\"testsuite\")\n tnode = node.find_first_by_tag(\"testcase\")\n tnode.assert_attr(bar=\"1\")\n tnode.assert_attr(foo=\"<1\")\n result.stdout.fnmatch_lines(\n [\"*test_record_attribute.py:6:*record_xml_attribute is an experimental feature\"]\n )"},{"col":0,"comment":"Regression test case for https://github.com/pytest-dev/pytest/issues/2836","endLoc":951,"header":"def test_fixture_scope_sibling_conftests(testdir)","id":4994,"name":"test_fixture_scope_sibling_conftests","nodeType":"Function","startLoc":923,"text":"def test_fixture_scope_sibling_conftests(testdir):\n \"\"\"Regression test case for https://github.com/pytest-dev/pytest/issues/2836\"\"\"\n foo_path = testdir.mkdir(\"foo\")\n foo_path.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import pytest\n @pytest.fixture\n def fix():\n return 1\n \"\"\"\n )\n )\n foo_path.join(\"test_foo.py\").write(\"def test_foo(fix): assert fix == 1\")\n\n # Tests in `food/` should not see the conftest fixture from `foo/`\n food_path = testdir.mkpydir(\"food\")\n food_path.join(\"test_food.py\").write(\"def test_food(fix): assert fix == 1\")\n\n res = testdir.runpytest()\n assert res.ret == 1\n\n res.stdout.fnmatch_lines(\n [\n \"*ERROR at setup of test_food*\",\n \"E*fixture 'fix' not found\",\n \"*1 passed, 1 error*\",\n ]\n )"},{"col":0,"comment":"Ensure record_xml_attribute and record_property drop values when outside of legacy family\n ","endLoc":1076,"header":"@pytest.mark.filterwarnings(\"default\")\n@pytest.mark.parametrize(\"fixture_name\", [\"record_xml_attribute\", \"record_property\"])\ndef test_record_fixtures_xunit2(testdir, fixture_name)","id":4995,"name":"test_record_fixtures_xunit2","nodeType":"Function","startLoc":1039,"text":"@pytest.mark.filterwarnings(\"default\")\n@pytest.mark.parametrize(\"fixture_name\", [\"record_xml_attribute\", \"record_property\"])\ndef test_record_fixtures_xunit2(testdir, fixture_name):\n \"\"\"Ensure record_xml_attribute and record_property drop values when outside of legacy family\n \"\"\"\n testdir.makeini(\n \"\"\"\n [pytest]\n junit_family = xunit2\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def other({fixture_name}):\n {fixture_name}(\"bar\", 1)\n def test_record({fixture_name}, other):\n {fixture_name}(\"foo\", \"<1\");\n \"\"\".format(\n fixture_name=fixture_name\n )\n )\n\n result, dom = runandparse(testdir, \"-rw\")\n expected_lines = []\n if fixture_name == \"record_xml_attribute\":\n expected_lines.append(\n \"*test_record_fixtures_xunit2.py:6:*record_xml_attribute is an experimental feature\"\n )\n expected_lines = [\n \"*test_record_fixtures_xunit2.py:6:*{fixture_name} is incompatible \"\n \"with junit_family 'xunit2' (use 'legacy' or 'xunit1')\".format(\n fixture_name=fixture_name\n )\n ]\n result.stdout.fnmatch_lines(expected_lines)"},{"col":0,"comment":"Check that we collect files from __init__.py files when they patch the 'python_files' (#3773)","endLoc":1012,"header":"def test_collect_init_tests(testdir)","id":4996,"name":"test_collect_init_tests","nodeType":"Function","startLoc":954,"text":"def test_collect_init_tests(testdir):\n \"\"\"Check that we collect files from __init__.py files when they patch the 'python_files' (#3773)\"\"\"\n p = testdir.copy_example(\"collect/collect_init_tests\")\n result = testdir.runpytest(p, \"--collect-only\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items\",\n \"\",\n \" \",\n \" \",\n \" \",\n ]\n )\n result = testdir.runpytest(\"./tests\", \"--collect-only\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items\",\n \"\",\n \" \",\n \" \",\n \" \",\n ]\n )\n # Ignores duplicates with \".\" and pkginit (#4310).\n result = testdir.runpytest(\"./tests\", \".\", \"--collect-only\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items\",\n \"\",\n \" \",\n \" \",\n \" \",\n \" \",\n ]\n )\n # Same as before, but different order.\n result = testdir.runpytest(\".\", \"tests\", \"--collect-only\")\n result.stdout.fnmatch_lines(\n [\n \"collected 2 items\",\n \"\",\n \" \",\n \" \",\n \" \",\n \" \",\n ]\n )\n result = testdir.runpytest(\"./tests/test_foo.py\", \"--collect-only\")\n result.stdout.fnmatch_lines(\n [\"\", \" \", \" \"]\n )\n assert \"test_init\" not in result.stdout.str()\n result = testdir.runpytest(\"./tests/__init__.py\", \"--collect-only\")\n result.stdout.fnmatch_lines(\n [\"\", \" \", \" \"]\n )\n assert \"test_foo\" not in result.stdout.str()"},{"col":0,"comment":"Check that we issue a proper message when we can't determine the signature of a test\n function (#4026).\n ","endLoc":1032,"header":"def test_collect_invalid_signature_message(testdir)","id":4997,"name":"test_collect_invalid_signature_message","nodeType":"Function","startLoc":1015,"text":"def test_collect_invalid_signature_message(testdir):\n \"\"\"Check that we issue a proper message when we can't determine the signature of a test\n function (#4026).\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n class TestCase:\n @pytest.fixture\n def fix():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"Could not determine arguments of *.fix *: invalid method signature\"]\n )"},{"col":0,"comment":"Handle proxy classes like Django's LazySettings that might raise on\n ``isinstance`` (#4266).\n ","endLoc":1059,"header":"def test_collect_handles_raising_on_dunder_class(testdir)","id":4998,"name":"test_collect_handles_raising_on_dunder_class","nodeType":"Function","startLoc":1035,"text":"def test_collect_handles_raising_on_dunder_class(testdir):\n \"\"\"Handle proxy classes like Django's LazySettings that might raise on\n ``isinstance`` (#4266).\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n class ImproperlyConfigured(Exception):\n pass\n\n class RaisesOnGetAttr(object):\n def raises(self):\n raise ImproperlyConfigured\n\n __class__ = property(raises)\n\n raises = RaisesOnGetAttr()\n\n\n def test_1():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed in*\"])\n assert result.ret == 0"},{"col":0,"comment":"null","endLoc":1095,"header":"def test_collect_with_chdir_during_import(testdir)","id":4999,"name":"test_collect_with_chdir_during_import","nodeType":"Function","startLoc":1062,"text":"def test_collect_with_chdir_during_import(testdir):\n subdir = testdir.tmpdir.mkdir(\"sub\")\n testdir.tmpdir.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\n import os\n os.chdir(%r)\n \"\"\"\n % (str(subdir),)\n )\n )\n testdir.makepyfile(\n \"\"\"\n def test_1():\n import os\n assert os.getcwd() == %r\n \"\"\"\n % (str(subdir),)\n )\n with testdir.tmpdir.as_cwd():\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed in*\"])\n assert result.ret == 0\n\n # Handles relative testpaths.\n testdir.makeini(\n \"\"\"\n [pytest]\n testpaths = .\n \"\"\"\n )\n with testdir.tmpdir.as_cwd():\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"collected 1 item\"])"},{"col":0,"comment":"xdist calls pytest_runtest_logreport as they are executed by the slaves,\n with nodes from several nodes overlapping, so junitxml must cope with that\n to produce correct reports. #1064\n ","endLoc":1101,"header":"def test_random_report_log_xdist(testdir, monkeypatch)","id":5000,"name":"test_random_report_log_xdist","nodeType":"Function","startLoc":1079,"text":"def test_random_report_log_xdist(testdir, monkeypatch):\n \"\"\"xdist calls pytest_runtest_logreport as they are executed by the slaves,\n with nodes from several nodes overlapping, so junitxml must cope with that\n to produce correct reports. #1064\n \"\"\"\n pytest.importorskip(\"xdist\")\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n testdir.makepyfile(\n \"\"\"\n import pytest, time\n @pytest.mark.parametrize('i', list(range(30)))\n def test_x(i):\n assert i != 22\n \"\"\"\n )\n _, dom = runandparse(testdir, \"-n2\")\n suite_node = dom.find_first_by_tag(\"testsuite\")\n failed = []\n for case_node in suite_node.find_by_tag(\"testcase\"):\n if case_node.find_first_by_tag(\"failure\"):\n failed.append(case_node[\"name\"])\n\n assert failed == [\"test_x[22]\"]"},{"col":0,"comment":"Suppress IOError when closing the temporary file used for capturing streams in py27 (#2370)","endLoc":850,"header":"def _attempt_to_close_capture_file(f)","id":5001,"name":"_attempt_to_close_capture_file","nodeType":"Function","startLoc":842,"text":"def _attempt_to_close_capture_file(f):\n \"\"\"Suppress IOError when closing the temporary file used for capturing streams in py27 (#2370)\"\"\"\n if six.PY2:\n try:\n f.close()\n except IOError:\n pass\n else:\n f.close()"},{"col":0,"comment":"null","endLoc":1115,"header":"def test_runs_twice(testdir)","id":5002,"name":"test_runs_twice","nodeType":"Function","startLoc":1104,"text":"def test_runs_twice(testdir):\n f = testdir.makepyfile(\n \"\"\"\n def test_pass():\n pass\n \"\"\"\n )\n\n result, dom = runandparse(testdir, f, f)\n assert \"INTERNALERROR\" not in result.stdout.str()\n first, second = [x[\"classname\"] for x in dom.find_by_tag(\"testcase\")]\n assert first == second"},{"col":0,"comment":"null","endLoc":1131,"header":"@pytest.mark.xfail(reason=\"hangs\", run=False)\ndef test_runs_twice_xdist(testdir)","id":5003,"name":"test_runs_twice_xdist","nodeType":"Function","startLoc":1118,"text":"@pytest.mark.xfail(reason=\"hangs\", run=False)\ndef test_runs_twice_xdist(testdir):\n pytest.importorskip(\"xdist\")\n f = testdir.makepyfile(\n \"\"\"\n def test_pass():\n pass\n \"\"\"\n )\n\n result, dom = runandparse(testdir, f, \"--dist\", \"each\", \"--tx\", \"2*popen\")\n assert \"INTERNALERROR\" not in result.stdout.str()\n first, second = [x[\"classname\"] for x in dom.find_by_tag(\"testcase\")]\n assert first == second"},{"col":4,"comment":"null","endLoc":617,"header":"def suspend(self)","id":5004,"name":"suspend","nodeType":"Function","startLoc":614,"text":"def suspend(self):\n self.syscapture.suspend()\n os.dup2(self.targetfd_save, self.targetfd)\n self._state = \"suspended\""},{"col":4,"comment":"null","endLoc":622,"header":"def resume(self)","id":5005,"name":"resume","nodeType":"Function","startLoc":619,"text":"def resume(self):\n self.syscapture.resume()\n os.dup2(self.tmpfile_fd, self.targetfd)\n self._state = \"resumed\""},{"attributeType":"bytes","col":4,"comment":"null","endLoc":553,"id":5006,"name":"EMPTY_BUFFER","nodeType":"Attribute","startLoc":553,"text":"EMPTY_BUFFER"},{"attributeType":"None","col":4,"comment":"null","endLoc":554,"id":5007,"name":"_state","nodeType":"Attribute","startLoc":554,"text":"_state"},{"attributeType":"NoCapture","col":20,"comment":"null","endLoc":576,"id":5008,"name":"syscapture","nodeType":"Attribute","startLoc":576,"text":"self.syscapture"},{"attributeType":"str","col":8,"comment":"null","endLoc":595,"id":5009,"name":"_state","nodeType":"Attribute","startLoc":595,"text":"self._state"},{"attributeType":"int","col":12,"comment":"null","endLoc":559,"id":5010,"name":"targetfd_save","nodeType":"Attribute","startLoc":559,"text":"self.targetfd_save"},{"attributeType":"{__eq__}","col":8,"comment":"null","endLoc":557,"id":5011,"name":"targetfd","nodeType":"Attribute","startLoc":557,"text":"self.targetfd"},{"col":4,"comment":"null","endLoc":588,"header":"def _write_report_lines_from_hooks(self, lines)","id":5012,"name":"_write_report_lines_from_hooks","nodeType":"Function","startLoc":585,"text":"def _write_report_lines_from_hooks(self, lines):\n lines.reverse()\n for line in collapse(lines):\n self.write_line(line)"},{"col":4,"comment":"null","endLoc":605,"header":"def pytest_report_header(self, config)","id":5013,"name":"pytest_report_header","nodeType":"Function","startLoc":590,"text":"def pytest_report_header(self, config):\n line = \"rootdir: %s\" % config.rootdir\n\n if config.inifile:\n line += \", inifile: \" + config.rootdir.bestrelpath(config.inifile)\n\n testpaths = config.getini(\"testpaths\")\n if testpaths and config.args == testpaths:\n rel_paths = [config.rootdir.bestrelpath(x) for x in testpaths]\n line += \", testpaths: {}\".format(\", \".join(rel_paths))\n result = [line]\n\n plugininfo = config.pluginmanager.list_plugin_distinfo()\n if plugininfo:\n result.append(\"plugins: %s\" % \", \".join(_plugin_nameversions(plugininfo)))\n return result"},{"attributeType":"function","col":12,"comment":"null","endLoc":561,"id":5014,"name":"start","nodeType":"Attribute","startLoc":561,"text":"self.start"},{"col":0,"comment":"null","endLoc":1183,"header":"def test_fancy_items_regression(testdir)","id":5015,"name":"test_fancy_items_regression","nodeType":"Function","startLoc":1134,"text":"def test_fancy_items_regression(testdir):\n # issue 1259\n testdir.makeconftest(\n \"\"\"\n import pytest\n class FunItem(pytest.Item):\n def runtest(self):\n pass\n class NoFunItem(pytest.Item):\n def runtest(self):\n pass\n\n class FunCollector(pytest.File):\n def collect(self):\n return [\n FunItem('a', self),\n NoFunItem('a', self),\n NoFunItem('b', self),\n ]\n\n def pytest_collect_file(path, parent):\n if path.check(ext='.py'):\n return FunCollector(path, parent)\n \"\"\"\n )\n\n testdir.makepyfile(\n \"\"\"\n def test_pass():\n pass\n \"\"\"\n )\n\n result, dom = runandparse(testdir)\n\n assert \"INTERNALERROR\" not in result.stdout.str()\n\n items = sorted(\"%(classname)s %(name)s\" % x for x in dom.find_by_tag(\"testcase\"))\n import pprint\n\n pprint.pprint(items)\n assert items == [\n u\"conftest a\",\n u\"conftest a\",\n u\"conftest b\",\n u\"test_fancy_items_regression a\",\n u\"test_fancy_items_regression a\",\n u\"test_fancy_items_regression b\",\n u\"test_fancy_items_regression test_pass\",\n ]"},{"attributeType":"function","col":12,"comment":"null","endLoc":562,"id":5016,"name":"done","nodeType":"Attribute","startLoc":562,"text":"self.done"},{"attributeType":"int","col":12,"comment":"null","endLoc":578,"id":5017,"name":"tmpfile_fd","nodeType":"Attribute","startLoc":578,"text":"self.tmpfile_fd"},{"col":0,"comment":"null","endLoc":1217,"header":"def test_global_properties(testdir)","id":5018,"name":"test_global_properties","nodeType":"Function","startLoc":1186,"text":"def test_global_properties(testdir):\n path = testdir.tmpdir.join(\"test_global_properties.xml\")\n log = LogXML(str(path), None)\n\n class Report(BaseReport):\n sections = []\n nodeid = \"test_node_id\"\n\n log.pytest_sessionstart()\n log.add_global_property(\"foo\", 1)\n log.add_global_property(\"bar\", 2)\n log.pytest_sessionfinish()\n\n dom = minidom.parse(str(path))\n\n properties = dom.getElementsByTagName(\"properties\")\n\n assert properties.length == 1, \"There must be one node\"\n\n property_list = dom.getElementsByTagName(\"property\")\n\n assert property_list.length == 2, \"There most be only 2 property nodes\"\n\n expected = {\"foo\": \"1\", \"bar\": \"2\"}\n actual = {}\n\n for p in property_list:\n k = str(p.getAttribute(\"name\"))\n v = str(p.getAttribute(\"value\"))\n actual[k] = v\n\n assert actual == expected"},{"attributeType":"TextIO | {fileno} | EncodedFile | {fileno}","col":12,"comment":"null","endLoc":577,"id":5019,"name":"tmpfile","nodeType":"Attribute","startLoc":577,"text":"self.tmpfile"},{"col":0,"comment":"null","endLoc":1085,"header":"def _plugin_nameversions(plugininfo)","id":5020,"name":"_plugin_nameversions","nodeType":"Function","startLoc":1073,"text":"def _plugin_nameversions(plugininfo):\n values = []\n for plugin, dist in plugininfo:\n # gets us name and version!\n name = \"{dist.project_name}-{dist.version}\".format(dist=dist)\n # questionable convenience, but it keeps things short\n if name.startswith(\"pytest-\"):\n name = name[7:]\n # we decided to print python package names\n # they can have more than one plugin\n if name not in values:\n values.append(name)\n return values"},{"attributeType":"set","col":8,"comment":"null","endLoc":955,"id":5021,"name":"_ids","nodeType":"Attribute","startLoc":955,"text":"self._ids"},{"attributeType":"null","col":8,"comment":"null","endLoc":949,"id":5022,"name":"fixturenames","nodeType":"Attribute","startLoc":949,"text":"self.fixturenames"},{"col":0,"comment":"null","endLoc":1117,"header":"def test_collect_pyargs_with_testpaths(testdir, monkeypatch)","id":5023,"name":"test_collect_pyargs_with_testpaths","nodeType":"Function","startLoc":1098,"text":"def test_collect_pyargs_with_testpaths(testdir, monkeypatch):\n testmod = testdir.mkdir(\"testmod\")\n # NOTE: __init__.py is not collected since it does not match python_files.\n testmod.ensure(\"__init__.py\").write(\"def test_func(): pass\")\n testmod.ensure(\"test_file.py\").write(\"def test_func(): pass\")\n\n root = testdir.mkdir(\"root\")\n root.ensure(\"pytest.ini\").write(\n textwrap.dedent(\n \"\"\"\n [pytest]\n addopts = --pyargs\n testpaths = testmod\n \"\"\"\n )\n )\n monkeypatch.setenv(\"PYTHONPATH\", str(testdir.tmpdir), prepend=os.pathsep)\n with root.as_cwd():\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*1 passed in*\"])"},{"className":"FDCapture","col":0,"comment":"Capture IO to/from a given os-level filedescriptor.\n\n snap() produces text\n ","endLoc":644,"id":5024,"nodeType":"Class","startLoc":631,"text":"class FDCapture(FDCaptureBinary):\n \"\"\"Capture IO to/from a given os-level filedescriptor.\n\n snap() produces text\n \"\"\"\n\n EMPTY_BUFFER = str()\n\n def snap(self):\n res = super(FDCapture, self).snap()\n enc = getattr(self.tmpfile, \"encoding\", None)\n if enc and isinstance(res, bytes):\n res = six.text_type(res, enc, \"replace\")\n return res"},{"attributeType":"str","col":4,"comment":"null","endLoc":637,"id":5025,"name":"EMPTY_BUFFER","nodeType":"Attribute","startLoc":637,"text":"EMPTY_BUFFER"},{"attributeType":"null","col":8,"comment":"null","endLoc":943,"id":5026,"name":"module","nodeType":"Attribute","startLoc":943,"text":"self.module"},{"attributeType":"None","col":8,"comment":"null","endLoc":946,"id":5027,"name":"function","nodeType":"Attribute","startLoc":946,"text":"self.function"},{"col":0,"comment":"Test that collecting a direct symlink, where the target does not match python_files works (#4325).","endLoc":1136,"header":"@pytest.mark.skipif(\n not hasattr(py.path.local, \"mksymlinkto\"),\n reason=\"symlink not available on this platform\",\n)\ndef test_collect_symlink_file_arg(testdir)","id":5028,"name":"test_collect_symlink_file_arg","nodeType":"Function","startLoc":1120,"text":"@pytest.mark.skipif(\n not hasattr(py.path.local, \"mksymlinkto\"),\n reason=\"symlink not available on this platform\",\n)\ndef test_collect_symlink_file_arg(testdir):\n \"\"\"Test that collecting a direct symlink, where the target does not match python_files works (#4325).\"\"\"\n real = testdir.makepyfile(\n real=\"\"\"\n def test_nodeid(request):\n assert request.node.nodeid == \"real.py::test_nodeid\"\n \"\"\"\n )\n symlink = testdir.tmpdir.join(\"symlink.py\")\n symlink.mksymlinkto(real)\n result = testdir.runpytest(\"-v\", symlink)\n result.stdout.fnmatch_lines([\"real.py::test_nodeid PASSED*\", \"*1 passed in*\"])\n assert result.ret == 0"},{"className":"SysCapture","col":0,"comment":"null","endLoc":697,"id":5029,"nodeType":"Class","startLoc":647,"text":"class SysCapture(object):\n\n EMPTY_BUFFER = str()\n _state = None\n\n def __init__(self, fd, tmpfile=None):\n name = patchsysdict[fd]\n self._old = getattr(sys, name)\n self.name = name\n if tmpfile is None:\n if name == \"stdin\":\n tmpfile = DontReadFromInput()\n else:\n tmpfile = CaptureIO()\n self.tmpfile = tmpfile\n\n def __repr__(self):\n return \"\" % (\n self.name,\n self._old,\n self.tmpfile,\n self._state,\n )\n\n def start(self):\n setattr(sys, self.name, self.tmpfile)\n self._state = \"started\"\n\n def snap(self):\n res = self.tmpfile.getvalue()\n self.tmpfile.seek(0)\n self.tmpfile.truncate()\n return res\n\n def done(self):\n setattr(sys, self.name, self._old)\n del self._old\n _attempt_to_close_capture_file(self.tmpfile)\n self._state = \"done\"\n\n def suspend(self):\n setattr(sys, self.name, self._old)\n self._state = \"suspended\"\n\n def resume(self):\n setattr(sys, self.name, self.tmpfile)\n self._state = \"resumed\"\n\n def writeorg(self, data):\n self._old.write(data)\n self._old.flush()"},{"col":4,"comment":"null","endLoc":669,"header":"def __repr__(self)","id":5030,"name":"__repr__","nodeType":"Function","startLoc":663,"text":"def __repr__(self):\n return \"\" % (\n self.name,\n self._old,\n self.tmpfile,\n self._state,\n )"},{"col":4,"comment":"null","endLoc":673,"header":"def start(self)","id":5031,"name":"start","nodeType":"Function","startLoc":671,"text":"def start(self):\n setattr(sys, self.name, self.tmpfile)\n self._state = \"started\""},{"col":4,"comment":"null","endLoc":679,"header":"def snap(self)","id":5032,"name":"snap","nodeType":"Function","startLoc":675,"text":"def snap(self):\n res = self.tmpfile.getvalue()\n self.tmpfile.seek(0)\n self.tmpfile.truncate()\n return res"},{"col":0,"comment":"Test collection of symlink via out-of-tree rootdir.","endLoc":1169,"header":"@pytest.mark.skipif(\n not hasattr(py.path.local, \"mksymlinkto\"),\n reason=\"symlink not available on this platform\",\n)\ndef test_collect_symlink_out_of_tree(testdir)","id":5033,"name":"test_collect_symlink_out_of_tree","nodeType":"Function","startLoc":1139,"text":"@pytest.mark.skipif(\n not hasattr(py.path.local, \"mksymlinkto\"),\n reason=\"symlink not available on this platform\",\n)\ndef test_collect_symlink_out_of_tree(testdir):\n \"\"\"Test collection of symlink via out-of-tree rootdir.\"\"\"\n sub = testdir.tmpdir.join(\"sub\")\n real = sub.join(\"test_real.py\")\n real.write(\n textwrap.dedent(\n \"\"\"\n def test_nodeid(request):\n # Should not contain sub/ prefix.\n assert request.node.nodeid == \"test_real.py::test_nodeid\"\n \"\"\"\n ),\n ensure=True,\n )\n\n out_of_tree = testdir.tmpdir.join(\"out_of_tree\").ensure(dir=True)\n symlink_to_sub = out_of_tree.join(\"symlink_to_sub\")\n symlink_to_sub.mksymlinkto(sub)\n sub.chdir()\n result = testdir.runpytest(\"-vs\", \"--rootdir=%s\" % sub, symlink_to_sub)\n result.stdout.fnmatch_lines(\n [\n # Should not contain \"sub/\"!\n \"test_real.py::test_nodeid PASSED\"\n ]\n )\n assert result.ret == 0"},{"col":0,"comment":"collect_ignore in parent conftest skips importing child (issue #4592).","endLoc":1182,"header":"def test_collectignore_via_conftest(testdir, monkeypatch)","id":5034,"name":"test_collectignore_via_conftest","nodeType":"Function","startLoc":1172,"text":"def test_collectignore_via_conftest(testdir, monkeypatch):\n \"\"\"collect_ignore in parent conftest skips importing child (issue #4592).\"\"\"\n tests = testdir.mkpydir(\"tests\")\n tests.ensure(\"conftest.py\").write(\"collect_ignore = ['ignore_me']\")\n\n ignore_me = tests.mkdir(\"ignore_me\")\n ignore_me.ensure(\"__init__.py\")\n ignore_me.ensure(\"conftest.py\").write(\"assert 0, 'should_not_be_called'\")\n\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED"},{"col":0,"comment":"null","endLoc":1211,"header":"def test_collect_pkg_init_and_file_in_args(testdir)","id":5035,"name":"test_collect_pkg_init_and_file_in_args","nodeType":"Function","startLoc":1185,"text":"def test_collect_pkg_init_and_file_in_args(testdir):\n subdir = testdir.mkdir(\"sub\")\n init = subdir.ensure(\"__init__.py\")\n init.write(\"def test_init(): pass\")\n p = subdir.ensure(\"test_file.py\")\n p.write(\"def test_file(): pass\")\n\n # NOTE: without \"-o python_files=*.py\" this collects test_file.py twice.\n # This changed/broke with \"Add package scoped fixtures #2283\" (2b1410895)\n # initially (causing a RecursionError).\n result = testdir.runpytest(\"-v\", str(init), str(p))\n result.stdout.fnmatch_lines(\n [\n \"sub/test_file.py::test_file PASSED*\",\n \"sub/test_file.py::test_file PASSED*\",\n \"*2 passed in*\",\n ]\n )\n\n result = testdir.runpytest(\"-v\", \"-o\", \"python_files=*.py\", str(init), str(p))\n result.stdout.fnmatch_lines(\n [\n \"sub/__init__.py::test_init PASSED*\",\n \"sub/test_file.py::test_file PASSED*\",\n \"*2 passed in*\",\n ]\n )"},{"attributeType":"{obj} | FunctionDefinition","col":8,"comment":"null","endLoc":937,"id":5036,"name":"definition","nodeType":"Attribute","startLoc":937,"text":"self.definition"},{"attributeType":"null","col":8,"comment":"null","endLoc":952,"id":5037,"name":"cls","nodeType":"Attribute","startLoc":952,"text":"self.cls"},{"attributeType":"list","col":8,"comment":"null","endLoc":954,"id":5038,"name":"_calls","nodeType":"Attribute","startLoc":954,"text":"self._calls"},{"attributeType":"null","col":8,"comment":"null","endLoc":940,"id":5039,"name":"config","nodeType":"Attribute","startLoc":940,"text":"self.config"},{"className":"FunctionDefinition","col":0,"comment":"\n internal hack until we get actual definition nodes instead of the\n crappy metafunc hack\n ","endLoc":1480,"id":5040,"nodeType":"Class","startLoc":1471,"text":"class FunctionDefinition(Function):\n \"\"\"\n internal hack until we get actual definition nodes instead of the\n crappy metafunc hack\n \"\"\"\n\n def runtest(self):\n raise RuntimeError(\"function definitions are not supposed to be used\")\n\n setup = runtest"},{"col":4,"comment":"null","endLoc":1478,"header":"def runtest(self)","id":5041,"name":"runtest","nodeType":"Function","startLoc":1477,"text":"def runtest(self):\n raise RuntimeError(\"function definitions are not supposed to be used\")"},{"col":4,"comment":"null","endLoc":685,"header":"def done(self)","id":5042,"name":"done","nodeType":"Function","startLoc":681,"text":"def done(self):\n setattr(sys, self.name, self._old)\n del self._old\n _attempt_to_close_capture_file(self.tmpfile)\n self._state = \"done\""},{"attributeType":"function","col":4,"comment":"null","endLoc":1480,"id":5043,"name":"setup","nodeType":"Attribute","startLoc":1480,"text":"setup"},{"col":0,"comment":"null","endLoc":61,"header":"def pyobj_property(name)","id":5044,"name":"pyobj_property","nodeType":"Function","startLoc":52,"text":"def pyobj_property(name):\n def get(self):\n node = self.getparent(getattr(__import__(\"pytest\"), name))\n if node is not None:\n return node.obj\n\n doc = \"python %s object this node was collected from (can be None).\" % (\n name.lower(),\n )\n return property(get, None, None, doc)"},{"col":4,"comment":"null","endLoc":689,"header":"def suspend(self)","id":5045,"name":"suspend","nodeType":"Function","startLoc":687,"text":"def suspend(self):\n setattr(sys, self.name, self._old)\n self._state = \"suspended\""},{"col":4,"comment":"null","endLoc":693,"header":"def resume(self)","id":5046,"name":"resume","nodeType":"Function","startLoc":691,"text":"def resume(self):\n setattr(sys, self.name, self.tmpfile)\n self._state = \"resumed\""},{"col":4,"comment":"null","endLoc":697,"header":"def writeorg(self, data)","id":5047,"name":"writeorg","nodeType":"Function","startLoc":695,"text":"def writeorg(self, data):\n self._old.write(data)\n self._old.flush()"},{"attributeType":"str","col":4,"comment":"null","endLoc":649,"id":5048,"name":"EMPTY_BUFFER","nodeType":"Attribute","startLoc":649,"text":"EMPTY_BUFFER"},{"attributeType":"None","col":4,"comment":"null","endLoc":650,"id":5049,"name":"_state","nodeType":"Attribute","startLoc":650,"text":"_state"},{"attributeType":"null","col":8,"comment":"null","endLoc":654,"id":5050,"name":"_old","nodeType":"Attribute","startLoc":654,"text":"self._old"},{"attributeType":"str","col":8,"comment":"null","endLoc":673,"id":5051,"name":"_state","nodeType":"Attribute","startLoc":673,"text":"self._state"},{"attributeType":"str","col":8,"comment":"null","endLoc":655,"id":5052,"name":"name","nodeType":"Attribute","startLoc":655,"text":"self.name"},{"attributeType":"DontReadFromInput | CaptureIO | CaptureIO","col":8,"comment":"null","endLoc":661,"id":5053,"name":"tmpfile","nodeType":"Attribute","startLoc":661,"text":"self.tmpfile"},{"className":"SysCaptureBinary","col":0,"comment":"null","endLoc":707,"id":5054,"nodeType":"Class","startLoc":700,"text":"class SysCaptureBinary(SysCapture):\n EMPTY_BUFFER = b\"\"\n\n def snap(self):\n res = self.tmpfile.buffer.getvalue()\n self.tmpfile.seek(0)\n self.tmpfile.truncate()\n return res"},{"col":4,"comment":"null","endLoc":707,"header":"def snap(self)","id":5055,"name":"snap","nodeType":"Function","startLoc":703,"text":"def snap(self):\n res = self.tmpfile.buffer.getvalue()\n self.tmpfile.seek(0)\n self.tmpfile.truncate()\n return res"},{"col":0,"comment":"null","endLoc":1223,"header":"def test_collect_pkg_init_only(testdir)","id":5056,"name":"test_collect_pkg_init_only","nodeType":"Function","startLoc":1214,"text":"def test_collect_pkg_init_only(testdir):\n subdir = testdir.mkdir(\"sub\")\n init = subdir.ensure(\"__init__.py\")\n init.write(\"def test_init(): pass\")\n\n result = testdir.runpytest(str(init))\n result.stdout.fnmatch_lines([\"*no tests ran in*\"])\n\n result = testdir.runpytest(\"-v\", \"-o\", \"python_files=*.py\", str(init))\n result.stdout.fnmatch_lines([\"sub/__init__.py::test_init PASSED*\", \"*1 passed in*\"])"},{"col":0,"comment":"null","endLoc":116,"header":"def pytest_addoption(parser)","id":5057,"name":"pytest_addoption","nodeType":"Function","startLoc":64,"text":"def pytest_addoption(parser):\n group = parser.getgroup(\"general\")\n group.addoption(\n \"--fixtures\",\n \"--funcargs\",\n action=\"store_true\",\n dest=\"showfixtures\",\n default=False,\n help=\"show available fixtures, sorted by plugin appearance \"\n \"(fixtures with leading '_' are only shown with '-v')\",\n )\n group.addoption(\n \"--fixtures-per-test\",\n action=\"store_true\",\n dest=\"show_fixtures_per_test\",\n default=False,\n help=\"show fixtures per test\",\n )\n parser.addini(\n \"python_files\",\n type=\"args\",\n # NOTE: default is also used in AssertionRewritingHook.\n default=[\"test_*.py\", \"*_test.py\"],\n help=\"glob-style file patterns for Python test module discovery\",\n )\n parser.addini(\n \"python_classes\",\n type=\"args\",\n default=[\"Test\"],\n help=\"prefixes or glob names for Python test class discovery\",\n )\n parser.addini(\n \"python_functions\",\n type=\"args\",\n default=[\"test\"],\n help=\"prefixes or glob names for Python test function and method discovery\",\n )\n parser.addini(\n \"disable_test_id_escaping_and_forfeit_all_rights_to_community_support\",\n type=\"bool\",\n default=False,\n help=\"disable string escape non-ascii characters, might cause unwanted \"\n \"side effects(use at your own risk)\",\n )\n\n group.addoption(\n \"--import-mode\",\n default=\"prepend\",\n choices=[\"prepend\", \"append\"],\n dest=\"importmode\",\n help=\"prepend/append to sys.path when importing test modules, \"\n \"default is to prepend.\",\n )"},{"col":0,"comment":"null","endLoc":125,"header":"def pytest_cmdline_main(config)","id":5058,"name":"pytest_cmdline_main","nodeType":"Function","startLoc":119,"text":"def pytest_cmdline_main(config):\n if config.option.showfixtures:\n showfixtures(config)\n return 0\n if config.option.show_fixtures_per_test:\n show_fixtures_per_test(config)\n return 0"},{"col":0,"comment":"null","endLoc":1297,"header":"def showfixtures(config)","id":5059,"name":"showfixtures","nodeType":"Function","startLoc":1294,"text":"def showfixtures(config):\n from _pytest.main import wrap_session\n\n return wrap_session(config, _showfixtures_main)"},{"col":0,"comment":"null","endLoc":1239,"header":"def show_fixtures_per_test(config)","id":5060,"name":"show_fixtures_per_test","nodeType":"Function","startLoc":1236,"text":"def show_fixtures_per_test(config):\n from _pytest.main import wrap_session\n\n return wrap_session(config, _show_fixtures_per_test)"},{"col":0,"comment":"null","endLoc":137,"header":"def pytest_generate_tests(metafunc)","id":5061,"name":"pytest_generate_tests","nodeType":"Function","startLoc":128,"text":"def pytest_generate_tests(metafunc):\n # those alternative spellings are common - raise a specific error to alert\n # the user\n alt_spellings = [\"parameterize\", \"parametrise\", \"parameterise\"]\n for mark_name in alt_spellings:\n if metafunc.definition.get_closest_marker(mark_name):\n msg = \"{0} has '{1}' mark, spelling should be 'parametrize'\"\n fail(msg.format(metafunc.function.__name__, mark_name), pytrace=False)\n for marker in metafunc.definition.iter_markers(name=\"parametrize\"):\n metafunc.parametrize(*marker.args, **marker.kwargs)"},{"col":4,"comment":"null","endLoc":622,"header":"def pytest_collection_finish(self, session)","id":5062,"name":"pytest_collection_finish","nodeType":"Function","startLoc":607,"text":"def pytest_collection_finish(self, session):\n self.report_collect(True)\n\n if self.config.getoption(\"collectonly\"):\n self._printcollecteditems(session.items)\n\n lines = self.config.hook.pytest_report_collectionfinish(\n config=self.config, startdir=self.startdir, items=session.items\n )\n self._write_report_lines_from_hooks(lines)\n\n if self.config.getoption(\"collectonly\"):\n if self.stats.get(\"failed\"):\n self._tw.sep(\"!\", \"collection failures\")\n for rep in self.stats.get(\"failed\"):\n rep.toterminal(self._tw)"},{"col":0,"comment":"null","endLoc":1250,"header":"@pytest.mark.skipif(\n not hasattr(py.path.local, \"mksymlinkto\"),\n reason=\"symlink not available on this platform\",\n)\n@pytest.mark.parametrize(\"use_pkg\", (True, False))\ndef test_collect_sub_with_symlinks(use_pkg, testdir)","id":5063,"name":"test_collect_sub_with_symlinks","nodeType":"Function","startLoc":1226,"text":"@pytest.mark.skipif(\n not hasattr(py.path.local, \"mksymlinkto\"),\n reason=\"symlink not available on this platform\",\n)\n@pytest.mark.parametrize(\"use_pkg\", (True, False))\ndef test_collect_sub_with_symlinks(use_pkg, testdir):\n sub = testdir.mkdir(\"sub\")\n if use_pkg:\n sub.ensure(\"__init__.py\")\n sub.ensure(\"test_file.py\").write(\"def test_file(): pass\")\n\n # Create a broken symlink.\n sub.join(\"test_broken.py\").mksymlinkto(\"test_doesnotexist.py\")\n\n # Symlink that gets collected.\n sub.join(\"test_symlink.py\").mksymlinkto(\"test_file.py\")\n\n result = testdir.runpytest(\"-v\", str(sub))\n result.stdout.fnmatch_lines(\n [\n \"sub/test_file.py::test_file PASSED*\",\n \"sub/test_symlink.py::test_file PASSED*\",\n \"*2 passed in*\",\n ]\n )"},{"col":0,"comment":"null","endLoc":157,"header":"def pytest_configure(config)","id":5064,"name":"pytest_configure","nodeType":"Function","startLoc":140,"text":"def pytest_configure(config):\n config.addinivalue_line(\n \"markers\",\n \"parametrize(argnames, argvalues): call a test function multiple \"\n \"times passing in different arguments in turn. argvalues generally \"\n \"needs to be a list of values if argnames specifies only one name \"\n \"or a list of tuples of values if argnames specifies multiple names. \"\n \"Example: @parametrize('arg1', [1,2]) would lead to two calls of the \"\n \"decorated test function, one with arg1=1 and another with arg1=2.\"\n \"see https://docs.pytest.org/en/latest/parametrize.html for more info \"\n \"and examples.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"usefixtures(fixturename1, fixturename2, ...): mark tests as needing \"\n \"all of the specified fixtures. see \"\n \"https://docs.pytest.org/en/latest/fixture.html#usefixtures \",\n )"},{"col":0,"comment":"null","endLoc":175,"header":"@hookimpl(trylast=True)\ndef pytest_pyfunc_call(pyfuncitem)","id":5065,"name":"pytest_pyfunc_call","nodeType":"Function","startLoc":160,"text":"@hookimpl(trylast=True)\ndef pytest_pyfunc_call(pyfuncitem):\n testfunction = pyfuncitem.obj\n iscoroutinefunction = getattr(inspect, \"iscoroutinefunction\", None)\n if iscoroutinefunction is not None and iscoroutinefunction(testfunction):\n msg = \"Coroutine functions are not natively supported and have been skipped.\\n\"\n msg += \"You need to install a suitable plugin for your async framework, for example:\\n\"\n msg += \" - pytest-asyncio\\n\"\n msg += \" - pytest-trio\\n\"\n msg += \" - pytest-tornasync\"\n warnings.warn(PytestUnhandledCoroutineWarning(msg.format(pyfuncitem.nodeid)))\n skip(msg=\"coroutine function and no async plugin installed (see warnings)\")\n funcargs = pyfuncitem.funcargs\n testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames}\n testfunction(**testargs)\n return True"},{"col":0,"comment":"null","endLoc":1267,"header":"def test_collector_respects_tbstyle(testdir)","id":5066,"name":"test_collector_respects_tbstyle","nodeType":"Function","startLoc":1253,"text":"def test_collector_respects_tbstyle(testdir):\n p1 = testdir.makepyfile(\"assert 0\")\n result = testdir.runpytest(p1, \"--tb=native\")\n assert result.ret == EXIT_INTERRUPTED\n result.stdout.fnmatch_lines(\n [\n \"*_ ERROR collecting test_collector_respects_tbstyle.py _*\",\n \"Traceback (most recent call last):\",\n ' File \"*/test_collector_respects_tbstyle.py\", line 1, in ',\n \" assert 0\",\n \"AssertionError: assert 0\",\n \"*! Interrupted: 1 errors during collection !*\",\n \"*= 1 error in *\",\n ]\n )"},{"attributeType":"TypedDict","col":0,"comment":"null","endLoc":814,"id":5067,"name":"COLLECTION_ERROR_PY_FILES","nodeType":"Attribute","startLoc":814,"text":"COLLECTION_ERROR_PY_FILES"},{"col":0,"comment":"null","endLoc":187,"header":"def pytest_collect_file(path, parent)","id":5068,"name":"pytest_collect_file","nodeType":"Function","startLoc":178,"text":"def pytest_collect_file(path, parent):\n ext = path.ext\n if ext == \".py\":\n if not parent.session.isinitpath(path):\n if not path_matches_patterns(\n path, parent.config.getini(\"python_files\") + [\"__init__.py\"]\n ):\n return\n ihook = parent.session.gethookproxy(path)\n return ihook.pytest_pycollect_makemodule(path=path, parent=parent)"},{"col":4,"comment":"null","endLoc":657,"header":"def _printcollecteditems(self, items)","id":5075,"name":"_printcollecteditems","nodeType":"Function","startLoc":624,"text":"def _printcollecteditems(self, items):\n # to print out items and their parent collectors\n # we take care to leave out Instances aka ()\n # because later versions are going to get rid of them anyway\n if self.config.option.verbose < 0:\n if self.config.option.verbose < -1:\n counts = {}\n for item in items:\n name = item.nodeid.split(\"::\", 1)[0]\n counts[name] = counts.get(name, 0) + 1\n for name, count in sorted(counts.items()):\n self._tw.line(\"%s: %d\" % (name, count))\n else:\n for item in items:\n self._tw.line(item.nodeid)\n return\n stack = []\n indent = \"\"\n for item in items:\n needed_collectors = item.listchain()[1:] # strip root node\n while stack:\n if stack == needed_collectors[: len(stack)]:\n break\n stack.pop()\n for col in needed_collectors[len(stack) :]:\n stack.append(col)\n if col.name == \"()\": # Skip Instances.\n continue\n indent = (len(stack) - 1) * \" \"\n self._tw.line(\"%s%s\" % (indent, col))\n if self.config.option.verbose >= 1:\n if hasattr(col, \"_obj\") and col._obj.__doc__:\n for line in col._obj.__doc__.strip().splitlines():\n self._tw.line(\"%s%s\" % (indent + \" \", line.strip()))"},{"col":0,"comment":"null","endLoc":198,"header":"def pytest_pycollect_makemodule(path, parent)","id":5076,"name":"pytest_pycollect_makemodule","nodeType":"Function","startLoc":195,"text":"def pytest_pycollect_makemodule(path, parent):\n if path.basename == \"__init__.py\":\n return Package(path, parent)\n return Module(path, parent)"},{"col":0,"comment":"null","endLoc":235,"header":"@hookimpl(hookwrapper=True)\ndef pytest_pycollect_makeitem(collector, name, obj)","id":5077,"name":"pytest_pycollect_makeitem","nodeType":"Function","startLoc":201,"text":"@hookimpl(hookwrapper=True)\ndef pytest_pycollect_makeitem(collector, name, obj):\n outcome = yield\n res = outcome.get_result()\n if res is not None:\n return\n # nothing was collected elsewhere, let's do it here\n if safe_isclass(obj):\n if collector.istestclass(obj, name):\n outcome.force_result(Class(name, parent=collector))\n elif collector.istestfunction(obj, name):\n # mock seems to store unbound methods (issue473), normalize it\n obj = getattr(obj, \"__func__\", obj)\n # We need to try and unwrap the function if it's a functools.partial\n # or a funtools.wrapped.\n # We musn't if it's been wrapped with mock.patch (python 2 only)\n if not (isfunction(obj) or isfunction(get_real_func(obj))):\n filename, lineno = getfslineno(obj)\n warnings.warn_explicit(\n message=PytestCollectionWarning(\n \"cannot collect %r because it is not a function.\" % name\n ),\n category=None,\n filename=str(filename),\n lineno=lineno + 1,\n )\n elif getattr(obj, \"__test__\", True):\n if is_generator(obj):\n res = Function(name, parent=collector)\n reason = deprecated.YIELD_TESTS.format(name=name)\n res.add_marker(MARK_GEN.xfail(run=False, reason=reason))\n res.warn(PytestCollectionWarning(reason))\n else:\n res = list(collector._genfunctions(name, obj))\n outcome.force_result(res)"},{"attributeType":"bytes","col":4,"comment":"null","endLoc":701,"id":5080,"name":"EMPTY_BUFFER","nodeType":"Attribute","startLoc":701,"text":"EMPTY_BUFFER"},{"className":"DontReadFromInput","col":0,"comment":"Temporary stub class. Ideally when stdin is accessed, the\n capturing should be turned off, with possibly all data captured\n so far sent to the screen. This should be configurable, though,\n because in automated test runs it is better to crash than\n hang indefinitely.\n ","endLoc":744,"id":5081,"nodeType":"Class","startLoc":710,"text":"class DontReadFromInput(six.Iterator):\n \"\"\"Temporary stub class. Ideally when stdin is accessed, the\n capturing should be turned off, with possibly all data captured\n so far sent to the screen. This should be configurable, though,\n because in automated test runs it is better to crash than\n hang indefinitely.\n \"\"\"\n\n encoding = None\n\n def read(self, *args):\n raise IOError(\"reading from stdin while output is captured\")\n\n readline = read\n readlines = read\n __next__ = read\n\n def __iter__(self):\n return self\n\n def fileno(self):\n raise UnsupportedOperation(\"redirected stdin is pseudofile, has no fileno()\")\n\n def isatty(self):\n return False\n\n def close(self):\n pass\n\n @property\n def buffer(self):\n if sys.version_info >= (3, 0):\n return self\n else:\n raise AttributeError(\"redirected stdin has no attribute buffer\")"},{"col":4,"comment":"null","endLoc":721,"header":"def read(self, *args)","id":5082,"name":"read","nodeType":"Function","startLoc":720,"text":"def read(self, *args):\n raise IOError(\"reading from stdin while output is captured\")"},{"col":4,"comment":"null","endLoc":728,"header":"def __iter__(self)","id":5083,"name":"__iter__","nodeType":"Function","startLoc":727,"text":"def __iter__(self):\n return self"},{"col":4,"comment":"null","endLoc":731,"header":"def fileno(self)","id":5084,"name":"fileno","nodeType":"Function","startLoc":730,"text":"def fileno(self):\n raise UnsupportedOperation(\"redirected stdin is pseudofile, has no fileno()\")"},{"col":4,"comment":"null","endLoc":734,"header":"def isatty(self)","id":5085,"name":"isatty","nodeType":"Function","startLoc":733,"text":"def isatty(self):\n return False"},{"col":4,"comment":"null","endLoc":737,"header":"def close(self)","id":5086,"name":"close","nodeType":"Function","startLoc":736,"text":"def close(self):\n pass"},{"col":4,"comment":"null","endLoc":744,"header":"@property\n def buffer(self)","id":5087,"name":"buffer","nodeType":"Function","startLoc":739,"text":"@property\n def buffer(self):\n if sys.version_info >= (3, 0):\n return self\n else:\n raise AttributeError(\"redirected stdin has no attribute buffer\")"},{"attributeType":"None","col":4,"comment":"null","endLoc":718,"id":5088,"name":"encoding","nodeType":"Attribute","startLoc":718,"text":"encoding"},{"attributeType":"function","col":4,"comment":"null","endLoc":723,"id":5089,"name":"readline","nodeType":"Attribute","startLoc":723,"text":"readline"},{"attributeType":"function","col":4,"comment":"null","endLoc":724,"id":5090,"name":"readlines","nodeType":"Attribute","startLoc":724,"text":"readlines"},{"attributeType":"function","col":4,"comment":"null","endLoc":725,"id":5091,"name":"__next__","nodeType":"Attribute","startLoc":725,"text":"__next__"},{"col":0,"comment":"null","endLoc":67,"header":"@pytest.hookimpl(hookwrapper=True)\ndef pytest_load_initial_conftests(early_config, parser, args)","id":5092,"name":"pytest_load_initial_conftests","nodeType":"Function","startLoc":46,"text":"@pytest.hookimpl(hookwrapper=True)\ndef pytest_load_initial_conftests(early_config, parser, args):\n ns = early_config.known_args_namespace\n if ns.capture == \"fd\":\n _py36_windowsconsoleio_workaround(sys.stdout)\n _colorama_workaround()\n _readline_workaround()\n pluginmanager = early_config.pluginmanager\n capman = CaptureManager(ns.capture)\n pluginmanager.register(capman, \"capturemanager\")\n\n # make sure that capturemanager is properly reset at final shutdown\n early_config.add_cleanup(capman.stop_global_capturing)\n\n # finally trigger conftest loading but while capturing (issue93)\n capman.start_global_capturing()\n outcome = yield\n capman.suspend_global_capture()\n if outcome.excinfo is not None:\n out, err = capman.read_global_capture()\n sys.stdout.write(out)\n sys.stderr.write(err)"},{"col":0,"comment":"\n Python 3.6 implemented unicode console handling for Windows. This works\n by reading/writing to the raw console handle using\n ``{Read,Write}ConsoleW``.\n\n The problem is that we are going to ``dup2`` over the stdio file\n descriptors when doing ``FDCapture`` and this will ``CloseHandle`` the\n handles used by Python to write to the console. Though there is still some\n weirdness and the console handle seems to only be closed randomly and not\n on the first call to ``CloseHandle``, or maybe it gets reopened with the\n same handle value when we suspend capturing.\n\n The workaround in this case will reopen stdio with a different fd which\n also means a different handle by replicating the logic in\n \"Py_lifecycle.c:initstdio/create_stdio\".\n\n :param stream: in practice ``sys.stdout`` or ``sys.stderr``, but given\n here as parameter for unittesting purposes.\n\n See https://github.com/pytest-dev/py/issues/103\n ","endLoc":839,"header":"def _py36_windowsconsoleio_workaround(stream)","id":5093,"name":"_py36_windowsconsoleio_workaround","nodeType":"Function","startLoc":788,"text":"def _py36_windowsconsoleio_workaround(stream):\n \"\"\"\n Python 3.6 implemented unicode console handling for Windows. This works\n by reading/writing to the raw console handle using\n ``{Read,Write}ConsoleW``.\n\n The problem is that we are going to ``dup2`` over the stdio file\n descriptors when doing ``FDCapture`` and this will ``CloseHandle`` the\n handles used by Python to write to the console. Though there is still some\n weirdness and the console handle seems to only be closed randomly and not\n on the first call to ``CloseHandle``, or maybe it gets reopened with the\n same handle value when we suspend capturing.\n\n The workaround in this case will reopen stdio with a different fd which\n also means a different handle by replicating the logic in\n \"Py_lifecycle.c:initstdio/create_stdio\".\n\n :param stream: in practice ``sys.stdout`` or ``sys.stderr``, but given\n here as parameter for unittesting purposes.\n\n See https://github.com/pytest-dev/py/issues/103\n \"\"\"\n if not sys.platform.startswith(\"win32\") or sys.version_info[:2] < (3, 6):\n return\n\n # bail out if ``stream`` doesn't seem like a proper ``io`` stream (#2666)\n if not hasattr(stream, \"buffer\"):\n return\n\n buffered = hasattr(stream.buffer, \"raw\")\n raw_stdout = stream.buffer.raw if buffered else stream.buffer\n\n if not isinstance(raw_stdout, io._WindowsConsoleIO):\n return\n\n def _reopen_stdio(f, mode):\n if not buffered and mode[0] == \"w\":\n buffering = 0\n else:\n buffering = -1\n\n return io.TextIOWrapper(\n open(os.dup(f.fileno()), mode, buffering),\n f.encoding,\n f.errors,\n f.newlines,\n f.line_buffering,\n )\n\n sys.stdin = _reopen_stdio(sys.stdin, \"rb\")\n sys.stdout = _reopen_stdio(sys.stdout, \"wb\")\n sys.stderr = _reopen_stdio(sys.stderr, \"wb\")"},{"col":4,"comment":"null","endLoc":678,"header":"@pytest.hookimpl(hookwrapper=True)\n def pytest_sessionfinish(self, exitstatus)","id":5094,"name":"pytest_sessionfinish","nodeType":"Function","startLoc":659,"text":"@pytest.hookimpl(hookwrapper=True)\n def pytest_sessionfinish(self, exitstatus):\n outcome = yield\n outcome.get_result()\n self._tw.line(\"\")\n summary_exit_codes = (\n EXIT_OK,\n EXIT_TESTSFAILED,\n EXIT_INTERRUPTED,\n EXIT_USAGEERROR,\n EXIT_NOTESTSCOLLECTED,\n )\n if exitstatus in summary_exit_codes:\n self.config.hook.pytest_terminal_summary(\n terminalreporter=self, exitstatus=exitstatus, config=self.config\n )\n if exitstatus == EXIT_INTERRUPTED:\n self._report_keyboardinterrupt()\n del self._keyboardinterrupt_memo\n self.summary_stats()"},{"col":4,"comment":"null","endLoc":710,"header":"def _report_keyboardinterrupt(self)","id":5095,"name":"_report_keyboardinterrupt","nodeType":"Function","startLoc":698,"text":"def _report_keyboardinterrupt(self):\n excrepr = self._keyboardinterrupt_memo\n msg = excrepr.reprcrash.message\n self.write_sep(\"!\", msg)\n if \"KeyboardInterrupt\" in msg:\n if self.config.option.fulltrace:\n excrepr.toterminal(self._tw)\n else:\n excrepr.reprcrash.toterminal(self._tw)\n self._tw.line(\n \"(to show a full traceback on KeyboardInterrupt use --fulltrace)\",\n yellow=True,\n )"},{"col":0,"comment":"null","endLoc":814,"header":"def test_unicode_in_longrepr(testdir)","id":5097,"name":"test_unicode_in_longrepr","nodeType":"Function","startLoc":793,"text":"def test_unicode_in_longrepr(testdir):\n testdir.makeconftest(\n \"\"\"\n # -*- coding: utf-8 -*-\n import pytest\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_makereport():\n outcome = yield\n rep = outcome.get_result()\n if rep.when == \"call\":\n rep.longrepr = u'ä'\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_out():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n assert \"UnicodeEncodeError\" not in result.stderr.str()"},{"col":0,"comment":"null","endLoc":827,"header":"def test_failure_in_setup(testdir)","id":5098,"name":"test_failure_in_setup","nodeType":"Function","startLoc":817,"text":"def test_failure_in_setup(testdir):\n testdir.makepyfile(\n \"\"\"\n def setup_module():\n 0/0\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--tb=line\")\n assert \"def setup_module\" not in result.stdout.str()"},{"col":0,"comment":"","endLoc":2,"header":"test_collection.py#","id":5099,"name":"","nodeType":"Function","startLoc":2,"text":"COLLECTION_ERROR_PY_FILES = dict(\n test_01_failure=\"\"\"\n def test_1():\n assert False\n \"\"\",\n test_02_import_error=\"\"\"\n import asdfasdfasdf\n def test_2():\n assert True\n \"\"\",\n test_03_import_error=\"\"\"\n import asdfasdfasdf\n def test_3():\n assert True\n \"\"\",\n test_04_success=\"\"\"\n def test_4():\n assert True\n \"\"\",\n)"},{"col":0,"comment":"null","endLoc":840,"header":"def test_makereport_getsource(testdir)","id":5100,"name":"test_makereport_getsource","nodeType":"Function","startLoc":830,"text":"def test_makereport_getsource(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n if False: pass\n else: assert False\n \"\"\"\n )\n result = testdir.runpytest()\n assert \"INTERNALERROR\" not in result.stdout.str()\n result.stdout.fnmatch_lines([\"*else: assert False*\"])"},{"col":4,"comment":"null","endLoc":883,"header":"def summary_stats(self)","id":5102,"name":"summary_stats","nodeType":"Function","startLoc":874,"text":"def summary_stats(self):\n session_duration = time.time() - self._sessionstarttime\n (line, color) = build_summary_stats_line(self.stats)\n msg = \"%s in %.2f seconds\" % (line, session_duration)\n markup = {color: True, \"bold\": True}\n\n if self.verbosity >= 0:\n self.write_sep(\"=\", msg, **markup)\n if self.verbosity == -1:\n self.write_line(msg, **markup)"},{"col":0,"comment":"null","endLoc":1070,"header":"def build_summary_stats_line(stats)","id":5103,"name":"build_summary_stats_line","nodeType":"Function","startLoc":1037,"text":"def build_summary_stats_line(stats):\n known_types = (\n \"failed passed skipped deselected xfailed xpassed warnings error\".split()\n )\n unknown_type_seen = False\n for found_type in stats:\n if found_type not in known_types:\n if found_type: # setup/teardown reports have an empty key, ignore them\n known_types.append(found_type)\n unknown_type_seen = True\n parts = []\n for key in known_types:\n reports = stats.get(key, None)\n if reports:\n count = sum(\n 1 for rep in reports if getattr(rep, \"count_towards_summary\", True)\n )\n parts.append(\"%d %s\" % (count, key))\n\n if parts:\n line = \", \".join(parts)\n else:\n line = \"no tests ran\"\n\n if \"failed\" in stats or \"error\" in stats:\n color = \"red\"\n elif \"warnings\" in stats or unknown_type_seen:\n color = \"yellow\"\n elif \"passed\" in stats:\n color = \"green\"\n else:\n color = \"yellow\"\n\n return line, color"},{"col":0,"comment":"Test that exception in dynamically generated code doesn't break getting the source line.","endLoc":871,"header":"def test_makereport_getsource_dynamic_code(testdir, monkeypatch)","id":5104,"name":"test_makereport_getsource_dynamic_code","nodeType":"Function","startLoc":843,"text":"def test_makereport_getsource_dynamic_code(testdir, monkeypatch):\n \"\"\"Test that exception in dynamically generated code doesn't break getting the source line.\"\"\"\n import inspect\n\n original_findsource = inspect.findsource\n\n def findsource(obj, *args, **kwargs):\n # Can be triggered by dynamically created functions\n if obj.__name__ == \"foo\":\n raise IndexError()\n return original_findsource(obj, *args, **kwargs)\n\n monkeypatch.setattr(inspect, \"findsource\", findsource)\n\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def foo(missing):\n pass\n\n def test_fix(foo):\n assert False\n \"\"\"\n )\n result = testdir.runpytest(\"-vv\")\n assert \"INTERNALERROR\" not in result.stdout.str()\n result.stdout.fnmatch_lines([\"*test_fix*\", \"*fixture*'missing'*not found*\"])"},{"id":5105,"name":"release-2.8.7.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.8.7\n============\n\nThis is a hotfix release to solve a regression\nin the builtin monkeypatch plugin that got introduced in 2.8.6.\n\npytest is a mature Python testing tool with more than a 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is supposed to be drop-in compatible to 2.8.5.\n\nSee below for the changes and see docs at:\n\n http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n Ronny Pfannschmidt\n\n\nHappy testing,\nThe py.test Development Team\n\n\n2.8.7 (compared to 2.8.6)\n-------------------------\n\n- fix #1338: use predictable object resolution for monkeypatch\n"},{"id":5106,"name":"5801.trivial.rst","nodeType":"TextFile","path":"changelog","text":"Fixes python version checks (detected by ``flake8-2020``) in case python4 becomes a thing.\n"},{"col":0,"comment":" Test that upon test failure, the exception info is stored on\n sys.last_traceback and friends.\n ","endLoc":901,"header":"def test_store_except_info_on_error()","id":5107,"name":"test_store_except_info_on_error","nodeType":"Function","startLoc":874,"text":"def test_store_except_info_on_error():\n \"\"\" Test that upon test failure, the exception info is stored on\n sys.last_traceback and friends.\n \"\"\"\n # Simulate item that might raise a specific exception, depending on `raise_error` class var\n class ItemMightRaise(object):\n nodeid = \"item_that_raises\"\n raise_error = True\n\n def runtest(self):\n if self.raise_error:\n raise IndexError(\"TEST\")\n\n try:\n runner.pytest_runtest_call(ItemMightRaise())\n except IndexError:\n pass\n # Check that exception info is stored on sys\n assert sys.last_type is IndexError\n assert sys.last_value.args[0] == \"TEST\"\n assert sys.last_traceback\n\n # The next run should clear the exception info stored by the previous run\n ItemMightRaise.raise_error = False\n runner.pytest_runtest_call(ItemMightRaise())\n assert sys.last_type is None\n assert sys.last_value is None\n assert sys.last_traceback is None"},{"col":0,"comment":"null","endLoc":933,"header":"def test_current_test_env_var(testdir, monkeypatch)","id":5111,"name":"test_current_test_env_var","nodeType":"Function","startLoc":904,"text":"def test_current_test_env_var(testdir, monkeypatch):\n pytest_current_test_vars = []\n monkeypatch.setattr(\n sys, \"pytest_current_test_vars\", pytest_current_test_vars, raising=False\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n import sys\n import os\n\n @pytest.fixture\n def fix():\n sys.pytest_current_test_vars.append(('setup', os.environ['PYTEST_CURRENT_TEST']))\n yield\n sys.pytest_current_test_vars.append(('teardown', os.environ['PYTEST_CURRENT_TEST']))\n\n def test(fix):\n sys.pytest_current_test_vars.append(('call', os.environ['PYTEST_CURRENT_TEST']))\n \"\"\"\n )\n result = testdir.runpytest_inprocess()\n assert result.ret == 0\n test_id = \"test_current_test_env_var.py::test\"\n assert pytest_current_test_vars == [\n (\"setup\", test_id + \" (setup)\"),\n (\"call\", test_id + \" (call)\"),\n (\"teardown\", test_id + \" (teardown)\"),\n ]\n assert \"PYTEST_CURRENT_TEST\" not in os.environ"},{"attributeType":"list","col":0,"comment":"null","endLoc":468,"id":5112,"name":"reporttypes","nodeType":"Attribute","startLoc":468,"text":"reporttypes"},{"col":0,"comment":"","endLoc":2,"header":"test_runner.py#","id":5113,"name":"","nodeType":"Function","startLoc":2,"text":"reporttypes = [reports.BaseReport, reports.TestReport, reports.CollectReport]"},{"id":5114,"name":"release-3.6.3.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.6.3\n=======================================\n\npytest 3.6.3 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* AdamEr8\n* Anthony Sottile\n* Bruno Oliveira\n* Jean-Paul Calderone\n* Jon Dufresne\n* Marcelo Duarte Trevisani\n* Ondřej Súkup\n* Ronny Pfannschmidt\n* T.E.A de Souza\n* Victor Maryama\n\n\nHappy testing,\nThe pytest Development Team\n"},{"id":5115,"name":"changelog.rst","nodeType":"TextFile","path":"doc/en","text":"\n.. _changelog:\n\n.. include:: ../../CHANGELOG.rst\n"},{"fileName":"nose.py","filePath":"src/_pytest","id":5116,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\" run test suites written for nose. \"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\n\nimport six\n\nimport pytest\nfrom _pytest import python\nfrom _pytest import runner\nfrom _pytest import unittest\nfrom _pytest.config import hookimpl\n\n\ndef get_skip_exceptions():\n skip_classes = set()\n for module_name in (\"unittest\", \"unittest2\", \"nose\"):\n mod = sys.modules.get(module_name)\n if hasattr(mod, \"SkipTest\"):\n skip_classes.add(mod.SkipTest)\n return tuple(skip_classes)\n\n\ndef pytest_runtest_makereport(item, call):\n if call.excinfo and call.excinfo.errisinstance(get_skip_exceptions()):\n # let's substitute the excinfo with a pytest.skip one\n call2 = runner.CallInfo.from_call(\n lambda: pytest.skip(six.text_type(call.excinfo.value)), call.when\n )\n call.excinfo = call2.excinfo\n\n\n@hookimpl(trylast=True)\ndef pytest_runtest_setup(item):\n if is_potential_nosetest(item):\n if not call_optional(item.obj, \"setup\"):\n # call module level setup if there is no object level one\n call_optional(item.parent.obj, \"setup\")\n # XXX this implies we only call teardown when setup worked\n item.session._setupstate.addfinalizer((lambda: teardown_nose(item)), item)\n\n\ndef teardown_nose(item):\n if is_potential_nosetest(item):\n if not call_optional(item.obj, \"teardown\"):\n call_optional(item.parent.obj, \"teardown\")\n # if hasattr(item.parent, '_nosegensetup'):\n # #call_optional(item._nosegensetup, 'teardown')\n # del item.parent._nosegensetup\n\n\ndef is_potential_nosetest(item):\n # extra check needed since we do not do nose style setup/teardown\n # on direct unittest style classes\n return isinstance(item, python.Function) and not isinstance(\n item, unittest.TestCaseFunction\n )\n\n\ndef call_optional(obj, name):\n method = getattr(obj, name, None)\n isfixture = hasattr(method, \"_pytestfixturefunction\")\n if method is not None and not isfixture and callable(method):\n # If there's any problems allow the exception to raise rather than\n # silently ignoring them\n method()\n return True\n"},{"col":0,"comment":"null","endLoc":33,"header":"def pytest_runtest_makereport(item, call)","id":5117,"name":"pytest_runtest_makereport","nodeType":"Function","startLoc":27,"text":"def pytest_runtest_makereport(item, call):\n if call.excinfo and call.excinfo.errisinstance(get_skip_exceptions()):\n # let's substitute the excinfo with a pytest.skip one\n call2 = runner.CallInfo.from_call(\n lambda: pytest.skip(six.text_type(call.excinfo.value)), call.when\n )\n call.excinfo = call2.excinfo"},{"col":0,"comment":"\n Ensure colorama is imported so that it attaches to the correct stdio\n handles on Windows.\n\n colorama uses the terminal on import time. So if something does the\n first import of colorama while I/O capture is active, colorama will\n fail in various ways.\n ","endLoc":760,"header":"def _colorama_workaround()","id":5119,"name":"_colorama_workaround","nodeType":"Function","startLoc":747,"text":"def _colorama_workaround():\n \"\"\"\n Ensure colorama is imported so that it attaches to the correct stdio\n handles on Windows.\n\n colorama uses the terminal on import time. So if something does the\n first import of colorama while I/O capture is active, colorama will\n fail in various ways.\n \"\"\"\n if sys.platform.startswith(\"win32\"):\n try:\n import colorama # noqa: F401\n except ImportError:\n pass"},{"col":0,"comment":"\n Ensure readline is imported so that it attaches to the correct stdio\n handles on Windows.\n\n Pdb uses readline support where available--when not running from the Python\n prompt, the readline module is not imported until running the pdb REPL. If\n running pytest with the --pdb option this means the readline module is not\n imported until after I/O capture has been started.\n\n This is a problem for pyreadline, which is often used to implement readline\n support on Windows, as it does not attach to the correct handles for stdout\n and/or stdin if they have been redirected by the FDCapture mechanism. This\n workaround ensures that readline is imported before I/O capture is setup so\n that it can attach to the actual stdin/out for the console.\n\n See https://github.com/pytest-dev/pytest/pull/1281\n ","endLoc":785,"header":"def _readline_workaround()","id":5120,"name":"_readline_workaround","nodeType":"Function","startLoc":763,"text":"def _readline_workaround():\n \"\"\"\n Ensure readline is imported so that it attaches to the correct stdio\n handles on Windows.\n\n Pdb uses readline support where available--when not running from the Python\n prompt, the readline module is not imported until running the pdb REPL. If\n running pytest with the --pdb option this means the readline module is not\n imported until after I/O capture has been started.\n\n This is a problem for pyreadline, which is often used to implement readline\n support on Windows, as it does not attach to the correct handles for stdout\n and/or stdin if they have been redirected by the FDCapture mechanism. This\n workaround ensures that readline is imported before I/O capture is setup so\n that it can attach to the actual stdin/out for the console.\n\n See https://github.com/pytest-dev/pytest/pull/1281\n \"\"\"\n if sys.platform.startswith(\"win32\"):\n try:\n import readline # noqa: F401\n except ImportError:\n pass"},{"attributeType":"list","col":8,"comment":"null","endLoc":58,"id":5121,"name":"allowednames","nodeType":"Attribute","startLoc":58,"text":"self.allowednames"},{"attributeType":"bool","col":8,"comment":"null","endLoc":59,"id":5122,"name":"directories","nodeType":"Attribute","startLoc":59,"text":"self.directories"},{"col":4,"comment":"null","endLoc":689,"header":"@pytest.hookimpl(hookwrapper=True)\n def pytest_terminal_summary(self)","id":5123,"name":"pytest_terminal_summary","nodeType":"Function","startLoc":680,"text":"@pytest.hookimpl(hookwrapper=True)\n def pytest_terminal_summary(self):\n self.summary_errors()\n self.summary_failures()\n self.summary_warnings()\n self.summary_passes()\n yield\n self.short_test_summary()\n # Display any extra warnings from teardown here (if any).\n self.summary_warnings()"},{"className":"TestArgComplete","col":0,"comment":"null","endLoc":119,"id":5124,"nodeType":"Class","startLoc":93,"text":"class TestArgComplete(object):\n @pytest.mark.skipif(\"sys.platform in ('win32', 'darwin')\")\n def test_compare_with_compgen(self, tmpdir):\n from _pytest._argcomplete import FastFilesCompleter\n\n ffc = FastFilesCompleter()\n fc = FilesCompleter()\n\n with tmpdir.as_cwd():\n assert equal_with_bash(\"\", ffc, fc, out=sys.stdout)\n\n tmpdir.ensure(\"data\")\n\n for x in [\"d\", \"data\", \"doesnotexist\", \"\"]:\n assert equal_with_bash(x, ffc, fc, out=sys.stdout)\n\n @pytest.mark.skipif(\"sys.platform in ('win32', 'darwin')\")\n def test_remove_dir_prefix(self):\n \"\"\"this is not compatible with compgen but it is with bash itself:\n ls /usr/\n \"\"\"\n from _pytest._argcomplete import FastFilesCompleter\n\n ffc = FastFilesCompleter()\n fc = FilesCompleter()\n for x in \"/usr/\".split():\n assert not equal_with_bash(x, ffc, fc, out=sys.stdout)"},{"col":4,"comment":"null","endLoc":107,"header":"@pytest.mark.skipif(\"sys.platform in ('win32', 'darwin')\")\n def test_compare_with_compgen(self, tmpdir)","id":5125,"name":"test_compare_with_compgen","nodeType":"Function","startLoc":94,"text":"@pytest.mark.skipif(\"sys.platform in ('win32', 'darwin')\")\n def test_compare_with_compgen(self, tmpdir):\n from _pytest._argcomplete import FastFilesCompleter\n\n ffc = FastFilesCompleter()\n fc = FilesCompleter()\n\n with tmpdir.as_cwd():\n assert equal_with_bash(\"\", ffc, fc, out=sys.stdout)\n\n tmpdir.ensure(\"data\")\n\n for x in [\"d\", \"data\", \"doesnotexist\", \"\"]:\n assert equal_with_bash(x, ffc, fc, out=sys.stdout)"},{"col":0,"comment":"null","endLoc":239,"header":"def pytest_make_parametrize_id(config, val, argname=None)","id":5126,"name":"pytest_make_parametrize_id","nodeType":"Function","startLoc":238,"text":"def pytest_make_parametrize_id(config, val, argname=None):\n return None"},{"col":0,"comment":"\n Return a callable to perform xunit-style setup or teardown if\n the function exists in the ``holder`` object.\n The ``param_obj`` parameter is the parameter which will be passed to the function\n when the callable is called without arguments, defaults to the ``holder`` object.\n Return ``None`` if a suitable callable is not found.\n ","endLoc":687,"header":"def _get_xunit_setup_teardown(holder, attr_name, param_obj=None)","id":5127,"name":"_get_xunit_setup_teardown","nodeType":"Function","startLoc":669,"text":"def _get_xunit_setup_teardown(holder, attr_name, param_obj=None):\n \"\"\"\n Return a callable to perform xunit-style setup or teardown if\n the function exists in the ``holder`` object.\n The ``param_obj`` parameter is the parameter which will be passed to the function\n when the callable is called without arguments, defaults to the ``holder`` object.\n Return ``None`` if a suitable callable is not found.\n \"\"\"\n # TODO: only needed because of Package!\n param_obj = param_obj if param_obj is not None else holder\n result = _get_non_fixture_func(holder, attr_name)\n if result is not None:\n arg_count = result.__code__.co_argcount\n if inspect.ismethod(result):\n arg_count -= 1\n if arg_count:\n return lambda: result(param_obj)\n else:\n return result"},{"col":4,"comment":"null","endLoc":70,"header":"def __init__(self, directories=True)","id":5128,"name":"__init__","nodeType":"Function","startLoc":69,"text":"def __init__(self, directories=True):\n self.directories = directories"},{"col":0,"comment":"null","endLoc":23,"header":"def equal_with_bash(prefix, ffc, fc, out=None)","id":5129,"name":"equal_with_bash","nodeType":"Function","startLoc":14,"text":"def equal_with_bash(prefix, ffc, fc, out=None):\n res = ffc(prefix)\n res_bash = set(fc(prefix))\n retval = set(res) == res_bash\n if out:\n out.write(\"equal_with_bash({}) {} {}\\n\".format(prefix, retval, res))\n if not retval:\n out.write(\" python - bash: %s\\n\" % (set(res) - res_bash))\n out.write(\" bash - python: %s\\n\" % (res_bash - set(res)))\n return retval"},{"col":19,"endLoc":685,"id":5130,"nodeType":"Lambda","startLoc":685,"text":"lambda: result(param_obj)"},{"col":0,"comment":"null","endLoc":1291,"header":"def _show_fixtures_per_test(config, session)","id":5131,"name":"_show_fixtures_per_test","nodeType":"Function","startLoc":1242,"text":"def _show_fixtures_per_test(config, session):\n import _pytest.config\n\n session.perform_collect()\n curdir = py.path.local()\n tw = _pytest.config.create_terminal_writer(config)\n verbose = config.getvalue(\"verbose\")\n\n def get_best_relpath(func):\n loc = getlocation(func, curdir)\n return curdir.bestrelpath(loc)\n\n def write_fixture(fixture_def):\n argname = fixture_def.argname\n if verbose <= 0 and argname.startswith(\"_\"):\n return\n if verbose > 0:\n bestrel = get_best_relpath(fixture_def.func)\n funcargspec = \"{} -- {}\".format(argname, bestrel)\n else:\n funcargspec = argname\n tw.line(funcargspec, green=True)\n fixture_doc = fixture_def.func.__doc__\n if fixture_doc:\n write_docstring(tw, fixture_doc)\n else:\n tw.line(\" no docstring available\", red=True)\n\n def write_item(item):\n try:\n info = item._fixtureinfo\n except AttributeError:\n # doctests items have no _fixtureinfo attribute\n return\n if not info.name2fixturedefs:\n # this test item does not use any fixtures\n return\n tw.line()\n tw.sep(\"-\", \"fixtures used by {}\".format(item.name))\n tw.sep(\"-\", \"({})\".format(get_best_relpath(item.function)))\n # dict key not used in loop but needed for sorting\n for _, fixturedefs in sorted(info.name2fixturedefs.items()):\n assert fixturedefs is not None\n if not fixturedefs:\n continue\n # last item is expected to be the one used by the test item\n write_fixture(fixturedefs[-1])\n\n for session_item in session.items:\n write_item(session_item)"},{"col":4,"comment":"null","endLoc":859,"header":"def summary_errors(self)","id":5133,"name":"summary_errors","nodeType":"Function","startLoc":846,"text":"def summary_errors(self):\n if self.config.option.tbstyle != \"no\":\n reports = self.getreports(\"error\")\n if not reports:\n return\n self.write_sep(\"=\", \"ERRORS\")\n for rep in self.stats[\"error\"]:\n msg = self._getfailureheadline(rep)\n if rep.when == \"collect\":\n msg = \"ERROR collecting \" + msg\n else:\n msg = \"ERROR at %s of %s\" % (rep.when, msg)\n self.write_sep(\"_\", msg, red=True, bold=True)\n self._outrep_summary(rep)"},{"col":4,"comment":"null","endLoc":757,"header":"def getreports(self, name)","id":5134,"name":"getreports","nodeType":"Function","startLoc":752,"text":"def getreports(self, name):\n values = []\n for x in self.stats.get(name, []):\n if not hasattr(x, \"_pdbshown\"):\n values.append(x)\n return values"},{"col":4,"comment":"null","endLoc":738,"header":"def _getfailureheadline(self, rep)","id":5135,"name":"_getfailureheadline","nodeType":"Function","startLoc":734,"text":"def _getfailureheadline(self, rep):\n head_line = rep.head_line\n if head_line:\n return head_line\n return \"test session\" # XXX?"},{"col":4,"comment":"null","endLoc":872,"header":"def _outrep_summary(self, rep)","id":5136,"name":"_outrep_summary","nodeType":"Function","startLoc":861,"text":"def _outrep_summary(self, rep):\n rep.toterminal(self._tw)\n showcapture = self.config.option.showcapture\n if showcapture == \"no\":\n return\n for secname, content in rep.sections:\n if showcapture != \"all\" and showcapture not in secname:\n continue\n self._tw.sep(\"-\", secname)\n if content[-1:] == \"\\n\":\n content = content[:-1]\n self._tw.line(content)"},{"col":12,"endLoc":31,"id":5137,"nodeType":"Lambda","startLoc":31,"text":"lambda: pytest.skip(six.text_type(call.excinfo.value))"},{"col":0,"comment":"null","endLoc":43,"header":"@hookimpl(trylast=True)\ndef pytest_runtest_setup(item)","id":5138,"name":"pytest_runtest_setup","nodeType":"Function","startLoc":36,"text":"@hookimpl(trylast=True)\ndef pytest_runtest_setup(item):\n if is_potential_nosetest(item):\n if not call_optional(item.obj, \"setup\"):\n # call module level setup if there is no object level one\n call_optional(item.parent.obj, \"setup\")\n # XXX this implies we only call teardown when setup worked\n item.session._setupstate.addfinalizer((lambda: teardown_nose(item)), item)"},{"col":0,"comment":"null","endLoc":1369,"header":"def write_docstring(tw, doc, indent=\" \")","id":5139,"name":"write_docstring","nodeType":"Function","startLoc":1357,"text":"def write_docstring(tw, doc, indent=\" \"):\n doc = doc.rstrip()\n if \"\\n\" in doc:\n firstline, rest = doc.split(\"\\n\", 1)\n else:\n firstline, rest = doc, \"\"\n\n if firstline.strip():\n tw.line(indent + firstline.strip())\n\n if rest:\n for line in dedent(rest).split(\"\\n\"):\n tw.write(indent + line + \"\\n\")"},{"col":0,"comment":"null","endLoc":60,"header":"def is_potential_nosetest(item)","id":5140,"name":"is_potential_nosetest","nodeType":"Function","startLoc":55,"text":"def is_potential_nosetest(item):\n # extra check needed since we do not do nose style setup/teardown\n # on direct unittest style classes\n return isinstance(item, python.Function) and not isinstance(\n item, unittest.TestCaseFunction\n )"},{"col":4,"comment":"this is not compatible with compgen but it is with bash itself:\n ls /usr/\n ","endLoc":119,"header":"@pytest.mark.skipif(\"sys.platform in ('win32', 'darwin')\")\n def test_remove_dir_prefix(self)","id":5141,"name":"test_remove_dir_prefix","nodeType":"Function","startLoc":109,"text":"@pytest.mark.skipif(\"sys.platform in ('win32', 'darwin')\")\n def test_remove_dir_prefix(self):\n \"\"\"this is not compatible with compgen but it is with bash itself:\n ls /usr/\n \"\"\"\n from _pytest._argcomplete import FastFilesCompleter\n\n ffc = FastFilesCompleter()\n fc = FilesCompleter()\n for x in \"/usr/\".split():\n assert not equal_with_bash(x, ffc, fc, out=sys.stdout)"},{"col":0,"comment":"null","endLoc":52,"header":"def teardown_nose(item)","id":5142,"name":"teardown_nose","nodeType":"Function","startLoc":46,"text":"def teardown_nose(item):\n if is_potential_nosetest(item):\n if not call_optional(item.obj, \"teardown\"):\n call_optional(item.parent.obj, \"teardown\")\n # if hasattr(item.parent, '_nosegensetup'):\n # #call_optional(item._nosegensetup, 'teardown')\n # del item.parent._nosegensetup"},{"col":47,"endLoc":43,"id":5143,"nodeType":"Lambda","startLoc":43,"text":"lambda: teardown_nose(item)"},{"col":0,"comment":"null","endLoc":261,"header":"def _ensure_only_one_capture_fixture(request, name)","id":5144,"name":"_ensure_only_one_capture_fixture","nodeType":"Function","startLoc":254,"text":"def _ensure_only_one_capture_fixture(request, name):\n fixtures = set(request.fixturenames) & capture_fixtures - {name}\n if fixtures:\n fixtures = sorted(fixtures)\n fixtures = fixtures[0] if len(fixtures) == 1 else fixtures\n raise request.raiseerror(\n \"cannot use {} and {} at the same time\".format(fixtures, name)\n )"},{"col":0,"comment":"","endLoc":2,"header":"nose.py#","id":5145,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" run test suites written for nose. \"\"\""},{"id":5146,"name":"README.rst","nodeType":"TextFile","path":"","text":".. image:: https://docs.pytest.org/en/latest/_static/pytest1.png\n :target: https://docs.pytest.org/en/latest/\n :align: center\n :alt: pytest\n\n\n------\n\n.. image:: https://img.shields.io/pypi/v/pytest.svg\n :target: https://pypi.org/project/pytest/\n\n.. image:: https://img.shields.io/conda/vn/conda-forge/pytest.svg\n :target: https://anaconda.org/conda-forge/pytest\n\n.. image:: https://img.shields.io/pypi/pyversions/pytest.svg\n :target: https://pypi.org/project/pytest/\n\n.. image:: https://codecov.io/gh/pytest-dev/pytest/branch/master/graph/badge.svg\n :target: https://codecov.io/gh/pytest-dev/pytest\n :alt: Code coverage Status\n\n.. image:: https://travis-ci.org/pytest-dev/pytest.svg?branch=master\n :target: https://travis-ci.org/pytest-dev/pytest\n\n.. image:: https://dev.azure.com/pytest-dev/pytest/_apis/build/status/pytest-CI?branchName=master\n :target: https://dev.azure.com/pytest-dev/pytest\n\n.. image:: https://img.shields.io/badge/code%20style-black-000000.svg\n :target: https://github.com/python/black\n\n.. image:: https://www.codetriage.com/pytest-dev/pytest/badges/users.svg\n :target: https://www.codetriage.com/pytest-dev/pytest\n\nThe ``pytest`` framework makes it easy to write small tests, yet\nscales to support complex functional testing for applications and libraries.\n\nAn example of a simple test:\n\n.. code-block:: python\n\n # content of test_sample.py\n def inc(x):\n return x + 1\n\n\n def test_answer():\n assert inc(3) == 5\n\n\nTo execute it::\n\n $ pytest\n ============================= test session starts =============================\n collected 1 items\n\n test_sample.py F\n\n ================================== FAILURES ===================================\n _________________________________ test_answer _________________________________\n\n def test_answer():\n > assert inc(3) == 5\n E assert 4 == 5\n E + where 4 = inc(3)\n\n test_sample.py:5: AssertionError\n ========================== 1 failed in 0.04 seconds ===========================\n\n\nDue to ``pytest``'s detailed assertion introspection, only plain ``assert`` statements are used. See `getting-started `_ for more examples.\n\n\nFeatures\n--------\n\n- Detailed info on failing `assert statements `_ (no need to remember ``self.assert*`` names);\n\n- `Auto-discovery\n `_\n of test modules and functions;\n\n- `Modular fixtures `_ for\n managing small or parametrized long-lived test resources;\n\n- Can run `unittest `_ (or trial),\n `nose `_ test suites out of the box;\n\n- Python 2.7, Python 3.4+, PyPy 2.3, Jython 2.5 (untested);\n\n- Rich plugin architecture, with over 315+ `external plugins `_ and thriving community;\n\n\nDocumentation\n-------------\n\nFor full documentation, including installation, tutorials and PDF documents, please see https://docs.pytest.org/en/latest/.\n\n\nBugs/Requests\n-------------\n\nPlease use the `GitHub issue tracker `_ to submit bugs or request features.\n\n\nChangelog\n---------\n\nConsult the `Changelog `__ page for fixes and enhancements of each version.\n\n\nSupport pytest\n--------------\n\nYou can support pytest by obtaining a `Tideflift subscription`_.\n\nTidelift gives software development teams a single source for purchasing and maintaining their software,\nwith professional grade assurances from the experts who know it best, while seamlessly integrating with existing tools.\n\n\n.. _`Tideflift subscription`: https://tidelift.com/subscription/pkg/pypi-pytest?utm_source=pypi-pytest&utm_medium=referral&utm_campaign=readme\n\n\nSecurity\n^^^^^^^^\n\npytest has never been associated with a security vunerability, but in any case, to report a\nsecurity vulnerability please use the `Tidelift security contact `_.\nTidelift will coordinate the fix and disclosure.\n\n\nLicense\n-------\n\nCopyright Holger Krekel and others, 2004-2019.\n\nDistributed under the terms of the `MIT`_ license, pytest is free and open source software.\n\n.. _`MIT`: https://github.com/pytest-dev/pytest/blob/master/LICENSE\n"},{"id":5147,"name":"builtin.rst","nodeType":"TextFile","path":"doc/en","text":":orphan:\n\n.. _`pytest helpers`:\n\nPytest API and builtin fixtures\n================================================\n\n\nMost of the information of this page has been moved over to :ref:`reference`.\n\nFor information on plugin hooks and objects, see :ref:`plugins`.\n\nFor information on the ``pytest.mark`` mechanism, see :ref:`mark`.\n\nFor information about fixtures, see :ref:`fixtures`. To see a complete list of available fixtures (add ``-v`` to also see fixtures with leading ``_``), type :\n\n.. code-block:: pytest\n\n $ pytest -q --fixtures\n cache\n Return a cache object that can persist state between testing sessions.\n\n cache.get(key, default)\n cache.set(key, value)\n\n Keys must be a ``/`` separated value, where the first part is usually the\n name of your plugin or application to avoid clashes with other cache users.\n\n Values can be any object handled by the json stdlib module.\n\n capsys\n Enable text capturing of writes to ``sys.stdout`` and ``sys.stderr``.\n\n The captured output is made available via ``capsys.readouterr()`` method\n calls, which return a ``(out, err)`` namedtuple.\n ``out`` and ``err`` will be ``text`` objects.\n\n capsysbinary\n Enable bytes capturing of writes to ``sys.stdout`` and ``sys.stderr``.\n\n The captured output is made available via ``capsysbinary.readouterr()``\n method calls, which return a ``(out, err)`` namedtuple.\n ``out`` and ``err`` will be ``bytes`` objects.\n\n capfd\n Enable text capturing of writes to file descriptors ``1`` and ``2``.\n\n The captured output is made available via ``capfd.readouterr()`` method\n calls, which return a ``(out, err)`` namedtuple.\n ``out`` and ``err`` will be ``text`` objects.\n\n capfdbinary\n Enable bytes capturing of writes to file descriptors ``1`` and ``2``.\n\n The captured output is made available via ``capfd.readouterr()`` method\n calls, which return a ``(out, err)`` namedtuple.\n ``out`` and ``err`` will be ``byte`` objects.\n\n doctest_namespace [session scope]\n Fixture that returns a :py:class:`dict` that will be injected into the namespace of doctests.\n\n pytestconfig [session scope]\n Session-scoped fixture that returns the :class:`_pytest.config.Config` object.\n\n Example::\n\n def test_foo(pytestconfig):\n if pytestconfig.getoption(\"verbose\") > 0:\n ...\n\n record_property\n Add an extra properties the calling test.\n User properties become part of the test report and are available to the\n configured reporters, like JUnit XML.\n The fixture is callable with ``(name, value)``, with value being automatically\n xml-encoded.\n\n Example::\n\n def test_function(record_property):\n record_property(\"example_key\", 1)\n\n record_xml_attribute\n Add extra xml attributes to the tag for the calling test.\n The fixture is callable with ``(name, value)``, with value being\n automatically xml-encoded\n\n record_testsuite_property [session scope]\n Records a new ```` tag as child of the root ````. This is suitable to\n writing global information regarding the entire test suite, and is compatible with ``xunit2`` JUnit family.\n\n This is a ``session``-scoped fixture which is called with ``(name, value)``. Example:\n\n .. code-block:: python\n\n def test_foo(record_testsuite_property):\n record_testsuite_property(\"ARCH\", \"PPC\")\n record_testsuite_property(\"STORAGE_TYPE\", \"CEPH\")\n\n ``name`` must be a string, ``value`` will be converted to a string and properly xml-escaped.\n\n caplog\n Access and control log capturing.\n\n Captured logs are available through the following properties/methods::\n\n * caplog.text -> string containing formatted log output\n * caplog.records -> list of logging.LogRecord instances\n * caplog.record_tuples -> list of (logger_name, level, message) tuples\n * caplog.clear() -> clear captured records and formatted log output string\n\n monkeypatch\n The returned ``monkeypatch`` fixture provides these\n helper methods to modify objects, dictionaries or os.environ::\n\n monkeypatch.setattr(obj, name, value, raising=True)\n monkeypatch.delattr(obj, name, raising=True)\n monkeypatch.setitem(mapping, name, value)\n monkeypatch.delitem(obj, name, raising=True)\n monkeypatch.setenv(name, value, prepend=False)\n monkeypatch.delenv(name, raising=True)\n monkeypatch.syspath_prepend(path)\n monkeypatch.chdir(path)\n\n All modifications will be undone after the requesting\n test function or fixture has finished. The ``raising``\n parameter determines if a KeyError or AttributeError\n will be raised if the set/deletion operation has no target.\n\n recwarn\n Return a :class:`WarningsRecorder` instance that records all warnings emitted by test functions.\n\n See http://docs.python.org/library/warnings.html for information\n on warning categories.\n\n tmpdir_factory [session scope]\n Return a :class:`_pytest.tmpdir.TempdirFactory` instance for the test session.\n\n tmp_path_factory [session scope]\n Return a :class:`_pytest.tmpdir.TempPathFactory` instance for the test session.\n\n tmpdir\n Return a temporary directory path object\n which is unique to each test function invocation,\n created as a sub directory of the base temporary\n directory. The returned object is a `py.path.local`_\n path object.\n\n .. _`py.path.local`: https://py.readthedocs.io/en/latest/path.html\n\n tmp_path\n Return a temporary directory path object\n which is unique to each test function invocation,\n created as a sub directory of the base temporary\n directory. The returned object is a :class:`pathlib.Path`\n object.\n\n .. note::\n\n in python < 3.6 this is a pathlib2.Path\n\n\n no tests ran in 0.12 seconds\n\nYou can also interactively ask for help, e.g. by typing on the Python interactive prompt something like::\n\n import pytest\n help(pytest)\n"},{"id":5148,"name":"parametrize.rst","nodeType":"TextFile","path":"doc/en","text":"\n.. _`test generators`:\n.. _`parametrizing-tests`:\n.. _`parametrized test functions`:\n.. _`parametrize`:\n\n.. _`parametrize-basics`:\n\nParametrizing fixtures and test functions\n==========================================================================\n\npytest enables test parametrization at several levels:\n\n- :py:func:`pytest.fixture` allows one to :ref:`parametrize fixture\n functions `.\n\n* `@pytest.mark.parametrize`_ allows one to define multiple sets of\n arguments and fixtures at the test function or class.\n\n* `pytest_generate_tests`_ allows one to define custom parametrization\n schemes or extensions.\n\n.. _parametrizemark:\n.. _`@pytest.mark.parametrize`:\n\n\n``@pytest.mark.parametrize``: parametrizing test functions\n---------------------------------------------------------------------\n\n.. regendoc: wipe\n\n\n\n Several improvements.\n\nThe builtin :ref:`pytest.mark.parametrize ref` decorator enables\nparametrization of arguments for a test function. Here is a typical example\nof a test function that implements checking that a certain input leads\nto an expected output:\n\n.. code-block:: python\n\n # content of test_expectation.py\n import pytest\n\n\n @pytest.mark.parametrize(\"test_input,expected\", [(\"3+5\", 8), (\"2+4\", 6), (\"6*9\", 42)])\n def test_eval(test_input, expected):\n assert eval(test_input) == expected\n\nHere, the ``@parametrize`` decorator defines three different ``(test_input,expected)``\ntuples so that the ``test_eval`` function will run three times using\nthem in turn:\n\n.. code-block:: pytest\n\n $ pytest\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 3 items\n\n test_expectation.py ..F [100%]\n\n ================================= FAILURES =================================\n ____________________________ test_eval[6*9-42] _____________________________\n\n test_input = '6*9', expected = 42\n\n @pytest.mark.parametrize(\"test_input,expected\", [(\"3+5\", 8), (\"2+4\", 6), (\"6*9\", 42)])\n def test_eval(test_input, expected):\n > assert eval(test_input) == expected\n E AssertionError: assert 54 == 42\n E + where 54 = eval('6*9')\n\n test_expectation.py:6: AssertionError\n ==================== 1 failed, 2 passed in 0.12 seconds ====================\n\n.. note::\n\n pytest by default escapes any non-ascii characters used in unicode strings\n for the parametrization because it has several downsides.\n If however you would like to use unicode strings in parametrization and see them in the terminal as is (non-escaped), use this option in your ``pytest.ini``:\n\n .. code-block:: ini\n\n [pytest]\n disable_test_id_escaping_and_forfeit_all_rights_to_community_support = True\n\n Keep in mind however that this might cause unwanted side effects and\n even bugs depending on the OS used and plugins currently installed, so use it at your own risk.\n\n\nAs designed in this example, only one pair of input/output values fails\nthe simple test function. And as usual with test function arguments,\nyou can see the ``input`` and ``output`` values in the traceback.\n\nNote that you could also use the parametrize marker on a class or a module\n(see :ref:`mark`) which would invoke several functions with the argument sets.\n\nIt is also possible to mark individual test instances within parametrize,\nfor example with the builtin ``mark.xfail``:\n\n.. code-block:: python\n\n # content of test_expectation.py\n import pytest\n\n\n @pytest.mark.parametrize(\n \"test_input,expected\",\n [(\"3+5\", 8), (\"2+4\", 6), pytest.param(\"6*9\", 42, marks=pytest.mark.xfail)],\n )\n def test_eval(test_input, expected):\n assert eval(test_input) == expected\n\nLet's run this:\n\n.. code-block:: pytest\n\n $ pytest\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 3 items\n\n test_expectation.py ..x [100%]\n\n =================== 2 passed, 1 xfailed in 0.12 seconds ====================\n\nThe one parameter set which caused a failure previously now\nshows up as an \"xfailed (expected to fail)\" test.\n\nIn case the values provided to ``parametrize`` result in an empty list - for\nexample, if they're dynamically generated by some function - the behaviour of\npytest is defined by the :confval:`empty_parameter_set_mark` option.\n\nTo get all combinations of multiple parametrized arguments you can stack\n``parametrize`` decorators:\n\n.. code-block:: python\n\n import pytest\n\n\n @pytest.mark.parametrize(\"x\", [0, 1])\n @pytest.mark.parametrize(\"y\", [2, 3])\n def test_foo(x, y):\n pass\n\nThis will run the test with the arguments set to ``x=0/y=2``, ``x=1/y=2``,\n``x=0/y=3``, and ``x=1/y=3`` exhausting parameters in the order of the decorators.\n\n.. _`pytest_generate_tests`:\n\nBasic ``pytest_generate_tests`` example\n---------------------------------------------\n\nSometimes you may want to implement your own parametrization scheme\nor implement some dynamism for determining the parameters or scope\nof a fixture. For this, you can use the ``pytest_generate_tests`` hook\nwhich is called when collecting a test function. Through the passed in\n``metafunc`` object you can inspect the requesting test context and, most\nimportantly, you can call ``metafunc.parametrize()`` to cause\nparametrization.\n\nFor example, let's say we want to run a test taking string inputs which\nwe want to set via a new ``pytest`` command line option. Let's first write\na simple test accepting a ``stringinput`` fixture function argument:\n\n.. code-block:: python\n\n # content of test_strings.py\n\n\n def test_valid_string(stringinput):\n assert stringinput.isalpha()\n\nNow we add a ``conftest.py`` file containing the addition of a\ncommand line option and the parametrization of our test function:\n\n.. code-block:: python\n\n # content of conftest.py\n\n\n def pytest_addoption(parser):\n parser.addoption(\n \"--stringinput\",\n action=\"append\",\n default=[],\n help=\"list of stringinputs to pass to test functions\",\n )\n\n\n def pytest_generate_tests(metafunc):\n if \"stringinput\" in metafunc.fixturenames:\n metafunc.parametrize(\"stringinput\", metafunc.config.getoption(\"stringinput\"))\n\nIf we now pass two stringinput values, our test will run twice:\n\n.. code-block:: pytest\n\n $ pytest -q --stringinput=\"hello\" --stringinput=\"world\" test_strings.py\n .. [100%]\n 2 passed in 0.12 seconds\n\nLet's also run with a stringinput that will lead to a failing test:\n\n.. code-block:: pytest\n\n $ pytest -q --stringinput=\"!\" test_strings.py\n F [100%]\n ================================= FAILURES =================================\n ___________________________ test_valid_string[!] ___________________________\n\n stringinput = '!'\n\n def test_valid_string(stringinput):\n > assert stringinput.isalpha()\n E AssertionError: assert False\n E + where False = ()\n E + where = '!'.isalpha\n\n test_strings.py:4: AssertionError\n 1 failed in 0.12 seconds\n\nAs expected our test function fails.\n\nIf you don't specify a stringinput it will be skipped because\n``metafunc.parametrize()`` will be called with an empty parameter\nlist:\n\n.. code-block:: pytest\n\n $ pytest -q -rs test_strings.py\n s [100%]\n ========================= short test summary info ==========================\n SKIPPED [1] test_strings.py: got empty parameter set ['stringinput'], function test_valid_string at $REGENDOC_TMPDIR/test_strings.py:2\n 1 skipped in 0.12 seconds\n\nNote that when calling ``metafunc.parametrize`` multiple times with different parameter sets, all parameter names across\nthose sets cannot be duplicated, otherwise an error will be raised.\n\nMore examples\n-------------\n\nFor further examples, you might want to look at :ref:`more\nparametrization examples `.\n"},{"id":5149,"name":"projects.rst","nodeType":"TextFile","path":"doc/en","text":".. _projects:\n\n.. image:: img/gaynor3.png\n :width: 400px\n :align: right\n\n.. image:: img/theuni.png\n :width: 400px\n :align: right\n\n.. image:: img/cramer2.png\n :width: 400px\n :align: right\n\n.. image:: img/keleshev.png\n :width: 400px\n :align: right\n\n\nProject examples\n==========================\n\nHere are some examples of projects using ``pytest`` (please send notes via :ref:`contact`):\n\n* `PyPy `_, Python with a JIT compiler, running over\n `21000 tests `_\n* the `MoinMoin `_ Wiki Engine\n* `sentry `_, realtime app-maintenance and exception tracking\n* `Astropy `_ and `affiliated packages `_\n* `tox `_, virtualenv/Hudson integration tool\n* `PIDA `_ framework for integrated development\n* `PyPM `_ ActiveState's package manager\n* `Fom `_ a fluid object mapper for FluidDB\n* `applib `_ cross-platform utilities\n* `six `_ Python 2 and 3 compatibility utilities\n* `pediapress `_ MediaWiki articles\n* `mwlib `_ mediawiki parser and utility library\n* `The Translate Toolkit `_ for localization and conversion\n* `execnet `_ rapid multi-Python deployment\n* `pylib `_ cross-platform path, IO, dynamic code library\n* `Pacha `_ configuration management in five minutes\n* `bbfreeze `_ create standalone executables from Python scripts\n* `pdb++ `_ a fancier version of PDB\n* `py-s3fuse `_ Amazon S3 FUSE based filesystem\n* `waskr `_ WSGI Stats Middleware\n* `guachi `_ global persistent configs for Python modules\n* `Circuits `_ lightweight Event Driven Framework\n* `pygtk-helpers `_ easy interaction with PyGTK\n* `QuantumCore `_ statusmessage and repoze openid plugin\n* `pydataportability `_ libraries for managing the open web\n* `XIST `_ extensible HTML/XML generator\n* `tiddlyweb `_ optionally headless, extensible RESTful datastore\n* `fancycompleter `_ for colorful tab-completion\n* `Paludis `_ tools for Gentoo Paludis package manager\n* `Gerald `_ schema comparison tool\n* `abjad `_ Python API for Formalized Score control\n* `bu `_ a microscopic build system\n* `katcp `_ Telescope communication protocol over Twisted\n* `kss plugin timer `_\n* `pyudev `_ a pure Python binding to the Linux library libudev\n* `pytest-localserver `_ a plugin for pytest that provides an httpserver and smtpserver\n* `pytest-monkeyplus `_ a plugin that extends monkeypatch\n\nThese projects help integrate ``pytest`` into other Python frameworks:\n\n* `pytest-django `_ for Django\n* `zope.pytest `_ for Zope and Grok\n* `pytest_gae `_ for Google App Engine\n* There is `some work `_ underway for Kotti, a CMS built in Pyramid/Pylons\n\n\nSome organisations using pytest\n-----------------------------------\n\n* `Square Kilometre Array, Cape Town `_\n* `Some Mozilla QA people `_ use pytest to distribute their Selenium tests\n* `Tandberg `_\n* `Shootq `_\n* `Stups department of Heinrich Heine University Duesseldorf `_\n* `cellzome `_\n* `Open End, Gothenborg `_\n* `Laboratory of Bioinformatics, Warsaw `_\n* `merlinux, Germany `_\n* `ESSS, Brazil `_\n* many more ... (please be so kind to send a note via :ref:`contact`)\n"},{"id":5150,"name":"HOWTORELEASE.rst","nodeType":"TextFile","path":"","text":"Release Procedure\n-----------------\n\nOur current policy for releasing is to aim for a bugfix every few weeks and a minor release every 2-3 months. The idea\nis to get fixes and new features out instead of trying to cram a ton of features into a release and by consequence\ntaking a lot of time to make a new one.\n\n.. important::\n\n pytest releases must be prepared on **Linux** because the docs and examples expect\n to be executed in that platform.\n\n#. Create a branch ``release-X.Y.Z`` with the version for the release.\n\n * **patch releases**: from the latest ``master``;\n\n * **minor releases**: from the latest ``features``; then merge with the latest ``master``;\n\n Ensure your are in a clean work tree.\n\n#. Using ``tox``, generate docs, changelog, announcements::\n\n $ tox -e release -- \n\n This will generate a commit with all the changes ready for pushing.\n\n#. Open a PR for this branch targeting ``master``.\n\n#. After all tests pass and the PR has been approved, publish to PyPI by pushing the tag::\n\n git tag \n git push git@github.com:pytest-dev/pytest.git \n\n Wait for the deploy to complete, then make sure it is `available on PyPI `_.\n\n#. Merge the PR into ``master``.\n\n#. Send an email announcement with the contents from::\n\n doc/en/announce/release-.rst\n\n To the following mailing lists:\n\n * pytest-dev@python.org (all releases)\n * python-announce-list@python.org (all releases)\n * testing-in-python@lists.idyll.org (only major/minor releases)\n\n And announce it on `Twitter `_ with the ``#pytest`` hashtag.\n"},{"id":5151,"name":"LICENSE","nodeType":"TextFile","path":"doc/en/_themes","text":"Copyright (c) 2010 by Armin Ronacher.\n\nSome rights reserved.\n\nRedistribution and use in source and binary forms of the theme, with or\nwithout modification, are permitted provided that the following conditions\nare met:\n\n* Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n\n* The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n\nWe kindly ask you to only use these themes in an unmodified manner just\nfor Flask and Flask-related products, not for unrelated projects. If you\nlike the visual style and want to use it for your own projects, please\nconsider making some larger changes to the themes (such as changing\nfont faces, sizes, colors or margins).\n\nTHIS THEME IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS THEME, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n"},{"id":5152,"name":"theme.conf","nodeType":"TextFile","path":"doc/en/_themes/flask","text":"[theme]\ninherit = basic\nstylesheet = flasky.css\npygments_style = flask_theme_support.FlaskyStyle\n\n[options]\nindex_logo = ''\nindex_logo_height = 120px\ntouch_icon =\n"},{"id":5153,"name":"testing/example_scripts/collect/package_infinite_recursion","nodeType":"Package"},{"fileName":"conftest.py","filePath":"testing/example_scripts/collect/package_infinite_recursion","id":5154,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ndef pytest_ignore_collect(path):\n return False\n"},{"col":0,"comment":"null","endLoc":3,"header":"def pytest_ignore_collect(path)","id":5155,"name":"pytest_ignore_collect","nodeType":"Function","startLoc":2,"text":"def pytest_ignore_collect(path):\n return False"},{"id":5156,"name":"testing/example_scripts/tmpdir","nodeType":"Package"},{"fileName":"tmpdir_fixture.py","filePath":"testing/example_scripts/tmpdir","id":5157,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\n@pytest.mark.parametrize(\"a\", [r\"qwe/\\abc\"])\ndef test_fixture(tmpdir, a):\n tmpdir.check(dir=1)\n assert tmpdir.listdir() == []\n"},{"col":0,"comment":"null","endLoc":8,"header":"@pytest.mark.parametrize(\"a\", [r\"qwe/\\abc\"])\ndef test_fixture(tmpdir, a)","id":5158,"name":"test_fixture","nodeType":"Function","startLoc":5,"text":"@pytest.mark.parametrize(\"a\", [r\"qwe/\\abc\"])\ndef test_fixture(tmpdir, a):\n tmpdir.check(dir=1)\n assert tmpdir.listdir() == []"},{"id":5159,"name":".gitattributes","nodeType":"TextFile","path":"","text":"*.bat text eol=crlf\n"},{"col":0,"comment":"null","endLoc":1354,"header":"def _showfixtures_main(config, session)","id":5162,"name":"_showfixtures_main","nodeType":"Function","startLoc":1300,"text":"def _showfixtures_main(config, session):\n import _pytest.config\n\n session.perform_collect()\n curdir = py.path.local()\n tw = _pytest.config.create_terminal_writer(config)\n verbose = config.getvalue(\"verbose\")\n\n fm = session._fixturemanager\n\n available = []\n seen = set()\n\n for argname, fixturedefs in fm._arg2fixturedefs.items():\n assert fixturedefs is not None\n if not fixturedefs:\n continue\n for fixturedef in fixturedefs:\n loc = getlocation(fixturedef.func, curdir)\n if (fixturedef.argname, loc) in seen:\n continue\n seen.add((fixturedef.argname, loc))\n available.append(\n (\n len(fixturedef.baseid),\n fixturedef.func.__module__,\n curdir.bestrelpath(loc),\n fixturedef.argname,\n fixturedef,\n )\n )\n\n available.sort()\n currentmodule = None\n for baseid, module, bestrel, argname, fixturedef in available:\n if currentmodule != module:\n if not module.startswith(\"_pytest.\"):\n tw.line()\n tw.sep(\"-\", \"fixtures defined from %s\" % (module,))\n currentmodule = module\n if verbose <= 0 and argname[0] == \"_\":\n continue\n tw.write(argname, green=True)\n if fixturedef.scope != \"function\":\n tw.write(\" [%s scope]\" % fixturedef.scope, cyan=True)\n if verbose > 0:\n tw.write(\" -- %s\" % bestrel, yellow=True)\n tw.write(\"\\n\")\n loc = getlocation(fixturedef.func, curdir)\n doc = fixturedef.func.__doc__ or \"\"\n if doc:\n write_docstring(tw, doc)\n else:\n tw.line(\" %s: no docstring available\" % (loc,), red=True)\n tw.line()"},{"col":4,"comment":"null","endLoc":844,"header":"def summary_failures(self)","id":5163,"name":"summary_failures","nodeType":"Function","startLoc":823,"text":"def summary_failures(self):\n if self.config.option.tbstyle != \"no\":\n reports = self.getreports(\"failed\")\n if not reports:\n return\n self.write_sep(\"=\", \"FAILURES\")\n if self.config.option.tbstyle == \"line\":\n for rep in reports:\n line = self._getcrashline(rep)\n self.write_line(line)\n else:\n teardown_sections = {}\n for report in self.getreports(\"\"):\n if report.when == \"teardown\":\n teardown_sections.setdefault(report.nodeid, []).append(report)\n\n for rep in reports:\n msg = self._getfailureheadline(rep)\n self.write_sep(\"_\", msg, red=True, bold=True)\n self._outrep_summary(rep)\n for report in teardown_sections.get(rep.nodeid, []):\n self.print_teardown_sections(report)"},{"col":4,"comment":"null","endLoc":747,"header":"def _getcrashline(self, rep)","id":5164,"name":"_getcrashline","nodeType":"Function","startLoc":740,"text":"def _getcrashline(self, rep):\n try:\n return str(rep.longrepr.reprcrash)\n except AttributeError:\n try:\n return str(rep.longrepr)[:50]\n except AttributeError:\n return \"\""},{"col":4,"comment":"null","endLoc":821,"header":"def print_teardown_sections(self, rep)","id":5165,"name":"print_teardown_sections","nodeType":"Function","startLoc":810,"text":"def print_teardown_sections(self, rep):\n showcapture = self.config.option.showcapture\n if showcapture == \"no\":\n return\n for secname, content in rep.sections:\n if showcapture != \"all\" and showcapture not in secname:\n continue\n if \"teardown\" in secname:\n self._tw.sep(\"-\", secname)\n if content[-1:] == \"\\n\":\n content = content[:-1]\n self._tw.line(content)"},{"fileName":"pytester.py","filePath":"src/_pytest","id":5166,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"(disabled by default) support for testing pytest and pytest plugins.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport codecs\nimport gc\nimport os\nimport platform\nimport re\nimport subprocess\nimport sys\nimport time\nimport traceback\nfrom fnmatch import fnmatch\nfrom weakref import WeakKeyDictionary\n\nimport py\nimport six\n\nimport pytest\nfrom _pytest._code import Source\nfrom _pytest._io.saferepr import saferepr\nfrom _pytest.assertion.rewrite import AssertionRewritingHook\nfrom _pytest.capture import MultiCapture\nfrom _pytest.capture import SysCapture\nfrom _pytest.compat import safe_str\nfrom _pytest.compat import Sequence\nfrom _pytest.main import EXIT_INTERRUPTED\nfrom _pytest.main import EXIT_OK\nfrom _pytest.main import Session\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pathlib import Path\n\nIGNORE_PAM = [ # filenames added when obtaining details about the current user\n u\"/var/lib/sss/mc/passwd\"\n]\n\n\ndef pytest_addoption(parser):\n parser.addoption(\n \"--lsof\",\n action=\"store_true\",\n dest=\"lsof\",\n default=False,\n help=\"run FD checks if lsof is available\",\n )\n\n parser.addoption(\n \"--runpytest\",\n default=\"inprocess\",\n dest=\"runpytest\",\n choices=(\"inprocess\", \"subprocess\"),\n help=(\n \"run pytest sub runs in tests using an 'inprocess' \"\n \"or 'subprocess' (python -m main) method\"\n ),\n )\n\n parser.addini(\n \"pytester_example_dir\", help=\"directory to take the pytester example files from\"\n )\n\n\ndef pytest_configure(config):\n if config.getvalue(\"lsof\"):\n checker = LsofFdLeakChecker()\n if checker.matching_platform():\n config.pluginmanager.register(checker)\n\n config.addinivalue_line(\n \"markers\",\n \"pytester_example_path(*path_segments): join the given path \"\n \"segments to `pytester_example_dir` for this test.\",\n )\n\n\ndef raise_on_kwargs(kwargs):\n __tracebackhide__ = True\n if kwargs: # pragma: no branch\n raise TypeError(\n \"Unexpected keyword arguments: {}\".format(\", \".join(sorted(kwargs)))\n )\n\n\nclass LsofFdLeakChecker(object):\n def get_open_files(self):\n out = self._exec_lsof()\n open_files = self._parse_lsof_output(out)\n return open_files\n\n def _exec_lsof(self):\n pid = os.getpid()\n # py3: use subprocess.DEVNULL directly.\n with open(os.devnull, \"wb\") as devnull:\n return subprocess.check_output(\n (\"lsof\", \"-Ffn0\", \"-p\", str(pid)), stderr=devnull\n ).decode()\n\n def _parse_lsof_output(self, out):\n def isopen(line):\n return line.startswith(\"f\") and (\n \"deleted\" not in line\n and \"mem\" not in line\n and \"txt\" not in line\n and \"cwd\" not in line\n )\n\n open_files = []\n\n for line in out.split(\"\\n\"):\n if isopen(line):\n fields = line.split(\"\\0\")\n fd = fields[0][1:]\n filename = fields[1][1:]\n if filename in IGNORE_PAM:\n continue\n if filename.startswith(\"/\"):\n open_files.append((fd, filename))\n\n return open_files\n\n def matching_platform(self):\n try:\n subprocess.check_output((\"lsof\", \"-v\"))\n except (OSError, subprocess.CalledProcessError):\n return False\n else:\n return True\n\n @pytest.hookimpl(hookwrapper=True, tryfirst=True)\n def pytest_runtest_protocol(self, item):\n lines1 = self.get_open_files()\n yield\n if hasattr(sys, \"pypy_version_info\"):\n gc.collect()\n lines2 = self.get_open_files()\n\n new_fds = {t[0] for t in lines2} - {t[0] for t in lines1}\n leaked_files = [t for t in lines2 if t[0] in new_fds]\n if leaked_files:\n error = []\n error.append(\"***** %s FD leakage detected\" % len(leaked_files))\n error.extend([str(f) for f in leaked_files])\n error.append(\"*** Before:\")\n error.extend([str(f) for f in lines1])\n error.append(\"*** After:\")\n error.extend([str(f) for f in lines2])\n error.append(error[0])\n error.append(\"*** function %s:%s: %s \" % item.location)\n error.append(\"See issue #2366\")\n item.warn(pytest.PytestWarning(\"\\n\".join(error)))\n\n\n# used at least by pytest-xdist plugin\n\n\n@pytest.fixture\ndef _pytest(request):\n \"\"\"Return a helper which offers a gethookrecorder(hook) method which\n returns a HookRecorder instance which helps to make assertions about called\n hooks.\n\n \"\"\"\n return PytestArg(request)\n\n\nclass PytestArg(object):\n def __init__(self, request):\n self.request = request\n\n def gethookrecorder(self, hook):\n hookrecorder = HookRecorder(hook._pm)\n self.request.addfinalizer(hookrecorder.finish_recording)\n return hookrecorder\n\n\ndef get_public_names(values):\n \"\"\"Only return names from iterator values without a leading underscore.\"\"\"\n return [x for x in values if x[0] != \"_\"]\n\n\nclass ParsedCall(object):\n def __init__(self, name, kwargs):\n self.__dict__.update(kwargs)\n self._name = name\n\n def __repr__(self):\n d = self.__dict__.copy()\n del d[\"_name\"]\n return \"\" % (self._name, d)\n\n\nclass HookRecorder(object):\n \"\"\"Record all hooks called in a plugin manager.\n\n This wraps all the hook calls in the plugin manager, recording each call\n before propagating the normal calls.\n\n \"\"\"\n\n def __init__(self, pluginmanager):\n self._pluginmanager = pluginmanager\n self.calls = []\n\n def before(hook_name, hook_impls, kwargs):\n self.calls.append(ParsedCall(hook_name, kwargs))\n\n def after(outcome, hook_name, hook_impls, kwargs):\n pass\n\n self._undo_wrapping = pluginmanager.add_hookcall_monitoring(before, after)\n\n def finish_recording(self):\n self._undo_wrapping()\n\n def getcalls(self, names):\n if isinstance(names, str):\n names = names.split()\n return [call for call in self.calls if call._name in names]\n\n def assert_contains(self, entries):\n __tracebackhide__ = True\n i = 0\n entries = list(entries)\n backlocals = sys._getframe(1).f_locals\n while entries:\n name, check = entries.pop(0)\n for ind, call in enumerate(self.calls[i:]):\n if call._name == name:\n print(\"NAMEMATCH\", name, call)\n if eval(check, backlocals, call.__dict__):\n print(\"CHECKERMATCH\", repr(check), \"->\", call)\n else:\n print(\"NOCHECKERMATCH\", repr(check), \"-\", call)\n continue\n i += ind + 1\n break\n print(\"NONAMEMATCH\", name, \"with\", call)\n else:\n pytest.fail(\"could not find %r check %r\" % (name, check))\n\n def popcall(self, name):\n __tracebackhide__ = True\n for i, call in enumerate(self.calls):\n if call._name == name:\n del self.calls[i]\n return call\n lines = [\"could not find call %r, in:\" % (name,)]\n lines.extend([\" %s\" % x for x in self.calls])\n pytest.fail(\"\\n\".join(lines))\n\n def getcall(self, name):\n values = self.getcalls(name)\n assert len(values) == 1, (name, values)\n return values[0]\n\n # functionality for test reports\n\n def getreports(self, names=\"pytest_runtest_logreport pytest_collectreport\"):\n return [x.report for x in self.getcalls(names)]\n\n def matchreport(\n self,\n inamepart=\"\",\n names=\"pytest_runtest_logreport pytest_collectreport\",\n when=None,\n ):\n \"\"\"return a testreport whose dotted import path matches\"\"\"\n values = []\n for rep in self.getreports(names=names):\n if not when and rep.when != \"call\" and rep.passed:\n # setup/teardown passing reports - let's ignore those\n continue\n if when and rep.when != when:\n continue\n if not inamepart or inamepart in rep.nodeid.split(\"::\"):\n values.append(rep)\n if not values:\n raise ValueError(\n \"could not find test report matching %r: \"\n \"no test reports at all!\" % (inamepart,)\n )\n if len(values) > 1:\n raise ValueError(\n \"found 2 or more testreports matching %r: %s\" % (inamepart, values)\n )\n return values[0]\n\n def getfailures(self, names=\"pytest_runtest_logreport pytest_collectreport\"):\n return [rep for rep in self.getreports(names) if rep.failed]\n\n def getfailedcollections(self):\n return self.getfailures(\"pytest_collectreport\")\n\n def listoutcomes(self):\n passed = []\n skipped = []\n failed = []\n for rep in self.getreports(\"pytest_collectreport pytest_runtest_logreport\"):\n if rep.passed:\n if rep.when == \"call\":\n passed.append(rep)\n elif rep.skipped:\n skipped.append(rep)\n else:\n assert rep.failed, \"Unexpected outcome: {!r}\".format(rep)\n failed.append(rep)\n return passed, skipped, failed\n\n def countoutcomes(self):\n return [len(x) for x in self.listoutcomes()]\n\n def assertoutcome(self, passed=0, skipped=0, failed=0):\n realpassed, realskipped, realfailed = self.listoutcomes()\n assert passed == len(realpassed)\n assert skipped == len(realskipped)\n assert failed == len(realfailed)\n\n def clear(self):\n self.calls[:] = []\n\n\n@pytest.fixture\ndef linecomp(request):\n return LineComp()\n\n\n@pytest.fixture(name=\"LineMatcher\")\ndef LineMatcher_fixture(request):\n return LineMatcher\n\n\n@pytest.fixture\ndef testdir(request, tmpdir_factory):\n return Testdir(request, tmpdir_factory)\n\n\n@pytest.fixture\ndef _sys_snapshot():\n snappaths = SysPathsSnapshot()\n snapmods = SysModulesSnapshot()\n yield\n snapmods.restore()\n snappaths.restore()\n\n\n@pytest.fixture\ndef _config_for_test():\n from _pytest.config import get_config\n\n config = get_config()\n yield config\n config._ensure_unconfigure() # cleanup, e.g. capman closing tmpfiles.\n\n\nrex_outcome = re.compile(r\"(\\d+) ([\\w-]+)\")\n\n\nclass RunResult(object):\n \"\"\"The result of running a command.\n\n Attributes:\n\n :ret: the return value\n :outlines: list of lines captured from stdout\n :errlines: list of lines captures from stderr\n :stdout: :py:class:`LineMatcher` of stdout, use ``stdout.str()`` to\n reconstruct stdout or the commonly used ``stdout.fnmatch_lines()``\n method\n :stderr: :py:class:`LineMatcher` of stderr\n :duration: duration in seconds\n\n \"\"\"\n\n def __init__(self, ret, outlines, errlines, duration):\n self.ret = ret\n self.outlines = outlines\n self.errlines = errlines\n self.stdout = LineMatcher(outlines)\n self.stderr = LineMatcher(errlines)\n self.duration = duration\n\n def __repr__(self):\n return (\n \"\"\n % (self.ret, len(self.stdout.lines), len(self.stderr.lines), self.duration)\n )\n\n def parseoutcomes(self):\n \"\"\"Return a dictionary of outcomestring->num from parsing the terminal\n output that the test process produced.\n\n \"\"\"\n for line in reversed(self.outlines):\n if \"seconds\" in line:\n outcomes = rex_outcome.findall(line)\n if outcomes:\n d = {}\n for num, cat in outcomes:\n d[cat] = int(num)\n return d\n raise ValueError(\"Pytest terminal report not found\")\n\n def assert_outcomes(\n self, passed=0, skipped=0, failed=0, error=0, xpassed=0, xfailed=0\n ):\n \"\"\"Assert that the specified outcomes appear with the respective\n numbers (0 means it didn't occur) in the text output from a test run.\n\n \"\"\"\n d = self.parseoutcomes()\n obtained = {\n \"passed\": d.get(\"passed\", 0),\n \"skipped\": d.get(\"skipped\", 0),\n \"failed\": d.get(\"failed\", 0),\n \"error\": d.get(\"error\", 0),\n \"xpassed\": d.get(\"xpassed\", 0),\n \"xfailed\": d.get(\"xfailed\", 0),\n }\n expected = {\n \"passed\": passed,\n \"skipped\": skipped,\n \"failed\": failed,\n \"error\": error,\n \"xpassed\": xpassed,\n \"xfailed\": xfailed,\n }\n assert obtained == expected\n\n\nclass CwdSnapshot(object):\n def __init__(self):\n self.__saved = os.getcwd()\n\n def restore(self):\n os.chdir(self.__saved)\n\n\nclass SysModulesSnapshot(object):\n def __init__(self, preserve=None):\n self.__preserve = preserve\n self.__saved = dict(sys.modules)\n\n def restore(self):\n if self.__preserve:\n self.__saved.update(\n (k, m) for k, m in sys.modules.items() if self.__preserve(k)\n )\n sys.modules.clear()\n sys.modules.update(self.__saved)\n\n\nclass SysPathsSnapshot(object):\n def __init__(self):\n self.__saved = list(sys.path), list(sys.meta_path)\n\n def restore(self):\n sys.path[:], sys.meta_path[:] = self.__saved\n\n\nclass Testdir(object):\n \"\"\"Temporary test directory with tools to test/run pytest itself.\n\n This is based on the ``tmpdir`` fixture but provides a number of methods\n which aid with testing pytest itself. Unless :py:meth:`chdir` is used all\n methods will use :py:attr:`tmpdir` as their current working directory.\n\n Attributes:\n\n :tmpdir: The :py:class:`py.path.local` instance of the temporary directory.\n\n :plugins: A list of plugins to use with :py:meth:`parseconfig` and\n :py:meth:`runpytest`. Initially this is an empty list but plugins can\n be added to the list. The type of items to add to the list depends on\n the method using them so refer to them for details.\n\n \"\"\"\n\n CLOSE_STDIN = object\n\n class TimeoutExpired(Exception):\n pass\n\n def __init__(self, request, tmpdir_factory):\n self.request = request\n self._mod_collections = WeakKeyDictionary()\n name = request.function.__name__\n self.tmpdir = tmpdir_factory.mktemp(name, numbered=True)\n self.test_tmproot = tmpdir_factory.mktemp(\"tmp-\" + name, numbered=True)\n self.plugins = []\n self._cwd_snapshot = CwdSnapshot()\n self._sys_path_snapshot = SysPathsSnapshot()\n self._sys_modules_snapshot = self.__take_sys_modules_snapshot()\n self.chdir()\n self.request.addfinalizer(self.finalize)\n method = self.request.config.getoption(\"--runpytest\")\n if method == \"inprocess\":\n self._runpytest_method = self.runpytest_inprocess\n elif method == \"subprocess\":\n self._runpytest_method = self.runpytest_subprocess\n\n mp = self.monkeypatch = MonkeyPatch()\n mp.setenv(\"PYTEST_DEBUG_TEMPROOT\", str(self.test_tmproot))\n # Ensure no unexpected caching via tox.\n mp.delenv(\"TOX_ENV_DIR\", raising=False)\n # Discard outer pytest options.\n mp.delenv(\"PYTEST_ADDOPTS\", raising=False)\n\n # Environment (updates) for inner runs.\n tmphome = str(self.tmpdir)\n self._env_run_update = {\"HOME\": tmphome, \"USERPROFILE\": tmphome}\n\n def __repr__(self):\n return \"\" % (self.tmpdir,)\n\n def __str__(self):\n return str(self.tmpdir)\n\n def finalize(self):\n \"\"\"Clean up global state artifacts.\n\n Some methods modify the global interpreter state and this tries to\n clean this up. It does not remove the temporary directory however so\n it can be looked at after the test run has finished.\n\n \"\"\"\n self._sys_modules_snapshot.restore()\n self._sys_path_snapshot.restore()\n self._cwd_snapshot.restore()\n self.monkeypatch.undo()\n\n def __take_sys_modules_snapshot(self):\n # some zope modules used by twisted-related tests keep internal state\n # and can't be deleted; we had some trouble in the past with\n # `zope.interface` for example\n def preserve_module(name):\n return name.startswith(\"zope\")\n\n return SysModulesSnapshot(preserve=preserve_module)\n\n def make_hook_recorder(self, pluginmanager):\n \"\"\"Create a new :py:class:`HookRecorder` for a PluginManager.\"\"\"\n pluginmanager.reprec = reprec = HookRecorder(pluginmanager)\n self.request.addfinalizer(reprec.finish_recording)\n return reprec\n\n def chdir(self):\n \"\"\"Cd into the temporary directory.\n\n This is done automatically upon instantiation.\n\n \"\"\"\n self.tmpdir.chdir()\n\n def _makefile(self, ext, args, kwargs, encoding=\"utf-8\"):\n items = list(kwargs.items())\n\n def to_text(s):\n return s.decode(encoding) if isinstance(s, bytes) else six.text_type(s)\n\n if args:\n source = u\"\\n\".join(to_text(x) for x in args)\n basename = self.request.function.__name__\n items.insert(0, (basename, source))\n\n ret = None\n for basename, value in items:\n p = self.tmpdir.join(basename).new(ext=ext)\n p.dirpath().ensure_dir()\n source = Source(value)\n source = u\"\\n\".join(to_text(line) for line in source.lines)\n p.write(source.strip().encode(encoding), \"wb\")\n if ret is None:\n ret = p\n return ret\n\n def makefile(self, ext, *args, **kwargs):\n r\"\"\"Create new file(s) in the testdir.\n\n :param str ext: The extension the file(s) should use, including the dot, e.g. `.py`.\n :param list[str] args: All args will be treated as strings and joined using newlines.\n The result will be written as contents to the file. The name of the\n file will be based on the test function requesting this fixture.\n :param kwargs: Each keyword is the name of a file, while the value of it will\n be written as contents of the file.\n\n Examples:\n\n .. code-block:: python\n\n testdir.makefile(\".txt\", \"line1\", \"line2\")\n\n testdir.makefile(\".ini\", pytest=\"[pytest]\\naddopts=-rs\\n\")\n\n \"\"\"\n return self._makefile(ext, args, kwargs)\n\n def makeconftest(self, source):\n \"\"\"Write a contest.py file with 'source' as contents.\"\"\"\n return self.makepyfile(conftest=source)\n\n def makeini(self, source):\n \"\"\"Write a tox.ini file with 'source' as contents.\"\"\"\n return self.makefile(\".ini\", tox=source)\n\n def getinicfg(self, source):\n \"\"\"Return the pytest section from the tox.ini config file.\"\"\"\n p = self.makeini(source)\n return py.iniconfig.IniConfig(p)[\"pytest\"]\n\n def makepyfile(self, *args, **kwargs):\n \"\"\"Shortcut for .makefile() with a .py extension.\"\"\"\n return self._makefile(\".py\", args, kwargs)\n\n def maketxtfile(self, *args, **kwargs):\n \"\"\"Shortcut for .makefile() with a .txt extension.\"\"\"\n return self._makefile(\".txt\", args, kwargs)\n\n def syspathinsert(self, path=None):\n \"\"\"Prepend a directory to sys.path, defaults to :py:attr:`tmpdir`.\n\n This is undone automatically when this object dies at the end of each\n test.\n \"\"\"\n if path is None:\n path = self.tmpdir\n\n self.monkeypatch.syspath_prepend(str(path))\n\n def mkdir(self, name):\n \"\"\"Create a new (sub)directory.\"\"\"\n return self.tmpdir.mkdir(name)\n\n def mkpydir(self, name):\n \"\"\"Create a new python package.\n\n This creates a (sub)directory with an empty ``__init__.py`` file so it\n gets recognised as a python package.\n\n \"\"\"\n p = self.mkdir(name)\n p.ensure(\"__init__.py\")\n return p\n\n def copy_example(self, name=None):\n import warnings\n from _pytest.warning_types import PYTESTER_COPY_EXAMPLE\n\n warnings.warn(PYTESTER_COPY_EXAMPLE, stacklevel=2)\n example_dir = self.request.config.getini(\"pytester_example_dir\")\n if example_dir is None:\n raise ValueError(\"pytester_example_dir is unset, can't copy examples\")\n example_dir = self.request.config.rootdir.join(example_dir)\n\n for extra_element in self.request.node.iter_markers(\"pytester_example_path\"):\n assert extra_element.args\n example_dir = example_dir.join(*extra_element.args)\n\n if name is None:\n func_name = self.request.function.__name__\n maybe_dir = example_dir / func_name\n maybe_file = example_dir / (func_name + \".py\")\n\n if maybe_dir.isdir():\n example_path = maybe_dir\n elif maybe_file.isfile():\n example_path = maybe_file\n else:\n raise LookupError(\n \"{} cant be found as module or package in {}\".format(\n func_name, example_dir.bestrelpath(self.request.config.rootdir)\n )\n )\n else:\n example_path = example_dir.join(name)\n\n if example_path.isdir() and not example_path.join(\"__init__.py\").isfile():\n example_path.copy(self.tmpdir)\n return self.tmpdir\n elif example_path.isfile():\n result = self.tmpdir.join(example_path.basename)\n example_path.copy(result)\n return result\n else:\n raise LookupError(\n 'example \"{}\" is not found as a file or directory'.format(example_path)\n )\n\n Session = Session\n\n def getnode(self, config, arg):\n \"\"\"Return the collection node of a file.\n\n :param config: :py:class:`_pytest.config.Config` instance, see\n :py:meth:`parseconfig` and :py:meth:`parseconfigure` to create the\n configuration\n\n :param arg: a :py:class:`py.path.local` instance of the file\n\n \"\"\"\n session = Session(config)\n assert \"::\" not in str(arg)\n p = py.path.local(arg)\n config.hook.pytest_sessionstart(session=session)\n res = session.perform_collect([str(p)], genitems=False)[0]\n config.hook.pytest_sessionfinish(session=session, exitstatus=EXIT_OK)\n return res\n\n def getpathnode(self, path):\n \"\"\"Return the collection node of a file.\n\n This is like :py:meth:`getnode` but uses :py:meth:`parseconfigure` to\n create the (configured) pytest Config instance.\n\n :param path: a :py:class:`py.path.local` instance of the file\n\n \"\"\"\n config = self.parseconfigure(path)\n session = Session(config)\n x = session.fspath.bestrelpath(path)\n config.hook.pytest_sessionstart(session=session)\n res = session.perform_collect([x], genitems=False)[0]\n config.hook.pytest_sessionfinish(session=session, exitstatus=EXIT_OK)\n return res\n\n def genitems(self, colitems):\n \"\"\"Generate all test items from a collection node.\n\n This recurses into the collection node and returns a list of all the\n test items contained within.\n\n \"\"\"\n session = colitems[0].session\n result = []\n for colitem in colitems:\n result.extend(session.genitems(colitem))\n return result\n\n def runitem(self, source):\n \"\"\"Run the \"test_func\" Item.\n\n The calling test instance (class containing the test method) must\n provide a ``.getrunner()`` method which should return a runner which\n can run the test protocol for a single item, e.g.\n :py:func:`_pytest.runner.runtestprotocol`.\n\n \"\"\"\n # used from runner functional tests\n item = self.getitem(source)\n # the test class where we are called from wants to provide the runner\n testclassinstance = self.request.instance\n runner = testclassinstance.getrunner()\n return runner(item)\n\n def inline_runsource(self, source, *cmdlineargs):\n \"\"\"Run a test module in process using ``pytest.main()``.\n\n This run writes \"source\" into a temporary file and runs\n ``pytest.main()`` on it, returning a :py:class:`HookRecorder` instance\n for the result.\n\n :param source: the source code of the test module\n\n :param cmdlineargs: any extra command line arguments to use\n\n :return: :py:class:`HookRecorder` instance of the result\n\n \"\"\"\n p = self.makepyfile(source)\n values = list(cmdlineargs) + [p]\n return self.inline_run(*values)\n\n def inline_genitems(self, *args):\n \"\"\"Run ``pytest.main(['--collectonly'])`` in-process.\n\n Runs the :py:func:`pytest.main` function to run all of pytest inside\n the test process itself like :py:meth:`inline_run`, but returns a\n tuple of the collected items and a :py:class:`HookRecorder` instance.\n\n \"\"\"\n rec = self.inline_run(\"--collect-only\", *args)\n items = [x.item for x in rec.getcalls(\"pytest_itemcollected\")]\n return items, rec\n\n def inline_run(self, *args, **kwargs):\n \"\"\"Run ``pytest.main()`` in-process, returning a HookRecorder.\n\n Runs the :py:func:`pytest.main` function to run all of pytest inside\n the test process itself. This means it can return a\n :py:class:`HookRecorder` instance which gives more detailed results\n from that run than can be done by matching stdout/stderr from\n :py:meth:`runpytest`.\n\n :param args: command line arguments to pass to :py:func:`pytest.main`\n\n :param plugins: (keyword-only) extra plugin instances the\n ``pytest.main()`` instance should use\n\n :return: a :py:class:`HookRecorder` instance\n \"\"\"\n plugins = kwargs.pop(\"plugins\", [])\n no_reraise_ctrlc = kwargs.pop(\"no_reraise_ctrlc\", None)\n raise_on_kwargs(kwargs)\n\n finalizers = []\n try:\n # Do not load user config (during runs only).\n mp_run = MonkeyPatch()\n for k, v in self._env_run_update.items():\n mp_run.setenv(k, v)\n finalizers.append(mp_run.undo)\n\n # When running pytest inline any plugins active in the main test\n # process are already imported. So this disables the warning which\n # will trigger to say they can no longer be rewritten, which is\n # fine as they have already been rewritten.\n orig_warn = AssertionRewritingHook._warn_already_imported\n\n def revert_warn_already_imported():\n AssertionRewritingHook._warn_already_imported = orig_warn\n\n finalizers.append(revert_warn_already_imported)\n AssertionRewritingHook._warn_already_imported = lambda *a: None\n\n # Any sys.module or sys.path changes done while running pytest\n # inline should be reverted after the test run completes to avoid\n # clashing with later inline tests run within the same pytest test,\n # e.g. just because they use matching test module names.\n finalizers.append(self.__take_sys_modules_snapshot().restore)\n finalizers.append(SysPathsSnapshot().restore)\n\n # Important note:\n # - our tests should not leave any other references/registrations\n # laying around other than possibly loaded test modules\n # referenced from sys.modules, as nothing will clean those up\n # automatically\n\n rec = []\n\n class Collect(object):\n def pytest_configure(x, config):\n rec.append(self.make_hook_recorder(config.pluginmanager))\n\n plugins.append(Collect())\n ret = pytest.main(list(args), plugins=plugins)\n if len(rec) == 1:\n reprec = rec.pop()\n else:\n\n class reprec(object):\n pass\n\n reprec.ret = ret\n\n # typically we reraise keyboard interrupts from the child run\n # because it's our user requesting interruption of the testing\n if ret == EXIT_INTERRUPTED and not no_reraise_ctrlc:\n calls = reprec.getcalls(\"pytest_keyboard_interrupt\")\n if calls and calls[-1].excinfo.type == KeyboardInterrupt:\n raise KeyboardInterrupt()\n return reprec\n finally:\n for finalizer in finalizers:\n finalizer()\n\n def runpytest_inprocess(self, *args, **kwargs):\n \"\"\"Return result of running pytest in-process, providing a similar\n interface to what self.runpytest() provides.\n \"\"\"\n syspathinsert = kwargs.pop(\"syspathinsert\", False)\n\n if syspathinsert:\n self.syspathinsert()\n now = time.time()\n capture = MultiCapture(Capture=SysCapture)\n capture.start_capturing()\n try:\n try:\n reprec = self.inline_run(*args, **kwargs)\n except SystemExit as e:\n\n class reprec(object):\n ret = e.args[0]\n\n except Exception:\n traceback.print_exc()\n\n class reprec(object):\n ret = 3\n\n finally:\n out, err = capture.readouterr()\n capture.stop_capturing()\n sys.stdout.write(out)\n sys.stderr.write(err)\n\n res = RunResult(reprec.ret, out.split(\"\\n\"), err.split(\"\\n\"), time.time() - now)\n res.reprec = reprec\n return res\n\n def runpytest(self, *args, **kwargs):\n \"\"\"Run pytest inline or in a subprocess, depending on the command line\n option \"--runpytest\" and return a :py:class:`RunResult`.\n\n \"\"\"\n args = self._ensure_basetemp(args)\n return self._runpytest_method(*args, **kwargs)\n\n def _ensure_basetemp(self, args):\n args = list(args)\n for x in args:\n if safe_str(x).startswith(\"--basetemp\"):\n break\n else:\n args.append(\"--basetemp=%s\" % self.tmpdir.dirpath(\"basetemp\"))\n return args\n\n def parseconfig(self, *args):\n \"\"\"Return a new pytest Config instance from given commandline args.\n\n This invokes the pytest bootstrapping code in _pytest.config to create\n a new :py:class:`_pytest.core.PluginManager` and call the\n pytest_cmdline_parse hook to create a new\n :py:class:`_pytest.config.Config` instance.\n\n If :py:attr:`plugins` has been populated they should be plugin modules\n to be registered with the PluginManager.\n\n \"\"\"\n args = self._ensure_basetemp(args)\n\n import _pytest.config\n\n config = _pytest.config._prepareconfig(args, self.plugins)\n # we don't know what the test will do with this half-setup config\n # object and thus we make sure it gets unconfigured properly in any\n # case (otherwise capturing could still be active, for example)\n self.request.addfinalizer(config._ensure_unconfigure)\n return config\n\n def parseconfigure(self, *args):\n \"\"\"Return a new pytest configured Config instance.\n\n This returns a new :py:class:`_pytest.config.Config` instance like\n :py:meth:`parseconfig`, but also calls the pytest_configure hook.\n\n \"\"\"\n config = self.parseconfig(*args)\n config._do_configure()\n self.request.addfinalizer(config._ensure_unconfigure)\n return config\n\n def getitem(self, source, funcname=\"test_func\"):\n \"\"\"Return the test item for a test function.\n\n This writes the source to a python file and runs pytest's collection on\n the resulting module, returning the test item for the requested\n function name.\n\n :param source: the module source\n\n :param funcname: the name of the test function for which to return a\n test item\n\n \"\"\"\n items = self.getitems(source)\n for item in items:\n if item.name == funcname:\n return item\n assert 0, \"%r item not found in module:\\n%s\\nitems: %s\" % (\n funcname,\n source,\n items,\n )\n\n def getitems(self, source):\n \"\"\"Return all test items collected from the module.\n\n This writes the source to a python file and runs pytest's collection on\n the resulting module, returning all test items contained within.\n\n \"\"\"\n modcol = self.getmodulecol(source)\n return self.genitems([modcol])\n\n def getmodulecol(self, source, configargs=(), withinit=False):\n \"\"\"Return the module collection node for ``source``.\n\n This writes ``source`` to a file using :py:meth:`makepyfile` and then\n runs the pytest collection on it, returning the collection node for the\n test module.\n\n :param source: the source code of the module to collect\n\n :param configargs: any extra arguments to pass to\n :py:meth:`parseconfigure`\n\n :param withinit: whether to also write an ``__init__.py`` file to the\n same directory to ensure it is a package\n\n \"\"\"\n if isinstance(source, Path):\n path = self.tmpdir.join(str(source))\n assert not withinit, \"not supported for paths\"\n else:\n kw = {self.request.function.__name__: Source(source).strip()}\n path = self.makepyfile(**kw)\n if withinit:\n self.makepyfile(__init__=\"#\")\n self.config = config = self.parseconfigure(path, *configargs)\n return self.getnode(config, path)\n\n def collect_by_name(self, modcol, name):\n \"\"\"Return the collection node for name from the module collection.\n\n This will search a module collection node for a collection node\n matching the given name.\n\n :param modcol: a module collection node; see :py:meth:`getmodulecol`\n\n :param name: the name of the node to return\n\n \"\"\"\n if modcol not in self._mod_collections:\n self._mod_collections[modcol] = list(modcol.collect())\n for colitem in self._mod_collections[modcol]:\n if colitem.name == name:\n return colitem\n\n def popen(\n self,\n cmdargs,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n stdin=CLOSE_STDIN,\n **kw\n ):\n \"\"\"Invoke subprocess.Popen.\n\n This calls subprocess.Popen making sure the current working directory\n is in the PYTHONPATH.\n\n You probably want to use :py:meth:`run` instead.\n\n \"\"\"\n env = os.environ.copy()\n env[\"PYTHONPATH\"] = os.pathsep.join(\n filter(None, [os.getcwd(), env.get(\"PYTHONPATH\", \"\")])\n )\n env.update(self._env_run_update)\n kw[\"env\"] = env\n\n if stdin is Testdir.CLOSE_STDIN:\n kw[\"stdin\"] = subprocess.PIPE\n elif isinstance(stdin, bytes):\n kw[\"stdin\"] = subprocess.PIPE\n else:\n kw[\"stdin\"] = stdin\n\n popen = subprocess.Popen(cmdargs, stdout=stdout, stderr=stderr, **kw)\n if stdin is Testdir.CLOSE_STDIN:\n popen.stdin.close()\n elif isinstance(stdin, bytes):\n popen.stdin.write(stdin)\n\n return popen\n\n def run(self, *cmdargs, **kwargs):\n \"\"\"Run a command with arguments.\n\n Run a process using subprocess.Popen saving the stdout and stderr.\n\n :param args: the sequence of arguments to pass to `subprocess.Popen()`\n :param timeout: the period in seconds after which to timeout and raise\n :py:class:`Testdir.TimeoutExpired`\n :param stdin: optional standard input. Bytes are being send, closing\n the pipe, otherwise it is passed through to ``popen``.\n Defaults to ``CLOSE_STDIN``, which translates to using a pipe\n (``subprocess.PIPE``) that gets closed.\n\n Returns a :py:class:`RunResult`.\n\n \"\"\"\n __tracebackhide__ = True\n\n timeout = kwargs.pop(\"timeout\", None)\n stdin = kwargs.pop(\"stdin\", Testdir.CLOSE_STDIN)\n raise_on_kwargs(kwargs)\n\n cmdargs = [\n str(arg) if isinstance(arg, py.path.local) else arg for arg in cmdargs\n ]\n p1 = self.tmpdir.join(\"stdout\")\n p2 = self.tmpdir.join(\"stderr\")\n print(\"running:\", *cmdargs)\n print(\" in:\", py.path.local())\n f1 = codecs.open(str(p1), \"w\", encoding=\"utf8\")\n f2 = codecs.open(str(p2), \"w\", encoding=\"utf8\")\n try:\n now = time.time()\n popen = self.popen(\n cmdargs,\n stdin=stdin,\n stdout=f1,\n stderr=f2,\n close_fds=(sys.platform != \"win32\"),\n )\n if isinstance(stdin, bytes):\n popen.stdin.close()\n\n def handle_timeout():\n __tracebackhide__ = True\n\n timeout_message = (\n \"{seconds} second timeout expired running:\"\n \" {command}\".format(seconds=timeout, command=cmdargs)\n )\n\n popen.kill()\n popen.wait()\n raise self.TimeoutExpired(timeout_message)\n\n if timeout is None:\n ret = popen.wait()\n elif not six.PY2:\n try:\n ret = popen.wait(timeout)\n except subprocess.TimeoutExpired:\n handle_timeout()\n else:\n end = time.time() + timeout\n\n resolution = min(0.1, timeout / 10)\n\n while True:\n ret = popen.poll()\n if ret is not None:\n break\n\n if time.time() > end:\n handle_timeout()\n\n time.sleep(resolution)\n finally:\n f1.close()\n f2.close()\n f1 = codecs.open(str(p1), \"r\", encoding=\"utf8\")\n f2 = codecs.open(str(p2), \"r\", encoding=\"utf8\")\n try:\n out = f1.read().splitlines()\n err = f2.read().splitlines()\n finally:\n f1.close()\n f2.close()\n self._dump_lines(out, sys.stdout)\n self._dump_lines(err, sys.stderr)\n return RunResult(ret, out, err, time.time() - now)\n\n def _dump_lines(self, lines, fp):\n try:\n for line in lines:\n print(line, file=fp)\n except UnicodeEncodeError:\n print(\"couldn't print to %s because of encoding\" % (fp,))\n\n def _getpytestargs(self):\n return sys.executable, \"-mpytest\"\n\n def runpython(self, script):\n \"\"\"Run a python script using sys.executable as interpreter.\n\n Returns a :py:class:`RunResult`.\n\n \"\"\"\n return self.run(sys.executable, script)\n\n def runpython_c(self, command):\n \"\"\"Run python -c \"command\", return a :py:class:`RunResult`.\"\"\"\n return self.run(sys.executable, \"-c\", command)\n\n def runpytest_subprocess(self, *args, **kwargs):\n \"\"\"Run pytest as a subprocess with given arguments.\n\n Any plugins added to the :py:attr:`plugins` list will be added using the\n ``-p`` command line option. Additionally ``--basetemp`` is used to put\n any temporary files and directories in a numbered directory prefixed\n with \"runpytest-\" to not conflict with the normal numbered pytest\n location for temporary files and directories.\n\n :param args: the sequence of arguments to pass to the pytest subprocess\n :param timeout: the period in seconds after which to timeout and raise\n :py:class:`Testdir.TimeoutExpired`\n\n Returns a :py:class:`RunResult`.\n \"\"\"\n __tracebackhide__ = True\n timeout = kwargs.pop(\"timeout\", None)\n raise_on_kwargs(kwargs)\n\n p = py.path.local.make_numbered_dir(\n prefix=\"runpytest-\", keep=None, rootdir=self.tmpdir\n )\n args = (\"--basetemp=%s\" % p,) + args\n plugins = [x for x in self.plugins if isinstance(x, str)]\n if plugins:\n args = (\"-p\", plugins[0]) + args\n args = self._getpytestargs() + args\n return self.run(*args, timeout=timeout)\n\n def spawn_pytest(self, string, expect_timeout=10.0):\n \"\"\"Run pytest using pexpect.\n\n This makes sure to use the right pytest and sets up the temporary\n directory locations.\n\n The pexpect child is returned.\n\n \"\"\"\n basetemp = self.tmpdir.mkdir(\"temp-pexpect\")\n invoke = \" \".join(map(str, self._getpytestargs()))\n cmd = \"%s --basetemp=%s %s\" % (invoke, basetemp, string)\n return self.spawn(cmd, expect_timeout=expect_timeout)\n\n def spawn(self, cmd, expect_timeout=10.0):\n \"\"\"Run a command using pexpect.\n\n The pexpect child is returned.\n\n \"\"\"\n pexpect = pytest.importorskip(\"pexpect\", \"3.0\")\n if hasattr(sys, \"pypy_version_info\") and \"64\" in platform.machine():\n pytest.skip(\"pypy-64 bit not supported\")\n if sys.platform.startswith(\"freebsd\"):\n pytest.xfail(\"pexpect does not work reliably on freebsd\")\n logfile = self.tmpdir.join(\"spawn.out\").open(\"wb\")\n\n # Do not load user config.\n env = os.environ.copy()\n env.update(self._env_run_update)\n\n child = pexpect.spawn(cmd, logfile=logfile, env=env)\n self.request.addfinalizer(logfile.close)\n child.timeout = expect_timeout\n return child\n\n\ndef getdecoded(out):\n try:\n return out.decode(\"utf-8\")\n except UnicodeDecodeError:\n return \"INTERNAL not-utf8-decodeable, truncated string:\\n%s\" % (saferepr(out),)\n\n\nclass LineComp(object):\n def __init__(self):\n self.stringio = py.io.TextIO()\n\n def assert_contains_lines(self, lines2):\n \"\"\"Assert that lines2 are contained (linearly) in lines1.\n\n Return a list of extralines found.\n\n \"\"\"\n __tracebackhide__ = True\n val = self.stringio.getvalue()\n self.stringio.truncate(0)\n self.stringio.seek(0)\n lines1 = val.split(\"\\n\")\n return LineMatcher(lines1).fnmatch_lines(lines2)\n\n\nclass LineMatcher(object):\n \"\"\"Flexible matching of text.\n\n This is a convenience class to test large texts like the output of\n commands.\n\n The constructor takes a list of lines without their trailing newlines, i.e.\n ``text.splitlines()``.\n\n \"\"\"\n\n def __init__(self, lines):\n self.lines = lines\n self._log_output = []\n\n def str(self):\n \"\"\"Return the entire original text.\"\"\"\n return \"\\n\".join(self.lines)\n\n def _getlines(self, lines2):\n if isinstance(lines2, str):\n lines2 = Source(lines2)\n if isinstance(lines2, Source):\n lines2 = lines2.strip().lines\n return lines2\n\n def fnmatch_lines_random(self, lines2):\n \"\"\"Check lines exist in the output using in any order.\n\n Lines are checked using ``fnmatch.fnmatch``. The argument is a list of\n lines which have to occur in the output, in any order.\n\n \"\"\"\n self._match_lines_random(lines2, fnmatch)\n\n def re_match_lines_random(self, lines2):\n \"\"\"Check lines exist in the output using ``re.match``, in any order.\n\n The argument is a list of lines which have to occur in the output, in\n any order.\n\n \"\"\"\n self._match_lines_random(lines2, lambda name, pat: re.match(pat, name))\n\n def _match_lines_random(self, lines2, match_func):\n \"\"\"Check lines exist in the output.\n\n The argument is a list of lines which have to occur in the output, in\n any order. Each line can contain glob whildcards.\n\n \"\"\"\n lines2 = self._getlines(lines2)\n for line in lines2:\n for x in self.lines:\n if line == x or match_func(x, line):\n self._log(\"matched: \", repr(line))\n break\n else:\n self._log(\"line %r not found in output\" % line)\n raise ValueError(self._log_text)\n\n def get_lines_after(self, fnline):\n \"\"\"Return all lines following the given line in the text.\n\n The given line can contain glob wildcards.\n\n \"\"\"\n for i, line in enumerate(self.lines):\n if fnline == line or fnmatch(line, fnline):\n return self.lines[i + 1 :]\n raise ValueError(\"line %r not found in output\" % fnline)\n\n def _log(self, *args):\n self._log_output.append(\" \".join(str(x) for x in args))\n\n @property\n def _log_text(self):\n return \"\\n\".join(self._log_output)\n\n def fnmatch_lines(self, lines2):\n \"\"\"Search captured text for matching lines using ``fnmatch.fnmatch``.\n\n The argument is a list of lines which have to match and can use glob\n wildcards. If they do not match a pytest.fail() is called. The\n matches and non-matches are also printed on stdout.\n\n \"\"\"\n __tracebackhide__ = True\n self._match_lines(lines2, fnmatch, \"fnmatch\")\n\n def re_match_lines(self, lines2):\n \"\"\"Search captured text for matching lines using ``re.match``.\n\n The argument is a list of lines which have to match using ``re.match``.\n If they do not match a pytest.fail() is called.\n\n The matches and non-matches are also printed on stdout.\n\n \"\"\"\n __tracebackhide__ = True\n self._match_lines(lines2, lambda name, pat: re.match(pat, name), \"re.match\")\n\n def _match_lines(self, lines2, match_func, match_nickname):\n \"\"\"Underlying implementation of ``fnmatch_lines`` and ``re_match_lines``.\n\n :param list[str] lines2: list of string patterns to match. The actual\n format depends on ``match_func``\n :param match_func: a callable ``match_func(line, pattern)`` where line\n is the captured line from stdout/stderr and pattern is the matching\n pattern\n :param str match_nickname: the nickname for the match function that\n will be logged to stdout when a match occurs\n\n \"\"\"\n assert isinstance(lines2, Sequence)\n lines2 = self._getlines(lines2)\n lines1 = self.lines[:]\n nextline = None\n extralines = []\n __tracebackhide__ = True\n for line in lines2:\n nomatchprinted = False\n while lines1:\n nextline = lines1.pop(0)\n if line == nextline:\n self._log(\"exact match:\", repr(line))\n break\n elif match_func(nextline, line):\n self._log(\"%s:\" % match_nickname, repr(line))\n self._log(\" with:\", repr(nextline))\n break\n else:\n if not nomatchprinted:\n self._log(\"nomatch:\", repr(line))\n nomatchprinted = True\n self._log(\" and:\", repr(nextline))\n extralines.append(nextline)\n else:\n self._log(\"remains unmatched: %r\" % (line,))\n pytest.fail(self._log_text)\n"},{"className":"WeakKeyDictionary","col":0,"comment":"null","endLoc":150,"id":5167,"nodeType":"Class","startLoc":109,"text":"class WeakKeyDictionary(MutableMapping[_KT, _VT]):\n @overload\n def __init__(self, dict: None = None) -> None: ...\n @overload\n def __init__(self, dict: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]]) -> None: ...\n def __len__(self) -> int: ...\n def __getitem__(self, key: _KT) -> _VT: ...\n def __setitem__(self, key: _KT, value: _VT) -> None: ...\n def __delitem__(self, key: _KT) -> None: ...\n def __contains__(self, key: object) -> bool: ...\n def __iter__(self) -> Iterator[_KT]: ...\n def copy(self) -> WeakKeyDictionary[_KT, _VT]: ...\n __copy__ = copy\n def __deepcopy__(self, memo: Any) -> Self: ...\n @overload\n def get(self, key: _KT, default: None = None) -> _VT | None: ...\n @overload\n def get(self, key: _KT, default: _T) -> _VT | _T: ...\n # These are incompatible with Mapping\n def keys(self) -> Iterator[_KT]: ... # type: ignore[override]\n def values(self) -> Iterator[_VT]: ... # type: ignore[override]\n def items(self) -> Iterator[tuple[_KT, _VT]]: ... # type: ignore[override]\n def keyrefs(self) -> list[ref[_KT]]: ...\n # Keep WeakKeyDictionary.setdefault in line with MutableMapping.setdefault, modulo positional-only differences\n @overload\n def setdefault(self: WeakKeyDictionary[_KT, _VT | None], key: _KT, default: None = None) -> _VT: ...\n @overload\n def setdefault(self, key: _KT, default: _VT) -> _VT: ...\n @overload\n def pop(self, key: _KT) -> _VT: ...\n @overload\n def pop(self, key: _KT, default: _VT) -> _VT: ...\n @overload\n def pop(self, key: _KT, default: _T) -> _VT | _T: ...\n if sys.version_info >= (3, 9):\n def __or__(self, other: Mapping[_T1, _T2]) -> WeakKeyDictionary[_KT | _T1, _VT | _T2]: ...\n def __ror__(self, other: Mapping[_T1, _T2]) -> WeakKeyDictionary[_KT | _T1, _VT | _T2]: ...\n # WeakKeyDictionary.__ior__ should be kept roughly in line with MutableMapping.update()\n @overload # type: ignore[misc]\n def __ior__(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ...\n @overload\n def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ..."},{"col":4,"comment":"null","endLoc":111,"header":"@overload\n def __init__(self, dict: None = None) -> None","id":5168,"name":"__init__","nodeType":"Function","startLoc":110,"text":"@overload\n def __init__(self, dict: None = None) -> None: ..."},{"col":4,"comment":"null","endLoc":113,"header":"@overload\n def __init__(self, dict: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]]) -> None","id":5169,"name":"__init__","nodeType":"Function","startLoc":112,"text":"@overload\n def __init__(self, dict: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]]) -> None: ..."},{"col":4,"comment":"null","endLoc":114,"header":"def __len__(self) -> int","id":5170,"name":"__len__","nodeType":"Function","startLoc":114,"text":"def __len__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":115,"header":"def __getitem__(self, key: _KT) -> _VT","id":5171,"name":"__getitem__","nodeType":"Function","startLoc":115,"text":"def __getitem__(self, key: _KT) -> _VT: ..."},{"col":4,"comment":"null","endLoc":116,"header":"def __setitem__(self, key: _KT, value: _VT) -> None","id":5172,"name":"__setitem__","nodeType":"Function","startLoc":116,"text":"def __setitem__(self, key: _KT, value: _VT) -> None: ..."},{"col":4,"comment":"null","endLoc":117,"header":"def __delitem__(self, key: _KT) -> None","id":5173,"name":"__delitem__","nodeType":"Function","startLoc":117,"text":"def __delitem__(self, key: _KT) -> None: ..."},{"col":4,"comment":"null","endLoc":118,"header":"def __contains__(self, key: object) -> bool","id":5174,"name":"__contains__","nodeType":"Function","startLoc":118,"text":"def __contains__(self, key: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":119,"header":"def __iter__(self) -> Iterator[_KT]","id":5175,"name":"__iter__","nodeType":"Function","startLoc":119,"text":"def __iter__(self) -> Iterator[_KT]: ..."},{"col":4,"comment":"null","endLoc":120,"header":"def copy(self) -> WeakKeyDictionary[_KT, _VT]","id":5176,"name":"copy","nodeType":"Function","startLoc":120,"text":"def copy(self) -> WeakKeyDictionary[_KT, _VT]: ..."},{"col":4,"comment":"null","endLoc":122,"header":"def __deepcopy__(self, memo: Any) -> Self","id":5177,"name":"__deepcopy__","nodeType":"Function","startLoc":122,"text":"def __deepcopy__(self, memo: Any) -> Self: ..."},{"col":4,"comment":"null","endLoc":124,"header":"@overload\n def get(self, key: _KT, default: None = None) -> _VT | None","id":5178,"name":"get","nodeType":"Function","startLoc":123,"text":"@overload\n def get(self, key: _KT, default: None = None) -> _VT | None: ..."},{"col":4,"comment":"null","endLoc":126,"header":"@overload\n def get(self, key: _KT, default: _T) -> _VT | _T","id":5179,"name":"get","nodeType":"Function","startLoc":125,"text":"@overload\n def get(self, key: _KT, default: _T) -> _VT | _T: ..."},{"col":4,"comment":"null","endLoc":128,"header":"def keys(self) -> Iterator[_KT]","id":5180,"name":"keys","nodeType":"Function","startLoc":128,"text":"def keys(self) -> Iterator[_KT]: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":129,"header":"def values(self) -> Iterator[_VT]","id":5181,"name":"values","nodeType":"Function","startLoc":129,"text":"def values(self) -> Iterator[_VT]: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":130,"header":"def items(self) -> Iterator[tuple[_KT, _VT]]","id":5182,"name":"items","nodeType":"Function","startLoc":130,"text":"def items(self) -> Iterator[tuple[_KT, _VT]]: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":131,"header":"def keyrefs(self) -> list[ref[_KT]]","id":5183,"name":"keyrefs","nodeType":"Function","startLoc":131,"text":"def keyrefs(self) -> list[ref[_KT]]: ..."},{"col":4,"comment":"null","endLoc":134,"header":"@overload\n def setdefault(self: WeakKeyDictionary[_KT, _VT | None], key: _KT, default: None = None) -> _VT","id":5184,"name":"setdefault","nodeType":"Function","startLoc":133,"text":"@overload\n def setdefault(self: WeakKeyDictionary[_KT, _VT | None], key: _KT, default: None = None) -> _VT: ..."},{"col":4,"comment":"null","endLoc":136,"header":"@overload\n def setdefault(self, key: _KT, default: _VT) -> _VT","id":5185,"name":"setdefault","nodeType":"Function","startLoc":135,"text":"@overload\n def setdefault(self, key: _KT, default: _VT) -> _VT: ..."},{"col":4,"comment":"null","endLoc":138,"header":"@overload\n def pop(self, key: _KT) -> _VT","id":5186,"name":"pop","nodeType":"Function","startLoc":137,"text":"@overload\n def pop(self, key: _KT) -> _VT: ..."},{"col":4,"comment":"null","endLoc":140,"header":"@overload\n def pop(self, key: _KT, default: _VT) -> _VT","id":5187,"name":"pop","nodeType":"Function","startLoc":139,"text":"@overload\n def pop(self, key: _KT, default: _VT) -> _VT: ..."},{"col":4,"comment":"null","endLoc":142,"header":"@overload\n def pop(self, key: _KT, default: _T) -> _VT | _T","id":5188,"name":"pop","nodeType":"Function","startLoc":141,"text":"@overload\n def pop(self, key: _KT, default: _T) -> _VT | _T: ..."},{"col":8,"comment":"null","endLoc":144,"header":"def __or__(self, other: Mapping[_T1, _T2]) -> WeakKeyDictionary[_KT | _T1, _VT | _T2]","id":5189,"name":"__or__","nodeType":"Function","startLoc":144,"text":"def __or__(self, other: Mapping[_T1, _T2]) -> WeakKeyDictionary[_KT | _T1, _VT | _T2]: ..."},{"col":8,"comment":"null","endLoc":145,"header":"def __ror__(self, other: Mapping[_T1, _T2]) -> WeakKeyDictionary[_KT | _T1, _VT | _T2]","id":5190,"name":"__ror__","nodeType":"Function","startLoc":145,"text":"def __ror__(self, other: Mapping[_T1, _T2]) -> WeakKeyDictionary[_KT | _T1, _VT | _T2]: ..."},{"col":8,"comment":"null","endLoc":148,"header":"@overload # type: ignore[misc]\n def __ior__(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self","id":5191,"name":"__ior__","nodeType":"Function","startLoc":147,"text":"@overload # type: ignore[misc]\n def __ior__(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ..."},{"col":8,"comment":"null","endLoc":150,"header":"@overload\n def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self","id":5192,"name":"__ior__","nodeType":"Function","startLoc":149,"text":"@overload\n def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ..."},{"attributeType":"function","col":4,"comment":"null","endLoc":121,"id":5193,"name":"__copy__","nodeType":"Attribute","startLoc":121,"text":"__copy__"},{"col":0,"comment":"Enable text capturing of writes to ``sys.stdout`` and ``sys.stderr``.\n\n The captured output is made available via ``capsys.readouterr()`` method\n calls, which return a ``(out, err)`` namedtuple.\n ``out`` and ``err`` will be ``text`` objects.\n ","endLoc":274,"header":"@pytest.fixture\ndef capsys(request)","id":5194,"name":"capsys","nodeType":"Function","startLoc":264,"text":"@pytest.fixture\ndef capsys(request):\n \"\"\"Enable text capturing of writes to ``sys.stdout`` and ``sys.stderr``.\n\n The captured output is made available via ``capsys.readouterr()`` method\n calls, which return a ``(out, err)`` namedtuple.\n ``out`` and ``err`` will be ``text`` objects.\n \"\"\"\n _ensure_only_one_capture_fixture(request, \"capsys\")\n with _install_capture_fixture_on_item(request, SysCapture) as fixture:\n yield fixture"},{"fileName":"acceptance_test.py","filePath":"testing","id":5195,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport textwrap\nimport types\n\nimport attr\nimport importlib_metadata\nimport py\nimport six\n\nimport pytest\nfrom _pytest.main import EXIT_NOTESTSCOLLECTED\nfrom _pytest.main import EXIT_USAGEERROR\nfrom _pytest.warnings import SHOW_PYTEST_WARNINGS_ARG\n\n\ndef prepend_pythonpath(*dirs):\n cur = os.getenv(\"PYTHONPATH\")\n if cur:\n dirs += (cur,)\n return os.pathsep.join(str(p) for p in dirs)\n\n\nclass TestGeneralUsage(object):\n def test_config_error(self, testdir):\n testdir.copy_example(\"conftest_usageerror/conftest.py\")\n result = testdir.runpytest(testdir.tmpdir)\n assert result.ret == EXIT_USAGEERROR\n result.stderr.fnmatch_lines([\"*ERROR: hello\"])\n result.stdout.fnmatch_lines([\"*pytest_unconfigure_called\"])\n\n def test_root_conftest_syntax_error(self, testdir):\n testdir.makepyfile(conftest=\"raise SyntaxError\\n\")\n result = testdir.runpytest()\n result.stderr.fnmatch_lines([\"*raise SyntaxError*\"])\n assert result.ret != 0\n\n def test_early_hook_error_issue38_1(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_sessionstart():\n 0 / 0\n \"\"\"\n )\n result = testdir.runpytest(testdir.tmpdir)\n assert result.ret != 0\n # tracestyle is native by default for hook failures\n result.stdout.fnmatch_lines(\n [\"*INTERNALERROR*File*conftest.py*line 2*\", \"*0 / 0*\"]\n )\n result = testdir.runpytest(testdir.tmpdir, \"--fulltrace\")\n assert result.ret != 0\n # tracestyle is native by default for hook failures\n result.stdout.fnmatch_lines(\n [\"*INTERNALERROR*def pytest_sessionstart():*\", \"*INTERNALERROR*0 / 0*\"]\n )\n\n def test_early_hook_configure_error_issue38(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_configure():\n 0 / 0\n \"\"\"\n )\n result = testdir.runpytest(testdir.tmpdir)\n assert result.ret != 0\n # here we get it on stderr\n result.stderr.fnmatch_lines(\n [\"*INTERNALERROR*File*conftest.py*line 2*\", \"*0 / 0*\"]\n )\n\n def test_file_not_found(self, testdir):\n result = testdir.runpytest(\"asd\")\n assert result.ret != 0\n result.stderr.fnmatch_lines([\"ERROR: file not found*asd\"])\n\n def test_file_not_found_unconfigure_issue143(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_configure():\n print(\"---configure\")\n def pytest_unconfigure():\n print(\"---unconfigure\")\n \"\"\"\n )\n result = testdir.runpytest(\"-s\", \"asd\")\n assert result.ret == 4 # EXIT_USAGEERROR\n result.stderr.fnmatch_lines([\"ERROR: file not found*asd\"])\n result.stdout.fnmatch_lines([\"*---configure\", \"*---unconfigure\"])\n\n def test_config_preparse_plugin_option(self, testdir):\n testdir.makepyfile(\n pytest_xyz=\"\"\"\n def pytest_addoption(parser):\n parser.addoption(\"--xyz\", dest=\"xyz\", action=\"store\")\n \"\"\"\n )\n testdir.makepyfile(\n test_one=\"\"\"\n def test_option(pytestconfig):\n assert pytestconfig.option.xyz == \"123\"\n \"\"\"\n )\n result = testdir.runpytest(\"-p\", \"pytest_xyz\", \"--xyz=123\", syspathinsert=True)\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n @pytest.mark.parametrize(\"load_cov_early\", [True, False])\n def test_early_load_setuptools_name(self, testdir, monkeypatch, load_cov_early):\n testdir.makepyfile(mytestplugin1_module=\"\")\n testdir.makepyfile(mytestplugin2_module=\"\")\n testdir.makepyfile(mycov_module=\"\")\n testdir.syspathinsert()\n\n loaded = []\n\n @attr.s\n class DummyEntryPoint(object):\n name = attr.ib()\n module = attr.ib()\n group = \"pytest11\"\n\n def load(self):\n __import__(self.module)\n loaded.append(self.name)\n return sys.modules[self.module]\n\n entry_points = [\n DummyEntryPoint(\"myplugin1\", \"mytestplugin1_module\"),\n DummyEntryPoint(\"myplugin2\", \"mytestplugin2_module\"),\n DummyEntryPoint(\"mycov\", \"mycov_module\"),\n ]\n\n @attr.s\n class DummyDist(object):\n entry_points = attr.ib()\n files = ()\n\n def my_dists():\n return (DummyDist(entry_points),)\n\n monkeypatch.setattr(importlib_metadata, \"distributions\", my_dists)\n params = (\"-p\", \"mycov\") if load_cov_early else ()\n testdir.runpytest_inprocess(*params)\n if load_cov_early:\n assert loaded == [\"mycov\", \"myplugin1\", \"myplugin2\"]\n else:\n assert loaded == [\"myplugin1\", \"myplugin2\", \"mycov\"]\n\n def test_assertion_magic(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_this():\n x = 0\n assert x\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"> assert x\", \"E assert 0\"])\n assert result.ret == 1\n\n def test_nested_import_error(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import import_fails\n def test_this():\n assert import_fails.a == 1\n \"\"\"\n )\n testdir.makepyfile(import_fails=\"import does_not_work\")\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n # XXX on jython this fails: \"> import import_fails\",\n \"ImportError while importing test module*\",\n \"*No module named *does_not_work*\",\n ]\n )\n assert result.ret == 2\n\n def test_not_collectable_arguments(self, testdir):\n p1 = testdir.makepyfile(\"\")\n p2 = testdir.makefile(\".pyc\", \"123\")\n result = testdir.runpytest(p1, p2)\n assert result.ret\n result.stderr.fnmatch_lines([\"*ERROR: not found:*{}\".format(p2.basename)])\n\n @pytest.mark.filterwarnings(\"default\")\n def test_better_reporting_on_conftest_load_failure(self, testdir, request):\n \"\"\"Show a user-friendly traceback on conftest import failures (#486, #3332)\"\"\"\n testdir.makepyfile(\"\")\n testdir.makeconftest(\n \"\"\"\n def foo():\n import qwerty\n foo()\n \"\"\"\n )\n result = testdir.runpytest(\"--help\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *--version*\n *warning*conftest.py*\n \"\"\"\n )\n result = testdir.runpytest()\n dirname = request.node.name + \"0\"\n exc_name = (\n \"ModuleNotFoundError\" if sys.version_info >= (3, 6) else \"ImportError\"\n )\n result.stderr.fnmatch_lines(\n [\n \"ImportError while loading conftest '*{sep}{dirname}{sep}conftest.py'.\".format(\n dirname=dirname, sep=os.sep\n ),\n \"conftest.py:3: in \",\n \" foo()\",\n \"conftest.py:2: in foo\",\n \" import qwerty\",\n \"E {}: No module named {q}qwerty{q}\".format(\n exc_name, q=\"\" if six.PY2 else \"'\"\n ),\n ]\n )\n\n def test_early_skip(self, testdir):\n testdir.mkdir(\"xyz\")\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_collect_directory():\n pytest.skip(\"early\")\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result.stdout.fnmatch_lines([\"*1 skip*\"])\n\n def test_issue88_initial_file_multinodes(self, testdir):\n testdir.copy_example(\"issue88_initial_file_multinodes\")\n p = testdir.makepyfile(\"def test_hello(): pass\")\n result = testdir.runpytest(p, \"--collect-only\")\n result.stdout.fnmatch_lines([\"*MyFile*test_issue88*\", \"*Module*test_issue88*\"])\n\n def test_issue93_initialnode_importing_capturing(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import sys\n print(\"should not be seen\")\n sys.stderr.write(\"stder42\\\\n\")\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n assert \"should not be seen\" not in result.stdout.str()\n assert \"stderr42\" not in result.stderr.str()\n\n def test_conftest_printing_shows_if_error(self, testdir):\n testdir.makeconftest(\n \"\"\"\n print(\"should be seen\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret != 0\n assert \"should be seen\" in result.stdout.str()\n\n @pytest.mark.skipif(\n not hasattr(py.path.local, \"mksymlinkto\"),\n reason=\"symlink not available on this platform\",\n )\n def test_chdir(self, testdir):\n testdir.tmpdir.join(\"py\").mksymlinkto(py._pydir)\n p = testdir.tmpdir.join(\"main.py\")\n p.write(\n textwrap.dedent(\n \"\"\"\\\n import sys, os\n sys.path.insert(0, '')\n import py\n print(py.__file__)\n print(py.__path__)\n os.chdir(os.path.dirname(os.getcwd()))\n print(py.log)\n \"\"\"\n )\n )\n result = testdir.runpython(p)\n assert not result.ret\n\n def test_issue109_sibling_conftests_not_loaded(self, testdir):\n sub1 = testdir.mkdir(\"sub1\")\n sub2 = testdir.mkdir(\"sub2\")\n sub1.join(\"conftest.py\").write(\"assert 0\")\n result = testdir.runpytest(sub2)\n assert result.ret == EXIT_NOTESTSCOLLECTED\n sub2.ensure(\"__init__.py\")\n p = sub2.ensure(\"test_hello.py\")\n result = testdir.runpytest(p)\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result = testdir.runpytest(sub1)\n assert result.ret == EXIT_USAGEERROR\n\n def test_directory_skipped(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_ignore_collect():\n pytest.skip(\"intentional\")\n \"\"\"\n )\n testdir.makepyfile(\"def test_hello(): pass\")\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result.stdout.fnmatch_lines([\"*1 skipped*\"])\n\n def test_multiple_items_per_collector_byid(self, testdir):\n c = testdir.makeconftest(\n \"\"\"\n import pytest\n class MyItem(pytest.Item):\n def runtest(self):\n pass\n class MyCollector(pytest.File):\n def collect(self):\n return [MyItem(name=\"xyz\", parent=self)]\n def pytest_collect_file(path, parent):\n if path.basename.startswith(\"conftest\"):\n return MyCollector(path, parent)\n \"\"\"\n )\n result = testdir.runpytest(c.basename + \"::\" + \"xyz\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 pass*\"])\n\n def test_skip_on_generated_funcarg_id(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('x', [3], ids=['hello-123'])\n def pytest_runtest_setup(item):\n print(item.keywords)\n if 'hello-123' in item.keywords:\n pytest.skip(\"hello\")\n assert 0\n \"\"\"\n )\n p = testdir.makepyfile(\"\"\"def test_func(x): pass\"\"\")\n res = testdir.runpytest(p, SHOW_PYTEST_WARNINGS_ARG)\n assert res.ret == 0\n res.stdout.fnmatch_lines([\"*1 skipped*\"])\n\n def test_direct_addressing_selects(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('i', [1, 2], ids=[\"1\", \"2\"])\n def test_func(i):\n pass\n \"\"\"\n )\n res = testdir.runpytest(\n p.basename + \"::\" + \"test_func[1]\", SHOW_PYTEST_WARNINGS_ARG\n )\n assert res.ret == 0\n res.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_direct_addressing_notfound(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n res = testdir.runpytest(p.basename + \"::\" + \"test_notfound\")\n assert res.ret\n res.stderr.fnmatch_lines([\"*ERROR*not found*\"])\n\n def test_docstring_on_hookspec(self):\n from _pytest import hookspec\n\n for name, value in vars(hookspec).items():\n if name.startswith(\"pytest_\"):\n assert value.__doc__, \"no docstring for %s\" % name\n\n def test_initialization_error_issue49(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_configure():\n x\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 3 # internal error\n result.stderr.fnmatch_lines([\"INTERNAL*pytest_configure*\", \"INTERNAL*x*\"])\n assert \"sessionstarttime\" not in result.stderr.str()\n\n @pytest.mark.parametrize(\"lookfor\", [\"test_fun.py::test_a\"])\n def test_issue134_report_error_when_collecting_member(self, testdir, lookfor):\n testdir.makepyfile(\n test_fun=\"\"\"\n def test_a():\n pass\n def\"\"\"\n )\n result = testdir.runpytest(lookfor)\n result.stdout.fnmatch_lines([\"*SyntaxError*\"])\n if \"::\" in lookfor:\n result.stderr.fnmatch_lines([\"*ERROR*\"])\n assert result.ret == 4 # usage error only if item not found\n\n def test_report_all_failed_collections_initargs(self, testdir):\n testdir.makeconftest(\n \"\"\"\n from _pytest.main import EXIT_USAGEERROR\n\n def pytest_sessionfinish(exitstatus):\n assert exitstatus == EXIT_USAGEERROR\n print(\"pytest_sessionfinish_called\")\n \"\"\"\n )\n testdir.makepyfile(test_a=\"def\", test_b=\"def\")\n result = testdir.runpytest(\"test_a.py::a\", \"test_b.py::b\")\n result.stderr.fnmatch_lines([\"*ERROR*test_a.py::a*\", \"*ERROR*test_b.py::b*\"])\n result.stdout.fnmatch_lines([\"pytest_sessionfinish_called\"])\n assert result.ret == EXIT_USAGEERROR\n\n @pytest.mark.usefixtures(\"recwarn\")\n def test_namespace_import_doesnt_confuse_import_hook(self, testdir):\n \"\"\"\n Ref #383. Python 3.3's namespace package messed with our import hooks\n Importing a module that didn't exist, even if the ImportError was\n gracefully handled, would make our test crash.\n\n Use recwarn here to silence this warning in Python 2.7:\n ImportWarning: Not importing directory '...\\not_a_package': missing __init__.py\n \"\"\"\n testdir.mkdir(\"not_a_package\")\n p = testdir.makepyfile(\n \"\"\"\n try:\n from not_a_package import doesnt_exist\n except ImportError:\n # We handle the import error gracefully here\n pass\n\n def test_whatever():\n pass\n \"\"\"\n )\n res = testdir.runpytest(p.basename)\n assert res.ret == 0\n\n def test_unknown_option(self, testdir):\n result = testdir.runpytest(\"--qwlkej\")\n result.stderr.fnmatch_lines(\n \"\"\"\n *unrecognized*\n \"\"\"\n )\n\n def test_getsourcelines_error_issue553(self, testdir, monkeypatch):\n monkeypatch.setattr(\"inspect.getsourcelines\", None)\n p = testdir.makepyfile(\n \"\"\"\n def raise_error(obj):\n raise IOError('source code not available')\n\n import inspect\n inspect.getsourcelines = raise_error\n\n def test_foo(invalid_fixture):\n pass\n \"\"\"\n )\n res = testdir.runpytest(p)\n res.stdout.fnmatch_lines(\n [\"*source code not available*\", \"E*fixture 'invalid_fixture' not found\"]\n )\n\n def test_plugins_given_as_strings(self, tmpdir, monkeypatch, _sys_snapshot):\n \"\"\"test that str values passed to main() as `plugins` arg\n are interpreted as module names to be imported and registered.\n #855.\n \"\"\"\n with pytest.raises(ImportError) as excinfo:\n pytest.main([str(tmpdir)], plugins=[\"invalid.module\"])\n assert \"invalid\" in str(excinfo.value)\n\n p = tmpdir.join(\"test_test_plugins_given_as_strings.py\")\n p.write(\"def test_foo(): pass\")\n mod = types.ModuleType(\"myplugin\")\n monkeypatch.setitem(sys.modules, \"myplugin\", mod)\n assert pytest.main(args=[str(tmpdir)], plugins=[\"myplugin\"]) == 0\n\n def test_parametrized_with_bytes_regex(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import re\n import pytest\n @pytest.mark.parametrize('r', [re.compile(b'foo')])\n def test_stuff(r):\n pass\n \"\"\"\n )\n res = testdir.runpytest(p)\n res.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_parametrized_with_null_bytes(self, testdir):\n \"\"\"Test parametrization with values that contain null bytes and unicode characters (#2644, #2957)\"\"\"\n p = testdir.makepyfile(\n u\"\"\"\n # encoding: UTF-8\n import pytest\n\n @pytest.mark.parametrize(\"data\", [b\"\\\\x00\", \"\\\\x00\", u'ação'])\n def test_foo(data):\n assert data\n \"\"\"\n )\n res = testdir.runpytest(p)\n res.assert_outcomes(passed=3)\n\n\nclass TestInvocationVariants(object):\n def test_earlyinit(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n assert hasattr(pytest, 'mark')\n \"\"\"\n )\n result = testdir.runpython(p)\n assert result.ret == 0\n\n @pytest.mark.xfail(\"sys.platform.startswith('java')\")\n def test_pydoc(self, testdir):\n for name in (\"py.test\", \"pytest\"):\n result = testdir.runpython_c(\"import {};help({})\".format(name, name))\n assert result.ret == 0\n s = result.stdout.str()\n assert \"MarkGenerator\" in s\n\n def test_import_star_py_dot_test(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n from py.test import *\n #collect\n #cmdline\n #Item\n # assert collect.Item is Item\n # assert collect.Collector is Collector\n main\n skip\n xfail\n \"\"\"\n )\n result = testdir.runpython(p)\n assert result.ret == 0\n\n def test_import_star_pytest(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n from pytest import *\n #Item\n #File\n main\n skip\n xfail\n \"\"\"\n )\n result = testdir.runpython(p)\n assert result.ret == 0\n\n def test_double_pytestcmdline(self, testdir):\n p = testdir.makepyfile(\n run=\"\"\"\n import pytest\n pytest.main()\n pytest.main()\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n pass\n \"\"\"\n )\n result = testdir.runpython(p)\n result.stdout.fnmatch_lines([\"*1 passed*\", \"*1 passed*\"])\n\n def test_python_minus_m_invocation_ok(self, testdir):\n p1 = testdir.makepyfile(\"def test_hello(): pass\")\n res = testdir.run(sys.executable, \"-m\", \"pytest\", str(p1))\n assert res.ret == 0\n\n def test_python_minus_m_invocation_fail(self, testdir):\n p1 = testdir.makepyfile(\"def test_fail(): 0/0\")\n res = testdir.run(sys.executable, \"-m\", \"pytest\", str(p1))\n assert res.ret == 1\n\n def test_python_pytest_package(self, testdir):\n p1 = testdir.makepyfile(\"def test_pass(): pass\")\n res = testdir.run(sys.executable, \"-m\", \"pytest\", str(p1))\n assert res.ret == 0\n res.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_equivalence_pytest_pytest(self):\n assert pytest.main == py.test.cmdline.main\n\n def test_invoke_with_invalid_type(self, capsys):\n with pytest.raises(\n TypeError, match=\"expected to be a list or tuple of strings, got: '-h'\"\n ):\n pytest.main(\"-h\")\n\n def test_invoke_with_path(self, tmpdir, capsys):\n retcode = pytest.main(tmpdir)\n assert retcode == EXIT_NOTESTSCOLLECTED\n out, err = capsys.readouterr()\n\n def test_invoke_plugin_api(self, testdir, capsys):\n class MyPlugin(object):\n def pytest_addoption(self, parser):\n parser.addoption(\"--myopt\")\n\n pytest.main([\"-h\"], plugins=[MyPlugin()])\n out, err = capsys.readouterr()\n assert \"--myopt\" in out\n\n def test_pyargs_importerror(self, testdir, monkeypatch):\n monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", False)\n path = testdir.mkpydir(\"tpkg\")\n path.join(\"test_hello.py\").write(\"raise ImportError\")\n\n result = testdir.runpytest(\"--pyargs\", \"tpkg.test_hello\", syspathinsert=True)\n assert result.ret != 0\n\n result.stdout.fnmatch_lines([\"collected*0*items*/*1*errors\"])\n\n def test_cmdline_python_package(self, testdir, monkeypatch):\n import warnings\n\n monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", False)\n path = testdir.mkpydir(\"tpkg\")\n path.join(\"test_hello.py\").write(\"def test_hello(): pass\")\n path.join(\"test_world.py\").write(\"def test_world(): pass\")\n result = testdir.runpytest(\"--pyargs\", \"tpkg\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n result = testdir.runpytest(\"--pyargs\", \"tpkg.test_hello\", syspathinsert=True)\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n empty_package = testdir.mkpydir(\"empty_package\")\n monkeypatch.setenv(\"PYTHONPATH\", str(empty_package), prepend=os.pathsep)\n # the path which is not a package raises a warning on pypy;\n # no idea why only pypy and not normal python warn about it here\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", ImportWarning)\n result = testdir.runpytest(\"--pyargs\", \".\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n monkeypatch.setenv(\"PYTHONPATH\", str(testdir), prepend=os.pathsep)\n result = testdir.runpytest(\"--pyargs\", \"tpkg.test_missing\", syspathinsert=True)\n assert result.ret != 0\n result.stderr.fnmatch_lines([\"*not*found*test_missing*\"])\n\n def test_cmdline_python_namespace_package(self, testdir, monkeypatch):\n \"\"\"\n test --pyargs option with namespace packages (#1567)\n\n Ref: https://packaging.python.org/guides/packaging-namespace-packages/\n \"\"\"\n monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", raising=False)\n\n search_path = []\n for dirname in \"hello\", \"world\":\n d = testdir.mkdir(dirname)\n search_path.append(d)\n ns = d.mkdir(\"ns_pkg\")\n ns.join(\"__init__.py\").write(\n \"__import__('pkg_resources').declare_namespace(__name__)\"\n )\n lib = ns.mkdir(dirname)\n lib.ensure(\"__init__.py\")\n lib.join(\"test_{}.py\".format(dirname)).write(\n \"def test_{}(): pass\\ndef test_other():pass\".format(dirname)\n )\n\n # The structure of the test directory is now:\n # .\n # ├── hello\n # │ └── ns_pkg\n # │ ├── __init__.py\n # │ └── hello\n # │ ├── __init__.py\n # │ └── test_hello.py\n # └── world\n # └── ns_pkg\n # ├── __init__.py\n # └── world\n # ├── __init__.py\n # └── test_world.py\n\n # NOTE: the different/reversed ordering is intentional here.\n monkeypatch.setenv(\"PYTHONPATH\", prepend_pythonpath(*search_path))\n for p in search_path:\n monkeypatch.syspath_prepend(p)\n\n # mixed module and filenames:\n monkeypatch.chdir(\"world\")\n result = testdir.runpytest(\"--pyargs\", \"-v\", \"ns_pkg.hello\", \"ns_pkg/world\")\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n [\n \"test_hello.py::test_hello*PASSED*\",\n \"test_hello.py::test_other*PASSED*\",\n \"ns_pkg/world/test_world.py::test_world*PASSED*\",\n \"ns_pkg/world/test_world.py::test_other*PASSED*\",\n \"*4 passed in*\",\n ]\n )\n\n # specify tests within a module\n testdir.chdir()\n result = testdir.runpytest(\n \"--pyargs\", \"-v\", \"ns_pkg.world.test_world::test_other\"\n )\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n [\"*test_world.py::test_other*PASSED*\", \"*1 passed*\"]\n )\n\n def test_invoke_test_and_doctestmodules(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test():\n pass\n \"\"\"\n )\n result = testdir.runpytest(str(p) + \"::test\", \"--doctest-modules\")\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n @pytest.mark.skipif(not hasattr(os, \"symlink\"), reason=\"requires symlinks\")\n def test_cmdline_python_package_symlink(self, testdir, monkeypatch):\n \"\"\"\n test --pyargs option with packages with path containing symlink can\n have conftest.py in their package (#2985)\n \"\"\"\n # dummy check that we can actually create symlinks: on Windows `os.symlink` is available,\n # but normal users require special admin privileges to create symlinks.\n if sys.platform == \"win32\":\n try:\n os.symlink(\n str(testdir.tmpdir.ensure(\"tmpfile\")),\n str(testdir.tmpdir.join(\"tmpfile2\")),\n )\n except OSError as e:\n pytest.skip(six.text_type(e.args[0]))\n monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", raising=False)\n\n dirname = \"lib\"\n d = testdir.mkdir(dirname)\n foo = d.mkdir(\"foo\")\n foo.ensure(\"__init__.py\")\n lib = foo.mkdir(\"bar\")\n lib.ensure(\"__init__.py\")\n lib.join(\"test_bar.py\").write(\n \"def test_bar(): pass\\ndef test_other(a_fixture):pass\"\n )\n lib.join(\"conftest.py\").write(\n \"import pytest\\n@pytest.fixture\\ndef a_fixture():pass\"\n )\n\n d_local = testdir.mkdir(\"local\")\n symlink_location = os.path.join(str(d_local), \"lib\")\n if six.PY2:\n os.symlink(str(d), symlink_location)\n else:\n os.symlink(str(d), symlink_location, target_is_directory=True)\n\n # The structure of the test directory is now:\n # .\n # ├── local\n # │ └── lib -> ../lib\n # └── lib\n # └── foo\n # ├── __init__.py\n # └── bar\n # ├── __init__.py\n # ├── conftest.py\n # └── test_bar.py\n\n # NOTE: the different/reversed ordering is intentional here.\n search_path = [\"lib\", os.path.join(\"local\", \"lib\")]\n monkeypatch.setenv(\"PYTHONPATH\", prepend_pythonpath(*search_path))\n for p in search_path:\n monkeypatch.syspath_prepend(p)\n\n # module picked up in symlink-ed directory:\n # It picks up local/lib/foo/bar (symlink) via sys.path.\n result = testdir.runpytest(\"--pyargs\", \"-v\", \"foo.bar\")\n testdir.chdir()\n assert result.ret == 0\n if hasattr(py.path.local, \"mksymlinkto\"):\n result.stdout.fnmatch_lines(\n [\n \"lib/foo/bar/test_bar.py::test_bar PASSED*\",\n \"lib/foo/bar/test_bar.py::test_other PASSED*\",\n \"*2 passed*\",\n ]\n )\n else:\n result.stdout.fnmatch_lines(\n [\n \"*lib/foo/bar/test_bar.py::test_bar PASSED*\",\n \"*lib/foo/bar/test_bar.py::test_other PASSED*\",\n \"*2 passed*\",\n ]\n )\n\n def test_cmdline_python_package_not_exists(self, testdir):\n result = testdir.runpytest(\"--pyargs\", \"tpkgwhatv\")\n assert result.ret\n result.stderr.fnmatch_lines([\"ERROR*file*or*package*not*found*\"])\n\n @pytest.mark.xfail(reason=\"decide: feature or bug\")\n def test_noclass_discovery_if_not_testcase(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n class TestHello(object):\n def test_hello(self):\n assert self.attr\n\n class RealTest(unittest.TestCase, TestHello):\n attr = 42\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n reprec.assertoutcome(passed=1)\n\n def test_doctest_id(self, testdir):\n testdir.makefile(\n \".txt\",\n \"\"\"\n >>> x=3\n >>> x\n 4\n \"\"\",\n )\n result = testdir.runpytest(\"-rf\")\n lines = result.stdout.str().splitlines()\n for line in lines:\n if line.startswith((\"FAIL \", \"FAILED \")):\n _fail, _sep, testid = line.partition(\" \")\n break\n result = testdir.runpytest(testid, \"-rf\")\n result.stdout.fnmatch_lines(\n [\"FAILED test_doctest_id.txt::test_doctest_id.txt\", \"*1 failed*\"]\n )\n\n def test_core_backward_compatibility(self):\n \"\"\"Test backward compatibility for get_plugin_manager function. See #787.\"\"\"\n import _pytest.config\n\n assert (\n type(_pytest.config.get_plugin_manager())\n is _pytest.config.PytestPluginManager\n )\n\n def test_has_plugin(self, request):\n \"\"\"Test hasplugin function of the plugin manager (#932).\"\"\"\n assert request.config.pluginmanager.hasplugin(\"python\")\n\n\nclass TestDurations(object):\n source = \"\"\"\n import time\n frag = 0.002\n def test_something():\n pass\n def test_2():\n time.sleep(frag*5)\n def test_1():\n time.sleep(frag)\n def test_3():\n time.sleep(frag*10)\n \"\"\"\n\n def test_calls(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"--durations=10\")\n assert result.ret == 0\n result.stdout.fnmatch_lines_random(\n [\"*durations*\", \"*call*test_3*\", \"*call*test_2*\"]\n )\n result.stdout.fnmatch_lines(\n [\"(0.00 durations hidden. Use -vv to show these durations.)\"]\n )\n\n def test_calls_show_2(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"--durations=2\")\n assert result.ret == 0\n lines = result.stdout.get_lines_after(\"*slowest*durations*\")\n assert \"4 passed\" in lines[2]\n\n def test_calls_showall(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"--durations=0\")\n assert result.ret == 0\n for x in \"23\":\n for y in (\"call\",): # 'setup', 'call', 'teardown':\n for line in result.stdout.lines:\n if (\"test_%s\" % x) in line and y in line:\n break\n else:\n raise AssertionError(\"not found {} {}\".format(x, y))\n\n def test_calls_showall_verbose(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"--durations=0\", \"-vv\")\n assert result.ret == 0\n for x in \"123\":\n for y in (\"call\",): # 'setup', 'call', 'teardown':\n for line in result.stdout.lines:\n if (\"test_%s\" % x) in line and y in line:\n break\n else:\n raise AssertionError(\"not found {} {}\".format(x, y))\n\n def test_with_deselected(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"--durations=2\", \"-k test_2\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*durations*\", \"*call*test_2*\"])\n\n def test_with_failing_collection(self, testdir):\n testdir.makepyfile(self.source)\n testdir.makepyfile(test_collecterror=\"\"\"xyz\"\"\")\n result = testdir.runpytest(\"--durations=2\", \"-k test_1\")\n assert result.ret == 2\n result.stdout.fnmatch_lines([\"*Interrupted: 1 errors during collection*\"])\n # Collection errors abort test execution, therefore no duration is\n # output\n assert \"duration\" not in result.stdout.str()\n\n def test_with_not(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"-k not 1\")\n assert result.ret == 0\n\n\nclass TestDurationWithFixture(object):\n source = \"\"\"\n import pytest\n import time\n frag = 0.01\n\n @pytest.fixture\n def setup_fixt():\n time.sleep(frag)\n\n def test_1(setup_fixt):\n time.sleep(frag)\n \"\"\"\n\n def test_setup_function(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"--durations=10\")\n assert result.ret == 0\n\n result.stdout.fnmatch_lines_random(\n \"\"\"\n *durations*\n * setup *test_1*\n * call *test_1*\n \"\"\"\n )\n\n\ndef test_zipimport_hook(testdir, tmpdir):\n \"\"\"Test package loader is being used correctly (see #1837).\"\"\"\n zipapp = pytest.importorskip(\"zipapp\")\n testdir.tmpdir.join(\"app\").ensure(dir=1)\n testdir.makepyfile(\n **{\n \"app/foo.py\": \"\"\"\n import pytest\n def main():\n pytest.main(['--pyarg', 'foo'])\n \"\"\"\n }\n )\n target = tmpdir.join(\"foo.zip\")\n zipapp.create_archive(str(testdir.tmpdir.join(\"app\")), str(target), main=\"foo:main\")\n result = testdir.runpython(target)\n assert result.ret == 0\n result.stderr.fnmatch_lines([\"*not found*foo*\"])\n assert \"INTERNALERROR>\" not in result.stdout.str()\n\n\ndef test_import_plugin_unicode_name(testdir):\n testdir.makepyfile(myplugin=\"\")\n testdir.makepyfile(\n \"\"\"\n def test(): pass\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n pytest_plugins = [u'myplugin']\n \"\"\"\n )\n r = testdir.runpytest()\n assert r.ret == 0\n\n\ndef test_pytest_plugins_as_module(testdir):\n \"\"\"Do not raise an error if pytest_plugins attribute is a module (#3899)\"\"\"\n testdir.makepyfile(\n **{\n \"__init__.py\": \"\",\n \"pytest_plugins.py\": \"\",\n \"conftest.py\": \"from . import pytest_plugins\",\n \"test_foo.py\": \"def test(): pass\",\n }\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 passed in *\"])\n\n\ndef test_deferred_hook_checking(testdir):\n \"\"\"\n Check hooks as late as possible (#1821).\n \"\"\"\n testdir.syspathinsert()\n testdir.makepyfile(\n **{\n \"plugin.py\": \"\"\"\n class Hooks(object):\n def pytest_my_hook(self, config):\n pass\n\n def pytest_configure(config):\n config.pluginmanager.add_hookspecs(Hooks)\n \"\"\",\n \"conftest.py\": \"\"\"\n pytest_plugins = ['plugin']\n def pytest_my_hook(config):\n return 40\n \"\"\",\n \"test_foo.py\": \"\"\"\n def test(request):\n assert request.config.hook.pytest_my_hook(config=request.config) == [40]\n \"\"\",\n }\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 passed *\"])\n\n\ndef test_fixture_values_leak(testdir):\n \"\"\"Ensure that fixture objects are properly destroyed by the garbage collector at the end of their expected\n life-times (#2981).\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import attr\n import gc\n import pytest\n import weakref\n\n @attr.s\n class SomeObj(object):\n name = attr.ib()\n\n fix_of_test1_ref = None\n session_ref = None\n\n @pytest.fixture(scope='session')\n def session_fix():\n global session_ref\n obj = SomeObj(name='session-fixture')\n session_ref = weakref.ref(obj)\n return obj\n\n @pytest.fixture\n def fix(session_fix):\n global fix_of_test1_ref\n obj = SomeObj(name='local-fixture')\n fix_of_test1_ref = weakref.ref(obj)\n return obj\n\n def test1(fix):\n assert fix_of_test1_ref() is fix\n\n def test2():\n gc.collect()\n # fixture \"fix\" created during test1 must have been destroyed by now\n assert fix_of_test1_ref() is None\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed *\"])\n\n\ndef test_fixture_order_respects_scope(testdir):\n \"\"\"Ensure that fixtures are created according to scope order, regression test for #2405\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n data = {}\n\n @pytest.fixture(scope='module')\n def clean_data():\n data.clear()\n\n @pytest.fixture(autouse=True)\n def add_data():\n data.update(value=True)\n\n @pytest.mark.usefixtures('clean_data')\n def test_value():\n assert data.get('value')\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0\n\n\ndef test_frame_leak_on_failing_test(testdir):\n \"\"\"pytest would leak garbage referencing the frames of tests that failed that could never be reclaimed (#2798)\n\n Unfortunately it was not possible to remove the actual circles because most of them\n are made of traceback objects which cannot be weakly referenced. Those objects at least\n can be eventually claimed by the garbage collector.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import gc\n import weakref\n\n class Obj:\n pass\n\n ref = None\n\n def test1():\n obj = Obj()\n global ref\n ref = weakref.ref(obj)\n assert 0\n\n def test2():\n gc.collect()\n assert ref() is None\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*1 failed, 1 passed in*\"])\n\n\ndef test_fixture_mock_integration(testdir):\n \"\"\"Test that decorators applied to fixture are left working (#3774)\"\"\"\n p = testdir.copy_example(\"acceptance/fixture_mock_integration.py\")\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_usage_error_code(testdir):\n result = testdir.runpytest(\"-unknown-option-\")\n assert result.ret == EXIT_USAGEERROR\n\n\n@pytest.mark.skipif(\n sys.version_info[:2] < (3, 5), reason=\"async def syntax python 3.5+ only\"\n)\n@pytest.mark.filterwarnings(\"default\")\ndef test_warn_on_async_function(testdir):\n testdir.makepyfile(\n test_async=\"\"\"\n async def test_1():\n pass\n async def test_2():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"test_async.py::test_1\",\n \"test_async.py::test_2\",\n \"*Coroutine functions are not natively supported*\",\n \"*2 skipped, 2 warnings in*\",\n ]\n )\n # ensure our warning message appears only once\n assert (\n result.stdout.str().count(\"Coroutine functions are not natively supported\") == 1\n )\n"},{"className":"TestGeneralUsage","col":0,"comment":"null","endLoc":529,"id":5196,"nodeType":"Class","startLoc":29,"text":"class TestGeneralUsage(object):\n def test_config_error(self, testdir):\n testdir.copy_example(\"conftest_usageerror/conftest.py\")\n result = testdir.runpytest(testdir.tmpdir)\n assert result.ret == EXIT_USAGEERROR\n result.stderr.fnmatch_lines([\"*ERROR: hello\"])\n result.stdout.fnmatch_lines([\"*pytest_unconfigure_called\"])\n\n def test_root_conftest_syntax_error(self, testdir):\n testdir.makepyfile(conftest=\"raise SyntaxError\\n\")\n result = testdir.runpytest()\n result.stderr.fnmatch_lines([\"*raise SyntaxError*\"])\n assert result.ret != 0\n\n def test_early_hook_error_issue38_1(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_sessionstart():\n 0 / 0\n \"\"\"\n )\n result = testdir.runpytest(testdir.tmpdir)\n assert result.ret != 0\n # tracestyle is native by default for hook failures\n result.stdout.fnmatch_lines(\n [\"*INTERNALERROR*File*conftest.py*line 2*\", \"*0 / 0*\"]\n )\n result = testdir.runpytest(testdir.tmpdir, \"--fulltrace\")\n assert result.ret != 0\n # tracestyle is native by default for hook failures\n result.stdout.fnmatch_lines(\n [\"*INTERNALERROR*def pytest_sessionstart():*\", \"*INTERNALERROR*0 / 0*\"]\n )\n\n def test_early_hook_configure_error_issue38(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_configure():\n 0 / 0\n \"\"\"\n )\n result = testdir.runpytest(testdir.tmpdir)\n assert result.ret != 0\n # here we get it on stderr\n result.stderr.fnmatch_lines(\n [\"*INTERNALERROR*File*conftest.py*line 2*\", \"*0 / 0*\"]\n )\n\n def test_file_not_found(self, testdir):\n result = testdir.runpytest(\"asd\")\n assert result.ret != 0\n result.stderr.fnmatch_lines([\"ERROR: file not found*asd\"])\n\n def test_file_not_found_unconfigure_issue143(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_configure():\n print(\"---configure\")\n def pytest_unconfigure():\n print(\"---unconfigure\")\n \"\"\"\n )\n result = testdir.runpytest(\"-s\", \"asd\")\n assert result.ret == 4 # EXIT_USAGEERROR\n result.stderr.fnmatch_lines([\"ERROR: file not found*asd\"])\n result.stdout.fnmatch_lines([\"*---configure\", \"*---unconfigure\"])\n\n def test_config_preparse_plugin_option(self, testdir):\n testdir.makepyfile(\n pytest_xyz=\"\"\"\n def pytest_addoption(parser):\n parser.addoption(\"--xyz\", dest=\"xyz\", action=\"store\")\n \"\"\"\n )\n testdir.makepyfile(\n test_one=\"\"\"\n def test_option(pytestconfig):\n assert pytestconfig.option.xyz == \"123\"\n \"\"\"\n )\n result = testdir.runpytest(\"-p\", \"pytest_xyz\", \"--xyz=123\", syspathinsert=True)\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n @pytest.mark.parametrize(\"load_cov_early\", [True, False])\n def test_early_load_setuptools_name(self, testdir, monkeypatch, load_cov_early):\n testdir.makepyfile(mytestplugin1_module=\"\")\n testdir.makepyfile(mytestplugin2_module=\"\")\n testdir.makepyfile(mycov_module=\"\")\n testdir.syspathinsert()\n\n loaded = []\n\n @attr.s\n class DummyEntryPoint(object):\n name = attr.ib()\n module = attr.ib()\n group = \"pytest11\"\n\n def load(self):\n __import__(self.module)\n loaded.append(self.name)\n return sys.modules[self.module]\n\n entry_points = [\n DummyEntryPoint(\"myplugin1\", \"mytestplugin1_module\"),\n DummyEntryPoint(\"myplugin2\", \"mytestplugin2_module\"),\n DummyEntryPoint(\"mycov\", \"mycov_module\"),\n ]\n\n @attr.s\n class DummyDist(object):\n entry_points = attr.ib()\n files = ()\n\n def my_dists():\n return (DummyDist(entry_points),)\n\n monkeypatch.setattr(importlib_metadata, \"distributions\", my_dists)\n params = (\"-p\", \"mycov\") if load_cov_early else ()\n testdir.runpytest_inprocess(*params)\n if load_cov_early:\n assert loaded == [\"mycov\", \"myplugin1\", \"myplugin2\"]\n else:\n assert loaded == [\"myplugin1\", \"myplugin2\", \"mycov\"]\n\n def test_assertion_magic(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_this():\n x = 0\n assert x\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"> assert x\", \"E assert 0\"])\n assert result.ret == 1\n\n def test_nested_import_error(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import import_fails\n def test_this():\n assert import_fails.a == 1\n \"\"\"\n )\n testdir.makepyfile(import_fails=\"import does_not_work\")\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n # XXX on jython this fails: \"> import import_fails\",\n \"ImportError while importing test module*\",\n \"*No module named *does_not_work*\",\n ]\n )\n assert result.ret == 2\n\n def test_not_collectable_arguments(self, testdir):\n p1 = testdir.makepyfile(\"\")\n p2 = testdir.makefile(\".pyc\", \"123\")\n result = testdir.runpytest(p1, p2)\n assert result.ret\n result.stderr.fnmatch_lines([\"*ERROR: not found:*{}\".format(p2.basename)])\n\n @pytest.mark.filterwarnings(\"default\")\n def test_better_reporting_on_conftest_load_failure(self, testdir, request):\n \"\"\"Show a user-friendly traceback on conftest import failures (#486, #3332)\"\"\"\n testdir.makepyfile(\"\")\n testdir.makeconftest(\n \"\"\"\n def foo():\n import qwerty\n foo()\n \"\"\"\n )\n result = testdir.runpytest(\"--help\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *--version*\n *warning*conftest.py*\n \"\"\"\n )\n result = testdir.runpytest()\n dirname = request.node.name + \"0\"\n exc_name = (\n \"ModuleNotFoundError\" if sys.version_info >= (3, 6) else \"ImportError\"\n )\n result.stderr.fnmatch_lines(\n [\n \"ImportError while loading conftest '*{sep}{dirname}{sep}conftest.py'.\".format(\n dirname=dirname, sep=os.sep\n ),\n \"conftest.py:3: in \",\n \" foo()\",\n \"conftest.py:2: in foo\",\n \" import qwerty\",\n \"E {}: No module named {q}qwerty{q}\".format(\n exc_name, q=\"\" if six.PY2 else \"'\"\n ),\n ]\n )\n\n def test_early_skip(self, testdir):\n testdir.mkdir(\"xyz\")\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_collect_directory():\n pytest.skip(\"early\")\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result.stdout.fnmatch_lines([\"*1 skip*\"])\n\n def test_issue88_initial_file_multinodes(self, testdir):\n testdir.copy_example(\"issue88_initial_file_multinodes\")\n p = testdir.makepyfile(\"def test_hello(): pass\")\n result = testdir.runpytest(p, \"--collect-only\")\n result.stdout.fnmatch_lines([\"*MyFile*test_issue88*\", \"*Module*test_issue88*\"])\n\n def test_issue93_initialnode_importing_capturing(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import sys\n print(\"should not be seen\")\n sys.stderr.write(\"stder42\\\\n\")\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n assert \"should not be seen\" not in result.stdout.str()\n assert \"stderr42\" not in result.stderr.str()\n\n def test_conftest_printing_shows_if_error(self, testdir):\n testdir.makeconftest(\n \"\"\"\n print(\"should be seen\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret != 0\n assert \"should be seen\" in result.stdout.str()\n\n @pytest.mark.skipif(\n not hasattr(py.path.local, \"mksymlinkto\"),\n reason=\"symlink not available on this platform\",\n )\n def test_chdir(self, testdir):\n testdir.tmpdir.join(\"py\").mksymlinkto(py._pydir)\n p = testdir.tmpdir.join(\"main.py\")\n p.write(\n textwrap.dedent(\n \"\"\"\\\n import sys, os\n sys.path.insert(0, '')\n import py\n print(py.__file__)\n print(py.__path__)\n os.chdir(os.path.dirname(os.getcwd()))\n print(py.log)\n \"\"\"\n )\n )\n result = testdir.runpython(p)\n assert not result.ret\n\n def test_issue109_sibling_conftests_not_loaded(self, testdir):\n sub1 = testdir.mkdir(\"sub1\")\n sub2 = testdir.mkdir(\"sub2\")\n sub1.join(\"conftest.py\").write(\"assert 0\")\n result = testdir.runpytest(sub2)\n assert result.ret == EXIT_NOTESTSCOLLECTED\n sub2.ensure(\"__init__.py\")\n p = sub2.ensure(\"test_hello.py\")\n result = testdir.runpytest(p)\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result = testdir.runpytest(sub1)\n assert result.ret == EXIT_USAGEERROR\n\n def test_directory_skipped(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_ignore_collect():\n pytest.skip(\"intentional\")\n \"\"\"\n )\n testdir.makepyfile(\"def test_hello(): pass\")\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result.stdout.fnmatch_lines([\"*1 skipped*\"])\n\n def test_multiple_items_per_collector_byid(self, testdir):\n c = testdir.makeconftest(\n \"\"\"\n import pytest\n class MyItem(pytest.Item):\n def runtest(self):\n pass\n class MyCollector(pytest.File):\n def collect(self):\n return [MyItem(name=\"xyz\", parent=self)]\n def pytest_collect_file(path, parent):\n if path.basename.startswith(\"conftest\"):\n return MyCollector(path, parent)\n \"\"\"\n )\n result = testdir.runpytest(c.basename + \"::\" + \"xyz\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 pass*\"])\n\n def test_skip_on_generated_funcarg_id(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('x', [3], ids=['hello-123'])\n def pytest_runtest_setup(item):\n print(item.keywords)\n if 'hello-123' in item.keywords:\n pytest.skip(\"hello\")\n assert 0\n \"\"\"\n )\n p = testdir.makepyfile(\"\"\"def test_func(x): pass\"\"\")\n res = testdir.runpytest(p, SHOW_PYTEST_WARNINGS_ARG)\n assert res.ret == 0\n res.stdout.fnmatch_lines([\"*1 skipped*\"])\n\n def test_direct_addressing_selects(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('i', [1, 2], ids=[\"1\", \"2\"])\n def test_func(i):\n pass\n \"\"\"\n )\n res = testdir.runpytest(\n p.basename + \"::\" + \"test_func[1]\", SHOW_PYTEST_WARNINGS_ARG\n )\n assert res.ret == 0\n res.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_direct_addressing_notfound(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n res = testdir.runpytest(p.basename + \"::\" + \"test_notfound\")\n assert res.ret\n res.stderr.fnmatch_lines([\"*ERROR*not found*\"])\n\n def test_docstring_on_hookspec(self):\n from _pytest import hookspec\n\n for name, value in vars(hookspec).items():\n if name.startswith(\"pytest_\"):\n assert value.__doc__, \"no docstring for %s\" % name\n\n def test_initialization_error_issue49(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_configure():\n x\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 3 # internal error\n result.stderr.fnmatch_lines([\"INTERNAL*pytest_configure*\", \"INTERNAL*x*\"])\n assert \"sessionstarttime\" not in result.stderr.str()\n\n @pytest.mark.parametrize(\"lookfor\", [\"test_fun.py::test_a\"])\n def test_issue134_report_error_when_collecting_member(self, testdir, lookfor):\n testdir.makepyfile(\n test_fun=\"\"\"\n def test_a():\n pass\n def\"\"\"\n )\n result = testdir.runpytest(lookfor)\n result.stdout.fnmatch_lines([\"*SyntaxError*\"])\n if \"::\" in lookfor:\n result.stderr.fnmatch_lines([\"*ERROR*\"])\n assert result.ret == 4 # usage error only if item not found\n\n def test_report_all_failed_collections_initargs(self, testdir):\n testdir.makeconftest(\n \"\"\"\n from _pytest.main import EXIT_USAGEERROR\n\n def pytest_sessionfinish(exitstatus):\n assert exitstatus == EXIT_USAGEERROR\n print(\"pytest_sessionfinish_called\")\n \"\"\"\n )\n testdir.makepyfile(test_a=\"def\", test_b=\"def\")\n result = testdir.runpytest(\"test_a.py::a\", \"test_b.py::b\")\n result.stderr.fnmatch_lines([\"*ERROR*test_a.py::a*\", \"*ERROR*test_b.py::b*\"])\n result.stdout.fnmatch_lines([\"pytest_sessionfinish_called\"])\n assert result.ret == EXIT_USAGEERROR\n\n @pytest.mark.usefixtures(\"recwarn\")\n def test_namespace_import_doesnt_confuse_import_hook(self, testdir):\n \"\"\"\n Ref #383. Python 3.3's namespace package messed with our import hooks\n Importing a module that didn't exist, even if the ImportError was\n gracefully handled, would make our test crash.\n\n Use recwarn here to silence this warning in Python 2.7:\n ImportWarning: Not importing directory '...\\not_a_package': missing __init__.py\n \"\"\"\n testdir.mkdir(\"not_a_package\")\n p = testdir.makepyfile(\n \"\"\"\n try:\n from not_a_package import doesnt_exist\n except ImportError:\n # We handle the import error gracefully here\n pass\n\n def test_whatever():\n pass\n \"\"\"\n )\n res = testdir.runpytest(p.basename)\n assert res.ret == 0\n\n def test_unknown_option(self, testdir):\n result = testdir.runpytest(\"--qwlkej\")\n result.stderr.fnmatch_lines(\n \"\"\"\n *unrecognized*\n \"\"\"\n )\n\n def test_getsourcelines_error_issue553(self, testdir, monkeypatch):\n monkeypatch.setattr(\"inspect.getsourcelines\", None)\n p = testdir.makepyfile(\n \"\"\"\n def raise_error(obj):\n raise IOError('source code not available')\n\n import inspect\n inspect.getsourcelines = raise_error\n\n def test_foo(invalid_fixture):\n pass\n \"\"\"\n )\n res = testdir.runpytest(p)\n res.stdout.fnmatch_lines(\n [\"*source code not available*\", \"E*fixture 'invalid_fixture' not found\"]\n )\n\n def test_plugins_given_as_strings(self, tmpdir, monkeypatch, _sys_snapshot):\n \"\"\"test that str values passed to main() as `plugins` arg\n are interpreted as module names to be imported and registered.\n #855.\n \"\"\"\n with pytest.raises(ImportError) as excinfo:\n pytest.main([str(tmpdir)], plugins=[\"invalid.module\"])\n assert \"invalid\" in str(excinfo.value)\n\n p = tmpdir.join(\"test_test_plugins_given_as_strings.py\")\n p.write(\"def test_foo(): pass\")\n mod = types.ModuleType(\"myplugin\")\n monkeypatch.setitem(sys.modules, \"myplugin\", mod)\n assert pytest.main(args=[str(tmpdir)], plugins=[\"myplugin\"]) == 0\n\n def test_parametrized_with_bytes_regex(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import re\n import pytest\n @pytest.mark.parametrize('r', [re.compile(b'foo')])\n def test_stuff(r):\n pass\n \"\"\"\n )\n res = testdir.runpytest(p)\n res.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_parametrized_with_null_bytes(self, testdir):\n \"\"\"Test parametrization with values that contain null bytes and unicode characters (#2644, #2957)\"\"\"\n p = testdir.makepyfile(\n u\"\"\"\n # encoding: UTF-8\n import pytest\n\n @pytest.mark.parametrize(\"data\", [b\"\\\\x00\", \"\\\\x00\", u'ação'])\n def test_foo(data):\n assert data\n \"\"\"\n )\n res = testdir.runpytest(p)\n res.assert_outcomes(passed=3)"},{"col":4,"comment":"null","endLoc":35,"header":"def test_config_error(self, testdir)","id":5197,"name":"test_config_error","nodeType":"Function","startLoc":30,"text":"def test_config_error(self, testdir):\n testdir.copy_example(\"conftest_usageerror/conftest.py\")\n result = testdir.runpytest(testdir.tmpdir)\n assert result.ret == EXIT_USAGEERROR\n result.stderr.fnmatch_lines([\"*ERROR: hello\"])\n result.stdout.fnmatch_lines([\"*pytest_unconfigure_called\"])"},{"col":0,"comment":"Enable bytes capturing of writes to ``sys.stdout`` and ``sys.stderr``.\n\n The captured output is made available via ``capsysbinary.readouterr()``\n method calls, which return a ``(out, err)`` namedtuple.\n ``out`` and ``err`` will be ``bytes`` objects.\n ","endLoc":291,"header":"@pytest.fixture\ndef capsysbinary(request)","id":5198,"name":"capsysbinary","nodeType":"Function","startLoc":277,"text":"@pytest.fixture\ndef capsysbinary(request):\n \"\"\"Enable bytes capturing of writes to ``sys.stdout`` and ``sys.stderr``.\n\n The captured output is made available via ``capsysbinary.readouterr()``\n method calls, which return a ``(out, err)`` namedtuple.\n ``out`` and ``err`` will be ``bytes`` objects.\n \"\"\"\n _ensure_only_one_capture_fixture(request, \"capsysbinary\")\n # Currently, the implementation uses the python3 specific `.buffer`\n # property of CaptureIO.\n if sys.version_info < (3,):\n raise request.raiseerror(\"capsysbinary is only supported on Python 3\")\n with _install_capture_fixture_on_item(request, SysCaptureBinary) as fixture:\n yield fixture"},{"col":0,"comment":"","endLoc":2,"header":"python.py#","id":5199,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" Python test discovery, setup and run of test functions. \"\"\""},{"col":0,"comment":"Enable text capturing of writes to file descriptors ``1`` and ``2``.\n\n The captured output is made available via ``capfd.readouterr()`` method\n calls, which return a ``(out, err)`` namedtuple.\n ``out`` and ``err`` will be ``text`` objects.\n ","endLoc":308,"header":"@pytest.fixture\ndef capfd(request)","id":5200,"name":"capfd","nodeType":"Function","startLoc":294,"text":"@pytest.fixture\ndef capfd(request):\n \"\"\"Enable text capturing of writes to file descriptors ``1`` and ``2``.\n\n The captured output is made available via ``capfd.readouterr()`` method\n calls, which return a ``(out, err)`` namedtuple.\n ``out`` and ``err`` will be ``text`` objects.\n \"\"\"\n _ensure_only_one_capture_fixture(request, \"capfd\")\n if not hasattr(os, \"dup\"):\n pytest.skip(\n \"capfd fixture needs os.dup function which is not available in this system\"\n )\n with _install_capture_fixture_on_item(request, FDCapture) as fixture:\n yield fixture"},{"col":0,"comment":"Enable bytes capturing of writes to file descriptors ``1`` and ``2``.\n\n The captured output is made available via ``capfd.readouterr()`` method\n calls, which return a ``(out, err)`` namedtuple.\n ``out`` and ``err`` will be ``byte`` objects.\n ","endLoc":325,"header":"@pytest.fixture\ndef capfdbinary(request)","id":5201,"name":"capfdbinary","nodeType":"Function","startLoc":311,"text":"@pytest.fixture\ndef capfdbinary(request):\n \"\"\"Enable bytes capturing of writes to file descriptors ``1`` and ``2``.\n\n The captured output is made available via ``capfd.readouterr()`` method\n calls, which return a ``(out, err)`` namedtuple.\n ``out`` and ``err`` will be ``byte`` objects.\n \"\"\"\n _ensure_only_one_capture_fixture(request, \"capfdbinary\")\n if not hasattr(os, \"dup\"):\n pytest.skip(\n \"capfdbinary fixture needs os.dup function which is not available in this system\"\n )\n with _install_capture_fixture_on_item(request, FDCaptureBinary) as fixture:\n yield fixture"},{"col":0,"comment":"\n Context manager which creates a ``CaptureFixture`` instance and \"installs\" it on\n the item/node of the given request. Used by ``capsys`` and ``capfd``.\n\n The CaptureFixture is added as attribute of the item because it needs to accessed\n by ``CaptureManager`` during its ``pytest_runtest_*`` hooks.\n ","endLoc":345,"header":"@contextlib.contextmanager\ndef _install_capture_fixture_on_item(request, capture_class)","id":5202,"name":"_install_capture_fixture_on_item","nodeType":"Function","startLoc":328,"text":"@contextlib.contextmanager\ndef _install_capture_fixture_on_item(request, capture_class):\n \"\"\"\n Context manager which creates a ``CaptureFixture`` instance and \"installs\" it on\n the item/node of the given request. Used by ``capsys`` and ``capfd``.\n\n The CaptureFixture is added as attribute of the item because it needs to accessed\n by ``CaptureManager`` during its ``pytest_runtest_*`` hooks.\n \"\"\"\n request.node._capture_fixture = fixture = CaptureFixture(capture_class, request)\n capmanager = request.config.pluginmanager.getplugin(\"capturemanager\")\n # Need to active this fixture right away in case it is being used by another fixture (setup phase).\n # If this fixture is being used only by a test function (call phase), then we wouldn't need this\n # activation, but it doesn't hurt.\n capmanager.activate_fixture(request.node)\n yield fixture\n fixture.close()\n del request.node._capture_fixture"},{"attributeType":"dict","col":0,"comment":"null","endLoc":24,"id":5203,"name":"patchsysdict","nodeType":"Attribute","startLoc":24,"text":"patchsysdict"},{"attributeType":"set","col":0,"comment":"null","endLoc":251,"id":5204,"name":"capture_fixtures","nodeType":"Attribute","startLoc":251,"text":"capture_fixtures"},{"attributeType":"CaptureResult","col":0,"comment":"null","endLoc":460,"id":5205,"name":"CaptureResult","nodeType":"Attribute","startLoc":460,"text":"CaptureResult"},{"col":0,"comment":"","endLoc":5,"header":"capture.py#","id":5206,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"\nper-test stdout/stderr capturing mechanism.\n\n\"\"\"\n\npatchsysdict = {0: \"stdin\", 1: \"stdout\", 2: \"stderr\"}\n\ncapture_fixtures = {\"capfd\", \"capfdbinary\", \"capsys\", \"capsysbinary\"}\n\nCaptureResult = collections.namedtuple(\"CaptureResult\", [\"out\", \"err\"])"},{"id":5207,"name":"testing/example_scripts/collect/collect_init_tests","nodeType":"Package"},{"id":5208,"name":"pytest.ini","nodeType":"TextFile","path":"testing/example_scripts/collect/collect_init_tests","text":"[pytest]\npython_files = *.py\n"},{"id":5209,"name":"testing/example_scripts/collect/package_infinite_recursion/tests","nodeType":"Package"},{"fileName":"__init__.py","filePath":"testing/example_scripts/collect/package_infinite_recursion/tests","id":5210,"nodeType":"File","text":""},{"id":5211,"name":"release-3.7.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.7.2\n=======================================\n\npytest 3.7.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Josh Holland\n* Ronny Pfannschmidt\n* Sankt Petersbug\n* Wes Thomas\n* turturica\n\n\nHappy testing,\nThe pytest Development Team\n"},{"id":5212,"name":"markers.rst","nodeType":"TextFile","path":"doc/en/example","text":"\n.. _`mark examples`:\n\nWorking with custom markers\n=================================================\n\nHere are some examples using the :ref:`mark` mechanism.\n\n.. _`mark run`:\n\nMarking test functions and selecting them for a run\n----------------------------------------------------\n\nYou can \"mark\" a test function with custom metadata like this:\n\n.. code-block:: python\n\n # content of test_server.py\n\n import pytest\n\n\n @pytest.mark.webtest\n def test_send_http():\n pass # perform some webtest test for your app\n\n\n def test_something_quick():\n pass\n\n\n def test_another():\n pass\n\n\n class TestClass(object):\n def test_method(self):\n pass\n\n\n\nYou can then restrict a test run to only run tests marked with ``webtest``:\n\n.. code-block:: pytest\n\n $ pytest -v -m webtest\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collecting ... collected 4 items / 3 deselected / 1 selected\n\n test_server.py::test_send_http PASSED [100%]\n\n ================== 1 passed, 3 deselected in 0.12 seconds ==================\n\nOr the inverse, running all tests except the webtest ones:\n\n.. code-block:: pytest\n\n $ pytest -v -m \"not webtest\"\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collecting ... collected 4 items / 1 deselected / 3 selected\n\n test_server.py::test_something_quick PASSED [ 33%]\n test_server.py::test_another PASSED [ 66%]\n test_server.py::TestClass::test_method PASSED [100%]\n\n ================== 3 passed, 1 deselected in 0.12 seconds ==================\n\nSelecting tests based on their node ID\n--------------------------------------\n\nYou can provide one or more :ref:`node IDs ` as positional\narguments to select only specified tests. This makes it easy to select\ntests based on their module, class, method, or function name:\n\n.. code-block:: pytest\n\n $ pytest -v test_server.py::TestClass::test_method\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collecting ... collected 1 item\n\n test_server.py::TestClass::test_method PASSED [100%]\n\n ========================= 1 passed in 0.12 seconds =========================\n\nYou can also select on the class:\n\n.. code-block:: pytest\n\n $ pytest -v test_server.py::TestClass\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collecting ... collected 1 item\n\n test_server.py::TestClass::test_method PASSED [100%]\n\n ========================= 1 passed in 0.12 seconds =========================\n\nOr select multiple nodes:\n\n.. code-block:: pytest\n\n $ pytest -v test_server.py::TestClass test_server.py::test_send_http\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collecting ... collected 2 items\n\n test_server.py::TestClass::test_method PASSED [ 50%]\n test_server.py::test_send_http PASSED [100%]\n\n ========================= 2 passed in 0.12 seconds =========================\n\n.. _node-id:\n\n.. note::\n\n Node IDs are of the form ``module.py::class::method`` or\n ``module.py::function``. Node IDs control which tests are\n collected, so ``module.py::class`` will select all test methods\n on the class. Nodes are also created for each parameter of a\n parametrized fixture or test, so selecting a parametrized test\n must include the parameter value, e.g.\n ``module.py::function[param]``.\n\n Node IDs for failing tests are displayed in the test summary info\n when running pytest with the ``-rf`` option. You can also\n construct Node IDs from the output of ``pytest --collectonly``.\n\nUsing ``-k expr`` to select tests based on their name\n-------------------------------------------------------\n\n.. versionadded: 2.0/2.3.4\n\nYou can use the ``-k`` command line option to specify an expression\nwhich implements a substring match on the test names instead of the\nexact match on markers that ``-m`` provides. This makes it easy to\nselect tests based on their names:\n\n.. code-block:: pytest\n\n $ pytest -v -k http # running with the above defined example module\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collecting ... collected 4 items / 3 deselected / 1 selected\n\n test_server.py::test_send_http PASSED [100%]\n\n ================== 1 passed, 3 deselected in 0.12 seconds ==================\n\nAnd you can also run all tests except the ones that match the keyword:\n\n.. code-block:: pytest\n\n $ pytest -k \"not send_http\" -v\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collecting ... collected 4 items / 1 deselected / 3 selected\n\n test_server.py::test_something_quick PASSED [ 33%]\n test_server.py::test_another PASSED [ 66%]\n test_server.py::TestClass::test_method PASSED [100%]\n\n ================== 3 passed, 1 deselected in 0.12 seconds ==================\n\nOr to select \"http\" and \"quick\" tests:\n\n.. code-block:: pytest\n\n $ pytest -k \"http or quick\" -v\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collecting ... collected 4 items / 2 deselected / 2 selected\n\n test_server.py::test_send_http PASSED [ 50%]\n test_server.py::test_something_quick PASSED [100%]\n\n ================== 2 passed, 2 deselected in 0.12 seconds ==================\n\n.. note::\n\n If you are using expressions such as ``\"X and Y\"`` then both ``X`` and ``Y``\n need to be simple non-keyword names. For example, ``\"pass\"`` or ``\"from\"``\n will result in SyntaxErrors because ``\"-k\"`` evaluates the expression using\n Python's `eval`_ function.\n\n.. _`eval`: https://docs.python.org/3.6/library/functions.html#eval\n\n\n However, if the ``\"-k\"`` argument is a simple string, no such restrictions\n apply. Also ``\"-k 'not STRING'\"`` has no restrictions. You can also\n specify numbers like ``\"-k 1.3\"`` to match tests which are parametrized\n with the float ``\"1.3\"``.\n\nRegistering markers\n-------------------------------------\n\n\n\n.. ini-syntax for custom markers:\n\nRegistering markers for your test suite is simple:\n\n.. code-block:: ini\n\n # content of pytest.ini\n [pytest]\n markers =\n webtest: mark a test as a webtest.\n\nYou can ask which markers exist for your test suite - the list includes our just defined ``webtest`` markers:\n\n.. code-block:: pytest\n\n $ pytest --markers\n @pytest.mark.webtest: mark a test as a webtest.\n\n @pytest.mark.filterwarnings(warning): add a warning filter to the given test. see https://docs.pytest.org/en/latest/warnings.html#pytest-mark-filterwarnings\n\n @pytest.mark.skip(reason=None): skip the given test function with an optional reason. Example: skip(reason=\"no way of currently testing this\") skips the test.\n\n @pytest.mark.skipif(condition): skip the given test function if eval(condition) results in a True value. Evaluation happens within the module global context. Example: skipif('sys.platform == \"win32\"') skips the test if we are on the win32 platform. see https://docs.pytest.org/en/latest/skipping.html\n\n @pytest.mark.xfail(condition, reason=None, run=True, raises=None, strict=False): mark the test function as an expected failure if eval(condition) has a True value. Optionally specify a reason for better reporting and run=False if you don't even want to execute the test function. If only specific exception(s) are expected, you can list them in raises, and if the test fails in other ways, it will be reported as a true failure. See https://docs.pytest.org/en/latest/skipping.html\n\n @pytest.mark.parametrize(argnames, argvalues): call a test function multiple times passing in different arguments in turn. argvalues generally needs to be a list of values if argnames specifies only one name or a list of tuples of values if argnames specifies multiple names. Example: @parametrize('arg1', [1,2]) would lead to two calls of the decorated test function, one with arg1=1 and another with arg1=2.see https://docs.pytest.org/en/latest/parametrize.html for more info and examples.\n\n @pytest.mark.usefixtures(fixturename1, fixturename2, ...): mark tests as needing all of the specified fixtures. see https://docs.pytest.org/en/latest/fixture.html#usefixtures\n\n @pytest.mark.tryfirst: mark a hook implementation function such that the plugin machinery will try to call it first/as early as possible.\n\n @pytest.mark.trylast: mark a hook implementation function such that the plugin machinery will try to call it last/as late as possible.\n\n\nFor an example on how to add and work with markers from a plugin, see\n:ref:`adding a custom marker from a plugin`.\n\n.. note::\n\n It is recommended to explicitly register markers so that:\n\n * There is one place in your test suite defining your markers\n\n * Asking for existing markers via ``pytest --markers`` gives good output\n\n * Typos in function markers are treated as an error if you use\n the ``--strict-markers`` option.\n\n.. _`scoped-marking`:\n\nMarking whole classes or modules\n----------------------------------------------------\n\nYou may use ``pytest.mark`` decorators with classes to apply markers to all of\nits test methods:\n\n.. code-block:: python\n\n # content of test_mark_classlevel.py\n import pytest\n\n\n @pytest.mark.webtest\n class TestClass(object):\n def test_startup(self):\n pass\n\n def test_startup_and_more(self):\n pass\n\nThis is equivalent to directly applying the decorator to the\ntwo test functions.\n\nTo remain backward-compatible with Python 2.4 you can also set a\n``pytestmark`` attribute on a TestClass like this:\n\n.. code-block:: python\n\n import pytest\n\n\n class TestClass(object):\n pytestmark = pytest.mark.webtest\n\nor if you need to use multiple markers you can use a list:\n\n.. code-block:: python\n\n import pytest\n\n\n class TestClass(object):\n pytestmark = [pytest.mark.webtest, pytest.mark.slowtest]\n\nYou can also set a module level marker::\n\n import pytest\n pytestmark = pytest.mark.webtest\n\nor multiple markers::\n\n pytestmark = [pytest.mark.webtest, pytest.mark.slowtest]\n\nin which case markers will be applied (in left-to-right order) to\nall functions and methods defined in the module.\n\n.. _`marking individual tests when using parametrize`:\n\nMarking individual tests when using parametrize\n-----------------------------------------------\n\nWhen using parametrize, applying a mark will make it apply\nto each individual test. However it is also possible to\napply a marker to an individual test instance:\n\n.. code-block:: python\n\n import pytest\n\n\n @pytest.mark.foo\n @pytest.mark.parametrize(\n (\"n\", \"expected\"), [(1, 2), pytest.param((1, 3), marks=pytest.mark.bar), (2, 3)]\n )\n def test_increment(n, expected):\n assert n + 1 == expected\n\nIn this example the mark \"foo\" will apply to each of the three\ntests, whereas the \"bar\" mark is only applied to the second test.\nSkip and xfail marks can also be applied in this way, see :ref:`skip/xfail with parametrize`.\n\n.. _`adding a custom marker from a plugin`:\n\nCustom marker and command line option to control test runs\n----------------------------------------------------------\n\n.. regendoc:wipe\n\nPlugins can provide custom markers and implement specific behaviour\nbased on it. This is a self-contained example which adds a command\nline option and a parametrized test function marker to run tests\nspecifies via named environments:\n\n.. code-block:: python\n\n # content of conftest.py\n\n import pytest\n\n\n def pytest_addoption(parser):\n parser.addoption(\n \"-E\",\n action=\"store\",\n metavar=\"NAME\",\n help=\"only run tests matching the environment NAME.\",\n )\n\n\n def pytest_configure(config):\n # register an additional marker\n config.addinivalue_line(\n \"markers\", \"env(name): mark test to run only on named environment\"\n )\n\n\n def pytest_runtest_setup(item):\n envnames = [mark.args[0] for mark in item.iter_markers(name=\"env\")]\n if envnames:\n if item.config.getoption(\"-E\") not in envnames:\n pytest.skip(\"test requires env in %r\" % envnames)\n\nA test file using this local plugin:\n\n.. code-block:: python\n\n # content of test_someenv.py\n\n import pytest\n\n\n @pytest.mark.env(\"stage1\")\n def test_basic_db_operation():\n pass\n\nand an example invocations specifying a different environment than what\nthe test needs:\n\n.. code-block:: pytest\n\n $ pytest -E stage2\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 1 item\n\n test_someenv.py s [100%]\n\n ======================== 1 skipped in 0.12 seconds =========================\n\nand here is one that specifies exactly the environment needed:\n\n.. code-block:: pytest\n\n $ pytest -E stage1\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 1 item\n\n test_someenv.py . [100%]\n\n ========================= 1 passed in 0.12 seconds =========================\n\nThe ``--markers`` option always gives you a list of available markers:\n\n.. code-block:: pytest\n\n $ pytest --markers\n @pytest.mark.env(name): mark test to run only on named environment\n\n @pytest.mark.filterwarnings(warning): add a warning filter to the given test. see https://docs.pytest.org/en/latest/warnings.html#pytest-mark-filterwarnings\n\n @pytest.mark.skip(reason=None): skip the given test function with an optional reason. Example: skip(reason=\"no way of currently testing this\") skips the test.\n\n @pytest.mark.skipif(condition): skip the given test function if eval(condition) results in a True value. Evaluation happens within the module global context. Example: skipif('sys.platform == \"win32\"') skips the test if we are on the win32 platform. see https://docs.pytest.org/en/latest/skipping.html\n\n @pytest.mark.xfail(condition, reason=None, run=True, raises=None, strict=False): mark the test function as an expected failure if eval(condition) has a True value. Optionally specify a reason for better reporting and run=False if you don't even want to execute the test function. If only specific exception(s) are expected, you can list them in raises, and if the test fails in other ways, it will be reported as a true failure. See https://docs.pytest.org/en/latest/skipping.html\n\n @pytest.mark.parametrize(argnames, argvalues): call a test function multiple times passing in different arguments in turn. argvalues generally needs to be a list of values if argnames specifies only one name or a list of tuples of values if argnames specifies multiple names. Example: @parametrize('arg1', [1,2]) would lead to two calls of the decorated test function, one with arg1=1 and another with arg1=2.see https://docs.pytest.org/en/latest/parametrize.html for more info and examples.\n\n @pytest.mark.usefixtures(fixturename1, fixturename2, ...): mark tests as needing all of the specified fixtures. see https://docs.pytest.org/en/latest/fixture.html#usefixtures\n\n @pytest.mark.tryfirst: mark a hook implementation function such that the plugin machinery will try to call it first/as early as possible.\n\n @pytest.mark.trylast: mark a hook implementation function such that the plugin machinery will try to call it last/as late as possible.\n\n\n.. _`passing callables to custom markers`:\n\nPassing a callable to custom markers\n--------------------------------------------\n\n.. regendoc:wipe\n\nBelow is the config file that will be used in the next examples:\n\n.. code-block:: python\n\n # content of conftest.py\n import sys\n\n\n def pytest_runtest_setup(item):\n for marker in item.iter_markers(name=\"my_marker\"):\n print(marker)\n sys.stdout.flush()\n\nA custom marker can have its argument set, i.e. ``args`` and ``kwargs`` properties, defined by either invoking it as a callable or using ``pytest.mark.MARKER_NAME.with_args``. These two methods achieve the same effect most of the time.\n\nHowever, if there is a callable as the single positional argument with no keyword arguments, using the ``pytest.mark.MARKER_NAME(c)`` will not pass ``c`` as a positional argument but decorate ``c`` with the custom marker (see :ref:`MarkDecorator `). Fortunately, ``pytest.mark.MARKER_NAME.with_args`` comes to the rescue:\n\n.. code-block:: python\n\n # content of test_custom_marker.py\n import pytest\n\n\n def hello_world(*args, **kwargs):\n return \"Hello World\"\n\n\n @pytest.mark.my_marker.with_args(hello_world)\n def test_with_args():\n pass\n\nThe output is as follows:\n\n.. code-block:: pytest\n\n $ pytest -q -s\n Mark(name='my_marker', args=(,), kwargs={})\n .\n 1 passed in 0.12 seconds\n\nWe can see that the custom marker has its argument set extended with the function ``hello_world``. This is the key difference between creating a custom marker as a callable, which invokes ``__call__`` behind the scenes, and using ``with_args``.\n\n\nReading markers which were set from multiple places\n----------------------------------------------------\n\n.. versionadded: 2.2.2\n\n.. regendoc:wipe\n\nIf you are heavily using markers in your test suite you may encounter the case where a marker is applied several times to a test function. From plugin\ncode you can read over all such settings. Example:\n\n.. code-block:: python\n\n # content of test_mark_three_times.py\n import pytest\n\n pytestmark = pytest.mark.glob(\"module\", x=1)\n\n\n @pytest.mark.glob(\"class\", x=2)\n class TestClass(object):\n @pytest.mark.glob(\"function\", x=3)\n def test_something(self):\n pass\n\nHere we have the marker \"glob\" applied three times to the same\ntest function. From a conftest file we can read it like this:\n\n.. code-block:: python\n\n # content of conftest.py\n import sys\n\n\n def pytest_runtest_setup(item):\n for mark in item.iter_markers(name=\"glob\"):\n print(\"glob args=%s kwargs=%s\" % (mark.args, mark.kwargs))\n sys.stdout.flush()\n\nLet's run this without capturing output and see what we get:\n\n.. code-block:: pytest\n\n $ pytest -q -s\n glob args=('function',) kwargs={'x': 3}\n glob args=('class',) kwargs={'x': 2}\n glob args=('module',) kwargs={'x': 1}\n .\n 1 passed in 0.12 seconds\n\nmarking platform specific tests with pytest\n--------------------------------------------------------------\n\n.. regendoc:wipe\n\nConsider you have a test suite which marks tests for particular platforms,\nnamely ``pytest.mark.darwin``, ``pytest.mark.win32`` etc. and you\nalso have tests that run on all platforms and have no specific\nmarker. If you now want to have a way to only run the tests\nfor your particular platform, you could use the following plugin:\n\n.. code-block:: python\n\n # content of conftest.py\n #\n import sys\n import pytest\n\n ALL = set(\"darwin linux win32\".split())\n\n\n def pytest_runtest_setup(item):\n supported_platforms = ALL.intersection(mark.name for mark in item.iter_markers())\n plat = sys.platform\n if supported_platforms and plat not in supported_platforms:\n pytest.skip(\"cannot run on platform %s\" % (plat))\n\nthen tests will be skipped if they were specified for a different platform.\nLet's do a little test file to show how this looks like:\n\n.. code-block:: python\n\n # content of test_plat.py\n\n import pytest\n\n\n @pytest.mark.darwin\n def test_if_apple_is_evil():\n pass\n\n\n @pytest.mark.linux\n def test_if_linux_works():\n pass\n\n\n @pytest.mark.win32\n def test_if_win32_crashes():\n pass\n\n\n def test_runs_everywhere():\n pass\n\nthen you will see two tests skipped and two executed tests as expected:\n\n.. code-block:: pytest\n\n $ pytest -rs # this option reports skip reasons\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 4 items\n\n test_plat.py s.s. [100%]\n\n ========================= short test summary info ==========================\n SKIPPED [2] $REGENDOC_TMPDIR/conftest.py:13: cannot run on platform linux\n =================== 2 passed, 2 skipped in 0.12 seconds ====================\n\nNote that if you specify a platform via the marker-command line option like this:\n\n.. code-block:: pytest\n\n $ pytest -m linux\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 4 items / 3 deselected / 1 selected\n\n test_plat.py . [100%]\n\n ================== 1 passed, 3 deselected in 0.12 seconds ==================\n\nthen the unmarked-tests will not be run. It is thus a way to restrict the run to the specific tests.\n\nAutomatically adding markers based on test names\n--------------------------------------------------------\n\n.. regendoc:wipe\n\nIf you a test suite where test function names indicate a certain\ntype of test, you can implement a hook that automatically defines\nmarkers so that you can use the ``-m`` option with it. Let's look\nat this test module:\n\n.. code-block:: python\n\n # content of test_module.py\n\n\n def test_interface_simple():\n assert 0\n\n\n def test_interface_complex():\n assert 0\n\n\n def test_event_simple():\n assert 0\n\n\n def test_something_else():\n assert 0\n\nWe want to dynamically define two markers and can do it in a\n``conftest.py`` plugin:\n\n.. code-block:: python\n\n # content of conftest.py\n\n import pytest\n\n\n def pytest_collection_modifyitems(items):\n for item in items:\n if \"interface\" in item.nodeid:\n item.add_marker(pytest.mark.interface)\n elif \"event\" in item.nodeid:\n item.add_marker(pytest.mark.event)\n\nWe can now use the ``-m option`` to select one set:\n\n.. code-block:: pytest\n\n $ pytest -m interface --tb=short\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 4 items / 2 deselected / 2 selected\n\n test_module.py FF [100%]\n\n ================================= FAILURES =================================\n __________________________ test_interface_simple ___________________________\n test_module.py:4: in test_interface_simple\n assert 0\n E assert 0\n __________________________ test_interface_complex __________________________\n test_module.py:8: in test_interface_complex\n assert 0\n E assert 0\n ================== 2 failed, 2 deselected in 0.12 seconds ==================\n\nor to select both \"event\" and \"interface\" tests:\n\n.. code-block:: pytest\n\n $ pytest -m \"interface or event\" --tb=short\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 4 items / 1 deselected / 3 selected\n\n test_module.py FFF [100%]\n\n ================================= FAILURES =================================\n __________________________ test_interface_simple ___________________________\n test_module.py:4: in test_interface_simple\n assert 0\n E assert 0\n __________________________ test_interface_complex __________________________\n test_module.py:8: in test_interface_complex\n assert 0\n E assert 0\n ____________________________ test_event_simple _____________________________\n test_module.py:12: in test_event_simple\n assert 0\n E assert 0\n ================== 3 failed, 1 deselected in 0.12 seconds ==================\n"},{"id":5213,"name":"license.rst","nodeType":"TextFile","path":"doc/en","text":".. _license:\n\nLicense\n-------\n\nDistributed under the terms of the `MIT`_ license, pytest is free and open source software.\n\n.. code-block:: text\n\n The MIT License (MIT)\n\n Copyright (c) 2004-2017 Holger Krekel and others\n\n Permission is hereby granted, free of charge, to any person obtaining a copy of\n this software and associated documentation files (the \"Software\"), to deal in\n the Software without restriction, including without limitation the rights to\n use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n of the Software, and to permit persons to whom the Software is furnished to do\n so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n.. _`MIT`: https://github.com/pytest-dev/pytest/blob/master/LICENSE\n"},{"id":5214,"name":"contact.rst","nodeType":"TextFile","path":"doc/en","text":"\n.. _`contact channels`:\n.. _`contact`:\n\nContact channels\n===================================\n\n- `pytest issue tracker`_ to report bugs or suggest features (for version\n 2.0 and above).\n\n- `pytest on stackoverflow.com `_\n to post questions with the tag ``pytest``. New Questions will usually\n be seen by pytest users or developers and answered quickly.\n\n- `Testing In Python`_: a mailing list for Python testing tools and discussion.\n\n- `pytest-dev at python.org (mailing list)`_ pytest specific announcements and discussions.\n\n- `pytest-commit at python.org (mailing list)`_: for commits and new issues\n\n- :doc:`contribution guide ` for help on submitting pull\n requests to GitHub.\n\n- ``#pylib`` on irc.freenode.net IRC channel for random questions.\n\n- private mail to Holger.Krekel at gmail com if you want to communicate sensitive issues\n\n\n- `merlinux.eu`_ offers pytest and tox-related professional teaching and\n consulting.\n\n.. _`pytest issue tracker`: https://github.com/pytest-dev/pytest/issues\n.. _`old issue tracker`: http://bitbucket.org/hpk42/py-trunk/issues/\n\n.. _`merlinux.eu`: http://merlinux.eu\n\n.. _`get an account`:\n\n.. _tetamap: http://tetamap.wordpress.com\n\n.. _`@pylibcommit`: http://twitter.com/pylibcommit\n\n\n.. _`Testing in Python`: http://lists.idyll.org/listinfo/testing-in-python\n.. _FOAF: http://en.wikipedia.org/wiki/FOAF\n.. _`py-dev`:\n.. _`development mailing list`:\n.. _`pytest-dev at python.org (mailing list)`: http://mail.python.org/mailman/listinfo/pytest-dev\n.. _`pytest-commit at python.org (mailing list)`: http://mail.python.org/mailman/listinfo/pytest-commit\n"},{"fileName":"test_basic.py","filePath":"testing/example_scripts/collect/package_infinite_recursion/tests","id":5215,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ndef test():\n pass\n"},{"col":0,"comment":"null","endLoc":3,"header":"def test()","id":5216,"name":"test","nodeType":"Function","startLoc":2,"text":"def test():\n pass"},{"fileName":"test_pastebin.py","filePath":"testing","id":5217,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\n\nimport pytest\n\n\nclass TestPasteCapture(object):\n @pytest.fixture\n def pastebinlist(self, monkeypatch, request):\n pastebinlist = []\n plugin = request.config.pluginmanager.getplugin(\"pastebin\")\n monkeypatch.setattr(plugin, \"create_new_paste\", pastebinlist.append)\n return pastebinlist\n\n def test_failed(self, testdir, pastebinlist):\n testpath = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_pass():\n pass\n def test_fail():\n assert 0\n def test_skip():\n pytest.skip(\"\")\n \"\"\"\n )\n reprec = testdir.inline_run(testpath, \"--paste=failed\")\n assert len(pastebinlist) == 1\n s = pastebinlist[0]\n assert s.find(\"def test_fail\") != -1\n assert reprec.countoutcomes() == [1, 1, 1]\n\n def test_all(self, testdir, pastebinlist):\n from _pytest.pytester import LineMatcher\n\n testpath = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_pass():\n pass\n def test_fail():\n assert 0\n def test_skip():\n pytest.skip(\"\")\n \"\"\"\n )\n reprec = testdir.inline_run(testpath, \"--pastebin=all\", \"-v\")\n assert reprec.countoutcomes() == [1, 1, 1]\n assert len(pastebinlist) == 1\n contents = pastebinlist[0].decode(\"utf-8\")\n matcher = LineMatcher(contents.splitlines())\n matcher.fnmatch_lines(\n [\n \"*test_pass PASSED*\",\n \"*test_fail FAILED*\",\n \"*test_skip SKIPPED*\",\n \"*== 1 failed, 1 passed, 1 skipped in *\",\n ]\n )\n\n def test_non_ascii_paste_text(self, testdir):\n \"\"\"Make sure that text which contains non-ascii characters is pasted\n correctly. See #1219.\n \"\"\"\n testdir.makepyfile(\n test_unicode=\"\"\"\n # -*- coding: utf-8 -*-\n def test():\n assert '☺' == 1\n \"\"\"\n )\n result = testdir.runpytest(\"--pastebin=all\")\n if sys.version_info[0] >= 3:\n expected_msg = \"*assert '☺' == 1*\"\n else:\n expected_msg = \"*assert '\\\\xe2\\\\x98\\\\xba' == 1*\"\n result.stdout.fnmatch_lines(\n [\n expected_msg,\n \"*== 1 failed in *\",\n \"*Sending information to Paste Service*\",\n ]\n )\n\n\nclass TestPaste(object):\n @pytest.fixture\n def pastebin(self, request):\n return request.config.pluginmanager.getplugin(\"pastebin\")\n\n @pytest.fixture\n def mocked_urlopen(self, monkeypatch):\n \"\"\"\n monkeypatch the actual urlopen calls done by the internal plugin\n function that connects to bpaste service.\n \"\"\"\n calls = []\n\n def mocked(url, data):\n calls.append((url, data))\n\n class DummyFile(object):\n def read(self):\n # part of html of a normal response\n return b'View raw.'\n\n return DummyFile()\n\n if sys.version_info < (3, 0):\n import urllib\n\n monkeypatch.setattr(urllib, \"urlopen\", mocked)\n else:\n import urllib.request\n\n monkeypatch.setattr(urllib.request, \"urlopen\", mocked)\n return calls\n\n def test_create_new_paste(self, pastebin, mocked_urlopen):\n result = pastebin.create_new_paste(b\"full-paste-contents\")\n assert result == \"https://bpaste.net/show/3c0c6750bd\"\n assert len(mocked_urlopen) == 1\n url, data = mocked_urlopen[0]\n assert type(data) is bytes\n lexer = \"python3\" if sys.version_info[0] >= 3 else \"python\"\n assert url == \"https://bpaste.net\"\n assert \"lexer=%s\" % lexer in data.decode()\n assert \"code=full-paste-contents\" in data.decode()\n assert \"expiry=1week\" in data.decode()\n"},{"className":"TestPasteCapture","col":0,"comment":"null","endLoc":87,"id":5218,"nodeType":"Class","startLoc":11,"text":"class TestPasteCapture(object):\n @pytest.fixture\n def pastebinlist(self, monkeypatch, request):\n pastebinlist = []\n plugin = request.config.pluginmanager.getplugin(\"pastebin\")\n monkeypatch.setattr(plugin, \"create_new_paste\", pastebinlist.append)\n return pastebinlist\n\n def test_failed(self, testdir, pastebinlist):\n testpath = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_pass():\n pass\n def test_fail():\n assert 0\n def test_skip():\n pytest.skip(\"\")\n \"\"\"\n )\n reprec = testdir.inline_run(testpath, \"--paste=failed\")\n assert len(pastebinlist) == 1\n s = pastebinlist[0]\n assert s.find(\"def test_fail\") != -1\n assert reprec.countoutcomes() == [1, 1, 1]\n\n def test_all(self, testdir, pastebinlist):\n from _pytest.pytester import LineMatcher\n\n testpath = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_pass():\n pass\n def test_fail():\n assert 0\n def test_skip():\n pytest.skip(\"\")\n \"\"\"\n )\n reprec = testdir.inline_run(testpath, \"--pastebin=all\", \"-v\")\n assert reprec.countoutcomes() == [1, 1, 1]\n assert len(pastebinlist) == 1\n contents = pastebinlist[0].decode(\"utf-8\")\n matcher = LineMatcher(contents.splitlines())\n matcher.fnmatch_lines(\n [\n \"*test_pass PASSED*\",\n \"*test_fail FAILED*\",\n \"*test_skip SKIPPED*\",\n \"*== 1 failed, 1 passed, 1 skipped in *\",\n ]\n )\n\n def test_non_ascii_paste_text(self, testdir):\n \"\"\"Make sure that text which contains non-ascii characters is pasted\n correctly. See #1219.\n \"\"\"\n testdir.makepyfile(\n test_unicode=\"\"\"\n # -*- coding: utf-8 -*-\n def test():\n assert '☺' == 1\n \"\"\"\n )\n result = testdir.runpytest(\"--pastebin=all\")\n if sys.version_info[0] >= 3:\n expected_msg = \"*assert '☺' == 1*\"\n else:\n expected_msg = \"*assert '\\\\xe2\\\\x98\\\\xba' == 1*\"\n result.stdout.fnmatch_lines(\n [\n expected_msg,\n \"*== 1 failed in *\",\n \"*Sending information to Paste Service*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":17,"header":"@pytest.fixture\n def pastebinlist(self, monkeypatch, request)","id":5219,"name":"pastebinlist","nodeType":"Function","startLoc":12,"text":"@pytest.fixture\n def pastebinlist(self, monkeypatch, request):\n pastebinlist = []\n plugin = request.config.pluginmanager.getplugin(\"pastebin\")\n monkeypatch.setattr(plugin, \"create_new_paste\", pastebinlist.append)\n return pastebinlist"},{"col":4,"comment":"null","endLoc":795,"header":"def summary_warnings(self)","id":5220,"name":"summary_warnings","nodeType":"Function","startLoc":759,"text":"def summary_warnings(self):\n if self.hasopt(\"w\"):\n all_warnings = self.stats.get(\"warnings\")\n if not all_warnings:\n return\n\n final = hasattr(self, \"_already_displayed_warnings\")\n if final:\n warning_reports = all_warnings[self._already_displayed_warnings :]\n else:\n warning_reports = all_warnings\n self._already_displayed_warnings = len(warning_reports)\n if not warning_reports:\n return\n\n reports_grouped_by_message = collections.OrderedDict()\n for wr in warning_reports:\n reports_grouped_by_message.setdefault(wr.message, []).append(wr)\n\n title = \"warnings summary (final)\" if final else \"warnings summary\"\n self.write_sep(\"=\", title, yellow=True, bold=False)\n for message, warning_reports in reports_grouped_by_message.items():\n has_any_location = False\n for w in warning_reports:\n location = w.get_location(self.config)\n if location:\n self._tw.line(str(location))\n has_any_location = True\n if has_any_location:\n lines = message.splitlines()\n indented = \"\\n\".join(\" \" + x for x in lines)\n message = indented.rstrip()\n else:\n message = message.rstrip()\n self._tw.line(message)\n self._tw.line()\n self._tw.line(\"-- Docs: https://docs.pytest.org/en/latest/warnings.html\")"},{"col":4,"comment":"null","endLoc":808,"header":"def summary_passes(self)","id":5221,"name":"summary_passes","nodeType":"Function","startLoc":797,"text":"def summary_passes(self):\n if self.config.option.tbstyle != \"no\":\n if self.hasopt(\"P\"):\n reports = self.getreports(\"passed\")\n if not reports:\n return\n self.write_sep(\"=\", \"PASSES\")\n for rep in reports:\n if rep.sections:\n msg = self._getfailureheadline(rep)\n self.write_sep(\"_\", msg, green=True, bold=True)\n self._outrep_summary(rep)"},{"col":4,"comment":"null","endLoc":954,"header":"def short_test_summary(self)","id":5222,"name":"short_test_summary","nodeType":"Function","startLoc":885,"text":"def short_test_summary(self):\n if not self.reportchars:\n return\n\n def show_simple(stat, lines):\n failed = self.stats.get(stat, [])\n if not failed:\n return\n termwidth = self.writer.fullwidth\n config = self.config\n for rep in failed:\n line = _get_line_with_reprcrash_message(config, rep, termwidth)\n lines.append(line)\n\n def show_xfailed(lines):\n xfailed = self.stats.get(\"xfailed\", [])\n for rep in xfailed:\n verbose_word = rep._get_verbose_word(self.config)\n pos = _get_pos(self.config, rep)\n lines.append(\"%s %s\" % (verbose_word, pos))\n reason = rep.wasxfail\n if reason:\n lines.append(\" \" + str(reason))\n\n def show_xpassed(lines):\n xpassed = self.stats.get(\"xpassed\", [])\n for rep in xpassed:\n verbose_word = rep._get_verbose_word(self.config)\n pos = _get_pos(self.config, rep)\n reason = rep.wasxfail\n lines.append(\"%s %s %s\" % (verbose_word, pos, reason))\n\n def show_skipped(lines):\n skipped = self.stats.get(\"skipped\", [])\n fskips = _folded_skips(skipped) if skipped else []\n if not fskips:\n return\n verbose_word = skipped[0]._get_verbose_word(self.config)\n for num, fspath, lineno, reason in fskips:\n if reason.startswith(\"Skipped: \"):\n reason = reason[9:]\n if lineno is not None:\n lines.append(\n \"%s [%d] %s:%d: %s\"\n % (verbose_word, num, fspath, lineno + 1, reason)\n )\n else:\n lines.append(\"%s [%d] %s: %s\" % (verbose_word, num, fspath, reason))\n\n REPORTCHAR_ACTIONS = {\n \"x\": show_xfailed,\n \"X\": show_xpassed,\n \"f\": partial(show_simple, \"failed\"),\n \"F\": partial(show_simple, \"failed\"),\n \"s\": show_skipped,\n \"S\": show_skipped,\n \"p\": partial(show_simple, \"passed\"),\n \"E\": partial(show_simple, \"error\"),\n }\n\n lines = []\n for char in self.reportchars:\n action = REPORTCHAR_ACTIONS.get(char)\n if action: # skipping e.g. \"P\" (passed with output) here.\n action(lines)\n\n if lines:\n self.write_sep(\"=\", \"short test summary info\")\n for line in lines:\n self.write_line(line)"},{"col":0,"comment":"Get summary line for a report, trying to add reprcrash message.","endLoc":1012,"header":"def _get_line_with_reprcrash_message(config, rep, termwidth)","id":5223,"name":"_get_line_with_reprcrash_message","nodeType":"Function","startLoc":962,"text":"def _get_line_with_reprcrash_message(config, rep, termwidth):\n \"\"\"Get summary line for a report, trying to add reprcrash message.\"\"\"\n from wcwidth import wcswidth\n\n verbose_word = rep._get_verbose_word(config)\n pos = _get_pos(config, rep)\n\n line = \"%s %s\" % (verbose_word, pos)\n len_line = wcswidth(line)\n ellipsis, len_ellipsis = \"...\", 3\n if len_line > termwidth - len_ellipsis:\n # No space for an additional message.\n return line\n\n try:\n msg = rep.longrepr.reprcrash.message\n except AttributeError:\n pass\n else:\n # Only use the first line.\n i = msg.find(\"\\n\")\n if i != -1:\n msg = msg[:i]\n len_msg = wcswidth(msg)\n\n sep, len_sep = \" - \", 3\n max_len_msg = termwidth - len_line - len_sep\n if max_len_msg >= len_ellipsis:\n if len_msg > max_len_msg:\n max_len_msg -= len_ellipsis\n msg = msg[:max_len_msg]\n while wcswidth(msg) > max_len_msg:\n msg = msg[:-1]\n if six.PY2:\n # on python 2 systems with narrow unicode compilation, trying to\n # get a single character out of a multi-byte unicode character such as\n # u'😄' will result in a High Surrogate (U+D83D) character, which is\n # rendered as u'�'; in this case we just strip that character out as it\n # serves no purpose being rendered\n try:\n surrogate = six.unichr(0xD83D)\n msg = msg.rstrip(surrogate)\n except ValueError: # pragma: no cover\n # Jython cannot represent this lone surrogate at all (#5256):\n # ValueError: unichr() arg is a lone surrogate in range\n # (0xD800, 0xDFFF) (Jython UTF-16 encoding)\n # ignore this case as it shouldn't appear in the string anyway\n pass\n msg += ellipsis\n line += sep + msg\n return line"},{"col":0,"comment":"null","endLoc":959,"header":"def _get_pos(config, rep)","id":5224,"name":"_get_pos","nodeType":"Function","startLoc":957,"text":"def _get_pos(config, rep):\n nodeid = config.cwd_relative_nodeid(rep.nodeid)\n return nodeid"},{"col":4,"comment":"null","endLoc":1052,"header":"def test_simple_resume_suspend(self, tmpfile)","id":5227,"name":"test_simple_resume_suspend","nodeType":"Function","startLoc":1032,"text":"def test_simple_resume_suspend(self, tmpfile):\n with saved_fd(1):\n cap = capture.FDCapture(1)\n cap.start()\n data = b\"hello\"\n os.write(1, data)\n sys.stdout.write(\"whatever\")\n s = cap.snap()\n assert s == \"hellowhatever\"\n cap.suspend()\n os.write(1, b\"world\")\n sys.stdout.write(\"qlwkej\")\n assert not cap.snap()\n cap.resume()\n os.write(1, b\"but now\")\n sys.stdout.write(\" yes\\n\")\n s = cap.snap()\n assert s == \"but now yes\\n\"\n cap.suspend()\n cap.done()\n pytest.raises(AttributeError, cap.suspend)"},{"fileName":"pastebin.py","filePath":"src/_pytest","id":5232,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\" submit failure or test session information to a pastebin service. \"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nimport tempfile\n\nimport six\n\nimport pytest\n\n\ndef pytest_addoption(parser):\n group = parser.getgroup(\"terminal reporting\")\n group._addoption(\n \"--pastebin\",\n metavar=\"mode\",\n action=\"store\",\n dest=\"pastebin\",\n default=None,\n choices=[\"failed\", \"all\"],\n help=\"send failed|all info to bpaste.net pastebin service.\",\n )\n\n\n@pytest.hookimpl(trylast=True)\ndef pytest_configure(config):\n if config.option.pastebin == \"all\":\n tr = config.pluginmanager.getplugin(\"terminalreporter\")\n # if no terminal reporter plugin is present, nothing we can do here;\n # this can happen when this function executes in a slave node\n # when using pytest-xdist, for example\n if tr is not None:\n # pastebin file will be utf-8 encoded binary file\n config._pastebinfile = tempfile.TemporaryFile(\"w+b\")\n oldwrite = tr._tw.write\n\n def tee_write(s, **kwargs):\n oldwrite(s, **kwargs)\n if isinstance(s, six.text_type):\n s = s.encode(\"utf-8\")\n config._pastebinfile.write(s)\n\n tr._tw.write = tee_write\n\n\ndef pytest_unconfigure(config):\n if hasattr(config, \"_pastebinfile\"):\n # get terminal contents and delete file\n config._pastebinfile.seek(0)\n sessionlog = config._pastebinfile.read()\n config._pastebinfile.close()\n del config._pastebinfile\n # undo our patching in the terminal reporter\n tr = config.pluginmanager.getplugin(\"terminalreporter\")\n del tr._tw.__dict__[\"write\"]\n # write summary\n tr.write_sep(\"=\", \"Sending information to Paste Service\")\n pastebinurl = create_new_paste(sessionlog)\n tr.write_line(\"pastebin session-log: %s\\n\" % pastebinurl)\n\n\ndef create_new_paste(contents):\n \"\"\"\n Creates a new paste using bpaste.net service.\n\n :contents: paste contents as utf-8 encoded bytes\n :returns: url to the pasted contents\n \"\"\"\n import re\n\n if sys.version_info < (3, 0):\n from urllib import urlopen, urlencode\n else:\n from urllib.request import urlopen\n from urllib.parse import urlencode\n\n params = {\n \"code\": contents,\n \"lexer\": \"python3\" if sys.version_info[0] >= 3 else \"python\",\n \"expiry\": \"1week\",\n }\n url = \"https://bpaste.net\"\n response = urlopen(url, data=urlencode(params).encode(\"ascii\")).read()\n m = re.search(r'href=\"/raw/(\\w+)\"', response.decode(\"utf-8\"))\n if m:\n return \"%s/show/%s\" % (url, m.group(1))\n else:\n return \"bad response: \" + response\n\n\ndef pytest_terminal_summary(terminalreporter):\n import _pytest.config\n\n if terminalreporter.config.option.pastebin != \"failed\":\n return\n tr = terminalreporter\n if \"failed\" in tr.stats:\n terminalreporter.write_sep(\"=\", \"Sending information to Paste Service\")\n for rep in terminalreporter.stats.get(\"failed\"):\n try:\n msg = rep.longrepr.reprtraceback.reprentries[-1].reprfileloc\n except AttributeError:\n msg = tr._getfailureheadline(rep)\n tw = _pytest.config.create_terminal_writer(\n terminalreporter.config, stringio=True\n )\n rep.toterminal(tw)\n s = tw.stringio.getvalue()\n assert len(s)\n pastebinurl = create_new_paste(s)\n tr.write_line(\"%s --> %s\" % (msg, pastebinurl))\n"},{"col":0,"comment":"null","endLoc":1243,"header":"def test_url_property(testdir)","id":5235,"name":"test_url_property","nodeType":"Function","startLoc":1220,"text":"def test_url_property(testdir):\n test_url = \"http://www.github.com/pytest-dev\"\n path = testdir.tmpdir.join(\"test_url_property.xml\")\n log = LogXML(str(path), None)\n\n class Report(BaseReport):\n longrepr = \"FooBarBaz\"\n sections = []\n nodeid = \"something\"\n location = \"tests/filename.py\", 42, \"TestClass.method\"\n url = test_url\n\n test_report = Report()\n\n log.pytest_sessionstart()\n node_reporter = log._opentestcase(test_report)\n node_reporter.append_failure(test_report)\n log.pytest_sessionfinish()\n\n test_case = minidom.parse(str(path)).getElementsByTagName(\"testcase\")[0]\n\n assert (\n test_case.getAttribute(\"url\") == test_url\n ), \"The URL did not get written to the xml\""},{"col":0,"comment":"null","endLoc":25,"header":"def pytest_addoption(parser)","id":5236,"name":"pytest_addoption","nodeType":"Function","startLoc":15,"text":"def pytest_addoption(parser):\n group = parser.getgroup(\"terminal reporting\")\n group._addoption(\n \"--pastebin\",\n metavar=\"mode\",\n action=\"store\",\n dest=\"pastebin\",\n default=None,\n choices=[\"failed\", \"all\"],\n help=\"send failed|all info to bpaste.net pastebin service.\",\n )"},{"col":0,"comment":"null","endLoc":46,"header":"@pytest.hookimpl(trylast=True)\ndef pytest_configure(config)","id":5237,"name":"pytest_configure","nodeType":"Function","startLoc":28,"text":"@pytest.hookimpl(trylast=True)\ndef pytest_configure(config):\n if config.option.pastebin == \"all\":\n tr = config.pluginmanager.getplugin(\"terminalreporter\")\n # if no terminal reporter plugin is present, nothing we can do here;\n # this can happen when this function executes in a slave node\n # when using pytest-xdist, for example\n if tr is not None:\n # pastebin file will be utf-8 encoded binary file\n config._pastebinfile = tempfile.TemporaryFile(\"w+b\")\n oldwrite = tr._tw.write\n\n def tee_write(s, **kwargs):\n oldwrite(s, **kwargs)\n if isinstance(s, six.text_type):\n s = s.encode(\"utf-8\")\n config._pastebinfile.write(s)\n\n tr._tw.write = tee_write"},{"col":0,"comment":"null","endLoc":1263,"header":"def test_record_testsuite_property(testdir)","id":5238,"name":"test_record_testsuite_property","nodeType":"Function","startLoc":1246,"text":"def test_record_testsuite_property(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_func1(record_testsuite_property):\n record_testsuite_property(\"stats\", \"all good\")\n\n def test_func2(record_testsuite_property):\n record_testsuite_property(\"stats\", 10)\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testsuite\")\n properties_node = node.find_first_by_tag(\"properties\")\n p1_node = properties_node.find_nth_by_tag(\"property\", 0)\n p2_node = properties_node.find_nth_by_tag(\"property\", 1)\n p1_node.assert_attr(name=\"stats\", value=\"all good\")\n p2_node.assert_attr(name=\"stats\", value=\"10\")"},{"col":4,"comment":"null","endLoc":1055,"header":"def test_capfd_sys_stdout_mode(self, capfd)","id":5239,"name":"test_capfd_sys_stdout_mode","nodeType":"Function","startLoc":1054,"text":"def test_capfd_sys_stdout_mode(self, capfd):\n assert \"b\" not in sys.stdout.mode"},{"attributeType":"null","col":4,"comment":"null","endLoc":971,"id":5240,"name":"pytestmark","nodeType":"Attribute","startLoc":971,"text":"pytestmark"},{"className":"TestStdCapture","col":0,"comment":"null","endLoc":1193,"id":5241,"nodeType":"Class","startLoc":1068,"text":"class TestStdCapture(object):\n captureclass = staticmethod(StdCapture)\n\n @contextlib.contextmanager\n def getcapture(self, **kw):\n cap = self.__class__.captureclass(**kw)\n cap.start_capturing()\n try:\n yield cap\n finally:\n cap.stop_capturing()\n\n def test_capturing_done_simple(self):\n with self.getcapture() as cap:\n sys.stdout.write(\"hello\")\n sys.stderr.write(\"world\")\n out, err = cap.readouterr()\n assert out == \"hello\"\n assert err == \"world\"\n\n def test_capturing_reset_simple(self):\n with self.getcapture() as cap:\n print(\"hello world\")\n sys.stderr.write(\"hello error\\n\")\n out, err = cap.readouterr()\n assert out == \"hello world\\n\"\n assert err == \"hello error\\n\"\n\n def test_capturing_readouterr(self):\n with self.getcapture() as cap:\n print(\"hello world\")\n sys.stderr.write(\"hello error\\n\")\n out, err = cap.readouterr()\n assert out == \"hello world\\n\"\n assert err == \"hello error\\n\"\n sys.stderr.write(\"error2\")\n out, err = cap.readouterr()\n assert err == \"error2\"\n\n def test_capture_results_accessible_by_attribute(self):\n with self.getcapture() as cap:\n sys.stdout.write(\"hello\")\n sys.stderr.write(\"world\")\n capture_result = cap.readouterr()\n assert capture_result.out == \"hello\"\n assert capture_result.err == \"world\"\n\n def test_capturing_readouterr_unicode(self):\n with self.getcapture() as cap:\n print(\"hxąć\")\n out, err = cap.readouterr()\n assert out == u\"hxąć\\n\"\n\n @pytest.mark.skipif(\n \"sys.version_info >= (3,)\", reason=\"text output different for bytes on python3\"\n )\n def test_capturing_readouterr_decode_error_handling(self):\n with self.getcapture() as cap:\n # triggered an internal error in pytest\n print(\"\\xa6\")\n out, err = cap.readouterr()\n assert out == u\"\\ufffd\\n\"\n\n def test_reset_twice_error(self):\n with self.getcapture() as cap:\n print(\"hello\")\n out, err = cap.readouterr()\n pytest.raises(ValueError, cap.stop_capturing)\n assert out == \"hello\\n\"\n assert not err\n\n def test_capturing_modify_sysouterr_in_between(self):\n oldout = sys.stdout\n olderr = sys.stderr\n with self.getcapture() as cap:\n sys.stdout.write(\"hello\")\n sys.stderr.write(\"world\")\n sys.stdout = capture.CaptureIO()\n sys.stderr = capture.CaptureIO()\n print(\"not seen\")\n sys.stderr.write(\"not seen\\n\")\n out, err = cap.readouterr()\n assert out == \"hello\"\n assert err == \"world\"\n assert sys.stdout == oldout\n assert sys.stderr == olderr\n\n def test_capturing_error_recursive(self):\n with self.getcapture() as cap1:\n print(\"cap1\")\n with self.getcapture() as cap2:\n print(\"cap2\")\n out2, err2 = cap2.readouterr()\n out1, err1 = cap1.readouterr()\n assert out1 == \"cap1\\n\"\n assert out2 == \"cap2\\n\"\n\n def test_just_out_capture(self):\n with self.getcapture(out=True, err=False) as cap:\n sys.stdout.write(\"hello\")\n sys.stderr.write(\"world\")\n out, err = cap.readouterr()\n assert out == \"hello\"\n assert not err\n\n def test_just_err_capture(self):\n with self.getcapture(out=False, err=True) as cap:\n sys.stdout.write(\"hello\")\n sys.stderr.write(\"world\")\n out, err = cap.readouterr()\n assert err == \"world\"\n assert not out\n\n def test_stdin_restored(self):\n old = sys.stdin\n with self.getcapture(in_=True):\n newstdin = sys.stdin\n assert newstdin != sys.stdin\n assert sys.stdin is old\n\n def test_stdin_nulled_by_default(self):\n print(\"XXX this test may well hang instead of crashing\")\n print(\"XXX which indicates an error in the underlying capturing\")\n print(\"XXX mechanisms\")\n with self.getcapture():\n pytest.raises(IOError, sys.stdin.read)"},{"col":4,"comment":"null","endLoc":1078,"header":"@contextlib.contextmanager\n def getcapture(self, **kw)","id":5242,"name":"getcapture","nodeType":"Function","startLoc":1071,"text":"@contextlib.contextmanager\n def getcapture(self, **kw):\n cap = self.__class__.captureclass(**kw)\n cap.start_capturing()\n try:\n yield cap\n finally:\n cap.stop_capturing()"},{"col":0,"comment":"null","endLoc":1274,"header":"def test_record_testsuite_property_junit_disabled(testdir)","id":5243,"name":"test_record_testsuite_property_junit_disabled","nodeType":"Function","startLoc":1266,"text":"def test_record_testsuite_property_junit_disabled(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_func1(record_testsuite_property):\n record_testsuite_property(\"stats\", \"all good\")\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0"},{"col":0,"comment":"null","endLoc":1290,"header":"@pytest.mark.parametrize(\"junit\", [True, False])\ndef test_record_testsuite_property_type_checking(testdir, junit)","id":5244,"name":"test_record_testsuite_property_type_checking","nodeType":"Function","startLoc":1277,"text":"@pytest.mark.parametrize(\"junit\", [True, False])\ndef test_record_testsuite_property_type_checking(testdir, junit):\n testdir.makepyfile(\n \"\"\"\n def test_func1(record_testsuite_property):\n record_testsuite_property(1, 2)\n \"\"\"\n )\n args = (\"--junitxml=tests.xml\",) if junit else ()\n result = testdir.runpytest(*args)\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\"*TypeError: name parameter needs to be a string, but int given\"]\n )"},{"col":0,"comment":"null","endLoc":1318,"header":"@pytest.mark.parametrize(\"suite_name\", [\"my_suite\", \"\"])\ndef test_set_suite_name(testdir, suite_name)","id":5245,"name":"test_set_suite_name","nodeType":"Function","startLoc":1293,"text":"@pytest.mark.parametrize(\"suite_name\", [\"my_suite\", \"\"])\ndef test_set_suite_name(testdir, suite_name):\n if suite_name:\n testdir.makeini(\n \"\"\"\n [pytest]\n junit_suite_name={}\n \"\"\".format(\n suite_name\n )\n )\n expected = suite_name\n else:\n expected = \"pytest\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n def test_func():\n pass\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testsuite\")\n node.assert_attr(name=expected)"},{"col":0,"comment":"null","endLoc":1334,"header":"def test_escaped_skipreason_issue3533(testdir)","id":5246,"name":"test_escaped_skipreason_issue3533","nodeType":"Function","startLoc":1321,"text":"def test_escaped_skipreason_issue3533(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip(reason='1 <> 2')\n def test_skip():\n pass\n \"\"\"\n )\n _, dom = runandparse(testdir)\n node = dom.find_first_by_tag(\"testcase\")\n snode = node.find_first_by_tag(\"skipped\")\n assert \"1 <> 2\" in snode.text\n snode.assert_attr(message=\"1 <> 2\")"},{"col":0,"comment":"null","endLoc":1361,"header":"def test_logging_passing_tests_disabled_does_not_log_test_output(testdir)","id":5247,"name":"test_logging_passing_tests_disabled_does_not_log_test_output","nodeType":"Function","startLoc":1337,"text":"def test_logging_passing_tests_disabled_does_not_log_test_output(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n junit_log_passing_tests=False\n junit_logging=system-out\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n import sys\n\n def test_func():\n sys.stdout.write('This is stdout')\n sys.stderr.write('This is stderr')\n logging.warning('hello')\n \"\"\"\n )\n result, dom = runandparse(testdir)\n assert result.ret == 0\n node = dom.find_first_by_tag(\"testcase\")\n assert len(node.find_by_tag(\"system-err\")) == 0\n assert len(node.find_by_tag(\"system-out\")) == 0"},{"col":4,"comment":"null","endLoc":1086,"header":"def test_capturing_done_simple(self)","id":5248,"name":"test_capturing_done_simple","nodeType":"Function","startLoc":1080,"text":"def test_capturing_done_simple(self):\n with self.getcapture() as cap:\n sys.stdout.write(\"hello\")\n sys.stderr.write(\"world\")\n out, err = cap.readouterr()\n assert out == \"hello\"\n assert err == \"world\""},{"id":5249,"name":"release-4.0.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-4.0.1\n=======================================\n\npytest 4.0.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Michael D. Hoyle\n* Ronny Pfannschmidt\n* Slam\n\n\nHappy testing,\nThe pytest Development Team\n"},{"fileName":"xfail_demo.py","filePath":"doc/en/example","id":5250,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\nxfail = pytest.mark.xfail\n\n\n@xfail\ndef test_hello():\n assert 0\n\n\n@xfail(run=False)\ndef test_hello2():\n assert 0\n\n\n@xfail(\"hasattr(os, 'sep')\")\ndef test_hello3():\n assert 0\n\n\n@xfail(reason=\"bug 110\")\ndef test_hello4():\n assert 0\n\n\n@xfail('pytest.__version__[0] != \"17\"')\ndef test_hello5():\n assert 0\n\n\ndef test_hello6():\n pytest.xfail(\"reason\")\n\n\n@xfail(raises=IndexError)\ndef test_hello7():\n x = []\n x[1] = 1\n"},{"col":0,"comment":"null","endLoc":9,"header":"@xfail\ndef test_hello()","id":5251,"name":"test_hello","nodeType":"Function","startLoc":7,"text":"@xfail\ndef test_hello():\n assert 0"},{"col":0,"comment":"null","endLoc":14,"header":"@xfail(run=False)\ndef test_hello2()","id":5252,"name":"test_hello2","nodeType":"Function","startLoc":12,"text":"@xfail(run=False)\ndef test_hello2():\n assert 0"},{"col":0,"comment":"null","endLoc":19,"header":"@xfail(\"hasattr(os, 'sep')\")\ndef test_hello3()","id":5253,"name":"test_hello3","nodeType":"Function","startLoc":17,"text":"@xfail(\"hasattr(os, 'sep')\")\ndef test_hello3():\n assert 0"},{"col":0,"comment":"null","endLoc":24,"header":"@xfail(reason=\"bug 110\")\ndef test_hello4()","id":5254,"name":"test_hello4","nodeType":"Function","startLoc":22,"text":"@xfail(reason=\"bug 110\")\ndef test_hello4():\n assert 0"},{"col":0,"comment":"null","endLoc":29,"header":"@xfail('pytest.__version__[0] != \"17\"')\ndef test_hello5()","id":5255,"name":"test_hello5","nodeType":"Function","startLoc":27,"text":"@xfail('pytest.__version__[0] != \"17\"')\ndef test_hello5():\n assert 0"},{"col":0,"comment":"null","endLoc":33,"header":"def test_hello6()","id":5256,"name":"test_hello6","nodeType":"Function","startLoc":32,"text":"def test_hello6():\n pytest.xfail(\"reason\")"},{"col":0,"comment":"null","endLoc":39,"header":"@xfail(raises=IndexError)\ndef test_hello7()","id":5257,"name":"test_hello7","nodeType":"Function","startLoc":36,"text":"@xfail(raises=IndexError)\ndef test_hello7():\n x = []\n x[1] = 1"},{"attributeType":"null","col":0,"comment":"null","endLoc":4,"id":5258,"name":"xfail","nodeType":"Attribute","startLoc":4,"text":"xfail"},{"col":0,"comment":"","endLoc":2,"header":"xfail_demo.py#","id":5259,"name":"","nodeType":"Function","startLoc":2,"text":"xfail = pytest.mark.xfail"},{"fileName":"pythoncollection.py","filePath":"doc/en/example","id":5260,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n# run this with $ pytest --collect-only test_collectonly.py\n#\n\n\ndef test_function():\n pass\n\n\nclass TestClass(object):\n def test_method(self):\n pass\n\n def test_anothermethod(self):\n pass\n"},{"className":"TestClass","col":0,"comment":"null","endLoc":15,"id":5261,"nodeType":"Class","startLoc":10,"text":"class TestClass(object):\n def test_method(self):\n pass\n\n def test_anothermethod(self):\n pass"},{"col":4,"comment":"null","endLoc":12,"header":"def test_method(self)","id":5262,"name":"test_method","nodeType":"Function","startLoc":11,"text":"def test_method(self):\n pass"},{"col":4,"comment":"null","endLoc":15,"header":"def test_anothermethod(self)","id":5263,"name":"test_anothermethod","nodeType":"Function","startLoc":14,"text":"def test_anothermethod(self):\n pass"},{"col":0,"comment":"null","endLoc":7,"header":"def test_function()","id":5264,"name":"test_function","nodeType":"Function","startLoc":6,"text":"def test_function():\n pass"},{"id":5265,"name":"assert.rst","nodeType":"TextFile","path":"doc/en","text":"\nThe writing and reporting of assertions in tests\n==================================================\n\n.. _`assertfeedback`:\n.. _`assert with the assert statement`:\n.. _`assert`:\n\n\nAsserting with the ``assert`` statement\n---------------------------------------------------------\n\n``pytest`` allows you to use the standard python ``assert`` for verifying\nexpectations and values in Python tests. For example, you can write the\nfollowing:\n\n.. code-block:: python\n\n # content of test_assert1.py\n def f():\n return 3\n\n\n def test_function():\n assert f() == 4\n\nto assert that your function returns a certain value. If this assertion fails\nyou will see the return value of the function call:\n\n.. code-block:: pytest\n\n $ pytest test_assert1.py\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 1 item\n\n test_assert1.py F [100%]\n\n ================================= FAILURES =================================\n ______________________________ test_function _______________________________\n\n def test_function():\n > assert f() == 4\n E assert 3 == 4\n E + where 3 = f()\n\n test_assert1.py:6: AssertionError\n ========================= 1 failed in 0.12 seconds =========================\n\n``pytest`` has support for showing the values of the most common subexpressions\nincluding calls, attributes, comparisons, and binary and unary\noperators. (See :ref:`tbreportdemo`). This allows you to use the\nidiomatic python constructs without boilerplate code while not losing\nintrospection information.\n\nHowever, if you specify a message with the assertion like this:\n\n.. code-block:: python\n\n assert a % 2 == 0, \"value was odd, should be even\"\n\nthen no assertion introspection takes places at all and the message\nwill be simply shown in the traceback.\n\nSee :ref:`assert-details` for more information on assertion introspection.\n\n.. _`assertraises`:\n\nAssertions about expected exceptions\n------------------------------------------\n\nIn order to write assertions about raised exceptions, you can use\n``pytest.raises`` as a context manager like this:\n\n.. code-block:: python\n\n import pytest\n\n\n def test_zero_division():\n with pytest.raises(ZeroDivisionError):\n 1 / 0\n\nand if you need to have access to the actual exception info you may use:\n\n.. code-block:: python\n\n def test_recursion_depth():\n with pytest.raises(RuntimeError) as excinfo:\n\n def f():\n f()\n\n f()\n assert \"maximum recursion\" in str(excinfo.value)\n\n``excinfo`` is a ``ExceptionInfo`` instance, which is a wrapper around\nthe actual exception raised. The main attributes of interest are\n``.type``, ``.value`` and ``.traceback``.\n\nYou can pass a ``match`` keyword parameter to the context-manager to test\nthat a regular expression matches on the string representation of an exception\n(similar to the ``TestCase.assertRaisesRegexp`` method from ``unittest``):\n\n.. code-block:: python\n\n import pytest\n\n\n def myfunc():\n raise ValueError(\"Exception 123 raised\")\n\n\n def test_match():\n with pytest.raises(ValueError, match=r\".* 123 .*\"):\n myfunc()\n\nThe regexp parameter of the ``match`` method is matched with the ``re.search``\nfunction, so in the above example ``match='123'`` would have worked as\nwell.\n\nThere's an alternate form of the ``pytest.raises`` function where you pass\na function that will be executed with the given ``*args`` and ``**kwargs`` and\nassert that the given exception is raised:\n\n.. code-block:: python\n\n pytest.raises(ExpectedException, func, *args, **kwargs)\n\nThe reporter will provide you with helpful output in case of failures such as *no\nexception* or *wrong exception*.\n\nNote that it is also possible to specify a \"raises\" argument to\n``pytest.mark.xfail``, which checks that the test is failing in a more\nspecific way than just having any exception raised:\n\n.. code-block:: python\n\n @pytest.mark.xfail(raises=IndexError)\n def test_f():\n f()\n\nUsing ``pytest.raises`` is likely to be better for cases where you are testing\nexceptions your own code is deliberately raising, whereas using\n``@pytest.mark.xfail`` with a check function is probably better for something\nlike documenting unfixed bugs (where the test describes what \"should\" happen)\nor bugs in dependencies.\n\n\n.. _`assertwarns`:\n\nAssertions about expected warnings\n-----------------------------------------\n\n\n\nYou can check that code raises a particular warning using\n:ref:`pytest.warns `.\n\n\n.. _newreport:\n\nMaking use of context-sensitive comparisons\n-------------------------------------------------\n\n\n\n``pytest`` has rich support for providing context-sensitive information\nwhen it encounters comparisons. For example:\n\n.. code-block:: python\n\n # content of test_assert2.py\n\n\n def test_set_comparison():\n set1 = set(\"1308\")\n set2 = set(\"8035\")\n assert set1 == set2\n\nif you run this module:\n\n.. code-block:: pytest\n\n $ pytest test_assert2.py\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 1 item\n\n test_assert2.py F [100%]\n\n ================================= FAILURES =================================\n ___________________________ test_set_comparison ____________________________\n\n def test_set_comparison():\n set1 = set(\"1308\")\n set2 = set(\"8035\")\n > assert set1 == set2\n E AssertionError: assert {'0', '1', '3', '8'} == {'0', '3', '5', '8'}\n E Extra items in the left set:\n E '1'\n E Extra items in the right set:\n E '5'\n E Use -v to get the full diff\n\n test_assert2.py:6: AssertionError\n ========================= 1 failed in 0.12 seconds =========================\n\nSpecial comparisons are done for a number of cases:\n\n* comparing long strings: a context diff is shown\n* comparing long sequences: first failing indices\n* comparing dicts: different entries\n\nSee the :ref:`reporting demo ` for many more examples.\n\nDefining your own explanation for failed assertions\n---------------------------------------------------\n\nIt is possible to add your own detailed explanations by implementing\nthe ``pytest_assertrepr_compare`` hook.\n\n.. autofunction:: _pytest.hookspec.pytest_assertrepr_compare\n :noindex:\n\nAs an example consider adding the following hook in a :ref:`conftest.py `\nfile which provides an alternative explanation for ``Foo`` objects:\n\n.. code-block:: python\n\n # content of conftest.py\n from test_foocompare import Foo\n\n\n def pytest_assertrepr_compare(op, left, right):\n if isinstance(left, Foo) and isinstance(right, Foo) and op == \"==\":\n return [\"Comparing Foo instances:\", \" vals: %s != %s\" % (left.val, right.val)]\n\nnow, given this test module:\n\n.. code-block:: python\n\n # content of test_foocompare.py\n class Foo(object):\n def __init__(self, val):\n self.val = val\n\n def __eq__(self, other):\n return self.val == other.val\n\n\n def test_compare():\n f1 = Foo(1)\n f2 = Foo(2)\n assert f1 == f2\n\nyou can run the test module and get the custom output defined in\nthe conftest file:\n\n.. code-block:: pytest\n\n $ pytest -q test_foocompare.py\n F [100%]\n ================================= FAILURES =================================\n _______________________________ test_compare _______________________________\n\n def test_compare():\n f1 = Foo(1)\n f2 = Foo(2)\n > assert f1 == f2\n E assert Comparing Foo instances:\n E vals: 1 != 2\n\n test_foocompare.py:12: AssertionError\n 1 failed in 0.12 seconds\n\n.. _assert-details:\n.. _`assert introspection`:\n\nAssertion introspection details\n-------------------------------\n\n\n\n\nReporting details about a failing assertion is achieved by rewriting assert\nstatements before they are run. Rewritten assert statements put introspection\ninformation into the assertion failure message. ``pytest`` only rewrites test\nmodules directly discovered by its test collection process, so **asserts in\nsupporting modules which are not themselves test modules will not be rewritten**.\n\nYou can manually enable assertion rewriting for an imported module by calling\n`register_assert_rewrite `_\nbefore you import it (a good place to do that is in your root ``conftest.py``).\n\nFor further information, Benjamin Peterson wrote up `Behind the scenes of pytest's new assertion rewriting `_.\n\nAssertion rewriting caches files on disk\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n``pytest`` will write back the rewritten modules to disk for caching. You can disable\nthis behavior (for example to avoid leaving stale ``.pyc`` files around in projects that\nmove files around a lot) by adding this to the top of your ``conftest.py`` file:\n\n.. code-block:: python\n\n import sys\n\n sys.dont_write_bytecode = True\n\nNote that you still get the benefits of assertion introspection, the only change is that\nthe ``.pyc`` files won't be cached on disk.\n\nAdditionally, rewriting will silently skip caching if it cannot write new ``.pyc`` files,\ni.e. in a read-only filesystem or a zipfile.\n\n\nDisabling assert rewriting\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n``pytest`` rewrites test modules on import by using an import\nhook to write new ``pyc`` files. Most of the time this works transparently.\nHowever, if you are working with the import machinery yourself, the import hook may\ninterfere.\n\nIf this is the case you have two options:\n\n* Disable rewriting for a specific module by adding the string\n ``PYTEST_DONT_REWRITE`` to its docstring.\n\n* Disable rewriting for all modules by using ``--assert=plain``.\n\n\n\n Add assert rewriting as an alternate introspection technique.\n\n\n Introduce the ``--assert`` option. Deprecate ``--no-assert`` and\n ``--nomagic``.\n\n\n Removes the ``--no-assert`` and ``--nomagic`` options.\n Removes the ``--assert=reinterp`` option.\n"},{"id":5266,"name":"warnings.rst","nodeType":"TextFile","path":"doc/en","text":".. _`warnings`:\n\nWarnings Capture\n================\n\n\n\nStarting from version ``3.1``, pytest now automatically catches warnings during test execution\nand displays them at the end of the session:\n\n.. code-block:: python\n\n # content of test_show_warnings.py\n import warnings\n\n\n def api_v1():\n warnings.warn(UserWarning(\"api v1, should use functions from v2\"))\n return 1\n\n\n def test_one():\n assert api_v1() == 1\n\nRunning pytest now produces this output:\n\n.. code-block:: pytest\n\n $ pytest test_show_warnings.py\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 1 item\n\n test_show_warnings.py . [100%]\n\n ============================= warnings summary =============================\n test_show_warnings.py::test_one\n $REGENDOC_TMPDIR/test_show_warnings.py:5: UserWarning: api v1, should use functions from v2\n warnings.warn(UserWarning(\"api v1, should use functions from v2\"))\n\n -- Docs: https://docs.pytest.org/en/latest/warnings.html\n =================== 1 passed, 1 warnings in 0.12 seconds ===================\n\nThe ``-W`` flag can be passed to control which warnings will be displayed or even turn\nthem into errors:\n\n.. code-block:: pytest\n\n $ pytest -q test_show_warnings.py -W error::UserWarning\n F [100%]\n ================================= FAILURES =================================\n _________________________________ test_one _________________________________\n\n def test_one():\n > assert api_v1() == 1\n\n test_show_warnings.py:10:\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n\n def api_v1():\n > warnings.warn(UserWarning(\"api v1, should use functions from v2\"))\n E UserWarning: api v1, should use functions from v2\n\n test_show_warnings.py:5: UserWarning\n 1 failed in 0.12 seconds\n\nThe same option can be set in the ``pytest.ini`` file using the ``filterwarnings`` ini option.\nFor example, the configuration below will ignore all user warnings, but will transform\nall other warnings into errors.\n\n.. code-block:: ini\n\n [pytest]\n filterwarnings =\n error\n ignore::UserWarning\n\n\nWhen a warning matches more than one option in the list, the action for the last matching option\nis performed.\n\nBoth ``-W`` command-line option and ``filterwarnings`` ini option are based on Python's own\n`-W option`_ and `warnings.simplefilter`_, so please refer to those sections in the Python\ndocumentation for other examples and advanced usage.\n\n.. _`filterwarnings`:\n\n``@pytest.mark.filterwarnings``\n-------------------------------\n\n\n\nYou can use the ``@pytest.mark.filterwarnings`` to add warning filters to specific test items,\nallowing you to have finer control of which warnings should be captured at test, class or\neven module level:\n\n.. code-block:: python\n\n import warnings\n\n\n def api_v1():\n warnings.warn(UserWarning(\"api v1, should use functions from v2\"))\n return 1\n\n\n @pytest.mark.filterwarnings(\"ignore:api v1\")\n def test_one():\n assert api_v1() == 1\n\n\nFilters applied using a mark take precedence over filters passed on the command line or configured\nby the ``filterwarnings`` ini option.\n\nYou may apply a filter to all tests of a class by using the ``filterwarnings`` mark as a class\ndecorator or to all tests in a module by setting the ``pytestmark`` variable:\n\n.. code-block:: python\n\n # turns all warnings into errors for this module\n pytestmark = pytest.mark.filterwarnings(\"error\")\n\n\n\n*Credits go to Florian Schulze for the reference implementation in the* `pytest-warnings`_\n*plugin.*\n\n.. _`-W option`: https://docs.python.org/3/using/cmdline.html?highlight=#cmdoption-W\n.. _warnings.simplefilter: https://docs.python.org/3/library/warnings.html#warnings.simplefilter\n.. _`pytest-warnings`: https://github.com/fschulze/pytest-warnings\n\nDisabling warnings summary\n--------------------------\n\nAlthough not recommended, you can use the ``--disable-warnings`` command-line option to suppress the\nwarning summary entirely from the test run output.\n\nDisabling warning capture entirely\n----------------------------------\n\nThis plugin is enabled by default but can be disabled entirely in your ``pytest.ini`` file with:\n\n .. code-block:: ini\n\n [pytest]\n addopts = -p no:warnings\n\nOr passing ``-p no:warnings`` in the command-line. This might be useful if your test suites handles warnings\nusing an external system.\n\n\n.. _`deprecation-warnings`:\n\nDeprecationWarning and PendingDeprecationWarning\n------------------------------------------------\n\n\n\n\nBy default pytest will display ``DeprecationWarning`` and ``PendingDeprecationWarning`` warnings from\nuser code and third-party libraries, as recommended by `PEP-0565 `_.\nThis helps users keep their code modern and avoid breakages when deprecated warnings are effectively removed.\n\nSometimes it is useful to hide some specific deprecation warnings that happen in code that you have no control over\n(such as third-party libraries), in which case you might use the warning filters options (ini or marks) to ignore\nthose warnings.\n\nFor example:\n\n.. code-block:: ini\n\n [pytest]\n filterwarnings =\n ignore:.*U.*mode is deprecated:DeprecationWarning\n\n\nThis will ignore all warnings of type ``DeprecationWarning`` where the start of the message matches\nthe regular expression ``\".*U.*mode is deprecated\"``.\n\n.. note::\n If warnings are configured at the interpreter level, using\n the `PYTHONWARNINGS `_ environment variable or the\n ``-W`` command-line option, pytest will not configure any filters by default.\n\n Also pytest doesn't follow ``PEP-0506`` suggestion of resetting all warning filters because\n it might break test suites that configure warning filters themselves\n by calling ``warnings.simplefilter`` (see issue `#2430 `_\n for an example of that).\n\n\n.. _`ensuring a function triggers a deprecation warning`:\n\n.. _ensuring_function_triggers:\n\nEnsuring code triggers a deprecation warning\n--------------------------------------------\n\nYou can also call a global helper for checking\nthat a certain function call triggers a ``DeprecationWarning`` or\n``PendingDeprecationWarning``:\n\n.. code-block:: python\n\n import pytest\n\n\n def test_global():\n pytest.deprecated_call(myfunction, 17)\n\nBy default, ``DeprecationWarning`` and ``PendingDeprecationWarning`` will not be\ncaught when using ``pytest.warns`` or ``recwarn`` because default Python warnings filters hide\nthem. If you wish to record them in your own code, use the\ncommand ``warnings.simplefilter('always')``:\n\n.. code-block:: python\n\n import warnings\n import pytest\n\n\n def test_deprecation(recwarn):\n warnings.simplefilter(\"always\")\n warnings.warn(\"deprecated\", DeprecationWarning)\n assert len(recwarn) == 1\n assert recwarn.pop(DeprecationWarning)\n\nYou can also use it as a contextmanager:\n\n.. code-block:: python\n\n def test_global():\n with pytest.deprecated_call():\n myobject.deprecated_method()\n\n\n\n.. _`asserting warnings`:\n\n.. _assertwarnings:\n\n.. _`asserting warnings with the warns function`:\n\n.. _warns:\n\nAsserting warnings with the warns function\n------------------------------------------\n\n\n\nYou can check that code raises a particular warning using ``pytest.warns``,\nwhich works in a similar manner to :ref:`raises `:\n\n.. code-block:: python\n\n import warnings\n import pytest\n\n\n def test_warning():\n with pytest.warns(UserWarning):\n warnings.warn(\"my warning\", UserWarning)\n\nThe test will fail if the warning in question is not raised. The keyword\nargument ``match`` to assert that the exception matches a text or regex::\n\n >>> with warns(UserWarning, match='must be 0 or None'):\n ... warnings.warn(\"value must be 0 or None\", UserWarning)\n\n >>> with warns(UserWarning, match=r'must be \\d+$'):\n ... warnings.warn(\"value must be 42\", UserWarning)\n\n >>> with warns(UserWarning, match=r'must be \\d+$'):\n ... warnings.warn(\"this is not here\", UserWarning)\n Traceback (most recent call last):\n ...\n Failed: DID NOT WARN. No warnings of type ...UserWarning... was emitted...\n\nYou can also call ``pytest.warns`` on a function or code string::\n\n pytest.warns(expected_warning, func, *args, **kwargs)\n pytest.warns(expected_warning, \"func(*args, **kwargs)\")\n\nThe function also returns a list of all raised warnings (as\n``warnings.WarningMessage`` objects), which you can query for\nadditional information:\n\n.. code-block:: python\n\n with pytest.warns(RuntimeWarning) as record:\n warnings.warn(\"another warning\", RuntimeWarning)\n\n # check that only one warning was raised\n assert len(record) == 1\n # check that the message matches\n assert record[0].message.args[0] == \"another warning\"\n\nAlternatively, you can examine raised warnings in detail using the\n:ref:`recwarn ` fixture (see below).\n\n.. note::\n ``DeprecationWarning`` and ``PendingDeprecationWarning`` are treated\n differently; see :ref:`ensuring_function_triggers`.\n\n.. _`recording warnings`:\n\n.. _recwarn:\n\nRecording warnings\n------------------\n\nYou can record raised warnings either using ``pytest.warns`` or with\nthe ``recwarn`` fixture.\n\nTo record with ``pytest.warns`` without asserting anything about the warnings,\npass ``None`` as the expected warning type:\n\n.. code-block:: python\n\n with pytest.warns(None) as record:\n warnings.warn(\"user\", UserWarning)\n warnings.warn(\"runtime\", RuntimeWarning)\n\n assert len(record) == 2\n assert str(record[0].message) == \"user\"\n assert str(record[1].message) == \"runtime\"\n\nThe ``recwarn`` fixture will record warnings for the whole function:\n\n.. code-block:: python\n\n import warnings\n\n\n def test_hello(recwarn):\n warnings.warn(\"hello\", UserWarning)\n assert len(recwarn) == 1\n w = recwarn.pop(UserWarning)\n assert issubclass(w.category, UserWarning)\n assert str(w.message) == \"hello\"\n assert w.filename\n assert w.lineno\n\nBoth ``recwarn`` and ``pytest.warns`` return the same interface for recorded\nwarnings: a WarningsRecorder instance. To view the recorded warnings, you can\niterate over this instance, call ``len`` on it to get the number of recorded\nwarnings, or index into it to get a particular recorded warning.\n\n.. currentmodule:: _pytest.warnings\n\nFull API: :class:`WarningsRecorder`.\n\n.. _custom_failure_messages:\n\nCustom failure messages\n-----------------------\n\nRecording warnings provides an opportunity to produce custom test\nfailure messages for when no warnings are issued or other conditions\nare met.\n\n.. code-block:: python\n\n def test():\n with pytest.warns(Warning) as record:\n f()\n if not record:\n pytest.fail(\"Expected a warning!\")\n\nIf no warnings are issued when calling ``f``, then ``not record`` will\nevaluate to ``True``. You can then call ``pytest.fail`` with a\ncustom error message.\n\n.. _internal-warnings:\n\nInternal pytest warnings\n------------------------\n\n\n\npytest may generate its own warnings in some situations, such as improper usage or deprecated features.\n\nFor example, pytest will emit a warning if it encounters a class that matches :confval:`python_classes` but also\ndefines an ``__init__`` constructor, as this prevents the class from being instantiated:\n\n.. code-block:: python\n\n # content of test_pytest_warnings.py\n class Test:\n def __init__(self):\n pass\n\n def test_foo(self):\n assert 1 == 1\n\n.. code-block:: pytest\n\n $ pytest test_pytest_warnings.py -q\n\n ============================= warnings summary =============================\n test_pytest_warnings.py:1\n $REGENDOC_TMPDIR/test_pytest_warnings.py:1: PytestCollectionWarning: cannot collect test class 'Test' because it has a __init__ constructor (from: test_pytest_warnings.py)\n class Test:\n\n -- Docs: https://docs.pytest.org/en/latest/warnings.html\n 1 warnings in 0.12 seconds\n\nThese warnings might be filtered using the same builtin mechanisms used to filter other types of warnings.\n\nPlease read our :ref:`backwards-compatibility` to learn how we proceed about deprecating and eventually removing\nfeatures.\n\nThe following warning types ares used by pytest and are part of the public API:\n\n.. autoclass:: pytest.PytestWarning\n\n.. autoclass:: pytest.PytestAssertRewriteWarning\n\n.. autoclass:: pytest.PytestCacheWarning\n\n.. autoclass:: pytest.PytestCollectionWarning\n\n.. autoclass:: pytest.PytestConfigWarning\n\n.. autoclass:: pytest.PytestDeprecationWarning\n\n.. autoclass:: pytest.PytestExperimentalApiWarning\n\n.. autoclass:: pytest.PytestUnhandledCoroutineWarning\n\n.. autoclass:: pytest.PytestUnknownMarkWarning\n\n.. autoclass:: pytest.RemovedInPytest4Warning\n"},{"fileName":"test_setup_skip_module.py","filePath":"testing/example_scripts/unittest","id":5267,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"setUpModule is always called, even if all tests in the module are skipped\"\"\"\nimport unittest\n\n\ndef setUpModule():\n assert 0\n\n\n@unittest.skip(\"skip all tests\")\nclass Base(unittest.TestCase):\n def test(self):\n assert 0\n"},{"className":"Base","col":0,"comment":"null","endLoc":13,"id":5268,"nodeType":"Class","startLoc":10,"text":"@unittest.skip(\"skip all tests\")\nclass Base(unittest.TestCase):\n def test(self):\n assert 0"},{"col":4,"comment":"null","endLoc":13,"header":"def test(self)","id":5269,"name":"test","nodeType":"Function","startLoc":12,"text":"def test(self):\n assert 0"},{"col":0,"comment":"null","endLoc":7,"header":"def setUpModule()","id":5270,"name":"setUpModule","nodeType":"Function","startLoc":6,"text":"def setUpModule():\n assert 0"},{"col":0,"comment":"","endLoc":2,"header":"test_setup_skip_module.py#","id":5271,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"setUpModule is always called, even if all tests in the module are skipped\"\"\""},{"id":5272,"name":"doc/en/example/costlysetup/sub_b","nodeType":"Package"},{"fileName":"test_two.py","filePath":"doc/en/example/costlysetup/sub_b","id":5273,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ndef test_something(setup):\n assert setup.timecostly == 1\n\n\ndef test_something_more(setup):\n assert setup.timecostly == 1\n"},{"col":0,"comment":"null","endLoc":3,"header":"def test_something(setup)","id":5274,"name":"test_something","nodeType":"Function","startLoc":2,"text":"def test_something(setup):\n assert setup.timecostly == 1"},{"col":0,"comment":"null","endLoc":7,"header":"def test_something_more(setup)","id":5275,"name":"test_something_more","nodeType":"Function","startLoc":6,"text":"def test_something_more(setup):\n assert setup.timecostly == 1"},{"id":5276,"name":"release-2.3.3.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.3.3: integration fixes, py24 support, ``*/**`` shown in traceback\n===========================================================================\n\npytest-2.3.3 is another stabilization release of the py.test tool\nwhich offers uebersimple assertions, scalable fixture mechanisms\nand deep customization for testing with Python. Particularly,\nthis release provides:\n\n- integration fixes and improvements related to flask, numpy, nose,\n unittest, mock\n\n- makes pytest work on py24 again (yes, people sometimes still need to use it)\n\n- show ``*,**`` args in pytest tracebacks\n\nThanks to Manuel Jacob, Thomas Waldmann, Ronny Pfannschmidt, Pavel Repin\nand Andreas Taumoefolau for providing patches and all for the issues.\n\nSee\n\n http://pytest.org/\n\nfor general information. To install or upgrade pytest:\n\n pip install -U pytest # or\n easy_install -U pytest\n\nbest,\nholger krekel\n\nChanges between 2.3.2 and 2.3.3\n-----------------------------------\n\n- fix issue214 - parse modules that contain special objects like e. g.\n flask's request object which blows up on getattr access if no request\n is active. thanks Thomas Waldmann.\n\n- fix issue213 - allow to parametrize with values like numpy arrays that\n do not support an __eq__ operator\n\n- fix issue215 - split test_python.org into multiple files\n\n- fix issue148 - @unittest.skip on classes is now recognized and avoids\n calling setUpClass/tearDownClass, thanks Pavel Repin\n\n- fix issue209 - reintroduce python2.4 support by depending on newer\n pylib which re-introduced statement-finding for pre-AST interpreters\n\n- nose support: only call setup if it's a callable, thanks Andrew\n Taumoefolau\n\n- fix issue219 - add py2.4-3.3 classifiers to TROVE list\n\n- in tracebacks *,** arg values are now shown next to normal arguments\n (thanks Manuel Jacob)\n\n- fix issue217 - support mock.patch with pytest's fixtures - note that\n you need either mock-1.0.1 or the python3.3 builtin unittest.mock.\n\n- fix issue127 - improve documentation for pytest_addoption() and\n add a ``config.getoption(name)`` helper function for consistency.\n"},{"fileName":"exceptions.py","filePath":"src/_pytest/config","id":5277,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nclass UsageError(Exception):\n \"\"\" error in pytest usage or invocation\"\"\"\n\n\nclass PrintHelp(Exception):\n \"\"\"Raised when pytest should print it's help to skip the rest of the\n argument parsing and validation.\"\"\"\n\n pass\n"},{"id":5278,"name":"release-2.3.5.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.3.5: bug fixes and little improvements\n===========================================================================\n\npytest-2.3.5 is a maintenance release with many bug fixes and little\nimprovements. See the changelog below for details. No backward\ncompatibility issues are foreseen and all plugins which worked with the\nprior version are expected to work unmodified. Speaking of which, a\nfew interesting new plugins saw the light last month:\n\n- pytest-instafail: show failure information while tests are running\n- pytest-qt: testing of GUI applications written with QT/Pyside\n- pytest-xprocess: managing external processes across test runs\n- pytest-random: randomize test ordering\n\nAnd several others like pytest-django saw maintenance releases.\nFor a more complete list, check out\nhttps://pypi.org/search/?q=pytest\n\nFor general information see:\n\n http://pytest.org/\n\nTo install or upgrade pytest:\n\n pip install -U pytest # or\n easy_install -U pytest\n\nParticular thanks to Floris, Ronny, Benjamin and the many bug reporters\nand fix providers.\n\nmay the fixtures be with you,\nholger krekel\n\n\nChanges between 2.3.4 and 2.3.5\n-----------------------------------\n\n- never consider a fixture function for test function collection\n\n- allow re-running of test items / helps to fix pytest-reruntests plugin\n and also help to keep less fixture/resource references alive\n\n- put captured stdout/stderr into junitxml output even for passing tests\n (thanks Adam Goucher)\n\n- Issue 265 - integrate nose setup/teardown with setupstate\n so it doesn't try to teardown if it did not setup\n\n- issue 271 - don't write junitxml on slave nodes\n\n- Issue 274 - don't try to show full doctest example\n when doctest does not know the example location\n\n- issue 280 - disable assertion rewriting on buggy CPython 2.6.0\n\n- inject \"getfixture()\" helper to retrieve fixtures from doctests,\n thanks Andreas Zeidler\n\n- issue 259 - when assertion rewriting, be consistent with the default\n source encoding of ASCII on Python 2\n\n- issue 251 - report a skip instead of ignoring classes with init\n\n- issue250 unicode/str mixes in parametrization names and values now works\n\n- issue257, assertion-triggered compilation of source ending in a\n comment line doesn't blow up in python2.5 (fixed through py>=1.4.13.dev6)\n\n- fix --genscript option to generate standalone scripts that also\n work with python3.3 (importer ordering)\n\n- issue171 - in assertion rewriting, show the repr of some\n global variables\n\n- fix option help for \"-k\"\n\n- move long description of distribution into README.rst\n\n- improve docstring for metafunc.parametrize()\n\n- fix bug where using capsys with pytest.set_trace() in a test\n function would break when looking at capsys.readouterr()\n\n- allow to specify prefixes starting with \"_\" when\n customizing python_functions test discovery. (thanks Graham Horler)\n\n- improve PYTEST_DEBUG tracing output by putting\n extra data on a new lines with additional indent\n\n- ensure OutcomeExceptions like skip/fail have initialized exception attributes\n\n- issue 260 - don't use nose special setup on plain unittest cases\n\n- fix issue134 - print the collect errors that prevent running specified test items\n\n- fix issue266 - accept unicode in MarkEvaluator expressions\n"},{"id":5279,"name":"yieldfixture.rst","nodeType":"TextFile","path":"doc/en","text":":orphan:\n\n.. _yieldfixture:\n\n\"yield_fixture\" functions\n---------------------------------------------------------------\n\n\n\n\n\n.. important::\n Since pytest-3.0, fixtures using the normal ``fixture`` decorator can use a ``yield``\n statement to provide fixture values and execute teardown code, exactly like ``yield_fixture``\n in previous versions.\n\n Marking functions as ``yield_fixture`` is still supported, but deprecated and should not\n be used in new code.\n"},{"col":4,"comment":"null","endLoc":1094,"header":"def test_capturing_reset_simple(self)","id":5280,"name":"test_capturing_reset_simple","nodeType":"Function","startLoc":1088,"text":"def test_capturing_reset_simple(self):\n with self.getcapture() as cap:\n print(\"hello world\")\n sys.stderr.write(\"hello error\\n\")\n out, err = cap.readouterr()\n assert out == \"hello world\\n\"\n assert err == \"hello error\\n\""},{"col":4,"comment":"null","endLoc":1105,"header":"def test_capturing_readouterr(self)","id":5281,"name":"test_capturing_readouterr","nodeType":"Function","startLoc":1096,"text":"def test_capturing_readouterr(self):\n with self.getcapture() as cap:\n print(\"hello world\")\n sys.stderr.write(\"hello error\\n\")\n out, err = cap.readouterr()\n assert out == \"hello world\\n\"\n assert err == \"hello error\\n\"\n sys.stderr.write(\"error2\")\n out, err = cap.readouterr()\n assert err == \"error2\""},{"col":4,"comment":"null","endLoc":1113,"header":"def test_capture_results_accessible_by_attribute(self)","id":5282,"name":"test_capture_results_accessible_by_attribute","nodeType":"Function","startLoc":1107,"text":"def test_capture_results_accessible_by_attribute(self):\n with self.getcapture() as cap:\n sys.stdout.write(\"hello\")\n sys.stderr.write(\"world\")\n capture_result = cap.readouterr()\n assert capture_result.out == \"hello\"\n assert capture_result.err == \"world\""},{"col":4,"comment":"null","endLoc":1119,"header":"def test_capturing_readouterr_unicode(self)","id":5283,"name":"test_capturing_readouterr_unicode","nodeType":"Function","startLoc":1115,"text":"def test_capturing_readouterr_unicode(self):\n with self.getcapture() as cap:\n print(\"hxąć\")\n out, err = cap.readouterr()\n assert out == u\"hxąć\\n\""},{"col":4,"comment":"null","endLoc":1129,"header":"@pytest.mark.skipif(\n \"sys.version_info >= (3,)\", reason=\"text output different for bytes on python3\"\n )\n def test_capturing_readouterr_decode_error_handling(self)","id":5284,"name":"test_capturing_readouterr_decode_error_handling","nodeType":"Function","startLoc":1121,"text":"@pytest.mark.skipif(\n \"sys.version_info >= (3,)\", reason=\"text output different for bytes on python3\"\n )\n def test_capturing_readouterr_decode_error_handling(self):\n with self.getcapture() as cap:\n # triggered an internal error in pytest\n print(\"\\xa6\")\n out, err = cap.readouterr()\n assert out == u\"\\ufffd\\n\""},{"fileName":"test_config.py","filePath":"testing","id":5285,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nimport textwrap\n\nimport importlib_metadata\n\nimport _pytest._code\nimport pytest\nfrom _pytest.config import _iter_rewritable_modules\nfrom _pytest.config.exceptions import UsageError\nfrom _pytest.config.findpaths import determine_setup\nfrom _pytest.config.findpaths import get_common_ancestor\nfrom _pytest.config.findpaths import getcfg\nfrom _pytest.main import EXIT_INTERRUPTED\nfrom _pytest.main import EXIT_NOTESTSCOLLECTED\nfrom _pytest.main import EXIT_OK\nfrom _pytest.main import EXIT_TESTSFAILED\nfrom _pytest.main import EXIT_USAGEERROR\n\n\nclass TestParseIni(object):\n @pytest.mark.parametrize(\n \"section, filename\", [(\"pytest\", \"pytest.ini\"), (\"tool:pytest\", \"setup.cfg\")]\n )\n def test_getcfg_and_config(self, testdir, tmpdir, section, filename):\n sub = tmpdir.mkdir(\"sub\")\n sub.chdir()\n tmpdir.join(filename).write(\n textwrap.dedent(\n \"\"\"\\\n [{section}]\n name = value\n \"\"\".format(\n section=section\n )\n )\n )\n rootdir, inifile, cfg = getcfg([sub])\n assert cfg[\"name\"] == \"value\"\n config = testdir.parseconfigure(sub)\n assert config.inicfg[\"name\"] == \"value\"\n\n def test_getcfg_empty_path(self):\n \"\"\"correctly handle zero length arguments (a la pytest '')\"\"\"\n getcfg([\"\"])\n\n def test_setupcfg_uses_toolpytest_with_pytest(self, testdir):\n p1 = testdir.makepyfile(\"def test(): pass\")\n testdir.makefile(\n \".cfg\",\n setup=\"\"\"\n [tool:pytest]\n testpaths=%s\n [pytest]\n testpaths=ignored\n \"\"\"\n % p1.basename,\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*, inifile: setup.cfg, *\", \"* 1 passed in *\"])\n assert result.ret == 0\n\n def test_append_parse_args(self, testdir, tmpdir, monkeypatch):\n monkeypatch.setenv(\"PYTEST_ADDOPTS\", '--color no -rs --tb=\"short\"')\n tmpdir.join(\"pytest.ini\").write(\n textwrap.dedent(\n \"\"\"\\\n [pytest]\n addopts = --verbose\n \"\"\"\n )\n )\n config = testdir.parseconfig(tmpdir)\n assert config.option.color == \"no\"\n assert config.option.reportchars == \"s\"\n assert config.option.tbstyle == \"short\"\n assert config.option.verbose\n\n def test_tox_ini_wrong_version(self, testdir):\n testdir.makefile(\n \".ini\",\n tox=\"\"\"\n [pytest]\n minversion=9.0\n \"\"\",\n )\n result = testdir.runpytest()\n assert result.ret != 0\n result.stderr.fnmatch_lines([\"*tox.ini:2*requires*9.0*actual*\"])\n\n @pytest.mark.parametrize(\n \"section, name\",\n [(\"tool:pytest\", \"setup.cfg\"), (\"pytest\", \"tox.ini\"), (\"pytest\", \"pytest.ini\")],\n )\n def test_ini_names(self, testdir, name, section):\n testdir.tmpdir.join(name).write(\n textwrap.dedent(\n \"\"\"\n [{section}]\n minversion = 1.0\n \"\"\".format(\n section=section\n )\n )\n )\n config = testdir.parseconfig()\n assert config.getini(\"minversion\") == \"1.0\"\n\n def test_toxini_before_lower_pytestini(self, testdir):\n sub = testdir.tmpdir.mkdir(\"sub\")\n sub.join(\"tox.ini\").write(\n textwrap.dedent(\n \"\"\"\n [pytest]\n minversion = 2.0\n \"\"\"\n )\n )\n testdir.tmpdir.join(\"pytest.ini\").write(\n textwrap.dedent(\n \"\"\"\n [pytest]\n minversion = 1.5\n \"\"\"\n )\n )\n config = testdir.parseconfigure(sub)\n assert config.getini(\"minversion\") == \"2.0\"\n\n def test_ini_parse_error(self, testdir):\n testdir.tmpdir.join(\"pytest.ini\").write(\"addopts = -x\")\n result = testdir.runpytest()\n assert result.ret != 0\n result.stderr.fnmatch_lines([\"ERROR: *pytest.ini:1: no section header defined\"])\n\n @pytest.mark.xfail(reason=\"probably not needed\")\n def test_confcutdir(self, testdir):\n sub = testdir.mkdir(\"sub\")\n sub.chdir()\n testdir.makeini(\n \"\"\"\n [pytest]\n addopts = --qwe\n \"\"\"\n )\n result = testdir.inline_run(\"--confcutdir=.\")\n assert result.ret == 0\n\n\nclass TestConfigCmdlineParsing(object):\n def test_parsing_again_fails(self, testdir):\n config = testdir.parseconfig()\n pytest.raises(AssertionError, lambda: config.parse([]))\n\n def test_explicitly_specified_config_file_is_loaded(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"custom\", \"\")\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n custom = 0\n \"\"\"\n )\n testdir.makefile(\n \".ini\",\n custom=\"\"\"\n [pytest]\n custom = 1\n \"\"\",\n )\n config = testdir.parseconfig(\"-c\", \"custom.ini\")\n assert config.getini(\"custom\") == \"1\"\n\n testdir.makefile(\n \".cfg\",\n custom_tool_pytest_section=\"\"\"\n [tool:pytest]\n custom = 1\n \"\"\",\n )\n config = testdir.parseconfig(\"-c\", \"custom_tool_pytest_section.cfg\")\n assert config.getini(\"custom\") == \"1\"\n\n def test_absolute_win32_path(self, testdir):\n temp_ini_file = testdir.makefile(\n \".ini\",\n custom=\"\"\"\n [pytest]\n addopts = --version\n \"\"\",\n )\n from os.path import normpath\n\n temp_ini_file = normpath(str(temp_ini_file))\n ret = pytest.main([\"-c\", temp_ini_file])\n assert ret == _pytest.main.EXIT_OK\n\n\nclass TestConfigAPI(object):\n def test_config_trace(self, testdir):\n config = testdir.parseconfig()\n values = []\n config.trace.root.setwriter(values.append)\n config.trace(\"hello\")\n assert len(values) == 1\n assert values[0] == \"hello [config]\\n\"\n\n def test_config_getoption(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addoption(\"--hello\", \"-X\", dest=\"hello\")\n \"\"\"\n )\n config = testdir.parseconfig(\"--hello=this\")\n for x in (\"hello\", \"--hello\", \"-X\"):\n assert config.getoption(x) == \"this\"\n pytest.raises(ValueError, config.getoption, \"qweqwe\")\n\n @pytest.mark.skipif(\"sys.version_info[0] < 3\")\n def test_config_getoption_unicode(self, testdir):\n testdir.makeconftest(\n \"\"\"\n from __future__ import unicode_literals\n\n def pytest_addoption(parser):\n parser.addoption('--hello', type=str)\n \"\"\"\n )\n config = testdir.parseconfig(\"--hello=this\")\n assert config.getoption(\"hello\") == \"this\"\n\n def test_config_getvalueorskip(self, testdir):\n config = testdir.parseconfig()\n pytest.raises(pytest.skip.Exception, config.getvalueorskip, \"hello\")\n verbose = config.getvalueorskip(\"verbose\")\n assert verbose == config.option.verbose\n\n def test_config_getvalueorskip_None(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addoption(\"--hello\")\n \"\"\"\n )\n config = testdir.parseconfig()\n with pytest.raises(pytest.skip.Exception):\n config.getvalueorskip(\"hello\")\n\n def test_getoption(self, testdir):\n config = testdir.parseconfig()\n with pytest.raises(ValueError):\n config.getvalue(\"x\")\n assert config.getoption(\"x\", 1) == 1\n\n def test_getconftest_pathlist(self, testdir, tmpdir):\n somepath = tmpdir.join(\"x\", \"y\", \"z\")\n p = tmpdir.join(\"conftest.py\")\n p.write(\"pathlist = ['.', %r]\" % str(somepath))\n config = testdir.parseconfigure(p)\n assert config._getconftest_pathlist(\"notexist\", path=tmpdir) is None\n pl = config._getconftest_pathlist(\"pathlist\", path=tmpdir)\n print(pl)\n assert len(pl) == 2\n assert pl[0] == tmpdir\n assert pl[1] == somepath\n\n def test_addini(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"myname\", \"my new ini value\")\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n myname=hello\n \"\"\"\n )\n config = testdir.parseconfig()\n val = config.getini(\"myname\")\n assert val == \"hello\"\n pytest.raises(ValueError, config.getini, \"other\")\n\n def test_addini_pathlist(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"paths\", \"my new ini value\", type=\"pathlist\")\n parser.addini(\"abc\", \"abc value\")\n \"\"\"\n )\n p = testdir.makeini(\n \"\"\"\n [pytest]\n paths=hello world/sub.py\n \"\"\"\n )\n config = testdir.parseconfig()\n values = config.getini(\"paths\")\n assert len(values) == 2\n assert values[0] == p.dirpath(\"hello\")\n assert values[1] == p.dirpath(\"world/sub.py\")\n pytest.raises(ValueError, config.getini, \"other\")\n\n def test_addini_args(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"args\", \"new args\", type=\"args\")\n parser.addini(\"a2\", \"\", \"args\", default=\"1 2 3\".split())\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n args=123 \"123 hello\" \"this\"\n \"\"\"\n )\n config = testdir.parseconfig()\n values = config.getini(\"args\")\n assert len(values) == 3\n assert values == [\"123\", \"123 hello\", \"this\"]\n values = config.getini(\"a2\")\n assert values == list(\"123\")\n\n def test_addini_linelist(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"xy\", \"\", type=\"linelist\")\n parser.addini(\"a2\", \"\", \"linelist\")\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n xy= 123 345\n second line\n \"\"\"\n )\n config = testdir.parseconfig()\n values = config.getini(\"xy\")\n assert len(values) == 2\n assert values == [\"123 345\", \"second line\"]\n values = config.getini(\"a2\")\n assert values == []\n\n @pytest.mark.parametrize(\n \"str_val, bool_val\", [(\"True\", True), (\"no\", False), (\"no-ini\", True)]\n )\n def test_addini_bool(self, testdir, str_val, bool_val):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"strip\", \"\", type=\"bool\", default=True)\n \"\"\"\n )\n if str_val != \"no-ini\":\n testdir.makeini(\n \"\"\"\n [pytest]\n strip=%s\n \"\"\"\n % str_val\n )\n config = testdir.parseconfig()\n assert config.getini(\"strip\") is bool_val\n\n def test_addinivalue_line_existing(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"xy\", \"\", type=\"linelist\")\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n xy= 123\n \"\"\"\n )\n config = testdir.parseconfig()\n values = config.getini(\"xy\")\n assert len(values) == 1\n assert values == [\"123\"]\n config.addinivalue_line(\"xy\", \"456\")\n values = config.getini(\"xy\")\n assert len(values) == 2\n assert values == [\"123\", \"456\"]\n\n def test_addinivalue_line_new(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"xy\", \"\", type=\"linelist\")\n \"\"\"\n )\n config = testdir.parseconfig()\n assert not config.getini(\"xy\")\n config.addinivalue_line(\"xy\", \"456\")\n values = config.getini(\"xy\")\n assert len(values) == 1\n assert values == [\"456\"]\n config.addinivalue_line(\"xy\", \"123\")\n values = config.getini(\"xy\")\n assert len(values) == 2\n assert values == [\"456\", \"123\"]\n\n def test_confcutdir_check_isdir(self, testdir):\n \"\"\"Give an error if --confcutdir is not a valid directory (#2078)\"\"\"\n with pytest.raises(pytest.UsageError):\n testdir.parseconfig(\n \"--confcutdir\", testdir.tmpdir.join(\"file\").ensure(file=1)\n )\n with pytest.raises(pytest.UsageError):\n testdir.parseconfig(\"--confcutdir\", testdir.tmpdir.join(\"inexistant\"))\n config = testdir.parseconfig(\n \"--confcutdir\", testdir.tmpdir.join(\"dir\").ensure(dir=1)\n )\n assert config.getoption(\"confcutdir\") == str(testdir.tmpdir.join(\"dir\"))\n\n @pytest.mark.parametrize(\n \"names, expected\",\n [\n ([\"bar.py\"], [\"bar\"]),\n ([\"foo\", \"bar.py\"], []),\n ([\"foo\", \"bar.pyc\"], []),\n ([\"foo\", \"__init__.py\"], [\"foo\"]),\n ([\"foo\", \"bar\", \"__init__.py\"], []),\n ],\n )\n def test_iter_rewritable_modules(self, names, expected):\n assert list(_iter_rewritable_modules([\"/\".join(names)])) == expected\n\n\nclass TestConfigFromdictargs(object):\n def test_basic_behavior(self, _sys_snapshot):\n from _pytest.config import Config\n\n option_dict = {\"verbose\": 444, \"foo\": \"bar\", \"capture\": \"no\"}\n args = [\"a\", \"b\"]\n\n config = Config.fromdictargs(option_dict, args)\n with pytest.raises(AssertionError):\n config.parse([\"should refuse to parse again\"])\n assert config.option.verbose == 444\n assert config.option.foo == \"bar\"\n assert config.option.capture == \"no\"\n assert config.args == args\n\n def test_origargs(self, _sys_snapshot):\n \"\"\"Show that fromdictargs can handle args in their \"orig\" format\"\"\"\n from _pytest.config import Config\n\n option_dict = {}\n args = [\"-vvvv\", \"-s\", \"a\", \"b\"]\n\n config = Config.fromdictargs(option_dict, args)\n assert config.args == [\"a\", \"b\"]\n assert config._origargs == args\n assert config.option.verbose == 4\n assert config.option.capture == \"no\"\n\n def test_inifilename(self, tmpdir):\n tmpdir.join(\"foo/bar.ini\").ensure().write(\n textwrap.dedent(\n \"\"\"\\\n [pytest]\n name = value\n \"\"\"\n )\n )\n\n from _pytest.config import Config\n\n inifile = \"../../foo/bar.ini\"\n option_dict = {\"inifilename\": inifile, \"capture\": \"no\"}\n\n cwd = tmpdir.join(\"a/b\")\n cwd.join(\"pytest.ini\").ensure().write(\n textwrap.dedent(\n \"\"\"\\\n [pytest]\n name = wrong-value\n should_not_be_set = true\n \"\"\"\n )\n )\n with cwd.ensure(dir=True).as_cwd():\n config = Config.fromdictargs(option_dict, ())\n\n assert config.args == [str(cwd)]\n assert config.option.inifilename == inifile\n assert config.option.capture == \"no\"\n\n # this indicates this is the file used for getting configuration values\n assert config.inifile == inifile\n assert config.inicfg.get(\"name\") == \"value\"\n assert config.inicfg.get(\"should_not_be_set\") is None\n\n\ndef test_options_on_small_file_do_not_blow_up(testdir):\n def runfiletest(opts):\n reprec = testdir.inline_run(*opts)\n passed, skipped, failed = reprec.countoutcomes()\n assert failed == 2\n assert skipped == passed == 0\n\n path = testdir.makepyfile(\n \"\"\"\n def test_f1(): assert 0\n def test_f2(): assert 0\n \"\"\"\n )\n\n for opts in (\n [],\n [\"-l\"],\n [\"-s\"],\n [\"--tb=no\"],\n [\"--tb=short\"],\n [\"--tb=long\"],\n [\"--fulltrace\"],\n [\"--traceconfig\"],\n [\"-v\"],\n [\"-v\", \"-v\"],\n ):\n runfiletest(opts + [path])\n\n\ndef test_preparse_ordering_with_setuptools(testdir, monkeypatch):\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n\n class EntryPoint(object):\n name = \"mytestplugin\"\n group = \"pytest11\"\n\n def load(self):\n class PseudoPlugin(object):\n x = 42\n\n return PseudoPlugin()\n\n class Dist(object):\n files = ()\n entry_points = (EntryPoint(),)\n\n def my_dists():\n return (Dist,)\n\n monkeypatch.setattr(importlib_metadata, \"distributions\", my_dists)\n testdir.makeconftest(\n \"\"\"\n pytest_plugins = \"mytestplugin\",\n \"\"\"\n )\n monkeypatch.setenv(\"PYTEST_PLUGINS\", \"mytestplugin\")\n config = testdir.parseconfig()\n plugin = config.pluginmanager.getplugin(\"mytestplugin\")\n assert plugin.x == 42\n\n\ndef test_setuptools_importerror_issue1479(testdir, monkeypatch):\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n\n class DummyEntryPoint(object):\n name = \"mytestplugin\"\n group = \"pytest11\"\n\n def load(self):\n raise ImportError(\"Don't hide me!\")\n\n class Distribution(object):\n version = \"1.0\"\n files = (\"foo.txt\",)\n entry_points = (DummyEntryPoint(),)\n\n def distributions():\n return (Distribution(),)\n\n monkeypatch.setattr(importlib_metadata, \"distributions\", distributions)\n with pytest.raises(ImportError):\n testdir.parseconfig()\n\n\ndef test_importlib_metadata_broken_distribution(testdir, monkeypatch):\n \"\"\"Integration test for broken distributions with 'files' metadata being None (#5389)\"\"\"\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n\n class DummyEntryPoint:\n name = \"mytestplugin\"\n group = \"pytest11\"\n\n def load(self):\n return object()\n\n class Distribution:\n version = \"1.0\"\n files = None\n entry_points = (DummyEntryPoint(),)\n\n def distributions():\n return (Distribution(),)\n\n monkeypatch.setattr(importlib_metadata, \"distributions\", distributions)\n testdir.parseconfig()\n\n\n@pytest.mark.parametrize(\"block_it\", [True, False])\ndef test_plugin_preparse_prevents_setuptools_loading(testdir, monkeypatch, block_it):\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n\n plugin_module_placeholder = object()\n\n class DummyEntryPoint(object):\n name = \"mytestplugin\"\n group = \"pytest11\"\n\n def load(self):\n return plugin_module_placeholder\n\n class Distribution(object):\n version = \"1.0\"\n files = (\"foo.txt\",)\n entry_points = (DummyEntryPoint(),)\n\n def distributions():\n return (Distribution(),)\n\n monkeypatch.setattr(importlib_metadata, \"distributions\", distributions)\n args = (\"-p\", \"no:mytestplugin\") if block_it else ()\n config = testdir.parseconfig(*args)\n config.pluginmanager.import_plugin(\"mytestplugin\")\n if block_it:\n assert \"mytestplugin\" not in sys.modules\n assert config.pluginmanager.get_plugin(\"mytestplugin\") is None\n else:\n assert (\n config.pluginmanager.get_plugin(\"mytestplugin\") is plugin_module_placeholder\n )\n\n\n@pytest.mark.parametrize(\n \"parse_args,should_load\", [((\"-p\", \"mytestplugin\"), True), ((), False)]\n)\ndef test_disable_plugin_autoload(testdir, monkeypatch, parse_args, should_load):\n class DummyEntryPoint(object):\n project_name = name = \"mytestplugin\"\n group = \"pytest11\"\n version = \"1.0\"\n\n def load(self):\n return sys.modules[self.name]\n\n class Distribution(object):\n entry_points = (DummyEntryPoint(),)\n files = ()\n\n class PseudoPlugin(object):\n x = 42\n\n def distributions():\n return (Distribution(),)\n\n monkeypatch.setenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", \"1\")\n monkeypatch.setattr(importlib_metadata, \"distributions\", distributions)\n monkeypatch.setitem(sys.modules, \"mytestplugin\", PseudoPlugin())\n config = testdir.parseconfig(*parse_args)\n has_loaded = config.pluginmanager.get_plugin(\"mytestplugin\") is not None\n assert has_loaded == should_load\n\n\ndef test_cmdline_processargs_simple(testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_cmdline_preparse(args):\n args.append(\"-h\")\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*pytest*\", \"*-h*\"])\n\n\ndef test_invalid_options_show_extra_information(testdir):\n \"\"\"display extra information when pytest exits due to unrecognized\n options in the command-line\"\"\"\n testdir.makeini(\n \"\"\"\n [pytest]\n addopts = --invalid-option\n \"\"\"\n )\n result = testdir.runpytest()\n result.stderr.fnmatch_lines(\n [\n \"*error: unrecognized arguments: --invalid-option*\",\n \"* inifile: %s*\" % testdir.tmpdir.join(\"tox.ini\"),\n \"* rootdir: %s*\" % testdir.tmpdir,\n ]\n )\n\n\n@pytest.mark.parametrize(\n \"args\",\n [\n [\"dir1\", \"dir2\", \"-v\"],\n [\"dir1\", \"-v\", \"dir2\"],\n [\"dir2\", \"-v\", \"dir1\"],\n [\"-v\", \"dir2\", \"dir1\"],\n ],\n)\ndef test_consider_args_after_options_for_rootdir(testdir, args):\n \"\"\"\n Consider all arguments in the command-line for rootdir\n discovery, even if they happen to occur after an option. #949\n \"\"\"\n # replace \"dir1\" and \"dir2\" from \"args\" into their real directory\n root = testdir.tmpdir.mkdir(\"myroot\")\n d1 = root.mkdir(\"dir1\")\n d2 = root.mkdir(\"dir2\")\n for i, arg in enumerate(args):\n if arg == \"dir1\":\n args[i] = d1\n elif arg == \"dir2\":\n args[i] = d2\n with root.as_cwd():\n result = testdir.runpytest(*args)\n result.stdout.fnmatch_lines([\"*rootdir: *myroot\"])\n\n\n@pytest.mark.skipif(\"sys.platform == 'win32'\")\ndef test_toolongargs_issue224(testdir):\n result = testdir.runpytest(\"-m\", \"hello\" * 500)\n assert result.ret == EXIT_NOTESTSCOLLECTED\n\n\ndef test_config_in_subdirectory_colon_command_line_issue2148(testdir):\n conftest_source = \"\"\"\n def pytest_addoption(parser):\n parser.addini('foo', 'foo')\n \"\"\"\n\n testdir.makefile(\n \".ini\",\n **{\"pytest\": \"[pytest]\\nfoo = root\", \"subdir/pytest\": \"[pytest]\\nfoo = subdir\"}\n )\n\n testdir.makepyfile(\n **{\n \"conftest\": conftest_source,\n \"subdir/conftest\": conftest_source,\n \"subdir/test_foo\": \"\"\"\\\n def test_foo(pytestconfig):\n assert pytestconfig.getini('foo') == 'subdir'\n \"\"\",\n }\n )\n\n result = testdir.runpytest(\"subdir/test_foo.py::test_foo\")\n assert result.ret == 0\n\n\ndef test_notify_exception(testdir, capfd):\n config = testdir.parseconfig()\n with pytest.raises(ValueError) as excinfo:\n raise ValueError(1)\n config.notify_exception(excinfo, config.option)\n out, err = capfd.readouterr()\n assert \"ValueError\" in err\n\n class A(object):\n def pytest_internalerror(self, excrepr):\n return True\n\n config.pluginmanager.register(A())\n config.notify_exception(excinfo, config.option)\n out, err = capfd.readouterr()\n assert not err\n\n config = testdir.parseconfig(\"-p\", \"no:terminal\")\n with pytest.raises(ValueError) as excinfo:\n raise ValueError(1)\n config.notify_exception(excinfo, config.option)\n out, err = capfd.readouterr()\n assert \"ValueError\" in err\n\n\ndef test_no_terminal_discovery_error(testdir):\n testdir.makepyfile(\"raise TypeError('oops!')\")\n result = testdir.runpytest(\"-p\", \"no:terminal\", \"--collect-only\")\n assert result.ret == EXIT_INTERRUPTED\n\n\ndef test_load_initial_conftest_last_ordering(testdir, _config_for_test):\n pm = _config_for_test.pluginmanager\n\n class My(object):\n def pytest_load_initial_conftests(self):\n pass\n\n m = My()\n pm.register(m)\n hc = pm.hook.pytest_load_initial_conftests\n values = hc._nonwrappers + hc._wrappers\n expected = [\"_pytest.config\", \"test_config\", \"_pytest.capture\"]\n assert [x.function.__module__ for x in values] == expected\n\n\ndef test_get_plugin_specs_as_list():\n from _pytest.config import _get_plugin_specs_as_list\n\n with pytest.raises(pytest.UsageError):\n _get_plugin_specs_as_list({\"foo\"})\n with pytest.raises(pytest.UsageError):\n _get_plugin_specs_as_list(dict())\n\n assert _get_plugin_specs_as_list(None) == []\n assert _get_plugin_specs_as_list(\"\") == []\n assert _get_plugin_specs_as_list(\"foo\") == [\"foo\"]\n assert _get_plugin_specs_as_list(\"foo,bar\") == [\"foo\", \"bar\"]\n assert _get_plugin_specs_as_list([\"foo\", \"bar\"]) == [\"foo\", \"bar\"]\n assert _get_plugin_specs_as_list((\"foo\", \"bar\")) == [\"foo\", \"bar\"]\n\n\ndef test_collect_pytest_prefix_bug_integration(testdir):\n \"\"\"Integration test for issue #3775\"\"\"\n p = testdir.copy_example(\"config/collect_pytest_prefix\")\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"* 1 passed *\"])\n\n\ndef test_collect_pytest_prefix_bug(pytestconfig):\n \"\"\"Ensure we collect only actual functions from conftest files (#3775)\"\"\"\n\n class Dummy(object):\n class pytest_something(object):\n pass\n\n pm = pytestconfig.pluginmanager\n assert pm.parse_hookimpl_opts(Dummy(), \"pytest_something\") is None\n\n\nclass TestRootdir(object):\n def test_simple_noini(self, tmpdir):\n assert get_common_ancestor([tmpdir]) == tmpdir\n a = tmpdir.mkdir(\"a\")\n assert get_common_ancestor([a, tmpdir]) == tmpdir\n assert get_common_ancestor([tmpdir, a]) == tmpdir\n with tmpdir.as_cwd():\n assert get_common_ancestor([]) == tmpdir\n no_path = tmpdir.join(\"does-not-exist\")\n assert get_common_ancestor([no_path]) == tmpdir\n assert get_common_ancestor([no_path.join(\"a\")]) == tmpdir\n\n @pytest.mark.parametrize(\"name\", \"setup.cfg tox.ini pytest.ini\".split())\n def test_with_ini(self, tmpdir, name):\n inifile = tmpdir.join(name)\n inifile.write(\"[pytest]\\n\" if name != \"setup.cfg\" else \"[tool:pytest]\\n\")\n\n a = tmpdir.mkdir(\"a\")\n b = a.mkdir(\"b\")\n for args in ([tmpdir], [a], [b]):\n rootdir, inifile, inicfg = determine_setup(None, args)\n assert rootdir == tmpdir\n assert inifile == inifile\n rootdir, inifile, inicfg = determine_setup(None, [b, a])\n assert rootdir == tmpdir\n assert inifile == inifile\n\n @pytest.mark.parametrize(\"name\", \"setup.cfg tox.ini\".split())\n def test_pytestini_overrides_empty_other(self, tmpdir, name):\n inifile = tmpdir.ensure(\"pytest.ini\")\n a = tmpdir.mkdir(\"a\")\n a.ensure(name)\n rootdir, inifile, inicfg = determine_setup(None, [a])\n assert rootdir == tmpdir\n assert inifile == inifile\n\n def test_setuppy_fallback(self, tmpdir):\n a = tmpdir.mkdir(\"a\")\n a.ensure(\"setup.cfg\")\n tmpdir.ensure(\"setup.py\")\n rootdir, inifile, inicfg = determine_setup(None, [a])\n assert rootdir == tmpdir\n assert inifile is None\n assert inicfg == {}\n\n def test_nothing(self, tmpdir, monkeypatch):\n monkeypatch.chdir(str(tmpdir))\n rootdir, inifile, inicfg = determine_setup(None, [tmpdir])\n assert rootdir == tmpdir\n assert inifile is None\n assert inicfg == {}\n\n def test_with_specific_inifile(self, tmpdir):\n inifile = tmpdir.ensure(\"pytest.ini\")\n rootdir, inifile, inicfg = determine_setup(inifile, [tmpdir])\n assert rootdir == tmpdir\n\n\nclass TestOverrideIniArgs(object):\n @pytest.mark.parametrize(\"name\", \"setup.cfg tox.ini pytest.ini\".split())\n def test_override_ini_names(self, testdir, name):\n section = \"[pytest]\" if name != \"setup.cfg\" else \"[tool:pytest]\"\n testdir.tmpdir.join(name).write(\n textwrap.dedent(\n \"\"\"\n {section}\n custom = 1.0\"\"\".format(\n section=section\n )\n )\n )\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"custom\", \"\")\"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_pass(pytestconfig):\n ini_val = pytestconfig.getini(\"custom\")\n print('\\\\ncustom_option:%s\\\\n' % ini_val)\"\"\"\n )\n\n result = testdir.runpytest(\"--override-ini\", \"custom=2.0\", \"-s\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"custom_option:2.0\"])\n\n result = testdir.runpytest(\n \"--override-ini\", \"custom=2.0\", \"--override-ini=custom=3.0\", \"-s\"\n )\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"custom_option:3.0\"])\n\n def test_override_ini_pathlist(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"paths\", \"my new ini value\", type=\"pathlist\")\"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n paths=blah.py\"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import py.path\n def test_pathlist(pytestconfig):\n config_paths = pytestconfig.getini(\"paths\")\n print(config_paths)\n for cpf in config_paths:\n print('\\\\nuser_path:%s' % cpf.basename)\"\"\"\n )\n result = testdir.runpytest(\n \"--override-ini\", \"paths=foo/bar1.py foo/bar2.py\", \"-s\"\n )\n result.stdout.fnmatch_lines([\"user_path:bar1.py\", \"user_path:bar2.py\"])\n\n def test_override_multiple_and_default(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n addini = parser.addini\n addini(\"custom_option_1\", \"\", default=\"o1\")\n addini(\"custom_option_2\", \"\", default=\"o2\")\n addini(\"custom_option_3\", \"\", default=False, type=\"bool\")\n addini(\"custom_option_4\", \"\", default=True, type=\"bool\")\"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n custom_option_1=custom_option_1\n custom_option_2=custom_option_2\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_multiple_options(pytestconfig):\n prefix = \"custom_option\"\n for x in range(1, 5):\n ini_value=pytestconfig.getini(\"%s_%d\" % (prefix, x))\n print('\\\\nini%d:%s' % (x, ini_value))\n \"\"\"\n )\n result = testdir.runpytest(\n \"--override-ini\",\n \"custom_option_1=fulldir=/tmp/user1\",\n \"-o\",\n \"custom_option_2=url=/tmp/user2?a=b&d=e\",\n \"-o\",\n \"custom_option_3=True\",\n \"-o\",\n \"custom_option_4=no\",\n \"-s\",\n )\n result.stdout.fnmatch_lines(\n [\n \"ini1:fulldir=/tmp/user1\",\n \"ini2:url=/tmp/user2?a=b&d=e\",\n \"ini3:True\",\n \"ini4:False\",\n ]\n )\n\n def test_override_ini_usage_error_bad_style(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n xdist_strict=False\n \"\"\"\n )\n result = testdir.runpytest(\"--override-ini\", \"xdist_strict True\", \"-s\")\n result.stderr.fnmatch_lines([\"*ERROR* *expects option=value*\"])\n\n @pytest.mark.parametrize(\"with_ini\", [True, False])\n def test_override_ini_handled_asap(self, testdir, with_ini):\n \"\"\"-o should be handled as soon as possible and always override what's in ini files (#2238)\"\"\"\n if with_ini:\n testdir.makeini(\n \"\"\"\n [pytest]\n python_files=test_*.py\n \"\"\"\n )\n testdir.makepyfile(\n unittest_ini_handle=\"\"\"\n def test():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--override-ini\", \"python_files=unittest_*.py\")\n result.stdout.fnmatch_lines([\"*1 passed in*\"])\n\n def test_with_arg_outside_cwd_without_inifile(self, tmpdir, monkeypatch):\n monkeypatch.chdir(str(tmpdir))\n a = tmpdir.mkdir(\"a\")\n b = tmpdir.mkdir(\"b\")\n rootdir, inifile, inicfg = determine_setup(None, [a, b])\n assert rootdir == tmpdir\n assert inifile is None\n\n def test_with_arg_outside_cwd_with_inifile(self, tmpdir):\n a = tmpdir.mkdir(\"a\")\n b = tmpdir.mkdir(\"b\")\n inifile = a.ensure(\"pytest.ini\")\n rootdir, parsed_inifile, inicfg = determine_setup(None, [a, b])\n assert rootdir == a\n assert inifile == parsed_inifile\n\n @pytest.mark.parametrize(\"dirs\", ([], [\"does-not-exist\"], [\"a/does-not-exist\"]))\n def test_with_non_dir_arg(self, dirs, tmpdir):\n with tmpdir.ensure(dir=True).as_cwd():\n rootdir, inifile, inicfg = determine_setup(None, dirs)\n assert rootdir == tmpdir\n assert inifile is None\n\n def test_with_existing_file_in_subdir(self, tmpdir):\n a = tmpdir.mkdir(\"a\")\n a.ensure(\"exist\")\n with tmpdir.as_cwd():\n rootdir, inifile, inicfg = determine_setup(None, [\"a/exist\"])\n assert rootdir == tmpdir\n assert inifile is None\n\n def test_addopts_before_initini(self, monkeypatch, _config_for_test, _sys_snapshot):\n cache_dir = \".custom_cache\"\n monkeypatch.setenv(\"PYTEST_ADDOPTS\", \"-o cache_dir=%s\" % cache_dir)\n config = _config_for_test\n config._preparse([], addopts=True)\n assert config._override_ini == [\"cache_dir=%s\" % cache_dir]\n\n def test_addopts_from_env_not_concatenated(self, monkeypatch, _config_for_test):\n \"\"\"PYTEST_ADDOPTS should not take values from normal args (#4265).\"\"\"\n monkeypatch.setenv(\"PYTEST_ADDOPTS\", \"-o\")\n config = _config_for_test\n with pytest.raises(UsageError) as excinfo:\n config._preparse([\"cache_dir=ignored\"], addopts=True)\n assert (\n \"error: argument -o/--override-ini: expected one argument (via PYTEST_ADDOPTS)\"\n in excinfo.value.args[0]\n )\n\n def test_addopts_from_ini_not_concatenated(self, testdir):\n \"\"\"addopts from ini should not take values from normal args (#4265).\"\"\"\n testdir.makeini(\n \"\"\"\n [pytest]\n addopts=-o\n \"\"\"\n )\n result = testdir.runpytest(\"cache_dir=ignored\")\n result.stderr.fnmatch_lines(\n [\n \"%s: error: argument -o/--override-ini: expected one argument (via addopts config)\"\n % (testdir.request.config._parser.optparser.prog,)\n ]\n )\n assert result.ret == _pytest.main.EXIT_USAGEERROR\n\n def test_override_ini_does_not_contain_paths(self, _config_for_test, _sys_snapshot):\n \"\"\"Check that -o no longer swallows all options after it (#3103)\"\"\"\n config = _config_for_test\n config._preparse([\"-o\", \"cache_dir=/cache\", \"/some/test/path\"])\n assert config._override_ini == [\"cache_dir=/cache\"]\n\n def test_multiple_override_ini_options(self, testdir, request):\n \"\"\"Ensure a file path following a '-o' option does not generate an error (#3103)\"\"\"\n testdir.makepyfile(\n **{\n \"conftest.py\": \"\"\"\n def pytest_addoption(parser):\n parser.addini('foo', default=None, help='some option')\n parser.addini('bar', default=None, help='some option')\n \"\"\",\n \"test_foo.py\": \"\"\"\n def test(pytestconfig):\n assert pytestconfig.getini('foo') == '1'\n assert pytestconfig.getini('bar') == '0'\n \"\"\",\n \"test_bar.py\": \"\"\"\n def test():\n assert False\n \"\"\",\n }\n )\n result = testdir.runpytest(\"-o\", \"foo=1\", \"-o\", \"bar=0\", \"test_foo.py\")\n assert \"ERROR:\" not in result.stderr.str()\n result.stdout.fnmatch_lines([\"collected 1 item\", \"*= 1 passed in *=\"])\n\n\ndef test_help_via_addopts(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n addopts = --unknown-option-should-allow-for-help --help\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n [\n \"usage: *\",\n \"positional arguments:\",\n # Displays full/default help.\n \"to see available markers type: pytest --markers\",\n ]\n )\n\n\ndef test_help_and_version_after_argument_error(testdir):\n testdir.makeconftest(\n \"\"\"\n def validate(arg):\n raise argparse.ArgumentTypeError(\"argerror\")\n\n def pytest_addoption(parser):\n group = parser.getgroup('cov')\n group.addoption(\n \"--invalid-option-should-allow-for-help\",\n type=validate,\n )\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n addopts = --invalid-option-should-allow-for-help\n \"\"\"\n )\n result = testdir.runpytest(\"--help\")\n result.stdout.fnmatch_lines(\n [\n \"usage: *\",\n \"positional arguments:\",\n \"NOTE: displaying only minimal help due to UsageError.\",\n ]\n )\n result.stderr.fnmatch_lines(\n [\n \"ERROR: usage: *\",\n \"%s: error: argument --invalid-option-should-allow-for-help: expected one argument\"\n % (testdir.request.config._parser.optparser.prog,),\n ]\n )\n # Does not display full/default help.\n assert \"to see available markers type: pytest --markers\" not in result.stdout.lines\n assert result.ret == EXIT_USAGEERROR\n\n result = testdir.runpytest(\"--version\")\n result.stderr.fnmatch_lines(\n [\"*pytest*{}*imported from*\".format(pytest.__version__)]\n )\n assert result.ret == EXIT_USAGEERROR\n\n\ndef test_config_does_not_load_blocked_plugin_from_args(testdir):\n \"\"\"This tests that pytest's config setup handles \"-p no:X\".\"\"\"\n p = testdir.makepyfile(\"def test(capfd): pass\")\n result = testdir.runpytest(str(p), \"-pno:capture\")\n result.stdout.fnmatch_lines([\"E fixture 'capfd' not found\"])\n assert result.ret == EXIT_TESTSFAILED\n\n result = testdir.runpytest(str(p), \"-pno:capture\", \"-s\")\n result.stderr.fnmatch_lines([\"*: error: unrecognized arguments: -s\"])\n assert result.ret == EXIT_USAGEERROR\n\n\n@pytest.mark.parametrize(\n \"plugin\",\n [\n x\n for x in _pytest.config.default_plugins\n if x not in _pytest.config.essential_plugins\n ],\n)\ndef test_config_blocked_default_plugins(testdir, plugin):\n if plugin == \"debugging\":\n # Fixed in xdist master (after 1.27.0).\n # https://github.com/pytest-dev/pytest-xdist/pull/422\n try:\n import xdist # noqa: F401\n except ImportError:\n pass\n else:\n pytest.skip(\"does not work with xdist currently\")\n\n p = testdir.makepyfile(\"def test(): pass\")\n result = testdir.runpytest(str(p), \"-pno:%s\" % plugin)\n\n if plugin == \"python\":\n assert result.ret == EXIT_USAGEERROR\n result.stderr.fnmatch_lines(\n [\n \"ERROR: not found: */test_config_blocked_default_plugins.py\",\n \"(no name '*/test_config_blocked_default_plugins.py' in any of [])\",\n ]\n )\n return\n\n assert result.ret == EXIT_OK\n if plugin != \"terminal\":\n result.stdout.fnmatch_lines([\"* 1 passed in *\"])\n\n p = testdir.makepyfile(\"def test(): assert 0\")\n result = testdir.runpytest(str(p), \"-pno:%s\" % plugin)\n assert result.ret == EXIT_TESTSFAILED\n if plugin != \"terminal\":\n result.stdout.fnmatch_lines([\"* 1 failed in *\"])\n else:\n assert result.stdout.lines == [\"\"]\n"},{"className":"TestParseIni","col":0,"comment":"null","endLoc":151,"id":5287,"nodeType":"Class","startLoc":25,"text":"class TestParseIni(object):\n @pytest.mark.parametrize(\n \"section, filename\", [(\"pytest\", \"pytest.ini\"), (\"tool:pytest\", \"setup.cfg\")]\n )\n def test_getcfg_and_config(self, testdir, tmpdir, section, filename):\n sub = tmpdir.mkdir(\"sub\")\n sub.chdir()\n tmpdir.join(filename).write(\n textwrap.dedent(\n \"\"\"\\\n [{section}]\n name = value\n \"\"\".format(\n section=section\n )\n )\n )\n rootdir, inifile, cfg = getcfg([sub])\n assert cfg[\"name\"] == \"value\"\n config = testdir.parseconfigure(sub)\n assert config.inicfg[\"name\"] == \"value\"\n\n def test_getcfg_empty_path(self):\n \"\"\"correctly handle zero length arguments (a la pytest '')\"\"\"\n getcfg([\"\"])\n\n def test_setupcfg_uses_toolpytest_with_pytest(self, testdir):\n p1 = testdir.makepyfile(\"def test(): pass\")\n testdir.makefile(\n \".cfg\",\n setup=\"\"\"\n [tool:pytest]\n testpaths=%s\n [pytest]\n testpaths=ignored\n \"\"\"\n % p1.basename,\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*, inifile: setup.cfg, *\", \"* 1 passed in *\"])\n assert result.ret == 0\n\n def test_append_parse_args(self, testdir, tmpdir, monkeypatch):\n monkeypatch.setenv(\"PYTEST_ADDOPTS\", '--color no -rs --tb=\"short\"')\n tmpdir.join(\"pytest.ini\").write(\n textwrap.dedent(\n \"\"\"\\\n [pytest]\n addopts = --verbose\n \"\"\"\n )\n )\n config = testdir.parseconfig(tmpdir)\n assert config.option.color == \"no\"\n assert config.option.reportchars == \"s\"\n assert config.option.tbstyle == \"short\"\n assert config.option.verbose\n\n def test_tox_ini_wrong_version(self, testdir):\n testdir.makefile(\n \".ini\",\n tox=\"\"\"\n [pytest]\n minversion=9.0\n \"\"\",\n )\n result = testdir.runpytest()\n assert result.ret != 0\n result.stderr.fnmatch_lines([\"*tox.ini:2*requires*9.0*actual*\"])\n\n @pytest.mark.parametrize(\n \"section, name\",\n [(\"tool:pytest\", \"setup.cfg\"), (\"pytest\", \"tox.ini\"), (\"pytest\", \"pytest.ini\")],\n )\n def test_ini_names(self, testdir, name, section):\n testdir.tmpdir.join(name).write(\n textwrap.dedent(\n \"\"\"\n [{section}]\n minversion = 1.0\n \"\"\".format(\n section=section\n )\n )\n )\n config = testdir.parseconfig()\n assert config.getini(\"minversion\") == \"1.0\"\n\n def test_toxini_before_lower_pytestini(self, testdir):\n sub = testdir.tmpdir.mkdir(\"sub\")\n sub.join(\"tox.ini\").write(\n textwrap.dedent(\n \"\"\"\n [pytest]\n minversion = 2.0\n \"\"\"\n )\n )\n testdir.tmpdir.join(\"pytest.ini\").write(\n textwrap.dedent(\n \"\"\"\n [pytest]\n minversion = 1.5\n \"\"\"\n )\n )\n config = testdir.parseconfigure(sub)\n assert config.getini(\"minversion\") == \"2.0\"\n\n def test_ini_parse_error(self, testdir):\n testdir.tmpdir.join(\"pytest.ini\").write(\"addopts = -x\")\n result = testdir.runpytest()\n assert result.ret != 0\n result.stderr.fnmatch_lines([\"ERROR: *pytest.ini:1: no section header defined\"])\n\n @pytest.mark.xfail(reason=\"probably not needed\")\n def test_confcutdir(self, testdir):\n sub = testdir.mkdir(\"sub\")\n sub.chdir()\n testdir.makeini(\n \"\"\"\n [pytest]\n addopts = --qwe\n \"\"\"\n )\n result = testdir.inline_run(\"--confcutdir=.\")\n assert result.ret == 0"},{"col":4,"comment":"null","endLoc":45,"header":"@pytest.mark.parametrize(\n \"section, filename\", [(\"pytest\", \"pytest.ini\"), (\"tool","id":5288,"name":"test_getcfg_and_config","nodeType":"Function","startLoc":26,"text":"@pytest.mark.parametrize(\n \"section, filename\", [(\"pytest\", \"pytest.ini\"), (\"tool:pytest\", \"setup.cfg\")]\n )\n def test_getcfg_and_config(self, testdir, tmpdir, section, filename):\n sub = tmpdir.mkdir(\"sub\")\n sub.chdir()\n tmpdir.join(filename).write(\n textwrap.dedent(\n \"\"\"\\\n [{section}]\n name = value\n \"\"\".format(\n section=section\n )\n )\n )\n rootdir, inifile, cfg = getcfg([sub])\n assert cfg[\"name\"] == \"value\"\n config = testdir.parseconfigure(sub)\n assert config.inicfg[\"name\"] == \"value\""},{"id":5289,"name":"usage.rst","nodeType":"TextFile","path":"doc/en","text":"\n.. _usage:\n\nUsage and Invocations\n==========================================\n\n\n.. _cmdline:\n\nCalling pytest through ``python -m pytest``\n-----------------------------------------------------\n\n\n\nYou can invoke testing through the Python interpreter from the command line:\n\n.. code-block:: text\n\n python -m pytest [...]\n\nThis is almost equivalent to invoking the command line script ``pytest [...]``\ndirectly, except that calling via ``python`` will also add the current directory to ``sys.path``.\n\nPossible exit codes\n--------------------------------------------------------------\n\nRunning ``pytest`` can result in six different exit codes:\n\n:Exit code 0: All tests were collected and passed successfully\n:Exit code 1: Tests were collected and run but some of the tests failed\n:Exit code 2: Test execution was interrupted by the user\n:Exit code 3: Internal error happened while executing tests\n:Exit code 4: pytest command line usage error\n:Exit code 5: No tests were collected\n\nGetting help on version, option names, environment variables\n--------------------------------------------------------------\n\n.. code-block:: bash\n\n pytest --version # shows where pytest was imported from\n pytest --fixtures # show available builtin function arguments\n pytest -h | --help # show help on command line and config file options\n\n\n.. _maxfail:\n\nStopping after the first (or N) failures\n---------------------------------------------------\n\nTo stop the testing process after the first (N) failures:\n\n.. code-block:: bash\n\n pytest -x # stop after first failure\n pytest --maxfail=2 # stop after two failures\n\n.. _select-tests:\n\nSpecifying tests / selecting tests\n---------------------------------------------------\n\nPytest supports several ways to run and select tests from the command-line.\n\n**Run tests in a module**\n\n.. code-block:: bash\n\n pytest test_mod.py\n\n**Run tests in a directory**\n\n.. code-block:: bash\n\n pytest testing/\n\n**Run tests by keyword expressions**\n\n.. code-block:: bash\n\n pytest -k \"MyClass and not method\"\n\nThis will run tests which contain names that match the given *string expression*, which can\ninclude Python operators that use filenames, class names and function names as variables.\nThe example above will run ``TestMyClass.test_something`` but not ``TestMyClass.test_method_simple``.\n\n.. _nodeids:\n\n**Run tests by node ids**\n\nEach collected test is assigned a unique ``nodeid`` which consist of the module filename followed\nby specifiers like class names, function names and parameters from parametrization, separated by ``::`` characters.\n\nTo run a specific test within a module:\n\n.. code-block:: bash\n\n pytest test_mod.py::test_func\n\n\nAnother example specifying a test method in the command line:\n\n.. code-block:: bash\n\n pytest test_mod.py::TestClass::test_method\n\n**Run tests by marker expressions**\n\n.. code-block:: bash\n\n pytest -m slow\n\nWill run all tests which are decorated with the ``@pytest.mark.slow`` decorator.\n\nFor more information see :ref:`marks `.\n\n**Run tests from packages**\n\n.. code-block:: bash\n\n pytest --pyargs pkg.testing\n\nThis will import ``pkg.testing`` and use its filesystem location to find and run tests from.\n\n\nModifying Python traceback printing\n----------------------------------------------\n\nExamples for modifying traceback printing:\n\n.. code-block:: bash\n\n pytest --showlocals # show local variables in tracebacks\n pytest -l # show local variables (shortcut)\n\n pytest --tb=auto # (default) 'long' tracebacks for the first and last\n # entry, but 'short' style for the other entries\n pytest --tb=long # exhaustive, informative traceback formatting\n pytest --tb=short # shorter traceback format\n pytest --tb=line # only one line per failure\n pytest --tb=native # Python standard library formatting\n pytest --tb=no # no traceback at all\n\nThe ``--full-trace`` causes very long traces to be printed on error (longer\nthan ``--tb=long``). It also ensures that a stack trace is printed on\n**KeyboardInterrupt** (Ctrl+C).\nThis is very useful if the tests are taking too long and you interrupt them\nwith Ctrl+C to find out where the tests are *hanging*. By default no output\nwill be shown (because KeyboardInterrupt is caught by pytest). By using this\noption you make sure a trace is shown.\n\n\n.. _`pytest.detailed_failed_tests_usage`:\n\nDetailed summary report\n-----------------------\n\n\n\nThe ``-r`` flag can be used to display a \"short test summary info\" at the end of the test session,\nmaking it easy in large test suites to get a clear picture of all failures, skips, xfails, etc.\n\nExample:\n\n.. code-block:: python\n\n # content of test_example.py\n import pytest\n\n\n @pytest.fixture\n def error_fixture():\n assert 0\n\n\n def test_ok():\n print(\"ok\")\n\n\n def test_fail():\n assert 0\n\n\n def test_error(error_fixture):\n pass\n\n\n def test_skip():\n pytest.skip(\"skipping this test\")\n\n\n def test_xfail():\n pytest.xfail(\"xfailing this test\")\n\n\n @pytest.mark.xfail(reason=\"always xfail\")\n def test_xpass():\n pass\n\n\n.. code-block:: pytest\n\n $ pytest -ra\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 6 items\n\n test_example.py .FEsxX [100%]\n\n ================================== ERRORS ==================================\n _______________________ ERROR at setup of test_error _______________________\n\n @pytest.fixture\n def error_fixture():\n > assert 0\n E assert 0\n\n test_example.py:6: AssertionError\n ================================= FAILURES =================================\n ________________________________ test_fail _________________________________\n\n def test_fail():\n > assert 0\n E assert 0\n\n test_example.py:14: AssertionError\n ========================= short test summary info ==========================\n SKIPPED [1] $REGENDOC_TMPDIR/test_example.py:23: skipping this test\n XFAIL test_example.py::test_xfail\n reason: xfailing this test\n XPASS test_example.py::test_xpass always xfail\n ERROR test_example.py::test_error - assert 0\n FAILED test_example.py::test_fail - assert 0\n = 1 failed, 1 passed, 1 skipped, 1 xfailed, 1 xpassed, 1 error in 0.12 seconds =\n\nThe ``-r`` options accepts a number of characters after it, with ``a`` used\nabove meaning \"all except passes\".\n\nHere is the full list of available characters that can be used:\n\n - ``f`` - failed\n - ``E`` - error\n - ``s`` - skipped\n - ``x`` - xfailed\n - ``X`` - xpassed\n - ``p`` - passed\n - ``P`` - passed with output\n - ``a`` - all except ``pP``\n - ``A`` - all\n\nMore than one character can be used, so for example to only see failed and skipped tests, you can execute:\n\n.. code-block:: pytest\n\n $ pytest -rfs\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 6 items\n\n test_example.py .FEsxX [100%]\n\n ================================== ERRORS ==================================\n _______________________ ERROR at setup of test_error _______________________\n\n @pytest.fixture\n def error_fixture():\n > assert 0\n E assert 0\n\n test_example.py:6: AssertionError\n ================================= FAILURES =================================\n ________________________________ test_fail _________________________________\n\n def test_fail():\n > assert 0\n E assert 0\n\n test_example.py:14: AssertionError\n ========================= short test summary info ==========================\n FAILED test_example.py::test_fail - assert 0\n SKIPPED [1] $REGENDOC_TMPDIR/test_example.py:23: skipping this test\n = 1 failed, 1 passed, 1 skipped, 1 xfailed, 1 xpassed, 1 error in 0.12 seconds =\n\nUsing ``p`` lists the passing tests, whilst ``P`` adds an extra section \"PASSES\" with those tests that passed but had\ncaptured output:\n\n.. code-block:: pytest\n\n $ pytest -rpP\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 6 items\n\n test_example.py .FEsxX [100%]\n\n ================================== ERRORS ==================================\n _______________________ ERROR at setup of test_error _______________________\n\n @pytest.fixture\n def error_fixture():\n > assert 0\n E assert 0\n\n test_example.py:6: AssertionError\n ================================= FAILURES =================================\n ________________________________ test_fail _________________________________\n\n def test_fail():\n > assert 0\n E assert 0\n\n test_example.py:14: AssertionError\n ================================== PASSES ==================================\n _________________________________ test_ok __________________________________\n --------------------------- Captured stdout call ---------------------------\n ok\n ========================= short test summary info ==========================\n PASSED test_example.py::test_ok\n = 1 failed, 1 passed, 1 skipped, 1 xfailed, 1 xpassed, 1 error in 0.12 seconds =\n\n.. _pdb-option:\n\nDropping to PDB_ (Python Debugger) on failures\n-----------------------------------------------\n\n.. _PDB: http://docs.python.org/library/pdb.html\n\nPython comes with a builtin Python debugger called PDB_. ``pytest``\nallows one to drop into the PDB_ prompt via a command line option:\n\n.. code-block:: bash\n\n pytest --pdb\n\nThis will invoke the Python debugger on every failure (or KeyboardInterrupt).\nOften you might only want to do this for the first failing test to understand\na certain failure situation:\n\n.. code-block:: bash\n\n pytest -x --pdb # drop to PDB on first failure, then end test session\n pytest --pdb --maxfail=3 # drop to PDB for first three failures\n\nNote that on any failure the exception information is stored on\n``sys.last_value``, ``sys.last_type`` and ``sys.last_traceback``. In\ninteractive use, this allows one to drop into postmortem debugging with\nany debug tool. One can also manually access the exception information,\nfor example::\n\n >>> import sys\n >>> sys.last_traceback.tb_lineno\n 42\n >>> sys.last_value\n AssertionError('assert result == \"ok\"',)\n\n.. _trace-option:\n\nDropping to PDB_ (Python Debugger) at the start of a test\n----------------------------------------------------------\n\n\n``pytest`` allows one to drop into the PDB_ prompt immediately at the start of each test via a command line option:\n\n.. code-block:: bash\n\n pytest --trace\n\nThis will invoke the Python debugger at the start of every test.\n\n.. _breakpoints:\n\nSetting breakpoints\n-------------------\n\n.. versionadded: 2.4.0\n\nTo set a breakpoint in your code use the native Python ``import pdb;pdb.set_trace()`` call\nin your code and pytest automatically disables its output capture for that test:\n\n* Output capture in other tests is not affected.\n* Any prior test output that has already been captured and will be processed as\n such.\n* Output capture gets resumed when ending the debugger session (via the\n ``continue`` command).\n\n\n.. _`breakpoint-builtin`:\n\nUsing the builtin breakpoint function\n-------------------------------------\n\nPython 3.7 introduces a builtin ``breakpoint()`` function.\nPytest supports the use of ``breakpoint()`` with the following behaviours:\n\n - When ``breakpoint()`` is called and ``PYTHONBREAKPOINT`` is set to the default value, pytest will use the custom internal PDB trace UI instead of the system default ``Pdb``.\n - When tests are complete, the system will default back to the system ``Pdb`` trace UI.\n - With ``--pdb`` passed to pytest, the custom internal Pdb trace UI is used with both ``breakpoint()`` and failed tests/unhandled exceptions.\n - ``--pdbcls`` can be used to specify a custom debugger class.\n\n.. _durations:\n\nProfiling test execution duration\n-------------------------------------\n\n.. versionadded: 2.2\n\nTo get a list of the slowest 10 test durations:\n\n.. code-block:: bash\n\n pytest --durations=10\n\nBy default, pytest will not show test durations that are too small (<0.01s) unless ``-vv`` is passed on the command-line.\n\nCreating JUnitXML format files\n----------------------------------------------------\n\nTo create result files which can be read by Jenkins_ or other Continuous\nintegration servers, use this invocation:\n\n.. code-block:: bash\n\n pytest --junitxml=path\n\nto create an XML file at ``path``.\n\n\n\nTo set the name of the root test suite xml item, you can configure the ``junit_suite_name`` option in your config file:\n\n.. code-block:: ini\n\n [pytest]\n junit_suite_name = my_suite\n\n.. versionadded:: 4.0\n\nJUnit XML specification seems to indicate that ``\"time\"`` attribute\nshould report total test execution times, including setup and teardown\n(`1 `_, `2\n`_).\nIt is the default pytest behavior. To report just call durations\ninstead, configure the ``junit_duration_report`` option like this:\n\n.. code-block:: ini\n\n [pytest]\n junit_duration_report = call\n\n.. _record_property example:\n\nrecord_property\n^^^^^^^^^^^^^^^\n\nIf you want to log additional information for a test, you can use the\n``record_property`` fixture:\n\n.. code-block:: python\n\n def test_function(record_property):\n record_property(\"example_key\", 1)\n assert True\n\nThis will add an extra property ``example_key=\"1\"`` to the generated\n``testcase`` tag:\n\n.. code-block:: xml\n\n \n \n \n \n \n\nAlternatively, you can integrate this functionality with custom markers:\n\n.. code-block:: python\n\n # content of conftest.py\n\n\n def pytest_collection_modifyitems(session, config, items):\n for item in items:\n for marker in item.iter_markers(name=\"test_id\"):\n test_id = marker.args[0]\n item.user_properties.append((\"test_id\", test_id))\n\nAnd in your tests:\n\n.. code-block:: python\n\n # content of test_function.py\n import pytest\n\n\n @pytest.mark.test_id(1501)\n def test_function():\n assert True\n\nWill result in:\n\n.. code-block:: xml\n\n \n \n \n \n \n\n.. warning::\n\n Please note that using this feature will break schema verifications for the latest JUnitXML schema.\n This might be a problem when used with some CI servers.\n\nrecord_xml_attribute\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n\n\nTo add an additional xml attribute to a testcase element, you can use\n``record_xml_attribute`` fixture. This can also be used to override existing values:\n\n.. code-block:: python\n\n def test_function(record_xml_attribute):\n record_xml_attribute(\"assertions\", \"REQ-1234\")\n record_xml_attribute(\"classname\", \"custom_classname\")\n print(\"hello world\")\n assert True\n\nUnlike ``record_property``, this will not add a new child element.\nInstead, this will add an attribute ``assertions=\"REQ-1234\"`` inside the generated\n``testcase`` tag and override the default ``classname`` with ``\"classname=custom_classname\"``:\n\n.. code-block:: xml\n\n \n \n hello world\n \n \n\n.. warning::\n\n ``record_xml_attribute`` is an experimental feature, and its interface might be replaced\n by something more powerful and general in future versions. The\n functionality per-se will be kept, however.\n\n Using this over ``record_xml_property`` can help when using ci tools to parse the xml report.\n However, some parsers are quite strict about the elements and attributes that are allowed.\n Many tools use an xsd schema (like the example below) to validate incoming xml.\n Make sure you are using attribute names that are allowed by your parser.\n\n Below is the Scheme used by Jenkins to validate the XML report:\n\n .. code-block:: xml\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n.. warning::\n\n Please note that using this feature will break schema verifications for the latest JUnitXML schema.\n This might be a problem when used with some CI servers.\n\n.. _record_testsuite_property example:\n\nrecord_testsuite_property\n^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. versionadded:: 4.5\n\nIf you want to add a properties node at the test-suite level, which may contains properties\nthat are relevant to all tests, you can use the ``record_testsuite_property`` session-scoped fixture:\n\nThe ``record_testsuite_property`` session-scoped fixture can be used to add properties relevant\nto all tests.\n\n.. code-block:: python\n\n import pytest\n\n\n @pytest.fixture(scope=\"session\", autouse=True)\n def log_global_env_facts(record_testsuite_property):\n record_testsuite_property(\"ARCH\", \"PPC\")\n record_testsuite_property(\"STORAGE_TYPE\", \"CEPH\")\n\n\n class TestMe(object):\n def test_foo(self):\n assert True\n\nThe fixture is a callable which receives ``name`` and ``value`` of a ```` tag\nadded at the test-suite level of the generated xml:\n\n.. code-block:: xml\n\n \n \n \n \n \n \n \n\n``name`` must be a string, ``value`` will be converted to a string and properly xml-escaped.\n\nThe generated XML is compatible with the latest ``xunit`` standard, contrary to `record_property`_\nand `record_xml_attribute`_.\n\n\nCreating resultlog format files\n----------------------------------------------------\n\n\n\n This option is rarely used and is scheduled for removal in 5.0.\n\n See `the deprecation docs `__\n for more information.\n\nTo create plain-text machine-readable result files you can issue:\n\n.. code-block:: bash\n\n pytest --resultlog=path\n\nand look at the content at the ``path`` location. Such files are used e.g.\nby the `PyPy-test`_ web page to show test results over several revisions.\n\n.. _`PyPy-test`: http://buildbot.pypy.org/summary\n\n\nSending test report to online pastebin service\n-----------------------------------------------------\n\n**Creating a URL for each test failure**:\n\n.. code-block:: bash\n\n pytest --pastebin=failed\n\nThis will submit test run information to a remote Paste service and\nprovide a URL for each failure. You may select tests as usual or add\nfor example ``-x`` if you only want to send one particular failure.\n\n**Creating a URL for a whole test session log**:\n\n.. code-block:: bash\n\n pytest --pastebin=all\n\nCurrently only pasting to the http://bpaste.net service is implemented.\n\nEarly loading plugins\n---------------------\n\nYou can early-load plugins (internal and external) explicitly in the command-line with the ``-p`` option::\n\n pytest -p mypluginmodule\n\nThe option receives a ``name`` parameter, which can be:\n\n* A full module dotted name, for example ``myproject.plugins``. This dotted name must be importable.\n* The entry-point name of a plugin. This is the name passed to ``setuptools`` when the plugin is\n registered. For example to early-load the `pytest-cov `__ plugin you can use::\n\n pytest -p pytest_cov\n\n\nDisabling plugins\n-----------------\n\nTo disable loading specific plugins at invocation time, use the ``-p`` option\ntogether with the prefix ``no:``.\n\nExample: to disable loading the plugin ``doctest``, which is responsible for\nexecuting doctest tests from text files, invoke pytest like this:\n\n.. code-block:: bash\n\n pytest -p no:doctest\n\n.. _`pytest.main-usage`:\n\nCalling pytest from Python code\n----------------------------------------------------\n\n\n\nYou can invoke ``pytest`` from Python code directly::\n\n pytest.main()\n\nthis acts as if you would call \"pytest\" from the command line.\nIt will not raise ``SystemExit`` but return the exitcode instead.\nYou can pass in options and arguments::\n\n pytest.main(['-x', 'mytestdir'])\n\nYou can specify additional plugins to ``pytest.main``::\n\n # content of myinvoke.py\n import pytest\n class MyPlugin(object):\n def pytest_sessionfinish(self):\n print(\"*** test run reporting finishing\")\n\n pytest.main([\"-qq\"], plugins=[MyPlugin()])\n\nRunning it will show that ``MyPlugin`` was added and its\nhook was invoked:\n\n.. code-block:: pytest\n\n $ python myinvoke.py\n .FEsxX. [100%]*** test run reporting finishing\n\n ================================== ERRORS ==================================\n _______________________ ERROR at setup of test_error _______________________\n\n @pytest.fixture\n def error_fixture():\n > assert 0\n E assert 0\n\n test_example.py:6: AssertionError\n ================================= FAILURES =================================\n ________________________________ test_fail _________________________________\n\n def test_fail():\n > assert 0\n E assert 0\n\n test_example.py:14: AssertionError\n\n.. note::\n\n Calling ``pytest.main()`` will result in importing your tests and any modules\n that they import. Due to the caching mechanism of python's import system,\n making subsequent calls to ``pytest.main()`` from the same process will not\n reflect changes to those files between the calls. For this reason, making\n multiple calls to ``pytest.main()`` from the same process (in order to re-run\n tests, for example) is not recommended.\n\n\n.. include:: links.inc\n"},{"col":4,"comment":"correctly handle zero length arguments (a la pytest '')","endLoc":49,"header":"def test_getcfg_empty_path(self)","id":5291,"name":"test_getcfg_empty_path","nodeType":"Function","startLoc":47,"text":"def test_getcfg_empty_path(self):\n \"\"\"correctly handle zero length arguments (a la pytest '')\"\"\"\n getcfg([\"\"])"},{"col":4,"comment":"null","endLoc":65,"header":"def test_setupcfg_uses_toolpytest_with_pytest(self, testdir)","id":5292,"name":"test_setupcfg_uses_toolpytest_with_pytest","nodeType":"Function","startLoc":51,"text":"def test_setupcfg_uses_toolpytest_with_pytest(self, testdir):\n p1 = testdir.makepyfile(\"def test(): pass\")\n testdir.makefile(\n \".cfg\",\n setup=\"\"\"\n [tool:pytest]\n testpaths=%s\n [pytest]\n testpaths=ignored\n \"\"\"\n % p1.basename,\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*, inifile: setup.cfg, *\", \"* 1 passed in *\"])\n assert result.ret == 0"},{"fileName":"test_in_sub2.py","filePath":"testing/example_scripts/fixtures/fill_fixtures/test_conftest_funcargs_only_available_in_subdir/sub2","id":5293,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ndef test_2(arg2):\n pass\n"},{"col":0,"comment":"null","endLoc":3,"header":"def test_2(arg2)","id":5294,"name":"test_2","nodeType":"Function","startLoc":2,"text":"def test_2(arg2):\n pass"},{"fileName":"__init__.py","filePath":"doc/en/example/costlysetup/sub_b","id":5295,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n#\n"},{"col":4,"comment":"null","endLoc":81,"header":"def test_append_parse_args(self, testdir, tmpdir, monkeypatch)","id":5296,"name":"test_append_parse_args","nodeType":"Function","startLoc":67,"text":"def test_append_parse_args(self, testdir, tmpdir, monkeypatch):\n monkeypatch.setenv(\"PYTEST_ADDOPTS\", '--color no -rs --tb=\"short\"')\n tmpdir.join(\"pytest.ini\").write(\n textwrap.dedent(\n \"\"\"\\\n [pytest]\n addopts = --verbose\n \"\"\"\n )\n )\n config = testdir.parseconfig(tmpdir)\n assert config.option.color == \"no\"\n assert config.option.reportchars == \"s\"\n assert config.option.tbstyle == \"short\"\n assert config.option.verbose"},{"col":4,"comment":"null","endLoc":93,"header":"def test_tox_ini_wrong_version(self, testdir)","id":5298,"name":"test_tox_ini_wrong_version","nodeType":"Function","startLoc":83,"text":"def test_tox_ini_wrong_version(self, testdir):\n testdir.makefile(\n \".ini\",\n tox=\"\"\"\n [pytest]\n minversion=9.0\n \"\"\",\n )\n result = testdir.runpytest()\n assert result.ret != 0\n result.stderr.fnmatch_lines([\"*tox.ini:2*requires*9.0*actual*\"])"},{"col":4,"comment":"null","endLoc":111,"header":"@pytest.mark.parametrize(\n \"section, name\",\n [(\"tool:pytest\", \"setup.cfg\"), (\"pytest\", \"tox.ini\"), (\"pytest\", \"pytest.ini\")],\n )\n def test_ini_names(self, testdir, name, section)","id":5299,"name":"test_ini_names","nodeType":"Function","startLoc":95,"text":"@pytest.mark.parametrize(\n \"section, name\",\n [(\"tool:pytest\", \"setup.cfg\"), (\"pytest\", \"tox.ini\"), (\"pytest\", \"pytest.ini\")],\n )\n def test_ini_names(self, testdir, name, section):\n testdir.tmpdir.join(name).write(\n textwrap.dedent(\n \"\"\"\n [{section}]\n minversion = 1.0\n \"\"\".format(\n section=section\n )\n )\n )\n config = testdir.parseconfig()\n assert config.getini(\"minversion\") == \"1.0\""},{"col":4,"comment":"null","endLoc":1137,"header":"def test_reset_twice_error(self)","id":5300,"name":"test_reset_twice_error","nodeType":"Function","startLoc":1131,"text":"def test_reset_twice_error(self):\n with self.getcapture() as cap:\n print(\"hello\")\n out, err = cap.readouterr()\n pytest.raises(ValueError, cap.stop_capturing)\n assert out == \"hello\\n\"\n assert not err"},{"fileName":"test_quick.py","filePath":"doc/en/example/costlysetup/sub_a","id":5301,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ndef test_quick(setup):\n pass\n"},{"col":0,"comment":"null","endLoc":3,"header":"def test_quick(setup)","id":5302,"name":"test_quick","nodeType":"Function","startLoc":2,"text":"def test_quick(setup):\n pass"},{"col":4,"comment":"null","endLoc":132,"header":"def test_toxini_before_lower_pytestini(self, testdir)","id":5304,"name":"test_toxini_before_lower_pytestini","nodeType":"Function","startLoc":113,"text":"def test_toxini_before_lower_pytestini(self, testdir):\n sub = testdir.tmpdir.mkdir(\"sub\")\n sub.join(\"tox.ini\").write(\n textwrap.dedent(\n \"\"\"\n [pytest]\n minversion = 2.0\n \"\"\"\n )\n )\n testdir.tmpdir.join(\"pytest.ini\").write(\n textwrap.dedent(\n \"\"\"\n [pytest]\n minversion = 1.5\n \"\"\"\n )\n )\n config = testdir.parseconfigure(sub)\n assert config.getini(\"minversion\") == \"2.0\""},{"col":4,"comment":"null","endLoc":138,"header":"def test_ini_parse_error(self, testdir)","id":5309,"name":"test_ini_parse_error","nodeType":"Function","startLoc":134,"text":"def test_ini_parse_error(self, testdir):\n testdir.tmpdir.join(\"pytest.ini\").write(\"addopts = -x\")\n result = testdir.runpytest()\n assert result.ret != 0\n result.stderr.fnmatch_lines([\"ERROR: *pytest.ini:1: no section header defined\"])"},{"col":4,"comment":"null","endLoc":1153,"header":"def test_capturing_modify_sysouterr_in_between(self)","id":5310,"name":"test_capturing_modify_sysouterr_in_between","nodeType":"Function","startLoc":1139,"text":"def test_capturing_modify_sysouterr_in_between(self):\n oldout = sys.stdout\n olderr = sys.stderr\n with self.getcapture() as cap:\n sys.stdout.write(\"hello\")\n sys.stderr.write(\"world\")\n sys.stdout = capture.CaptureIO()\n sys.stderr = capture.CaptureIO()\n print(\"not seen\")\n sys.stderr.write(\"not seen\\n\")\n out, err = cap.readouterr()\n assert out == \"hello\"\n assert err == \"world\"\n assert sys.stdout == oldout\n assert sys.stderr == olderr"},{"col":4,"comment":"null","endLoc":151,"header":"@pytest.mark.xfail(reason=\"probably not needed\")\n def test_confcutdir(self, testdir)","id":5311,"name":"test_confcutdir","nodeType":"Function","startLoc":140,"text":"@pytest.mark.xfail(reason=\"probably not needed\")\n def test_confcutdir(self, testdir):\n sub = testdir.mkdir(\"sub\")\n sub.chdir()\n testdir.makeini(\n \"\"\"\n [pytest]\n addopts = --qwe\n \"\"\"\n )\n result = testdir.inline_run(\"--confcutdir=.\")\n assert result.ret == 0"},{"className":"TestConfigCmdlineParsing","col":0,"comment":"null","endLoc":204,"id":5312,"nodeType":"Class","startLoc":154,"text":"class TestConfigCmdlineParsing(object):\n def test_parsing_again_fails(self, testdir):\n config = testdir.parseconfig()\n pytest.raises(AssertionError, lambda: config.parse([]))\n\n def test_explicitly_specified_config_file_is_loaded(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"custom\", \"\")\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n custom = 0\n \"\"\"\n )\n testdir.makefile(\n \".ini\",\n custom=\"\"\"\n [pytest]\n custom = 1\n \"\"\",\n )\n config = testdir.parseconfig(\"-c\", \"custom.ini\")\n assert config.getini(\"custom\") == \"1\"\n\n testdir.makefile(\n \".cfg\",\n custom_tool_pytest_section=\"\"\"\n [tool:pytest]\n custom = 1\n \"\"\",\n )\n config = testdir.parseconfig(\"-c\", \"custom_tool_pytest_section.cfg\")\n assert config.getini(\"custom\") == \"1\"\n\n def test_absolute_win32_path(self, testdir):\n temp_ini_file = testdir.makefile(\n \".ini\",\n custom=\"\"\"\n [pytest]\n addopts = --version\n \"\"\",\n )\n from os.path import normpath\n\n temp_ini_file = normpath(str(temp_ini_file))\n ret = pytest.main([\"-c\", temp_ini_file])\n assert ret == _pytest.main.EXIT_OK"},{"col":4,"comment":"null","endLoc":157,"header":"def test_parsing_again_fails(self, testdir)","id":5313,"name":"test_parsing_again_fails","nodeType":"Function","startLoc":155,"text":"def test_parsing_again_fails(self, testdir):\n config = testdir.parseconfig()\n pytest.raises(AssertionError, lambda: config.parse([]))"},{"col":38,"endLoc":157,"id":5314,"nodeType":"Lambda","startLoc":157,"text":"lambda: config.parse([])"},{"col":4,"comment":"null","endLoc":190,"header":"def test_explicitly_specified_config_file_is_loaded(self, testdir)","id":5315,"name":"test_explicitly_specified_config_file_is_loaded","nodeType":"Function","startLoc":159,"text":"def test_explicitly_specified_config_file_is_loaded(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"custom\", \"\")\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n custom = 0\n \"\"\"\n )\n testdir.makefile(\n \".ini\",\n custom=\"\"\"\n [pytest]\n custom = 1\n \"\"\",\n )\n config = testdir.parseconfig(\"-c\", \"custom.ini\")\n assert config.getini(\"custom\") == \"1\"\n\n testdir.makefile(\n \".cfg\",\n custom_tool_pytest_section=\"\"\"\n [tool:pytest]\n custom = 1\n \"\"\",\n )\n config = testdir.parseconfig(\"-c\", \"custom_tool_pytest_section.cfg\")\n assert config.getini(\"custom\") == \"1\""},{"col":4,"comment":"null","endLoc":204,"header":"def test_absolute_win32_path(self, testdir)","id":5316,"name":"test_absolute_win32_path","nodeType":"Function","startLoc":192,"text":"def test_absolute_win32_path(self, testdir):\n temp_ini_file = testdir.makefile(\n \".ini\",\n custom=\"\"\"\n [pytest]\n addopts = --version\n \"\"\",\n )\n from os.path import normpath\n\n temp_ini_file = normpath(str(temp_ini_file))\n ret = pytest.main([\"-c\", temp_ini_file])\n assert ret == _pytest.main.EXIT_OK"},{"col":4,"comment":"null","endLoc":1163,"header":"def test_capturing_error_recursive(self)","id":5318,"name":"test_capturing_error_recursive","nodeType":"Function","startLoc":1155,"text":"def test_capturing_error_recursive(self):\n with self.getcapture() as cap1:\n print(\"cap1\")\n with self.getcapture() as cap2:\n print(\"cap2\")\n out2, err2 = cap2.readouterr()\n out1, err1 = cap1.readouterr()\n assert out1 == \"cap1\\n\"\n assert out2 == \"cap2\\n\""},{"className":"TestConfigAPI","col":0,"comment":"null","endLoc":443,"id":5324,"nodeType":"Class","startLoc":207,"text":"class TestConfigAPI(object):\n def test_config_trace(self, testdir):\n config = testdir.parseconfig()\n values = []\n config.trace.root.setwriter(values.append)\n config.trace(\"hello\")\n assert len(values) == 1\n assert values[0] == \"hello [config]\\n\"\n\n def test_config_getoption(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addoption(\"--hello\", \"-X\", dest=\"hello\")\n \"\"\"\n )\n config = testdir.parseconfig(\"--hello=this\")\n for x in (\"hello\", \"--hello\", \"-X\"):\n assert config.getoption(x) == \"this\"\n pytest.raises(ValueError, config.getoption, \"qweqwe\")\n\n @pytest.mark.skipif(\"sys.version_info[0] < 3\")\n def test_config_getoption_unicode(self, testdir):\n testdir.makeconftest(\n \"\"\"\n from __future__ import unicode_literals\n\n def pytest_addoption(parser):\n parser.addoption('--hello', type=str)\n \"\"\"\n )\n config = testdir.parseconfig(\"--hello=this\")\n assert config.getoption(\"hello\") == \"this\"\n\n def test_config_getvalueorskip(self, testdir):\n config = testdir.parseconfig()\n pytest.raises(pytest.skip.Exception, config.getvalueorskip, \"hello\")\n verbose = config.getvalueorskip(\"verbose\")\n assert verbose == config.option.verbose\n\n def test_config_getvalueorskip_None(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addoption(\"--hello\")\n \"\"\"\n )\n config = testdir.parseconfig()\n with pytest.raises(pytest.skip.Exception):\n config.getvalueorskip(\"hello\")\n\n def test_getoption(self, testdir):\n config = testdir.parseconfig()\n with pytest.raises(ValueError):\n config.getvalue(\"x\")\n assert config.getoption(\"x\", 1) == 1\n\n def test_getconftest_pathlist(self, testdir, tmpdir):\n somepath = tmpdir.join(\"x\", \"y\", \"z\")\n p = tmpdir.join(\"conftest.py\")\n p.write(\"pathlist = ['.', %r]\" % str(somepath))\n config = testdir.parseconfigure(p)\n assert config._getconftest_pathlist(\"notexist\", path=tmpdir) is None\n pl = config._getconftest_pathlist(\"pathlist\", path=tmpdir)\n print(pl)\n assert len(pl) == 2\n assert pl[0] == tmpdir\n assert pl[1] == somepath\n\n def test_addini(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"myname\", \"my new ini value\")\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n myname=hello\n \"\"\"\n )\n config = testdir.parseconfig()\n val = config.getini(\"myname\")\n assert val == \"hello\"\n pytest.raises(ValueError, config.getini, \"other\")\n\n def test_addini_pathlist(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"paths\", \"my new ini value\", type=\"pathlist\")\n parser.addini(\"abc\", \"abc value\")\n \"\"\"\n )\n p = testdir.makeini(\n \"\"\"\n [pytest]\n paths=hello world/sub.py\n \"\"\"\n )\n config = testdir.parseconfig()\n values = config.getini(\"paths\")\n assert len(values) == 2\n assert values[0] == p.dirpath(\"hello\")\n assert values[1] == p.dirpath(\"world/sub.py\")\n pytest.raises(ValueError, config.getini, \"other\")\n\n def test_addini_args(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"args\", \"new args\", type=\"args\")\n parser.addini(\"a2\", \"\", \"args\", default=\"1 2 3\".split())\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n args=123 \"123 hello\" \"this\"\n \"\"\"\n )\n config = testdir.parseconfig()\n values = config.getini(\"args\")\n assert len(values) == 3\n assert values == [\"123\", \"123 hello\", \"this\"]\n values = config.getini(\"a2\")\n assert values == list(\"123\")\n\n def test_addini_linelist(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"xy\", \"\", type=\"linelist\")\n parser.addini(\"a2\", \"\", \"linelist\")\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n xy= 123 345\n second line\n \"\"\"\n )\n config = testdir.parseconfig()\n values = config.getini(\"xy\")\n assert len(values) == 2\n assert values == [\"123 345\", \"second line\"]\n values = config.getini(\"a2\")\n assert values == []\n\n @pytest.mark.parametrize(\n \"str_val, bool_val\", [(\"True\", True), (\"no\", False), (\"no-ini\", True)]\n )\n def test_addini_bool(self, testdir, str_val, bool_val):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"strip\", \"\", type=\"bool\", default=True)\n \"\"\"\n )\n if str_val != \"no-ini\":\n testdir.makeini(\n \"\"\"\n [pytest]\n strip=%s\n \"\"\"\n % str_val\n )\n config = testdir.parseconfig()\n assert config.getini(\"strip\") is bool_val\n\n def test_addinivalue_line_existing(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"xy\", \"\", type=\"linelist\")\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n xy= 123\n \"\"\"\n )\n config = testdir.parseconfig()\n values = config.getini(\"xy\")\n assert len(values) == 1\n assert values == [\"123\"]\n config.addinivalue_line(\"xy\", \"456\")\n values = config.getini(\"xy\")\n assert len(values) == 2\n assert values == [\"123\", \"456\"]\n\n def test_addinivalue_line_new(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"xy\", \"\", type=\"linelist\")\n \"\"\"\n )\n config = testdir.parseconfig()\n assert not config.getini(\"xy\")\n config.addinivalue_line(\"xy\", \"456\")\n values = config.getini(\"xy\")\n assert len(values) == 1\n assert values == [\"456\"]\n config.addinivalue_line(\"xy\", \"123\")\n values = config.getini(\"xy\")\n assert len(values) == 2\n assert values == [\"456\", \"123\"]\n\n def test_confcutdir_check_isdir(self, testdir):\n \"\"\"Give an error if --confcutdir is not a valid directory (#2078)\"\"\"\n with pytest.raises(pytest.UsageError):\n testdir.parseconfig(\n \"--confcutdir\", testdir.tmpdir.join(\"file\").ensure(file=1)\n )\n with pytest.raises(pytest.UsageError):\n testdir.parseconfig(\"--confcutdir\", testdir.tmpdir.join(\"inexistant\"))\n config = testdir.parseconfig(\n \"--confcutdir\", testdir.tmpdir.join(\"dir\").ensure(dir=1)\n )\n assert config.getoption(\"confcutdir\") == str(testdir.tmpdir.join(\"dir\"))\n\n @pytest.mark.parametrize(\n \"names, expected\",\n [\n ([\"bar.py\"], [\"bar\"]),\n ([\"foo\", \"bar.py\"], []),\n ([\"foo\", \"bar.pyc\"], []),\n ([\"foo\", \"__init__.py\"], [\"foo\"]),\n ([\"foo\", \"bar\", \"__init__.py\"], []),\n ],\n )\n def test_iter_rewritable_modules(self, names, expected):\n assert list(_iter_rewritable_modules([\"/\".join(names)])) == expected"},{"col":4,"comment":"null","endLoc":214,"header":"def test_config_trace(self, testdir)","id":5325,"name":"test_config_trace","nodeType":"Function","startLoc":208,"text":"def test_config_trace(self, testdir):\n config = testdir.parseconfig()\n values = []\n config.trace.root.setwriter(values.append)\n config.trace(\"hello\")\n assert len(values) == 1\n assert values[0] == \"hello [config]\\n\""},{"col":4,"comment":"null","endLoc":226,"header":"def test_config_getoption(self, testdir)","id":5326,"name":"test_config_getoption","nodeType":"Function","startLoc":216,"text":"def test_config_getoption(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addoption(\"--hello\", \"-X\", dest=\"hello\")\n \"\"\"\n )\n config = testdir.parseconfig(\"--hello=this\")\n for x in (\"hello\", \"--hello\", \"-X\"):\n assert config.getoption(x) == \"this\"\n pytest.raises(ValueError, config.getoption, \"qweqwe\")"},{"col":4,"comment":"null","endLoc":239,"header":"@pytest.mark.skipif(\"sys.version_info[0] < 3\")\n def test_config_getoption_unicode(self, testdir)","id":5327,"name":"test_config_getoption_unicode","nodeType":"Function","startLoc":228,"text":"@pytest.mark.skipif(\"sys.version_info[0] < 3\")\n def test_config_getoption_unicode(self, testdir):\n testdir.makeconftest(\n \"\"\"\n from __future__ import unicode_literals\n\n def pytest_addoption(parser):\n parser.addoption('--hello', type=str)\n \"\"\"\n )\n config = testdir.parseconfig(\"--hello=this\")\n assert config.getoption(\"hello\") == \"this\""},{"col":4,"comment":"null","endLoc":245,"header":"def test_config_getvalueorskip(self, testdir)","id":5329,"name":"test_config_getvalueorskip","nodeType":"Function","startLoc":241,"text":"def test_config_getvalueorskip(self, testdir):\n config = testdir.parseconfig()\n pytest.raises(pytest.skip.Exception, config.getvalueorskip, \"hello\")\n verbose = config.getvalueorskip(\"verbose\")\n assert verbose == config.option.verbose"},{"col":4,"comment":"null","endLoc":256,"header":"def test_config_getvalueorskip_None(self, testdir)","id":5330,"name":"test_config_getvalueorskip_None","nodeType":"Function","startLoc":247,"text":"def test_config_getvalueorskip_None(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addoption(\"--hello\")\n \"\"\"\n )\n config = testdir.parseconfig()\n with pytest.raises(pytest.skip.Exception):\n config.getvalueorskip(\"hello\")"},{"col":4,"comment":"null","endLoc":262,"header":"def test_getoption(self, testdir)","id":5332,"name":"test_getoption","nodeType":"Function","startLoc":258,"text":"def test_getoption(self, testdir):\n config = testdir.parseconfig()\n with pytest.raises(ValueError):\n config.getvalue(\"x\")\n assert config.getoption(\"x\", 1) == 1"},{"col":4,"comment":"null","endLoc":274,"header":"def test_getconftest_pathlist(self, testdir, tmpdir)","id":5334,"name":"test_getconftest_pathlist","nodeType":"Function","startLoc":264,"text":"def test_getconftest_pathlist(self, testdir, tmpdir):\n somepath = tmpdir.join(\"x\", \"y\", \"z\")\n p = tmpdir.join(\"conftest.py\")\n p.write(\"pathlist = ['.', %r]\" % str(somepath))\n config = testdir.parseconfigure(p)\n assert config._getconftest_pathlist(\"notexist\", path=tmpdir) is None\n pl = config._getconftest_pathlist(\"pathlist\", path=tmpdir)\n print(pl)\n assert len(pl) == 2\n assert pl[0] == tmpdir\n assert pl[1] == somepath"},{"col":4,"comment":" Change the current working directory to the specified path.\n Path can be a string or a py.path.local object.\n ","endLoc":299,"header":"def chdir(self, path)","id":5336,"name":"chdir","nodeType":"Function","startLoc":287,"text":"def chdir(self, path):\n \"\"\" Change the current working directory to the specified path.\n Path can be a string or a py.path.local object.\n \"\"\"\n if self._cwd is None:\n self._cwd = os.getcwd()\n if hasattr(path, \"chdir\"):\n path.chdir()\n elif isinstance(path, Path):\n # modern python uses the fspath protocol here LEGACY\n os.chdir(str(path))\n else:\n os.chdir(path)"},{"col":4,"comment":"null","endLoc":1171,"header":"def test_just_out_capture(self)","id":5337,"name":"test_just_out_capture","nodeType":"Function","startLoc":1165,"text":"def test_just_out_capture(self):\n with self.getcapture(out=True, err=False) as cap:\n sys.stdout.write(\"hello\")\n sys.stderr.write(\"world\")\n out, err = cap.readouterr()\n assert out == \"hello\"\n assert not err"},{"col":4,"comment":"null","endLoc":292,"header":"def test_addini(self, testdir)","id":5338,"name":"test_addini","nodeType":"Function","startLoc":276,"text":"def test_addini(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"myname\", \"my new ini value\")\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n myname=hello\n \"\"\"\n )\n config = testdir.parseconfig()\n val = config.getini(\"myname\")\n assert val == \"hello\"\n pytest.raises(ValueError, config.getini, \"other\")"},{"col":4,"comment":"null","endLoc":313,"header":"def test_addini_pathlist(self, testdir)","id":5339,"name":"test_addini_pathlist","nodeType":"Function","startLoc":294,"text":"def test_addini_pathlist(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"paths\", \"my new ini value\", type=\"pathlist\")\n parser.addini(\"abc\", \"abc value\")\n \"\"\"\n )\n p = testdir.makeini(\n \"\"\"\n [pytest]\n paths=hello world/sub.py\n \"\"\"\n )\n config = testdir.parseconfig()\n values = config.getini(\"paths\")\n assert len(values) == 2\n assert values[0] == p.dirpath(\"hello\")\n assert values[1] == p.dirpath(\"world/sub.py\")\n pytest.raises(ValueError, config.getini, \"other\")"},{"col":4,"comment":"null","endLoc":1179,"header":"def test_just_err_capture(self)","id":5340,"name":"test_just_err_capture","nodeType":"Function","startLoc":1173,"text":"def test_just_err_capture(self):\n with self.getcapture(out=False, err=True) as cap:\n sys.stdout.write(\"hello\")\n sys.stderr.write(\"world\")\n out, err = cap.readouterr()\n assert err == \"world\"\n assert not out"},{"col":4,"comment":"null","endLoc":334,"header":"def test_addini_args(self, testdir)","id":5341,"name":"test_addini_args","nodeType":"Function","startLoc":315,"text":"def test_addini_args(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"args\", \"new args\", type=\"args\")\n parser.addini(\"a2\", \"\", \"args\", default=\"1 2 3\".split())\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n args=123 \"123 hello\" \"this\"\n \"\"\"\n )\n config = testdir.parseconfig()\n values = config.getini(\"args\")\n assert len(values) == 3\n assert values == [\"123\", \"123 hello\", \"this\"]\n values = config.getini(\"a2\")\n assert values == list(\"123\")"},{"attributeType":"list","col":8,"comment":"null","endLoc":108,"id":5342,"name":"_setattr","nodeType":"Attribute","startLoc":108,"text":"self._setattr"},{"attributeType":"None","col":8,"comment":"null","endLoc":111,"id":5343,"name":"_savesyspath","nodeType":"Attribute","startLoc":111,"text":"self._savesyspath"},{"attributeType":"None","col":8,"comment":"null","endLoc":110,"id":5344,"name":"_cwd","nodeType":"Attribute","startLoc":110,"text":"self._cwd"},{"attributeType":"list","col":8,"comment":"null","endLoc":109,"id":5345,"name":"_setitem","nodeType":"Attribute","startLoc":109,"text":"self._setitem"},{"col":0,"comment":"The returned ``monkeypatch`` fixture provides these\n helper methods to modify objects, dictionaries or os.environ::\n\n monkeypatch.setattr(obj, name, value, raising=True)\n monkeypatch.delattr(obj, name, raising=True)\n monkeypatch.setitem(mapping, name, value)\n monkeypatch.delitem(obj, name, raising=True)\n monkeypatch.setenv(name, value, prepend=False)\n monkeypatch.delenv(name, raising=True)\n monkeypatch.syspath_prepend(path)\n monkeypatch.chdir(path)\n\n All modifications will be undone after the requesting\n test function or fixture has finished. The ``raising``\n parameter determines if a KeyError or AttributeError\n will be raised if the set/deletion operation has no target.\n ","endLoc":43,"header":"@fixture\ndef monkeypatch()","id":5346,"name":"monkeypatch","nodeType":"Function","startLoc":22,"text":"@fixture\ndef monkeypatch():\n \"\"\"The returned ``monkeypatch`` fixture provides these\n helper methods to modify objects, dictionaries or os.environ::\n\n monkeypatch.setattr(obj, name, value, raising=True)\n monkeypatch.delattr(obj, name, raising=True)\n monkeypatch.setitem(mapping, name, value)\n monkeypatch.delitem(obj, name, raising=True)\n monkeypatch.setenv(name, value, prepend=False)\n monkeypatch.delenv(name, raising=True)\n monkeypatch.syspath_prepend(path)\n monkeypatch.chdir(path)\n\n All modifications will be undone after the requesting\n test function or fixture has finished. The ``raising``\n parameter determines if a KeyError or AttributeError\n will be raised if the set/deletion operation has no target.\n \"\"\"\n mpatch = MonkeyPatch()\n yield mpatch\n mpatch.undo()"},{"attributeType":"Pattern","col":0,"comment":"null","endLoc":19,"id":5347,"name":"RE_IMPORT_ERROR_NAME","nodeType":"Attribute","startLoc":19,"text":"RE_IMPORT_ERROR_NAME"},{"attributeType":"Notset","col":0,"comment":"null","endLoc":100,"id":5348,"name":"notset","nodeType":"Attribute","startLoc":100,"text":"notset"},{"col":0,"comment":"","endLoc":2,"header":"monkeypatch.py#","id":5349,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" monkeypatching and mocking functionality. \"\"\"\n\nRE_IMPORT_ERROR_NAME = re.compile(r\"^No module named (.*)$\")\n\nnotset = Notset()"},{"col":4,"comment":"null","endLoc":356,"header":"def test_addini_linelist(self, testdir)","id":5350,"name":"test_addini_linelist","nodeType":"Function","startLoc":336,"text":"def test_addini_linelist(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"xy\", \"\", type=\"linelist\")\n parser.addini(\"a2\", \"\", \"linelist\")\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n xy= 123 345\n second line\n \"\"\"\n )\n config = testdir.parseconfig()\n values = config.getini(\"xy\")\n assert len(values) == 2\n assert values == [\"123 345\", \"second line\"]\n values = config.getini(\"a2\")\n assert values == []"},{"col":4,"comment":"null","endLoc":1186,"header":"def test_stdin_restored(self)","id":5351,"name":"test_stdin_restored","nodeType":"Function","startLoc":1181,"text":"def test_stdin_restored(self):\n old = sys.stdin\n with self.getcapture(in_=True):\n newstdin = sys.stdin\n assert newstdin != sys.stdin\n assert sys.stdin is old"},{"col":4,"comment":"null","endLoc":377,"header":"@pytest.mark.parametrize(\n \"str_val, bool_val\", [(\"True\", True), (\"no\", False), (\"no-ini\", True)]\n )\n def test_addini_bool(self, testdir, str_val, bool_val)","id":5352,"name":"test_addini_bool","nodeType":"Function","startLoc":358,"text":"@pytest.mark.parametrize(\n \"str_val, bool_val\", [(\"True\", True), (\"no\", False), (\"no-ini\", True)]\n )\n def test_addini_bool(self, testdir, str_val, bool_val):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"strip\", \"\", type=\"bool\", default=True)\n \"\"\"\n )\n if str_val != \"no-ini\":\n testdir.makeini(\n \"\"\"\n [pytest]\n strip=%s\n \"\"\"\n % str_val\n )\n config = testdir.parseconfig()\n assert config.getini(\"strip\") is bool_val"},{"fileName":"test_parametrized_fixture_error_message.py","filePath":"testing/example_scripts/unittest","id":5353,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport unittest\n\nimport pytest\n\n\n@pytest.fixture(params=[1, 2])\ndef two(request):\n return request.param\n\n\n@pytest.mark.usefixtures(\"two\")\nclass TestSomethingElse(unittest.TestCase):\n def test_two(self):\n pass\n"},{"col":4,"comment":"null","endLoc":1193,"header":"def test_stdin_nulled_by_default(self)","id":5354,"name":"test_stdin_nulled_by_default","nodeType":"Function","startLoc":1188,"text":"def test_stdin_nulled_by_default(self):\n print(\"XXX this test may well hang instead of crashing\")\n print(\"XXX which indicates an error in the underlying capturing\")\n print(\"XXX mechanisms\")\n with self.getcapture():\n pytest.raises(IOError, sys.stdin.read)"},{"col":4,"comment":"null","endLoc":35,"header":"def test_failed(self, testdir, pastebinlist)","id":5355,"name":"test_failed","nodeType":"Function","startLoc":19,"text":"def test_failed(self, testdir, pastebinlist):\n testpath = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_pass():\n pass\n def test_fail():\n assert 0\n def test_skip():\n pytest.skip(\"\")\n \"\"\"\n )\n reprec = testdir.inline_run(testpath, \"--paste=failed\")\n assert len(pastebinlist) == 1\n s = pastebinlist[0]\n assert s.find(\"def test_fail\") != -1\n assert reprec.countoutcomes() == [1, 1, 1]"},{"className":"TestSomethingElse","col":0,"comment":"null","endLoc":15,"id":5356,"nodeType":"Class","startLoc":12,"text":"@pytest.mark.usefixtures(\"two\")\nclass TestSomethingElse(unittest.TestCase):\n def test_two(self):\n pass"},{"col":4,"comment":"null","endLoc":15,"header":"def test_two(self)","id":5357,"name":"test_two","nodeType":"Function","startLoc":14,"text":"def test_two(self):\n pass"},{"col":0,"comment":"null","endLoc":9,"header":"@pytest.fixture(params=[1, 2])\ndef two(request)","id":5358,"name":"two","nodeType":"Function","startLoc":7,"text":"@pytest.fixture(params=[1, 2])\ndef two(request):\n return request.param"},{"attributeType":"staticmethod","col":4,"comment":"null","endLoc":1069,"id":5359,"name":"captureclass","nodeType":"Attribute","startLoc":1069,"text":"captureclass"},{"className":"TestStdCaptureFD","col":0,"comment":"null","endLoc":1236,"id":5360,"nodeType":"Class","startLoc":1196,"text":"class TestStdCaptureFD(TestStdCapture):\n pytestmark = needsosdup\n captureclass = staticmethod(StdCaptureFD)\n\n def test_simple_only_fd(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import os\n def test_x():\n os.write(1, \"hello\\\\n\".encode(\"ascii\"))\n assert 0\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines(\n \"\"\"\n *test_x*\n *assert 0*\n *Captured stdout*\n \"\"\"\n )\n\n def test_intermingling(self):\n with self.getcapture() as cap:\n os.write(1, b\"1\")\n sys.stdout.write(str(2))\n sys.stdout.flush()\n os.write(1, b\"3\")\n os.write(2, b\"a\")\n sys.stderr.write(\"b\")\n sys.stderr.flush()\n os.write(2, b\"c\")\n out, err = cap.readouterr()\n assert out == \"123\"\n assert err == \"abc\"\n\n def test_many(self, capfd):\n with lsof_check():\n for i in range(10):\n cap = StdCaptureFD()\n cap.stop_capturing()"},{"col":4,"comment":"null","endLoc":1216,"header":"def test_simple_only_fd(self, testdir)","id":5361,"name":"test_simple_only_fd","nodeType":"Function","startLoc":1200,"text":"def test_simple_only_fd(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import os\n def test_x():\n os.write(1, \"hello\\\\n\".encode(\"ascii\"))\n assert 0\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines(\n \"\"\"\n *test_x*\n *assert 0*\n *Captured stdout*\n \"\"\"\n )"},{"fileName":"test_setup_skip.py","filePath":"testing/example_scripts/unittest","id":5362,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"Skipping an entire subclass with unittest.skip() should *not* call setUp from a base class.\"\"\"\nimport unittest\n\n\nclass Base(unittest.TestCase):\n def setUp(self):\n assert 0\n\n\n@unittest.skip(\"skip all tests\")\nclass Test(Base):\n def test_foo(self):\n assert 0\n"},{"className":"Base","col":0,"comment":"null","endLoc":8,"id":5363,"nodeType":"Class","startLoc":6,"text":"class Base(unittest.TestCase):\n def setUp(self):\n assert 0"},{"col":4,"comment":"null","endLoc":8,"header":"def setUp(self)","id":5364,"name":"setUp","nodeType":"Function","startLoc":7,"text":"def setUp(self):\n assert 0"},{"col":4,"comment":"null","endLoc":1230,"header":"def test_intermingling(self)","id":5365,"name":"test_intermingling","nodeType":"Function","startLoc":1218,"text":"def test_intermingling(self):\n with self.getcapture() as cap:\n os.write(1, b\"1\")\n sys.stdout.write(str(2))\n sys.stdout.flush()\n os.write(1, b\"3\")\n os.write(2, b\"a\")\n sys.stderr.write(\"b\")\n sys.stderr.flush()\n os.write(2, b\"c\")\n out, err = cap.readouterr()\n assert out == \"123\"\n assert err == \"abc\""},{"className":"Test","col":0,"comment":"null","endLoc":14,"id":5366,"nodeType":"Class","startLoc":11,"text":"@unittest.skip(\"skip all tests\")\nclass Test(Base):\n def test_foo(self):\n assert 0"},{"col":4,"comment":"null","endLoc":14,"header":"def test_foo(self)","id":5367,"name":"test_foo","nodeType":"Function","startLoc":13,"text":"def test_foo(self):\n assert 0"},{"col":0,"comment":"","endLoc":2,"header":"test_setup_skip.py#","id":5368,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"Skipping an entire subclass with unittest.skip() should *not* call setUp from a base class.\"\"\""},{"col":4,"comment":"null","endLoc":399,"header":"def test_addinivalue_line_existing(self, testdir)","id":5369,"name":"test_addinivalue_line_existing","nodeType":"Function","startLoc":379,"text":"def test_addinivalue_line_existing(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"xy\", \"\", type=\"linelist\")\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n xy= 123\n \"\"\"\n )\n config = testdir.parseconfig()\n values = config.getini(\"xy\")\n assert len(values) == 1\n assert values == [\"123\"]\n config.addinivalue_line(\"xy\", \"456\")\n values = config.getini(\"xy\")\n assert len(values) == 2\n assert values == [\"123\", \"456\"]"},{"col":4,"comment":"null","endLoc":417,"header":"def test_addinivalue_line_new(self, testdir)","id":5370,"name":"test_addinivalue_line_new","nodeType":"Function","startLoc":401,"text":"def test_addinivalue_line_new(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"xy\", \"\", type=\"linelist\")\n \"\"\"\n )\n config = testdir.parseconfig()\n assert not config.getini(\"xy\")\n config.addinivalue_line(\"xy\", \"456\")\n values = config.getini(\"xy\")\n assert len(values) == 1\n assert values == [\"456\"]\n config.addinivalue_line(\"xy\", \"123\")\n values = config.getini(\"xy\")\n assert len(values) == 2\n assert values == [\"456\", \"123\"]"},{"col":4,"comment":"Give an error if --confcutdir is not a valid directory (#2078)","endLoc":430,"header":"def test_confcutdir_check_isdir(self, testdir)","id":5371,"name":"test_confcutdir_check_isdir","nodeType":"Function","startLoc":419,"text":"def test_confcutdir_check_isdir(self, testdir):\n \"\"\"Give an error if --confcutdir is not a valid directory (#2078)\"\"\"\n with pytest.raises(pytest.UsageError):\n testdir.parseconfig(\n \"--confcutdir\", testdir.tmpdir.join(\"file\").ensure(file=1)\n )\n with pytest.raises(pytest.UsageError):\n testdir.parseconfig(\"--confcutdir\", testdir.tmpdir.join(\"inexistant\"))\n config = testdir.parseconfig(\n \"--confcutdir\", testdir.tmpdir.join(\"dir\").ensure(dir=1)\n )\n assert config.getoption(\"confcutdir\") == str(testdir.tmpdir.join(\"dir\"))"},{"col":4,"comment":"null","endLoc":63,"header":"def test_all(self, testdir, pastebinlist)","id":5372,"name":"test_all","nodeType":"Function","startLoc":37,"text":"def test_all(self, testdir, pastebinlist):\n from _pytest.pytester import LineMatcher\n\n testpath = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_pass():\n pass\n def test_fail():\n assert 0\n def test_skip():\n pytest.skip(\"\")\n \"\"\"\n )\n reprec = testdir.inline_run(testpath, \"--pastebin=all\", \"-v\")\n assert reprec.countoutcomes() == [1, 1, 1]\n assert len(pastebinlist) == 1\n contents = pastebinlist[0].decode(\"utf-8\")\n matcher = LineMatcher(contents.splitlines())\n matcher.fnmatch_lines(\n [\n \"*test_pass PASSED*\",\n \"*test_fail FAILED*\",\n \"*test_skip SKIPPED*\",\n \"*== 1 failed, 1 passed, 1 skipped in *\",\n ]\n )"},{"col":4,"comment":"null","endLoc":443,"header":"@pytest.mark.parametrize(\n \"names, expected\",\n [\n ([\"bar.py\"], [\"bar\"]),\n ([\"foo\", \"bar.py\"], []),\n ([\"foo\", \"bar.pyc\"], []),\n ([\"foo\", \"__init__.py\"], [\"foo\"]),\n ([\"foo\", \"bar\", \"__init__.py\"], []),\n ],\n )\n def test_iter_rewritable_modules(self, names, expected)","id":5373,"name":"test_iter_rewritable_modules","nodeType":"Function","startLoc":432,"text":"@pytest.mark.parametrize(\n \"names, expected\",\n [\n ([\"bar.py\"], [\"bar\"]),\n ([\"foo\", \"bar.py\"], []),\n ([\"foo\", \"bar.pyc\"], []),\n ([\"foo\", \"__init__.py\"], [\"foo\"]),\n ([\"foo\", \"bar\", \"__init__.py\"], []),\n ],\n )\n def test_iter_rewritable_modules(self, names, expected):\n assert list(_iter_rewritable_modules([\"/\".join(names)])) == expected"},{"col":0,"comment":"null","endLoc":62,"header":"def pytest_unconfigure(config)","id":5378,"name":"pytest_unconfigure","nodeType":"Function","startLoc":49,"text":"def pytest_unconfigure(config):\n if hasattr(config, \"_pastebinfile\"):\n # get terminal contents and delete file\n config._pastebinfile.seek(0)\n sessionlog = config._pastebinfile.read()\n config._pastebinfile.close()\n del config._pastebinfile\n # undo our patching in the terminal reporter\n tr = config.pluginmanager.getplugin(\"terminalreporter\")\n del tr._tw.__dict__[\"write\"]\n # write summary\n tr.write_sep(\"=\", \"Sending information to Paste Service\")\n pastebinurl = create_new_paste(sessionlog)\n tr.write_line(\"pastebin session-log: %s\\n\" % pastebinurl)"},{"col":0,"comment":"\n Creates a new paste using bpaste.net service.\n\n :contents: paste contents as utf-8 encoded bytes\n :returns: url to the pasted contents\n ","endLoc":91,"header":"def create_new_paste(contents)","id":5379,"name":"create_new_paste","nodeType":"Function","startLoc":65,"text":"def create_new_paste(contents):\n \"\"\"\n Creates a new paste using bpaste.net service.\n\n :contents: paste contents as utf-8 encoded bytes\n :returns: url to the pasted contents\n \"\"\"\n import re\n\n if sys.version_info < (3, 0):\n from urllib import urlopen, urlencode\n else:\n from urllib.request import urlopen\n from urllib.parse import urlencode\n\n params = {\n \"code\": contents,\n \"lexer\": \"python3\" if sys.version_info[0] >= 3 else \"python\",\n \"expiry\": \"1week\",\n }\n url = \"https://bpaste.net\"\n response = urlopen(url, data=urlencode(params).encode(\"ascii\")).read()\n m = re.search(r'href=\"/raw/(\\w+)\"', response.decode(\"utf-8\"))\n if m:\n return \"%s/show/%s\" % (url, m.group(1))\n else:\n return \"bad response: \" + response"},{"fileName":"code.py","filePath":"src/_pytest/_code","id":5380,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport inspect\nimport re\nimport sys\nimport traceback\nfrom inspect import CO_VARARGS\nfrom inspect import CO_VARKEYWORDS\nfrom weakref import ref\n\nimport attr\nimport pluggy\nimport py\nfrom six import text_type\n\nimport _pytest\nfrom _pytest._io.saferepr import safeformat\nfrom _pytest._io.saferepr import saferepr\nfrom _pytest.compat import _PY2\nfrom _pytest.compat import _PY3\nfrom _pytest.compat import PY35\nfrom _pytest.compat import safe_str\n\nif _PY3:\n from traceback import format_exception_only\nelse:\n from ._py2traceback import format_exception_only\n\n\nclass Code(object):\n \"\"\" wrapper around Python code objects \"\"\"\n\n def __init__(self, rawcode):\n if not hasattr(rawcode, \"co_filename\"):\n rawcode = getrawcode(rawcode)\n try:\n self.filename = rawcode.co_filename\n self.firstlineno = rawcode.co_firstlineno - 1\n self.name = rawcode.co_name\n except AttributeError:\n raise TypeError(\"not a code object: %r\" % (rawcode,))\n self.raw = rawcode\n\n def __eq__(self, other):\n return self.raw == other.raw\n\n __hash__ = None\n\n def __ne__(self, other):\n return not self == other\n\n @property\n def path(self):\n \"\"\" return a path object pointing to source code (note that it\n might not point to an actually existing file). \"\"\"\n try:\n p = py.path.local(self.raw.co_filename)\n # maybe don't try this checking\n if not p.check():\n raise OSError(\"py.path check failed.\")\n except OSError:\n # XXX maybe try harder like the weird logic\n # in the standard lib [linecache.updatecache] does?\n p = self.raw.co_filename\n\n return p\n\n @property\n def fullsource(self):\n \"\"\" return a _pytest._code.Source object for the full source file of the code\n \"\"\"\n from _pytest._code import source\n\n full, _ = source.findsource(self.raw)\n return full\n\n def source(self):\n \"\"\" return a _pytest._code.Source object for the code object's source only\n \"\"\"\n # return source only for that part of code\n import _pytest._code\n\n return _pytest._code.Source(self.raw)\n\n def getargs(self, var=False):\n \"\"\" return a tuple with the argument names for the code object\n\n if 'var' is set True also return the names of the variable and\n keyword arguments when present\n \"\"\"\n # handfull shortcut for getting args\n raw = self.raw\n argcount = raw.co_argcount\n if var:\n argcount += raw.co_flags & CO_VARARGS\n argcount += raw.co_flags & CO_VARKEYWORDS\n return raw.co_varnames[:argcount]\n\n\nclass Frame(object):\n \"\"\"Wrapper around a Python frame holding f_locals and f_globals\n in which expressions can be evaluated.\"\"\"\n\n def __init__(self, frame):\n self.lineno = frame.f_lineno - 1\n self.f_globals = frame.f_globals\n self.f_locals = frame.f_locals\n self.raw = frame\n self.code = Code(frame.f_code)\n\n @property\n def statement(self):\n \"\"\" statement this frame is at \"\"\"\n import _pytest._code\n\n if self.code.fullsource is None:\n return _pytest._code.Source(\"\")\n return self.code.fullsource.getstatement(self.lineno)\n\n def eval(self, code, **vars):\n \"\"\" evaluate 'code' in the frame\n\n 'vars' are optional additional local variables\n\n returns the result of the evaluation\n \"\"\"\n f_locals = self.f_locals.copy()\n f_locals.update(vars)\n return eval(code, self.f_globals, f_locals)\n\n def exec_(self, code, **vars):\n \"\"\" exec 'code' in the frame\n\n 'vars' are optiona; additional local variables\n \"\"\"\n f_locals = self.f_locals.copy()\n f_locals.update(vars)\n exec(code, self.f_globals, f_locals)\n\n def repr(self, object):\n \"\"\" return a 'safe' (non-recursive, one-line) string repr for 'object'\n \"\"\"\n return saferepr(object)\n\n def is_true(self, object):\n return object\n\n def getargs(self, var=False):\n \"\"\" return a list of tuples (name, value) for all arguments\n\n if 'var' is set True also include the variable and keyword\n arguments when present\n \"\"\"\n retval = []\n for arg in self.code.getargs(var):\n try:\n retval.append((arg, self.f_locals[arg]))\n except KeyError:\n pass # this can occur when using Psyco\n return retval\n\n\nclass TracebackEntry(object):\n \"\"\" a single entry in a traceback \"\"\"\n\n _repr_style = None\n exprinfo = None\n\n def __init__(self, rawentry, excinfo=None):\n self._excinfo = excinfo\n self._rawentry = rawentry\n self.lineno = rawentry.tb_lineno - 1\n\n def set_repr_style(self, mode):\n assert mode in (\"short\", \"long\")\n self._repr_style = mode\n\n @property\n def frame(self):\n import _pytest._code\n\n return _pytest._code.Frame(self._rawentry.tb_frame)\n\n @property\n def relline(self):\n return self.lineno - self.frame.code.firstlineno\n\n def __repr__(self):\n return \"\" % (self.frame.code.path, self.lineno + 1)\n\n @property\n def statement(self):\n \"\"\" _pytest._code.Source object for the current statement \"\"\"\n source = self.frame.code.fullsource\n return source.getstatement(self.lineno)\n\n @property\n def path(self):\n \"\"\" path to the source code \"\"\"\n return self.frame.code.path\n\n def getlocals(self):\n return self.frame.f_locals\n\n locals = property(getlocals, None, None, \"locals of underlaying frame\")\n\n def getfirstlinesource(self):\n # on Jython this firstlineno can be -1 apparently\n return max(self.frame.code.firstlineno, 0)\n\n def getsource(self, astcache=None):\n \"\"\" return failing source code. \"\"\"\n # we use the passed in astcache to not reparse asttrees\n # within exception info printing\n from _pytest._code.source import getstatementrange_ast\n\n source = self.frame.code.fullsource\n if source is None:\n return None\n key = astnode = None\n if astcache is not None:\n key = self.frame.code.path\n if key is not None:\n astnode = astcache.get(key, None)\n start = self.getfirstlinesource()\n try:\n astnode, _, end = getstatementrange_ast(\n self.lineno, source, astnode=astnode\n )\n except SyntaxError:\n end = self.lineno + 1\n else:\n if key is not None:\n astcache[key] = astnode\n return source[start:end]\n\n source = property(getsource)\n\n def ishidden(self):\n \"\"\" return True if the current frame has a var __tracebackhide__\n resolving to True.\n\n If __tracebackhide__ is a callable, it gets called with the\n ExceptionInfo instance and can decide whether to hide the traceback.\n\n mostly for internal use\n \"\"\"\n f = self.frame\n tbh = f.f_locals.get(\n \"__tracebackhide__\", f.f_globals.get(\"__tracebackhide__\", False)\n )\n if tbh and callable(tbh):\n return tbh(None if self._excinfo is None else self._excinfo())\n return tbh\n\n def __str__(self):\n try:\n fn = str(self.path)\n except py.error.Error:\n fn = \"???\"\n name = self.frame.code.name\n try:\n line = str(self.statement).lstrip()\n except KeyboardInterrupt:\n raise\n except: # noqa\n line = \"???\"\n return \" File %r:%d in %s\\n %s\\n\" % (fn, self.lineno + 1, name, line)\n\n def name(self):\n return self.frame.code.raw.co_name\n\n name = property(name, None, None, \"co_name of underlaying code\")\n\n\nclass Traceback(list):\n \"\"\" Traceback objects encapsulate and offer higher level\n access to Traceback entries.\n \"\"\"\n\n Entry = TracebackEntry\n\n def __init__(self, tb, excinfo=None):\n \"\"\" initialize from given python traceback object and ExceptionInfo \"\"\"\n self._excinfo = excinfo\n if hasattr(tb, \"tb_next\"):\n\n def f(cur):\n while cur is not None:\n yield self.Entry(cur, excinfo=excinfo)\n cur = cur.tb_next\n\n list.__init__(self, f(tb))\n else:\n list.__init__(self, tb)\n\n def cut(self, path=None, lineno=None, firstlineno=None, excludepath=None):\n \"\"\" return a Traceback instance wrapping part of this Traceback\n\n by provding any combination of path, lineno and firstlineno, the\n first frame to start the to-be-returned traceback is determined\n\n this allows cutting the first part of a Traceback instance e.g.\n for formatting reasons (removing some uninteresting bits that deal\n with handling of the exception/traceback)\n \"\"\"\n for x in self:\n code = x.frame.code\n codepath = code.path\n if (\n (path is None or codepath == path)\n and (\n excludepath is None\n or not hasattr(codepath, \"relto\")\n or not codepath.relto(excludepath)\n )\n and (lineno is None or x.lineno == lineno)\n and (firstlineno is None or x.frame.code.firstlineno == firstlineno)\n ):\n return Traceback(x._rawentry, self._excinfo)\n return self\n\n def __getitem__(self, key):\n val = super(Traceback, self).__getitem__(key)\n if isinstance(key, type(slice(0))):\n val = self.__class__(val)\n return val\n\n def filter(self, fn=lambda x: not x.ishidden()):\n \"\"\" return a Traceback instance with certain items removed\n\n fn is a function that gets a single argument, a TracebackEntry\n instance, and should return True when the item should be added\n to the Traceback, False when not\n\n by default this removes all the TracebackEntries which are hidden\n (see ishidden() above)\n \"\"\"\n return Traceback(filter(fn, self), self._excinfo)\n\n def getcrashentry(self):\n \"\"\" return last non-hidden traceback entry that lead\n to the exception of a traceback.\n \"\"\"\n for i in range(-1, -len(self) - 1, -1):\n entry = self[i]\n if not entry.ishidden():\n return entry\n return self[-1]\n\n def recursionindex(self):\n \"\"\" return the index of the frame/TracebackEntry where recursion\n originates if appropriate, None if no recursion occurred\n \"\"\"\n cache = {}\n for i, entry in enumerate(self):\n # id for the code.raw is needed to work around\n # the strange metaprogramming in the decorator lib from pypi\n # which generates code objects that have hash/value equality\n # XXX needs a test\n key = entry.frame.code.path, id(entry.frame.code.raw), entry.lineno\n # print \"checking for recursion at\", key\n values = cache.setdefault(key, [])\n if values:\n f = entry.frame\n loc = f.f_locals\n for otherloc in values:\n if f.is_true(\n f.eval(\n co_equal,\n __recursioncache_locals_1=loc,\n __recursioncache_locals_2=otherloc,\n )\n ):\n return i\n values.append(entry.frame.f_locals)\n return None\n\n\nco_equal = compile(\n \"__recursioncache_locals_1 == __recursioncache_locals_2\", \"?\", \"eval\"\n)\n\n\n@attr.s(repr=False)\nclass ExceptionInfo(object):\n \"\"\" wraps sys.exc_info() objects and offers\n help for navigating the traceback.\n \"\"\"\n\n _assert_start_repr = (\n \"AssertionError(u'assert \" if _PY2 else \"AssertionError('assert \"\n )\n\n _excinfo = attr.ib()\n _striptext = attr.ib(default=\"\")\n _traceback = attr.ib(default=None)\n\n @classmethod\n def from_current(cls, exprinfo=None):\n \"\"\"returns an ExceptionInfo matching the current traceback\n\n .. warning::\n\n Experimental API\n\n\n :param exprinfo: a text string helping to determine if we should\n strip ``AssertionError`` from the output, defaults\n to the exception message/``__str__()``\n \"\"\"\n tup = sys.exc_info()\n assert tup[0] is not None, \"no current exception\"\n _striptext = \"\"\n if exprinfo is None and isinstance(tup[1], AssertionError):\n exprinfo = getattr(tup[1], \"msg\", None)\n if exprinfo is None:\n exprinfo = saferepr(tup[1])\n if exprinfo and exprinfo.startswith(cls._assert_start_repr):\n _striptext = \"AssertionError: \"\n\n return cls(tup, _striptext)\n\n @classmethod\n def for_later(cls):\n \"\"\"return an unfilled ExceptionInfo\n \"\"\"\n return cls(None)\n\n @property\n def type(self):\n \"\"\"the exception class\"\"\"\n return self._excinfo[0]\n\n @property\n def value(self):\n \"\"\"the exception value\"\"\"\n return self._excinfo[1]\n\n @property\n def tb(self):\n \"\"\"the exception raw traceback\"\"\"\n return self._excinfo[2]\n\n @property\n def typename(self):\n \"\"\"the type name of the exception\"\"\"\n return self.type.__name__\n\n @property\n def traceback(self):\n \"\"\"the traceback\"\"\"\n if self._traceback is None:\n self._traceback = Traceback(self.tb, excinfo=ref(self))\n return self._traceback\n\n @traceback.setter\n def traceback(self, value):\n self._traceback = value\n\n def __repr__(self):\n if self._excinfo is None:\n return \"\"\n return \"\" % (self.typename, len(self.traceback))\n\n def exconly(self, tryshort=False):\n \"\"\" return the exception as a string\n\n when 'tryshort' resolves to True, and the exception is a\n _pytest._code._AssertionError, only the actual exception part of\n the exception representation is returned (so 'AssertionError: ' is\n removed from the beginning)\n \"\"\"\n lines = format_exception_only(self.type, self.value)\n text = \"\".join(lines)\n text = text.rstrip()\n if tryshort:\n if text.startswith(self._striptext):\n text = text[len(self._striptext) :]\n return text\n\n def errisinstance(self, exc):\n \"\"\" return True if the exception is an instance of exc \"\"\"\n return isinstance(self.value, exc)\n\n def _getreprcrash(self):\n exconly = self.exconly(tryshort=True)\n entry = self.traceback.getcrashentry()\n path, lineno = entry.frame.code.raw.co_filename, entry.lineno\n return ReprFileLocation(path, lineno + 1, exconly)\n\n def getrepr(\n self,\n showlocals=False,\n style=\"long\",\n abspath=False,\n tbfilter=True,\n funcargs=False,\n truncate_locals=True,\n chain=True,\n ):\n \"\"\"\n Return str()able representation of this exception info.\n\n :param bool showlocals:\n Show locals per traceback entry.\n Ignored if ``style==\"native\"``.\n\n :param str style: long|short|no|native traceback style\n\n :param bool abspath:\n If paths should be changed to absolute or left unchanged.\n\n :param bool tbfilter:\n Hide entries that contain a local variable ``__tracebackhide__==True``.\n Ignored if ``style==\"native\"``.\n\n :param bool funcargs:\n Show fixtures (\"funcargs\" for legacy purposes) per traceback entry.\n\n :param bool truncate_locals:\n With ``showlocals==True``, make sure locals can be safely represented as strings.\n\n :param bool chain: if chained exceptions in Python 3 should be shown.\n\n .. versionchanged:: 3.9\n\n Added the ``chain`` parameter.\n \"\"\"\n if style == \"native\":\n return ReprExceptionInfo(\n ReprTracebackNative(\n traceback.format_exception(\n self.type, self.value, self.traceback[0]._rawentry\n )\n ),\n self._getreprcrash(),\n )\n\n fmt = FormattedExcinfo(\n showlocals=showlocals,\n style=style,\n abspath=abspath,\n tbfilter=tbfilter,\n funcargs=funcargs,\n truncate_locals=truncate_locals,\n chain=chain,\n )\n return fmt.repr_excinfo(self)\n\n def __str__(self):\n if self._excinfo is None:\n return repr(self)\n entry = self.traceback[-1]\n loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly())\n return str(loc)\n\n def __unicode__(self):\n entry = self.traceback[-1]\n loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly())\n return text_type(loc)\n\n def match(self, regexp):\n \"\"\"\n Check whether the regular expression 'regexp' is found in the string\n representation of the exception using ``re.search``. If it matches\n then True is returned (so that it is possible to write\n ``assert excinfo.match()``). If it doesn't match an AssertionError is\n raised.\n \"\"\"\n __tracebackhide__ = True\n value = (\n text_type(self.value) if isinstance(regexp, text_type) else str(self.value)\n )\n if not re.search(regexp, value):\n raise AssertionError(\n u\"Pattern {!r} not found in {!r}\".format(regexp, value)\n )\n return True\n\n\n@attr.s\nclass FormattedExcinfo(object):\n \"\"\" presenting information about failing Functions and Generators. \"\"\"\n\n # for traceback entries\n flow_marker = \">\"\n fail_marker = \"E\"\n\n showlocals = attr.ib(default=False)\n style = attr.ib(default=\"long\")\n abspath = attr.ib(default=True)\n tbfilter = attr.ib(default=True)\n funcargs = attr.ib(default=False)\n truncate_locals = attr.ib(default=True)\n chain = attr.ib(default=True)\n astcache = attr.ib(default=attr.Factory(dict), init=False, repr=False)\n\n def _getindent(self, source):\n # figure out indent for given source\n try:\n s = str(source.getstatement(len(source) - 1))\n except KeyboardInterrupt:\n raise\n except: # noqa\n try:\n s = str(source[-1])\n except KeyboardInterrupt:\n raise\n except: # noqa\n return 0\n return 4 + (len(s) - len(s.lstrip()))\n\n def _getentrysource(self, entry):\n source = entry.getsource(self.astcache)\n if source is not None:\n source = source.deindent()\n return source\n\n def repr_args(self, entry):\n if self.funcargs:\n args = []\n for argname, argvalue in entry.frame.getargs(var=True):\n args.append((argname, saferepr(argvalue)))\n return ReprFuncArgs(args)\n\n def get_source(self, source, line_index=-1, excinfo=None, short=False):\n \"\"\" return formatted and marked up source lines. \"\"\"\n import _pytest._code\n\n lines = []\n if source is None or line_index >= len(source.lines):\n source = _pytest._code.Source(\"???\")\n line_index = 0\n if line_index < 0:\n line_index += len(source)\n space_prefix = \" \"\n if short:\n lines.append(space_prefix + source.lines[line_index].strip())\n else:\n for line in source.lines[:line_index]:\n lines.append(space_prefix + line)\n lines.append(self.flow_marker + \" \" + source.lines[line_index])\n for line in source.lines[line_index + 1 :]:\n lines.append(space_prefix + line)\n if excinfo is not None:\n indent = 4 if short else self._getindent(source)\n lines.extend(self.get_exconly(excinfo, indent=indent, markall=True))\n return lines\n\n def get_exconly(self, excinfo, indent=4, markall=False):\n lines = []\n indent = \" \" * indent\n # get the real exception information out\n exlines = excinfo.exconly(tryshort=True).split(\"\\n\")\n failindent = self.fail_marker + indent[1:]\n for line in exlines:\n lines.append(failindent + line)\n if not markall:\n failindent = indent\n return lines\n\n def repr_locals(self, locals):\n if self.showlocals:\n lines = []\n keys = [loc for loc in locals if loc[0] != \"@\"]\n keys.sort()\n for name in keys:\n value = locals[name]\n if name == \"__builtins__\":\n lines.append(\"__builtins__ = \")\n else:\n # This formatting could all be handled by the\n # _repr() function, which is only reprlib.Repr in\n # disguise, so is very configurable.\n if self.truncate_locals:\n str_repr = saferepr(value)\n else:\n str_repr = safeformat(value)\n # if len(str_repr) < 70 or not isinstance(value,\n # (list, tuple, dict)):\n lines.append(\"%-10s = %s\" % (name, str_repr))\n # else:\n # self._line(\"%-10s =\\\\\" % (name,))\n # # XXX\n # pprint.pprint(value, stream=self.excinfowriter)\n return ReprLocals(lines)\n\n def repr_traceback_entry(self, entry, excinfo=None):\n import _pytest._code\n\n source = self._getentrysource(entry)\n if source is None:\n source = _pytest._code.Source(\"???\")\n line_index = 0\n else:\n # entry.getfirstlinesource() can be -1, should be 0 on jython\n line_index = entry.lineno - max(entry.getfirstlinesource(), 0)\n\n lines = []\n style = entry._repr_style\n if style is None:\n style = self.style\n if style in (\"short\", \"long\"):\n short = style == \"short\"\n reprargs = self.repr_args(entry) if not short else None\n s = self.get_source(source, line_index, excinfo, short=short)\n lines.extend(s)\n if short:\n message = \"in %s\" % (entry.name)\n else:\n message = excinfo and excinfo.typename or \"\"\n path = self._makepath(entry.path)\n filelocrepr = ReprFileLocation(path, entry.lineno + 1, message)\n localsrepr = None\n if not short:\n localsrepr = self.repr_locals(entry.locals)\n return ReprEntry(lines, reprargs, localsrepr, filelocrepr, style)\n if excinfo:\n lines.extend(self.get_exconly(excinfo, indent=4))\n return ReprEntry(lines, None, None, None, style)\n\n def _makepath(self, path):\n if not self.abspath:\n try:\n np = py.path.local().bestrelpath(path)\n except OSError:\n return path\n if len(np) < len(str(path)):\n path = np\n return path\n\n def repr_traceback(self, excinfo):\n traceback = excinfo.traceback\n if self.tbfilter:\n traceback = traceback.filter()\n\n if is_recursion_error(excinfo):\n traceback, extraline = self._truncate_recursive_traceback(traceback)\n else:\n extraline = None\n\n last = traceback[-1]\n entries = []\n for index, entry in enumerate(traceback):\n einfo = (last == entry) and excinfo or None\n reprentry = self.repr_traceback_entry(entry, einfo)\n entries.append(reprentry)\n return ReprTraceback(entries, extraline, style=self.style)\n\n def _truncate_recursive_traceback(self, traceback):\n \"\"\"\n Truncate the given recursive traceback trying to find the starting point\n of the recursion.\n\n The detection is done by going through each traceback entry and finding the\n point in which the locals of the frame are equal to the locals of a previous frame (see ``recursionindex()``.\n\n Handle the situation where the recursion process might raise an exception (for example\n comparing numpy arrays using equality raises a TypeError), in which case we do our best to\n warn the user of the error and show a limited traceback.\n \"\"\"\n try:\n recursionindex = traceback.recursionindex()\n except Exception as e:\n max_frames = 10\n extraline = (\n \"!!! Recursion error detected, but an error occurred locating the origin of recursion.\\n\"\n \" The following exception happened when comparing locals in the stack frame:\\n\"\n \" {exc_type}: {exc_msg}\\n\"\n \" Displaying first and last {max_frames} stack frames out of {total}.\"\n ).format(\n exc_type=type(e).__name__,\n exc_msg=safe_str(e),\n max_frames=max_frames,\n total=len(traceback),\n )\n traceback = traceback[:max_frames] + traceback[-max_frames:]\n else:\n if recursionindex is not None:\n extraline = \"!!! Recursion detected (same locals & position)\"\n traceback = traceback[: recursionindex + 1]\n else:\n extraline = None\n\n return traceback, extraline\n\n def repr_excinfo(self, excinfo):\n if _PY2:\n reprtraceback = self.repr_traceback(excinfo)\n reprcrash = excinfo._getreprcrash()\n\n return ReprExceptionInfo(reprtraceback, reprcrash)\n else:\n repr_chain = []\n e = excinfo.value\n descr = None\n seen = set()\n while e is not None and id(e) not in seen:\n seen.add(id(e))\n if excinfo:\n reprtraceback = self.repr_traceback(excinfo)\n reprcrash = excinfo._getreprcrash()\n else:\n # fallback to native repr if the exception doesn't have a traceback:\n # ExceptionInfo objects require a full traceback to work\n reprtraceback = ReprTracebackNative(\n traceback.format_exception(type(e), e, None)\n )\n reprcrash = None\n\n repr_chain += [(reprtraceback, reprcrash, descr)]\n if e.__cause__ is not None and self.chain:\n e = e.__cause__\n excinfo = (\n ExceptionInfo((type(e), e, e.__traceback__))\n if e.__traceback__\n else None\n )\n descr = \"The above exception was the direct cause of the following exception:\"\n elif (\n e.__context__ is not None\n and not e.__suppress_context__\n and self.chain\n ):\n e = e.__context__\n excinfo = (\n ExceptionInfo((type(e), e, e.__traceback__))\n if e.__traceback__\n else None\n )\n descr = \"During handling of the above exception, another exception occurred:\"\n else:\n e = None\n repr_chain.reverse()\n return ExceptionChainRepr(repr_chain)\n\n\nclass TerminalRepr(object):\n def __str__(self):\n s = self.__unicode__()\n if _PY2:\n s = s.encode(\"utf-8\")\n return s\n\n def __unicode__(self):\n # FYI this is called from pytest-xdist's serialization of exception\n # information.\n io = py.io.TextIO()\n tw = py.io.TerminalWriter(file=io)\n self.toterminal(tw)\n return io.getvalue().strip()\n\n def __repr__(self):\n return \"<%s instance at %0x>\" % (self.__class__, id(self))\n\n\nclass ExceptionRepr(TerminalRepr):\n def __init__(self):\n self.sections = []\n\n def addsection(self, name, content, sep=\"-\"):\n self.sections.append((name, content, sep))\n\n def toterminal(self, tw):\n for name, content, sep in self.sections:\n tw.sep(sep, name)\n tw.line(content)\n\n\nclass ExceptionChainRepr(ExceptionRepr):\n def __init__(self, chain):\n super(ExceptionChainRepr, self).__init__()\n self.chain = chain\n # reprcrash and reprtraceback of the outermost (the newest) exception\n # in the chain\n self.reprtraceback = chain[-1][0]\n self.reprcrash = chain[-1][1]\n\n def toterminal(self, tw):\n for element in self.chain:\n element[0].toterminal(tw)\n if element[2] is not None:\n tw.line(\"\")\n tw.line(element[2], yellow=True)\n super(ExceptionChainRepr, self).toterminal(tw)\n\n\nclass ReprExceptionInfo(ExceptionRepr):\n def __init__(self, reprtraceback, reprcrash):\n super(ReprExceptionInfo, self).__init__()\n self.reprtraceback = reprtraceback\n self.reprcrash = reprcrash\n\n def toterminal(self, tw):\n self.reprtraceback.toterminal(tw)\n super(ReprExceptionInfo, self).toterminal(tw)\n\n\nclass ReprTraceback(TerminalRepr):\n entrysep = \"_ \"\n\n def __init__(self, reprentries, extraline, style):\n self.reprentries = reprentries\n self.extraline = extraline\n self.style = style\n\n def toterminal(self, tw):\n # the entries might have different styles\n for i, entry in enumerate(self.reprentries):\n if entry.style == \"long\":\n tw.line(\"\")\n entry.toterminal(tw)\n if i < len(self.reprentries) - 1:\n next_entry = self.reprentries[i + 1]\n if (\n entry.style == \"long\"\n or entry.style == \"short\"\n and next_entry.style == \"long\"\n ):\n tw.sep(self.entrysep)\n\n if self.extraline:\n tw.line(self.extraline)\n\n\nclass ReprTracebackNative(ReprTraceback):\n def __init__(self, tblines):\n self.style = \"native\"\n self.reprentries = [ReprEntryNative(tblines)]\n self.extraline = None\n\n\nclass ReprEntryNative(TerminalRepr):\n style = \"native\"\n\n def __init__(self, tblines):\n self.lines = tblines\n\n def toterminal(self, tw):\n tw.write(\"\".join(self.lines))\n\n\nclass ReprEntry(TerminalRepr):\n def __init__(self, lines, reprfuncargs, reprlocals, filelocrepr, style):\n self.lines = lines\n self.reprfuncargs = reprfuncargs\n self.reprlocals = reprlocals\n self.reprfileloc = filelocrepr\n self.style = style\n\n def toterminal(self, tw):\n if self.style == \"short\":\n self.reprfileloc.toterminal(tw)\n for line in self.lines:\n red = line.startswith(\"E \")\n tw.line(line, bold=True, red=red)\n # tw.line(\"\")\n return\n if self.reprfuncargs:\n self.reprfuncargs.toterminal(tw)\n for line in self.lines:\n red = line.startswith(\"E \")\n tw.line(line, bold=True, red=red)\n if self.reprlocals:\n tw.line(\"\")\n self.reprlocals.toterminal(tw)\n if self.reprfileloc:\n if self.lines:\n tw.line(\"\")\n self.reprfileloc.toterminal(tw)\n\n def __str__(self):\n return \"%s\\n%s\\n%s\" % (\"\\n\".join(self.lines), self.reprlocals, self.reprfileloc)\n\n\nclass ReprFileLocation(TerminalRepr):\n def __init__(self, path, lineno, message):\n self.path = str(path)\n self.lineno = lineno\n self.message = message\n\n def toterminal(self, tw):\n # filename and lineno output for each entry,\n # using an output format that most editors unterstand\n msg = self.message\n i = msg.find(\"\\n\")\n if i != -1:\n msg = msg[:i]\n tw.write(self.path, bold=True, red=True)\n tw.line(\":%s: %s\" % (self.lineno, msg))\n\n\nclass ReprLocals(TerminalRepr):\n def __init__(self, lines):\n self.lines = lines\n\n def toterminal(self, tw):\n for line in self.lines:\n tw.line(line)\n\n\nclass ReprFuncArgs(TerminalRepr):\n def __init__(self, args):\n self.args = args\n\n def toterminal(self, tw):\n if self.args:\n linesofar = \"\"\n for name, value in self.args:\n ns = \"%s = %s\" % (safe_str(name), safe_str(value))\n if len(ns) + len(linesofar) + 2 > tw.fullwidth:\n if linesofar:\n tw.line(linesofar)\n linesofar = ns\n else:\n if linesofar:\n linesofar += \", \" + ns\n else:\n linesofar = ns\n if linesofar:\n tw.line(linesofar)\n tw.line(\"\")\n\n\ndef getrawcode(obj, trycall=True):\n \"\"\" return code object for given function. \"\"\"\n try:\n return obj.__code__\n except AttributeError:\n obj = getattr(obj, \"im_func\", obj)\n obj = getattr(obj, \"func_code\", obj)\n obj = getattr(obj, \"f_code\", obj)\n obj = getattr(obj, \"__code__\", obj)\n if trycall and not hasattr(obj, \"co_firstlineno\"):\n if hasattr(obj, \"__call__\") and not inspect.isclass(obj):\n x = getrawcode(obj.__call__, trycall=False)\n if hasattr(x, \"co_firstlineno\"):\n return x\n return obj\n\n\nif PY35: # RecursionError introduced in 3.5\n\n def is_recursion_error(excinfo):\n return excinfo.errisinstance(RecursionError) # noqa\n\n\nelse:\n\n def is_recursion_error(excinfo):\n if not excinfo.errisinstance(RuntimeError):\n return False\n try:\n return \"maximum recursion depth exceeded\" in str(excinfo.value)\n except UnicodeError:\n return False\n\n\n# relative paths that we use to filter traceback entries from appearing to the user;\n# see filter_traceback\n# note: if we need to add more paths than what we have now we should probably use a list\n# for better maintenance\n\n_PLUGGY_DIR = py.path.local(pluggy.__file__.rstrip(\"oc\"))\n# pluggy is either a package or a single module depending on the version\nif _PLUGGY_DIR.basename == \"__init__.py\":\n _PLUGGY_DIR = _PLUGGY_DIR.dirpath()\n_PYTEST_DIR = py.path.local(_pytest.__file__).dirpath()\n_PY_DIR = py.path.local(py.__file__).dirpath()\n\n\ndef filter_traceback(entry):\n \"\"\"Return True if a TracebackEntry instance should be removed from tracebacks:\n * dynamically generated code (no code to show up for it);\n * internal traceback from pytest or its internal libraries, py and pluggy.\n \"\"\"\n # entry.path might sometimes return a str object when the entry\n # points to dynamically generated code\n # see https://bitbucket.org/pytest-dev/py/issues/71\n raw_filename = entry.frame.code.raw.co_filename\n is_generated = \"<\" in raw_filename and \">\" in raw_filename\n if is_generated:\n return False\n # entry.path might point to a non-existing file, in which case it will\n # also return a str object. see #1133\n p = py.path.local(entry.path)\n return (\n not p.relto(_PLUGGY_DIR) and not p.relto(_PYTEST_DIR) and not p.relto(_PY_DIR)\n )\n"},{"attributeType":"null","col":0,"comment":"null","endLoc":166,"id":5381,"name":"CO_VARARGS","nodeType":"Attribute","startLoc":166,"text":"CO_VARARGS"},{"attributeType":"null","col":0,"comment":"null","endLoc":167,"id":5382,"name":"CO_VARKEYWORDS","nodeType":"Attribute","startLoc":167,"text":"CO_VARKEYWORDS"},{"attributeType":"ReferenceType","col":0,"comment":"null","endLoc":33,"id":5383,"name":"ref","nodeType":"Attribute","startLoc":33,"text":"ref"},{"attributeType":"ReferenceType","col":0,"comment":"null","endLoc":654,"id":5384,"name":"ref","nodeType":"Attribute","startLoc":654,"text":"ref"},{"col":4,"comment":"Make sure that text which contains non-ascii characters is pasted\n correctly. See #1219.\n ","endLoc":87,"header":"def test_non_ascii_paste_text(self, testdir)","id":5385,"name":"test_non_ascii_paste_text","nodeType":"Function","startLoc":65,"text":"def test_non_ascii_paste_text(self, testdir):\n \"\"\"Make sure that text which contains non-ascii characters is pasted\n correctly. See #1219.\n \"\"\"\n testdir.makepyfile(\n test_unicode=\"\"\"\n # -*- coding: utf-8 -*-\n def test():\n assert '☺' == 1\n \"\"\"\n )\n result = testdir.runpytest(\"--pastebin=all\")\n if sys.version_info[0] >= 3:\n expected_msg = \"*assert '☺' == 1*\"\n else:\n expected_msg = \"*assert '\\\\xe2\\\\x98\\\\xba' == 1*\"\n result.stdout.fnmatch_lines(\n [\n expected_msg,\n \"*== 1 failed in *\",\n \"*Sending information to Paste Service*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":1236,"header":"def test_many(self, capfd)","id":5386,"name":"test_many","nodeType":"Function","startLoc":1232,"text":"def test_many(self, capfd):\n with lsof_check():\n for i in range(10):\n cap = StdCaptureFD()\n cap.stop_capturing()"},{"className":"TracebackEntry","col":0,"comment":" a single entry in a traceback ","endLoc":276,"id":5388,"nodeType":"Class","startLoc":166,"text":"class TracebackEntry(object):\n \"\"\" a single entry in a traceback \"\"\"\n\n _repr_style = None\n exprinfo = None\n\n def __init__(self, rawentry, excinfo=None):\n self._excinfo = excinfo\n self._rawentry = rawentry\n self.lineno = rawentry.tb_lineno - 1\n\n def set_repr_style(self, mode):\n assert mode in (\"short\", \"long\")\n self._repr_style = mode\n\n @property\n def frame(self):\n import _pytest._code\n\n return _pytest._code.Frame(self._rawentry.tb_frame)\n\n @property\n def relline(self):\n return self.lineno - self.frame.code.firstlineno\n\n def __repr__(self):\n return \"\" % (self.frame.code.path, self.lineno + 1)\n\n @property\n def statement(self):\n \"\"\" _pytest._code.Source object for the current statement \"\"\"\n source = self.frame.code.fullsource\n return source.getstatement(self.lineno)\n\n @property\n def path(self):\n \"\"\" path to the source code \"\"\"\n return self.frame.code.path\n\n def getlocals(self):\n return self.frame.f_locals\n\n locals = property(getlocals, None, None, \"locals of underlaying frame\")\n\n def getfirstlinesource(self):\n # on Jython this firstlineno can be -1 apparently\n return max(self.frame.code.firstlineno, 0)\n\n def getsource(self, astcache=None):\n \"\"\" return failing source code. \"\"\"\n # we use the passed in astcache to not reparse asttrees\n # within exception info printing\n from _pytest._code.source import getstatementrange_ast\n\n source = self.frame.code.fullsource\n if source is None:\n return None\n key = astnode = None\n if astcache is not None:\n key = self.frame.code.path\n if key is not None:\n astnode = astcache.get(key, None)\n start = self.getfirstlinesource()\n try:\n astnode, _, end = getstatementrange_ast(\n self.lineno, source, astnode=astnode\n )\n except SyntaxError:\n end = self.lineno + 1\n else:\n if key is not None:\n astcache[key] = astnode\n return source[start:end]\n\n source = property(getsource)\n\n def ishidden(self):\n \"\"\" return True if the current frame has a var __tracebackhide__\n resolving to True.\n\n If __tracebackhide__ is a callable, it gets called with the\n ExceptionInfo instance and can decide whether to hide the traceback.\n\n mostly for internal use\n \"\"\"\n f = self.frame\n tbh = f.f_locals.get(\n \"__tracebackhide__\", f.f_globals.get(\"__tracebackhide__\", False)\n )\n if tbh and callable(tbh):\n return tbh(None if self._excinfo is None else self._excinfo())\n return tbh\n\n def __str__(self):\n try:\n fn = str(self.path)\n except py.error.Error:\n fn = \"???\"\n name = self.frame.code.name\n try:\n line = str(self.statement).lstrip()\n except KeyboardInterrupt:\n raise\n except: # noqa\n line = \"???\"\n return \" File %r:%d in %s\\n %s\\n\" % (fn, self.lineno + 1, name, line)\n\n def name(self):\n return self.frame.code.raw.co_name\n\n name = property(name, None, None, \"co_name of underlaying code\")"},{"col":4,"comment":"null","endLoc":179,"header":"def set_repr_style(self, mode)","id":5389,"name":"set_repr_style","nodeType":"Function","startLoc":177,"text":"def set_repr_style(self, mode):\n assert mode in (\"short\", \"long\")\n self._repr_style = mode"},{"col":4,"comment":"null","endLoc":185,"header":"@property\n def frame(self)","id":5390,"name":"frame","nodeType":"Function","startLoc":181,"text":"@property\n def frame(self):\n import _pytest._code\n\n return _pytest._code.Frame(self._rawentry.tb_frame)"},{"attributeType":"null","col":4,"comment":"null","endLoc":1197,"id":5391,"name":"pytestmark","nodeType":"Attribute","startLoc":1197,"text":"pytestmark"},{"attributeType":"staticmethod","col":4,"comment":"null","endLoc":1198,"id":5392,"name":"captureclass","nodeType":"Attribute","startLoc":1198,"text":"captureclass"},{"className":"TestStdCaptureFDinvalidFD","col":0,"comment":"null","endLoc":1272,"id":5393,"nodeType":"Class","startLoc":1239,"text":"class TestStdCaptureFDinvalidFD(object):\n pytestmark = needsosdup\n\n def test_stdcapture_fd_invalid_fd(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import os\n from _pytest import capture\n\n def StdCaptureFD(out=True, err=True, in_=True):\n return capture.MultiCapture(out, err, in_, Capture=capture.FDCapture)\n\n def test_stdout():\n os.close(1)\n cap = StdCaptureFD(out=True, err=False, in_=False)\n assert repr(cap.out) == \"\"\n cap.stop_capturing()\n\n def test_stderr():\n os.close(2)\n cap = StdCaptureFD(out=False, err=True, in_=False)\n assert repr(cap.err) == \"\"\n cap.stop_capturing()\n\n def test_stdin():\n os.close(0)\n cap = StdCaptureFD(out=False, err=False, in_=True)\n assert repr(cap.in_) == \"\"\n cap.stop_capturing()\n \"\"\"\n )\n result = testdir.runpytest_subprocess(\"--capture=fd\")\n assert result.ret == 0\n assert result.parseoutcomes()[\"passed\"] == 3"},{"col":4,"comment":"null","endLoc":1272,"header":"def test_stdcapture_fd_invalid_fd(self, testdir)","id":5394,"name":"test_stdcapture_fd_invalid_fd","nodeType":"Function","startLoc":1242,"text":"def test_stdcapture_fd_invalid_fd(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import os\n from _pytest import capture\n\n def StdCaptureFD(out=True, err=True, in_=True):\n return capture.MultiCapture(out, err, in_, Capture=capture.FDCapture)\n\n def test_stdout():\n os.close(1)\n cap = StdCaptureFD(out=True, err=False, in_=False)\n assert repr(cap.out) == \"\"\n cap.stop_capturing()\n\n def test_stderr():\n os.close(2)\n cap = StdCaptureFD(out=False, err=True, in_=False)\n assert repr(cap.err) == \"\"\n cap.stop_capturing()\n\n def test_stdin():\n os.close(0)\n cap = StdCaptureFD(out=False, err=False, in_=True)\n assert repr(cap.in_) == \"\"\n cap.stop_capturing()\n \"\"\"\n )\n result = testdir.runpytest_subprocess(\"--capture=fd\")\n assert result.ret == 0\n assert result.parseoutcomes()[\"passed\"] == 3"},{"col":4,"comment":"null","endLoc":189,"header":"@property\n def relline(self)","id":5395,"name":"relline","nodeType":"Function","startLoc":187,"text":"@property\n def relline(self):\n return self.lineno - self.frame.code.firstlineno"},{"col":4,"comment":"null","endLoc":192,"header":"def __repr__(self)","id":5396,"name":"__repr__","nodeType":"Function","startLoc":191,"text":"def __repr__(self):\n return \"\" % (self.frame.code.path, self.lineno + 1)"},{"col":4,"comment":" _pytest._code.Source object for the current statement ","endLoc":198,"header":"@property\n def statement(self)","id":5397,"name":"statement","nodeType":"Function","startLoc":194,"text":"@property\n def statement(self):\n \"\"\" _pytest._code.Source object for the current statement \"\"\"\n source = self.frame.code.fullsource\n return source.getstatement(self.lineno)"},{"attributeType":"null","col":4,"comment":"null","endLoc":1240,"id":5398,"name":"pytestmark","nodeType":"Attribute","startLoc":1240,"text":"pytestmark"},{"col":0,"comment":"null","endLoc":38,"header":"def StdCapture(out=True, err=True, in_=True)","id":5399,"name":"StdCapture","nodeType":"Function","startLoc":37,"text":"def StdCapture(out=True, err=True, in_=True):\n return capture.MultiCapture(out, err, in_, Capture=capture.SysCapture)"},{"col":0,"comment":"null","endLoc":119,"header":"@pytest.mark.parametrize(\"method\", [\"fd\", \"sys\"])\ndef test_capturing_unicode(testdir, method)","id":5400,"name":"test_capturing_unicode","nodeType":"Function","startLoc":99,"text":"@pytest.mark.parametrize(\"method\", [\"fd\", \"sys\"])\ndef test_capturing_unicode(testdir, method):\n if hasattr(sys, \"pypy_version_info\") and sys.pypy_version_info < (2, 2):\n pytest.xfail(\"does not work on pypy < 2.2\")\n if sys.version_info >= (3, 0):\n obj = \"'b\\u00f6y'\"\n else:\n obj = \"u'\\u00f6y'\"\n testdir.makepyfile(\n \"\"\"\n # -*- coding: utf-8 -*-\n # taken from issue 227 from nosetests\n def test_unicode():\n import sys\n print(sys.stdout)\n print(%s)\n \"\"\"\n % obj\n )\n result = testdir.runpytest(\"--capture=%s\" % method)\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"className":"TestConfigFromdictargs","col":0,"comment":"null","endLoc":509,"id":5402,"nodeType":"Class","startLoc":446,"text":"class TestConfigFromdictargs(object):\n def test_basic_behavior(self, _sys_snapshot):\n from _pytest.config import Config\n\n option_dict = {\"verbose\": 444, \"foo\": \"bar\", \"capture\": \"no\"}\n args = [\"a\", \"b\"]\n\n config = Config.fromdictargs(option_dict, args)\n with pytest.raises(AssertionError):\n config.parse([\"should refuse to parse again\"])\n assert config.option.verbose == 444\n assert config.option.foo == \"bar\"\n assert config.option.capture == \"no\"\n assert config.args == args\n\n def test_origargs(self, _sys_snapshot):\n \"\"\"Show that fromdictargs can handle args in their \"orig\" format\"\"\"\n from _pytest.config import Config\n\n option_dict = {}\n args = [\"-vvvv\", \"-s\", \"a\", \"b\"]\n\n config = Config.fromdictargs(option_dict, args)\n assert config.args == [\"a\", \"b\"]\n assert config._origargs == args\n assert config.option.verbose == 4\n assert config.option.capture == \"no\"\n\n def test_inifilename(self, tmpdir):\n tmpdir.join(\"foo/bar.ini\").ensure().write(\n textwrap.dedent(\n \"\"\"\\\n [pytest]\n name = value\n \"\"\"\n )\n )\n\n from _pytest.config import Config\n\n inifile = \"../../foo/bar.ini\"\n option_dict = {\"inifilename\": inifile, \"capture\": \"no\"}\n\n cwd = tmpdir.join(\"a/b\")\n cwd.join(\"pytest.ini\").ensure().write(\n textwrap.dedent(\n \"\"\"\\\n [pytest]\n name = wrong-value\n should_not_be_set = true\n \"\"\"\n )\n )\n with cwd.ensure(dir=True).as_cwd():\n config = Config.fromdictargs(option_dict, ())\n\n assert config.args == [str(cwd)]\n assert config.option.inifilename == inifile\n assert config.option.capture == \"no\"\n\n # this indicates this is the file used for getting configuration values\n assert config.inifile == inifile\n assert config.inicfg.get(\"name\") == \"value\"\n assert config.inicfg.get(\"should_not_be_set\") is None"},{"col":4,"comment":"null","endLoc":459,"header":"def test_basic_behavior(self, _sys_snapshot)","id":5404,"name":"test_basic_behavior","nodeType":"Function","startLoc":447,"text":"def test_basic_behavior(self, _sys_snapshot):\n from _pytest.config import Config\n\n option_dict = {\"verbose\": 444, \"foo\": \"bar\", \"capture\": \"no\"}\n args = [\"a\", \"b\"]\n\n config = Config.fromdictargs(option_dict, args)\n with pytest.raises(AssertionError):\n config.parse([\"should refuse to parse again\"])\n assert config.option.verbose == 444\n assert config.option.foo == \"bar\"\n assert config.option.capture == \"no\"\n assert config.args == args"},{"className":"TestPaste","col":0,"comment":"null","endLoc":133,"id":5405,"nodeType":"Class","startLoc":90,"text":"class TestPaste(object):\n @pytest.fixture\n def pastebin(self, request):\n return request.config.pluginmanager.getplugin(\"pastebin\")\n\n @pytest.fixture\n def mocked_urlopen(self, monkeypatch):\n \"\"\"\n monkeypatch the actual urlopen calls done by the internal plugin\n function that connects to bpaste service.\n \"\"\"\n calls = []\n\n def mocked(url, data):\n calls.append((url, data))\n\n class DummyFile(object):\n def read(self):\n # part of html of a normal response\n return b'View raw.'\n\n return DummyFile()\n\n if sys.version_info < (3, 0):\n import urllib\n\n monkeypatch.setattr(urllib, \"urlopen\", mocked)\n else:\n import urllib.request\n\n monkeypatch.setattr(urllib.request, \"urlopen\", mocked)\n return calls\n\n def test_create_new_paste(self, pastebin, mocked_urlopen):\n result = pastebin.create_new_paste(b\"full-paste-contents\")\n assert result == \"https://bpaste.net/show/3c0c6750bd\"\n assert len(mocked_urlopen) == 1\n url, data = mocked_urlopen[0]\n assert type(data) is bytes\n lexer = \"python3\" if sys.version_info[0] >= 3 else \"python\"\n assert url == \"https://bpaste.net\"\n assert \"lexer=%s\" % lexer in data.decode()\n assert \"code=full-paste-contents\" in data.decode()\n assert \"expiry=1week\" in data.decode()"},{"col":4,"comment":"null","endLoc":93,"header":"@pytest.fixture\n def pastebin(self, request)","id":5406,"name":"pastebin","nodeType":"Function","startLoc":91,"text":"@pytest.fixture\n def pastebin(self, request):\n return request.config.pluginmanager.getplugin(\"pastebin\")"},{"col":4,"comment":"Show that fromdictargs can handle args in their \"orig\" format","endLoc":472,"header":"def test_origargs(self, _sys_snapshot)","id":5407,"name":"test_origargs","nodeType":"Function","startLoc":461,"text":"def test_origargs(self, _sys_snapshot):\n \"\"\"Show that fromdictargs can handle args in their \"orig\" format\"\"\"\n from _pytest.config import Config\n\n option_dict = {}\n args = [\"-vvvv\", \"-s\", \"a\", \"b\"]\n\n config = Config.fromdictargs(option_dict, args)\n assert config.args == [\"a\", \"b\"]\n assert config._origargs == args\n assert config.option.verbose == 4\n assert config.option.capture == \"no\""},{"col":4,"comment":"\n monkeypatch the actual urlopen calls done by the internal plugin\n function that connects to bpaste service.\n ","endLoc":121,"header":"@pytest.fixture\n def mocked_urlopen(self, monkeypatch)","id":5408,"name":"mocked_urlopen","nodeType":"Function","startLoc":95,"text":"@pytest.fixture\n def mocked_urlopen(self, monkeypatch):\n \"\"\"\n monkeypatch the actual urlopen calls done by the internal plugin\n function that connects to bpaste service.\n \"\"\"\n calls = []\n\n def mocked(url, data):\n calls.append((url, data))\n\n class DummyFile(object):\n def read(self):\n # part of html of a normal response\n return b'View raw.'\n\n return DummyFile()\n\n if sys.version_info < (3, 0):\n import urllib\n\n monkeypatch.setattr(urllib, \"urlopen\", mocked)\n else:\n import urllib.request\n\n monkeypatch.setattr(urllib.request, \"urlopen\", mocked)\n return calls"},{"col":4,"comment":"null","endLoc":509,"header":"def test_inifilename(self, tmpdir)","id":5409,"name":"test_inifilename","nodeType":"Function","startLoc":474,"text":"def test_inifilename(self, tmpdir):\n tmpdir.join(\"foo/bar.ini\").ensure().write(\n textwrap.dedent(\n \"\"\"\\\n [pytest]\n name = value\n \"\"\"\n )\n )\n\n from _pytest.config import Config\n\n inifile = \"../../foo/bar.ini\"\n option_dict = {\"inifilename\": inifile, \"capture\": \"no\"}\n\n cwd = tmpdir.join(\"a/b\")\n cwd.join(\"pytest.ini\").ensure().write(\n textwrap.dedent(\n \"\"\"\\\n [pytest]\n name = wrong-value\n should_not_be_set = true\n \"\"\"\n )\n )\n with cwd.ensure(dir=True).as_cwd():\n config = Config.fromdictargs(option_dict, ())\n\n assert config.args == [str(cwd)]\n assert config.option.inifilename == inifile\n assert config.option.capture == \"no\"\n\n # this indicates this is the file used for getting configuration values\n assert config.inifile == inifile\n assert config.inicfg.get(\"name\") == \"value\"\n assert config.inicfg.get(\"should_not_be_set\") is None"},{"fileName":"test_terminal.py","filePath":"testing","id":5410,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"\nterminal reporting of the full testing process.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport os\nimport sys\nimport textwrap\n\nimport pluggy\nimport py\n\nimport pytest\nfrom _pytest.main import EXIT_NOTESTSCOLLECTED\nfrom _pytest.reports import BaseReport\nfrom _pytest.terminal import _folded_skips\nfrom _pytest.terminal import _get_line_with_reprcrash_message\nfrom _pytest.terminal import _plugin_nameversions\nfrom _pytest.terminal import build_summary_stats_line\nfrom _pytest.terminal import getreportopt\nfrom _pytest.terminal import TerminalReporter\n\nDistInfo = collections.namedtuple(\"DistInfo\", [\"project_name\", \"version\"])\n\n\nclass Option(object):\n def __init__(self, verbosity=0, fulltrace=False):\n self.verbosity = verbosity\n self.fulltrace = fulltrace\n\n @property\n def args(self):\n values = []\n values.append(\"--verbosity=%d\" % self.verbosity)\n if self.fulltrace:\n values.append(\"--fulltrace\")\n return values\n\n\n@pytest.fixture(\n params=[\n Option(verbosity=0),\n Option(verbosity=1),\n Option(verbosity=-1),\n Option(fulltrace=True),\n ],\n ids=[\"default\", \"verbose\", \"quiet\", \"fulltrace\"],\n)\ndef option(request):\n return request.param\n\n\n@pytest.mark.parametrize(\n \"input,expected\",\n [\n ([DistInfo(project_name=\"test\", version=1)], [\"test-1\"]),\n ([DistInfo(project_name=\"pytest-test\", version=1)], [\"test-1\"]),\n (\n [\n DistInfo(project_name=\"test\", version=1),\n DistInfo(project_name=\"test\", version=1),\n ],\n [\"test-1\"],\n ),\n ],\n ids=[\"normal\", \"prefix-strip\", \"deduplicate\"],\n)\ndef test_plugin_nameversion(input, expected):\n pluginlist = [(None, x) for x in input]\n result = _plugin_nameversions(pluginlist)\n assert result == expected\n\n\nclass TestTerminal(object):\n def test_pass_skip_fail(self, testdir, option):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_ok():\n pass\n def test_skip():\n pytest.skip(\"xx\")\n def test_func():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(*option.args)\n if option.verbosity > 0:\n result.stdout.fnmatch_lines(\n [\n \"*test_pass_skip_fail.py::test_ok PASS*\",\n \"*test_pass_skip_fail.py::test_skip SKIP*\",\n \"*test_pass_skip_fail.py::test_func FAIL*\",\n ]\n )\n elif option.verbosity == 0:\n result.stdout.fnmatch_lines([\"*test_pass_skip_fail.py .sF*\"])\n else:\n result.stdout.fnmatch_lines([\".sF*\"])\n result.stdout.fnmatch_lines(\n [\" def test_func():\", \"> assert 0\", \"E assert 0\"]\n )\n\n def test_internalerror(self, testdir, linecomp):\n modcol = testdir.getmodulecol(\"def test_one(): pass\")\n rep = TerminalReporter(modcol.config, file=linecomp.stringio)\n with pytest.raises(ValueError) as excinfo:\n raise ValueError(\"hello\")\n rep.pytest_internalerror(excinfo.getrepr())\n linecomp.assert_contains_lines([\"INTERNALERROR> *ValueError*hello*\"])\n\n def test_writeline(self, testdir, linecomp):\n modcol = testdir.getmodulecol(\"def test_one(): pass\")\n rep = TerminalReporter(modcol.config, file=linecomp.stringio)\n rep.write_fspath_result(modcol.nodeid, \".\")\n rep.write_line(\"hello world\")\n lines = linecomp.stringio.getvalue().split(\"\\n\")\n assert not lines[0]\n assert lines[1].endswith(modcol.name + \" .\")\n assert lines[2] == \"hello world\"\n\n def test_show_runtest_logstart(self, testdir, linecomp):\n item = testdir.getitem(\"def test_func(): pass\")\n tr = TerminalReporter(item.config, file=linecomp.stringio)\n item.config.pluginmanager.register(tr)\n location = item.reportinfo()\n tr.config.hook.pytest_runtest_logstart(\n nodeid=item.nodeid, location=location, fspath=str(item.fspath)\n )\n linecomp.assert_contains_lines([\"*test_show_runtest_logstart.py*\"])\n\n def test_runtest_location_shown_before_test_starts(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_1():\n import time\n time.sleep(20)\n \"\"\"\n )\n child = testdir.spawn_pytest(\"\")\n child.expect(\".*test_runtest_location.*py\")\n child.sendeof()\n child.kill(15)\n\n def test_report_collect_after_half_a_second(self, testdir):\n \"\"\"Test for \"collecting\" being updated after 0.5s\"\"\"\n\n testdir.makepyfile(\n **{\n \"test1.py\": \"\"\"\n import _pytest.terminal\n\n _pytest.terminal.REPORT_COLLECTING_RESOLUTION = 0\n\n def test_1():\n pass\n \"\"\",\n \"test2.py\": \"def test_2(): pass\",\n }\n )\n\n child = testdir.spawn_pytest(\"-v test1.py test2.py\")\n child.expect(r\"collecting \\.\\.\\.\")\n child.expect(r\"collecting 1 item\")\n child.expect(r\"collecting 2 items\")\n child.expect(r\"collected 2 items\")\n rest = child.read().decode(\"utf8\")\n assert \"2 passed in\" in rest\n\n def test_itemreport_subclasses_show_subclassed_file(self, testdir):\n testdir.makepyfile(\n test_p1=\"\"\"\n class BaseTests(object):\n def test_p1(self):\n pass\n class TestClass(BaseTests):\n pass\n \"\"\"\n )\n p2 = testdir.makepyfile(\n test_p2=\"\"\"\n from test_p1 import BaseTests\n class TestMore(BaseTests):\n pass\n \"\"\"\n )\n result = testdir.runpytest(p2)\n result.stdout.fnmatch_lines([\"*test_p2.py .*\", \"*1 passed*\"])\n result = testdir.runpytest(\"-vv\", p2)\n result.stdout.fnmatch_lines(\n [\"*test_p2.py::TestMore::test_p1* <- *test_p1.py*PASSED*\"]\n )\n\n def test_itemreport_directclasses_not_shown_as_subclasses(self, testdir):\n a = testdir.mkpydir(\"a123\")\n a.join(\"test_hello123.py\").write(\n textwrap.dedent(\n \"\"\"\\\n class TestClass(object):\n def test_method(self):\n pass\n \"\"\"\n )\n )\n result = testdir.runpytest(\"-vv\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*a123/test_hello123.py*PASS*\"])\n assert \" <- \" not in result.stdout.str()\n\n def test_keyboard_interrupt(self, testdir, option):\n testdir.makepyfile(\n \"\"\"\n def test_foobar():\n assert 0\n def test_spamegg():\n import py; pytest.skip('skip me please!')\n def test_interrupt_me():\n raise KeyboardInterrupt # simulating the user\n \"\"\"\n )\n\n result = testdir.runpytest(*option.args, no_reraise_ctrlc=True)\n result.stdout.fnmatch_lines(\n [\n \" def test_foobar():\",\n \"> assert 0\",\n \"E assert 0\",\n \"*_keyboard_interrupt.py:6: KeyboardInterrupt*\",\n ]\n )\n if option.fulltrace:\n result.stdout.fnmatch_lines(\n [\"*raise KeyboardInterrupt # simulating the user*\"]\n )\n else:\n result.stdout.fnmatch_lines(\n [\"(to show a full traceback on KeyboardInterrupt use --fulltrace)\"]\n )\n result.stdout.fnmatch_lines([\"*KeyboardInterrupt*\"])\n\n def test_keyboard_in_sessionstart(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_sessionstart():\n raise KeyboardInterrupt\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_foobar():\n pass\n \"\"\"\n )\n\n result = testdir.runpytest(no_reraise_ctrlc=True)\n assert result.ret == 2\n result.stdout.fnmatch_lines([\"*KeyboardInterrupt*\"])\n\n def test_collect_single_item(self, testdir):\n \"\"\"Use singular 'item' when reporting a single test item\"\"\"\n testdir.makepyfile(\n \"\"\"\n def test_foobar():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"collected 1 item\"])\n\n def test_rewrite(self, testdir, monkeypatch):\n config = testdir.parseconfig()\n f = py.io.TextIO()\n monkeypatch.setattr(f, \"isatty\", lambda *args: True)\n tr = TerminalReporter(config, f)\n tr._tw.fullwidth = 10\n tr.write(\"hello\")\n tr.rewrite(\"hey\", erase=True)\n assert f.getvalue() == \"hello\" + \"\\r\" + \"hey\" + (6 * \" \")\n\n\nclass TestCollectonly(object):\n def test_collectonly_basic(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines(\n [\"\", \" \"]\n )\n\n def test_collectonly_skipped_module(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n pytest.skip(\"hello\")\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\", \"-rs\")\n result.stdout.fnmatch_lines([\"*ERROR collecting*\"])\n\n def test_collectonly_display_test_description(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_with_description():\n \\\"\"\" This test has a description.\n \\\"\"\"\n assert True\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\", \"--verbose\")\n result.stdout.fnmatch_lines([\" This test has a description.\"])\n\n def test_collectonly_failed_module(self, testdir):\n testdir.makepyfile(\"\"\"raise ValueError(0)\"\"\")\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*raise ValueError*\", \"*1 error*\"])\n\n def test_collectonly_fatal(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_collectstart(collector):\n assert 0, \"urgs\"\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*INTERNAL*args*\"])\n assert result.ret == 3\n\n def test_collectonly_simple(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_func1():\n pass\n class TestClass(object):\n def test_method(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\", p)\n # assert stderr.startswith(\"inserting into sys.path\")\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n [\n \"*\",\n \"* \",\n \"* \",\n \"* \",\n ]\n )\n\n def test_collectonly_error(self, testdir):\n p = testdir.makepyfile(\"import Errlkjqweqwe\")\n result = testdir.runpytest(\"--collect-only\", p)\n assert result.ret == 2\n result.stdout.fnmatch_lines(\n textwrap.dedent(\n \"\"\"\\\n *ERROR*\n *ImportError*\n *No module named *Errlk*\n *1 error*\n \"\"\"\n ).strip()\n )\n\n def test_collectonly_missing_path(self, testdir):\n \"\"\"this checks issue 115,\n failure in parseargs will cause session\n not to have the items attribute\n \"\"\"\n result = testdir.runpytest(\"--collect-only\", \"uhm_missing_path\")\n assert result.ret == 4\n result.stderr.fnmatch_lines([\"*ERROR: file not found*\"])\n\n def test_collectonly_quiet(self, testdir):\n testdir.makepyfile(\"def test_foo(): pass\")\n result = testdir.runpytest(\"--collect-only\", \"-q\")\n result.stdout.fnmatch_lines([\"*test_foo*\"])\n\n def test_collectonly_more_quiet(self, testdir):\n testdir.makepyfile(test_fun=\"def test_foo(): pass\")\n result = testdir.runpytest(\"--collect-only\", \"-qq\")\n result.stdout.fnmatch_lines([\"*test_fun.py: 1*\"])\n\n\nclass TestFixtureReporting(object):\n def test_setup_fixture_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def setup_function(function):\n print(\"setup func\")\n assert 0\n def test_nada():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*ERROR at setup of test_nada*\",\n \"*setup_function(function):*\",\n \"*setup func*\",\n \"*assert 0*\",\n \"*1 error*\",\n ]\n )\n assert result.ret != 0\n\n def test_teardown_fixture_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_nada():\n pass\n def teardown_function(function):\n print(\"teardown func\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*ERROR at teardown*\",\n \"*teardown_function(function):*\",\n \"*assert 0*\",\n \"*Captured stdout*\",\n \"*teardown func*\",\n \"*1 passed*1 error*\",\n ]\n )\n\n def test_teardown_fixture_error_and_test_failure(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_fail():\n assert 0, \"failingfunc\"\n\n def teardown_function(function):\n print(\"teardown func\")\n assert False\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*ERROR at teardown of test_fail*\",\n \"*teardown_function(function):*\",\n \"*assert False*\",\n \"*Captured stdout*\",\n \"*teardown func*\",\n \"*test_fail*\",\n \"*def test_fail():\",\n \"*failingfunc*\",\n \"*1 failed*1 error*\",\n ]\n )\n\n def test_setup_teardown_output_and_test_failure(self, testdir):\n \"\"\" Test for issue #442 \"\"\"\n testdir.makepyfile(\n \"\"\"\n def setup_function(function):\n print(\"setup func\")\n\n def test_fail():\n assert 0, \"failingfunc\"\n\n def teardown_function(function):\n print(\"teardown func\")\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*test_fail*\",\n \"*def test_fail():\",\n \"*failingfunc*\",\n \"*Captured stdout setup*\",\n \"*setup func*\",\n \"*Captured stdout teardown*\",\n \"*teardown func*\",\n \"*1 failed*\",\n ]\n )\n\n\nclass TestTerminalFunctional(object):\n def test_deselected(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n def test_one():\n pass\n def test_two():\n pass\n def test_three():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-k\", \"test_two:\", testpath)\n result.stdout.fnmatch_lines(\n [\"collected 3 items / 1 deselected / 2 selected\", \"*test_deselected.py ..*\"]\n )\n assert result.ret == 0\n\n def test_deselected_with_hookwrapper(self, testdir):\n testpath = testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_collection_modifyitems(config, items):\n yield\n deselected = items.pop()\n config.hook.pytest_deselected(items=[deselected])\n \"\"\"\n )\n testpath = testdir.makepyfile(\n \"\"\"\n def test_one():\n pass\n def test_two():\n pass\n def test_three():\n pass\n \"\"\"\n )\n result = testdir.runpytest(testpath)\n result.stdout.fnmatch_lines(\n [\n \"collected 3 items / 1 deselected / 2 selected\",\n \"*= 2 passed, 1 deselected in*\",\n ]\n )\n assert result.ret == 0\n\n def test_show_deselected_items_using_markexpr_before_test_execution(self, testdir):\n testdir.makepyfile(\n test_show_deselected=\"\"\"\n import pytest\n\n @pytest.mark.foo\n def test_foobar():\n pass\n\n @pytest.mark.bar\n def test_bar():\n pass\n\n def test_pass():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-m\", \"not foo\")\n result.stdout.fnmatch_lines(\n [\n \"collected 3 items / 1 deselected / 2 selected\",\n \"*test_show_deselected.py ..*\",\n \"*= 2 passed, 1 deselected in * =*\",\n ]\n )\n assert \"= 1 deselected =\" not in result.stdout.str()\n assert result.ret == 0\n\n def test_no_skip_summary_if_failure(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_ok():\n pass\n def test_fail():\n assert 0\n def test_skip():\n pytest.skip(\"dontshow\")\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.stdout.str().find(\"skip test summary\") == -1\n assert result.ret == 1\n\n def test_passes(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_passes():\n pass\n class TestClass(object):\n def test_method(self):\n pass\n \"\"\"\n )\n old = p1.dirpath().chdir()\n try:\n result = testdir.runpytest()\n finally:\n old.chdir()\n result.stdout.fnmatch_lines([\"test_passes.py ..*\", \"* 2 pass*\"])\n assert result.ret == 0\n\n def test_header_trailer_info(self, testdir, request):\n testdir.makepyfile(\n \"\"\"\n def test_passes():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n verinfo = \".\".join(map(str, sys.version_info[:3]))\n result.stdout.fnmatch_lines(\n [\n \"*===== test session starts ====*\",\n \"platform %s -- Python %s*pytest-%s*py-%s*pluggy-%s\"\n % (\n sys.platform,\n verinfo,\n pytest.__version__,\n py.__version__,\n pluggy.__version__,\n ),\n \"*test_header_trailer_info.py .*\",\n \"=* 1 passed*in *.[0-9][0-9] seconds *=\",\n ]\n )\n if request.config.pluginmanager.list_plugin_distinfo():\n result.stdout.fnmatch_lines([\"plugins: *\"])\n\n def test_header(self, testdir, request):\n testdir.tmpdir.join(\"tests\").ensure_dir()\n testdir.tmpdir.join(\"gui\").ensure_dir()\n\n # no ini file\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"rootdir: *test_header0\"])\n\n # with inifile\n testdir.makeini(\"\"\"[pytest]\"\"\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"rootdir: *test_header0, inifile: tox.ini\"])\n\n # with testpaths option, and not passing anything in the command-line\n testdir.makeini(\n \"\"\"\n [pytest]\n testpaths = tests gui\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"rootdir: *test_header0, inifile: tox.ini, testpaths: tests, gui\"]\n )\n\n # with testpaths option, passing directory in command-line: do not show testpaths then\n result = testdir.runpytest(\"tests\")\n result.stdout.fnmatch_lines([\"rootdir: *test_header0, inifile: tox.ini\"])\n\n def test_showlocals(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_showlocals():\n x = 3\n y = \"x\" * 5000\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p1, \"-l\")\n result.stdout.fnmatch_lines(\n [\n # \"_ _ * Locals *\",\n \"x* = 3\",\n \"y* = 'xxxxxx*\",\n ]\n )\n\n @pytest.fixture\n def verbose_testfile(self, testdir):\n return testdir.makepyfile(\n \"\"\"\n import pytest\n def test_fail():\n raise ValueError()\n def test_pass():\n pass\n class TestClass(object):\n def test_skip(self):\n pytest.skip(\"hello\")\n def test_gen():\n def check(x):\n assert x == 1\n yield check, 0\n \"\"\"\n )\n\n def test_verbose_reporting(self, verbose_testfile, testdir, pytestconfig):\n result = testdir.runpytest(\n verbose_testfile, \"-v\", \"-Walways::pytest.PytestWarning\"\n )\n result.stdout.fnmatch_lines(\n [\n \"*test_verbose_reporting.py::test_fail *FAIL*\",\n \"*test_verbose_reporting.py::test_pass *PASS*\",\n \"*test_verbose_reporting.py::TestClass::test_skip *SKIP*\",\n \"*test_verbose_reporting.py::test_gen *XFAIL*\",\n ]\n )\n assert result.ret == 1\n\n def test_verbose_reporting_xdist(self, verbose_testfile, testdir, pytestconfig):\n if not pytestconfig.pluginmanager.get_plugin(\"xdist\"):\n pytest.skip(\"xdist plugin not installed\")\n\n result = testdir.runpytest(\n verbose_testfile, \"-v\", \"-n 1\", \"-Walways::pytest.PytestWarning\"\n )\n result.stdout.fnmatch_lines(\n [\"*FAIL*test_verbose_reporting_xdist.py::test_fail*\"]\n )\n assert result.ret == 1\n\n def test_quiet_reporting(self, testdir):\n p1 = testdir.makepyfile(\"def test_pass(): pass\")\n result = testdir.runpytest(p1, \"-q\")\n s = result.stdout.str()\n assert \"test session starts\" not in s\n assert p1.basename not in s\n assert \"===\" not in s\n assert \"passed\" in s\n\n def test_more_quiet_reporting(self, testdir):\n p1 = testdir.makepyfile(\"def test_pass(): pass\")\n result = testdir.runpytest(p1, \"-qq\")\n s = result.stdout.str()\n assert \"test session starts\" not in s\n assert p1.basename not in s\n assert \"===\" not in s\n assert \"passed\" not in s\n\n @pytest.mark.parametrize(\n \"params\", [(), (\"--collect-only\",)], ids=[\"no-params\", \"collect-only\"]\n )\n def test_report_collectionfinish_hook(self, testdir, params):\n testdir.makeconftest(\n \"\"\"\n def pytest_report_collectionfinish(config, startdir, items):\n return ['hello from hook: {0} items'.format(len(items))]\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('i', range(3))\n def test(i):\n pass\n \"\"\"\n )\n result = testdir.runpytest(*params)\n result.stdout.fnmatch_lines([\"collected 3 items\", \"hello from hook: 3 items\"])\n\n\ndef test_fail_extra_reporting(testdir, monkeypatch):\n monkeypatch.setenv(\"COLUMNS\", \"80\")\n testdir.makepyfile(\"def test_this(): assert 0, 'this_failed' * 100\")\n result = testdir.runpytest()\n assert \"short test summary\" not in result.stdout.str()\n result = testdir.runpytest(\"-rf\")\n result.stdout.fnmatch_lines(\n [\n \"*test summary*\",\n \"FAILED test_fail_extra_reporting.py::test_this - AssertionError: this_failedt...\",\n ]\n )\n\n\ndef test_fail_reporting_on_pass(testdir):\n testdir.makepyfile(\"def test_this(): assert 1\")\n result = testdir.runpytest(\"-rf\")\n assert \"short test summary\" not in result.stdout.str()\n\n\ndef test_pass_extra_reporting(testdir):\n testdir.makepyfile(\"def test_this(): assert 1\")\n result = testdir.runpytest()\n assert \"short test summary\" not in result.stdout.str()\n result = testdir.runpytest(\"-rp\")\n result.stdout.fnmatch_lines([\"*test summary*\", \"PASS*test_pass_extra_reporting*\"])\n\n\ndef test_pass_reporting_on_fail(testdir):\n testdir.makepyfile(\"def test_this(): assert 0\")\n result = testdir.runpytest(\"-rp\")\n assert \"short test summary\" not in result.stdout.str()\n\n\ndef test_pass_output_reporting(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_pass_has_output():\n print(\"Four score and seven years ago...\")\n def test_pass_no_output():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n s = result.stdout.str()\n assert \"test_pass_has_output\" not in s\n assert \"Four score and seven years ago...\" not in s\n assert \"test_pass_no_output\" not in s\n result = testdir.runpytest(\"-rPp\")\n result.stdout.fnmatch_lines(\n [\n \"*= PASSES =*\",\n \"*_ test_pass_has_output _*\",\n \"*- Captured stdout call -*\",\n \"Four score and seven years ago...\",\n \"*= short test summary info =*\",\n \"PASSED test_pass_output_reporting.py::test_pass_has_output\",\n \"PASSED test_pass_output_reporting.py::test_pass_no_output\",\n \"*= 2 passed in *\",\n ]\n )\n\n\ndef test_color_yes(testdir):\n testdir.makepyfile(\"def test_this(): assert 1\")\n result = testdir.runpytest(\"--color=yes\")\n assert \"test session starts\" in result.stdout.str()\n assert \"\\x1b[1m\" in result.stdout.str()\n\n\ndef test_color_no(testdir):\n testdir.makepyfile(\"def test_this(): assert 1\")\n result = testdir.runpytest(\"--color=no\")\n assert \"test session starts\" in result.stdout.str()\n assert \"\\x1b[1m\" not in result.stdout.str()\n\n\n@pytest.mark.parametrize(\"verbose\", [True, False])\ndef test_color_yes_collection_on_non_atty(testdir, verbose):\n \"\"\"skip collect progress report when working on non-terminals.\n #1397\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('i', range(10))\n def test_this(i):\n assert 1\n \"\"\"\n )\n args = [\"--color=yes\"]\n if verbose:\n args.append(\"-vv\")\n result = testdir.runpytest(*args)\n assert \"test session starts\" in result.stdout.str()\n assert \"\\x1b[1m\" in result.stdout.str()\n assert \"collecting 10 items\" not in result.stdout.str()\n if verbose:\n assert \"collecting ...\" in result.stdout.str()\n assert \"collected 10 items\" in result.stdout.str()\n\n\ndef test_getreportopt():\n class Config(object):\n class Option(object):\n reportchars = \"\"\n disable_warnings = True\n\n option = Option()\n\n config = Config()\n\n config.option.reportchars = \"sf\"\n assert getreportopt(config) == \"sf\"\n\n config.option.reportchars = \"sfxw\"\n assert getreportopt(config) == \"sfx\"\n\n # Now with --disable-warnings.\n config.option.disable_warnings = False\n config.option.reportchars = \"a\"\n assert getreportopt(config) == \"sxXwEf\" # NOTE: \"w\" included!\n\n config.option.reportchars = \"sfx\"\n assert getreportopt(config) == \"sfxw\"\n\n config.option.reportchars = \"sfxw\"\n assert getreportopt(config) == \"sfxw\"\n\n config.option.reportchars = \"a\"\n assert getreportopt(config) == \"sxXwEf\" # NOTE: \"w\" included!\n\n config.option.reportchars = \"A\"\n assert getreportopt(config) == \"PpsxXwEf\"\n\n\ndef test_terminalreporter_reportopt_addopts(testdir):\n testdir.makeini(\"[pytest]\\naddopts=-rs\")\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def tr(request):\n tr = request.config.pluginmanager.getplugin(\"terminalreporter\")\n return tr\n def test_opt(tr):\n assert tr.hasopt('skipped')\n assert not tr.hasopt('qwe')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_tbstyle_short(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def arg(request):\n return 42\n def test_opt(arg):\n x = 0\n assert x\n \"\"\"\n )\n result = testdir.runpytest(\"--tb=short\")\n s = result.stdout.str()\n assert \"arg = 42\" not in s\n assert \"x = 0\" not in s\n result.stdout.fnmatch_lines([\"*%s:8*\" % p.basename, \" assert x\", \"E assert*\"])\n result = testdir.runpytest()\n s = result.stdout.str()\n assert \"x = 0\" in s\n assert \"assert x\" in s\n\n\ndef test_traceconfig(testdir, monkeypatch):\n result = testdir.runpytest(\"--traceconfig\")\n result.stdout.fnmatch_lines([\"*active plugins*\"])\n assert result.ret == EXIT_NOTESTSCOLLECTED\n\n\nclass TestGenericReporting(object):\n \"\"\" this test class can be subclassed with a different option\n provider to run e.g. distributed tests.\n \"\"\"\n\n def test_collect_fail(self, testdir, option):\n testdir.makepyfile(\"import xyz\\n\")\n result = testdir.runpytest(*option.args)\n result.stdout.fnmatch_lines(\n [\"ImportError while importing*\", \"*No module named *xyz*\", \"*1 error*\"]\n )\n\n def test_maxfailures(self, testdir, option):\n testdir.makepyfile(\n \"\"\"\n def test_1():\n assert 0\n def test_2():\n assert 0\n def test_3():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"--maxfail=2\", *option.args)\n result.stdout.fnmatch_lines(\n [\"*def test_1():*\", \"*def test_2():*\", \"*2 failed*\"]\n )\n\n def test_tb_option(self, testdir, option):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def g():\n raise IndexError\n def test_func():\n print(6*7)\n g() # --calling--\n \"\"\"\n )\n for tbopt in [\"long\", \"short\", \"no\"]:\n print(\"testing --tb=%s...\" % tbopt)\n result = testdir.runpytest(\"--tb=%s\" % tbopt)\n s = result.stdout.str()\n if tbopt == \"long\":\n assert \"print(6*7)\" in s\n else:\n assert \"print(6*7)\" not in s\n if tbopt != \"no\":\n assert \"--calling--\" in s\n assert \"IndexError\" in s\n else:\n assert \"FAILURES\" not in s\n assert \"--calling--\" not in s\n assert \"IndexError\" not in s\n\n def test_tb_crashline(self, testdir, option):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def g():\n raise IndexError\n def test_func1():\n print(6*7)\n g() # --calling--\n def test_func2():\n assert 0, \"hello\"\n \"\"\"\n )\n result = testdir.runpytest(\"--tb=line\")\n bn = p.basename\n result.stdout.fnmatch_lines(\n [\"*%s:3: IndexError*\" % bn, \"*%s:8: AssertionError: hello*\" % bn]\n )\n s = result.stdout.str()\n assert \"def test_func2\" not in s\n\n def test_pytest_report_header(self, testdir, option):\n testdir.makeconftest(\n \"\"\"\n def pytest_sessionstart(session):\n session.config._somevalue = 42\n def pytest_report_header(config):\n return \"hello: %s\" % config._somevalue\n \"\"\"\n )\n testdir.mkdir(\"a\").join(\"conftest.py\").write(\n \"\"\"\ndef pytest_report_header(config, startdir):\n return [\"line1\", str(startdir)]\n\"\"\"\n )\n result = testdir.runpytest(\"a\")\n result.stdout.fnmatch_lines([\"*hello: 42*\", \"line1\", str(testdir.tmpdir)])\n\n def test_show_capture(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n import logging\n def test_one():\n sys.stdout.write('!This is stdout!')\n sys.stderr.write('!This is stderr!')\n logging.warning('!This is a warning log msg!')\n assert False, 'Something failed'\n \"\"\"\n )\n\n result = testdir.runpytest(\"--tb=short\")\n result.stdout.fnmatch_lines(\n [\n \"!This is stdout!\",\n \"!This is stderr!\",\n \"*WARNING*!This is a warning log msg!\",\n ]\n )\n\n result = testdir.runpytest(\"--show-capture=all\", \"--tb=short\")\n result.stdout.fnmatch_lines(\n [\n \"!This is stdout!\",\n \"!This is stderr!\",\n \"*WARNING*!This is a warning log msg!\",\n ]\n )\n\n stdout = testdir.runpytest(\"--show-capture=stdout\", \"--tb=short\").stdout.str()\n assert \"!This is stderr!\" not in stdout\n assert \"!This is stdout!\" in stdout\n assert \"!This is a warning log msg!\" not in stdout\n\n stdout = testdir.runpytest(\"--show-capture=stderr\", \"--tb=short\").stdout.str()\n assert \"!This is stdout!\" not in stdout\n assert \"!This is stderr!\" in stdout\n assert \"!This is a warning log msg!\" not in stdout\n\n stdout = testdir.runpytest(\"--show-capture=log\", \"--tb=short\").stdout.str()\n assert \"!This is stdout!\" not in stdout\n assert \"!This is stderr!\" not in stdout\n assert \"!This is a warning log msg!\" in stdout\n\n stdout = testdir.runpytest(\"--show-capture=no\", \"--tb=short\").stdout.str()\n assert \"!This is stdout!\" not in stdout\n assert \"!This is stderr!\" not in stdout\n assert \"!This is a warning log msg!\" not in stdout\n\n def test_show_capture_with_teardown_logs(self, testdir):\n \"\"\"Ensure that the capturing of teardown logs honor --show-capture setting\"\"\"\n testdir.makepyfile(\n \"\"\"\n import logging\n import sys\n import pytest\n\n @pytest.fixture(scope=\"function\", autouse=\"True\")\n def hook_each_test(request):\n yield\n sys.stdout.write(\"!stdout!\")\n sys.stderr.write(\"!stderr!\")\n logging.warning(\"!log!\")\n\n def test_func():\n assert False\n \"\"\"\n )\n\n result = testdir.runpytest(\"--show-capture=stdout\", \"--tb=short\").stdout.str()\n assert \"!stdout!\" in result\n assert \"!stderr!\" not in result\n assert \"!log!\" not in result\n\n result = testdir.runpytest(\"--show-capture=stderr\", \"--tb=short\").stdout.str()\n assert \"!stdout!\" not in result\n assert \"!stderr!\" in result\n assert \"!log!\" not in result\n\n result = testdir.runpytest(\"--show-capture=log\", \"--tb=short\").stdout.str()\n assert \"!stdout!\" not in result\n assert \"!stderr!\" not in result\n assert \"!log!\" in result\n\n result = testdir.runpytest(\"--show-capture=no\", \"--tb=short\").stdout.str()\n assert \"!stdout!\" not in result\n assert \"!stderr!\" not in result\n assert \"!log!\" not in result\n\n\n@pytest.mark.xfail(\"not hasattr(os, 'dup')\")\ndef test_fdopen_kept_alive_issue124(testdir):\n testdir.makepyfile(\n \"\"\"\n import os, sys\n k = []\n def test_open_file_and_keep_alive(capfd):\n stdout = os.fdopen(1, 'w', 1)\n k.append(stdout)\n\n def test_close_kept_alive_file():\n stdout = k.pop()\n stdout.close()\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n\ndef test_tbstyle_native_setup_error(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def setup_error_fixture():\n raise Exception(\"error in exception\")\n\n def test_error_fixture(setup_error_fixture):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--tb=native\")\n result.stdout.fnmatch_lines(\n ['*File *test_tbstyle_native_setup_error.py\", line *, in setup_error_fixture*']\n )\n\n\ndef test_terminal_summary(testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_terminal_summary(terminalreporter, exitstatus):\n w = terminalreporter\n w.section(\"hello\")\n w.line(\"world\")\n w.line(\"exitstatus: {0}\".format(exitstatus))\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n \"\"\"\n *==== hello ====*\n world\n exitstatus: 5\n \"\"\"\n )\n\n\n@pytest.mark.filterwarnings(\"default\")\ndef test_terminal_summary_warnings_are_displayed(testdir):\n \"\"\"Test that warnings emitted during pytest_terminal_summary are displayed.\n (#1305).\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import warnings\n def pytest_terminal_summary(terminalreporter):\n warnings.warn(UserWarning('internal warning'))\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_failure():\n import warnings\n warnings.warn(\"warning_from_\" + \"test\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"-ra\")\n result.stdout.fnmatch_lines(\n [\n \"*= warnings summary =*\",\n \"*warning_from_test*\",\n \"*= short test summary info =*\",\n \"*= warnings summary (final) =*\",\n \"*conftest.py:3:*internal warning\",\n \"*== 1 failed, 2 warnings in *\",\n ]\n )\n assert \"None\" not in result.stdout.str()\n stdout = result.stdout.str()\n assert stdout.count(\"warning_from_test\") == 1\n assert stdout.count(\"=== warnings summary \") == 2\n\n\n@pytest.mark.filterwarnings(\"default\")\ndef test_terminal_summary_warnings_header_once(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_failure():\n import warnings\n warnings.warn(\"warning_from_\" + \"test\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"-ra\")\n result.stdout.fnmatch_lines(\n [\n \"*= warnings summary =*\",\n \"*warning_from_test*\",\n \"*= short test summary info =*\",\n \"*== 1 failed, 1 warnings in *\",\n ]\n )\n assert \"None\" not in result.stdout.str()\n stdout = result.stdout.str()\n assert stdout.count(\"warning_from_test\") == 1\n assert stdout.count(\"=== warnings summary \") == 1\n\n\n@pytest.mark.parametrize(\n \"exp_color, exp_line, stats_arg\",\n [\n # The method under test only cares about the length of each\n # dict value, not the actual contents, so tuples of anything\n # suffice\n # Important statuses -- the highest priority of these always wins\n (\"red\", \"1 failed\", {\"failed\": (1,)}),\n (\"red\", \"1 failed, 1 passed\", {\"failed\": (1,), \"passed\": (1,)}),\n (\"red\", \"1 error\", {\"error\": (1,)}),\n (\"red\", \"1 passed, 1 error\", {\"error\": (1,), \"passed\": (1,)}),\n # (a status that's not known to the code)\n (\"yellow\", \"1 weird\", {\"weird\": (1,)}),\n (\"yellow\", \"1 passed, 1 weird\", {\"weird\": (1,), \"passed\": (1,)}),\n (\"yellow\", \"1 warnings\", {\"warnings\": (1,)}),\n (\"yellow\", \"1 passed, 1 warnings\", {\"warnings\": (1,), \"passed\": (1,)}),\n (\"green\", \"5 passed\", {\"passed\": (1, 2, 3, 4, 5)}),\n # \"Boring\" statuses. These have no effect on the color of the summary\n # line. Thus, if *every* test has a boring status, the summary line stays\n # at its default color, i.e. yellow, to warn the user that the test run\n # produced no useful information\n (\"yellow\", \"1 skipped\", {\"skipped\": (1,)}),\n (\"green\", \"1 passed, 1 skipped\", {\"skipped\": (1,), \"passed\": (1,)}),\n (\"yellow\", \"1 deselected\", {\"deselected\": (1,)}),\n (\"green\", \"1 passed, 1 deselected\", {\"deselected\": (1,), \"passed\": (1,)}),\n (\"yellow\", \"1 xfailed\", {\"xfailed\": (1,)}),\n (\"green\", \"1 passed, 1 xfailed\", {\"xfailed\": (1,), \"passed\": (1,)}),\n (\"yellow\", \"1 xpassed\", {\"xpassed\": (1,)}),\n (\"green\", \"1 passed, 1 xpassed\", {\"xpassed\": (1,), \"passed\": (1,)}),\n # Likewise if no tests were found at all\n (\"yellow\", \"no tests ran\", {}),\n # Test the empty-key special case\n (\"yellow\", \"no tests ran\", {\"\": (1,)}),\n (\"green\", \"1 passed\", {\"\": (1,), \"passed\": (1,)}),\n # A couple more complex combinations\n (\n \"red\",\n \"1 failed, 2 passed, 3 xfailed\",\n {\"passed\": (1, 2), \"failed\": (1,), \"xfailed\": (1, 2, 3)},\n ),\n (\n \"green\",\n \"1 passed, 2 skipped, 3 deselected, 2 xfailed\",\n {\n \"passed\": (1,),\n \"skipped\": (1, 2),\n \"deselected\": (1, 2, 3),\n \"xfailed\": (1, 2),\n },\n ),\n ],\n)\ndef test_summary_stats(exp_line, exp_color, stats_arg):\n print(\"Based on stats: %s\" % stats_arg)\n print('Expect summary: \"{}\"; with color \"{}\"'.format(exp_line, exp_color))\n (line, color) = build_summary_stats_line(stats_arg)\n print('Actually got: \"{}\"; with color \"{}\"'.format(line, color))\n assert line == exp_line\n assert color == exp_color\n\n\ndef test_skip_counting_towards_summary():\n class DummyReport(BaseReport):\n count_towards_summary = True\n\n r1 = DummyReport()\n r2 = DummyReport()\n res = build_summary_stats_line({\"failed\": (r1, r2)})\n assert res == (\"2 failed\", \"red\")\n\n r1.count_towards_summary = False\n res = build_summary_stats_line({\"failed\": (r1, r2)})\n assert res == (\"1 failed\", \"red\")\n\n\nclass TestClassicOutputStyle(object):\n \"\"\"Ensure classic output style works as expected (#3883)\"\"\"\n\n @pytest.fixture\n def test_files(self, testdir):\n testdir.makepyfile(\n **{\n \"test_one.py\": \"def test_one(): pass\",\n \"test_two.py\": \"def test_two(): assert 0\",\n \"sub/test_three.py\": \"\"\"\n def test_three_1(): pass\n def test_three_2(): assert 0\n def test_three_3(): pass\n \"\"\",\n }\n )\n\n def test_normal_verbosity(self, testdir, test_files):\n result = testdir.runpytest(\"-o\", \"console_output_style=classic\")\n result.stdout.fnmatch_lines(\n [\n \"test_one.py .\",\n \"test_two.py F\",\n \"sub{}test_three.py .F.\".format(os.sep),\n \"*2 failed, 3 passed in*\",\n ]\n )\n\n def test_verbose(self, testdir, test_files):\n result = testdir.runpytest(\"-o\", \"console_output_style=classic\", \"-v\")\n result.stdout.fnmatch_lines(\n [\n \"test_one.py::test_one PASSED\",\n \"test_two.py::test_two FAILED\",\n \"sub{}test_three.py::test_three_1 PASSED\".format(os.sep),\n \"sub{}test_three.py::test_three_2 FAILED\".format(os.sep),\n \"sub{}test_three.py::test_three_3 PASSED\".format(os.sep),\n \"*2 failed, 3 passed in*\",\n ]\n )\n\n def test_quiet(self, testdir, test_files):\n result = testdir.runpytest(\"-o\", \"console_output_style=classic\", \"-q\")\n result.stdout.fnmatch_lines([\".F.F.\", \"*2 failed, 3 passed in*\"])\n\n\nclass TestProgressOutputStyle(object):\n @pytest.fixture\n def many_tests_files(self, testdir):\n testdir.makepyfile(\n test_bar=\"\"\"\n import pytest\n @pytest.mark.parametrize('i', range(10))\n def test_bar(i): pass\n \"\"\",\n test_foo=\"\"\"\n import pytest\n @pytest.mark.parametrize('i', range(5))\n def test_foo(i): pass\n \"\"\",\n test_foobar=\"\"\"\n import pytest\n @pytest.mark.parametrize('i', range(5))\n def test_foobar(i): pass\n \"\"\",\n )\n\n def test_zero_tests_collected(self, testdir):\n \"\"\"Some plugins (testmon for example) might issue pytest_runtest_logreport without any tests being\n actually collected (#2971).\"\"\"\n testdir.makeconftest(\n \"\"\"\n def pytest_collection_modifyitems(items, config):\n from _pytest.runner import CollectReport\n for node_id in ('nodeid1', 'nodeid2'):\n rep = CollectReport(node_id, 'passed', None, None)\n rep.when = 'passed'\n rep.duration = 0.1\n config.hook.pytest_runtest_logreport(report=rep)\n \"\"\"\n )\n output = testdir.runpytest()\n assert \"ZeroDivisionError\" not in output.stdout.str()\n output.stdout.fnmatch_lines([\"=* 2 passed in *=\"])\n\n def test_normal(self, many_tests_files, testdir):\n output = testdir.runpytest()\n output.stdout.re_match_lines(\n [\n r\"test_bar.py \\.{10} \\s+ \\[ 50%\\]\",\n r\"test_foo.py \\.{5} \\s+ \\[ 75%\\]\",\n r\"test_foobar.py \\.{5} \\s+ \\[100%\\]\",\n ]\n )\n\n def test_count(self, many_tests_files, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style = count\n \"\"\"\n )\n output = testdir.runpytest()\n output.stdout.re_match_lines(\n [\n r\"test_bar.py \\.{10} \\s+ \\[10/20\\]\",\n r\"test_foo.py \\.{5} \\s+ \\[15/20\\]\",\n r\"test_foobar.py \\.{5} \\s+ \\[20/20\\]\",\n ]\n )\n\n def test_verbose(self, many_tests_files, testdir):\n output = testdir.runpytest(\"-v\")\n output.stdout.re_match_lines(\n [\n r\"test_bar.py::test_bar\\[0\\] PASSED \\s+ \\[ 5%\\]\",\n r\"test_foo.py::test_foo\\[4\\] PASSED \\s+ \\[ 75%\\]\",\n r\"test_foobar.py::test_foobar\\[4\\] PASSED \\s+ \\[100%\\]\",\n ]\n )\n\n def test_verbose_count(self, many_tests_files, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style = count\n \"\"\"\n )\n output = testdir.runpytest(\"-v\")\n output.stdout.re_match_lines(\n [\n r\"test_bar.py::test_bar\\[0\\] PASSED \\s+ \\[ 1/20\\]\",\n r\"test_foo.py::test_foo\\[4\\] PASSED \\s+ \\[15/20\\]\",\n r\"test_foobar.py::test_foobar\\[4\\] PASSED \\s+ \\[20/20\\]\",\n ]\n )\n\n def test_xdist_normal(self, many_tests_files, testdir, monkeypatch):\n pytest.importorskip(\"xdist\")\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n output = testdir.runpytest(\"-n2\")\n output.stdout.re_match_lines([r\"\\.{20} \\s+ \\[100%\\]\"])\n\n def test_xdist_normal_count(self, many_tests_files, testdir, monkeypatch):\n pytest.importorskip(\"xdist\")\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style = count\n \"\"\"\n )\n output = testdir.runpytest(\"-n2\")\n output.stdout.re_match_lines([r\"\\.{20} \\s+ \\[20/20\\]\"])\n\n def test_xdist_verbose(self, many_tests_files, testdir, monkeypatch):\n pytest.importorskip(\"xdist\")\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n output = testdir.runpytest(\"-n2\", \"-v\")\n output.stdout.re_match_lines_random(\n [\n r\"\\[gw\\d\\] \\[\\s*\\d+%\\] PASSED test_bar.py::test_bar\\[1\\]\",\n r\"\\[gw\\d\\] \\[\\s*\\d+%\\] PASSED test_foo.py::test_foo\\[1\\]\",\n r\"\\[gw\\d\\] \\[\\s*\\d+%\\] PASSED test_foobar.py::test_foobar\\[1\\]\",\n ]\n )\n\n def test_capture_no(self, many_tests_files, testdir):\n output = testdir.runpytest(\"-s\")\n output.stdout.re_match_lines(\n [r\"test_bar.py \\.{10}\", r\"test_foo.py \\.{5}\", r\"test_foobar.py \\.{5}\"]\n )\n\n output = testdir.runpytest(\"--capture=no\")\n assert \"%]\" not in output.stdout.str()\n\n\nclass TestProgressWithTeardown(object):\n \"\"\"Ensure we show the correct percentages for tests that fail during teardown (#3088)\"\"\"\n\n @pytest.fixture\n def contest_with_teardown_fixture(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def fail_teardown():\n yield\n assert False\n \"\"\"\n )\n\n @pytest.fixture\n def many_files(self, testdir, contest_with_teardown_fixture):\n testdir.makepyfile(\n test_bar=\"\"\"\n import pytest\n @pytest.mark.parametrize('i', range(5))\n def test_bar(fail_teardown, i):\n pass\n \"\"\",\n test_foo=\"\"\"\n import pytest\n @pytest.mark.parametrize('i', range(15))\n def test_foo(fail_teardown, i):\n pass\n \"\"\",\n )\n\n def test_teardown_simple(self, testdir, contest_with_teardown_fixture):\n testdir.makepyfile(\n \"\"\"\n def test_foo(fail_teardown):\n pass\n \"\"\"\n )\n output = testdir.runpytest()\n output.stdout.re_match_lines([r\"test_teardown_simple.py \\.E\\s+\\[100%\\]\"])\n\n def test_teardown_with_test_also_failing(\n self, testdir, contest_with_teardown_fixture\n ):\n testdir.makepyfile(\n \"\"\"\n def test_foo(fail_teardown):\n assert False\n \"\"\"\n )\n output = testdir.runpytest()\n output.stdout.re_match_lines(\n [r\"test_teardown_with_test_also_failing.py FE\\s+\\[100%\\]\"]\n )\n\n def test_teardown_many(self, testdir, many_files):\n output = testdir.runpytest()\n output.stdout.re_match_lines(\n [r\"test_bar.py (\\.E){5}\\s+\\[ 25%\\]\", r\"test_foo.py (\\.E){15}\\s+\\[100%\\]\"]\n )\n\n def test_teardown_many_verbose(self, testdir, many_files):\n output = testdir.runpytest(\"-v\")\n output.stdout.re_match_lines(\n [\n r\"test_bar.py::test_bar\\[0\\] PASSED\\s+\\[ 5%\\]\",\n r\"test_bar.py::test_bar\\[0\\] ERROR\\s+\\[ 5%\\]\",\n r\"test_bar.py::test_bar\\[4\\] PASSED\\s+\\[ 25%\\]\",\n r\"test_bar.py::test_bar\\[4\\] ERROR\\s+\\[ 25%\\]\",\n ]\n )\n\n def test_xdist_normal(self, many_files, testdir, monkeypatch):\n pytest.importorskip(\"xdist\")\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n output = testdir.runpytest(\"-n2\")\n output.stdout.re_match_lines([r\"[\\.E]{40} \\s+ \\[100%\\]\"])\n\n\ndef test_skip_reasons_folding():\n path = \"xyz\"\n lineno = 3\n message = \"justso\"\n longrepr = (path, lineno, message)\n\n class X(object):\n pass\n\n ev1 = X()\n ev1.when = \"execute\"\n ev1.skipped = True\n ev1.longrepr = longrepr\n\n ev2 = X()\n ev2.when = \"execute\"\n ev2.longrepr = longrepr\n ev2.skipped = True\n\n # ev3 might be a collection report\n ev3 = X()\n ev3.when = \"collect\"\n ev3.longrepr = longrepr\n ev3.skipped = True\n\n values = _folded_skips([ev1, ev2, ev3])\n assert len(values) == 1\n num, fspath, lineno, reason = values[0]\n assert num == 3\n assert fspath == path\n assert lineno == lineno\n assert reason == message\n\n\ndef test_line_with_reprcrash(monkeypatch):\n import _pytest.terminal\n from wcwidth import wcswidth\n\n mocked_verbose_word = \"FAILED\"\n\n mocked_pos = \"some::nodeid\"\n\n def mock_get_pos(*args):\n return mocked_pos\n\n monkeypatch.setattr(_pytest.terminal, \"_get_pos\", mock_get_pos)\n\n class config(object):\n pass\n\n class rep(object):\n def _get_verbose_word(self, *args):\n return mocked_verbose_word\n\n class longrepr:\n class reprcrash:\n pass\n\n def check(msg, width, expected):\n __tracebackhide__ = True\n if msg:\n rep.longrepr.reprcrash.message = msg\n actual = _get_line_with_reprcrash_message(config, rep(), width)\n\n assert actual == expected\n if actual != \"%s %s\" % (mocked_verbose_word, mocked_pos):\n assert len(actual) <= width\n assert wcswidth(actual) <= width\n\n # AttributeError with message\n check(None, 80, \"FAILED some::nodeid\")\n\n check(\"msg\", 80, \"FAILED some::nodeid - msg\")\n check(\"msg\", 3, \"FAILED some::nodeid\")\n\n check(\"msg\", 24, \"FAILED some::nodeid\")\n check(\"msg\", 25, \"FAILED some::nodeid - msg\")\n\n check(\"some longer msg\", 24, \"FAILED some::nodeid\")\n check(\"some longer msg\", 25, \"FAILED some::nodeid - ...\")\n check(\"some longer msg\", 26, \"FAILED some::nodeid - s...\")\n\n check(\"some\\nmessage\", 25, \"FAILED some::nodeid - ...\")\n check(\"some\\nmessage\", 26, \"FAILED some::nodeid - some\")\n check(\"some\\nmessage\", 80, \"FAILED some::nodeid - some\")\n\n # Test unicode safety.\n check(u\"😄😄😄😄😄\\n2nd line\", 25, u\"FAILED some::nodeid - ...\")\n check(u\"😄😄😄😄😄\\n2nd line\", 26, u\"FAILED some::nodeid - ...\")\n check(u\"😄😄😄😄😄\\n2nd line\", 27, u\"FAILED some::nodeid - 😄...\")\n check(u\"😄😄😄😄😄\\n2nd line\", 28, u\"FAILED some::nodeid - 😄...\")\n check(u\"😄😄😄😄😄\\n2nd line\", 29, u\"FAILED some::nodeid - 😄😄...\")\n\n # NOTE: constructed, not sure if this is supported.\n # It would fail if not using u\"\" in Python 2 for mocked_pos.\n mocked_pos = u\"nodeid::😄::withunicode\"\n check(u\"😄😄😄😄😄\\n2nd line\", 29, u\"FAILED nodeid::😄::withunicode\")\n check(u\"😄😄😄😄😄\\n2nd line\", 40, u\"FAILED nodeid::😄::withunicode - 😄😄...\")\n check(u\"😄😄😄😄😄\\n2nd line\", 41, u\"FAILED nodeid::😄::withunicode - 😄😄...\")\n check(u\"😄😄😄😄😄\\n2nd line\", 42, u\"FAILED nodeid::😄::withunicode - 😄😄😄...\")\n check(u\"😄😄😄😄😄\\n2nd line\", 80, u\"FAILED nodeid::😄::withunicode - 😄😄😄😄😄\")\n"},{"col":0,"comment":"null","endLoc":1034,"header":"def _folded_skips(skipped)","id":5411,"name":"_folded_skips","nodeType":"Function","startLoc":1015,"text":"def _folded_skips(skipped):\n d = {}\n for event in skipped:\n key = event.longrepr\n assert len(key) == 3, (event, key)\n keywords = getattr(event, \"keywords\", {})\n # folding reports with global pytestmark variable\n # this is workaround, because for now we cannot identify the scope of a skip marker\n # TODO: revisit after marks scope would be fixed\n if (\n event.when == \"setup\"\n and \"skip\" in keywords\n and \"pytestmark\" not in keywords\n ):\n key = (key[0], None, key[2])\n d.setdefault(key, []).append(event)\n values = []\n for key, events in d.items():\n values.append((len(events),) + key)\n return values"},{"col":4,"comment":" path to the source code ","endLoc":203,"header":"@property\n def path(self)","id":5412,"name":"path","nodeType":"Function","startLoc":200,"text":"@property\n def path(self):\n \"\"\" path to the source code \"\"\"\n return self.frame.code.path"},{"col":4,"comment":"null","endLoc":206,"header":"def getlocals(self)","id":5413,"name":"getlocals","nodeType":"Function","startLoc":205,"text":"def getlocals(self):\n return self.frame.f_locals"},{"col":4,"comment":"null","endLoc":212,"header":"def getfirstlinesource(self)","id":5414,"name":"getfirstlinesource","nodeType":"Function","startLoc":210,"text":"def getfirstlinesource(self):\n # on Jython this firstlineno can be -1 apparently\n return max(self.frame.code.firstlineno, 0)"},{"col":4,"comment":" return failing source code. ","endLoc":238,"header":"def getsource(self, astcache=None)","id":5415,"name":"getsource","nodeType":"Function","startLoc":214,"text":"def getsource(self, astcache=None):\n \"\"\" return failing source code. \"\"\"\n # we use the passed in astcache to not reparse asttrees\n # within exception info printing\n from _pytest._code.source import getstatementrange_ast\n\n source = self.frame.code.fullsource\n if source is None:\n return None\n key = astnode = None\n if astcache is not None:\n key = self.frame.code.path\n if key is not None:\n astnode = astcache.get(key, None)\n start = self.getfirstlinesource()\n try:\n astnode, _, end = getstatementrange_ast(\n self.lineno, source, astnode=astnode\n )\n except SyntaxError:\n end = self.lineno + 1\n else:\n if key is not None:\n astcache[key] = astnode\n return source[start:end]"},{"className":"Option","col":0,"comment":"null","endLoc":41,"id":5416,"nodeType":"Class","startLoc":30,"text":"class Option(object):\n def __init__(self, verbosity=0, fulltrace=False):\n self.verbosity = verbosity\n self.fulltrace = fulltrace\n\n @property\n def args(self):\n values = []\n values.append(\"--verbosity=%d\" % self.verbosity)\n if self.fulltrace:\n values.append(\"--fulltrace\")\n return values"},{"col":4,"comment":"null","endLoc":33,"header":"def __init__(self, verbosity=0, fulltrace=False)","id":5417,"name":"__init__","nodeType":"Function","startLoc":31,"text":"def __init__(self, verbosity=0, fulltrace=False):\n self.verbosity = verbosity\n self.fulltrace = fulltrace"},{"col":4,"comment":"null","endLoc":41,"header":"@property\n def args(self)","id":5418,"name":"args","nodeType":"Function","startLoc":35,"text":"@property\n def args(self):\n values = []\n values.append(\"--verbosity=%d\" % self.verbosity)\n if self.fulltrace:\n values.append(\"--fulltrace\")\n return values"},{"col":4,"comment":"null","endLoc":133,"header":"def test_create_new_paste(self, pastebin, mocked_urlopen)","id":5419,"name":"test_create_new_paste","nodeType":"Function","startLoc":123,"text":"def test_create_new_paste(self, pastebin, mocked_urlopen):\n result = pastebin.create_new_paste(b\"full-paste-contents\")\n assert result == \"https://bpaste.net/show/3c0c6750bd\"\n assert len(mocked_urlopen) == 1\n url, data = mocked_urlopen[0]\n assert type(data) is bytes\n lexer = \"python3\" if sys.version_info[0] >= 3 else \"python\"\n assert url == \"https://bpaste.net\"\n assert \"lexer=%s\" % lexer in data.decode()\n assert \"code=full-paste-contents\" in data.decode()\n assert \"expiry=1week\" in data.decode()"},{"className":"TestRootdir","col":0,"comment":"null","endLoc":908,"id":5420,"nodeType":"Class","startLoc":853,"text":"class TestRootdir(object):\n def test_simple_noini(self, tmpdir):\n assert get_common_ancestor([tmpdir]) == tmpdir\n a = tmpdir.mkdir(\"a\")\n assert get_common_ancestor([a, tmpdir]) == tmpdir\n assert get_common_ancestor([tmpdir, a]) == tmpdir\n with tmpdir.as_cwd():\n assert get_common_ancestor([]) == tmpdir\n no_path = tmpdir.join(\"does-not-exist\")\n assert get_common_ancestor([no_path]) == tmpdir\n assert get_common_ancestor([no_path.join(\"a\")]) == tmpdir\n\n @pytest.mark.parametrize(\"name\", \"setup.cfg tox.ini pytest.ini\".split())\n def test_with_ini(self, tmpdir, name):\n inifile = tmpdir.join(name)\n inifile.write(\"[pytest]\\n\" if name != \"setup.cfg\" else \"[tool:pytest]\\n\")\n\n a = tmpdir.mkdir(\"a\")\n b = a.mkdir(\"b\")\n for args in ([tmpdir], [a], [b]):\n rootdir, inifile, inicfg = determine_setup(None, args)\n assert rootdir == tmpdir\n assert inifile == inifile\n rootdir, inifile, inicfg = determine_setup(None, [b, a])\n assert rootdir == tmpdir\n assert inifile == inifile\n\n @pytest.mark.parametrize(\"name\", \"setup.cfg tox.ini\".split())\n def test_pytestini_overrides_empty_other(self, tmpdir, name):\n inifile = tmpdir.ensure(\"pytest.ini\")\n a = tmpdir.mkdir(\"a\")\n a.ensure(name)\n rootdir, inifile, inicfg = determine_setup(None, [a])\n assert rootdir == tmpdir\n assert inifile == inifile\n\n def test_setuppy_fallback(self, tmpdir):\n a = tmpdir.mkdir(\"a\")\n a.ensure(\"setup.cfg\")\n tmpdir.ensure(\"setup.py\")\n rootdir, inifile, inicfg = determine_setup(None, [a])\n assert rootdir == tmpdir\n assert inifile is None\n assert inicfg == {}\n\n def test_nothing(self, tmpdir, monkeypatch):\n monkeypatch.chdir(str(tmpdir))\n rootdir, inifile, inicfg = determine_setup(None, [tmpdir])\n assert rootdir == tmpdir\n assert inifile is None\n assert inicfg == {}\n\n def test_with_specific_inifile(self, tmpdir):\n inifile = tmpdir.ensure(\"pytest.ini\")\n rootdir, inifile, inicfg = determine_setup(inifile, [tmpdir])\n assert rootdir == tmpdir"},{"col":0,"comment":"null","endLoc":131,"header":"@pytest.mark.parametrize(\"method\", [\"fd\", \"sys\"])\ndef test_capturing_bytes_in_utf8_encoding(testdir, method)","id":5421,"name":"test_capturing_bytes_in_utf8_encoding","nodeType":"Function","startLoc":122,"text":"@pytest.mark.parametrize(\"method\", [\"fd\", \"sys\"])\ndef test_capturing_bytes_in_utf8_encoding(testdir, method):\n testdir.makepyfile(\n \"\"\"\n def test_unicode():\n print('b\\\\u00f6y')\n \"\"\"\n )\n result = testdir.runpytest(\"--capture=%s\" % method)\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":4,"comment":"null","endLoc":863,"header":"def test_simple_noini(self, tmpdir)","id":5422,"name":"test_simple_noini","nodeType":"Function","startLoc":854,"text":"def test_simple_noini(self, tmpdir):\n assert get_common_ancestor([tmpdir]) == tmpdir\n a = tmpdir.mkdir(\"a\")\n assert get_common_ancestor([a, tmpdir]) == tmpdir\n assert get_common_ancestor([tmpdir, a]) == tmpdir\n with tmpdir.as_cwd():\n assert get_common_ancestor([]) == tmpdir\n no_path = tmpdir.join(\"does-not-exist\")\n assert get_common_ancestor([no_path]) == tmpdir\n assert get_common_ancestor([no_path.join(\"a\")]) == tmpdir"},{"col":0,"comment":"null","endLoc":152,"header":"def test_collect_capturing(testdir)","id":5423,"name":"test_collect_capturing","nodeType":"Function","startLoc":134,"text":"def test_collect_capturing(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import sys\n\n print(\"collect %s failure\" % 13)\n sys.stderr.write(\"collect %s_stderr failure\" % 13)\n import xyz42123\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n \"*Captured stdout*\",\n \"collect 13 failure\",\n \"*Captured stderr*\",\n \"collect 13_stderr failure\",\n ]\n )"},{"col":0,"comment":"null","endLoc":731,"header":"def test_setup_failure_does_not_kill_capturing(testdir)","id":5424,"name":"test_setup_failure_does_not_kill_capturing","nodeType":"Function","startLoc":719,"text":"def test_setup_failure_does_not_kill_capturing(testdir):\n sub1 = testdir.mkpydir(\"sub1\")\n sub1.join(\"conftest.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def pytest_runtest_setup(item):\n raise ValueError(42)\n \"\"\"\n )\n )\n sub1.join(\"test_mod.py\").write(\"def test_func1(): pass\")\n result = testdir.runpytest(testdir.tmpdir, \"--traceconfig\")\n result.stdout.fnmatch_lines([\"*ValueError(42)*\", \"*1 error*\"])"},{"col":4,"comment":"null","endLoc":878,"header":"@pytest.mark.parametrize(\"name\", \"setup.cfg tox.ini pytest.ini\".split())\n def test_with_ini(self, tmpdir, name)","id":5425,"name":"test_with_ini","nodeType":"Function","startLoc":865,"text":"@pytest.mark.parametrize(\"name\", \"setup.cfg tox.ini pytest.ini\".split())\n def test_with_ini(self, tmpdir, name):\n inifile = tmpdir.join(name)\n inifile.write(\"[pytest]\\n\" if name != \"setup.cfg\" else \"[tool:pytest]\\n\")\n\n a = tmpdir.mkdir(\"a\")\n b = a.mkdir(\"b\")\n for args in ([tmpdir], [a], [b]):\n rootdir, inifile, inicfg = determine_setup(None, args)\n assert rootdir == tmpdir\n assert inifile == inifile\n rootdir, inifile, inicfg = determine_setup(None, [b, a])\n assert rootdir == tmpdir\n assert inifile == inifile"},{"col":0,"comment":"null","endLoc":745,"header":"def test_fdfuncarg_skips_on_no_osdup(testdir)","id":5426,"name":"test_fdfuncarg_skips_on_no_osdup","nodeType":"Function","startLoc":734,"text":"def test_fdfuncarg_skips_on_no_osdup(testdir):\n testdir.makepyfile(\n \"\"\"\n import os\n if hasattr(os, 'dup'):\n del os.dup\n def test_hello(capfd):\n pass\n \"\"\"\n )\n result = testdir.runpytest_subprocess(\"--capture=no\")\n result.stdout.fnmatch_lines([\"*1 skipped*\"])"},{"col":0,"comment":"null","endLoc":758,"header":"def test_capture_conftest_runtest_setup(testdir)","id":5427,"name":"test_capture_conftest_runtest_setup","nodeType":"Function","startLoc":748,"text":"def test_capture_conftest_runtest_setup(testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_runtest_setup():\n print(\"hello19\")\n \"\"\"\n )\n testdir.makepyfile(\"def test_func(): pass\")\n result = testdir.runpytest()\n assert result.ret == 0\n assert \"hello19\" not in result.stdout.str()"},{"col":0,"comment":"null","endLoc":780,"header":"def test_capture_badoutput_issue412(testdir)","id":5428,"name":"test_capture_badoutput_issue412","nodeType":"Function","startLoc":761,"text":"def test_capture_badoutput_issue412(testdir):\n testdir.makepyfile(\n \"\"\"\n import os\n\n def test_func():\n omg = bytearray([1,129,1])\n os.write(1, omg)\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"--cap=fd\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *def test_func*\n *assert 0*\n *Captured*\n *1 failed*\n \"\"\"\n )"},{"col":0,"comment":"null","endLoc":793,"header":"def test_capture_early_option_parsing(testdir)","id":5429,"name":"test_capture_early_option_parsing","nodeType":"Function","startLoc":783,"text":"def test_capture_early_option_parsing(testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_runtest_setup():\n print(\"hello19\")\n \"\"\"\n )\n testdir.makepyfile(\"def test_func(): pass\")\n result = testdir.runpytest(\"-vs\")\n assert result.ret == 0\n assert \"hello19\" in result.stdout.str()"},{"col":0,"comment":"null","endLoc":814,"header":"def test_capture_binary_output(testdir)","id":5430,"name":"test_capture_binary_output","nodeType":"Function","startLoc":796,"text":"def test_capture_binary_output(testdir):\n testdir.makepyfile(\n r\"\"\"\n import pytest\n\n def test_a():\n import sys\n import subprocess\n subprocess.call([sys.executable, __file__])\n\n def test_foo():\n import os;os.write(1, b'\\xc3')\n\n if __name__ == '__main__':\n test_foo()\n \"\"\"\n )\n result = testdir.runpytest(\"--assert=plain\")\n result.assert_outcomes(passed=2)"},{"col":0,"comment":"Make sure we suspend capturing if errors occur during readouterr","endLoc":833,"header":"def test_error_during_readouterr(testdir)","id":5431,"name":"test_error_during_readouterr","nodeType":"Function","startLoc":817,"text":"def test_error_during_readouterr(testdir):\n \"\"\"Make sure we suspend capturing if errors occur during readouterr\"\"\"\n testdir.makepyfile(\n pytest_xyz=\"\"\"\n from _pytest.capture import FDCapture\n\n def bad_snap(self):\n raise Exception('boom')\n\n assert FDCapture.snap\n FDCapture.snap = bad_snap\n \"\"\"\n )\n result = testdir.runpytest_subprocess(\"-p\", \"pytest_xyz\", \"--version\")\n result.stderr.fnmatch_lines(\n [\"*in bad_snap\", \" raise Exception('boom')\", \"Exception: boom\"]\n )"},{"col":0,"comment":"null","endLoc":876,"header":"def test_dontreadfrominput()","id":5432,"name":"test_dontreadfrominput","nodeType":"Function","startLoc":866,"text":"def test_dontreadfrominput():\n from _pytest.capture import DontReadFromInput\n\n f = DontReadFromInput()\n assert not f.isatty()\n pytest.raises(IOError, f.read)\n pytest.raises(IOError, f.readlines)\n iter_f = iter(f)\n pytest.raises(IOError, next, iter_f)\n pytest.raises(UnsupportedOperation, f.fileno)\n f.close() # just for completeness"},{"col":0,"comment":"null","endLoc":891,"header":"@pytest.mark.skipif(\"sys.version_info < (3,)\", reason=\"python2 has no buffer\")\ndef test_dontreadfrominput_buffer_python3()","id":5433,"name":"test_dontreadfrominput_buffer_python3","nodeType":"Function","startLoc":879,"text":"@pytest.mark.skipif(\"sys.version_info < (3,)\", reason=\"python2 has no buffer\")\ndef test_dontreadfrominput_buffer_python3():\n from _pytest.capture import DontReadFromInput\n\n f = DontReadFromInput()\n fb = f.buffer\n assert not fb.isatty()\n pytest.raises(IOError, fb.read)\n pytest.raises(IOError, fb.readlines)\n iter_f = iter(f)\n pytest.raises(IOError, next, iter_f)\n pytest.raises(ValueError, fb.fileno)\n f.close() # just for completeness"},{"col":4,"comment":"null","endLoc":41,"header":"def test_root_conftest_syntax_error(self, testdir)","id":5434,"name":"test_root_conftest_syntax_error","nodeType":"Function","startLoc":37,"text":"def test_root_conftest_syntax_error(self, testdir):\n testdir.makepyfile(conftest=\"raise SyntaxError\\n\")\n result = testdir.runpytest()\n result.stderr.fnmatch_lines([\"*raise SyntaxError*\"])\n assert result.ret != 0"},{"col":4,"comment":"null","endLoc":61,"header":"def test_early_hook_error_issue38_1(self, testdir)","id":5435,"name":"test_early_hook_error_issue38_1","nodeType":"Function","startLoc":43,"text":"def test_early_hook_error_issue38_1(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_sessionstart():\n 0 / 0\n \"\"\"\n )\n result = testdir.runpytest(testdir.tmpdir)\n assert result.ret != 0\n # tracestyle is native by default for hook failures\n result.stdout.fnmatch_lines(\n [\"*INTERNALERROR*File*conftest.py*line 2*\", \"*0 / 0*\"]\n )\n result = testdir.runpytest(testdir.tmpdir, \"--fulltrace\")\n assert result.ret != 0\n # tracestyle is native by default for hook failures\n result.stdout.fnmatch_lines(\n [\"*INTERNALERROR*def pytest_sessionstart():*\", \"*INTERNALERROR*0 / 0*\"]\n )"},{"col":4,"comment":"null","endLoc":75,"header":"def test_early_hook_configure_error_issue38(self, testdir)","id":5436,"name":"test_early_hook_configure_error_issue38","nodeType":"Function","startLoc":63,"text":"def test_early_hook_configure_error_issue38(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_configure():\n 0 / 0\n \"\"\"\n )\n result = testdir.runpytest(testdir.tmpdir)\n assert result.ret != 0\n # here we get it on stderr\n result.stderr.fnmatch_lines(\n [\"*INTERNALERROR*File*conftest.py*line 2*\", \"*0 / 0*\"]\n )"},{"col":4,"comment":"null","endLoc":80,"header":"def test_file_not_found(self, testdir)","id":5437,"name":"test_file_not_found","nodeType":"Function","startLoc":77,"text":"def test_file_not_found(self, testdir):\n result = testdir.runpytest(\"asd\")\n assert result.ret != 0\n result.stderr.fnmatch_lines([\"ERROR: file not found*asd\"])"},{"col":4,"comment":"null","endLoc":94,"header":"def test_file_not_found_unconfigure_issue143(self, testdir)","id":5438,"name":"test_file_not_found_unconfigure_issue143","nodeType":"Function","startLoc":82,"text":"def test_file_not_found_unconfigure_issue143(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_configure():\n print(\"---configure\")\n def pytest_unconfigure():\n print(\"---unconfigure\")\n \"\"\"\n )\n result = testdir.runpytest(\"-s\", \"asd\")\n assert result.ret == 4 # EXIT_USAGEERROR\n result.stderr.fnmatch_lines([\"ERROR: file not found*asd\"])\n result.stdout.fnmatch_lines([\"*---configure\", \"*---unconfigure\"])"},{"col":4,"comment":"null","endLoc":111,"header":"def test_config_preparse_plugin_option(self, testdir)","id":5439,"name":"test_config_preparse_plugin_option","nodeType":"Function","startLoc":96,"text":"def test_config_preparse_plugin_option(self, testdir):\n testdir.makepyfile(\n pytest_xyz=\"\"\"\n def pytest_addoption(parser):\n parser.addoption(\"--xyz\", dest=\"xyz\", action=\"store\")\n \"\"\"\n )\n testdir.makepyfile(\n test_one=\"\"\"\n def test_option(pytestconfig):\n assert pytestconfig.option.xyz == \"123\"\n \"\"\"\n )\n result = testdir.runpytest(\"-p\", \"pytest_xyz\", \"--xyz=123\", syspathinsert=True)\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":4,"comment":"null","endLoc":153,"header":"@pytest.mark.parametrize(\"load_cov_early\", [True, False])\n def test_early_load_setuptools_name(self, testdir, monkeypatch, load_cov_early)","id":5440,"name":"test_early_load_setuptools_name","nodeType":"Function","startLoc":113,"text":"@pytest.mark.parametrize(\"load_cov_early\", [True, False])\n def test_early_load_setuptools_name(self, testdir, monkeypatch, load_cov_early):\n testdir.makepyfile(mytestplugin1_module=\"\")\n testdir.makepyfile(mytestplugin2_module=\"\")\n testdir.makepyfile(mycov_module=\"\")\n testdir.syspathinsert()\n\n loaded = []\n\n @attr.s\n class DummyEntryPoint(object):\n name = attr.ib()\n module = attr.ib()\n group = \"pytest11\"\n\n def load(self):\n __import__(self.module)\n loaded.append(self.name)\n return sys.modules[self.module]\n\n entry_points = [\n DummyEntryPoint(\"myplugin1\", \"mytestplugin1_module\"),\n DummyEntryPoint(\"myplugin2\", \"mytestplugin2_module\"),\n DummyEntryPoint(\"mycov\", \"mycov_module\"),\n ]\n\n @attr.s\n class DummyDist(object):\n entry_points = attr.ib()\n files = ()\n\n def my_dists():\n return (DummyDist(entry_points),)\n\n monkeypatch.setattr(importlib_metadata, \"distributions\", my_dists)\n params = (\"-p\", \"mycov\") if load_cov_early else ()\n testdir.runpytest_inprocess(*params)\n if load_cov_early:\n assert loaded == [\"mycov\", \"myplugin1\", \"myplugin2\"]\n else:\n assert loaded == [\"myplugin1\", \"myplugin2\", \"mycov\"]"},{"col":0,"comment":"null","endLoc":901,"header":"@pytest.mark.skipif(\"sys.version_info >= (3,)\", reason=\"python2 has no buffer\")\ndef test_dontreadfrominput_buffer_python2()","id":5441,"name":"test_dontreadfrominput_buffer_python2","nodeType":"Function","startLoc":894,"text":"@pytest.mark.skipif(\"sys.version_info >= (3,)\", reason=\"python2 has no buffer\")\ndef test_dontreadfrominput_buffer_python2():\n from _pytest.capture import DontReadFromInput\n\n f = DontReadFromInput()\n with pytest.raises(AttributeError):\n f.buffer\n f.close() # just for completeness"},{"col":0,"comment":"null","endLoc":909,"header":"@pytest.yield_fixture\ndef tmpfile(testdir)","id":5443,"name":"tmpfile","nodeType":"Function","startLoc":904,"text":"@pytest.yield_fixture\ndef tmpfile(testdir):\n f = testdir.makepyfile(\"\").open(\"wb+\")\n yield f\n if not f.closed:\n f.close()"},{"col":4,"comment":"null","endLoc":887,"header":"@pytest.mark.parametrize(\"name\", \"setup.cfg tox.ini\".split())\n def test_pytestini_overrides_empty_other(self, tmpdir, name)","id":5444,"name":"test_pytestini_overrides_empty_other","nodeType":"Function","startLoc":880,"text":"@pytest.mark.parametrize(\"name\", \"setup.cfg tox.ini\".split())\n def test_pytestini_overrides_empty_other(self, tmpdir, name):\n inifile = tmpdir.ensure(\"pytest.ini\")\n a = tmpdir.mkdir(\"a\")\n a.ensure(name)\n rootdir, inifile, inicfg = determine_setup(None, [a])\n assert rootdir == tmpdir\n assert inifile == inifile"},{"col":0,"comment":"null","endLoc":936,"header":"@needsosdup\ndef test_dupfile(tmpfile)","id":5445,"name":"test_dupfile","nodeType":"Function","startLoc":912,"text":"@needsosdup\ndef test_dupfile(tmpfile):\n flist = []\n for i in range(5):\n nf = capture.safe_text_dupfile(tmpfile, \"wb\")\n assert nf != tmpfile\n assert nf.fileno() != tmpfile.fileno()\n assert nf not in flist\n print(i, end=\"\", file=nf)\n flist.append(nf)\n\n fname_open = flist[0].name\n assert fname_open == repr(flist[0].buffer)\n\n for i in range(5):\n f = flist[i]\n f.close()\n fname_closed = flist[0].name\n assert fname_closed == repr(flist[0].buffer)\n assert fname_closed != fname_open\n tmpfile.seek(0)\n s = tmpfile.read()\n assert \"01234\" in repr(s)\n tmpfile.close()\n assert fname_closed == repr(flist[0].buffer)"},{"attributeType":"bool","col":8,"comment":"null","endLoc":33,"id":5446,"name":"fulltrace","nodeType":"Attribute","startLoc":33,"text":"self.fulltrace"},{"attributeType":"int","col":8,"comment":"null","endLoc":32,"id":5447,"name":"verbosity","nodeType":"Attribute","startLoc":32,"text":"self.verbosity"},{"className":"TestTerminal","col":0,"comment":"null","endLoc":282,"id":5448,"nodeType":"Class","startLoc":78,"text":"class TestTerminal(object):\n def test_pass_skip_fail(self, testdir, option):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_ok():\n pass\n def test_skip():\n pytest.skip(\"xx\")\n def test_func():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(*option.args)\n if option.verbosity > 0:\n result.stdout.fnmatch_lines(\n [\n \"*test_pass_skip_fail.py::test_ok PASS*\",\n \"*test_pass_skip_fail.py::test_skip SKIP*\",\n \"*test_pass_skip_fail.py::test_func FAIL*\",\n ]\n )\n elif option.verbosity == 0:\n result.stdout.fnmatch_lines([\"*test_pass_skip_fail.py .sF*\"])\n else:\n result.stdout.fnmatch_lines([\".sF*\"])\n result.stdout.fnmatch_lines(\n [\" def test_func():\", \"> assert 0\", \"E assert 0\"]\n )\n\n def test_internalerror(self, testdir, linecomp):\n modcol = testdir.getmodulecol(\"def test_one(): pass\")\n rep = TerminalReporter(modcol.config, file=linecomp.stringio)\n with pytest.raises(ValueError) as excinfo:\n raise ValueError(\"hello\")\n rep.pytest_internalerror(excinfo.getrepr())\n linecomp.assert_contains_lines([\"INTERNALERROR> *ValueError*hello*\"])\n\n def test_writeline(self, testdir, linecomp):\n modcol = testdir.getmodulecol(\"def test_one(): pass\")\n rep = TerminalReporter(modcol.config, file=linecomp.stringio)\n rep.write_fspath_result(modcol.nodeid, \".\")\n rep.write_line(\"hello world\")\n lines = linecomp.stringio.getvalue().split(\"\\n\")\n assert not lines[0]\n assert lines[1].endswith(modcol.name + \" .\")\n assert lines[2] == \"hello world\"\n\n def test_show_runtest_logstart(self, testdir, linecomp):\n item = testdir.getitem(\"def test_func(): pass\")\n tr = TerminalReporter(item.config, file=linecomp.stringio)\n item.config.pluginmanager.register(tr)\n location = item.reportinfo()\n tr.config.hook.pytest_runtest_logstart(\n nodeid=item.nodeid, location=location, fspath=str(item.fspath)\n )\n linecomp.assert_contains_lines([\"*test_show_runtest_logstart.py*\"])\n\n def test_runtest_location_shown_before_test_starts(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_1():\n import time\n time.sleep(20)\n \"\"\"\n )\n child = testdir.spawn_pytest(\"\")\n child.expect(\".*test_runtest_location.*py\")\n child.sendeof()\n child.kill(15)\n\n def test_report_collect_after_half_a_second(self, testdir):\n \"\"\"Test for \"collecting\" being updated after 0.5s\"\"\"\n\n testdir.makepyfile(\n **{\n \"test1.py\": \"\"\"\n import _pytest.terminal\n\n _pytest.terminal.REPORT_COLLECTING_RESOLUTION = 0\n\n def test_1():\n pass\n \"\"\",\n \"test2.py\": \"def test_2(): pass\",\n }\n )\n\n child = testdir.spawn_pytest(\"-v test1.py test2.py\")\n child.expect(r\"collecting \\.\\.\\.\")\n child.expect(r\"collecting 1 item\")\n child.expect(r\"collecting 2 items\")\n child.expect(r\"collected 2 items\")\n rest = child.read().decode(\"utf8\")\n assert \"2 passed in\" in rest\n\n def test_itemreport_subclasses_show_subclassed_file(self, testdir):\n testdir.makepyfile(\n test_p1=\"\"\"\n class BaseTests(object):\n def test_p1(self):\n pass\n class TestClass(BaseTests):\n pass\n \"\"\"\n )\n p2 = testdir.makepyfile(\n test_p2=\"\"\"\n from test_p1 import BaseTests\n class TestMore(BaseTests):\n pass\n \"\"\"\n )\n result = testdir.runpytest(p2)\n result.stdout.fnmatch_lines([\"*test_p2.py .*\", \"*1 passed*\"])\n result = testdir.runpytest(\"-vv\", p2)\n result.stdout.fnmatch_lines(\n [\"*test_p2.py::TestMore::test_p1* <- *test_p1.py*PASSED*\"]\n )\n\n def test_itemreport_directclasses_not_shown_as_subclasses(self, testdir):\n a = testdir.mkpydir(\"a123\")\n a.join(\"test_hello123.py\").write(\n textwrap.dedent(\n \"\"\"\\\n class TestClass(object):\n def test_method(self):\n pass\n \"\"\"\n )\n )\n result = testdir.runpytest(\"-vv\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*a123/test_hello123.py*PASS*\"])\n assert \" <- \" not in result.stdout.str()\n\n def test_keyboard_interrupt(self, testdir, option):\n testdir.makepyfile(\n \"\"\"\n def test_foobar():\n assert 0\n def test_spamegg():\n import py; pytest.skip('skip me please!')\n def test_interrupt_me():\n raise KeyboardInterrupt # simulating the user\n \"\"\"\n )\n\n result = testdir.runpytest(*option.args, no_reraise_ctrlc=True)\n result.stdout.fnmatch_lines(\n [\n \" def test_foobar():\",\n \"> assert 0\",\n \"E assert 0\",\n \"*_keyboard_interrupt.py:6: KeyboardInterrupt*\",\n ]\n )\n if option.fulltrace:\n result.stdout.fnmatch_lines(\n [\"*raise KeyboardInterrupt # simulating the user*\"]\n )\n else:\n result.stdout.fnmatch_lines(\n [\"(to show a full traceback on KeyboardInterrupt use --fulltrace)\"]\n )\n result.stdout.fnmatch_lines([\"*KeyboardInterrupt*\"])\n\n def test_keyboard_in_sessionstart(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_sessionstart():\n raise KeyboardInterrupt\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_foobar():\n pass\n \"\"\"\n )\n\n result = testdir.runpytest(no_reraise_ctrlc=True)\n assert result.ret == 2\n result.stdout.fnmatch_lines([\"*KeyboardInterrupt*\"])\n\n def test_collect_single_item(self, testdir):\n \"\"\"Use singular 'item' when reporting a single test item\"\"\"\n testdir.makepyfile(\n \"\"\"\n def test_foobar():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"collected 1 item\"])\n\n def test_rewrite(self, testdir, monkeypatch):\n config = testdir.parseconfig()\n f = py.io.TextIO()\n monkeypatch.setattr(f, \"isatty\", lambda *args: True)\n tr = TerminalReporter(config, f)\n tr._tw.fullwidth = 10\n tr.write(\"hello\")\n tr.rewrite(\"hey\", erase=True)\n assert f.getvalue() == \"hello\" + \"\\r\" + \"hey\" + (6 * \" \")"},{"col":4,"comment":"null","endLoc":106,"header":"def test_pass_skip_fail(self, testdir, option)","id":5449,"name":"test_pass_skip_fail","nodeType":"Function","startLoc":79,"text":"def test_pass_skip_fail(self, testdir, option):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_ok():\n pass\n def test_skip():\n pytest.skip(\"xx\")\n def test_func():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(*option.args)\n if option.verbosity > 0:\n result.stdout.fnmatch_lines(\n [\n \"*test_pass_skip_fail.py::test_ok PASS*\",\n \"*test_pass_skip_fail.py::test_skip SKIP*\",\n \"*test_pass_skip_fail.py::test_func FAIL*\",\n ]\n )\n elif option.verbosity == 0:\n result.stdout.fnmatch_lines([\"*test_pass_skip_fail.py .sF*\"])\n else:\n result.stdout.fnmatch_lines([\".sF*\"])\n result.stdout.fnmatch_lines(\n [\" def test_func():\", \"> assert 0\", \"E assert 0\"]\n )"},{"col":4,"comment":"null","endLoc":896,"header":"def test_setuppy_fallback(self, tmpdir)","id":5450,"name":"test_setuppy_fallback","nodeType":"Function","startLoc":889,"text":"def test_setuppy_fallback(self, tmpdir):\n a = tmpdir.mkdir(\"a\")\n a.ensure(\"setup.cfg\")\n tmpdir.ensure(\"setup.py\")\n rootdir, inifile, inicfg = determine_setup(None, [a])\n assert rootdir == tmpdir\n assert inifile is None\n assert inicfg == {}"},{"col":4,"comment":"null","endLoc":903,"header":"def test_nothing(self, tmpdir, monkeypatch)","id":5451,"name":"test_nothing","nodeType":"Function","startLoc":898,"text":"def test_nothing(self, tmpdir, monkeypatch):\n monkeypatch.chdir(str(tmpdir))\n rootdir, inifile, inicfg = determine_setup(None, [tmpdir])\n assert rootdir == tmpdir\n assert inifile is None\n assert inicfg == {}"},{"className":"LsofFdLeakChecker","col":0,"comment":"null","endLoc":153,"id":5452,"nodeType":"Class","startLoc":87,"text":"class LsofFdLeakChecker(object):\n def get_open_files(self):\n out = self._exec_lsof()\n open_files = self._parse_lsof_output(out)\n return open_files\n\n def _exec_lsof(self):\n pid = os.getpid()\n # py3: use subprocess.DEVNULL directly.\n with open(os.devnull, \"wb\") as devnull:\n return subprocess.check_output(\n (\"lsof\", \"-Ffn0\", \"-p\", str(pid)), stderr=devnull\n ).decode()\n\n def _parse_lsof_output(self, out):\n def isopen(line):\n return line.startswith(\"f\") and (\n \"deleted\" not in line\n and \"mem\" not in line\n and \"txt\" not in line\n and \"cwd\" not in line\n )\n\n open_files = []\n\n for line in out.split(\"\\n\"):\n if isopen(line):\n fields = line.split(\"\\0\")\n fd = fields[0][1:]\n filename = fields[1][1:]\n if filename in IGNORE_PAM:\n continue\n if filename.startswith(\"/\"):\n open_files.append((fd, filename))\n\n return open_files\n\n def matching_platform(self):\n try:\n subprocess.check_output((\"lsof\", \"-v\"))\n except (OSError, subprocess.CalledProcessError):\n return False\n else:\n return True\n\n @pytest.hookimpl(hookwrapper=True, tryfirst=True)\n def pytest_runtest_protocol(self, item):\n lines1 = self.get_open_files()\n yield\n if hasattr(sys, \"pypy_version_info\"):\n gc.collect()\n lines2 = self.get_open_files()\n\n new_fds = {t[0] for t in lines2} - {t[0] for t in lines1}\n leaked_files = [t for t in lines2 if t[0] in new_fds]\n if leaked_files:\n error = []\n error.append(\"***** %s FD leakage detected\" % len(leaked_files))\n error.extend([str(f) for f in leaked_files])\n error.append(\"*** Before:\")\n error.extend([str(f) for f in lines1])\n error.append(\"*** After:\")\n error.extend([str(f) for f in lines2])\n error.append(error[0])\n error.append(\"*** function %s:%s: %s \" % item.location)\n error.append(\"See issue #2366\")\n item.warn(pytest.PytestWarning(\"\\n\".join(error)))"},{"col":4,"comment":"null","endLoc":91,"header":"def get_open_files(self)","id":5453,"name":"get_open_files","nodeType":"Function","startLoc":88,"text":"def get_open_files(self):\n out = self._exec_lsof()\n open_files = self._parse_lsof_output(out)\n return open_files"},{"col":4,"comment":"null","endLoc":114,"header":"def test_internalerror(self, testdir, linecomp)","id":5454,"name":"test_internalerror","nodeType":"Function","startLoc":108,"text":"def test_internalerror(self, testdir, linecomp):\n modcol = testdir.getmodulecol(\"def test_one(): pass\")\n rep = TerminalReporter(modcol.config, file=linecomp.stringio)\n with pytest.raises(ValueError) as excinfo:\n raise ValueError(\"hello\")\n rep.pytest_internalerror(excinfo.getrepr())\n linecomp.assert_contains_lines([\"INTERNALERROR> *ValueError*hello*\"])"},{"col":4,"comment":"null","endLoc":165,"header":"def test_assertion_magic(self, testdir)","id":5455,"name":"test_assertion_magic","nodeType":"Function","startLoc":155,"text":"def test_assertion_magic(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_this():\n x = 0\n assert x\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"> assert x\", \"E assert 0\"])\n assert result.ret == 1"},{"col":4,"comment":"null","endLoc":184,"header":"def test_nested_import_error(self, testdir)","id":5456,"name":"test_nested_import_error","nodeType":"Function","startLoc":167,"text":"def test_nested_import_error(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import import_fails\n def test_this():\n assert import_fails.a == 1\n \"\"\"\n )\n testdir.makepyfile(import_fails=\"import does_not_work\")\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines(\n [\n # XXX on jython this fails: \"> import import_fails\",\n \"ImportError while importing test module*\",\n \"*No module named *does_not_work*\",\n ]\n )\n assert result.ret == 2"},{"col":4,"comment":"null","endLoc":908,"header":"def test_with_specific_inifile(self, tmpdir)","id":5457,"name":"test_with_specific_inifile","nodeType":"Function","startLoc":905,"text":"def test_with_specific_inifile(self, tmpdir):\n inifile = tmpdir.ensure(\"pytest.ini\")\n rootdir, inifile, inicfg = determine_setup(inifile, [tmpdir])\n assert rootdir == tmpdir"},{"fileName":"argparsing.py","filePath":"src/_pytest/config","id":5458,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport argparse\nimport warnings\n\nimport py\nimport six\n\nfrom _pytest.config.exceptions import UsageError\n\nFILE_OR_DIR = \"file_or_dir\"\n\n\nclass Parser(object):\n \"\"\" Parser for command line arguments and ini-file values.\n\n :ivar extra_info: dict of generic param -> value to display in case\n there's an error processing the command line arguments.\n \"\"\"\n\n prog = None\n\n def __init__(self, usage=None, processopt=None):\n self._anonymous = OptionGroup(\"custom options\", parser=self)\n self._groups = []\n self._processopt = processopt\n self._usage = usage\n self._inidict = {}\n self._ininames = []\n self.extra_info = {}\n\n def processoption(self, option):\n if self._processopt:\n if option.dest:\n self._processopt(option)\n\n def getgroup(self, name, description=\"\", after=None):\n \"\"\" get (or create) a named option Group.\n\n :name: name of the option group.\n :description: long description for --help output.\n :after: name of other group, used for ordering --help output.\n\n The returned group object has an ``addoption`` method with the same\n signature as :py:func:`parser.addoption\n <_pytest.config.Parser.addoption>` but will be shown in the\n respective group in the output of ``pytest. --help``.\n \"\"\"\n for group in self._groups:\n if group.name == name:\n return group\n group = OptionGroup(name, description, parser=self)\n i = 0\n for i, grp in enumerate(self._groups):\n if grp.name == after:\n break\n self._groups.insert(i + 1, group)\n return group\n\n def addoption(self, *opts, **attrs):\n \"\"\" register a command line option.\n\n :opts: option names, can be short or long options.\n :attrs: same attributes which the ``add_option()`` function of the\n `argparse library\n `_\n accepts.\n\n After command line parsing options are available on the pytest config\n object via ``config.option.NAME`` where ``NAME`` is usually set\n by passing a ``dest`` attribute, for example\n ``addoption(\"--long\", dest=\"NAME\", ...)``.\n \"\"\"\n self._anonymous.addoption(*opts, **attrs)\n\n def parse(self, args, namespace=None):\n from _pytest._argcomplete import try_argcomplete\n\n self.optparser = self._getparser()\n try_argcomplete(self.optparser)\n args = [str(x) if isinstance(x, py.path.local) else x for x in args]\n return self.optparser.parse_args(args, namespace=namespace)\n\n def _getparser(self):\n from _pytest._argcomplete import filescompleter\n\n optparser = MyOptionParser(self, self.extra_info, prog=self.prog)\n groups = self._groups + [self._anonymous]\n for group in groups:\n if group.options:\n desc = group.description or group.name\n arggroup = optparser.add_argument_group(desc)\n for option in group.options:\n n = option.names()\n a = option.attrs()\n arggroup.add_argument(*n, **a)\n # bash like autocompletion for dirs (appending '/')\n optparser.add_argument(FILE_OR_DIR, nargs=\"*\").completer = filescompleter\n return optparser\n\n def parse_setoption(self, args, option, namespace=None):\n parsedoption = self.parse(args, namespace=namespace)\n for name, value in parsedoption.__dict__.items():\n setattr(option, name, value)\n return getattr(parsedoption, FILE_OR_DIR)\n\n def parse_known_args(self, args, namespace=None):\n \"\"\"parses and returns a namespace object with known arguments at this\n point.\n \"\"\"\n return self.parse_known_and_unknown_args(args, namespace=namespace)[0]\n\n def parse_known_and_unknown_args(self, args, namespace=None):\n \"\"\"parses and returns a namespace object with known arguments, and\n the remaining arguments unknown at this point.\n \"\"\"\n optparser = self._getparser()\n args = [str(x) if isinstance(x, py.path.local) else x for x in args]\n return optparser.parse_known_args(args, namespace=namespace)\n\n def addini(self, name, help, type=None, default=None):\n \"\"\" register an ini-file option.\n\n :name: name of the ini-variable\n :type: type of the variable, can be ``pathlist``, ``args``, ``linelist``\n or ``bool``.\n :default: default value if no ini-file option exists but is queried.\n\n The value of ini-variables can be retrieved via a call to\n :py:func:`config.getini(name) <_pytest.config.Config.getini>`.\n \"\"\"\n assert type in (None, \"pathlist\", \"args\", \"linelist\", \"bool\")\n self._inidict[name] = (help, type, default)\n self._ininames.append(name)\n\n\nclass ArgumentError(Exception):\n \"\"\"\n Raised if an Argument instance is created with invalid or\n inconsistent arguments.\n \"\"\"\n\n def __init__(self, msg, option):\n self.msg = msg\n self.option_id = str(option)\n\n def __str__(self):\n if self.option_id:\n return \"option %s: %s\" % (self.option_id, self.msg)\n else:\n return self.msg\n\n\nclass Argument(object):\n \"\"\"class that mimics the necessary behaviour of optparse.Option\n\n it's currently a least effort implementation\n and ignoring choices and integer prefixes\n https://docs.python.org/3/library/optparse.html#optparse-standard-option-types\n \"\"\"\n\n _typ_map = {\"int\": int, \"string\": str, \"float\": float, \"complex\": complex}\n\n def __init__(self, *names, **attrs):\n \"\"\"store parms in private vars for use in add_argument\"\"\"\n self._attrs = attrs\n self._short_opts = []\n self._long_opts = []\n self.dest = attrs.get(\"dest\")\n if \"%default\" in (attrs.get(\"help\") or \"\"):\n warnings.warn(\n 'pytest now uses argparse. \"%default\" should be'\n ' changed to \"%(default)s\" ',\n DeprecationWarning,\n stacklevel=3,\n )\n try:\n typ = attrs[\"type\"]\n except KeyError:\n pass\n else:\n # this might raise a keyerror as well, don't want to catch that\n if isinstance(typ, six.string_types):\n if typ == \"choice\":\n warnings.warn(\n \"`type` argument to addoption() is the string %r.\"\n \" For choices this is optional and can be omitted, \"\n \" but when supplied should be a type (for example `str` or `int`).\"\n \" (options: %s)\" % (typ, names),\n DeprecationWarning,\n stacklevel=4,\n )\n # argparse expects a type here take it from\n # the type of the first element\n attrs[\"type\"] = type(attrs[\"choices\"][0])\n else:\n warnings.warn(\n \"`type` argument to addoption() is the string %r, \"\n \" but when supplied should be a type (for example `str` or `int`).\"\n \" (options: %s)\" % (typ, names),\n DeprecationWarning,\n stacklevel=4,\n )\n attrs[\"type\"] = Argument._typ_map[typ]\n # used in test_parseopt -> test_parse_defaultgetter\n self.type = attrs[\"type\"]\n else:\n self.type = typ\n try:\n # attribute existence is tested in Config._processopt\n self.default = attrs[\"default\"]\n except KeyError:\n pass\n self._set_opt_strings(names)\n if not self.dest:\n if self._long_opts:\n self.dest = self._long_opts[0][2:].replace(\"-\", \"_\")\n else:\n try:\n self.dest = self._short_opts[0][1:]\n except IndexError:\n raise ArgumentError(\"need a long or short option\", self)\n\n def names(self):\n return self._short_opts + self._long_opts\n\n def attrs(self):\n # update any attributes set by processopt\n attrs = \"default dest help\".split()\n if self.dest:\n attrs.append(self.dest)\n for attr in attrs:\n try:\n self._attrs[attr] = getattr(self, attr)\n except AttributeError:\n pass\n if self._attrs.get(\"help\"):\n a = self._attrs[\"help\"]\n a = a.replace(\"%default\", \"%(default)s\")\n # a = a.replace('%prog', '%(prog)s')\n self._attrs[\"help\"] = a\n return self._attrs\n\n def _set_opt_strings(self, opts):\n \"\"\"directly from optparse\n\n might not be necessary as this is passed to argparse later on\"\"\"\n for opt in opts:\n if len(opt) < 2:\n raise ArgumentError(\n \"invalid option string %r: \"\n \"must be at least two characters long\" % opt,\n self,\n )\n elif len(opt) == 2:\n if not (opt[0] == \"-\" and opt[1] != \"-\"):\n raise ArgumentError(\n \"invalid short option string %r: \"\n \"must be of the form -x, (x any non-dash char)\" % opt,\n self,\n )\n self._short_opts.append(opt)\n else:\n if not (opt[0:2] == \"--\" and opt[2] != \"-\"):\n raise ArgumentError(\n \"invalid long option string %r: \"\n \"must start with --, followed by non-dash\" % opt,\n self,\n )\n self._long_opts.append(opt)\n\n def __repr__(self):\n args = []\n if self._short_opts:\n args += [\"_short_opts: \" + repr(self._short_opts)]\n if self._long_opts:\n args += [\"_long_opts: \" + repr(self._long_opts)]\n args += [\"dest: \" + repr(self.dest)]\n if hasattr(self, \"type\"):\n args += [\"type: \" + repr(self.type)]\n if hasattr(self, \"default\"):\n args += [\"default: \" + repr(self.default)]\n return \"Argument({})\".format(\", \".join(args))\n\n\nclass OptionGroup(object):\n def __init__(self, name, description=\"\", parser=None):\n self.name = name\n self.description = description\n self.options = []\n self.parser = parser\n\n def addoption(self, *optnames, **attrs):\n \"\"\" add an option to this group.\n\n if a shortened version of a long option is specified it will\n be suppressed in the help. addoption('--twowords', '--two-words')\n results in help showing '--two-words' only, but --twowords gets\n accepted **and** the automatic destination is in args.twowords\n \"\"\"\n conflict = set(optnames).intersection(\n name for opt in self.options for name in opt.names()\n )\n if conflict:\n raise ValueError(\"option names %s already added\" % conflict)\n option = Argument(*optnames, **attrs)\n self._addoption_instance(option, shortupper=False)\n\n def _addoption(self, *optnames, **attrs):\n option = Argument(*optnames, **attrs)\n self._addoption_instance(option, shortupper=True)\n\n def _addoption_instance(self, option, shortupper=False):\n if not shortupper:\n for opt in option._short_opts:\n if opt[0] == \"-\" and opt[1].islower():\n raise ValueError(\"lowercase shortoptions reserved\")\n if self.parser:\n self.parser.processoption(option)\n self.options.append(option)\n\n\nclass MyOptionParser(argparse.ArgumentParser):\n def __init__(self, parser, extra_info=None, prog=None):\n if not extra_info:\n extra_info = {}\n self._parser = parser\n argparse.ArgumentParser.__init__(\n self,\n prog=prog,\n usage=parser._usage,\n add_help=False,\n formatter_class=DropShorterLongHelpFormatter,\n )\n # extra_info is a dict of (param -> value) to display if there's\n # an usage error to provide more contextual information to the user\n self.extra_info = extra_info\n\n def error(self, message):\n \"\"\"Transform argparse error message into UsageError.\"\"\"\n msg = \"%s: error: %s\" % (self.prog, message)\n\n if hasattr(self._parser, \"_config_source_hint\"):\n msg = \"%s (%s)\" % (msg, self._parser._config_source_hint)\n\n raise UsageError(self.format_usage() + msg)\n\n def parse_args(self, args=None, namespace=None):\n \"\"\"allow splitting of positional arguments\"\"\"\n args, argv = self.parse_known_args(args, namespace)\n if argv:\n for arg in argv:\n if arg and arg[0] == \"-\":\n lines = [\"unrecognized arguments: %s\" % (\" \".join(argv))]\n for k, v in sorted(self.extra_info.items()):\n lines.append(\" %s: %s\" % (k, v))\n self.error(\"\\n\".join(lines))\n getattr(args, FILE_OR_DIR).extend(argv)\n return args\n\n\nclass DropShorterLongHelpFormatter(argparse.HelpFormatter):\n \"\"\"shorten help for long options that differ only in extra hyphens\n\n - collapse **long** options that are the same except for extra hyphens\n - special action attribute map_long_option allows surpressing additional\n long options\n - shortcut if there are only two options and one of them is a short one\n - cache result on action object as this is called at least 2 times\n \"\"\"\n\n def _format_action_invocation(self, action):\n orgstr = argparse.HelpFormatter._format_action_invocation(self, action)\n if orgstr and orgstr[0] != \"-\": # only optional arguments\n return orgstr\n res = getattr(action, \"_formatted_action_invocation\", None)\n if res:\n return res\n options = orgstr.split(\", \")\n if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2):\n # a shortcut for '-h, --help' or '--abc', '-a'\n action._formatted_action_invocation = orgstr\n return orgstr\n return_list = []\n option_map = getattr(action, \"map_long_option\", {})\n if option_map is None:\n option_map = {}\n short_long = {}\n for option in options:\n if len(option) == 2 or option[2] == \" \":\n continue\n if not option.startswith(\"--\"):\n raise ArgumentError(\n 'long optional argument without \"--\": [%s]' % (option), self\n )\n xxoption = option[2:]\n if xxoption.split()[0] not in option_map:\n shortened = xxoption.replace(\"-\", \"\")\n if shortened not in short_long or len(short_long[shortened]) < len(\n xxoption\n ):\n short_long[shortened] = xxoption\n # now short_long has been filled out to the longest with dashes\n # **and** we keep the right option ordering from add_argument\n for option in options:\n if len(option) == 2 or option[2] == \" \":\n return_list.append(option)\n if option[2:] == short_long.get(option.replace(\"-\", \"\")):\n return_list.append(option.replace(\" \", \"=\", 1))\n action._formatted_action_invocation = \", \".join(return_list)\n return action._formatted_action_invocation\n"},{"col":4,"comment":" return True if the current frame has a var __tracebackhide__\n resolving to True.\n\n If __tracebackhide__ is a callable, it gets called with the\n ExceptionInfo instance and can decide whether to hide the traceback.\n\n mostly for internal use\n ","endLoc":257,"header":"def ishidden(self)","id":5459,"name":"ishidden","nodeType":"Function","startLoc":242,"text":"def ishidden(self):\n \"\"\" return True if the current frame has a var __tracebackhide__\n resolving to True.\n\n If __tracebackhide__ is a callable, it gets called with the\n ExceptionInfo instance and can decide whether to hide the traceback.\n\n mostly for internal use\n \"\"\"\n f = self.frame\n tbh = f.f_locals.get(\n \"__tracebackhide__\", f.f_globals.get(\"__tracebackhide__\", False)\n )\n if tbh and callable(tbh):\n return tbh(None if self._excinfo is None else self._excinfo())\n return tbh"},{"className":"TestOverrideIniArgs","col":0,"comment":"null","endLoc":1140,"id":5460,"nodeType":"Class","startLoc":911,"text":"class TestOverrideIniArgs(object):\n @pytest.mark.parametrize(\"name\", \"setup.cfg tox.ini pytest.ini\".split())\n def test_override_ini_names(self, testdir, name):\n section = \"[pytest]\" if name != \"setup.cfg\" else \"[tool:pytest]\"\n testdir.tmpdir.join(name).write(\n textwrap.dedent(\n \"\"\"\n {section}\n custom = 1.0\"\"\".format(\n section=section\n )\n )\n )\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"custom\", \"\")\"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_pass(pytestconfig):\n ini_val = pytestconfig.getini(\"custom\")\n print('\\\\ncustom_option:%s\\\\n' % ini_val)\"\"\"\n )\n\n result = testdir.runpytest(\"--override-ini\", \"custom=2.0\", \"-s\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"custom_option:2.0\"])\n\n result = testdir.runpytest(\n \"--override-ini\", \"custom=2.0\", \"--override-ini=custom=3.0\", \"-s\"\n )\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"custom_option:3.0\"])\n\n def test_override_ini_pathlist(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"paths\", \"my new ini value\", type=\"pathlist\")\"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n paths=blah.py\"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import py.path\n def test_pathlist(pytestconfig):\n config_paths = pytestconfig.getini(\"paths\")\n print(config_paths)\n for cpf in config_paths:\n print('\\\\nuser_path:%s' % cpf.basename)\"\"\"\n )\n result = testdir.runpytest(\n \"--override-ini\", \"paths=foo/bar1.py foo/bar2.py\", \"-s\"\n )\n result.stdout.fnmatch_lines([\"user_path:bar1.py\", \"user_path:bar2.py\"])\n\n def test_override_multiple_and_default(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n addini = parser.addini\n addini(\"custom_option_1\", \"\", default=\"o1\")\n addini(\"custom_option_2\", \"\", default=\"o2\")\n addini(\"custom_option_3\", \"\", default=False, type=\"bool\")\n addini(\"custom_option_4\", \"\", default=True, type=\"bool\")\"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n custom_option_1=custom_option_1\n custom_option_2=custom_option_2\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_multiple_options(pytestconfig):\n prefix = \"custom_option\"\n for x in range(1, 5):\n ini_value=pytestconfig.getini(\"%s_%d\" % (prefix, x))\n print('\\\\nini%d:%s' % (x, ini_value))\n \"\"\"\n )\n result = testdir.runpytest(\n \"--override-ini\",\n \"custom_option_1=fulldir=/tmp/user1\",\n \"-o\",\n \"custom_option_2=url=/tmp/user2?a=b&d=e\",\n \"-o\",\n \"custom_option_3=True\",\n \"-o\",\n \"custom_option_4=no\",\n \"-s\",\n )\n result.stdout.fnmatch_lines(\n [\n \"ini1:fulldir=/tmp/user1\",\n \"ini2:url=/tmp/user2?a=b&d=e\",\n \"ini3:True\",\n \"ini4:False\",\n ]\n )\n\n def test_override_ini_usage_error_bad_style(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n xdist_strict=False\n \"\"\"\n )\n result = testdir.runpytest(\"--override-ini\", \"xdist_strict True\", \"-s\")\n result.stderr.fnmatch_lines([\"*ERROR* *expects option=value*\"])\n\n @pytest.mark.parametrize(\"with_ini\", [True, False])\n def test_override_ini_handled_asap(self, testdir, with_ini):\n \"\"\"-o should be handled as soon as possible and always override what's in ini files (#2238)\"\"\"\n if with_ini:\n testdir.makeini(\n \"\"\"\n [pytest]\n python_files=test_*.py\n \"\"\"\n )\n testdir.makepyfile(\n unittest_ini_handle=\"\"\"\n def test():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--override-ini\", \"python_files=unittest_*.py\")\n result.stdout.fnmatch_lines([\"*1 passed in*\"])\n\n def test_with_arg_outside_cwd_without_inifile(self, tmpdir, monkeypatch):\n monkeypatch.chdir(str(tmpdir))\n a = tmpdir.mkdir(\"a\")\n b = tmpdir.mkdir(\"b\")\n rootdir, inifile, inicfg = determine_setup(None, [a, b])\n assert rootdir == tmpdir\n assert inifile is None\n\n def test_with_arg_outside_cwd_with_inifile(self, tmpdir):\n a = tmpdir.mkdir(\"a\")\n b = tmpdir.mkdir(\"b\")\n inifile = a.ensure(\"pytest.ini\")\n rootdir, parsed_inifile, inicfg = determine_setup(None, [a, b])\n assert rootdir == a\n assert inifile == parsed_inifile\n\n @pytest.mark.parametrize(\"dirs\", ([], [\"does-not-exist\"], [\"a/does-not-exist\"]))\n def test_with_non_dir_arg(self, dirs, tmpdir):\n with tmpdir.ensure(dir=True).as_cwd():\n rootdir, inifile, inicfg = determine_setup(None, dirs)\n assert rootdir == tmpdir\n assert inifile is None\n\n def test_with_existing_file_in_subdir(self, tmpdir):\n a = tmpdir.mkdir(\"a\")\n a.ensure(\"exist\")\n with tmpdir.as_cwd():\n rootdir, inifile, inicfg = determine_setup(None, [\"a/exist\"])\n assert rootdir == tmpdir\n assert inifile is None\n\n def test_addopts_before_initini(self, monkeypatch, _config_for_test, _sys_snapshot):\n cache_dir = \".custom_cache\"\n monkeypatch.setenv(\"PYTEST_ADDOPTS\", \"-o cache_dir=%s\" % cache_dir)\n config = _config_for_test\n config._preparse([], addopts=True)\n assert config._override_ini == [\"cache_dir=%s\" % cache_dir]\n\n def test_addopts_from_env_not_concatenated(self, monkeypatch, _config_for_test):\n \"\"\"PYTEST_ADDOPTS should not take values from normal args (#4265).\"\"\"\n monkeypatch.setenv(\"PYTEST_ADDOPTS\", \"-o\")\n config = _config_for_test\n with pytest.raises(UsageError) as excinfo:\n config._preparse([\"cache_dir=ignored\"], addopts=True)\n assert (\n \"error: argument -o/--override-ini: expected one argument (via PYTEST_ADDOPTS)\"\n in excinfo.value.args[0]\n )\n\n def test_addopts_from_ini_not_concatenated(self, testdir):\n \"\"\"addopts from ini should not take values from normal args (#4265).\"\"\"\n testdir.makeini(\n \"\"\"\n [pytest]\n addopts=-o\n \"\"\"\n )\n result = testdir.runpytest(\"cache_dir=ignored\")\n result.stderr.fnmatch_lines(\n [\n \"%s: error: argument -o/--override-ini: expected one argument (via addopts config)\"\n % (testdir.request.config._parser.optparser.prog,)\n ]\n )\n assert result.ret == _pytest.main.EXIT_USAGEERROR\n\n def test_override_ini_does_not_contain_paths(self, _config_for_test, _sys_snapshot):\n \"\"\"Check that -o no longer swallows all options after it (#3103)\"\"\"\n config = _config_for_test\n config._preparse([\"-o\", \"cache_dir=/cache\", \"/some/test/path\"])\n assert config._override_ini == [\"cache_dir=/cache\"]\n\n def test_multiple_override_ini_options(self, testdir, request):\n \"\"\"Ensure a file path following a '-o' option does not generate an error (#3103)\"\"\"\n testdir.makepyfile(\n **{\n \"conftest.py\": \"\"\"\n def pytest_addoption(parser):\n parser.addini('foo', default=None, help='some option')\n parser.addini('bar', default=None, help='some option')\n \"\"\",\n \"test_foo.py\": \"\"\"\n def test(pytestconfig):\n assert pytestconfig.getini('foo') == '1'\n assert pytestconfig.getini('bar') == '0'\n \"\"\",\n \"test_bar.py\": \"\"\"\n def test():\n assert False\n \"\"\",\n }\n )\n result = testdir.runpytest(\"-o\", \"foo=1\", \"-o\", \"bar=0\", \"test_foo.py\")\n assert \"ERROR:\" not in result.stderr.str()\n result.stdout.fnmatch_lines([\"collected 1 item\", \"*= 1 passed in *=\"])"},{"col":4,"comment":"null","endLoc":944,"header":"@pytest.mark.parametrize(\"name\", \"setup.cfg tox.ini pytest.ini\".split())\n def test_override_ini_names(self, testdir, name)","id":5461,"name":"test_override_ini_names","nodeType":"Function","startLoc":912,"text":"@pytest.mark.parametrize(\"name\", \"setup.cfg tox.ini pytest.ini\".split())\n def test_override_ini_names(self, testdir, name):\n section = \"[pytest]\" if name != \"setup.cfg\" else \"[tool:pytest]\"\n testdir.tmpdir.join(name).write(\n textwrap.dedent(\n \"\"\"\n {section}\n custom = 1.0\"\"\".format(\n section=section\n )\n )\n )\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"custom\", \"\")\"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_pass(pytestconfig):\n ini_val = pytestconfig.getini(\"custom\")\n print('\\\\ncustom_option:%s\\\\n' % ini_val)\"\"\"\n )\n\n result = testdir.runpytest(\"--override-ini\", \"custom=2.0\", \"-s\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"custom_option:2.0\"])\n\n result = testdir.runpytest(\n \"--override-ini\", \"custom=2.0\", \"--override-ini=custom=3.0\", \"-s\"\n )\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"custom_option:3.0\"])"},{"col":4,"comment":"null","endLoc":191,"header":"def test_not_collectable_arguments(self, testdir)","id":5462,"name":"test_not_collectable_arguments","nodeType":"Function","startLoc":186,"text":"def test_not_collectable_arguments(self, testdir):\n p1 = testdir.makepyfile(\"\")\n p2 = testdir.makefile(\".pyc\", \"123\")\n result = testdir.runpytest(p1, p2)\n assert result.ret\n result.stderr.fnmatch_lines([\"*ERROR: not found:*{}\".format(p2.basename)])"},{"className":"Parser","col":0,"comment":" Parser for command line arguments and ini-file values.\n\n :ivar extra_info: dict of generic param -> value to display in case\n there's an error processing the command line arguments.\n ","endLoc":133,"id":5463,"nodeType":"Class","startLoc":13,"text":"class Parser(object):\n \"\"\" Parser for command line arguments and ini-file values.\n\n :ivar extra_info: dict of generic param -> value to display in case\n there's an error processing the command line arguments.\n \"\"\"\n\n prog = None\n\n def __init__(self, usage=None, processopt=None):\n self._anonymous = OptionGroup(\"custom options\", parser=self)\n self._groups = []\n self._processopt = processopt\n self._usage = usage\n self._inidict = {}\n self._ininames = []\n self.extra_info = {}\n\n def processoption(self, option):\n if self._processopt:\n if option.dest:\n self._processopt(option)\n\n def getgroup(self, name, description=\"\", after=None):\n \"\"\" get (or create) a named option Group.\n\n :name: name of the option group.\n :description: long description for --help output.\n :after: name of other group, used for ordering --help output.\n\n The returned group object has an ``addoption`` method with the same\n signature as :py:func:`parser.addoption\n <_pytest.config.Parser.addoption>` but will be shown in the\n respective group in the output of ``pytest. --help``.\n \"\"\"\n for group in self._groups:\n if group.name == name:\n return group\n group = OptionGroup(name, description, parser=self)\n i = 0\n for i, grp in enumerate(self._groups):\n if grp.name == after:\n break\n self._groups.insert(i + 1, group)\n return group\n\n def addoption(self, *opts, **attrs):\n \"\"\" register a command line option.\n\n :opts: option names, can be short or long options.\n :attrs: same attributes which the ``add_option()`` function of the\n `argparse library\n `_\n accepts.\n\n After command line parsing options are available on the pytest config\n object via ``config.option.NAME`` where ``NAME`` is usually set\n by passing a ``dest`` attribute, for example\n ``addoption(\"--long\", dest=\"NAME\", ...)``.\n \"\"\"\n self._anonymous.addoption(*opts, **attrs)\n\n def parse(self, args, namespace=None):\n from _pytest._argcomplete import try_argcomplete\n\n self.optparser = self._getparser()\n try_argcomplete(self.optparser)\n args = [str(x) if isinstance(x, py.path.local) else x for x in args]\n return self.optparser.parse_args(args, namespace=namespace)\n\n def _getparser(self):\n from _pytest._argcomplete import filescompleter\n\n optparser = MyOptionParser(self, self.extra_info, prog=self.prog)\n groups = self._groups + [self._anonymous]\n for group in groups:\n if group.options:\n desc = group.description or group.name\n arggroup = optparser.add_argument_group(desc)\n for option in group.options:\n n = option.names()\n a = option.attrs()\n arggroup.add_argument(*n, **a)\n # bash like autocompletion for dirs (appending '/')\n optparser.add_argument(FILE_OR_DIR, nargs=\"*\").completer = filescompleter\n return optparser\n\n def parse_setoption(self, args, option, namespace=None):\n parsedoption = self.parse(args, namespace=namespace)\n for name, value in parsedoption.__dict__.items():\n setattr(option, name, value)\n return getattr(parsedoption, FILE_OR_DIR)\n\n def parse_known_args(self, args, namespace=None):\n \"\"\"parses and returns a namespace object with known arguments at this\n point.\n \"\"\"\n return self.parse_known_and_unknown_args(args, namespace=namespace)[0]\n\n def parse_known_and_unknown_args(self, args, namespace=None):\n \"\"\"parses and returns a namespace object with known arguments, and\n the remaining arguments unknown at this point.\n \"\"\"\n optparser = self._getparser()\n args = [str(x) if isinstance(x, py.path.local) else x for x in args]\n return optparser.parse_known_args(args, namespace=namespace)\n\n def addini(self, name, help, type=None, default=None):\n \"\"\" register an ini-file option.\n\n :name: name of the ini-variable\n :type: type of the variable, can be ``pathlist``, ``args``, ``linelist``\n or ``bool``.\n :default: default value if no ini-file option exists but is queried.\n\n The value of ini-variables can be retrieved via a call to\n :py:func:`config.getini(name) <_pytest.config.Config.getini>`.\n \"\"\"\n assert type in (None, \"pathlist\", \"args\", \"linelist\", \"bool\")\n self._inidict[name] = (help, type, default)\n self._ininames.append(name)"},{"col":4,"comment":"null","endLoc":34,"header":"def processoption(self, option)","id":5464,"name":"processoption","nodeType":"Function","startLoc":31,"text":"def processoption(self, option):\n if self._processopt:\n if option.dest:\n self._processopt(option)"},{"col":4,"comment":"null","endLoc":969,"header":"def test_override_ini_pathlist(self, testdir)","id":5465,"name":"test_override_ini_pathlist","nodeType":"Function","startLoc":946,"text":"def test_override_ini_pathlist(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n parser.addini(\"paths\", \"my new ini value\", type=\"pathlist\")\"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n paths=blah.py\"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import py.path\n def test_pathlist(pytestconfig):\n config_paths = pytestconfig.getini(\"paths\")\n print(config_paths)\n for cpf in config_paths:\n print('\\\\nuser_path:%s' % cpf.basename)\"\"\"\n )\n result = testdir.runpytest(\n \"--override-ini\", \"paths=foo/bar1.py foo/bar2.py\", \"-s\"\n )\n result.stdout.fnmatch_lines([\"user_path:bar1.py\", \"user_path:bar2.py\"])"},{"col":4,"comment":"null","endLoc":1015,"header":"def test_override_multiple_and_default(self, testdir)","id":5466,"name":"test_override_multiple_and_default","nodeType":"Function","startLoc":971,"text":"def test_override_multiple_and_default(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_addoption(parser):\n addini = parser.addini\n addini(\"custom_option_1\", \"\", default=\"o1\")\n addini(\"custom_option_2\", \"\", default=\"o2\")\n addini(\"custom_option_3\", \"\", default=False, type=\"bool\")\n addini(\"custom_option_4\", \"\", default=True, type=\"bool\")\"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n custom_option_1=custom_option_1\n custom_option_2=custom_option_2\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_multiple_options(pytestconfig):\n prefix = \"custom_option\"\n for x in range(1, 5):\n ini_value=pytestconfig.getini(\"%s_%d\" % (prefix, x))\n print('\\\\nini%d:%s' % (x, ini_value))\n \"\"\"\n )\n result = testdir.runpytest(\n \"--override-ini\",\n \"custom_option_1=fulldir=/tmp/user1\",\n \"-o\",\n \"custom_option_2=url=/tmp/user2?a=b&d=e\",\n \"-o\",\n \"custom_option_3=True\",\n \"-o\",\n \"custom_option_4=no\",\n \"-s\",\n )\n result.stdout.fnmatch_lines(\n [\n \"ini1:fulldir=/tmp/user1\",\n \"ini2:url=/tmp/user2?a=b&d=e\",\n \"ini3:True\",\n \"ini4:False\",\n ]\n )"},{"col":4,"comment":"null","endLoc":1025,"header":"def test_override_ini_usage_error_bad_style(self, testdir)","id":5467,"name":"test_override_ini_usage_error_bad_style","nodeType":"Function","startLoc":1017,"text":"def test_override_ini_usage_error_bad_style(self, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n xdist_strict=False\n \"\"\"\n )\n result = testdir.runpytest(\"--override-ini\", \"xdist_strict True\", \"-s\")\n result.stderr.fnmatch_lines([\"*ERROR* *expects option=value*\"])"},{"col":4,"comment":"-o should be handled as soon as possible and always override what's in ini files (#2238)","endLoc":1044,"header":"@pytest.mark.parametrize(\"with_ini\", [True, False])\n def test_override_ini_handled_asap(self, testdir, with_ini)","id":5468,"name":"test_override_ini_handled_asap","nodeType":"Function","startLoc":1027,"text":"@pytest.mark.parametrize(\"with_ini\", [True, False])\n def test_override_ini_handled_asap(self, testdir, with_ini):\n \"\"\"-o should be handled as soon as possible and always override what's in ini files (#2238)\"\"\"\n if with_ini:\n testdir.makeini(\n \"\"\"\n [pytest]\n python_files=test_*.py\n \"\"\"\n )\n testdir.makepyfile(\n unittest_ini_handle=\"\"\"\n def test():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--override-ini\", \"python_files=unittest_*.py\")\n result.stdout.fnmatch_lines([\"*1 passed in*\"])"},{"col":4,"comment":"Show a user-friendly traceback on conftest import failures (#486, #3332)","endLoc":229,"header":"@pytest.mark.filterwarnings(\"default\")\n def test_better_reporting_on_conftest_load_failure(self, testdir, request)","id":5469,"name":"test_better_reporting_on_conftest_load_failure","nodeType":"Function","startLoc":193,"text":"@pytest.mark.filterwarnings(\"default\")\n def test_better_reporting_on_conftest_load_failure(self, testdir, request):\n \"\"\"Show a user-friendly traceback on conftest import failures (#486, #3332)\"\"\"\n testdir.makepyfile(\"\")\n testdir.makeconftest(\n \"\"\"\n def foo():\n import qwerty\n foo()\n \"\"\"\n )\n result = testdir.runpytest(\"--help\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *--version*\n *warning*conftest.py*\n \"\"\"\n )\n result = testdir.runpytest()\n dirname = request.node.name + \"0\"\n exc_name = (\n \"ModuleNotFoundError\" if sys.version_info >= (3, 6) else \"ImportError\"\n )\n result.stderr.fnmatch_lines(\n [\n \"ImportError while loading conftest '*{sep}{dirname}{sep}conftest.py'.\".format(\n dirname=dirname, sep=os.sep\n ),\n \"conftest.py:3: in \",\n \" foo()\",\n \"conftest.py:2: in foo\",\n \" import qwerty\",\n \"E {}: No module named {q}qwerty{q}\".format(\n exc_name, q=\"\" if six.PY2 else \"'\"\n ),\n ]\n )"},{"col":4,"comment":"null","endLoc":1052,"header":"def test_with_arg_outside_cwd_without_inifile(self, tmpdir, monkeypatch)","id":5470,"name":"test_with_arg_outside_cwd_without_inifile","nodeType":"Function","startLoc":1046,"text":"def test_with_arg_outside_cwd_without_inifile(self, tmpdir, monkeypatch):\n monkeypatch.chdir(str(tmpdir))\n a = tmpdir.mkdir(\"a\")\n b = tmpdir.mkdir(\"b\")\n rootdir, inifile, inicfg = determine_setup(None, [a, b])\n assert rootdir == tmpdir\n assert inifile is None"},{"col":4,"comment":"null","endLoc":124,"header":"def test_writeline(self, testdir, linecomp)","id":5471,"name":"test_writeline","nodeType":"Function","startLoc":116,"text":"def test_writeline(self, testdir, linecomp):\n modcol = testdir.getmodulecol(\"def test_one(): pass\")\n rep = TerminalReporter(modcol.config, file=linecomp.stringio)\n rep.write_fspath_result(modcol.nodeid, \".\")\n rep.write_line(\"hello world\")\n lines = linecomp.stringio.getvalue().split(\"\\n\")\n assert not lines[0]\n assert lines[1].endswith(modcol.name + \" .\")\n assert lines[2] == \"hello world\""},{"col":4,"comment":"null","endLoc":134,"header":"def test_show_runtest_logstart(self, testdir, linecomp)","id":5472,"name":"test_show_runtest_logstart","nodeType":"Function","startLoc":126,"text":"def test_show_runtest_logstart(self, testdir, linecomp):\n item = testdir.getitem(\"def test_func(): pass\")\n tr = TerminalReporter(item.config, file=linecomp.stringio)\n item.config.pluginmanager.register(tr)\n location = item.reportinfo()\n tr.config.hook.pytest_runtest_logstart(\n nodeid=item.nodeid, location=location, fspath=str(item.fspath)\n )\n linecomp.assert_contains_lines([\"*test_show_runtest_logstart.py*\"])"},{"fileName":"source.py","filePath":"src/_pytest/_code","id":5473,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport ast\nimport inspect\nimport linecache\nimport sys\nimport textwrap\nimport tokenize\nimport warnings\nfrom ast import PyCF_ONLY_AST as _AST_FLAG\nfrom bisect import bisect_right\n\nimport py\nimport six\n\n\nclass Source(object):\n \"\"\" an immutable object holding a source code fragment,\n possibly deindenting it.\n \"\"\"\n\n _compilecounter = 0\n\n def __init__(self, *parts, **kwargs):\n self.lines = lines = []\n de = kwargs.get(\"deindent\", True)\n for part in parts:\n if not part:\n partlines = []\n elif isinstance(part, Source):\n partlines = part.lines\n elif isinstance(part, (tuple, list)):\n partlines = [x.rstrip(\"\\n\") for x in part]\n elif isinstance(part, six.string_types):\n partlines = part.split(\"\\n\")\n else:\n partlines = getsource(part, deindent=de).lines\n if de:\n partlines = deindent(partlines)\n lines.extend(partlines)\n\n def __eq__(self, other):\n try:\n return self.lines == other.lines\n except AttributeError:\n if isinstance(other, str):\n return str(self) == other\n return False\n\n __hash__ = None\n\n def __getitem__(self, key):\n if isinstance(key, int):\n return self.lines[key]\n else:\n if key.step not in (None, 1):\n raise IndexError(\"cannot slice a Source with a step\")\n newsource = Source()\n newsource.lines = self.lines[key.start : key.stop]\n return newsource\n\n def __len__(self):\n return len(self.lines)\n\n def strip(self):\n \"\"\" return new source object with trailing\n and leading blank lines removed.\n \"\"\"\n start, end = 0, len(self)\n while start < end and not self.lines[start].strip():\n start += 1\n while end > start and not self.lines[end - 1].strip():\n end -= 1\n source = Source()\n source.lines[:] = self.lines[start:end]\n return source\n\n def putaround(self, before=\"\", after=\"\", indent=\" \" * 4):\n \"\"\" return a copy of the source object with\n 'before' and 'after' wrapped around it.\n \"\"\"\n before = Source(before)\n after = Source(after)\n newsource = Source()\n lines = [(indent + line) for line in self.lines]\n newsource.lines = before.lines + lines + after.lines\n return newsource\n\n def indent(self, indent=\" \" * 4):\n \"\"\" return a copy of the source object with\n all lines indented by the given indent-string.\n \"\"\"\n newsource = Source()\n newsource.lines = [(indent + line) for line in self.lines]\n return newsource\n\n def getstatement(self, lineno):\n \"\"\" return Source statement which contains the\n given linenumber (counted from 0).\n \"\"\"\n start, end = self.getstatementrange(lineno)\n return self[start:end]\n\n def getstatementrange(self, lineno):\n \"\"\" return (start, end) tuple which spans the minimal\n statement region which containing the given lineno.\n \"\"\"\n if not (0 <= lineno < len(self)):\n raise IndexError(\"lineno out of range\")\n ast, start, end = getstatementrange_ast(lineno, self)\n return start, end\n\n def deindent(self):\n \"\"\"return a new source object deindented.\"\"\"\n newsource = Source()\n newsource.lines[:] = deindent(self.lines)\n return newsource\n\n def isparseable(self, deindent=True):\n \"\"\" return True if source is parseable, heuristically\n deindenting it by default.\n \"\"\"\n from parser import suite as syntax_checker\n\n if deindent:\n source = str(self.deindent())\n else:\n source = str(self)\n try:\n # compile(source+'\\n', \"x\", \"exec\")\n syntax_checker(source + \"\\n\")\n except KeyboardInterrupt:\n raise\n except Exception:\n return False\n else:\n return True\n\n def __str__(self):\n return \"\\n\".join(self.lines)\n\n def compile(\n self, filename=None, mode=\"exec\", flag=0, dont_inherit=0, _genframe=None\n ):\n \"\"\" return compiled code object. if filename is None\n invent an artificial filename which displays\n the source/line position of the caller frame.\n \"\"\"\n if not filename or py.path.local(filename).check(file=0):\n if _genframe is None:\n _genframe = sys._getframe(1) # the caller\n fn, lineno = _genframe.f_code.co_filename, _genframe.f_lineno\n base = \"<%d-codegen \" % self._compilecounter\n self.__class__._compilecounter += 1\n if not filename:\n filename = base + \"%s:%d>\" % (fn, lineno)\n else:\n filename = base + \"%r %s:%d>\" % (filename, fn, lineno)\n source = \"\\n\".join(self.lines) + \"\\n\"\n try:\n co = compile(source, filename, mode, flag)\n except SyntaxError:\n ex = sys.exc_info()[1]\n # re-represent syntax errors from parsing python strings\n msglines = self.lines[: ex.lineno]\n if ex.offset:\n msglines.append(\" \" * ex.offset + \"^\")\n msglines.append(\"(code was compiled probably from here: %s)\" % filename)\n newex = SyntaxError(\"\\n\".join(msglines))\n newex.offset = ex.offset\n newex.lineno = ex.lineno\n newex.text = ex.text\n raise newex\n else:\n if flag & _AST_FLAG:\n return co\n lines = [(x + \"\\n\") for x in self.lines]\n linecache.cache[filename] = (1, None, lines, filename)\n return co\n\n\n#\n# public API shortcut functions\n#\n\n\ndef compile_(source, filename=None, mode=\"exec\", flags=0, dont_inherit=0):\n \"\"\" compile the given source to a raw code object,\n and maintain an internal cache which allows later\n retrieval of the source code for the code object\n and any recursively created code objects.\n \"\"\"\n if isinstance(source, ast.AST):\n # XXX should Source support having AST?\n return compile(source, filename, mode, flags, dont_inherit)\n _genframe = sys._getframe(1) # the caller\n s = Source(source)\n co = s.compile(filename, mode, flags, _genframe=_genframe)\n return co\n\n\ndef getfslineno(obj):\n \"\"\" Return source location (path, lineno) for the given object.\n If the source cannot be determined return (\"\", -1).\n\n The line number is 0-based.\n \"\"\"\n from .code import Code\n\n try:\n code = Code(obj)\n except TypeError:\n try:\n fn = inspect.getsourcefile(obj) or inspect.getfile(obj)\n except TypeError:\n return \"\", -1\n\n fspath = fn and py.path.local(fn) or None\n lineno = -1\n if fspath:\n try:\n _, lineno = findsource(obj)\n except IOError:\n pass\n else:\n fspath = code.path\n lineno = code.firstlineno\n assert isinstance(lineno, int)\n return fspath, lineno\n\n\n#\n# helper functions\n#\n\n\ndef findsource(obj):\n try:\n sourcelines, lineno = inspect.findsource(obj)\n except Exception:\n return None, -1\n source = Source()\n source.lines = [line.rstrip() for line in sourcelines]\n return source, lineno\n\n\ndef getsource(obj, **kwargs):\n from .code import getrawcode\n\n obj = getrawcode(obj)\n try:\n strsrc = inspect.getsource(obj)\n except IndentationError:\n strsrc = '\"Buggy python version consider upgrading, cannot get source\"'\n assert isinstance(strsrc, str)\n return Source(strsrc, **kwargs)\n\n\ndef deindent(lines):\n return textwrap.dedent(\"\\n\".join(lines)).splitlines()\n\n\ndef get_statement_startend2(lineno, node):\n import ast\n\n # flatten all statements and except handlers into one lineno-list\n # AST's line numbers start indexing at 1\n values = []\n for x in ast.walk(node):\n if isinstance(x, (ast.stmt, ast.ExceptHandler)):\n values.append(x.lineno - 1)\n for name in (\"finalbody\", \"orelse\"):\n val = getattr(x, name, None)\n if val:\n # treat the finally/orelse part as its own statement\n values.append(val[0].lineno - 1 - 1)\n values.sort()\n insert_index = bisect_right(values, lineno)\n start = values[insert_index - 1]\n if insert_index >= len(values):\n end = None\n else:\n end = values[insert_index]\n return start, end\n\n\ndef getstatementrange_ast(lineno, source, assertion=False, astnode=None):\n if astnode is None:\n content = str(source)\n # See #4260:\n # don't produce duplicate warnings when compiling source to find ast\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n astnode = compile(content, \"source\", \"exec\", _AST_FLAG)\n\n start, end = get_statement_startend2(lineno, astnode)\n # we need to correct the end:\n # - ast-parsing strips comments\n # - there might be empty lines\n # - we might have lesser indented code blocks at the end\n if end is None:\n end = len(source.lines)\n\n if end > start + 1:\n # make sure we don't span differently indented code blocks\n # by using the BlockFinder helper used which inspect.getsource() uses itself\n block_finder = inspect.BlockFinder()\n # if we start with an indented line, put blockfinder to \"started\" mode\n block_finder.started = source.lines[start][0].isspace()\n it = ((x + \"\\n\") for x in source.lines[start:end])\n try:\n for tok in tokenize.generate_tokens(lambda: next(it)):\n block_finder.tokeneater(*tok)\n except (inspect.EndOfBlock, IndentationError):\n end = block_finder.last + start\n except Exception:\n pass\n\n # the end might still point to a comment or empty line, correct it\n while end:\n line = source.lines[end - 1].lstrip()\n if line.startswith(\"#\") or not line:\n end -= 1\n else:\n break\n return astnode, start, end\n"},{"col":4,"comment":"null","endLoc":692,"header":"def pytest_keyboard_interrupt(self, excinfo)","id":5477,"name":"pytest_keyboard_interrupt","nodeType":"Function","startLoc":691,"text":"def pytest_keyboard_interrupt(self, excinfo):\n self._keyboardinterrupt_memo = excinfo.getrepr(funcargs=True)"},{"col":4,"comment":"null","endLoc":696,"header":"def pytest_unconfigure(self)","id":5478,"name":"pytest_unconfigure","nodeType":"Function","startLoc":694,"text":"def pytest_unconfigure(self):\n if hasattr(self, \"_keyboardinterrupt_memo\"):\n self._report_keyboardinterrupt()"},{"col":4,"comment":"null","endLoc":242,"header":"def test_early_skip(self, testdir)","id":5479,"name":"test_early_skip","nodeType":"Function","startLoc":231,"text":"def test_early_skip(self, testdir):\n testdir.mkdir(\"xyz\")\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_collect_directory():\n pytest.skip(\"early\")\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result.stdout.fnmatch_lines([\"*1 skip*\"])"},{"col":4,"comment":" get (or create) a named option Group.\n\n :name: name of the option group.\n :description: long description for --help output.\n :after: name of other group, used for ordering --help output.\n\n The returned group object has an ``addoption`` method with the same\n signature as :py:func:`parser.addoption\n <_pytest.config.Parser.addoption>` but will be shown in the\n respective group in the output of ``pytest. --help``.\n ","endLoc":57,"header":"def getgroup(self, name, description=\"\", after=None)","id":5480,"name":"getgroup","nodeType":"Function","startLoc":36,"text":"def getgroup(self, name, description=\"\", after=None):\n \"\"\" get (or create) a named option Group.\n\n :name: name of the option group.\n :description: long description for --help output.\n :after: name of other group, used for ordering --help output.\n\n The returned group object has an ``addoption`` method with the same\n signature as :py:func:`parser.addoption\n <_pytest.config.Parser.addoption>` but will be shown in the\n respective group in the output of ``pytest. --help``.\n \"\"\"\n for group in self._groups:\n if group.name == name:\n return group\n group = OptionGroup(name, description, parser=self)\n i = 0\n for i, grp in enumerate(self._groups):\n if grp.name == after:\n break\n self._groups.insert(i + 1, group)\n return group"},{"attributeType":"Literal[1024]","col":0,"comment":"null","endLoc":6,"id":5481,"name":"PyCF_ONLY_AST","nodeType":"Attribute","startLoc":6,"text":"PyCF_ONLY_AST"},{"attributeType":"int","col":8,"comment":"null","endLoc":233,"id":5482,"name":"_numcollected","nodeType":"Attribute","startLoc":233,"text":"self._numcollected"},{"attributeType":"null","col":8,"comment":"null","endLoc":244,"id":5483,"name":"_screen_width","nodeType":"Attribute","startLoc":244,"text":"self._screen_width"},{"attributeType":"null","col":8,"comment":"null","endLoc":241,"id":5484,"name":"_tw","nodeType":"Attribute","startLoc":241,"text":"self._tw"},{"attributeType":"None","col":8,"comment":"null","endLoc":235,"id":5485,"name":"_showfspath","nodeType":"Attribute","startLoc":235,"text":"self._showfspath"},{"attributeType":"bool","col":8,"comment":"null","endLoc":250,"id":5486,"name":"_show_progress_info","nodeType":"Attribute","startLoc":250,"text":"self._show_progress_info"},{"attributeType":"str","col":8,"comment":"null","endLoc":246,"id":5487,"name":"reportchars","nodeType":"Attribute","startLoc":246,"text":"self.reportchars"},{"col":4,"comment":"null","endLoc":271,"header":"def __str__(self)","id":5488,"name":"__str__","nodeType":"Function","startLoc":259,"text":"def __str__(self):\n try:\n fn = str(self.path)\n except py.error.Error:\n fn = \"???\"\n name = self.frame.code.name\n try:\n line = str(self.statement).lstrip()\n except KeyboardInterrupt:\n raise\n except: # noqa\n line = \"???\"\n return \" File %r:%d in %s\\n %s\\n\" % (fn, self.lineno + 1, name, line)"},{"attributeType":"null","col":8,"comment":"null","endLoc":692,"id":5489,"name":"_keyboardinterrupt_memo","nodeType":"Attribute","startLoc":692,"text":"self._keyboardinterrupt_memo"},{"attributeType":"int","col":12,"comment":"null","endLoc":770,"id":5490,"name":"_already_displayed_warnings","nodeType":"Attribute","startLoc":770,"text":"self._already_displayed_warnings"},{"col":0,"comment":"null","endLoc":944,"header":"def test_dupfile_on_bytesio()","id":5491,"name":"test_dupfile_on_bytesio","nodeType":"Function","startLoc":939,"text":"def test_dupfile_on_bytesio():\n bio = io.BytesIO()\n f = capture.safe_text_dupfile(bio, \"wb\")\n f.write(\"hello\")\n assert bio.getvalue() == b\"hello\"\n assert \"BytesIO object\" in f.name"},{"attributeType":"bool","col":8,"comment":"null","endLoc":248,"id":5492,"name":"isatty","nodeType":"Attribute","startLoc":248,"text":"self.isatty"},{"attributeType":"set","col":8,"comment":"null","endLoc":249,"id":5493,"name":"_progress_nodeids_reported","nodeType":"Attribute","startLoc":249,"text":"self._progress_nodeids_reported"},{"attributeType":"float","col":8,"comment":"null","endLoc":559,"id":5494,"name":"_sessionstarttime","nodeType":"Attribute","startLoc":559,"text":"self._sessionstarttime"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":237,"id":5495,"name":"stats","nodeType":"Attribute","startLoc":237,"text":"self.stats"},{"attributeType":"None","col":8,"comment":"null","endLoc":234,"id":5496,"name":"_session","nodeType":"Attribute","startLoc":234,"text":"self._session"},{"attributeType":"null","col":8,"comment":"null","endLoc":238,"id":5497,"name":"startdir","nodeType":"Attribute","startLoc":238,"text":"self.startdir"},{"attributeType":"None","col":8,"comment":"null","endLoc":245,"id":5498,"name":"currentfspath","nodeType":"Attribute","startLoc":245,"text":"self.currentfspath"},{"attributeType":"bool","col":8,"comment":"null","endLoc":397,"id":5499,"name":"_tests_ran","nodeType":"Attribute","startLoc":397,"text":"self._tests_ran"},{"col":4,"comment":"null","endLoc":248,"header":"def test_issue88_initial_file_multinodes(self, testdir)","id":5500,"name":"test_issue88_initial_file_multinodes","nodeType":"Function","startLoc":244,"text":"def test_issue88_initial_file_multinodes(self, testdir):\n testdir.copy_example(\"issue88_initial_file_multinodes\")\n p = testdir.makepyfile(\"def test_hello(): pass\")\n result = testdir.runpytest(p, \"--collect-only\")\n result.stdout.fnmatch_lines([\"*MyFile*test_issue88*\", \"*Module*test_issue88*\"])"},{"attributeType":"null","col":8,"comment":"null","endLoc":247,"id":5501,"name":"hasmarkup","nodeType":"Attribute","startLoc":247,"text":"self.hasmarkup"},{"col":0,"comment":"null","endLoc":952,"header":"def test_dupfile_on_textio()","id":5502,"name":"test_dupfile_on_textio","nodeType":"Function","startLoc":947,"text":"def test_dupfile_on_textio():\n tio = py.io.TextIO()\n f = capture.safe_text_dupfile(tio, \"wb\")\n f.write(\"hello\")\n assert tio.getvalue() == \"hello\"\n assert not hasattr(f, \"name\")"},{"attributeType":"null","col":8,"comment":"null","endLoc":243,"id":5503,"name":"writer","nodeType":"Attribute","startLoc":243,"text":"self.writer"},{"col":0,"comment":"null","endLoc":967,"header":"@contextlib.contextmanager\ndef lsof_check()","id":5504,"name":"lsof_check","nodeType":"Function","startLoc":955,"text":"@contextlib.contextmanager\ndef lsof_check():\n pid = os.getpid()\n try:\n out = subprocess.check_output((\"lsof\", \"-p\", str(pid))).decode()\n except (OSError, subprocess.CalledProcessError, UnicodeDecodeError):\n # about UnicodeDecodeError, see note on pytester\n pytest.skip(\"could not run 'lsof'\")\n yield\n out2 = subprocess.check_output((\"lsof\", \"-p\", str(pid))).decode()\n len1 = len([x for x in out.split(\"\\n\") if \"REG\" in x])\n len2 = len([x for x in out2.split(\"\\n\") if \"REG\" in x])\n assert len2 < len1 + 3, out2"},{"attributeType":"{invocation_dir, option}","col":8,"comment":"null","endLoc":232,"id":5505,"name":"config","nodeType":"Attribute","startLoc":232,"text":"self.config"},{"attributeType":"None","col":8,"comment":"null","endLoc":251,"id":5506,"name":"_collect_report_last_write","nodeType":"Attribute","startLoc":251,"text":"self._collect_report_last_write"},{"col":0,"comment":"null","endLoc":147,"header":"def pytest_addoption(parser)","id":5507,"name":"pytest_addoption","nodeType":"Function","startLoc":59,"text":"def pytest_addoption(parser):\n group = parser.getgroup(\"terminal reporting\", \"reporting\", after=\"general\")\n group._addoption(\n \"-v\",\n \"--verbose\",\n action=\"count\",\n default=0,\n dest=\"verbose\",\n help=\"increase verbosity.\",\n ),\n group._addoption(\n \"-q\",\n \"--quiet\",\n action=MoreQuietAction,\n default=0,\n dest=\"verbose\",\n help=\"decrease verbosity.\",\n ),\n group._addoption(\n \"--verbosity\", dest=\"verbose\", type=int, default=0, help=\"set verbosity\"\n )\n group._addoption(\n \"-r\",\n action=\"store\",\n dest=\"reportchars\",\n default=\"\",\n metavar=\"chars\",\n help=\"show extra test summary info as specified by chars: (f)ailed, \"\n \"(E)rror, (s)kipped, (x)failed, (X)passed, \"\n \"(p)assed, (P)assed with output, (a)ll except passed (p/P), or (A)ll. \"\n \"Warnings are displayed at all times except when \"\n \"--disable-warnings is set.\",\n )\n group._addoption(\n \"--disable-warnings\",\n \"--disable-pytest-warnings\",\n default=False,\n dest=\"disable_warnings\",\n action=\"store_true\",\n help=\"disable warnings summary\",\n )\n group._addoption(\n \"-l\",\n \"--showlocals\",\n action=\"store_true\",\n dest=\"showlocals\",\n default=False,\n help=\"show locals in tracebacks (disabled by default).\",\n )\n group._addoption(\n \"--tb\",\n metavar=\"style\",\n action=\"store\",\n dest=\"tbstyle\",\n default=\"auto\",\n choices=[\"auto\", \"long\", \"short\", \"no\", \"line\", \"native\"],\n help=\"traceback print mode (auto/long/short/line/native/no).\",\n )\n group._addoption(\n \"--show-capture\",\n action=\"store\",\n dest=\"showcapture\",\n choices=[\"no\", \"stdout\", \"stderr\", \"log\", \"all\"],\n default=\"all\",\n help=\"Controls how captured stdout/stderr/log is shown on failed tests. \"\n \"Default is 'all'.\",\n )\n group._addoption(\n \"--fulltrace\",\n \"--full-trace\",\n action=\"store_true\",\n default=False,\n help=\"don't cut any tracebacks (default is to cut).\",\n )\n group._addoption(\n \"--color\",\n metavar=\"color\",\n action=\"store\",\n dest=\"color\",\n default=\"auto\",\n choices=[\"yes\", \"no\", \"auto\"],\n help=\"color terminal output (yes/no/auto).\",\n )\n\n parser.addini(\n \"console_output_style\",\n help='console output: \"classic\", or with additional progress information (\"progress\" (percentage) | \"count\").',\n default=\"progress\",\n )"},{"col":4,"comment":"null","endLoc":261,"header":"def test_issue93_initialnode_importing_capturing(self, testdir)","id":5508,"name":"test_issue93_initialnode_importing_capturing","nodeType":"Function","startLoc":250,"text":"def test_issue93_initialnode_importing_capturing(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import sys\n print(\"should not be seen\")\n sys.stderr.write(\"stder42\\\\n\")\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n assert \"should not be seen\" not in result.stdout.str()\n assert \"stderr42\" not in result.stderr.str()"},{"col":0,"comment":"null","endLoc":1065,"header":"@contextlib.contextmanager\ndef saved_fd(fd)","id":5509,"name":"saved_fd","nodeType":"Function","startLoc":1058,"text":"@contextlib.contextmanager\ndef saved_fd(fd):\n new_fd = os.dup(fd)\n try:\n yield\n finally:\n os.dup2(new_fd, fd)\n os.close(new_fd)"},{"col":0,"comment":"null","endLoc":1277,"header":"def test_capture_not_started_but_reset()","id":5510,"name":"test_capture_not_started_but_reset","nodeType":"Function","startLoc":1275,"text":"def test_capture_not_started_but_reset():\n capsys = StdCapture()\n capsys.stop_capturing()"},{"col":4,"comment":"null","endLoc":1060,"header":"def test_with_arg_outside_cwd_with_inifile(self, tmpdir)","id":5511,"name":"test_with_arg_outside_cwd_with_inifile","nodeType":"Function","startLoc":1054,"text":"def test_with_arg_outside_cwd_with_inifile(self, tmpdir):\n a = tmpdir.mkdir(\"a\")\n b = tmpdir.mkdir(\"b\")\n inifile = a.ensure(\"pytest.ini\")\n rootdir, parsed_inifile, inicfg = determine_setup(None, [a, b])\n assert rootdir == a\n assert inifile == parsed_inifile"},{"col":0,"comment":"null","endLoc":1286,"header":"def test_using_capsys_fixture_works_with_sys_stdout_encoding(capsys)","id":5512,"name":"test_using_capsys_fixture_works_with_sys_stdout_encoding","nodeType":"Function","startLoc":1280,"text":"def test_using_capsys_fixture_works_with_sys_stdout_encoding(capsys):\n test_text = \"test text\"\n\n print(test_text.encode(sys.stdout.encoding, \"replace\"))\n (out, err) = capsys.readouterr()\n assert out\n assert err == \"\""},{"col":0,"comment":"null","endLoc":159,"header":"def pytest_configure(config)","id":5513,"name":"pytest_configure","nodeType":"Function","startLoc":150,"text":"def pytest_configure(config):\n reporter = TerminalReporter(config, sys.stdout)\n config.pluginmanager.register(reporter, \"terminalreporter\")\n if config.option.debug or config.option.traceconfig:\n\n def mywriter(tags, args):\n msg = \" \".join(map(str, args))\n reporter.write_line(\"[traceconfig] \" + msg)\n\n config.trace.root.setprocessor(\"pytest:config\", mywriter)"},{"col":4,"comment":"null","endLoc":1067,"header":"@pytest.mark.parametrize(\"dirs\", ([], [\"does-not-exist\"], [\"a/does-not-exist\"]))\n def test_with_non_dir_arg(self, dirs, tmpdir)","id":5514,"name":"test_with_non_dir_arg","nodeType":"Function","startLoc":1062,"text":"@pytest.mark.parametrize(\"dirs\", ([], [\"does-not-exist\"], [\"a/does-not-exist\"]))\n def test_with_non_dir_arg(self, dirs, tmpdir):\n with tmpdir.ensure(dir=True).as_cwd():\n rootdir, inifile, inicfg = determine_setup(None, dirs)\n assert rootdir == tmpdir\n assert inifile is None"},{"col":4,"comment":"null","endLoc":272,"header":"def test_conftest_printing_shows_if_error(self, testdir)","id":5515,"name":"test_conftest_printing_shows_if_error","nodeType":"Function","startLoc":263,"text":"def test_conftest_printing_shows_if_error(self, testdir):\n testdir.makeconftest(\n \"\"\"\n print(\"should be seen\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret != 0\n assert \"should be seen\" in result.stdout.str()"},{"col":4,"comment":"null","endLoc":1075,"header":"def test_with_existing_file_in_subdir(self, tmpdir)","id":5516,"name":"test_with_existing_file_in_subdir","nodeType":"Function","startLoc":1069,"text":"def test_with_existing_file_in_subdir(self, tmpdir):\n a = tmpdir.mkdir(\"a\")\n a.ensure(\"exist\")\n with tmpdir.as_cwd():\n rootdir, inifile, inicfg = determine_setup(None, [\"a/exist\"])\n assert rootdir == tmpdir\n assert inifile is None"},{"col":4,"comment":"null","endLoc":1082,"header":"def test_addopts_before_initini(self, monkeypatch, _config_for_test, _sys_snapshot)","id":5517,"name":"test_addopts_before_initini","nodeType":"Function","startLoc":1077,"text":"def test_addopts_before_initini(self, monkeypatch, _config_for_test, _sys_snapshot):\n cache_dir = \".custom_cache\"\n monkeypatch.setenv(\"PYTEST_ADDOPTS\", \"-o cache_dir=%s\" % cache_dir)\n config = _config_for_test\n config._preparse([], addopts=True)\n assert config._override_ini == [\"cache_dir=%s\" % cache_dir]"},{"col":4,"comment":"null","endLoc":295,"header":"@pytest.mark.skipif(\n not hasattr(py.path.local, \"mksymlinkto\"),\n reason=\"symlink not available on this platform\",\n )\n def test_chdir(self, testdir)","id":5518,"name":"test_chdir","nodeType":"Function","startLoc":274,"text":"@pytest.mark.skipif(\n not hasattr(py.path.local, \"mksymlinkto\"),\n reason=\"symlink not available on this platform\",\n )\n def test_chdir(self, testdir):\n testdir.tmpdir.join(\"py\").mksymlinkto(py._pydir)\n p = testdir.tmpdir.join(\"main.py\")\n p.write(\n textwrap.dedent(\n \"\"\"\\\n import sys, os\n sys.path.insert(0, '')\n import py\n print(py.__file__)\n print(py.__path__)\n os.chdir(os.path.dirname(os.getcwd()))\n print(py.log)\n \"\"\"\n )\n )\n result = testdir.runpython(p)\n assert not result.ret"},{"col":4,"comment":"PYTEST_ADDOPTS should not take values from normal args (#4265).","endLoc":1093,"header":"def test_addopts_from_env_not_concatenated(self, monkeypatch, _config_for_test)","id":5519,"name":"test_addopts_from_env_not_concatenated","nodeType":"Function","startLoc":1084,"text":"def test_addopts_from_env_not_concatenated(self, monkeypatch, _config_for_test):\n \"\"\"PYTEST_ADDOPTS should not take values from normal args (#4265).\"\"\"\n monkeypatch.setenv(\"PYTEST_ADDOPTS\", \"-o\")\n config = _config_for_test\n with pytest.raises(UsageError) as excinfo:\n config._preparse([\"cache_dir=ignored\"], addopts=True)\n assert (\n \"error: argument -o/--override-ini: expected one argument (via PYTEST_ADDOPTS)\"\n in excinfo.value.args[0]\n )"},{"col":0,"comment":"null","endLoc":1294,"header":"def test_capsys_results_accessible_by_attribute(capsys)","id":5520,"name":"test_capsys_results_accessible_by_attribute","nodeType":"Function","startLoc":1289,"text":"def test_capsys_results_accessible_by_attribute(capsys):\n sys.stdout.write(\"spam\")\n sys.stderr.write(\"eggs\")\n capture_result = capsys.readouterr()\n assert capture_result.out == \"spam\"\n assert capture_result.err == \"eggs\""},{"col":4,"comment":"addopts from ini should not take values from normal args (#4265).","endLoc":1110,"header":"def test_addopts_from_ini_not_concatenated(self, testdir)","id":5521,"name":"test_addopts_from_ini_not_concatenated","nodeType":"Function","startLoc":1095,"text":"def test_addopts_from_ini_not_concatenated(self, testdir):\n \"\"\"addopts from ini should not take values from normal args (#4265).\"\"\"\n testdir.makeini(\n \"\"\"\n [pytest]\n addopts=-o\n \"\"\"\n )\n result = testdir.runpytest(\"cache_dir=ignored\")\n result.stderr.fnmatch_lines(\n [\n \"%s: error: argument -o/--override-ini: expected one argument (via addopts config)\"\n % (testdir.request.config._parser.optparser.prog,)\n ]\n )\n assert result.ret == _pytest.main.EXIT_USAGEERROR"},{"col":4,"comment":"Check that -o no longer swallows all options after it (#3103)","endLoc":1116,"header":"def test_override_ini_does_not_contain_paths(self, _config_for_test, _sys_snapshot)","id":5522,"name":"test_override_ini_does_not_contain_paths","nodeType":"Function","startLoc":1112,"text":"def test_override_ini_does_not_contain_paths(self, _config_for_test, _sys_snapshot):\n \"\"\"Check that -o no longer swallows all options after it (#3103)\"\"\"\n config = _config_for_test\n config._preparse([\"-o\", \"cache_dir=/cache\", \"/some/test/path\"])\n assert config._override_ini == [\"cache_dir=/cache\"]"},{"col":4,"comment":"Ensure a file path following a '-o' option does not generate an error (#3103)","endLoc":1140,"header":"def test_multiple_override_ini_options(self, testdir, request)","id":5523,"name":"test_multiple_override_ini_options","nodeType":"Function","startLoc":1118,"text":"def test_multiple_override_ini_options(self, testdir, request):\n \"\"\"Ensure a file path following a '-o' option does not generate an error (#3103)\"\"\"\n testdir.makepyfile(\n **{\n \"conftest.py\": \"\"\"\n def pytest_addoption(parser):\n parser.addini('foo', default=None, help='some option')\n parser.addini('bar', default=None, help='some option')\n \"\"\",\n \"test_foo.py\": \"\"\"\n def test(pytestconfig):\n assert pytestconfig.getini('foo') == '1'\n assert pytestconfig.getini('bar') == '0'\n \"\"\",\n \"test_bar.py\": \"\"\"\n def test():\n assert False\n \"\"\",\n }\n )\n result = testdir.runpytest(\"-o\", \"foo=1\", \"-o\", \"bar=0\", \"test_foo.py\")\n assert \"ERROR:\" not in result.stderr.str()\n result.stdout.fnmatch_lines([\"collected 1 item\", \"*= 1 passed in *=\"])"},{"col":0,"comment":"null","endLoc":538,"header":"def test_options_on_small_file_do_not_blow_up(testdir)","id":5524,"name":"test_options_on_small_file_do_not_blow_up","nodeType":"Function","startLoc":512,"text":"def test_options_on_small_file_do_not_blow_up(testdir):\n def runfiletest(opts):\n reprec = testdir.inline_run(*opts)\n passed, skipped, failed = reprec.countoutcomes()\n assert failed == 2\n assert skipped == passed == 0\n\n path = testdir.makepyfile(\n \"\"\"\n def test_f1(): assert 0\n def test_f2(): assert 0\n \"\"\"\n )\n\n for opts in (\n [],\n [\"-l\"],\n [\"-s\"],\n [\"--tb=no\"],\n [\"--tb=short\"],\n [\"--tb=long\"],\n [\"--fulltrace\"],\n [\"--traceconfig\"],\n [\"-v\"],\n [\"-v\", \"-v\"],\n ):\n runfiletest(opts + [path])"},{"col":0,"comment":"null","endLoc":570,"header":"def test_preparse_ordering_with_setuptools(testdir, monkeypatch)","id":5526,"name":"test_preparse_ordering_with_setuptools","nodeType":"Function","startLoc":541,"text":"def test_preparse_ordering_with_setuptools(testdir, monkeypatch):\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n\n class EntryPoint(object):\n name = \"mytestplugin\"\n group = \"pytest11\"\n\n def load(self):\n class PseudoPlugin(object):\n x = 42\n\n return PseudoPlugin()\n\n class Dist(object):\n files = ()\n entry_points = (EntryPoint(),)\n\n def my_dists():\n return (Dist,)\n\n monkeypatch.setattr(importlib_metadata, \"distributions\", my_dists)\n testdir.makeconftest(\n \"\"\"\n pytest_plugins = \"mytestplugin\",\n \"\"\"\n )\n monkeypatch.setenv(\"PYTEST_PLUGINS\", \"mytestplugin\")\n config = testdir.parseconfig()\n plugin = config.pluginmanager.getplugin(\"mytestplugin\")\n assert plugin.x == 42"},{"col":4,"comment":"null","endLoc":147,"header":"def test_runtest_location_shown_before_test_starts(self, testdir)","id":5527,"name":"test_runtest_location_shown_before_test_starts","nodeType":"Function","startLoc":136,"text":"def test_runtest_location_shown_before_test_starts(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_1():\n import time\n time.sleep(20)\n \"\"\"\n )\n child = testdir.spawn_pytest(\"\")\n child.expect(\".*test_runtest_location.*py\")\n child.sendeof()\n child.kill(15)"},{"col":4,"comment":"Test for \"collecting\" being updated after 0.5s","endLoc":172,"header":"def test_report_collect_after_half_a_second(self, testdir)","id":5528,"name":"test_report_collect_after_half_a_second","nodeType":"Function","startLoc":149,"text":"def test_report_collect_after_half_a_second(self, testdir):\n \"\"\"Test for \"collecting\" being updated after 0.5s\"\"\"\n\n testdir.makepyfile(\n **{\n \"test1.py\": \"\"\"\n import _pytest.terminal\n\n _pytest.terminal.REPORT_COLLECTING_RESOLUTION = 0\n\n def test_1():\n pass\n \"\"\",\n \"test2.py\": \"def test_2(): pass\",\n }\n )\n\n child = testdir.spawn_pytest(\"-v test1.py test2.py\")\n child.expect(r\"collecting \\.\\.\\.\")\n child.expect(r\"collecting 1 item\")\n child.expect(r\"collecting 2 items\")\n child.expect(r\"collected 2 items\")\n rest = child.read().decode(\"utf8\")\n assert \"2 passed in\" in rest"},{"col":0,"comment":"null","endLoc":1310,"header":"@needsosdup\n@pytest.mark.parametrize(\"use\", [True, False])\ndef test_fdcapture_tmpfile_remains_the_same(tmpfile, use)","id":5529,"name":"test_fdcapture_tmpfile_remains_the_same","nodeType":"Function","startLoc":1297,"text":"@needsosdup\n@pytest.mark.parametrize(\"use\", [True, False])\ndef test_fdcapture_tmpfile_remains_the_same(tmpfile, use):\n if not use:\n tmpfile = True\n cap = StdCaptureFD(out=False, err=tmpfile)\n try:\n cap.start_capturing()\n capfile = cap.err.tmpfile\n cap.readouterr()\n finally:\n cap.stop_capturing()\n capfile2 = cap.err.tmpfile\n assert capfile2 == capfile"},{"col":4,"comment":"null","endLoc":196,"header":"def test_itemreport_subclasses_show_subclassed_file(self, testdir)","id":5530,"name":"test_itemreport_subclasses_show_subclassed_file","nodeType":"Function","startLoc":174,"text":"def test_itemreport_subclasses_show_subclassed_file(self, testdir):\n testdir.makepyfile(\n test_p1=\"\"\"\n class BaseTests(object):\n def test_p1(self):\n pass\n class TestClass(BaseTests):\n pass\n \"\"\"\n )\n p2 = testdir.makepyfile(\n test_p2=\"\"\"\n from test_p1 import BaseTests\n class TestMore(BaseTests):\n pass\n \"\"\"\n )\n result = testdir.runpytest(p2)\n result.stdout.fnmatch_lines([\"*test_p2.py .*\", \"*1 passed*\"])\n result = testdir.runpytest(\"-vv\", p2)\n result.stdout.fnmatch_lines(\n [\"*test_p2.py::TestMore::test_p1* <- *test_p1.py*PASSED*\"]\n )"},{"col":4,"comment":"null","endLoc":308,"header":"def test_issue109_sibling_conftests_not_loaded(self, testdir)","id":5531,"name":"test_issue109_sibling_conftests_not_loaded","nodeType":"Function","startLoc":297,"text":"def test_issue109_sibling_conftests_not_loaded(self, testdir):\n sub1 = testdir.mkdir(\"sub1\")\n sub2 = testdir.mkdir(\"sub2\")\n sub1.join(\"conftest.py\").write(\"assert 0\")\n result = testdir.runpytest(sub2)\n assert result.ret == EXIT_NOTESTSCOLLECTED\n sub2.ensure(\"__init__.py\")\n p = sub2.ensure(\"test_hello.py\")\n result = testdir.runpytest(p)\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result = testdir.runpytest(sub1)\n assert result.ret == EXIT_USAGEERROR"},{"col":4,"comment":"null","endLoc":212,"header":"def test_itemreport_directclasses_not_shown_as_subclasses(self, testdir)","id":5532,"name":"test_itemreport_directclasses_not_shown_as_subclasses","nodeType":"Function","startLoc":198,"text":"def test_itemreport_directclasses_not_shown_as_subclasses(self, testdir):\n a = testdir.mkpydir(\"a123\")\n a.join(\"test_hello123.py\").write(\n textwrap.dedent(\n \"\"\"\\\n class TestClass(object):\n def test_method(self):\n pass\n \"\"\"\n )\n )\n result = testdir.runpytest(\"-vv\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*a123/test_hello123.py*PASS*\"])\n assert \" <- \" not in result.stdout.str()"},{"col":0,"comment":"null","endLoc":593,"header":"def test_setuptools_importerror_issue1479(testdir, monkeypatch)","id":5533,"name":"test_setuptools_importerror_issue1479","nodeType":"Function","startLoc":573,"text":"def test_setuptools_importerror_issue1479(testdir, monkeypatch):\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n\n class DummyEntryPoint(object):\n name = \"mytestplugin\"\n group = \"pytest11\"\n\n def load(self):\n raise ImportError(\"Don't hide me!\")\n\n class Distribution(object):\n version = \"1.0\"\n files = (\"foo.txt\",)\n entry_points = (DummyEntryPoint(),)\n\n def distributions():\n return (Distribution(),)\n\n monkeypatch.setattr(importlib_metadata, \"distributions\", distributions)\n with pytest.raises(ImportError):\n testdir.parseconfig()"},{"col":0,"comment":"null","endLoc":114,"header":"def pytest_terminal_summary(terminalreporter)","id":5534,"name":"pytest_terminal_summary","nodeType":"Function","startLoc":94,"text":"def pytest_terminal_summary(terminalreporter):\n import _pytest.config\n\n if terminalreporter.config.option.pastebin != \"failed\":\n return\n tr = terminalreporter\n if \"failed\" in tr.stats:\n terminalreporter.write_sep(\"=\", \"Sending information to Paste Service\")\n for rep in terminalreporter.stats.get(\"failed\"):\n try:\n msg = rep.longrepr.reprtraceback.reprentries[-1].reprfileloc\n except AttributeError:\n msg = tr._getfailureheadline(rep)\n tw = _pytest.config.create_terminal_writer(\n terminalreporter.config, stringio=True\n )\n rep.toterminal(tw)\n s = tw.stringio.getvalue()\n assert len(s)\n pastebinurl = create_new_paste(s)\n tr.write_line(\"%s --> %s\" % (msg, pastebinurl))"},{"id":5535,"name":"release-4.0.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-4.0.2\n=======================================\n\npytest 4.0.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Pedro Algarvio\n* Ronny Pfannschmidt\n* Tomer Keren\n* Yash Todi\n\n\nHappy testing,\nThe pytest Development Team\n"},{"id":5536,"name":"release-2.7.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.7.1: bug fixes\n=======================\n\npytest is a mature Python testing tool with more than a 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is supposed to be drop-in compatible to 2.7.0.\n\nSee below for the changes and see docs at:\n\n http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n Bruno Oliveira\n Holger Krekel\n Ionel Maries Cristian\n Floris Bruynooghe\n\nHappy testing,\nThe py.test Development Team\n\n\n2.7.1 (compared to 2.7.0)\n-------------------------\n\n- fix issue731: do not get confused by the braces which may be present\n and unbalanced in an object's repr while collapsing False\n explanations. Thanks Carl Meyer for the report and test case.\n\n- fix issue553: properly handling inspect.getsourcelines failures in\n FixtureLookupError which would lead to an internal error,\n obfuscating the original problem. Thanks talljosh for initial\n diagnose/patch and Bruno Oliveira for final patch.\n\n- fix issue660: properly report scope-mismatch-access errors\n independently from ordering of fixture arguments. Also\n avoid the pytest internal traceback which does not provide\n information to the user. Thanks Holger Krekel.\n\n- streamlined and documented release process. Also all versions\n (in setup.py and documentation generation) are now read\n from _pytest/__init__.py. Thanks Holger Krekel.\n\n- fixed docs to remove the notion that yield-fixtures are experimental.\n They are here to stay :) Thanks Bruno Oliveira.\n\n- Support building wheels by using environment markers for the\n requirements. Thanks Ionel Maries Cristian.\n\n- fixed regression to 2.6.4 which surfaced e.g. in lost stdout capture printing\n when tests raised SystemExit. Thanks Holger Krekel.\n\n- reintroduced _pytest fixture of the pytester plugin which is used\n at least by pytest-xdist.\n"},{"col":0,"comment":"null","endLoc":1333,"header":"@needsosdup\ndef test_close_and_capture_again(testdir)","id":5537,"name":"test_close_and_capture_again","nodeType":"Function","startLoc":1313,"text":"@needsosdup\ndef test_close_and_capture_again(testdir):\n testdir.makepyfile(\n \"\"\"\n import os\n def test_close():\n os.close(1)\n def test_capture_again():\n os.write(1, b\"hello\\\\n\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines(\n \"\"\"\n *test_capture_again*\n *assert 0*\n *stdout*\n *hello*\n \"\"\"\n )"},{"id":5538,"name":"release-3.1.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.1.0\n=======================================\n\nThe pytest team is proud to announce the 3.1.0 release!\n\npytest is a mature Python testing tool with more than a 1600 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\nhttp://doc.pytest.org/en/latest/changelog.html\n\nFor complete documentation, please visit:\n\n http://docs.pytest.org\n\nAs usual, you can upgrade from pypi via:\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Ben Lloyd\n* Bruno Oliveira\n* David Giese\n* David Szotten\n* Dmitri Pribysh\n* Florian Bruhin\n* Florian Schulze\n* Floris Bruynooghe\n* John Towler\n* Jonas Obrist\n* Katerina Koukiou\n* Kodi Arfer\n* Krzysztof Szularz\n* Lev Maximov\n* Loïc Estève\n* Luke Murphy\n* Manuel Krebber\n* Matthew Duck\n* Matthias Bussonnier\n* Michael Howitz\n* Michal Wajszczuk\n* Paweł Adamczak\n* Rafael Bertoldi\n* Ravi Chandra\n* Ronny Pfannschmidt\n* Skylar Downes\n* Thomas Kriechbaumer\n* Vitaly Lashmanov\n* Vlad Dragos\n* Wheerd\n* Xander Johnson\n* mandeep\n* reut\n\n\nHappy testing,\nThe Pytest Development Team\n"},{"id":5539,"name":"release-2.3.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.3: improved fixtures / better unittest integration\n=============================================================================\n\npytest-2.3 comes with many major improvements for fixture/funcarg management\nand parametrized testing in Python. It is now easier, more efficient and\nmore predicatable to re-run the same tests with different fixture\ninstances. Also, you can directly declare the caching \"scope\" of\nfixtures so that dependent tests throughout your whole test suite can\nre-use database or other expensive fixture objects with ease. Lastly,\nit's possible for fixture functions (formerly known as funcarg\nfactories) to use other fixtures, allowing for a completely modular and\nre-useable fixture design.\n\nFor detailed info and tutorial-style examples, see:\n\n http://pytest.org/latest/fixture.html\n\nMoreover, there is now support for using pytest fixtures/funcargs with\nunittest-style suites, see here for examples:\n\n http://pytest.org/latest/unittest.html\n\nBesides, more unittest-test suites are now expected to \"simply work\"\nwith pytest.\n\nAll changes are backward compatible and you should be able to continue\nto run your test suites and 3rd party plugins that worked with\npytest-2.2.4.\n\nIf you are interested in the precise reasoning (including examples) of the\npytest-2.3 fixture evolution, please consult\nhttp://pytest.org/latest/funcarg_compare.html\n\nFor general info on installation and getting started:\n\n http://pytest.org/latest/getting-started.html\n\nDocs and PDF access as usual at:\n\n http://pytest.org\n\nand more details for those already in the knowing of pytest can be found\nin the CHANGELOG below.\n\nParticular thanks for this release go to Floris Bruynooghe, Alex Okrushko\nCarl Meyer, Ronny Pfannschmidt, Benjamin Peterson and Alex Gaynor for helping\nto get the new features right and well integrated. Ronny and Floris\nalso helped to fix a number of bugs and yet more people helped by\nproviding bug reports.\n\nhave fun,\nholger krekel\n\n\nChanges between 2.2.4 and 2.3.0\n-----------------------------------\n\n- fix issue202 - better automatic names for parametrized test functions\n- fix issue139 - introduce @pytest.fixture which allows direct scoping\n and parametrization of funcarg factories. Introduce new @pytest.setup\n marker to allow the writing of setup functions which accept funcargs.\n- fix issue198 - conftest fixtures were not found on windows32 in some\n circumstances with nested directory structures due to path manipulation issues\n- fix issue193 skip test functions with were parametrized with empty\n parameter sets\n- fix python3.3 compat, mostly reporting bits that previously depended\n on dict ordering\n- introduce re-ordering of tests by resource and parametrization setup\n which takes precedence to the usual file-ordering\n- fix issue185 monkeypatching time.time does not cause pytest to fail\n- fix issue172 duplicate call of pytest.setup-decoratored setup_module\n functions\n- fix junitxml=path construction so that if tests change the\n current working directory and the path is a relative path\n it is constructed correctly from the original current working dir.\n- fix \"python setup.py test\" example to cause a proper \"errno\" return\n- fix issue165 - fix broken doc links and mention stackoverflow for FAQ\n- catch unicode-issues when writing failure representations\n to terminal to prevent the whole session from crashing\n- fix xfail/skip confusion: a skip-mark or an imperative pytest.skip\n will now take precedence before xfail-markers because we\n can't determine xfail/xpass status in case of a skip. see also:\n http://stackoverflow.com/questions/11105828/in-py-test-when-i-explicitly-skip-a-test-that-is-marked-as-xfail-how-can-i-get\n\n- always report installed 3rd party plugins in the header of a test run\n\n- fix issue160: a failing setup of an xfail-marked tests should\n be reported as xfail (not xpass)\n\n- fix issue128: show captured output when capsys/capfd are used\n\n- fix issue179: properly show the dependency chain of factories\n\n- pluginmanager.register(...) now raises ValueError if the\n plugin has been already registered or the name is taken\n\n- fix issue159: improve http://pytest.org/latest/faq.html\n especially with respect to the \"magic\" history, also mention\n pytest-django, trial and unittest integration.\n\n- make request.keywords and node.keywords writable. All descendant\n collection nodes will see keyword values. Keywords are dictionaries\n containing markers and other info.\n\n- fix issue 178: xml binary escapes are now wrapped in py.xml.raw\n\n- fix issue 176: correctly catch the builtin AssertionError\n even when we replaced AssertionError with a subclass on the\n python level\n\n- factory discovery no longer fails with magic global callables\n that provide no sane __code__ object (mock.call for example)\n\n- fix issue 182: testdir.inprocess_run now considers passed plugins\n\n- fix issue 188: ensure sys.exc_info is clear on python2\n before calling into a test\n\n- fix issue 191: add unittest TestCase runTest method support\n- fix issue 156: monkeypatch correctly handles class level descriptors\n\n- reporting refinements:\n\n - pytest_report_header now receives a \"startdir\" so that\n you can use startdir.bestrelpath(yourpath) to show\n nice relative path\n\n - allow plugins to implement both pytest_report_header and\n pytest_sessionstart (sessionstart is invoked first).\n\n - don't show deselected reason line if there is none\n\n - py.test -vv will show all of assert comparisons instead of truncating\n"},{"col":4,"comment":"null","endLoc":243,"header":"def test_keyboard_interrupt(self, testdir, option)","id":5540,"name":"test_keyboard_interrupt","nodeType":"Function","startLoc":214,"text":"def test_keyboard_interrupt(self, testdir, option):\n testdir.makepyfile(\n \"\"\"\n def test_foobar():\n assert 0\n def test_spamegg():\n import py; pytest.skip('skip me please!')\n def test_interrupt_me():\n raise KeyboardInterrupt # simulating the user\n \"\"\"\n )\n\n result = testdir.runpytest(*option.args, no_reraise_ctrlc=True)\n result.stdout.fnmatch_lines(\n [\n \" def test_foobar():\",\n \"> assert 0\",\n \"E assert 0\",\n \"*_keyboard_interrupt.py:6: KeyboardInterrupt*\",\n ]\n )\n if option.fulltrace:\n result.stdout.fnmatch_lines(\n [\"*raise KeyboardInterrupt # simulating the user*\"]\n )\n else:\n result.stdout.fnmatch_lines(\n [\"(to show a full traceback on KeyboardInterrupt use --fulltrace)\"]\n )\n result.stdout.fnmatch_lines([\"*KeyboardInterrupt*\"])"},{"col":4,"comment":"null","endLoc":321,"header":"def test_directory_skipped(self, testdir)","id":5541,"name":"test_directory_skipped","nodeType":"Function","startLoc":310,"text":"def test_directory_skipped(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_ignore_collect():\n pytest.skip(\"intentional\")\n \"\"\"\n )\n testdir.makepyfile(\"def test_hello(): pass\")\n result = testdir.runpytest()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n result.stdout.fnmatch_lines([\"*1 skipped*\"])"},{"col":4,"comment":"null","endLoc":261,"header":"def test_keyboard_in_sessionstart(self, testdir)","id":5542,"name":"test_keyboard_in_sessionstart","nodeType":"Function","startLoc":245,"text":"def test_keyboard_in_sessionstart(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_sessionstart():\n raise KeyboardInterrupt\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_foobar():\n pass\n \"\"\"\n )\n\n result = testdir.runpytest(no_reraise_ctrlc=True)\n assert result.ret == 2\n result.stdout.fnmatch_lines([\"*KeyboardInterrupt*\"])"},{"col":0,"comment":"null","endLoc":1375,"header":"@pytest.mark.parametrize(\"method\", [\"SysCapture\", \"FDCapture\"])\ndef test_capturing_and_logging_fundamentals(testdir, method)","id":5543,"name":"test_capturing_and_logging_fundamentals","nodeType":"Function","startLoc":1336,"text":"@pytest.mark.parametrize(\"method\", [\"SysCapture\", \"FDCapture\"])\ndef test_capturing_and_logging_fundamentals(testdir, method):\n if method == \"StdCaptureFD\" and not hasattr(os, \"dup\"):\n pytest.skip(\"need os.dup\")\n # here we check a fundamental feature\n p = testdir.makepyfile(\n \"\"\"\n import sys, os\n import py, logging\n from _pytest import capture\n cap = capture.MultiCapture(out=False, in_=False,\n Capture=capture.%s)\n cap.start_capturing()\n\n logging.warning(\"hello1\")\n outerr = cap.readouterr()\n print(\"suspend, captured %%s\" %%(outerr,))\n logging.warning(\"hello2\")\n\n cap.pop_outerr_to_orig()\n logging.warning(\"hello3\")\n\n outerr = cap.readouterr()\n print(\"suspend2, captured %%s\" %% (outerr,))\n \"\"\"\n % (method,)\n )\n result = testdir.runpython(p)\n result.stdout.fnmatch_lines(\n \"\"\"\n suspend, captured*hello1*\n suspend2, captured*WARNING:root:hello3*\n \"\"\"\n )\n result.stderr.fnmatch_lines(\n \"\"\"\n WARNING:root:hello2\n \"\"\"\n )\n assert \"atexit\" not in result.stderr.str()"},{"col":4,"comment":"Use singular 'item' when reporting a single test item","endLoc":272,"header":"def test_collect_single_item(self, testdir)","id":5544,"name":"test_collect_single_item","nodeType":"Function","startLoc":263,"text":"def test_collect_single_item(self, testdir):\n \"\"\"Use singular 'item' when reporting a single test item\"\"\"\n testdir.makepyfile(\n \"\"\"\n def test_foobar():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"collected 1 item\"])"},{"col":0,"comment":"","endLoc":2,"header":"pastebin.py#","id":5545,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" submit failure or test session information to a pastebin service. \"\"\""},{"col":4,"comment":"null","endLoc":282,"header":"def test_rewrite(self, testdir, monkeypatch)","id":5546,"name":"test_rewrite","nodeType":"Function","startLoc":274,"text":"def test_rewrite(self, testdir, monkeypatch):\n config = testdir.parseconfig()\n f = py.io.TextIO()\n monkeypatch.setattr(f, \"isatty\", lambda *args: True)\n tr = TerminalReporter(config, f)\n tr._tw.fullwidth = 10\n tr.write(\"hello\")\n tr.rewrite(\"hey\", erase=True)\n assert f.getvalue() == \"hello\" + \"\\r\" + \"hey\" + (6 * \" \")"},{"col":4,"comment":"null","endLoc":340,"header":"def test_multiple_items_per_collector_byid(self, testdir)","id":5547,"name":"test_multiple_items_per_collector_byid","nodeType":"Function","startLoc":323,"text":"def test_multiple_items_per_collector_byid(self, testdir):\n c = testdir.makeconftest(\n \"\"\"\n import pytest\n class MyItem(pytest.Item):\n def runtest(self):\n pass\n class MyCollector(pytest.File):\n def collect(self):\n return [MyItem(name=\"xyz\", parent=self)]\n def pytest_collect_file(path, parent):\n if path.basename.startswith(\"conftest\"):\n return MyCollector(path, parent)\n \"\"\"\n )\n result = testdir.runpytest(c.basename + \"::\" + \"xyz\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 pass*\"])"},{"col":41,"endLoc":277,"id":5548,"nodeType":"Lambda","startLoc":277,"text":"lambda *args: True"},{"col":4,"comment":"null","endLoc":358,"header":"def test_skip_on_generated_funcarg_id(self, testdir)","id":5549,"name":"test_skip_on_generated_funcarg_id","nodeType":"Function","startLoc":342,"text":"def test_skip_on_generated_funcarg_id(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('x', [3], ids=['hello-123'])\n def pytest_runtest_setup(item):\n print(item.keywords)\n if 'hello-123' in item.keywords:\n pytest.skip(\"hello\")\n assert 0\n \"\"\"\n )\n p = testdir.makepyfile(\"\"\"def test_func(x): pass\"\"\")\n res = testdir.runpytest(p, SHOW_PYTEST_WARNINGS_ARG)\n assert res.ret == 0\n res.stdout.fnmatch_lines([\"*1 skipped*\"])"},{"className":"TestCollectonly","col":0,"comment":"null","endLoc":390,"id":5550,"nodeType":"Class","startLoc":285,"text":"class TestCollectonly(object):\n def test_collectonly_basic(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines(\n [\"\", \" \"]\n )\n\n def test_collectonly_skipped_module(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n pytest.skip(\"hello\")\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\", \"-rs\")\n result.stdout.fnmatch_lines([\"*ERROR collecting*\"])\n\n def test_collectonly_display_test_description(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_with_description():\n \\\"\"\" This test has a description.\n \\\"\"\"\n assert True\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\", \"--verbose\")\n result.stdout.fnmatch_lines([\" This test has a description.\"])\n\n def test_collectonly_failed_module(self, testdir):\n testdir.makepyfile(\"\"\"raise ValueError(0)\"\"\")\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*raise ValueError*\", \"*1 error*\"])\n\n def test_collectonly_fatal(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_collectstart(collector):\n assert 0, \"urgs\"\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*INTERNAL*args*\"])\n assert result.ret == 3\n\n def test_collectonly_simple(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_func1():\n pass\n class TestClass(object):\n def test_method(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\", p)\n # assert stderr.startswith(\"inserting into sys.path\")\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n [\n \"*\",\n \"* \",\n \"* \",\n \"* \",\n ]\n )\n\n def test_collectonly_error(self, testdir):\n p = testdir.makepyfile(\"import Errlkjqweqwe\")\n result = testdir.runpytest(\"--collect-only\", p)\n assert result.ret == 2\n result.stdout.fnmatch_lines(\n textwrap.dedent(\n \"\"\"\\\n *ERROR*\n *ImportError*\n *No module named *Errlk*\n *1 error*\n \"\"\"\n ).strip()\n )\n\n def test_collectonly_missing_path(self, testdir):\n \"\"\"this checks issue 115,\n failure in parseargs will cause session\n not to have the items attribute\n \"\"\"\n result = testdir.runpytest(\"--collect-only\", \"uhm_missing_path\")\n assert result.ret == 4\n result.stderr.fnmatch_lines([\"*ERROR: file not found*\"])\n\n def test_collectonly_quiet(self, testdir):\n testdir.makepyfile(\"def test_foo(): pass\")\n result = testdir.runpytest(\"--collect-only\", \"-q\")\n result.stdout.fnmatch_lines([\"*test_foo*\"])\n\n def test_collectonly_more_quiet(self, testdir):\n testdir.makepyfile(test_fun=\"def test_foo(): pass\")\n result = testdir.runpytest(\"--collect-only\", \"-qq\")\n result.stdout.fnmatch_lines([\"*test_fun.py: 1*\"])"},{"col":4,"comment":"null","endLoc":296,"header":"def test_collectonly_basic(self, testdir)","id":5551,"name":"test_collectonly_basic","nodeType":"Function","startLoc":286,"text":"def test_collectonly_basic(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines(\n [\"\", \" \"]\n )"},{"col":4,"comment":"null","endLoc":373,"header":"def test_direct_addressing_selects(self, testdir)","id":5552,"name":"test_direct_addressing_selects","nodeType":"Function","startLoc":360,"text":"def test_direct_addressing_selects(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def pytest_generate_tests(metafunc):\n metafunc.parametrize('i', [1, 2], ids=[\"1\", \"2\"])\n def test_func(i):\n pass\n \"\"\"\n )\n res = testdir.runpytest(\n p.basename + \"::\" + \"test_func[1]\", SHOW_PYTEST_WARNINGS_ARG\n )\n assert res.ret == 0\n res.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":0,"comment":"null","endLoc":190,"header":"@pytest.hookimpl(trylast=True) # after _pytest.runner\ndef pytest_report_teststatus(report)","id":5553,"name":"pytest_report_teststatus","nodeType":"Function","startLoc":180,"text":"@pytest.hookimpl(trylast=True) # after _pytest.runner\ndef pytest_report_teststatus(report):\n if report.passed:\n letter = \".\"\n elif report.skipped:\n letter = \"s\"\n elif report.failed:\n letter = \"F\"\n if report.when != \"call\":\n letter = \"f\"\n return report.outcome, letter, report.outcome.upper()"},{"col":4,"comment":"null","endLoc":306,"header":"def test_collectonly_skipped_module(self, testdir)","id":5554,"name":"test_collectonly_skipped_module","nodeType":"Function","startLoc":298,"text":"def test_collectonly_skipped_module(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n pytest.skip(\"hello\")\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\", \"-rs\")\n result.stdout.fnmatch_lines([\"*ERROR collecting*\"])"},{"col":4,"comment":"null","endLoc":384,"header":"def test_direct_addressing_notfound(self, testdir)","id":5555,"name":"test_direct_addressing_notfound","nodeType":"Function","startLoc":375,"text":"def test_direct_addressing_notfound(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_func():\n pass\n \"\"\"\n )\n res = testdir.runpytest(p.basename + \"::\" + \"test_notfound\")\n assert res.ret\n res.stderr.fnmatch_lines([\"*ERROR*not found*\"])"},{"attributeType":"None","col":4,"comment":"null","endLoc":20,"id":5556,"name":"prog","nodeType":"Attribute","startLoc":20,"text":"prog"},{"attributeType":"null","col":8,"comment":"null","endLoc":26,"id":5557,"name":"_usage","nodeType":"Attribute","startLoc":26,"text":"self._usage"},{"col":4,"comment":"null","endLoc":318,"header":"def test_collectonly_display_test_description(self, testdir)","id":5558,"name":"test_collectonly_display_test_description","nodeType":"Function","startLoc":308,"text":"def test_collectonly_display_test_description(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_with_description():\n \\\"\"\" This test has a description.\n \\\"\"\"\n assert True\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\", \"--verbose\")\n result.stdout.fnmatch_lines([\" This test has a description.\"])"},{"col":4,"comment":"null","endLoc":391,"header":"def test_docstring_on_hookspec(self)","id":5559,"name":"test_docstring_on_hookspec","nodeType":"Function","startLoc":386,"text":"def test_docstring_on_hookspec(self):\n from _pytest import hookspec\n\n for name, value in vars(hookspec).items():\n if name.startswith(\"pytest_\"):\n assert value.__doc__, \"no docstring for %s\" % name"},{"col":4,"comment":"null","endLoc":323,"header":"def test_collectonly_failed_module(self, testdir)","id":5560,"name":"test_collectonly_failed_module","nodeType":"Function","startLoc":320,"text":"def test_collectonly_failed_module(self, testdir):\n testdir.makepyfile(\"\"\"raise ValueError(0)\"\"\")\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*raise ValueError*\", \"*1 error*\"])"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":27,"id":5563,"name":"_inidict","nodeType":"Attribute","startLoc":27,"text":"self._inidict"},{"col":0,"comment":"Integration test for broken distributions with 'files' metadata being None (#5389)","endLoc":616,"header":"def test_importlib_metadata_broken_distribution(testdir, monkeypatch)","id":5564,"name":"test_importlib_metadata_broken_distribution","nodeType":"Function","startLoc":596,"text":"def test_importlib_metadata_broken_distribution(testdir, monkeypatch):\n \"\"\"Integration test for broken distributions with 'files' metadata being None (#5389)\"\"\"\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n\n class DummyEntryPoint:\n name = \"mytestplugin\"\n group = \"pytest11\"\n\n def load(self):\n return object()\n\n class Distribution:\n version = \"1.0\"\n files = None\n entry_points = (DummyEntryPoint(),)\n\n def distributions():\n return (Distribution(),)\n\n monkeypatch.setattr(importlib_metadata, \"distributions\", distributions)\n testdir.parseconfig()"},{"col":4,"comment":"null","endLoc":334,"header":"def test_collectonly_fatal(self, testdir)","id":5565,"name":"test_collectonly_fatal","nodeType":"Function","startLoc":325,"text":"def test_collectonly_fatal(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_collectstart(collector):\n assert 0, \"urgs\"\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines([\"*INTERNAL*args*\"])\n assert result.ret == 3"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":29,"id":5566,"name":"extra_info","nodeType":"Attribute","startLoc":29,"text":"self.extra_info"},{"col":4,"comment":"null","endLoc":356,"header":"def test_collectonly_simple(self, testdir)","id":5567,"name":"test_collectonly_simple","nodeType":"Function","startLoc":336,"text":"def test_collectonly_simple(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test_func1():\n pass\n class TestClass(object):\n def test_method(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\", p)\n # assert stderr.startswith(\"inserting into sys.path\")\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n [\n \"*\",\n \"* \",\n \"* \",\n \"* \",\n ]\n )"},{"attributeType":"list","col":8,"comment":"null","endLoc":28,"id":5568,"name":"_ininames","nodeType":"Attribute","startLoc":28,"text":"self._ininames"},{"col":4,"comment":"null","endLoc":371,"header":"def test_collectonly_error(self, testdir)","id":5569,"name":"test_collectonly_error","nodeType":"Function","startLoc":358,"text":"def test_collectonly_error(self, testdir):\n p = testdir.makepyfile(\"import Errlkjqweqwe\")\n result = testdir.runpytest(\"--collect-only\", p)\n assert result.ret == 2\n result.stdout.fnmatch_lines(\n textwrap.dedent(\n \"\"\"\\\n *ERROR*\n *ImportError*\n *No module named *Errlk*\n *1 error*\n \"\"\"\n ).strip()\n )"},{"attributeType":"OptionGroup","col":8,"comment":"null","endLoc":23,"id":5570,"name":"_anonymous","nodeType":"Attribute","startLoc":23,"text":"self._anonymous"},{"col":4,"comment":"null","endLoc":274,"header":"def name(self)","id":5571,"name":"name","nodeType":"Function","startLoc":273,"text":"def name(self):\n return self.frame.code.raw.co_name"},{"attributeType":"None","col":4,"comment":"null","endLoc":169,"id":5572,"name":"_repr_style","nodeType":"Attribute","startLoc":169,"text":"_repr_style"},{"col":0,"comment":"null","endLoc":650,"header":"@pytest.mark.parametrize(\"block_it\", [True, False])\ndef test_plugin_preparse_prevents_setuptools_loading(testdir, monkeypatch, block_it)","id":5573,"name":"test_plugin_preparse_prevents_setuptools_loading","nodeType":"Function","startLoc":619,"text":"@pytest.mark.parametrize(\"block_it\", [True, False])\ndef test_plugin_preparse_prevents_setuptools_loading(testdir, monkeypatch, block_it):\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n\n plugin_module_placeholder = object()\n\n class DummyEntryPoint(object):\n name = \"mytestplugin\"\n group = \"pytest11\"\n\n def load(self):\n return plugin_module_placeholder\n\n class Distribution(object):\n version = \"1.0\"\n files = (\"foo.txt\",)\n entry_points = (DummyEntryPoint(),)\n\n def distributions():\n return (Distribution(),)\n\n monkeypatch.setattr(importlib_metadata, \"distributions\", distributions)\n args = (\"-p\", \"no:mytestplugin\") if block_it else ()\n config = testdir.parseconfig(*args)\n config.pluginmanager.import_plugin(\"mytestplugin\")\n if block_it:\n assert \"mytestplugin\" not in sys.modules\n assert config.pluginmanager.get_plugin(\"mytestplugin\") is None\n else:\n assert (\n config.pluginmanager.get_plugin(\"mytestplugin\") is plugin_module_placeholder\n )"},{"attributeType":"None","col":4,"comment":"null","endLoc":170,"id":5574,"name":"exprinfo","nodeType":"Attribute","startLoc":170,"text":"exprinfo"},{"attributeType":"property","col":4,"comment":"null","endLoc":208,"id":5575,"name":"locals","nodeType":"Attribute","startLoc":208,"text":"locals"},{"attributeType":"null","col":8,"comment":"null","endLoc":25,"id":5576,"name":"_processopt","nodeType":"Attribute","startLoc":25,"text":"self._processopt"},{"attributeType":"list","col":8,"comment":"null","endLoc":24,"id":5577,"name":"_groups","nodeType":"Attribute","startLoc":24,"text":"self._groups"},{"attributeType":"MyOptionParser","col":8,"comment":"null","endLoc":78,"id":5578,"name":"optparser","nodeType":"Attribute","startLoc":78,"text":"self.optparser"},{"attributeType":"float","col":0,"comment":"null","endLoc":31,"id":5579,"name":"REPORT_COLLECTING_RESOLUTION","nodeType":"Attribute","startLoc":31,"text":"REPORT_COLLECTING_RESOLUTION"},{"col":0,"comment":"","endLoc":5,"header":"terminal.py#","id":5580,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" terminal reporting of the full testing process.\n\nThis is a good source for looking at the various reporting hooks.\n\"\"\"\n\nREPORT_COLLECTING_RESOLUTION = 0.5"},{"col":0,"comment":"null","endLoc":1388,"header":"def test_error_attribute_issue555(testdir)","id":5581,"name":"test_error_attribute_issue555","nodeType":"Function","startLoc":1378,"text":"def test_error_attribute_issue555(testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n def test_capattr():\n assert sys.stdout.errors == \"strict\"\n assert sys.stderr.errors == \"strict\"\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":0,"comment":"null","endLoc":680,"header":"@pytest.mark.parametrize(\n \"parse_args,should_load\", [((\"-p\", \"mytestplugin\"), True), ((), False)]\n)\ndef test_disable_plugin_autoload(testdir, monkeypatch, parse_args, should_load)","id":5582,"name":"test_disable_plugin_autoload","nodeType":"Function","startLoc":653,"text":"@pytest.mark.parametrize(\n \"parse_args,should_load\", [((\"-p\", \"mytestplugin\"), True), ((), False)]\n)\ndef test_disable_plugin_autoload(testdir, monkeypatch, parse_args, should_load):\n class DummyEntryPoint(object):\n project_name = name = \"mytestplugin\"\n group = \"pytest11\"\n version = \"1.0\"\n\n def load(self):\n return sys.modules[self.name]\n\n class Distribution(object):\n entry_points = (DummyEntryPoint(),)\n files = ()\n\n class PseudoPlugin(object):\n x = 42\n\n def distributions():\n return (Distribution(),)\n\n monkeypatch.setenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", \"1\")\n monkeypatch.setattr(importlib_metadata, \"distributions\", distributions)\n monkeypatch.setitem(sys.modules, \"mytestplugin\", PseudoPlugin())\n config = testdir.parseconfig(*parse_args)\n has_loaded = config.pluginmanager.get_plugin(\"mytestplugin\") is not None\n assert has_loaded == should_load"},{"attributeType":"property","col":4,"comment":"null","endLoc":240,"id":5583,"name":"source","nodeType":"Attribute","startLoc":240,"text":"source"},{"attributeType":"property","col":4,"comment":"null","endLoc":276,"id":5584,"name":"name","nodeType":"Attribute","startLoc":276,"text":"name"},{"attributeType":"null","col":8,"comment":"null","endLoc":173,"id":5585,"name":"_excinfo","nodeType":"Attribute","startLoc":173,"text":"self._excinfo"},{"attributeType":"{tb_lineno}","col":8,"comment":"null","endLoc":174,"id":5586,"name":"_rawentry","nodeType":"Attribute","startLoc":174,"text":"self._rawentry"},{"attributeType":"null","col":8,"comment":"null","endLoc":179,"id":5587,"name":"_repr_style","nodeType":"Attribute","startLoc":179,"text":"self._repr_style"},{"attributeType":"int","col":8,"comment":"null","endLoc":175,"id":5588,"name":"lineno","nodeType":"Attribute","startLoc":175,"text":"self.lineno"},{"col":0,"comment":"\n Ensure _py36_windowsconsoleio_workaround function works with objects that\n do not implement the full ``io``-based stream protocol, for example execnet channels (#2666).\n ","endLoc":1407,"header":"@pytest.mark.skipif(\n not sys.platform.startswith(\"win\") and sys.version_info[","id":5589,"name":"test_py36_windowsconsoleio_workaround_non_standard_streams","nodeType":"Function","startLoc":1391,"text":"@pytest.mark.skipif(\n not sys.platform.startswith(\"win\") and sys.version_info[:2] >= (3, 6),\n reason=\"only py3.6+ on windows\",\n)\ndef test_py36_windowsconsoleio_workaround_non_standard_streams():\n \"\"\"\n Ensure _py36_windowsconsoleio_workaround function works with objects that\n do not implement the full ``io``-based stream protocol, for example execnet channels (#2666).\n \"\"\"\n from _pytest.capture import _py36_windowsconsoleio_workaround\n\n class DummyStream(object):\n def write(self, s):\n pass\n\n stream = DummyStream()\n _py36_windowsconsoleio_workaround(stream)"},{"col":0,"comment":"null","endLoc":691,"header":"def test_cmdline_processargs_simple(testdir)","id":5590,"name":"test_cmdline_processargs_simple","nodeType":"Function","startLoc":683,"text":"def test_cmdline_processargs_simple(testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_cmdline_preparse(args):\n args.append(\"-h\")\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*pytest*\", \"*-h*\"])"},{"col":0,"comment":"display extra information when pytest exits due to unrecognized\n options in the command-line","endLoc":710,"header":"def test_invalid_options_show_extra_information(testdir)","id":5591,"name":"test_invalid_options_show_extra_information","nodeType":"Function","startLoc":694,"text":"def test_invalid_options_show_extra_information(testdir):\n \"\"\"display extra information when pytest exits due to unrecognized\n options in the command-line\"\"\"\n testdir.makeini(\n \"\"\"\n [pytest]\n addopts = --invalid-option\n \"\"\"\n )\n result = testdir.runpytest()\n result.stderr.fnmatch_lines(\n [\n \"*error: unrecognized arguments: --invalid-option*\",\n \"* inifile: %s*\" % testdir.tmpdir.join(\"tox.ini\"),\n \"* rootdir: %s*\" % testdir.tmpdir,\n ]\n )"},{"fileName":"test_skipping.py","filePath":"testing","id":5592,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\n\nimport pytest\nfrom _pytest.runner import runtestprotocol\nfrom _pytest.skipping import MarkEvaluator\nfrom _pytest.skipping import pytest_runtest_setup\n\n\nclass TestEvaluator(object):\n def test_no_marker(self, testdir):\n item = testdir.getitem(\"def test_func(): pass\")\n evalskipif = MarkEvaluator(item, \"skipif\")\n assert not evalskipif\n assert not evalskipif.istrue()\n\n def test_marked_no_args(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xyz\n def test_func():\n pass\n \"\"\"\n )\n ev = MarkEvaluator(item, \"xyz\")\n assert ev\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"\"\n assert not ev.get(\"run\", False)\n\n def test_marked_one_arg(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xyz(\"hasattr(os, 'sep')\")\n def test_func():\n pass\n \"\"\"\n )\n ev = MarkEvaluator(item, \"xyz\")\n assert ev\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"condition: hasattr(os, 'sep')\"\n\n @pytest.mark.skipif(\"sys.version_info[0] >= 3\")\n def test_marked_one_arg_unicode(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xyz(u\"hasattr(os, 'sep')\")\n def test_func():\n pass\n \"\"\"\n )\n ev = MarkEvaluator(item, \"xyz\")\n assert ev\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"condition: hasattr(os, 'sep')\"\n\n def test_marked_one_arg_with_reason(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xyz(\"hasattr(os, 'sep')\", attr=2, reason=\"hello world\")\n def test_func():\n pass\n \"\"\"\n )\n ev = MarkEvaluator(item, \"xyz\")\n assert ev\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"hello world\"\n assert ev.get(\"attr\") == 2\n\n def test_marked_one_arg_twice(self, testdir):\n lines = [\n \"\"\"@pytest.mark.skipif(\"not hasattr(os, 'murks')\")\"\"\",\n \"\"\"@pytest.mark.skipif(\"hasattr(os, 'murks')\")\"\"\",\n ]\n for i in range(0, 2):\n item = testdir.getitem(\n \"\"\"\n import pytest\n %s\n %s\n def test_func():\n pass\n \"\"\"\n % (lines[i], lines[(i + 1) % 2])\n )\n ev = MarkEvaluator(item, \"skipif\")\n assert ev\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"condition: not hasattr(os, 'murks')\"\n\n def test_marked_one_arg_twice2(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.skipif(\"hasattr(os, 'murks')\")\n @pytest.mark.skipif(\"not hasattr(os, 'murks')\")\n def test_func():\n pass\n \"\"\"\n )\n ev = MarkEvaluator(item, \"skipif\")\n assert ev\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"condition: not hasattr(os, 'murks')\"\n\n def test_marked_skip_with_not_string(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.skipif(False)\n def test_func():\n pass\n \"\"\"\n )\n ev = MarkEvaluator(item, \"skipif\")\n exc = pytest.raises(pytest.fail.Exception, ev.istrue)\n assert (\n \"\"\"Failed: you need to specify reason=STRING when using booleans as conditions.\"\"\"\n in exc.value.msg\n )\n\n def test_skipif_class(self, testdir):\n item, = testdir.getitems(\n \"\"\"\n import pytest\n class TestClass(object):\n pytestmark = pytest.mark.skipif(\"config._hackxyz\")\n def test_func(self):\n pass\n \"\"\"\n )\n item.config._hackxyz = 3\n ev = MarkEvaluator(item, \"skipif\")\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"condition: config._hackxyz\"\n\n\nclass TestXFail(object):\n @pytest.mark.parametrize(\"strict\", [True, False])\n def test_xfail_simple(self, testdir, strict):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xfail(strict=%s)\n def test_func():\n assert 0\n \"\"\"\n % strict\n )\n reports = runtestprotocol(item, log=False)\n assert len(reports) == 3\n callreport = reports[1]\n assert callreport.skipped\n assert callreport.wasxfail == \"\"\n\n def test_xfail_xpassed(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xfail(reason=\"this is an xfail\")\n def test_func():\n assert 1\n \"\"\"\n )\n reports = runtestprotocol(item, log=False)\n assert len(reports) == 3\n callreport = reports[1]\n assert callreport.passed\n assert callreport.wasxfail == \"this is an xfail\"\n\n def test_xfail_using_platform(self, testdir):\n \"\"\"\n Verify that platform can be used with xfail statements.\n \"\"\"\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xfail(\"platform.platform() == platform.platform()\")\n def test_func():\n assert 0\n \"\"\"\n )\n reports = runtestprotocol(item, log=False)\n assert len(reports) == 3\n callreport = reports[1]\n assert callreport.wasxfail\n\n def test_xfail_xpassed_strict(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xfail(strict=True, reason=\"nope\")\n def test_func():\n assert 1\n \"\"\"\n )\n reports = runtestprotocol(item, log=False)\n assert len(reports) == 3\n callreport = reports[1]\n assert callreport.failed\n assert callreport.longrepr == \"[XPASS(strict)] nope\"\n assert not hasattr(callreport, \"wasxfail\")\n\n def test_xfail_run_anyway(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail\n def test_func():\n assert 0\n def test_func2():\n pytest.xfail(\"hello\")\n \"\"\"\n )\n result = testdir.runpytest(\"--runxfail\")\n result.stdout.fnmatch_lines(\n [\"*def test_func():*\", \"*assert 0*\", \"*1 failed*1 pass*\"]\n )\n\n def test_xfail_evalfalse_but_fails(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xfail('False')\n def test_func():\n assert 0\n \"\"\"\n )\n reports = runtestprotocol(item, log=False)\n callreport = reports[1]\n assert callreport.failed\n assert not hasattr(callreport, \"wasxfail\")\n assert \"xfail\" in callreport.keywords\n\n def test_xfail_not_report_default(self, testdir):\n p = testdir.makepyfile(\n test_one=\"\"\"\n import pytest\n @pytest.mark.xfail\n def test_this():\n assert 0\n \"\"\"\n )\n testdir.runpytest(p, \"-v\")\n # result.stdout.fnmatch_lines([\n # \"*HINT*use*-r*\"\n # ])\n\n def test_xfail_not_run_xfail_reporting(self, testdir):\n p = testdir.makepyfile(\n test_one=\"\"\"\n import pytest\n @pytest.mark.xfail(run=False, reason=\"noway\")\n def test_this():\n assert 0\n @pytest.mark.xfail(\"True\", run=False)\n def test_this_true():\n assert 0\n @pytest.mark.xfail(\"False\", run=False, reason=\"huh\")\n def test_this_false():\n assert 1\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rx\")\n result.stdout.fnmatch_lines(\n [\n \"*test_one*test_this*\",\n \"*NOTRUN*noway\",\n \"*test_one*test_this_true*\",\n \"*NOTRUN*condition:*True*\",\n \"*1 passed*\",\n ]\n )\n\n def test_xfail_not_run_no_setup_run(self, testdir):\n p = testdir.makepyfile(\n test_one=\"\"\"\n import pytest\n @pytest.mark.xfail(run=False, reason=\"hello\")\n def test_this():\n assert 0\n def setup_module(mod):\n raise ValueError(42)\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rx\")\n result.stdout.fnmatch_lines(\n [\"*test_one*test_this*\", \"*NOTRUN*hello\", \"*1 xfailed*\"]\n )\n\n def test_xfail_xpass(self, testdir):\n p = testdir.makepyfile(\n test_one=\"\"\"\n import pytest\n @pytest.mark.xfail\n def test_that():\n assert 1\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rX\")\n result.stdout.fnmatch_lines([\"*XPASS*test_that*\", \"*1 xpassed*\"])\n assert result.ret == 0\n\n def test_xfail_imperative(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_this():\n pytest.xfail(\"hello\")\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*1 xfailed*\"])\n result = testdir.runpytest(p, \"-rx\")\n result.stdout.fnmatch_lines([\"*XFAIL*test_this*\", \"*reason:*hello*\"])\n result = testdir.runpytest(p, \"--runxfail\")\n result.stdout.fnmatch_lines([\"*1 pass*\"])\n\n def test_xfail_imperative_in_setup_function(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def setup_function(function):\n pytest.xfail(\"hello\")\n\n def test_this():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*1 xfailed*\"])\n result = testdir.runpytest(p, \"-rx\")\n result.stdout.fnmatch_lines([\"*XFAIL*test_this*\", \"*reason:*hello*\"])\n result = testdir.runpytest(p, \"--runxfail\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *def test_this*\n *1 fail*\n \"\"\"\n )\n\n def xtest_dynamic_xfail_set_during_setup(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def setup_function(function):\n pytest.mark.xfail(function)\n def test_this():\n assert 0\n def test_that():\n assert 1\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rxX\")\n result.stdout.fnmatch_lines([\"*XFAIL*test_this*\", \"*XPASS*test_that*\"])\n\n def test_dynamic_xfail_no_run(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def arg(request):\n request.applymarker(pytest.mark.xfail(run=False))\n def test_this(arg):\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rxX\")\n result.stdout.fnmatch_lines([\"*XFAIL*test_this*\", \"*NOTRUN*\"])\n\n def test_dynamic_xfail_set_during_funcarg_setup(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def arg(request):\n request.applymarker(pytest.mark.xfail)\n def test_this2(arg):\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*1 xfailed*\"])\n\n @pytest.mark.parametrize(\n \"expected, actual, matchline\",\n [\n (\"TypeError\", \"TypeError\", \"*1 xfailed*\"),\n (\"(AttributeError, TypeError)\", \"TypeError\", \"*1 xfailed*\"),\n (\"TypeError\", \"IndexError\", \"*1 failed*\"),\n (\"(AttributeError, TypeError)\", \"IndexError\", \"*1 failed*\"),\n ],\n )\n def test_xfail_raises(self, expected, actual, matchline, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(raises=%s)\n def test_raises():\n raise %s()\n \"\"\"\n % (expected, actual)\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([matchline])\n\n def test_strict_sanity(self, testdir):\n \"\"\"sanity check for xfail(strict=True): a failing test should behave\n exactly like a normal xfail.\n \"\"\"\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(reason='unsupported feature', strict=True)\n def test_foo():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rxX\")\n result.stdout.fnmatch_lines([\"*XFAIL*\", \"*unsupported feature*\"])\n assert result.ret == 0\n\n @pytest.mark.parametrize(\"strict\", [True, False])\n def test_strict_xfail(self, testdir, strict):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.xfail(reason='unsupported feature', strict=%s)\n def test_foo():\n with open('foo_executed', 'w'): pass # make sure test executes\n \"\"\"\n % strict\n )\n result = testdir.runpytest(p, \"-rxX\")\n if strict:\n result.stdout.fnmatch_lines(\n [\"*test_foo*\", \"*XPASS(strict)*unsupported feature*\"]\n )\n else:\n result.stdout.fnmatch_lines(\n [\n \"*test_strict_xfail*\",\n \"XPASS test_strict_xfail.py::test_foo unsupported feature\",\n ]\n )\n assert result.ret == (1 if strict else 0)\n assert testdir.tmpdir.join(\"foo_executed\").isfile()\n\n @pytest.mark.parametrize(\"strict\", [True, False])\n def test_strict_xfail_condition(self, testdir, strict):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.xfail(False, reason='unsupported feature', strict=%s)\n def test_foo():\n pass\n \"\"\"\n % strict\n )\n result = testdir.runpytest(p, \"-rxX\")\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n assert result.ret == 0\n\n @pytest.mark.parametrize(\"strict\", [True, False])\n def test_xfail_condition_keyword(self, testdir, strict):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.xfail(condition=False, reason='unsupported feature', strict=%s)\n def test_foo():\n pass\n \"\"\"\n % strict\n )\n result = testdir.runpytest(p, \"-rxX\")\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n assert result.ret == 0\n\n @pytest.mark.parametrize(\"strict_val\", [\"true\", \"false\"])\n def test_strict_xfail_default_from_file(self, testdir, strict_val):\n testdir.makeini(\n \"\"\"\n [pytest]\n xfail_strict = %s\n \"\"\"\n % strict_val\n )\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(reason='unsupported feature')\n def test_foo():\n pass\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rxX\")\n strict = strict_val == \"true\"\n result.stdout.fnmatch_lines([\"*1 failed*\" if strict else \"*1 xpassed*\"])\n assert result.ret == (1 if strict else 0)\n\n\nclass TestXFailwithSetupTeardown(object):\n def test_failing_setup_issue9(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def setup_function(func):\n assert 0\n\n @pytest.mark.xfail\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 xfail*\"])\n\n def test_failing_teardown_issue9(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def teardown_function(func):\n assert 0\n\n @pytest.mark.xfail\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 xfail*\"])\n\n\nclass TestSkip(object):\n def test_skip_class(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip\n class TestSomething(object):\n def test_foo(self):\n pass\n def test_bar(self):\n pass\n\n def test_baz():\n pass\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(skipped=2, passed=1)\n\n def test_skips_on_false_string(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip('False')\n def test_foo():\n pass\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(skipped=1)\n\n def test_arg_as_reason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip('testing stuff')\n def test_bar():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines([\"*testing stuff*\", \"*1 skipped*\"])\n\n def test_skip_no_reason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip\n def test_foo():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines([\"*unconditional skip*\", \"*1 skipped*\"])\n\n def test_skip_with_reason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip(reason=\"for lolz\")\n def test_bar():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines([\"*for lolz*\", \"*1 skipped*\"])\n\n def test_only_skips_marked_test(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip\n def test_foo():\n pass\n @pytest.mark.skip(reason=\"nothing in particular\")\n def test_bar():\n pass\n def test_baz():\n assert True\n \"\"\"\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines([\"*nothing in particular*\", \"*1 passed*2 skipped*\"])\n\n def test_strict_and_skip(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip\n def test_hello():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines([\"*unconditional skip*\", \"*1 skipped*\"])\n\n\nclass TestSkipif(object):\n def test_skipif_conditional(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.skipif(\"hasattr(os, 'sep')\")\n def test_func():\n pass\n \"\"\"\n )\n x = pytest.raises(pytest.skip.Exception, lambda: pytest_runtest_setup(item))\n assert x.value.msg == \"condition: hasattr(os, 'sep')\"\n\n @pytest.mark.parametrize(\n \"params\", [\"\\\"hasattr(sys, 'platform')\\\"\", 'True, reason=\"invalid platform\"']\n )\n def test_skipif_reporting(self, testdir, params):\n p = testdir.makepyfile(\n test_foo=\"\"\"\n import pytest\n @pytest.mark.skipif(%(params)s)\n def test_that():\n assert 0\n \"\"\"\n % dict(params=params)\n )\n result = testdir.runpytest(p, \"-s\", \"-rs\")\n result.stdout.fnmatch_lines([\"*SKIP*1*test_foo.py*platform*\", \"*1 skipped*\"])\n assert result.ret == 0\n\n def test_skipif_using_platform(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.skipif(\"platform.platform() == platform.platform()\")\n def test_func():\n pass\n \"\"\"\n )\n pytest.raises(pytest.skip.Exception, lambda: pytest_runtest_setup(item))\n\n @pytest.mark.parametrize(\n \"marker, msg1, msg2\",\n [(\"skipif\", \"SKIP\", \"skipped\"), (\"xfail\", \"XPASS\", \"xpassed\")],\n )\n def test_skipif_reporting_multiple(self, testdir, marker, msg1, msg2):\n testdir.makepyfile(\n test_foo=\"\"\"\n import pytest\n @pytest.mark.{marker}(False, reason='first_condition')\n @pytest.mark.{marker}(True, reason='second_condition')\n def test_foobar():\n assert 1\n \"\"\".format(\n marker=marker\n )\n )\n result = testdir.runpytest(\"-s\", \"-rsxX\")\n result.stdout.fnmatch_lines(\n [\n \"*{msg1}*test_foo.py*second_condition*\".format(msg1=msg1),\n \"*1 {msg2}*\".format(msg2=msg2),\n ]\n )\n assert result.ret == 0\n\n\ndef test_skip_not_report_default(testdir):\n p = testdir.makepyfile(\n test_one=\"\"\"\n import pytest\n def test_this():\n pytest.skip(\"hello\")\n \"\"\"\n )\n result = testdir.runpytest(p, \"-v\")\n result.stdout.fnmatch_lines(\n [\n # \"*HINT*use*-r*\",\n \"*1 skipped*\"\n ]\n )\n\n\ndef test_skipif_class(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n class TestClass(object):\n pytestmark = pytest.mark.skipif(\"True\")\n def test_that(self):\n assert 0\n def test_though(self):\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*2 skipped*\"])\n\n\ndef test_skipped_reasons_functional(testdir):\n testdir.makepyfile(\n test_one=\"\"\"\n from conftest import doskip\n def setup_function(func):\n doskip()\n def test_func():\n pass\n class TestClass(object):\n def test_method(self):\n doskip()\n \"\"\",\n conftest=\"\"\"\n import pytest\n def doskip():\n pytest.skip('test')\n \"\"\",\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines([\"*SKIP*2*conftest.py:4: test\"])\n assert result.ret == 0\n\n\ndef test_skipped_folding(testdir):\n testdir.makepyfile(\n test_one=\"\"\"\n import pytest\n pytestmark = pytest.mark.skip(\"Folding\")\n def setup_function(func):\n pass\n def test_func():\n pass\n class TestClass(object):\n def test_method(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines([\"*SKIP*2*test_one.py: Folding\"])\n assert result.ret == 0\n\n\ndef test_reportchars(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1():\n assert 0\n @pytest.mark.xfail\n def test_2():\n assert 0\n @pytest.mark.xfail\n def test_3():\n pass\n def test_4():\n pytest.skip(\"four\")\n \"\"\"\n )\n result = testdir.runpytest(\"-rfxXs\")\n result.stdout.fnmatch_lines(\n [\"FAIL*test_1*\", \"XFAIL*test_2*\", \"XPASS*test_3*\", \"SKIP*four*\"]\n )\n\n\ndef test_reportchars_error(testdir):\n testdir.makepyfile(\n conftest=\"\"\"\n def pytest_runtest_teardown():\n assert 0\n \"\"\",\n test_simple=\"\"\"\n def test_foo():\n pass\n \"\"\",\n )\n result = testdir.runpytest(\"-rE\")\n result.stdout.fnmatch_lines([\"ERROR*test_foo*\"])\n\n\ndef test_reportchars_all(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1():\n assert 0\n @pytest.mark.xfail\n def test_2():\n assert 0\n @pytest.mark.xfail\n def test_3():\n pass\n def test_4():\n pytest.skip(\"four\")\n @pytest.fixture\n def fail():\n assert 0\n def test_5(fail):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-ra\")\n result.stdout.fnmatch_lines(\n [\n \"SKIP*four*\",\n \"XFAIL*test_2*\",\n \"XPASS*test_3*\",\n \"ERROR*test_5*\",\n \"FAIL*test_1*\",\n ]\n )\n\n\ndef test_reportchars_all_error(testdir):\n testdir.makepyfile(\n conftest=\"\"\"\n def pytest_runtest_teardown():\n assert 0\n \"\"\",\n test_simple=\"\"\"\n def test_foo():\n pass\n \"\"\",\n )\n result = testdir.runpytest(\"-ra\")\n result.stdout.fnmatch_lines([\"ERROR*test_foo*\"])\n\n\ndef test_errors_in_xfail_skip_expressions(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skipif(\"asd\")\n def test_nameerror():\n pass\n @pytest.mark.xfail(\"syntax error\")\n def test_syntax():\n pass\n\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n markline = \" ^\"\n if sys.platform.startswith(\"java\"):\n # XXX report this to java\n markline = \"*\" + markline[8:]\n elif hasattr(sys, \"pypy_version_info\") and sys.pypy_version_info < (6,):\n markline = markline[5:]\n elif sys.version_info >= (3, 8) or hasattr(sys, \"pypy_version_info\"):\n markline = markline[4:]\n result.stdout.fnmatch_lines(\n [\n \"*ERROR*test_nameerror*\",\n \"*evaluating*skipif*expression*\",\n \"*asd*\",\n \"*ERROR*test_syntax*\",\n \"*evaluating*xfail*expression*\",\n \" syntax error\",\n markline,\n \"SyntaxError: invalid syntax\",\n \"*1 pass*2 error*\",\n ]\n )\n\n\ndef test_xfail_skipif_with_globals(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n x = 3\n @pytest.mark.skipif(\"x == 3\")\n def test_skip1():\n pass\n @pytest.mark.xfail(\"x == 3\")\n def test_boolean():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"-rsx\")\n result.stdout.fnmatch_lines([\"*SKIP*x == 3*\", \"*XFAIL*test_boolean*\", \"*x == 3*\"])\n\n\ndef test_direct_gives_error(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skipif(True)\n def test_skip1():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 error*\"])\n\n\ndef test_default_markers(testdir):\n result = testdir.runpytest(\"--markers\")\n result.stdout.fnmatch_lines(\n [\n \"*skipif(*condition)*skip*\",\n \"*xfail(*condition, reason=None, run=True, raises=None, strict=False)*expected failure*\",\n ]\n )\n\n\ndef test_xfail_test_setup_exception(testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_runtest_setup():\n 0 / 0\n \"\"\"\n )\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail\n def test_func():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p)\n assert result.ret == 0\n assert \"xfailed\" in result.stdout.str()\n assert \"xpassed\" not in result.stdout.str()\n\n\ndef test_imperativeskip_on_xfail_test(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail\n def test_that_fails():\n assert 0\n\n @pytest.mark.skipif(\"True\")\n def test_hello():\n pass\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_runtest_setup(item):\n pytest.skip(\"abc\")\n \"\"\"\n )\n result = testdir.runpytest(\"-rsxX\")\n result.stdout.fnmatch_lines_random(\n \"\"\"\n *SKIP*abc*\n *SKIP*condition: True*\n *2 skipped*\n \"\"\"\n )\n\n\nclass TestBooleanCondition(object):\n def test_skipif(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skipif(True, reason=\"True123\")\n def test_func1():\n pass\n @pytest.mark.skipif(False, reason=\"True123\")\n def test_func2():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n \"\"\"\n *1 passed*1 skipped*\n \"\"\"\n )\n\n def test_skipif_noreason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skipif(True)\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *1 error*\n \"\"\"\n )\n\n def test_xfail(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(True, reason=\"True123\")\n def test_func():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"-rxs\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *XFAIL*\n *True123*\n *1 xfail*\n \"\"\"\n )\n\n\ndef test_xfail_item(testdir):\n # Ensure pytest.xfail works with non-Python Item\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n class MyItem(pytest.Item):\n nodeid = 'foo'\n def runtest(self):\n pytest.xfail(\"Expected Failure\")\n\n def pytest_collect_file(path, parent):\n return MyItem(\"foo\", parent)\n \"\"\"\n )\n result = testdir.inline_run()\n passed, skipped, failed = result.listoutcomes()\n assert not failed\n xfailed = [r for r in skipped if hasattr(r, \"wasxfail\")]\n assert xfailed\n\n\ndef test_module_level_skip_error(testdir):\n \"\"\"\n Verify that using pytest.skip at module level causes a collection error\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.skip\n def test_func():\n assert True\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"*Using pytest.skip outside of a test is not allowed*\"]\n )\n\n\ndef test_module_level_skip_with_allow_module_level(testdir):\n \"\"\"\n Verify that using pytest.skip(allow_module_level=True) is allowed\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n pytest.skip(\"skip_module_level\", allow_module_level=True)\n\n def test_func():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"-rxs\")\n result.stdout.fnmatch_lines([\"*SKIP*skip_module_level\"])\n\n\ndef test_invalid_skip_keyword_parameter(testdir):\n \"\"\"\n Verify that using pytest.skip() with unknown parameter raises an error\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n pytest.skip(\"skip_module_level\", unknown=1)\n\n def test_func():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*TypeError:*['unknown']*\"])\n\n\ndef test_mark_xfail_item(testdir):\n # Ensure pytest.mark.xfail works with non-Python Item\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n class MyItem(pytest.Item):\n nodeid = 'foo'\n def setup(self):\n marker = pytest.mark.xfail(True, reason=\"Expected failure\")\n self.add_marker(marker)\n def runtest(self):\n assert False\n\n def pytest_collect_file(path, parent):\n return MyItem(\"foo\", parent)\n \"\"\"\n )\n result = testdir.inline_run()\n passed, skipped, failed = result.listoutcomes()\n assert not failed\n xfailed = [r for r in skipped if hasattr(r, \"wasxfail\")]\n assert xfailed\n\n\ndef test_summary_list_after_errors(testdir):\n \"\"\"Ensure the list of errors/fails/xfails/skips appears after tracebacks in terminal reporting.\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_fail():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"-ra\")\n result.stdout.fnmatch_lines(\n [\n \"=* FAILURES *=\",\n \"*= short test summary info =*\",\n \"FAILED test_summary_list_after_errors.py::test_fail - assert 0\",\n ]\n )\n\n\ndef test_importorskip():\n with pytest.raises(\n pytest.skip.Exception,\n match=\"^could not import 'doesnotexist': No module named .*\",\n ):\n pytest.importorskip(\"doesnotexist\")\n"},{"className":"ExceptionRepr","col":0,"comment":"null","endLoc":871,"id":5593,"nodeType":"Class","startLoc":861,"text":"class ExceptionRepr(TerminalRepr):\n def __init__(self):\n self.sections = []\n\n def addsection(self, name, content, sep=\"-\"):\n self.sections.append((name, content, sep))\n\n def toterminal(self, tw):\n for name, content, sep in self.sections:\n tw.sep(sep, name)\n tw.line(content)"},{"col":4,"comment":"null","endLoc":866,"header":"def addsection(self, name, content, sep=\"-\")","id":5594,"name":"addsection","nodeType":"Function","startLoc":865,"text":"def addsection(self, name, content, sep=\"-\"):\n self.sections.append((name, content, sep))"},{"col":4,"comment":"this checks issue 115,\n failure in parseargs will cause session\n not to have the items attribute\n ","endLoc":380,"header":"def test_collectonly_missing_path(self, testdir)","id":5595,"name":"test_collectonly_missing_path","nodeType":"Function","startLoc":373,"text":"def test_collectonly_missing_path(self, testdir):\n \"\"\"this checks issue 115,\n failure in parseargs will cause session\n not to have the items attribute\n \"\"\"\n result = testdir.runpytest(\"--collect-only\", \"uhm_missing_path\")\n assert result.ret == 4\n result.stderr.fnmatch_lines([\"*ERROR: file not found*\"])"},{"className":"MarkEvaluator","col":0,"comment":"null","endLoc":126,"id":5596,"nodeType":"Class","startLoc":26,"text":"class MarkEvaluator(object):\n def __init__(self, item, name):\n self.item = item\n self._marks = None\n self._mark = None\n self._mark_name = name\n\n def __bool__(self):\n # dont cache here to prevent staleness\n return bool(self._get_marks())\n\n __nonzero__ = __bool__\n\n def wasvalid(self):\n return not hasattr(self, \"exc\")\n\n def _get_marks(self):\n return list(self.item.iter_markers(name=self._mark_name))\n\n def invalidraise(self, exc):\n raises = self.get(\"raises\")\n if not raises:\n return\n return not isinstance(exc, raises)\n\n def istrue(self):\n try:\n return self._istrue()\n except TEST_OUTCOME:\n self.exc = sys.exc_info()\n if isinstance(self.exc[1], SyntaxError):\n msg = [\" \" * (self.exc[1].offset + 4) + \"^\"]\n msg.append(\"SyntaxError: invalid syntax\")\n else:\n msg = traceback.format_exception_only(*self.exc[:2])\n fail(\n \"Error evaluating %r expression\\n\"\n \" %s\\n\"\n \"%s\" % (self._mark_name, self.expr, \"\\n\".join(msg)),\n pytrace=False,\n )\n\n def _getglobals(self):\n d = {\"os\": os, \"sys\": sys, \"platform\": platform, \"config\": self.item.config}\n if hasattr(self.item, \"obj\"):\n d.update(self.item.obj.__globals__)\n return d\n\n def _istrue(self):\n if hasattr(self, \"result\"):\n return self.result\n self._marks = self._get_marks()\n\n if self._marks:\n self.result = False\n for mark in self._marks:\n self._mark = mark\n if \"condition\" in mark.kwargs:\n args = (mark.kwargs[\"condition\"],)\n else:\n args = mark.args\n\n for expr in args:\n self.expr = expr\n if isinstance(expr, six.string_types):\n d = self._getglobals()\n result = cached_eval(self.item.config, expr, d)\n else:\n if \"reason\" not in mark.kwargs:\n # XXX better be checked at collection time\n msg = (\n \"you need to specify reason=STRING \"\n \"when using booleans as conditions.\"\n )\n fail(msg)\n result = bool(expr)\n if result:\n self.result = True\n self.reason = mark.kwargs.get(\"reason\", None)\n self.expr = expr\n return self.result\n\n if not args:\n self.result = True\n self.reason = mark.kwargs.get(\"reason\", None)\n return self.result\n return False\n\n def get(self, attr, default=None):\n if self._mark is None:\n return default\n return self._mark.kwargs.get(attr, default)\n\n def getexplanation(self):\n expl = getattr(self, \"reason\", None) or self.get(\"reason\", None)\n if not expl:\n if not hasattr(self, \"expr\"):\n return \"\"\n else:\n return \"condition: \" + str(self.expr)\n return expl"},{"col":0,"comment":"\n Consider all arguments in the command-line for rootdir\n discovery, even if they happen to occur after an option. #949\n ","endLoc":738,"header":"@pytest.mark.parametrize(\n \"args\",\n [\n [\"dir1\", \"dir2\", \"-v\"],\n [\"dir1\", \"-v\", \"dir2\"],\n [\"dir2\", \"-v\", \"dir1\"],\n [\"-v\", \"dir2\", \"dir1\"],\n ],\n)\ndef test_consider_args_after_options_for_rootdir(testdir, args)","id":5597,"name":"test_consider_args_after_options_for_rootdir","nodeType":"Function","startLoc":713,"text":"@pytest.mark.parametrize(\n \"args\",\n [\n [\"dir1\", \"dir2\", \"-v\"],\n [\"dir1\", \"-v\", \"dir2\"],\n [\"dir2\", \"-v\", \"dir1\"],\n [\"-v\", \"dir2\", \"dir1\"],\n ],\n)\ndef test_consider_args_after_options_for_rootdir(testdir, args):\n \"\"\"\n Consider all arguments in the command-line for rootdir\n discovery, even if they happen to occur after an option. #949\n \"\"\"\n # replace \"dir1\" and \"dir2\" from \"args\" into their real directory\n root = testdir.tmpdir.mkdir(\"myroot\")\n d1 = root.mkdir(\"dir1\")\n d2 = root.mkdir(\"dir2\")\n for i, arg in enumerate(args):\n if arg == \"dir1\":\n args[i] = d1\n elif arg == \"dir2\":\n args[i] = d2\n with root.as_cwd():\n result = testdir.runpytest(*args)\n result.stdout.fnmatch_lines([\"*rootdir: *myroot\"])"},{"col":4,"comment":"null","endLoc":385,"header":"def test_collectonly_quiet(self, testdir)","id":5598,"name":"test_collectonly_quiet","nodeType":"Function","startLoc":382,"text":"def test_collectonly_quiet(self, testdir):\n testdir.makepyfile(\"def test_foo(): pass\")\n result = testdir.runpytest(\"--collect-only\", \"-q\")\n result.stdout.fnmatch_lines([\"*test_foo*\"])"},{"col":4,"comment":"null","endLoc":31,"header":"def __init__(self, item, name)","id":5599,"name":"__init__","nodeType":"Function","startLoc":27,"text":"def __init__(self, item, name):\n self.item = item\n self._marks = None\n self._mark = None\n self._mark_name = name"},{"col":4,"comment":"null","endLoc":35,"header":"def __bool__(self)","id":5600,"name":"__bool__","nodeType":"Function","startLoc":33,"text":"def __bool__(self):\n # dont cache here to prevent staleness\n return bool(self._get_marks())"},{"col":4,"comment":"null","endLoc":871,"header":"def toterminal(self, tw)","id":5601,"name":"toterminal","nodeType":"Function","startLoc":868,"text":"def toterminal(self, tw):\n for name, content, sep in self.sections:\n tw.sep(sep, name)\n tw.line(content)"},{"col":4,"comment":"null","endLoc":43,"header":"def _get_marks(self)","id":5602,"name":"_get_marks","nodeType":"Function","startLoc":42,"text":"def _get_marks(self):\n return list(self.item.iter_markers(name=self._mark_name))"},{"attributeType":"list","col":8,"comment":"null","endLoc":863,"id":5603,"name":"sections","nodeType":"Attribute","startLoc":863,"text":"self.sections"},{"className":"ExceptionChainRepr","col":0,"comment":"null","endLoc":889,"id":5604,"nodeType":"Class","startLoc":874,"text":"class ExceptionChainRepr(ExceptionRepr):\n def __init__(self, chain):\n super(ExceptionChainRepr, self).__init__()\n self.chain = chain\n # reprcrash and reprtraceback of the outermost (the newest) exception\n # in the chain\n self.reprtraceback = chain[-1][0]\n self.reprcrash = chain[-1][1]\n\n def toterminal(self, tw):\n for element in self.chain:\n element[0].toterminal(tw)\n if element[2] is not None:\n tw.line(\"\")\n tw.line(element[2], yellow=True)\n super(ExceptionChainRepr, self).toterminal(tw)"},{"col":4,"comment":"null","endLoc":889,"header":"def toterminal(self, tw)","id":5605,"name":"toterminal","nodeType":"Function","startLoc":883,"text":"def toterminal(self, tw):\n for element in self.chain:\n element[0].toterminal(tw)\n if element[2] is not None:\n tw.line(\"\")\n tw.line(element[2], yellow=True)\n super(ExceptionChainRepr, self).toterminal(tw)"},{"col":4,"comment":"null","endLoc":390,"header":"def test_collectonly_more_quiet(self, testdir)","id":5606,"name":"test_collectonly_more_quiet","nodeType":"Function","startLoc":387,"text":"def test_collectonly_more_quiet(self, testdir):\n testdir.makepyfile(test_fun=\"def test_foo(): pass\")\n result = testdir.runpytest(\"--collect-only\", \"-qq\")\n result.stdout.fnmatch_lines([\"*test_fun.py: 1*\"])"},{"className":"TestFixtureReporting","col":0,"comment":"null","endLoc":490,"id":5607,"nodeType":"Class","startLoc":393,"text":"class TestFixtureReporting(object):\n def test_setup_fixture_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def setup_function(function):\n print(\"setup func\")\n assert 0\n def test_nada():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*ERROR at setup of test_nada*\",\n \"*setup_function(function):*\",\n \"*setup func*\",\n \"*assert 0*\",\n \"*1 error*\",\n ]\n )\n assert result.ret != 0\n\n def test_teardown_fixture_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_nada():\n pass\n def teardown_function(function):\n print(\"teardown func\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*ERROR at teardown*\",\n \"*teardown_function(function):*\",\n \"*assert 0*\",\n \"*Captured stdout*\",\n \"*teardown func*\",\n \"*1 passed*1 error*\",\n ]\n )\n\n def test_teardown_fixture_error_and_test_failure(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_fail():\n assert 0, \"failingfunc\"\n\n def teardown_function(function):\n print(\"teardown func\")\n assert False\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*ERROR at teardown of test_fail*\",\n \"*teardown_function(function):*\",\n \"*assert False*\",\n \"*Captured stdout*\",\n \"*teardown func*\",\n \"*test_fail*\",\n \"*def test_fail():\",\n \"*failingfunc*\",\n \"*1 failed*1 error*\",\n ]\n )\n\n def test_setup_teardown_output_and_test_failure(self, testdir):\n \"\"\" Test for issue #442 \"\"\"\n testdir.makepyfile(\n \"\"\"\n def setup_function(function):\n print(\"setup func\")\n\n def test_fail():\n assert 0, \"failingfunc\"\n\n def teardown_function(function):\n print(\"teardown func\")\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*test_fail*\",\n \"*def test_fail():\",\n \"*failingfunc*\",\n \"*Captured stdout setup*\",\n \"*setup func*\",\n \"*Captured stdout teardown*\",\n \"*teardown func*\",\n \"*1 failed*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":414,"header":"def test_setup_fixture_error(self, testdir)","id":5608,"name":"test_setup_fixture_error","nodeType":"Function","startLoc":394,"text":"def test_setup_fixture_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def setup_function(function):\n print(\"setup func\")\n assert 0\n def test_nada():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*ERROR at setup of test_nada*\",\n \"*setup_function(function):*\",\n \"*setup func*\",\n \"*assert 0*\",\n \"*1 error*\",\n ]\n )\n assert result.ret != 0"},{"col":4,"comment":"null","endLoc":436,"header":"def test_teardown_fixture_error(self, testdir)","id":5609,"name":"test_teardown_fixture_error","nodeType":"Function","startLoc":416,"text":"def test_teardown_fixture_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_nada():\n pass\n def teardown_function(function):\n print(\"teardown func\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*ERROR at teardown*\",\n \"*teardown_function(function):*\",\n \"*assert 0*\",\n \"*Captured stdout*\",\n \"*teardown func*\",\n \"*1 passed*1 error*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":462,"header":"def test_teardown_fixture_error_and_test_failure(self, testdir)","id":5610,"name":"test_teardown_fixture_error_and_test_failure","nodeType":"Function","startLoc":438,"text":"def test_teardown_fixture_error_and_test_failure(self, testdir):\n testdir.makepyfile(\n \"\"\"\n def test_fail():\n assert 0, \"failingfunc\"\n\n def teardown_function(function):\n print(\"teardown func\")\n assert False\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*ERROR at teardown of test_fail*\",\n \"*teardown_function(function):*\",\n \"*assert False*\",\n \"*Captured stdout*\",\n \"*teardown func*\",\n \"*test_fail*\",\n \"*def test_fail():\",\n \"*failingfunc*\",\n \"*1 failed*1 error*\",\n ]\n )"},{"col":4,"comment":" Test for issue #442 ","endLoc":490,"header":"def test_setup_teardown_output_and_test_failure(self, testdir)","id":5611,"name":"test_setup_teardown_output_and_test_failure","nodeType":"Function","startLoc":464,"text":"def test_setup_teardown_output_and_test_failure(self, testdir):\n \"\"\" Test for issue #442 \"\"\"\n testdir.makepyfile(\n \"\"\"\n def setup_function(function):\n print(\"setup func\")\n\n def test_fail():\n assert 0, \"failingfunc\"\n\n def teardown_function(function):\n print(\"teardown func\")\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*test_fail*\",\n \"*def test_fail():\",\n \"*failingfunc*\",\n \"*Captured stdout setup*\",\n \"*setup func*\",\n \"*Captured stdout teardown*\",\n \"*teardown func*\",\n \"*1 failed*\",\n ]\n )"},{"className":"TestTerminalFunctional","col":0,"comment":"null","endLoc":760,"id":5612,"nodeType":"Class","startLoc":493,"text":"class TestTerminalFunctional(object):\n def test_deselected(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n def test_one():\n pass\n def test_two():\n pass\n def test_three():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-k\", \"test_two:\", testpath)\n result.stdout.fnmatch_lines(\n [\"collected 3 items / 1 deselected / 2 selected\", \"*test_deselected.py ..*\"]\n )\n assert result.ret == 0\n\n def test_deselected_with_hookwrapper(self, testdir):\n testpath = testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_collection_modifyitems(config, items):\n yield\n deselected = items.pop()\n config.hook.pytest_deselected(items=[deselected])\n \"\"\"\n )\n testpath = testdir.makepyfile(\n \"\"\"\n def test_one():\n pass\n def test_two():\n pass\n def test_three():\n pass\n \"\"\"\n )\n result = testdir.runpytest(testpath)\n result.stdout.fnmatch_lines(\n [\n \"collected 3 items / 1 deselected / 2 selected\",\n \"*= 2 passed, 1 deselected in*\",\n ]\n )\n assert result.ret == 0\n\n def test_show_deselected_items_using_markexpr_before_test_execution(self, testdir):\n testdir.makepyfile(\n test_show_deselected=\"\"\"\n import pytest\n\n @pytest.mark.foo\n def test_foobar():\n pass\n\n @pytest.mark.bar\n def test_bar():\n pass\n\n def test_pass():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-m\", \"not foo\")\n result.stdout.fnmatch_lines(\n [\n \"collected 3 items / 1 deselected / 2 selected\",\n \"*test_show_deselected.py ..*\",\n \"*= 2 passed, 1 deselected in * =*\",\n ]\n )\n assert \"= 1 deselected =\" not in result.stdout.str()\n assert result.ret == 0\n\n def test_no_skip_summary_if_failure(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_ok():\n pass\n def test_fail():\n assert 0\n def test_skip():\n pytest.skip(\"dontshow\")\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.stdout.str().find(\"skip test summary\") == -1\n assert result.ret == 1\n\n def test_passes(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_passes():\n pass\n class TestClass(object):\n def test_method(self):\n pass\n \"\"\"\n )\n old = p1.dirpath().chdir()\n try:\n result = testdir.runpytest()\n finally:\n old.chdir()\n result.stdout.fnmatch_lines([\"test_passes.py ..*\", \"* 2 pass*\"])\n assert result.ret == 0\n\n def test_header_trailer_info(self, testdir, request):\n testdir.makepyfile(\n \"\"\"\n def test_passes():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n verinfo = \".\".join(map(str, sys.version_info[:3]))\n result.stdout.fnmatch_lines(\n [\n \"*===== test session starts ====*\",\n \"platform %s -- Python %s*pytest-%s*py-%s*pluggy-%s\"\n % (\n sys.platform,\n verinfo,\n pytest.__version__,\n py.__version__,\n pluggy.__version__,\n ),\n \"*test_header_trailer_info.py .*\",\n \"=* 1 passed*in *.[0-9][0-9] seconds *=\",\n ]\n )\n if request.config.pluginmanager.list_plugin_distinfo():\n result.stdout.fnmatch_lines([\"plugins: *\"])\n\n def test_header(self, testdir, request):\n testdir.tmpdir.join(\"tests\").ensure_dir()\n testdir.tmpdir.join(\"gui\").ensure_dir()\n\n # no ini file\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"rootdir: *test_header0\"])\n\n # with inifile\n testdir.makeini(\"\"\"[pytest]\"\"\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"rootdir: *test_header0, inifile: tox.ini\"])\n\n # with testpaths option, and not passing anything in the command-line\n testdir.makeini(\n \"\"\"\n [pytest]\n testpaths = tests gui\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"rootdir: *test_header0, inifile: tox.ini, testpaths: tests, gui\"]\n )\n\n # with testpaths option, passing directory in command-line: do not show testpaths then\n result = testdir.runpytest(\"tests\")\n result.stdout.fnmatch_lines([\"rootdir: *test_header0, inifile: tox.ini\"])\n\n def test_showlocals(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_showlocals():\n x = 3\n y = \"x\" * 5000\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p1, \"-l\")\n result.stdout.fnmatch_lines(\n [\n # \"_ _ * Locals *\",\n \"x* = 3\",\n \"y* = 'xxxxxx*\",\n ]\n )\n\n @pytest.fixture\n def verbose_testfile(self, testdir):\n return testdir.makepyfile(\n \"\"\"\n import pytest\n def test_fail():\n raise ValueError()\n def test_pass():\n pass\n class TestClass(object):\n def test_skip(self):\n pytest.skip(\"hello\")\n def test_gen():\n def check(x):\n assert x == 1\n yield check, 0\n \"\"\"\n )\n\n def test_verbose_reporting(self, verbose_testfile, testdir, pytestconfig):\n result = testdir.runpytest(\n verbose_testfile, \"-v\", \"-Walways::pytest.PytestWarning\"\n )\n result.stdout.fnmatch_lines(\n [\n \"*test_verbose_reporting.py::test_fail *FAIL*\",\n \"*test_verbose_reporting.py::test_pass *PASS*\",\n \"*test_verbose_reporting.py::TestClass::test_skip *SKIP*\",\n \"*test_verbose_reporting.py::test_gen *XFAIL*\",\n ]\n )\n assert result.ret == 1\n\n def test_verbose_reporting_xdist(self, verbose_testfile, testdir, pytestconfig):\n if not pytestconfig.pluginmanager.get_plugin(\"xdist\"):\n pytest.skip(\"xdist plugin not installed\")\n\n result = testdir.runpytest(\n verbose_testfile, \"-v\", \"-n 1\", \"-Walways::pytest.PytestWarning\"\n )\n result.stdout.fnmatch_lines(\n [\"*FAIL*test_verbose_reporting_xdist.py::test_fail*\"]\n )\n assert result.ret == 1\n\n def test_quiet_reporting(self, testdir):\n p1 = testdir.makepyfile(\"def test_pass(): pass\")\n result = testdir.runpytest(p1, \"-q\")\n s = result.stdout.str()\n assert \"test session starts\" not in s\n assert p1.basename not in s\n assert \"===\" not in s\n assert \"passed\" in s\n\n def test_more_quiet_reporting(self, testdir):\n p1 = testdir.makepyfile(\"def test_pass(): pass\")\n result = testdir.runpytest(p1, \"-qq\")\n s = result.stdout.str()\n assert \"test session starts\" not in s\n assert p1.basename not in s\n assert \"===\" not in s\n assert \"passed\" not in s\n\n @pytest.mark.parametrize(\n \"params\", [(), (\"--collect-only\",)], ids=[\"no-params\", \"collect-only\"]\n )\n def test_report_collectionfinish_hook(self, testdir, params):\n testdir.makeconftest(\n \"\"\"\n def pytest_report_collectionfinish(config, startdir, items):\n return ['hello from hook: {0} items'.format(len(items))]\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('i', range(3))\n def test(i):\n pass\n \"\"\"\n )\n result = testdir.runpytest(*params)\n result.stdout.fnmatch_lines([\"collected 3 items\", \"hello from hook: 3 items\"])"},{"col":4,"comment":"null","endLoc":509,"header":"def test_deselected(self, testdir)","id":5613,"name":"test_deselected","nodeType":"Function","startLoc":494,"text":"def test_deselected(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n def test_one():\n pass\n def test_two():\n pass\n def test_three():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-k\", \"test_two:\", testpath)\n result.stdout.fnmatch_lines(\n [\"collected 3 items / 1 deselected / 2 selected\", \"*test_deselected.py ..*\"]\n )\n assert result.ret == 0"},{"col":4,"comment":"null","endLoc":540,"header":"def test_deselected_with_hookwrapper(self, testdir)","id":5614,"name":"test_deselected_with_hookwrapper","nodeType":"Function","startLoc":511,"text":"def test_deselected_with_hookwrapper(self, testdir):\n testpath = testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_collection_modifyitems(config, items):\n yield\n deselected = items.pop()\n config.hook.pytest_deselected(items=[deselected])\n \"\"\"\n )\n testpath = testdir.makepyfile(\n \"\"\"\n def test_one():\n pass\n def test_two():\n pass\n def test_three():\n pass\n \"\"\"\n )\n result = testdir.runpytest(testpath)\n result.stdout.fnmatch_lines(\n [\n \"collected 3 items / 1 deselected / 2 selected\",\n \"*= 2 passed, 1 deselected in*\",\n ]\n )\n assert result.ret == 0"},{"col":4,"comment":"null","endLoc":568,"header":"def test_show_deselected_items_using_markexpr_before_test_execution(self, testdir)","id":5615,"name":"test_show_deselected_items_using_markexpr_before_test_execution","nodeType":"Function","startLoc":542,"text":"def test_show_deselected_items_using_markexpr_before_test_execution(self, testdir):\n testdir.makepyfile(\n test_show_deselected=\"\"\"\n import pytest\n\n @pytest.mark.foo\n def test_foobar():\n pass\n\n @pytest.mark.bar\n def test_bar():\n pass\n\n def test_pass():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-m\", \"not foo\")\n result.stdout.fnmatch_lines(\n [\n \"collected 3 items / 1 deselected / 2 selected\",\n \"*test_show_deselected.py ..*\",\n \"*= 2 passed, 1 deselected in * =*\",\n ]\n )\n assert \"= 1 deselected =\" not in result.stdout.str()\n assert result.ret == 0"},{"fileName":"test_recwarn.py","filePath":"testing","id":5616,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport re\nimport warnings\n\nimport pytest\nfrom _pytest.recwarn import WarningsRecorder\nfrom _pytest.warning_types import PytestDeprecationWarning\n\n\ndef test_recwarn_stacklevel(recwarn):\n warnings.warn(\"hello\")\n warn = recwarn.pop()\n assert warn.filename == __file__\n\n\ndef test_recwarn_functional(testdir):\n testdir.makepyfile(\n \"\"\"\n import warnings\n def test_method(recwarn):\n warnings.warn(\"hello\")\n warn = recwarn.pop()\n assert isinstance(warn.message, UserWarning)\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n\nclass TestWarningsRecorderChecker(object):\n def test_recording(self):\n rec = WarningsRecorder()\n with rec:\n assert not rec.list\n warnings.warn_explicit(\"hello\", UserWarning, \"xyz\", 13)\n assert len(rec.list) == 1\n warnings.warn(DeprecationWarning(\"hello\"))\n assert len(rec.list) == 2\n warn = rec.pop()\n assert str(warn.message) == \"hello\"\n values = rec.list\n rec.clear()\n assert len(rec.list) == 0\n assert values is rec.list\n pytest.raises(AssertionError, rec.pop)\n\n def test_warn_stacklevel(self):\n \"\"\"#4243\"\"\"\n rec = WarningsRecorder()\n with rec:\n warnings.warn(\"test\", DeprecationWarning, 2)\n\n def test_typechecking(self):\n from _pytest.recwarn import WarningsChecker\n\n with pytest.raises(TypeError):\n WarningsChecker(5)\n with pytest.raises(TypeError):\n WarningsChecker((\"hi\", RuntimeWarning))\n with pytest.raises(TypeError):\n WarningsChecker([DeprecationWarning, RuntimeWarning])\n\n def test_invalid_enter_exit(self):\n # wrap this test in WarningsRecorder to ensure warning state gets reset\n with WarningsRecorder():\n with pytest.raises(RuntimeError):\n rec = WarningsRecorder()\n rec.__exit__(None, None, None) # can't exit before entering\n\n with pytest.raises(RuntimeError):\n rec = WarningsRecorder()\n with rec:\n with rec:\n pass # can't enter twice\n\n\nclass TestDeprecatedCall(object):\n \"\"\"test pytest.deprecated_call()\"\"\"\n\n def dep(self, i, j=None):\n if i == 0:\n warnings.warn(\"is deprecated\", DeprecationWarning, stacklevel=1)\n return 42\n\n def dep_explicit(self, i):\n if i == 0:\n warnings.warn_explicit(\n \"dep_explicit\", category=DeprecationWarning, filename=\"hello\", lineno=3\n )\n\n def test_deprecated_call_raises(self):\n with pytest.raises(pytest.fail.Exception, match=\"No warnings of type\"):\n pytest.deprecated_call(self.dep, 3, 5)\n\n def test_deprecated_call(self):\n pytest.deprecated_call(self.dep, 0, 5)\n\n def test_deprecated_call_ret(self):\n ret = pytest.deprecated_call(self.dep, 0)\n assert ret == 42\n\n def test_deprecated_call_preserves(self):\n onceregistry = warnings.onceregistry.copy()\n filters = warnings.filters[:]\n warn = warnings.warn\n warn_explicit = warnings.warn_explicit\n self.test_deprecated_call_raises()\n self.test_deprecated_call()\n assert onceregistry == warnings.onceregistry\n assert filters == warnings.filters\n assert warn is warnings.warn\n assert warn_explicit is warnings.warn_explicit\n\n def test_deprecated_explicit_call_raises(self):\n with pytest.raises(pytest.fail.Exception):\n pytest.deprecated_call(self.dep_explicit, 3)\n\n def test_deprecated_explicit_call(self):\n pytest.deprecated_call(self.dep_explicit, 0)\n pytest.deprecated_call(self.dep_explicit, 0)\n\n @pytest.mark.parametrize(\"mode\", [\"context_manager\", \"call\"])\n def test_deprecated_call_no_warning(self, mode):\n \"\"\"Ensure deprecated_call() raises the expected failure when its block/function does\n not raise a deprecation warning.\n \"\"\"\n\n def f():\n pass\n\n msg = \"No warnings of type (.*DeprecationWarning.*, .*PendingDeprecationWarning.*)\"\n with pytest.raises(pytest.fail.Exception, match=msg):\n if mode == \"call\":\n pytest.deprecated_call(f)\n else:\n with pytest.deprecated_call():\n f()\n\n @pytest.mark.parametrize(\n \"warning_type\", [PendingDeprecationWarning, DeprecationWarning]\n )\n @pytest.mark.parametrize(\"mode\", [\"context_manager\", \"call\"])\n @pytest.mark.parametrize(\"call_f_first\", [True, False])\n @pytest.mark.filterwarnings(\"ignore\")\n def test_deprecated_call_modes(self, warning_type, mode, call_f_first):\n \"\"\"Ensure deprecated_call() captures a deprecation warning as expected inside its\n block/function.\n \"\"\"\n\n def f():\n warnings.warn(warning_type(\"hi\"))\n return 10\n\n # ensure deprecated_call() can capture the warning even if it has already been triggered\n if call_f_first:\n assert f() == 10\n if mode == \"call\":\n assert pytest.deprecated_call(f) == 10\n else:\n with pytest.deprecated_call():\n assert f() == 10\n\n @pytest.mark.parametrize(\"mode\", [\"context_manager\", \"call\"])\n def test_deprecated_call_exception_is_raised(self, mode):\n \"\"\"If the block of the code being tested by deprecated_call() raises an exception,\n it must raise the exception undisturbed.\n \"\"\"\n\n def f():\n raise ValueError(\"some exception\")\n\n with pytest.raises(ValueError, match=\"some exception\"):\n if mode == \"call\":\n pytest.deprecated_call(f)\n else:\n with pytest.deprecated_call():\n f()\n\n def test_deprecated_call_specificity(self):\n other_warnings = [\n Warning,\n UserWarning,\n SyntaxWarning,\n RuntimeWarning,\n FutureWarning,\n ImportWarning,\n UnicodeWarning,\n ]\n for warning in other_warnings:\n\n def f():\n warnings.warn(warning(\"hi\"))\n\n with pytest.raises(pytest.fail.Exception):\n pytest.deprecated_call(f)\n with pytest.raises(pytest.fail.Exception):\n with pytest.deprecated_call():\n f()\n\n def test_deprecated_call_supports_match(self):\n with pytest.deprecated_call(match=r\"must be \\d+$\"):\n warnings.warn(\"value must be 42\", DeprecationWarning)\n\n with pytest.raises(pytest.fail.Exception):\n with pytest.deprecated_call(match=r\"must be \\d+$\"):\n warnings.warn(\"this is not here\", DeprecationWarning)\n\n\nclass TestWarns(object):\n def test_strings(self):\n # different messages, b/c Python suppresses multiple identical warnings\n source1 = \"warnings.warn('w1', RuntimeWarning)\"\n source2 = \"warnings.warn('w2', RuntimeWarning)\"\n source3 = \"warnings.warn('w3', RuntimeWarning)\"\n with pytest.warns(PytestDeprecationWarning) as warninfo: # yo dawg\n pytest.warns(RuntimeWarning, source1)\n pytest.raises(\n pytest.fail.Exception, lambda: pytest.warns(UserWarning, source2)\n )\n pytest.warns(RuntimeWarning, source3)\n assert len(warninfo) == 3\n for w in warninfo:\n assert w.filename == __file__\n msg, = w.message.args\n assert msg.startswith(\"warns(..., 'code(as_a_string)') is deprecated\")\n\n def test_function(self):\n pytest.warns(\n SyntaxWarning, lambda msg: warnings.warn(msg, SyntaxWarning), \"syntax\"\n )\n\n def test_warning_tuple(self):\n pytest.warns(\n (RuntimeWarning, SyntaxWarning), lambda: warnings.warn(\"w1\", RuntimeWarning)\n )\n pytest.warns(\n (RuntimeWarning, SyntaxWarning), lambda: warnings.warn(\"w2\", SyntaxWarning)\n )\n pytest.raises(\n pytest.fail.Exception,\n lambda: pytest.warns(\n (RuntimeWarning, SyntaxWarning),\n lambda: warnings.warn(\"w3\", UserWarning),\n ),\n )\n\n def test_as_contextmanager(self):\n with pytest.warns(RuntimeWarning):\n warnings.warn(\"runtime\", RuntimeWarning)\n\n with pytest.warns(UserWarning):\n warnings.warn(\"user\", UserWarning)\n\n with pytest.raises(pytest.fail.Exception) as excinfo:\n with pytest.warns(RuntimeWarning):\n warnings.warn(\"user\", UserWarning)\n excinfo.match(\n r\"DID NOT WARN. No warnings of type \\(.+RuntimeWarning.+,\\) was emitted. \"\n r\"The list of emitted warnings is: \\[UserWarning\\('user',?\\)\\].\"\n )\n\n with pytest.raises(pytest.fail.Exception) as excinfo:\n with pytest.warns(UserWarning):\n warnings.warn(\"runtime\", RuntimeWarning)\n excinfo.match(\n r\"DID NOT WARN. No warnings of type \\(.+UserWarning.+,\\) was emitted. \"\n r\"The list of emitted warnings is: \\[RuntimeWarning\\('runtime',?\\)\\].\"\n )\n\n with pytest.raises(pytest.fail.Exception) as excinfo:\n with pytest.warns(UserWarning):\n pass\n excinfo.match(\n r\"DID NOT WARN. No warnings of type \\(.+UserWarning.+,\\) was emitted. \"\n r\"The list of emitted warnings is: \\[\\].\"\n )\n\n warning_classes = (UserWarning, FutureWarning)\n with pytest.raises(pytest.fail.Exception) as excinfo:\n with pytest.warns(warning_classes) as warninfo:\n warnings.warn(\"runtime\", RuntimeWarning)\n warnings.warn(\"import\", ImportWarning)\n\n message_template = (\n \"DID NOT WARN. No warnings of type {0} was emitted. \"\n \"The list of emitted warnings is: {1}.\"\n )\n excinfo.match(\n re.escape(\n message_template.format(\n warning_classes, [each.message for each in warninfo]\n )\n )\n )\n\n def test_record(self):\n with pytest.warns(UserWarning) as record:\n warnings.warn(\"user\", UserWarning)\n\n assert len(record) == 1\n assert str(record[0].message) == \"user\"\n\n def test_record_only(self):\n with pytest.warns(None) as record:\n warnings.warn(\"user\", UserWarning)\n warnings.warn(\"runtime\", RuntimeWarning)\n\n assert len(record) == 2\n assert str(record[0].message) == \"user\"\n assert str(record[1].message) == \"runtime\"\n\n def test_record_by_subclass(self):\n with pytest.warns(Warning) as record:\n warnings.warn(\"user\", UserWarning)\n warnings.warn(\"runtime\", RuntimeWarning)\n\n assert len(record) == 2\n assert str(record[0].message) == \"user\"\n assert str(record[1].message) == \"runtime\"\n\n class MyUserWarning(UserWarning):\n pass\n\n class MyRuntimeWarning(RuntimeWarning):\n pass\n\n with pytest.warns((UserWarning, RuntimeWarning)) as record:\n warnings.warn(\"user\", MyUserWarning)\n warnings.warn(\"runtime\", MyRuntimeWarning)\n\n assert len(record) == 2\n assert str(record[0].message) == \"user\"\n assert str(record[1].message) == \"runtime\"\n\n def test_double_test(self, testdir):\n \"\"\"If a test is run again, the warning should still be raised\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n import warnings\n\n @pytest.mark.parametrize('run', [1, 2])\n def test(run):\n with pytest.warns(RuntimeWarning):\n warnings.warn(\"runtime\", RuntimeWarning)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 passed in*\"])\n\n def test_match_regex(self):\n with pytest.warns(UserWarning, match=r\"must be \\d+$\"):\n warnings.warn(\"value must be 42\", UserWarning)\n\n with pytest.raises(pytest.fail.Exception):\n with pytest.warns(UserWarning, match=r\"must be \\d+$\"):\n warnings.warn(\"this is not here\", UserWarning)\n\n with pytest.raises(pytest.fail.Exception):\n with pytest.warns(FutureWarning, match=r\"must be \\d+$\"):\n warnings.warn(\"value must be 42\", UserWarning)\n\n def test_one_from_multiple_warns(self):\n with pytest.warns(UserWarning, match=r\"aaa\"):\n warnings.warn(\"cccccccccc\", UserWarning)\n warnings.warn(\"bbbbbbbbbb\", UserWarning)\n warnings.warn(\"aaaaaaaaaa\", UserWarning)\n\n def test_none_of_multiple_warns(self):\n with pytest.raises(pytest.fail.Exception):\n with pytest.warns(UserWarning, match=r\"aaa\"):\n warnings.warn(\"bbbbbbbbbb\", UserWarning)\n warnings.warn(\"cccccccccc\", UserWarning)\n\n @pytest.mark.filterwarnings(\"ignore\")\n def test_can_capture_previously_warned(self):\n def f():\n warnings.warn(UserWarning(\"ohai\"))\n return 10\n\n assert f() == 10\n assert pytest.warns(UserWarning, f) == 10\n assert pytest.warns(UserWarning, f) == 10\n"},{"className":"WarningsRecorder","col":0,"comment":"A context manager to record raised warnings.\n\n Adapted from `warnings.catch_warnings`.\n ","endLoc":201,"id":5617,"nodeType":"Class","startLoc":113,"text":"class WarningsRecorder(warnings.catch_warnings):\n \"\"\"A context manager to record raised warnings.\n\n Adapted from `warnings.catch_warnings`.\n \"\"\"\n\n def __init__(self):\n super(WarningsRecorder, self).__init__(record=True)\n self._entered = False\n self._list = []\n\n @property\n def list(self):\n \"\"\"The list of recorded warnings.\"\"\"\n return self._list\n\n def __getitem__(self, i):\n \"\"\"Get a recorded warning by index.\"\"\"\n return self._list[i]\n\n def __iter__(self):\n \"\"\"Iterate through the recorded warnings.\"\"\"\n return iter(self._list)\n\n def __len__(self):\n \"\"\"The number of recorded warnings.\"\"\"\n return len(self._list)\n\n def pop(self, cls=Warning):\n \"\"\"Pop the first recorded warning, raise exception if not exists.\"\"\"\n for i, w in enumerate(self._list):\n if issubclass(w.category, cls):\n return self._list.pop(i)\n __tracebackhide__ = True\n raise AssertionError(\"%r not found in warning list\" % cls)\n\n def clear(self):\n \"\"\"Clear the list of recorded warnings.\"\"\"\n self._list[:] = []\n\n def __enter__(self):\n if self._entered:\n __tracebackhide__ = True\n raise RuntimeError(\"Cannot enter %r twice\" % self)\n self._list = super(WarningsRecorder, self).__enter__()\n warnings.simplefilter(\"always\")\n # python3 keeps track of a \"filter version\", when the filters are\n # updated previously seen warnings can be re-warned. python2 has no\n # concept of this so we must reset the warnings registry manually.\n # trivial patching of `warnings.warn` seems to be enough somehow?\n if six.PY2:\n\n def warn(message, category=None, stacklevel=1):\n # duplicate the stdlib logic due to\n # bad handing in the c version of warnings\n if isinstance(message, Warning):\n category = message.__class__\n # Check category argument\n if category is None:\n category = UserWarning\n assert issubclass(category, Warning)\n\n # emulate resetting the warn registry\n f_globals = sys._getframe(stacklevel).f_globals\n if \"__warningregistry__\" in f_globals:\n orig = f_globals[\"__warningregistry__\"]\n f_globals[\"__warningregistry__\"] = None\n try:\n return self._saved_warn(message, category, stacklevel + 1)\n finally:\n f_globals[\"__warningregistry__\"] = orig\n else:\n return self._saved_warn(message, category, stacklevel + 1)\n\n warnings.warn, self._saved_warn = warn, warnings.warn\n return self\n\n def __exit__(self, *exc_info):\n if not self._entered:\n __tracebackhide__ = True\n raise RuntimeError(\"Cannot exit %r without entering first\" % self)\n # see above where `self._saved_warn` is assigned\n if six.PY2:\n warnings.warn = self._saved_warn\n super(WarningsRecorder, self).__exit__(*exc_info)\n\n # Built-in catch_warnings does not reset entered state so we do it\n # manually here for this context manager to become reusable.\n self._entered = False"},{"className":"catch_warnings","col":0,"comment":"null","endLoc":118,"id":5618,"nodeType":"Class","startLoc":68,"text":"class catch_warnings(Generic[_W]):\n if sys.version_info >= (3, 11):\n @overload\n def __init__(\n self: catch_warnings[None],\n *,\n record: Literal[False] = False,\n module: ModuleType | None = None,\n action: _ActionKind | None = None,\n category: type[Warning] = ...,\n lineno: int = 0,\n append: bool = False,\n ) -> None: ...\n @overload\n def __init__(\n self: catch_warnings[list[WarningMessage]],\n *,\n record: Literal[True],\n module: ModuleType | None = None,\n action: _ActionKind | None = None,\n category: type[Warning] = ...,\n lineno: int = 0,\n append: bool = False,\n ) -> None: ...\n @overload\n def __init__(\n self: catch_warnings[list[WarningMessage] | None],\n *,\n record: bool,\n module: ModuleType | None = None,\n action: _ActionKind | None = None,\n category: type[Warning] = ...,\n lineno: int = 0,\n append: bool = False,\n ) -> None: ...\n else:\n @overload\n def __init__(self: catch_warnings[None], *, record: Literal[False] = False, module: ModuleType | None = None) -> None: ...\n @overload\n def __init__(\n self: catch_warnings[list[WarningMessage]], *, record: Literal[True], module: ModuleType | None = None\n ) -> None: ...\n @overload\n def __init__(\n self: catch_warnings[list[WarningMessage] | None], *, record: bool, module: ModuleType | None = None\n ) -> None: ...\n\n def __enter__(self) -> _W: ...\n def __exit__(\n self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":584,"header":"def test_no_skip_summary_if_failure(self, testdir)","id":5619,"name":"test_no_skip_summary_if_failure","nodeType":"Function","startLoc":570,"text":"def test_no_skip_summary_if_failure(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_ok():\n pass\n def test_fail():\n assert 0\n def test_skip():\n pytest.skip(\"dontshow\")\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.stdout.str().find(\"skip test summary\") == -1\n assert result.ret == 1"},{"col":0,"comment":"null","endLoc":1421,"header":"def test_dontreadfrominput_has_encoding(testdir)","id":5620,"name":"test_dontreadfrominput_has_encoding","nodeType":"Function","startLoc":1410,"text":"def test_dontreadfrominput_has_encoding(testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n def test_capattr():\n # should not raise AttributeError\n assert sys.stdout.encoding\n assert sys.stderr.encoding\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":"null","endLoc":602,"header":"def test_passes(self, testdir)","id":5621,"name":"test_passes","nodeType":"Function","startLoc":586,"text":"def test_passes(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_passes():\n pass\n class TestClass(object):\n def test_method(self):\n pass\n \"\"\"\n )\n old = p1.dirpath().chdir()\n try:\n result = testdir.runpytest()\n finally:\n old.chdir()\n result.stdout.fnmatch_lines([\"test_passes.py ..*\", \"* 2 pass*\"])\n assert result.ret == 0"},{"col":0,"comment":"null","endLoc":1455,"header":"def test_crash_on_closing_tmpfile_py27(testdir)","id":5622,"name":"test_crash_on_closing_tmpfile_py27","nodeType":"Function","startLoc":1424,"text":"def test_crash_on_closing_tmpfile_py27(testdir):\n p = testdir.makepyfile(\n \"\"\"\n from __future__ import print_function\n import threading\n import sys\n\n printing = threading.Event()\n\n def spam():\n f = sys.stderr\n print('SPAMBEFORE', end='', file=f)\n printing.set()\n\n while True:\n try:\n f.flush()\n except (OSError, ValueError):\n break\n\n def test_spam_in_thread():\n t = threading.Thread(target=spam)\n t.daemon = True\n t.start()\n\n printing.wait()\n \"\"\"\n )\n result = testdir.runpytest_subprocess(str(p))\n assert result.ret == 0\n assert result.stderr.str() == \"\"\n assert \"IOError\" not in result.stdout.str()"},{"attributeType":"{__getitem__}","col":8,"comment":"null","endLoc":877,"id":5623,"name":"chain","nodeType":"Attribute","startLoc":877,"text":"self.chain"},{"attributeType":"null","col":8,"comment":"null","endLoc":880,"id":5624,"name":"reprtraceback","nodeType":"Attribute","startLoc":880,"text":"self.reprtraceback"},{"col":4,"comment":"null","endLoc":629,"header":"def test_header_trailer_info(self, testdir, request)","id":5625,"name":"test_header_trailer_info","nodeType":"Function","startLoc":604,"text":"def test_header_trailer_info(self, testdir, request):\n testdir.makepyfile(\n \"\"\"\n def test_passes():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n verinfo = \".\".join(map(str, sys.version_info[:3]))\n result.stdout.fnmatch_lines(\n [\n \"*===== test session starts ====*\",\n \"platform %s -- Python %s*pytest-%s*py-%s*pluggy-%s\"\n % (\n sys.platform,\n verinfo,\n pytest.__version__,\n py.__version__,\n pluggy.__version__,\n ),\n \"*test_header_trailer_info.py .*\",\n \"=* 1 passed*in *.[0-9][0-9] seconds *=\",\n ]\n )\n if request.config.pluginmanager.list_plugin_distinfo():\n result.stdout.fnmatch_lines([\"plugins: *\"])"},{"col":4,"comment":"null","endLoc":115,"header":"def __enter__(self) -> _W","id":5626,"name":"__enter__","nodeType":"Function","startLoc":115,"text":"def __enter__(self) -> _W: ..."},{"col":4,"comment":"null","endLoc":118,"header":"def __exit__(\n self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n ) -> None","id":5627,"name":"__exit__","nodeType":"Function","startLoc":116,"text":"def __exit__(\n self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n ) -> None: ..."},{"col":4,"comment":"The list of recorded warnings.","endLoc":127,"header":"@property\n def list(self)","id":5628,"name":"list","nodeType":"Function","startLoc":124,"text":"@property\n def list(self):\n \"\"\"The list of recorded warnings.\"\"\"\n return self._list"},{"col":4,"comment":"Get a recorded warning by index.","endLoc":131,"header":"def __getitem__(self, i)","id":5629,"name":"__getitem__","nodeType":"Function","startLoc":129,"text":"def __getitem__(self, i):\n \"\"\"Get a recorded warning by index.\"\"\"\n return self._list[i]"},{"col":4,"comment":"Iterate through the recorded warnings.","endLoc":135,"header":"def __iter__(self)","id":5630,"name":"__iter__","nodeType":"Function","startLoc":133,"text":"def __iter__(self):\n \"\"\"Iterate through the recorded warnings.\"\"\"\n return iter(self._list)"},{"attributeType":"null","col":8,"comment":"null","endLoc":881,"id":5631,"name":"reprcrash","nodeType":"Attribute","startLoc":881,"text":"self.reprcrash"},{"col":0,"comment":"null","endLoc":1464,"header":"def test_pickling_and_unpickling_encoded_file()","id":5632,"name":"test_pickling_and_unpickling_encoded_file","nodeType":"Function","startLoc":1458,"text":"def test_pickling_and_unpickling_encoded_file():\n # See https://bitbucket.org/pytest-dev/pytest/pull-request/194\n # pickle.loads() raises infinite recursion if\n # EncodedFile.__getattr__ is not implemented properly\n ef = capture.EncodedFile(None, None)\n ef_as_str = pickle.dumps(ef)\n pickle.loads(ef_as_str)"},{"col":4,"comment":"The number of recorded warnings.","endLoc":139,"header":"def __len__(self)","id":5633,"name":"__len__","nodeType":"Function","startLoc":137,"text":"def __len__(self):\n \"\"\"The number of recorded warnings.\"\"\"\n return len(self._list)"},{"col":4,"comment":"Pop the first recorded warning, raise exception if not exists.","endLoc":147,"header":"def pop(self, cls=Warning)","id":5635,"name":"pop","nodeType":"Function","startLoc":141,"text":"def pop(self, cls=Warning):\n \"\"\"Pop the first recorded warning, raise exception if not exists.\"\"\"\n for i, w in enumerate(self._list):\n if issubclass(w.category, cls):\n return self._list.pop(i)\n __tracebackhide__ = True\n raise AssertionError(\"%r not found in warning list\" % cls)"},{"className":"ReprExceptionInfo","col":0,"comment":"null","endLoc":900,"id":5636,"nodeType":"Class","startLoc":892,"text":"class ReprExceptionInfo(ExceptionRepr):\n def __init__(self, reprtraceback, reprcrash):\n super(ReprExceptionInfo, self).__init__()\n self.reprtraceback = reprtraceback\n self.reprcrash = reprcrash\n\n def toterminal(self, tw):\n self.reprtraceback.toterminal(tw)\n super(ReprExceptionInfo, self).toterminal(tw)"},{"col":4,"comment":"null","endLoc":900,"header":"def toterminal(self, tw)","id":5637,"name":"toterminal","nodeType":"Function","startLoc":898,"text":"def toterminal(self, tw):\n self.reprtraceback.toterminal(tw)\n super(ReprExceptionInfo, self).toterminal(tw)"},{"col":0,"comment":"null","endLoc":1522,"header":"def test_global_capture_with_live_logging(testdir)","id":5639,"name":"test_global_capture_with_live_logging","nodeType":"Function","startLoc":1467,"text":"def test_global_capture_with_live_logging(testdir):\n # Issue 3819\n # capture should work with live cli logging\n\n # Teardown report seems to have the capture for the whole process (setup, capture, teardown)\n testdir.makeconftest(\n \"\"\"\n def pytest_runtest_logreport(report):\n if \"test_global\" in report.nodeid:\n if report.when == \"teardown\":\n with open(\"caplog\", \"w\") as f:\n f.write(report.caplog)\n with open(\"capstdout\", \"w\") as f:\n f.write(report.capstdout)\n \"\"\"\n )\n\n testdir.makepyfile(\n \"\"\"\n import logging\n import sys\n import pytest\n\n logger = logging.getLogger(__name__)\n\n @pytest.fixture\n def fix1():\n print(\"fix setup\")\n logging.info(\"fix setup\")\n yield\n logging.info(\"fix teardown\")\n print(\"fix teardown\")\n\n def test_global(fix1):\n print(\"begin test\")\n logging.info(\"something in test\")\n print(\"end test\")\n \"\"\"\n )\n result = testdir.runpytest_subprocess(\"--log-cli-level=INFO\")\n assert result.ret == 0\n\n with open(\"caplog\", \"r\") as f:\n caplog = f.read()\n\n assert \"fix setup\" in caplog\n assert \"something in test\" in caplog\n assert \"fix teardown\" in caplog\n\n with open(\"capstdout\", \"r\") as f:\n capstdout = f.read()\n\n assert \"fix setup\" in capstdout\n assert \"begin test\" in capstdout\n assert \"end test\" in capstdout\n assert \"fix teardown\" in capstdout"},{"col":0,"comment":"null","endLoc":744,"header":"@pytest.mark.skipif(\"sys.platform == 'win32'\")\ndef test_toolongargs_issue224(testdir)","id":5640,"name":"test_toolongargs_issue224","nodeType":"Function","startLoc":741,"text":"@pytest.mark.skipif(\"sys.platform == 'win32'\")\ndef test_toolongargs_issue224(testdir):\n result = testdir.runpytest(\"-m\", \"hello\" * 500)\n assert result.ret == EXIT_NOTESTSCOLLECTED"},{"col":0,"comment":"null","endLoc":770,"header":"def test_config_in_subdirectory_colon_command_line_issue2148(testdir)","id":5641,"name":"test_config_in_subdirectory_colon_command_line_issue2148","nodeType":"Function","startLoc":747,"text":"def test_config_in_subdirectory_colon_command_line_issue2148(testdir):\n conftest_source = \"\"\"\n def pytest_addoption(parser):\n parser.addini('foo', 'foo')\n \"\"\"\n\n testdir.makefile(\n \".ini\",\n **{\"pytest\": \"[pytest]\\nfoo = root\", \"subdir/pytest\": \"[pytest]\\nfoo = subdir\"}\n )\n\n testdir.makepyfile(\n **{\n \"conftest\": conftest_source,\n \"subdir/conftest\": conftest_source,\n \"subdir/test_foo\": \"\"\"\\\n def test_foo(pytestconfig):\n assert pytestconfig.getini('foo') == 'subdir'\n \"\"\",\n }\n )\n\n result = testdir.runpytest(\"subdir/test_foo.py::test_foo\")\n assert result.ret == 0"},{"col":0,"comment":"null","endLoc":795,"header":"def test_notify_exception(testdir, capfd)","id":5642,"name":"test_notify_exception","nodeType":"Function","startLoc":773,"text":"def test_notify_exception(testdir, capfd):\n config = testdir.parseconfig()\n with pytest.raises(ValueError) as excinfo:\n raise ValueError(1)\n config.notify_exception(excinfo, config.option)\n out, err = capfd.readouterr()\n assert \"ValueError\" in err\n\n class A(object):\n def pytest_internalerror(self, excrepr):\n return True\n\n config.pluginmanager.register(A())\n config.notify_exception(excinfo, config.option)\n out, err = capfd.readouterr()\n assert not err\n\n config = testdir.parseconfig(\"-p\", \"no:terminal\")\n with pytest.raises(ValueError) as excinfo:\n raise ValueError(1)\n config.notify_exception(excinfo, config.option)\n out, err = capfd.readouterr()\n assert \"ValueError\" in err"},{"col":4,"comment":"null","endLoc":40,"header":"def wasvalid(self)","id":5643,"name":"wasvalid","nodeType":"Function","startLoc":39,"text":"def wasvalid(self):\n return not hasattr(self, \"exc\")"},{"attributeType":"null","col":8,"comment":"null","endLoc":895,"id":5644,"name":"reprtraceback","nodeType":"Attribute","startLoc":895,"text":"self.reprtraceback"},{"attributeType":"null","col":8,"comment":"null","endLoc":896,"id":5645,"name":"reprcrash","nodeType":"Attribute","startLoc":896,"text":"self.reprcrash"},{"col":4,"comment":"null","endLoc":49,"header":"def invalidraise(self, exc)","id":5646,"name":"invalidraise","nodeType":"Function","startLoc":45,"text":"def invalidraise(self, exc):\n raises = self.get(\"raises\")\n if not raises:\n return\n return not isinstance(exc, raises)"},{"className":"ReprTraceback","col":0,"comment":"null","endLoc":927,"id":5647,"nodeType":"Class","startLoc":903,"text":"class ReprTraceback(TerminalRepr):\n entrysep = \"_ \"\n\n def __init__(self, reprentries, extraline, style):\n self.reprentries = reprentries\n self.extraline = extraline\n self.style = style\n\n def toterminal(self, tw):\n # the entries might have different styles\n for i, entry in enumerate(self.reprentries):\n if entry.style == \"long\":\n tw.line(\"\")\n entry.toterminal(tw)\n if i < len(self.reprentries) - 1:\n next_entry = self.reprentries[i + 1]\n if (\n entry.style == \"long\"\n or entry.style == \"short\"\n and next_entry.style == \"long\"\n ):\n tw.sep(self.entrysep)\n\n if self.extraline:\n tw.line(self.extraline)"},{"col":4,"comment":"null","endLoc":927,"header":"def toterminal(self, tw)","id":5648,"name":"toterminal","nodeType":"Function","startLoc":911,"text":"def toterminal(self, tw):\n # the entries might have different styles\n for i, entry in enumerate(self.reprentries):\n if entry.style == \"long\":\n tw.line(\"\")\n entry.toterminal(tw)\n if i < len(self.reprentries) - 1:\n next_entry = self.reprentries[i + 1]\n if (\n entry.style == \"long\"\n or entry.style == \"short\"\n and next_entry.style == \"long\"\n ):\n tw.sep(self.entrysep)\n\n if self.extraline:\n tw.line(self.extraline)"},{"col":4,"comment":"null","endLoc":117,"header":"def get(self, attr, default=None)","id":5649,"name":"get","nodeType":"Function","startLoc":114,"text":"def get(self, attr, default=None):\n if self._mark is None:\n return default\n return self._mark.kwargs.get(attr, default)"},{"col":0,"comment":"null","endLoc":801,"header":"def test_no_terminal_discovery_error(testdir)","id":5650,"name":"test_no_terminal_discovery_error","nodeType":"Function","startLoc":798,"text":"def test_no_terminal_discovery_error(testdir):\n testdir.makepyfile(\"raise TypeError('oops!')\")\n result = testdir.runpytest(\"-p\", \"no:terminal\", \"--collect-only\")\n assert result.ret == EXIT_INTERRUPTED"},{"col":0,"comment":"null","endLoc":816,"header":"def test_load_initial_conftest_last_ordering(testdir, _config_for_test)","id":5651,"name":"test_load_initial_conftest_last_ordering","nodeType":"Function","startLoc":804,"text":"def test_load_initial_conftest_last_ordering(testdir, _config_for_test):\n pm = _config_for_test.pluginmanager\n\n class My(object):\n def pytest_load_initial_conftests(self):\n pass\n\n m = My()\n pm.register(m)\n hc = pm.hook.pytest_load_initial_conftests\n values = hc._nonwrappers + hc._wrappers\n expected = [\"_pytest.config\", \"test_config\", \"_pytest.capture\"]\n assert [x.function.__module__ for x in values] == expected"},{"col":4,"comment":"null","endLoc":66,"header":"def istrue(self)","id":5652,"name":"istrue","nodeType":"Function","startLoc":51,"text":"def istrue(self):\n try:\n return self._istrue()\n except TEST_OUTCOME:\n self.exc = sys.exc_info()\n if isinstance(self.exc[1], SyntaxError):\n msg = [\" \" * (self.exc[1].offset + 4) + \"^\"]\n msg.append(\"SyntaxError: invalid syntax\")\n else:\n msg = traceback.format_exception_only(*self.exc[:2])\n fail(\n \"Error evaluating %r expression\\n\"\n \" %s\\n\"\n \"%s\" % (self._mark_name, self.expr, \"\\n\".join(msg)),\n pytrace=False,\n )"},{"col":0,"comment":"null","endLoc":832,"header":"def test_get_plugin_specs_as_list()","id":5653,"name":"test_get_plugin_specs_as_list","nodeType":"Function","startLoc":819,"text":"def test_get_plugin_specs_as_list():\n from _pytest.config import _get_plugin_specs_as_list\n\n with pytest.raises(pytest.UsageError):\n _get_plugin_specs_as_list({\"foo\"})\n with pytest.raises(pytest.UsageError):\n _get_plugin_specs_as_list(dict())\n\n assert _get_plugin_specs_as_list(None) == []\n assert _get_plugin_specs_as_list(\"\") == []\n assert _get_plugin_specs_as_list(\"foo\") == [\"foo\"]\n assert _get_plugin_specs_as_list(\"foo,bar\") == [\"foo\", \"bar\"]\n assert _get_plugin_specs_as_list([\"foo\", \"bar\"]) == [\"foo\", \"bar\"]\n assert _get_plugin_specs_as_list((\"foo\", \"bar\")) == [\"foo\", \"bar\"]"},{"col":4,"comment":"Clear the list of recorded warnings.","endLoc":151,"header":"def clear(self)","id":5654,"name":"clear","nodeType":"Function","startLoc":149,"text":"def clear(self):\n \"\"\"Clear the list of recorded warnings.\"\"\"\n self._list[:] = []"},{"col":4,"comment":"null","endLoc":188,"header":"def __enter__(self)","id":5655,"name":"__enter__","nodeType":"Function","startLoc":153,"text":"def __enter__(self):\n if self._entered:\n __tracebackhide__ = True\n raise RuntimeError(\"Cannot enter %r twice\" % self)\n self._list = super(WarningsRecorder, self).__enter__()\n warnings.simplefilter(\"always\")\n # python3 keeps track of a \"filter version\", when the filters are\n # updated previously seen warnings can be re-warned. python2 has no\n # concept of this so we must reset the warnings registry manually.\n # trivial patching of `warnings.warn` seems to be enough somehow?\n if six.PY2:\n\n def warn(message, category=None, stacklevel=1):\n # duplicate the stdlib logic due to\n # bad handing in the c version of warnings\n if isinstance(message, Warning):\n category = message.__class__\n # Check category argument\n if category is None:\n category = UserWarning\n assert issubclass(category, Warning)\n\n # emulate resetting the warn registry\n f_globals = sys._getframe(stacklevel).f_globals\n if \"__warningregistry__\" in f_globals:\n orig = f_globals[\"__warningregistry__\"]\n f_globals[\"__warningregistry__\"] = None\n try:\n return self._saved_warn(message, category, stacklevel + 1)\n finally:\n f_globals[\"__warningregistry__\"] = orig\n else:\n return self._saved_warn(message, category, stacklevel + 1)\n\n warnings.warn, self._saved_warn = warn, warnings.warn\n return self"},{"col":4,"comment":"null","endLoc":112,"header":"def _istrue(self)","id":5656,"name":"_istrue","nodeType":"Function","startLoc":74,"text":"def _istrue(self):\n if hasattr(self, \"result\"):\n return self.result\n self._marks = self._get_marks()\n\n if self._marks:\n self.result = False\n for mark in self._marks:\n self._mark = mark\n if \"condition\" in mark.kwargs:\n args = (mark.kwargs[\"condition\"],)\n else:\n args = mark.args\n\n for expr in args:\n self.expr = expr\n if isinstance(expr, six.string_types):\n d = self._getglobals()\n result = cached_eval(self.item.config, expr, d)\n else:\n if \"reason\" not in mark.kwargs:\n # XXX better be checked at collection time\n msg = (\n \"you need to specify reason=STRING \"\n \"when using booleans as conditions.\"\n )\n fail(msg)\n result = bool(expr)\n if result:\n self.result = True\n self.reason = mark.kwargs.get(\"reason\", None)\n self.expr = expr\n return self.result\n\n if not args:\n self.result = True\n self.reason = mark.kwargs.get(\"reason\", None)\n return self.result\n return False"},{"col":4,"comment":"null","endLoc":403,"header":"def test_initialization_error_issue49(self, testdir)","id":5657,"name":"test_initialization_error_issue49","nodeType":"Function","startLoc":393,"text":"def test_initialization_error_issue49(self, testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_configure():\n x\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 3 # internal error\n result.stderr.fnmatch_lines([\"INTERNAL*pytest_configure*\", \"INTERNAL*x*\"])\n assert \"sessionstarttime\" not in result.stderr.str()"},{"col":4,"comment":"null","endLoc":417,"header":"@pytest.mark.parametrize(\"lookfor\", [\"test_fun.py::test_a\"])\n def test_issue134_report_error_when_collecting_member(self, testdir, lookfor)","id":5658,"name":"test_issue134_report_error_when_collecting_member","nodeType":"Function","startLoc":405,"text":"@pytest.mark.parametrize(\"lookfor\", [\"test_fun.py::test_a\"])\n def test_issue134_report_error_when_collecting_member(self, testdir, lookfor):\n testdir.makepyfile(\n test_fun=\"\"\"\n def test_a():\n pass\n def\"\"\"\n )\n result = testdir.runpytest(lookfor)\n result.stdout.fnmatch_lines([\"*SyntaxError*\"])\n if \"::\" in lookfor:\n result.stderr.fnmatch_lines([\"*ERROR*\"])\n assert result.ret == 4 # usage error only if item not found"},{"col":4,"comment":"null","endLoc":72,"header":"def _getglobals(self)","id":5659,"name":"_getglobals","nodeType":"Function","startLoc":68,"text":"def _getglobals(self):\n d = {\"os\": os, \"sys\": sys, \"platform\": platform, \"config\": self.item.config}\n if hasattr(self.item, \"obj\"):\n d.update(self.item.obj.__globals__)\n return d"},{"col":0,"comment":"null","endLoc":23,"header":"def cached_eval(config, expr, d)","id":5660,"name":"cached_eval","nodeType":"Function","startLoc":13,"text":"def cached_eval(config, expr, d):\n if not hasattr(config, \"_evalcache\"):\n config._evalcache = {}\n try:\n return config._evalcache[expr]\n except KeyError:\n import _pytest._code\n\n exprcode = _pytest._code.compile(expr, mode=\"eval\")\n config._evalcache[expr] = x = eval(exprcode, d)\n return x"},{"col":0,"comment":"null","endLoc":1556,"header":"@pytest.mark.parametrize(\"capture_fixture\", [\"capsys\", \"capfd\"])\ndef test_capture_with_live_logging(testdir, capture_fixture)","id":5661,"name":"test_capture_with_live_logging","nodeType":"Function","startLoc":1525,"text":"@pytest.mark.parametrize(\"capture_fixture\", [\"capsys\", \"capfd\"])\ndef test_capture_with_live_logging(testdir, capture_fixture):\n # Issue 3819\n # capture should work with live cli logging\n\n testdir.makepyfile(\n \"\"\"\n import logging\n import sys\n\n logger = logging.getLogger(__name__)\n\n def test_capture({0}):\n print(\"hello\")\n sys.stderr.write(\"world\\\\n\")\n captured = {0}.readouterr()\n assert captured.out == \"hello\\\\n\"\n assert captured.err == \"world\\\\n\"\n\n logging.info(\"something\")\n print(\"next\")\n logging.info(\"something\")\n\n captured = {0}.readouterr()\n assert captured.out == \"next\\\\n\"\n \"\"\".format(\n capture_fixture\n )\n )\n\n result = testdir.runpytest_subprocess(\"--log-cli-level=INFO\")\n assert result.ret == 0"},{"col":4,"comment":"null","endLoc":201,"header":"def __exit__(self, *exc_info)","id":5662,"name":"__exit__","nodeType":"Function","startLoc":190,"text":"def __exit__(self, *exc_info):\n if not self._entered:\n __tracebackhide__ = True\n raise RuntimeError(\"Cannot exit %r without entering first\" % self)\n # see above where `self._saved_warn` is assigned\n if six.PY2:\n warnings.warn = self._saved_warn\n super(WarningsRecorder, self).__exit__(*exc_info)\n\n # Built-in catch_warnings does not reset entered state so we do it\n # manually here for this context manager to become reusable.\n self._entered = False"},{"col":4,"comment":"null","endLoc":433,"header":"def test_report_all_failed_collections_initargs(self, testdir)","id":5663,"name":"test_report_all_failed_collections_initargs","nodeType":"Function","startLoc":419,"text":"def test_report_all_failed_collections_initargs(self, testdir):\n testdir.makeconftest(\n \"\"\"\n from _pytest.main import EXIT_USAGEERROR\n\n def pytest_sessionfinish(exitstatus):\n assert exitstatus == EXIT_USAGEERROR\n print(\"pytest_sessionfinish_called\")\n \"\"\"\n )\n testdir.makepyfile(test_a=\"def\", test_b=\"def\")\n result = testdir.runpytest(\"test_a.py::a\", \"test_b.py::b\")\n result.stderr.fnmatch_lines([\"*ERROR*test_a.py::a*\", \"*ERROR*test_b.py::b*\"])\n result.stdout.fnmatch_lines([\"pytest_sessionfinish_called\"])\n assert result.ret == EXIT_USAGEERROR"},{"attributeType":"null","col":8,"comment":"null","endLoc":122,"id":5664,"name":"_list","nodeType":"Attribute","startLoc":122,"text":"self._list"},{"attributeType":"null","col":8,"comment":"null","endLoc":121,"id":5665,"name":"_entered","nodeType":"Attribute","startLoc":121,"text":"self._entered"},{"col":4,"comment":"\n Ref #383. Python 3.3's namespace package messed with our import hooks\n Importing a module that didn't exist, even if the ImportError was\n gracefully handled, would make our test crash.\n\n Use recwarn here to silence this warning in Python 2.7:\n ImportWarning: Not importing directory '...\not_a_package': missing __init__.py\n ","endLoc":459,"header":"@pytest.mark.usefixtures(\"recwarn\")\n def test_namespace_import_doesnt_confuse_import_hook(self, testdir)","id":5666,"name":"test_namespace_import_doesnt_confuse_import_hook","nodeType":"Function","startLoc":435,"text":"@pytest.mark.usefixtures(\"recwarn\")\n def test_namespace_import_doesnt_confuse_import_hook(self, testdir):\n \"\"\"\n Ref #383. Python 3.3's namespace package messed with our import hooks\n Importing a module that didn't exist, even if the ImportError was\n gracefully handled, would make our test crash.\n\n Use recwarn here to silence this warning in Python 2.7:\n ImportWarning: Not importing directory '...\\not_a_package': missing __init__.py\n \"\"\"\n testdir.mkdir(\"not_a_package\")\n p = testdir.makepyfile(\n \"\"\"\n try:\n from not_a_package import doesnt_exist\n except ImportError:\n # We handle the import error gracefully here\n pass\n\n def test_whatever():\n pass\n \"\"\"\n )\n res = testdir.runpytest(p.basename)\n assert res.ret == 0"},{"attributeType":"function | function | function","col":27,"comment":"null","endLoc":187,"id":5667,"name":"_saved_warn","nodeType":"Attribute","startLoc":187,"text":"self._saved_warn"},{"col":4,"comment":"null","endLoc":467,"header":"def test_unknown_option(self, testdir)","id":5668,"name":"test_unknown_option","nodeType":"Function","startLoc":461,"text":"def test_unknown_option(self, testdir):\n result = testdir.runpytest(\"--qwlkej\")\n result.stderr.fnmatch_lines(\n \"\"\"\n *unrecognized*\n \"\"\"\n )"},{"col":4,"comment":"null","endLoc":486,"header":"def test_getsourcelines_error_issue553(self, testdir, monkeypatch)","id":5669,"name":"test_getsourcelines_error_issue553","nodeType":"Function","startLoc":469,"text":"def test_getsourcelines_error_issue553(self, testdir, monkeypatch):\n monkeypatch.setattr(\"inspect.getsourcelines\", None)\n p = testdir.makepyfile(\n \"\"\"\n def raise_error(obj):\n raise IOError('source code not available')\n\n import inspect\n inspect.getsourcelines = raise_error\n\n def test_foo(invalid_fixture):\n pass\n \"\"\"\n )\n res = testdir.runpytest(p)\n res.stdout.fnmatch_lines(\n [\"*source code not available*\", \"E*fixture 'invalid_fixture' not found\"]\n )"},{"col":4,"comment":"test that str values passed to main() as `plugins` arg\n are interpreted as module names to be imported and registered.\n #855.\n ","endLoc":501,"header":"def test_plugins_given_as_strings(self, tmpdir, monkeypatch, _sys_snapshot)","id":5670,"name":"test_plugins_given_as_strings","nodeType":"Function","startLoc":488,"text":"def test_plugins_given_as_strings(self, tmpdir, monkeypatch, _sys_snapshot):\n \"\"\"test that str values passed to main() as `plugins` arg\n are interpreted as module names to be imported and registered.\n #855.\n \"\"\"\n with pytest.raises(ImportError) as excinfo:\n pytest.main([str(tmpdir)], plugins=[\"invalid.module\"])\n assert \"invalid\" in str(excinfo.value)\n\n p = tmpdir.join(\"test_test_plugins_given_as_strings.py\")\n p.write(\"def test_foo(): pass\")\n mod = types.ModuleType(\"myplugin\")\n monkeypatch.setitem(sys.modules, \"myplugin\", mod)\n assert pytest.main(args=[str(tmpdir)], plugins=[\"myplugin\"]) == 0"},{"className":"TestWarningsRecorderChecker","col":0,"comment":"null","endLoc":78,"id":5671,"nodeType":"Class","startLoc":34,"text":"class TestWarningsRecorderChecker(object):\n def test_recording(self):\n rec = WarningsRecorder()\n with rec:\n assert not rec.list\n warnings.warn_explicit(\"hello\", UserWarning, \"xyz\", 13)\n assert len(rec.list) == 1\n warnings.warn(DeprecationWarning(\"hello\"))\n assert len(rec.list) == 2\n warn = rec.pop()\n assert str(warn.message) == \"hello\"\n values = rec.list\n rec.clear()\n assert len(rec.list) == 0\n assert values is rec.list\n pytest.raises(AssertionError, rec.pop)\n\n def test_warn_stacklevel(self):\n \"\"\"#4243\"\"\"\n rec = WarningsRecorder()\n with rec:\n warnings.warn(\"test\", DeprecationWarning, 2)\n\n def test_typechecking(self):\n from _pytest.recwarn import WarningsChecker\n\n with pytest.raises(TypeError):\n WarningsChecker(5)\n with pytest.raises(TypeError):\n WarningsChecker((\"hi\", RuntimeWarning))\n with pytest.raises(TypeError):\n WarningsChecker([DeprecationWarning, RuntimeWarning])\n\n def test_invalid_enter_exit(self):\n # wrap this test in WarningsRecorder to ensure warning state gets reset\n with WarningsRecorder():\n with pytest.raises(RuntimeError):\n rec = WarningsRecorder()\n rec.__exit__(None, None, None) # can't exit before entering\n\n with pytest.raises(RuntimeError):\n rec = WarningsRecorder()\n with rec:\n with rec:\n pass # can't enter twice"},{"col":4,"comment":"null","endLoc":49,"header":"def test_recording(self)","id":5672,"name":"test_recording","nodeType":"Function","startLoc":35,"text":"def test_recording(self):\n rec = WarningsRecorder()\n with rec:\n assert not rec.list\n warnings.warn_explicit(\"hello\", UserWarning, \"xyz\", 13)\n assert len(rec.list) == 1\n warnings.warn(DeprecationWarning(\"hello\"))\n assert len(rec.list) == 2\n warn = rec.pop()\n assert str(warn.message) == \"hello\"\n values = rec.list\n rec.clear()\n assert len(rec.list) == 0\n assert values is rec.list\n pytest.raises(AssertionError, rec.pop)"},{"col":4,"comment":"null","endLoc":126,"header":"def getexplanation(self)","id":5673,"name":"getexplanation","nodeType":"Function","startLoc":119,"text":"def getexplanation(self):\n expl = getattr(self, \"reason\", None) or self.get(\"reason\", None)\n if not expl:\n if not hasattr(self, \"expr\"):\n return \"\"\n else:\n return \"condition: \" + str(self.expr)\n return expl"},{"className":"ArgumentError","col":0,"comment":"\n Raised if an Argument instance is created with invalid or\n inconsistent arguments.\n ","endLoc":150,"id":5674,"nodeType":"Class","startLoc":136,"text":"class ArgumentError(Exception):\n \"\"\"\n Raised if an Argument instance is created with invalid or\n inconsistent arguments.\n \"\"\"\n\n def __init__(self, msg, option):\n self.msg = msg\n self.option_id = str(option)\n\n def __str__(self):\n if self.option_id:\n return \"option %s: %s\" % (self.option_id, self.msg)\n else:\n return self.msg"},{"col":4,"comment":"null","endLoc":150,"header":"def __str__(self)","id":5675,"name":"__str__","nodeType":"Function","startLoc":146,"text":"def __str__(self):\n if self.option_id:\n return \"option %s: %s\" % (self.option_id, self.msg)\n else:\n return self.msg"},{"attributeType":"null","col":8,"comment":"null","endLoc":143,"id":5676,"name":"msg","nodeType":"Attribute","startLoc":143,"text":"self.msg"},{"attributeType":"str","col":8,"comment":"null","endLoc":144,"id":5677,"name":"option_id","nodeType":"Attribute","startLoc":144,"text":"self.option_id"},{"col":0,"comment":"It should behave the same with and without output capturing (#4861).","endLoc":1579,"header":"def test_typeerror_encodedfile_write(testdir)","id":5678,"name":"test_typeerror_encodedfile_write","nodeType":"Function","startLoc":1559,"text":"def test_typeerror_encodedfile_write(testdir):\n \"\"\"It should behave the same with and without output capturing (#4861).\"\"\"\n p = testdir.makepyfile(\n \"\"\"\n def test_fails():\n import sys\n sys.stdout.write(b\"foo\")\n \"\"\"\n )\n result_without_capture = testdir.runpytest(\"-s\", str(p))\n\n result_with_capture = testdir.runpytest(str(p))\n\n assert result_with_capture.ret == result_without_capture.ret\n\n if _PY3:\n result_with_capture.stdout.fnmatch_lines(\n [\"E TypeError: write() argument must be str, not bytes\"]\n )\n else:\n assert result_with_capture.ret == 0"},{"className":"Argument","col":0,"comment":"class that mimics the necessary behaviour of optparse.Option\n\n it's currently a least effort implementation\n and ignoring choices and integer prefixes\n https://docs.python.org/3/library/optparse.html#optparse-standard-option-types\n ","endLoc":282,"id":5679,"nodeType":"Class","startLoc":153,"text":"class Argument(object):\n \"\"\"class that mimics the necessary behaviour of optparse.Option\n\n it's currently a least effort implementation\n and ignoring choices and integer prefixes\n https://docs.python.org/3/library/optparse.html#optparse-standard-option-types\n \"\"\"\n\n _typ_map = {\"int\": int, \"string\": str, \"float\": float, \"complex\": complex}\n\n def __init__(self, *names, **attrs):\n \"\"\"store parms in private vars for use in add_argument\"\"\"\n self._attrs = attrs\n self._short_opts = []\n self._long_opts = []\n self.dest = attrs.get(\"dest\")\n if \"%default\" in (attrs.get(\"help\") or \"\"):\n warnings.warn(\n 'pytest now uses argparse. \"%default\" should be'\n ' changed to \"%(default)s\" ',\n DeprecationWarning,\n stacklevel=3,\n )\n try:\n typ = attrs[\"type\"]\n except KeyError:\n pass\n else:\n # this might raise a keyerror as well, don't want to catch that\n if isinstance(typ, six.string_types):\n if typ == \"choice\":\n warnings.warn(\n \"`type` argument to addoption() is the string %r.\"\n \" For choices this is optional and can be omitted, \"\n \" but when supplied should be a type (for example `str` or `int`).\"\n \" (options: %s)\" % (typ, names),\n DeprecationWarning,\n stacklevel=4,\n )\n # argparse expects a type here take it from\n # the type of the first element\n attrs[\"type\"] = type(attrs[\"choices\"][0])\n else:\n warnings.warn(\n \"`type` argument to addoption() is the string %r, \"\n \" but when supplied should be a type (for example `str` or `int`).\"\n \" (options: %s)\" % (typ, names),\n DeprecationWarning,\n stacklevel=4,\n )\n attrs[\"type\"] = Argument._typ_map[typ]\n # used in test_parseopt -> test_parse_defaultgetter\n self.type = attrs[\"type\"]\n else:\n self.type = typ\n try:\n # attribute existence is tested in Config._processopt\n self.default = attrs[\"default\"]\n except KeyError:\n pass\n self._set_opt_strings(names)\n if not self.dest:\n if self._long_opts:\n self.dest = self._long_opts[0][2:].replace(\"-\", \"_\")\n else:\n try:\n self.dest = self._short_opts[0][1:]\n except IndexError:\n raise ArgumentError(\"need a long or short option\", self)\n\n def names(self):\n return self._short_opts + self._long_opts\n\n def attrs(self):\n # update any attributes set by processopt\n attrs = \"default dest help\".split()\n if self.dest:\n attrs.append(self.dest)\n for attr in attrs:\n try:\n self._attrs[attr] = getattr(self, attr)\n except AttributeError:\n pass\n if self._attrs.get(\"help\"):\n a = self._attrs[\"help\"]\n a = a.replace(\"%default\", \"%(default)s\")\n # a = a.replace('%prog', '%(prog)s')\n self._attrs[\"help\"] = a\n return self._attrs\n\n def _set_opt_strings(self, opts):\n \"\"\"directly from optparse\n\n might not be necessary as this is passed to argparse later on\"\"\"\n for opt in opts:\n if len(opt) < 2:\n raise ArgumentError(\n \"invalid option string %r: \"\n \"must be at least two characters long\" % opt,\n self,\n )\n elif len(opt) == 2:\n if not (opt[0] == \"-\" and opt[1] != \"-\"):\n raise ArgumentError(\n \"invalid short option string %r: \"\n \"must be of the form -x, (x any non-dash char)\" % opt,\n self,\n )\n self._short_opts.append(opt)\n else:\n if not (opt[0:2] == \"--\" and opt[2] != \"-\"):\n raise ArgumentError(\n \"invalid long option string %r: \"\n \"must start with --, followed by non-dash\" % opt,\n self,\n )\n self._long_opts.append(opt)\n\n def __repr__(self):\n args = []\n if self._short_opts:\n args += [\"_short_opts: \" + repr(self._short_opts)]\n if self._long_opts:\n args += [\"_long_opts: \" + repr(self._long_opts)]\n args += [\"dest: \" + repr(self.dest)]\n if hasattr(self, \"type\"):\n args += [\"type: \" + repr(self.type)]\n if hasattr(self, \"default\"):\n args += [\"default: \" + repr(self.default)]\n return \"Argument({})\".format(\", \".join(args))"},{"col":4,"comment":"null","endLoc":224,"header":"def names(self)","id":5680,"name":"names","nodeType":"Function","startLoc":223,"text":"def names(self):\n return self._short_opts + self._long_opts"},{"col":4,"comment":"null","endLoc":282,"header":"def __repr__(self)","id":5681,"name":"__repr__","nodeType":"Function","startLoc":271,"text":"def __repr__(self):\n args = []\n if self._short_opts:\n args += [\"_short_opts: \" + repr(self._short_opts)]\n if self._long_opts:\n args += [\"_long_opts: \" + repr(self._long_opts)]\n args += [\"dest: \" + repr(self.dest)]\n if hasattr(self, \"type\"):\n args += [\"type: \" + repr(self.type)]\n if hasattr(self, \"default\"):\n args += [\"default: \" + repr(self.default)]\n return \"Argument({})\".format(\", \".join(args))"},{"attributeType":"null","col":0,"comment":"null","endLoc":28,"id":5682,"name":"needsosdup","nodeType":"Attribute","startLoc":28,"text":"needsosdup"},{"col":0,"comment":"","endLoc":2,"header":"test_capture.py#","id":5683,"name":"","nodeType":"Function","startLoc":2,"text":"needsosdup = pytest.mark.skipif(\n not hasattr(os, \"dup\"), reason=\"test needs os.dup, not available on this platform\"\n)"},{"col":4,"comment":"null","endLoc":514,"header":"def test_parametrized_with_bytes_regex(self, testdir)","id":5684,"name":"test_parametrized_with_bytes_regex","nodeType":"Function","startLoc":503,"text":"def test_parametrized_with_bytes_regex(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import re\n import pytest\n @pytest.mark.parametrize('r', [re.compile(b'foo')])\n def test_stuff(r):\n pass\n \"\"\"\n )\n res = testdir.runpytest(p)\n res.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":4,"comment":"Test parametrization with values that contain null bytes and unicode characters (#2644, #2957)","endLoc":529,"header":"def test_parametrized_with_null_bytes(self, testdir)","id":5685,"name":"test_parametrized_with_null_bytes","nodeType":"Function","startLoc":516,"text":"def test_parametrized_with_null_bytes(self, testdir):\n \"\"\"Test parametrization with values that contain null bytes and unicode characters (#2644, #2957)\"\"\"\n p = testdir.makepyfile(\n u\"\"\"\n # encoding: UTF-8\n import pytest\n\n @pytest.mark.parametrize(\"data\", [b\"\\\\x00\", \"\\\\x00\", u'ação'])\n def test_foo(data):\n assert data\n \"\"\"\n )\n res = testdir.runpytest(p)\n res.assert_outcomes(passed=3)"},{"className":"TestInvocationVariants","col":0,"comment":"null","endLoc":883,"id":5686,"nodeType":"Class","startLoc":532,"text":"class TestInvocationVariants(object):\n def test_earlyinit(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n assert hasattr(pytest, 'mark')\n \"\"\"\n )\n result = testdir.runpython(p)\n assert result.ret == 0\n\n @pytest.mark.xfail(\"sys.platform.startswith('java')\")\n def test_pydoc(self, testdir):\n for name in (\"py.test\", \"pytest\"):\n result = testdir.runpython_c(\"import {};help({})\".format(name, name))\n assert result.ret == 0\n s = result.stdout.str()\n assert \"MarkGenerator\" in s\n\n def test_import_star_py_dot_test(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n from py.test import *\n #collect\n #cmdline\n #Item\n # assert collect.Item is Item\n # assert collect.Collector is Collector\n main\n skip\n xfail\n \"\"\"\n )\n result = testdir.runpython(p)\n assert result.ret == 0\n\n def test_import_star_pytest(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n from pytest import *\n #Item\n #File\n main\n skip\n xfail\n \"\"\"\n )\n result = testdir.runpython(p)\n assert result.ret == 0\n\n def test_double_pytestcmdline(self, testdir):\n p = testdir.makepyfile(\n run=\"\"\"\n import pytest\n pytest.main()\n pytest.main()\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n pass\n \"\"\"\n )\n result = testdir.runpython(p)\n result.stdout.fnmatch_lines([\"*1 passed*\", \"*1 passed*\"])\n\n def test_python_minus_m_invocation_ok(self, testdir):\n p1 = testdir.makepyfile(\"def test_hello(): pass\")\n res = testdir.run(sys.executable, \"-m\", \"pytest\", str(p1))\n assert res.ret == 0\n\n def test_python_minus_m_invocation_fail(self, testdir):\n p1 = testdir.makepyfile(\"def test_fail(): 0/0\")\n res = testdir.run(sys.executable, \"-m\", \"pytest\", str(p1))\n assert res.ret == 1\n\n def test_python_pytest_package(self, testdir):\n p1 = testdir.makepyfile(\"def test_pass(): pass\")\n res = testdir.run(sys.executable, \"-m\", \"pytest\", str(p1))\n assert res.ret == 0\n res.stdout.fnmatch_lines([\"*1 passed*\"])\n\n def test_equivalence_pytest_pytest(self):\n assert pytest.main == py.test.cmdline.main\n\n def test_invoke_with_invalid_type(self, capsys):\n with pytest.raises(\n TypeError, match=\"expected to be a list or tuple of strings, got: '-h'\"\n ):\n pytest.main(\"-h\")\n\n def test_invoke_with_path(self, tmpdir, capsys):\n retcode = pytest.main(tmpdir)\n assert retcode == EXIT_NOTESTSCOLLECTED\n out, err = capsys.readouterr()\n\n def test_invoke_plugin_api(self, testdir, capsys):\n class MyPlugin(object):\n def pytest_addoption(self, parser):\n parser.addoption(\"--myopt\")\n\n pytest.main([\"-h\"], plugins=[MyPlugin()])\n out, err = capsys.readouterr()\n assert \"--myopt\" in out\n\n def test_pyargs_importerror(self, testdir, monkeypatch):\n monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", False)\n path = testdir.mkpydir(\"tpkg\")\n path.join(\"test_hello.py\").write(\"raise ImportError\")\n\n result = testdir.runpytest(\"--pyargs\", \"tpkg.test_hello\", syspathinsert=True)\n assert result.ret != 0\n\n result.stdout.fnmatch_lines([\"collected*0*items*/*1*errors\"])\n\n def test_cmdline_python_package(self, testdir, monkeypatch):\n import warnings\n\n monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", False)\n path = testdir.mkpydir(\"tpkg\")\n path.join(\"test_hello.py\").write(\"def test_hello(): pass\")\n path.join(\"test_world.py\").write(\"def test_world(): pass\")\n result = testdir.runpytest(\"--pyargs\", \"tpkg\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n result = testdir.runpytest(\"--pyargs\", \"tpkg.test_hello\", syspathinsert=True)\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n empty_package = testdir.mkpydir(\"empty_package\")\n monkeypatch.setenv(\"PYTHONPATH\", str(empty_package), prepend=os.pathsep)\n # the path which is not a package raises a warning on pypy;\n # no idea why only pypy and not normal python warn about it here\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", ImportWarning)\n result = testdir.runpytest(\"--pyargs\", \".\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n monkeypatch.setenv(\"PYTHONPATH\", str(testdir), prepend=os.pathsep)\n result = testdir.runpytest(\"--pyargs\", \"tpkg.test_missing\", syspathinsert=True)\n assert result.ret != 0\n result.stderr.fnmatch_lines([\"*not*found*test_missing*\"])\n\n def test_cmdline_python_namespace_package(self, testdir, monkeypatch):\n \"\"\"\n test --pyargs option with namespace packages (#1567)\n\n Ref: https://packaging.python.org/guides/packaging-namespace-packages/\n \"\"\"\n monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", raising=False)\n\n search_path = []\n for dirname in \"hello\", \"world\":\n d = testdir.mkdir(dirname)\n search_path.append(d)\n ns = d.mkdir(\"ns_pkg\")\n ns.join(\"__init__.py\").write(\n \"__import__('pkg_resources').declare_namespace(__name__)\"\n )\n lib = ns.mkdir(dirname)\n lib.ensure(\"__init__.py\")\n lib.join(\"test_{}.py\".format(dirname)).write(\n \"def test_{}(): pass\\ndef test_other():pass\".format(dirname)\n )\n\n # The structure of the test directory is now:\n # .\n # ├── hello\n # │ └── ns_pkg\n # │ ├── __init__.py\n # │ └── hello\n # │ ├── __init__.py\n # │ └── test_hello.py\n # └── world\n # └── ns_pkg\n # ├── __init__.py\n # └── world\n # ├── __init__.py\n # └── test_world.py\n\n # NOTE: the different/reversed ordering is intentional here.\n monkeypatch.setenv(\"PYTHONPATH\", prepend_pythonpath(*search_path))\n for p in search_path:\n monkeypatch.syspath_prepend(p)\n\n # mixed module and filenames:\n monkeypatch.chdir(\"world\")\n result = testdir.runpytest(\"--pyargs\", \"-v\", \"ns_pkg.hello\", \"ns_pkg/world\")\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n [\n \"test_hello.py::test_hello*PASSED*\",\n \"test_hello.py::test_other*PASSED*\",\n \"ns_pkg/world/test_world.py::test_world*PASSED*\",\n \"ns_pkg/world/test_world.py::test_other*PASSED*\",\n \"*4 passed in*\",\n ]\n )\n\n # specify tests within a module\n testdir.chdir()\n result = testdir.runpytest(\n \"--pyargs\", \"-v\", \"ns_pkg.world.test_world::test_other\"\n )\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n [\"*test_world.py::test_other*PASSED*\", \"*1 passed*\"]\n )\n\n def test_invoke_test_and_doctestmodules(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test():\n pass\n \"\"\"\n )\n result = testdir.runpytest(str(p) + \"::test\", \"--doctest-modules\")\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n @pytest.mark.skipif(not hasattr(os, \"symlink\"), reason=\"requires symlinks\")\n def test_cmdline_python_package_symlink(self, testdir, monkeypatch):\n \"\"\"\n test --pyargs option with packages with path containing symlink can\n have conftest.py in their package (#2985)\n \"\"\"\n # dummy check that we can actually create symlinks: on Windows `os.symlink` is available,\n # but normal users require special admin privileges to create symlinks.\n if sys.platform == \"win32\":\n try:\n os.symlink(\n str(testdir.tmpdir.ensure(\"tmpfile\")),\n str(testdir.tmpdir.join(\"tmpfile2\")),\n )\n except OSError as e:\n pytest.skip(six.text_type(e.args[0]))\n monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", raising=False)\n\n dirname = \"lib\"\n d = testdir.mkdir(dirname)\n foo = d.mkdir(\"foo\")\n foo.ensure(\"__init__.py\")\n lib = foo.mkdir(\"bar\")\n lib.ensure(\"__init__.py\")\n lib.join(\"test_bar.py\").write(\n \"def test_bar(): pass\\ndef test_other(a_fixture):pass\"\n )\n lib.join(\"conftest.py\").write(\n \"import pytest\\n@pytest.fixture\\ndef a_fixture():pass\"\n )\n\n d_local = testdir.mkdir(\"local\")\n symlink_location = os.path.join(str(d_local), \"lib\")\n if six.PY2:\n os.symlink(str(d), symlink_location)\n else:\n os.symlink(str(d), symlink_location, target_is_directory=True)\n\n # The structure of the test directory is now:\n # .\n # ├── local\n # │ └── lib -> ../lib\n # └── lib\n # └── foo\n # ├── __init__.py\n # └── bar\n # ├── __init__.py\n # ├── conftest.py\n # └── test_bar.py\n\n # NOTE: the different/reversed ordering is intentional here.\n search_path = [\"lib\", os.path.join(\"local\", \"lib\")]\n monkeypatch.setenv(\"PYTHONPATH\", prepend_pythonpath(*search_path))\n for p in search_path:\n monkeypatch.syspath_prepend(p)\n\n # module picked up in symlink-ed directory:\n # It picks up local/lib/foo/bar (symlink) via sys.path.\n result = testdir.runpytest(\"--pyargs\", \"-v\", \"foo.bar\")\n testdir.chdir()\n assert result.ret == 0\n if hasattr(py.path.local, \"mksymlinkto\"):\n result.stdout.fnmatch_lines(\n [\n \"lib/foo/bar/test_bar.py::test_bar PASSED*\",\n \"lib/foo/bar/test_bar.py::test_other PASSED*\",\n \"*2 passed*\",\n ]\n )\n else:\n result.stdout.fnmatch_lines(\n [\n \"*lib/foo/bar/test_bar.py::test_bar PASSED*\",\n \"*lib/foo/bar/test_bar.py::test_other PASSED*\",\n \"*2 passed*\",\n ]\n )\n\n def test_cmdline_python_package_not_exists(self, testdir):\n result = testdir.runpytest(\"--pyargs\", \"tpkgwhatv\")\n assert result.ret\n result.stderr.fnmatch_lines([\"ERROR*file*or*package*not*found*\"])\n\n @pytest.mark.xfail(reason=\"decide: feature or bug\")\n def test_noclass_discovery_if_not_testcase(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n class TestHello(object):\n def test_hello(self):\n assert self.attr\n\n class RealTest(unittest.TestCase, TestHello):\n attr = 42\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n reprec.assertoutcome(passed=1)\n\n def test_doctest_id(self, testdir):\n testdir.makefile(\n \".txt\",\n \"\"\"\n >>> x=3\n >>> x\n 4\n \"\"\",\n )\n result = testdir.runpytest(\"-rf\")\n lines = result.stdout.str().splitlines()\n for line in lines:\n if line.startswith((\"FAIL \", \"FAILED \")):\n _fail, _sep, testid = line.partition(\" \")\n break\n result = testdir.runpytest(testid, \"-rf\")\n result.stdout.fnmatch_lines(\n [\"FAILED test_doctest_id.txt::test_doctest_id.txt\", \"*1 failed*\"]\n )\n\n def test_core_backward_compatibility(self):\n \"\"\"Test backward compatibility for get_plugin_manager function. See #787.\"\"\"\n import _pytest.config\n\n assert (\n type(_pytest.config.get_plugin_manager())\n is _pytest.config.PytestPluginManager\n )\n\n def test_has_plugin(self, request):\n \"\"\"Test hasplugin function of the plugin manager (#932).\"\"\"\n assert request.config.pluginmanager.hasplugin(\"python\")"},{"col":4,"comment":"null","endLoc":541,"header":"def test_earlyinit(self, testdir)","id":5687,"name":"test_earlyinit","nodeType":"Function","startLoc":533,"text":"def test_earlyinit(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n assert hasattr(pytest, 'mark')\n \"\"\"\n )\n result = testdir.runpython(p)\n assert result.ret == 0"},{"col":4,"comment":"null","endLoc":549,"header":"@pytest.mark.xfail(\"sys.platform.startswith('java')\")\n def test_pydoc(self, testdir)","id":5688,"name":"test_pydoc","nodeType":"Function","startLoc":543,"text":"@pytest.mark.xfail(\"sys.platform.startswith('java')\")\n def test_pydoc(self, testdir):\n for name in (\"py.test\", \"pytest\"):\n result = testdir.runpython_c(\"import {};help({})\".format(name, name))\n assert result.ret == 0\n s = result.stdout.str()\n assert \"MarkGenerator\" in s"},{"attributeType":"function","col":4,"comment":"null","endLoc":37,"id":5689,"name":"__nonzero__","nodeType":"Attribute","startLoc":37,"text":"__nonzero__"},{"col":4,"comment":"null","endLoc":566,"header":"def test_import_star_py_dot_test(self, testdir)","id":5690,"name":"test_import_star_py_dot_test","nodeType":"Function","startLoc":551,"text":"def test_import_star_py_dot_test(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n from py.test import *\n #collect\n #cmdline\n #Item\n # assert collect.Item is Item\n # assert collect.Collector is Collector\n main\n skip\n xfail\n \"\"\"\n )\n result = testdir.runpython(p)\n assert result.ret == 0"},{"attributeType":"null","col":12,"comment":"null","endLoc":80,"id":5691,"name":"result","nodeType":"Attribute","startLoc":80,"text":"self.result"},{"col":4,"comment":"null","endLoc":580,"header":"def test_import_star_pytest(self, testdir)","id":5692,"name":"test_import_star_pytest","nodeType":"Function","startLoc":568,"text":"def test_import_star_pytest(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n from pytest import *\n #Item\n #File\n main\n skip\n xfail\n \"\"\"\n )\n result = testdir.runpython(p)\n assert result.ret == 0"},{"col":4,"comment":"null","endLoc":597,"header":"def test_double_pytestcmdline(self, testdir)","id":5693,"name":"test_double_pytestcmdline","nodeType":"Function","startLoc":582,"text":"def test_double_pytestcmdline(self, testdir):\n p = testdir.makepyfile(\n run=\"\"\"\n import pytest\n pytest.main()\n pytest.main()\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n pass\n \"\"\"\n )\n result = testdir.runpython(p)\n result.stdout.fnmatch_lines([\"*1 passed*\", \"*1 passed*\"])"},{"col":4,"comment":"null","endLoc":602,"header":"def test_python_minus_m_invocation_ok(self, testdir)","id":5694,"name":"test_python_minus_m_invocation_ok","nodeType":"Function","startLoc":599,"text":"def test_python_minus_m_invocation_ok(self, testdir):\n p1 = testdir.makepyfile(\"def test_hello(): pass\")\n res = testdir.run(sys.executable, \"-m\", \"pytest\", str(p1))\n assert res.ret == 0"},{"attributeType":"null","col":8,"comment":"null","endLoc":30,"id":5695,"name":"_mark","nodeType":"Attribute","startLoc":30,"text":"self._mark"},{"attributeType":"null","col":12,"comment":"null","endLoc":55,"id":5696,"name":"exc","nodeType":"Attribute","startLoc":55,"text":"self.exc"},{"attributeType":"null","col":24,"comment":"null","endLoc":104,"id":5697,"name":"reason","nodeType":"Attribute","startLoc":104,"text":"self.reason"},{"attributeType":"str","col":4,"comment":"null","endLoc":904,"id":5698,"name":"entrysep","nodeType":"Attribute","startLoc":904,"text":"entrysep"},{"attributeType":"null","col":8,"comment":"null","endLoc":907,"id":5699,"name":"reprentries","nodeType":"Attribute","startLoc":907,"text":"self.reprentries"},{"attributeType":"null","col":8,"comment":"null","endLoc":908,"id":5700,"name":"extraline","nodeType":"Attribute","startLoc":908,"text":"self.extraline"},{"attributeType":"null","col":8,"comment":"null","endLoc":909,"id":5701,"name":"style","nodeType":"Attribute","startLoc":909,"text":"self.style"},{"attributeType":"null","col":8,"comment":"null","endLoc":28,"id":5702,"name":"item","nodeType":"Attribute","startLoc":28,"text":"self.item"},{"attributeType":"null","col":20,"comment":"null","endLoc":89,"id":5703,"name":"expr","nodeType":"Attribute","startLoc":89,"text":"self.expr"},{"attributeType":"null","col":8,"comment":"null","endLoc":29,"id":5704,"name":"_marks","nodeType":"Attribute","startLoc":29,"text":"self._marks"},{"className":"ReprTracebackNative","col":0,"comment":"null","endLoc":934,"id":5705,"nodeType":"Class","startLoc":930,"text":"class ReprTracebackNative(ReprTraceback):\n def __init__(self, tblines):\n self.style = \"native\"\n self.reprentries = [ReprEntryNative(tblines)]\n self.extraline = None"},{"attributeType":"list","col":8,"comment":"null","endLoc":933,"id":5706,"name":"reprentries","nodeType":"Attribute","startLoc":933,"text":"self.reprentries"},{"col":4,"comment":"#4243","endLoc":55,"header":"def test_warn_stacklevel(self)","id":5707,"name":"test_warn_stacklevel","nodeType":"Function","startLoc":51,"text":"def test_warn_stacklevel(self):\n \"\"\"#4243\"\"\"\n rec = WarningsRecorder()\n with rec:\n warnings.warn(\"test\", DeprecationWarning, 2)"},{"attributeType":"TypedDict","col":4,"comment":"null","endLoc":161,"id":5708,"name":"_typ_map","nodeType":"Attribute","startLoc":161,"text":"_typ_map"},{"attributeType":"null","col":8,"comment":"null","endLoc":31,"id":5709,"name":"_mark_name","nodeType":"Attribute","startLoc":31,"text":"self._mark_name"},{"attributeType":"list","col":8,"comment":"null","endLoc":166,"id":5710,"name":"_short_opts","nodeType":"Attribute","startLoc":166,"text":"self._short_opts"},{"attributeType":"null","col":12,"comment":"null","endLoc":210,"id":5711,"name":"default","nodeType":"Attribute","startLoc":210,"text":"self.default"},{"col":0,"comment":"null","endLoc":92,"header":"@hookimpl(tryfirst=True)\ndef pytest_runtest_setup(item)","id":5712,"name":"pytest_runtest_setup","nodeType":"Function","startLoc":73,"text":"@hookimpl(tryfirst=True)\ndef pytest_runtest_setup(item):\n # Check if skip or skipif are specified as pytest marks\n item._skipped_by_mark = False\n eval_skipif = MarkEvaluator(item, \"skipif\")\n if eval_skipif.istrue():\n item._skipped_by_mark = True\n skip(eval_skipif.getexplanation())\n\n for skip_info in item.iter_markers(name=\"skip\"):\n item._skipped_by_mark = True\n if \"reason\" in skip_info.kwargs:\n skip(skip_info.kwargs[\"reason\"])\n elif skip_info.args:\n skip(skip_info.args[0])\n else:\n skip(\"unconditional skip\")\n\n item._evalxfail = MarkEvaluator(item, \"xfail\")\n check_xfail_no_run(item)"},{"attributeType":"None","col":8,"comment":"null","endLoc":934,"id":5713,"name":"extraline","nodeType":"Attribute","startLoc":934,"text":"self.extraline"},{"col":4,"comment":"null","endLoc":65,"header":"def test_typechecking(self)","id":5714,"name":"test_typechecking","nodeType":"Function","startLoc":57,"text":"def test_typechecking(self):\n from _pytest.recwarn import WarningsChecker\n\n with pytest.raises(TypeError):\n WarningsChecker(5)\n with pytest.raises(TypeError):\n WarningsChecker((\"hi\", RuntimeWarning))\n with pytest.raises(TypeError):\n WarningsChecker([DeprecationWarning, RuntimeWarning])"},{"attributeType":"str","col":8,"comment":"null","endLoc":932,"id":5715,"name":"style","nodeType":"Attribute","startLoc":932,"text":"self.style"},{"attributeType":"list","col":8,"comment":"null","endLoc":167,"id":5716,"name":"_long_opts","nodeType":"Attribute","startLoc":167,"text":"self._long_opts"},{"attributeType":"dict","col":8,"comment":"null","endLoc":165,"id":5717,"name":"_attrs","nodeType":"Attribute","startLoc":165,"text":"self._attrs"},{"attributeType":"null","col":20,"comment":"null","endLoc":219,"id":5718,"name":"dest","nodeType":"Attribute","startLoc":219,"text":"self.dest"},{"attributeType":"null","col":16,"comment":"null","endLoc":207,"id":5719,"name":"type","nodeType":"Attribute","startLoc":207,"text":"self.type"},{"className":"ReprEntryNative","col":0,"comment":"null","endLoc":944,"id":5720,"nodeType":"Class","startLoc":937,"text":"class ReprEntryNative(TerminalRepr):\n style = \"native\"\n\n def __init__(self, tblines):\n self.lines = tblines\n\n def toterminal(self, tw):\n tw.write(\"\".join(self.lines))"},{"col":4,"comment":"null","endLoc":944,"header":"def toterminal(self, tw)","id":5721,"name":"toterminal","nodeType":"Function","startLoc":943,"text":"def toterminal(self, tw):\n tw.write(\"\".join(self.lines))"},{"col":4,"comment":"null","endLoc":607,"header":"def test_python_minus_m_invocation_fail(self, testdir)","id":5722,"name":"test_python_minus_m_invocation_fail","nodeType":"Function","startLoc":604,"text":"def test_python_minus_m_invocation_fail(self, testdir):\n p1 = testdir.makepyfile(\"def test_fail(): 0/0\")\n res = testdir.run(sys.executable, \"-m\", \"pytest\", str(p1))\n assert res.ret == 1"},{"className":"OptionGroup","col":0,"comment":"null","endLoc":319,"id":5723,"nodeType":"Class","startLoc":285,"text":"class OptionGroup(object):\n def __init__(self, name, description=\"\", parser=None):\n self.name = name\n self.description = description\n self.options = []\n self.parser = parser\n\n def addoption(self, *optnames, **attrs):\n \"\"\" add an option to this group.\n\n if a shortened version of a long option is specified it will\n be suppressed in the help. addoption('--twowords', '--two-words')\n results in help showing '--two-words' only, but --twowords gets\n accepted **and** the automatic destination is in args.twowords\n \"\"\"\n conflict = set(optnames).intersection(\n name for opt in self.options for name in opt.names()\n )\n if conflict:\n raise ValueError(\"option names %s already added\" % conflict)\n option = Argument(*optnames, **attrs)\n self._addoption_instance(option, shortupper=False)\n\n def _addoption(self, *optnames, **attrs):\n option = Argument(*optnames, **attrs)\n self._addoption_instance(option, shortupper=True)\n\n def _addoption_instance(self, option, shortupper=False):\n if not shortupper:\n for opt in option._short_opts:\n if opt[0] == \"-\" and opt[1].islower():\n raise ValueError(\"lowercase shortoptions reserved\")\n if self.parser:\n self.parser.processoption(option)\n self.options.append(option)"},{"col":4,"comment":"null","endLoc":310,"header":"def _addoption(self, *optnames, **attrs)","id":5724,"name":"_addoption","nodeType":"Function","startLoc":308,"text":"def _addoption(self, *optnames, **attrs):\n option = Argument(*optnames, **attrs)\n self._addoption_instance(option, shortupper=True)"},{"col":0,"comment":"check xfail(run=False)","endLoc":110,"header":"def check_xfail_no_run(item)","id":5725,"name":"check_xfail_no_run","nodeType":"Function","startLoc":104,"text":"def check_xfail_no_run(item):\n \"\"\"check xfail(run=False)\"\"\"\n if not item.config.option.runxfail:\n evalxfail = item._evalxfail\n if evalxfail.istrue():\n if not evalxfail.get(\"run\", True):\n xfail(\"[NOTRUN] \" + evalxfail.getexplanation())"},{"className":"TestEvaluator","col":0,"comment":"null","endLoc":152,"id":5726,"nodeType":"Class","startLoc":14,"text":"class TestEvaluator(object):\n def test_no_marker(self, testdir):\n item = testdir.getitem(\"def test_func(): pass\")\n evalskipif = MarkEvaluator(item, \"skipif\")\n assert not evalskipif\n assert not evalskipif.istrue()\n\n def test_marked_no_args(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xyz\n def test_func():\n pass\n \"\"\"\n )\n ev = MarkEvaluator(item, \"xyz\")\n assert ev\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"\"\n assert not ev.get(\"run\", False)\n\n def test_marked_one_arg(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xyz(\"hasattr(os, 'sep')\")\n def test_func():\n pass\n \"\"\"\n )\n ev = MarkEvaluator(item, \"xyz\")\n assert ev\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"condition: hasattr(os, 'sep')\"\n\n @pytest.mark.skipif(\"sys.version_info[0] >= 3\")\n def test_marked_one_arg_unicode(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xyz(u\"hasattr(os, 'sep')\")\n def test_func():\n pass\n \"\"\"\n )\n ev = MarkEvaluator(item, \"xyz\")\n assert ev\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"condition: hasattr(os, 'sep')\"\n\n def test_marked_one_arg_with_reason(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xyz(\"hasattr(os, 'sep')\", attr=2, reason=\"hello world\")\n def test_func():\n pass\n \"\"\"\n )\n ev = MarkEvaluator(item, \"xyz\")\n assert ev\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"hello world\"\n assert ev.get(\"attr\") == 2\n\n def test_marked_one_arg_twice(self, testdir):\n lines = [\n \"\"\"@pytest.mark.skipif(\"not hasattr(os, 'murks')\")\"\"\",\n \"\"\"@pytest.mark.skipif(\"hasattr(os, 'murks')\")\"\"\",\n ]\n for i in range(0, 2):\n item = testdir.getitem(\n \"\"\"\n import pytest\n %s\n %s\n def test_func():\n pass\n \"\"\"\n % (lines[i], lines[(i + 1) % 2])\n )\n ev = MarkEvaluator(item, \"skipif\")\n assert ev\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"condition: not hasattr(os, 'murks')\"\n\n def test_marked_one_arg_twice2(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.skipif(\"hasattr(os, 'murks')\")\n @pytest.mark.skipif(\"not hasattr(os, 'murks')\")\n def test_func():\n pass\n \"\"\"\n )\n ev = MarkEvaluator(item, \"skipif\")\n assert ev\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"condition: not hasattr(os, 'murks')\"\n\n def test_marked_skip_with_not_string(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.skipif(False)\n def test_func():\n pass\n \"\"\"\n )\n ev = MarkEvaluator(item, \"skipif\")\n exc = pytest.raises(pytest.fail.Exception, ev.istrue)\n assert (\n \"\"\"Failed: you need to specify reason=STRING when using booleans as conditions.\"\"\"\n in exc.value.msg\n )\n\n def test_skipif_class(self, testdir):\n item, = testdir.getitems(\n \"\"\"\n import pytest\n class TestClass(object):\n pytestmark = pytest.mark.skipif(\"config._hackxyz\")\n def test_func(self):\n pass\n \"\"\"\n )\n item.config._hackxyz = 3\n ev = MarkEvaluator(item, \"skipif\")\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"condition: config._hackxyz\""},{"attributeType":"str","col":4,"comment":"null","endLoc":938,"id":5727,"name":"style","nodeType":"Attribute","startLoc":938,"text":"style"},{"attributeType":"null","col":8,"comment":"null","endLoc":941,"id":5728,"name":"lines","nodeType":"Attribute","startLoc":941,"text":"self.lines"},{"col":4,"comment":"null","endLoc":19,"header":"def test_no_marker(self, testdir)","id":5729,"name":"test_no_marker","nodeType":"Function","startLoc":15,"text":"def test_no_marker(self, testdir):\n item = testdir.getitem(\"def test_func(): pass\")\n evalskipif = MarkEvaluator(item, \"skipif\")\n assert not evalskipif\n assert not evalskipif.istrue()"},{"className":"ReprEntry","col":0,"comment":"null","endLoc":977,"id":5730,"nodeType":"Class","startLoc":947,"text":"class ReprEntry(TerminalRepr):\n def __init__(self, lines, reprfuncargs, reprlocals, filelocrepr, style):\n self.lines = lines\n self.reprfuncargs = reprfuncargs\n self.reprlocals = reprlocals\n self.reprfileloc = filelocrepr\n self.style = style\n\n def toterminal(self, tw):\n if self.style == \"short\":\n self.reprfileloc.toterminal(tw)\n for line in self.lines:\n red = line.startswith(\"E \")\n tw.line(line, bold=True, red=red)\n # tw.line(\"\")\n return\n if self.reprfuncargs:\n self.reprfuncargs.toterminal(tw)\n for line in self.lines:\n red = line.startswith(\"E \")\n tw.line(line, bold=True, red=red)\n if self.reprlocals:\n tw.line(\"\")\n self.reprlocals.toterminal(tw)\n if self.reprfileloc:\n if self.lines:\n tw.line(\"\")\n self.reprfileloc.toterminal(tw)\n\n def __str__(self):\n return \"%s\\n%s\\n%s\" % (\"\\n\".join(self.lines), self.reprlocals, self.reprfileloc)"},{"col":4,"comment":"null","endLoc":974,"header":"def toterminal(self, tw)","id":5731,"name":"toterminal","nodeType":"Function","startLoc":955,"text":"def toterminal(self, tw):\n if self.style == \"short\":\n self.reprfileloc.toterminal(tw)\n for line in self.lines:\n red = line.startswith(\"E \")\n tw.line(line, bold=True, red=red)\n # tw.line(\"\")\n return\n if self.reprfuncargs:\n self.reprfuncargs.toterminal(tw)\n for line in self.lines:\n red = line.startswith(\"E \")\n tw.line(line, bold=True, red=red)\n if self.reprlocals:\n tw.line(\"\")\n self.reprlocals.toterminal(tw)\n if self.reprfileloc:\n if self.lines:\n tw.line(\"\")\n self.reprfileloc.toterminal(tw)"},{"fileName":"test_reporting.py","filePath":"testing/logging","id":5732,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport os\nimport re\nfrom io import open\n\nimport six\n\nimport pytest\n\n\ndef test_nothing_logged(testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n\n def test_foo():\n sys.stdout.write('text going to stdout')\n sys.stderr.write('text going to stderr')\n assert False\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines([\"*- Captured stdout call -*\", \"text going to stdout\"])\n result.stdout.fnmatch_lines([\"*- Captured stderr call -*\", \"text going to stderr\"])\n with pytest.raises(pytest.fail.Exception):\n result.stdout.fnmatch_lines([\"*- Captured *log call -*\"])\n\n\ndef test_messages_logged(testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n import logging\n\n logger = logging.getLogger(__name__)\n\n def test_foo():\n sys.stdout.write('text going to stdout')\n sys.stderr.write('text going to stderr')\n logger.info('text going to logger')\n assert False\n \"\"\"\n )\n result = testdir.runpytest(\"--log-level=INFO\")\n assert result.ret == 1\n result.stdout.fnmatch_lines([\"*- Captured *log call -*\", \"*text going to logger*\"])\n result.stdout.fnmatch_lines([\"*- Captured stdout call -*\", \"text going to stdout\"])\n result.stdout.fnmatch_lines([\"*- Captured stderr call -*\", \"text going to stderr\"])\n\n\ndef test_root_logger_affected(testdir):\n testdir.makepyfile(\n \"\"\"\n import logging\n logger = logging.getLogger()\n\n def test_foo():\n logger.info('info text ' + 'going to logger')\n logger.warning('warning text ' + 'going to logger')\n logger.error('error text ' + 'going to logger')\n\n assert 0\n \"\"\"\n )\n log_file = testdir.tmpdir.join(\"pytest.log\").strpath\n result = testdir.runpytest(\"--log-level=ERROR\", \"--log-file=pytest.log\")\n assert result.ret == 1\n\n # The capture log calls in the stdout section only contain the\n # logger.error msg, because of --log-level=ERROR.\n result.stdout.fnmatch_lines([\"*error text going to logger*\"])\n stdout = result.stdout.str()\n assert \"warning text going to logger\" not in stdout\n assert \"info text going to logger\" not in stdout\n\n # The log file should contain the warning and the error log messages and\n # not the info one, because the default level of the root logger is\n # WARNING.\n assert os.path.isfile(log_file)\n with open(log_file) as rfh:\n contents = rfh.read()\n assert \"info text going to logger\" not in contents\n assert \"warning text going to logger\" in contents\n assert \"error text going to logger\" in contents\n\n\ndef test_log_cli_level_log_level_interaction(testdir):\n testdir.makepyfile(\n \"\"\"\n import logging\n logger = logging.getLogger()\n\n def test_foo():\n logger.debug('debug text ' + 'going to logger')\n logger.info('info text ' + 'going to logger')\n logger.warning('warning text ' + 'going to logger')\n logger.error('error text ' + 'going to logger')\n assert 0\n \"\"\"\n )\n\n result = testdir.runpytest(\"--log-cli-level=INFO\", \"--log-level=ERROR\")\n assert result.ret == 1\n\n result.stdout.fnmatch_lines(\n [\n \"*-- live log call --*\",\n \"*INFO*info text going to logger\",\n \"*WARNING*warning text going to logger\",\n \"*ERROR*error text going to logger\",\n \"=* 1 failed in *=\",\n ]\n )\n assert \"DEBUG\" not in result.stdout.str()\n\n\ndef test_setup_logging(testdir):\n testdir.makepyfile(\n \"\"\"\n import logging\n\n logger = logging.getLogger(__name__)\n\n def setup_function(function):\n logger.info('text going to logger from setup')\n\n def test_foo():\n logger.info('text going to logger from call')\n assert False\n \"\"\"\n )\n result = testdir.runpytest(\"--log-level=INFO\")\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\n \"*- Captured *log setup -*\",\n \"*text going to logger from setup*\",\n \"*- Captured *log call -*\",\n \"*text going to logger from call*\",\n ]\n )\n\n\ndef test_teardown_logging(testdir):\n testdir.makepyfile(\n \"\"\"\n import logging\n\n logger = logging.getLogger(__name__)\n\n def test_foo():\n logger.info('text going to logger from call')\n\n def teardown_function(function):\n logger.info('text going to logger from teardown')\n assert False\n \"\"\"\n )\n result = testdir.runpytest(\"--log-level=INFO\")\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\n \"*- Captured *log call -*\",\n \"*text going to logger from call*\",\n \"*- Captured *log teardown -*\",\n \"*text going to logger from teardown*\",\n ]\n )\n\n\ndef test_disable_log_capturing(testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n import logging\n\n logger = logging.getLogger(__name__)\n\n def test_foo():\n sys.stdout.write('text going to stdout')\n logger.warning('catch me if you can!')\n sys.stderr.write('text going to stderr')\n assert False\n \"\"\"\n )\n result = testdir.runpytest(\"--no-print-logs\")\n print(result.stdout)\n assert result.ret == 1\n result.stdout.fnmatch_lines([\"*- Captured stdout call -*\", \"text going to stdout\"])\n result.stdout.fnmatch_lines([\"*- Captured stderr call -*\", \"text going to stderr\"])\n with pytest.raises(pytest.fail.Exception):\n result.stdout.fnmatch_lines([\"*- Captured *log call -*\"])\n\n\ndef test_disable_log_capturing_ini(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n log_print=False\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import sys\n import logging\n\n logger = logging.getLogger(__name__)\n\n def test_foo():\n sys.stdout.write('text going to stdout')\n logger.warning('catch me if you can!')\n sys.stderr.write('text going to stderr')\n assert False\n \"\"\"\n )\n result = testdir.runpytest()\n print(result.stdout)\n assert result.ret == 1\n result.stdout.fnmatch_lines([\"*- Captured stdout call -*\", \"text going to stdout\"])\n result.stdout.fnmatch_lines([\"*- Captured stderr call -*\", \"text going to stderr\"])\n with pytest.raises(pytest.fail.Exception):\n result.stdout.fnmatch_lines([\"*- Captured *log call -*\"])\n\n\n@pytest.mark.parametrize(\"enabled\", [True, False])\ndef test_log_cli_enabled_disabled(testdir, enabled):\n msg = \"critical message logged by test\"\n testdir.makepyfile(\n \"\"\"\n import logging\n def test_log_cli():\n logging.critical(\"{}\")\n \"\"\".format(\n msg\n )\n )\n if enabled:\n testdir.makeini(\n \"\"\"\n [pytest]\n log_cli=true\n \"\"\"\n )\n result = testdir.runpytest()\n if enabled:\n result.stdout.fnmatch_lines(\n [\n \"test_log_cli_enabled_disabled.py::test_log_cli \",\n \"*-- live log call --*\",\n \"CRITICAL *test_log_cli_enabled_disabled.py* critical message logged by test\",\n \"PASSED*\",\n ]\n )\n else:\n assert msg not in result.stdout.str()\n\n\ndef test_log_cli_default_level(testdir):\n # Default log file level\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n def test_log_cli(request):\n plugin = request.config.pluginmanager.getplugin('logging-plugin')\n assert plugin.log_cli_handler.level == logging.NOTSET\n logging.getLogger('catchlog').info(\"INFO message won't be shown\")\n logging.getLogger('catchlog').warning(\"WARNING message will be shown\")\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n log_cli=true\n \"\"\"\n )\n\n result = testdir.runpytest()\n\n # fnmatch_lines does an assertion internally\n result.stdout.fnmatch_lines(\n [\n \"test_log_cli_default_level.py::test_log_cli \",\n \"WARNING*test_log_cli_default_level.py* message will be shown*\",\n ]\n )\n assert \"INFO message won't be shown\" not in result.stdout.str()\n # make sure that that we get a '0' exit code for the testsuite\n assert result.ret == 0\n\n\ndef test_log_cli_default_level_multiple_tests(testdir, request):\n \"\"\"Ensure we reset the first newline added by the live logger between tests\"\"\"\n filename = request.node.name + \".py\"\n testdir.makepyfile(\n \"\"\"\n import logging\n\n def test_log_1():\n logging.warning(\"log message from test_log_1\")\n\n def test_log_2():\n logging.warning(\"log message from test_log_2\")\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n log_cli=true\n \"\"\"\n )\n\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"{}::test_log_1 \".format(filename),\n \"*WARNING*log message from test_log_1*\",\n \"PASSED *50%*\",\n \"{}::test_log_2 \".format(filename),\n \"*WARNING*log message from test_log_2*\",\n \"PASSED *100%*\",\n \"=* 2 passed in *=\",\n ]\n )\n\n\ndef test_log_cli_default_level_sections(testdir, request):\n \"\"\"Check that with live logging enable we are printing the correct headers during\n start/setup/call/teardown/finish.\"\"\"\n filename = request.node.name + \".py\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n import logging\n\n def pytest_runtest_logstart():\n logging.warning('>>>>> START >>>>>')\n\n def pytest_runtest_logfinish():\n logging.warning('<<<<< END <<<<<<<')\n \"\"\"\n )\n\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n\n @pytest.fixture\n def fix(request):\n logging.warning(\"log message from setup of {}\".format(request.node.name))\n yield\n logging.warning(\"log message from teardown of {}\".format(request.node.name))\n\n def test_log_1(fix):\n logging.warning(\"log message from test_log_1\")\n\n def test_log_2(fix):\n logging.warning(\"log message from test_log_2\")\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n log_cli=true\n \"\"\"\n )\n\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"{}::test_log_1 \".format(filename),\n \"*-- live log start --*\",\n \"*WARNING* >>>>> START >>>>>*\",\n \"*-- live log setup --*\",\n \"*WARNING*log message from setup of test_log_1*\",\n \"*-- live log call --*\",\n \"*WARNING*log message from test_log_1*\",\n \"PASSED *50%*\",\n \"*-- live log teardown --*\",\n \"*WARNING*log message from teardown of test_log_1*\",\n \"*-- live log finish --*\",\n \"*WARNING* <<<<< END <<<<<<<*\",\n \"{}::test_log_2 \".format(filename),\n \"*-- live log start --*\",\n \"*WARNING* >>>>> START >>>>>*\",\n \"*-- live log setup --*\",\n \"*WARNING*log message from setup of test_log_2*\",\n \"*-- live log call --*\",\n \"*WARNING*log message from test_log_2*\",\n \"PASSED *100%*\",\n \"*-- live log teardown --*\",\n \"*WARNING*log message from teardown of test_log_2*\",\n \"*-- live log finish --*\",\n \"*WARNING* <<<<< END <<<<<<<*\",\n \"=* 2 passed in *=\",\n ]\n )\n\n\ndef test_live_logs_unknown_sections(testdir, request):\n \"\"\"Check that with live logging enable we are printing the correct headers during\n start/setup/call/teardown/finish.\"\"\"\n filename = request.node.name + \".py\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n import logging\n\n def pytest_runtest_protocol(item, nextitem):\n logging.warning('Unknown Section!')\n\n def pytest_runtest_logstart():\n logging.warning('>>>>> START >>>>>')\n\n def pytest_runtest_logfinish():\n logging.warning('<<<<< END <<<<<<<')\n \"\"\"\n )\n\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n\n @pytest.fixture\n def fix(request):\n logging.warning(\"log message from setup of {}\".format(request.node.name))\n yield\n logging.warning(\"log message from teardown of {}\".format(request.node.name))\n\n def test_log_1(fix):\n logging.warning(\"log message from test_log_1\")\n\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n log_cli=true\n \"\"\"\n )\n\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*WARNING*Unknown Section*\",\n \"{}::test_log_1 \".format(filename),\n \"*WARNING* >>>>> START >>>>>*\",\n \"*-- live log setup --*\",\n \"*WARNING*log message from setup of test_log_1*\",\n \"*-- live log call --*\",\n \"*WARNING*log message from test_log_1*\",\n \"PASSED *100%*\",\n \"*-- live log teardown --*\",\n \"*WARNING*log message from teardown of test_log_1*\",\n \"*WARNING* <<<<< END <<<<<<<*\",\n \"=* 1 passed in *=\",\n ]\n )\n\n\ndef test_sections_single_new_line_after_test_outcome(testdir, request):\n \"\"\"Check that only a single new line is written between log messages during\n teardown/finish.\"\"\"\n filename = request.node.name + \".py\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n import logging\n\n def pytest_runtest_logstart():\n logging.warning('>>>>> START >>>>>')\n\n def pytest_runtest_logfinish():\n logging.warning('<<<<< END <<<<<<<')\n logging.warning('<<<<< END <<<<<<<')\n \"\"\"\n )\n\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n\n @pytest.fixture\n def fix(request):\n logging.warning(\"log message from setup of {}\".format(request.node.name))\n yield\n logging.warning(\"log message from teardown of {}\".format(request.node.name))\n logging.warning(\"log message from teardown of {}\".format(request.node.name))\n\n def test_log_1(fix):\n logging.warning(\"log message from test_log_1\")\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n log_cli=true\n \"\"\"\n )\n\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"{}::test_log_1 \".format(filename),\n \"*-- live log start --*\",\n \"*WARNING* >>>>> START >>>>>*\",\n \"*-- live log setup --*\",\n \"*WARNING*log message from setup of test_log_1*\",\n \"*-- live log call --*\",\n \"*WARNING*log message from test_log_1*\",\n \"PASSED *100%*\",\n \"*-- live log teardown --*\",\n \"*WARNING*log message from teardown of test_log_1*\",\n \"*-- live log finish --*\",\n \"*WARNING* <<<<< END <<<<<<<*\",\n \"*WARNING* <<<<< END <<<<<<<*\",\n \"=* 1 passed in *=\",\n ]\n )\n assert (\n re.search(\n r\"(.+)live log teardown(.+)\\nWARNING(.+)\\nWARNING(.+)\",\n result.stdout.str(),\n re.MULTILINE,\n )\n is not None\n )\n assert (\n re.search(\n r\"(.+)live log finish(.+)\\nWARNING(.+)\\nWARNING(.+)\",\n result.stdout.str(),\n re.MULTILINE,\n )\n is not None\n )\n\n\ndef test_log_cli_level(testdir):\n # Default log file level\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n def test_log_cli(request):\n plugin = request.config.pluginmanager.getplugin('logging-plugin')\n assert plugin.log_cli_handler.level == logging.INFO\n logging.getLogger('catchlog').debug(\"This log message won't be shown\")\n logging.getLogger('catchlog').info(\"This log message will be shown\")\n print('PASSED')\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n log_cli=true\n \"\"\"\n )\n\n result = testdir.runpytest(\"-s\", \"--log-cli-level=INFO\")\n\n # fnmatch_lines does an assertion internally\n result.stdout.fnmatch_lines(\n [\n \"*test_log_cli_level.py*This log message will be shown\",\n \"PASSED\", # 'PASSED' on its own line because the log message prints a new line\n ]\n )\n assert \"This log message won't be shown\" not in result.stdout.str()\n\n # make sure that that we get a '0' exit code for the testsuite\n assert result.ret == 0\n\n result = testdir.runpytest(\"-s\", \"--log-level=INFO\")\n\n # fnmatch_lines does an assertion internally\n result.stdout.fnmatch_lines(\n [\n \"*test_log_cli_level.py* This log message will be shown\",\n \"PASSED\", # 'PASSED' on its own line because the log message prints a new line\n ]\n )\n assert \"This log message won't be shown\" not in result.stdout.str()\n\n # make sure that that we get a '0' exit code for the testsuite\n assert result.ret == 0\n\n\ndef test_log_cli_ini_level(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n log_cli=true\n log_cli_level = INFO\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n def test_log_cli(request):\n plugin = request.config.pluginmanager.getplugin('logging-plugin')\n assert plugin.log_cli_handler.level == logging.INFO\n logging.getLogger('catchlog').debug(\"This log message won't be shown\")\n logging.getLogger('catchlog').info(\"This log message will be shown\")\n print('PASSED')\n \"\"\"\n )\n\n result = testdir.runpytest(\"-s\")\n\n # fnmatch_lines does an assertion internally\n result.stdout.fnmatch_lines(\n [\n \"*test_log_cli_ini_level.py* This log message will be shown\",\n \"PASSED\", # 'PASSED' on its own line because the log message prints a new line\n ]\n )\n assert \"This log message won't be shown\" not in result.stdout.str()\n\n # make sure that that we get a '0' exit code for the testsuite\n assert result.ret == 0\n\n\n@pytest.mark.parametrize(\n \"cli_args\",\n [\"\", \"--log-level=WARNING\", \"--log-file-level=WARNING\", \"--log-cli-level=WARNING\"],\n)\ndef test_log_cli_auto_enable(testdir, request, cli_args):\n \"\"\"Check that live logs are enabled if --log-level or --log-cli-level is passed on the CLI.\n It should not be auto enabled if the same configs are set on the INI file.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import logging\n\n def test_log_1():\n logging.info(\"log message from test_log_1 not to be shown\")\n logging.warning(\"log message from test_log_1\")\n\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n log_level=INFO\n log_cli_level=INFO\n \"\"\"\n )\n\n result = testdir.runpytest(cli_args)\n stdout = result.stdout.str()\n if cli_args == \"--log-cli-level=WARNING\":\n result.stdout.fnmatch_lines(\n [\n \"*::test_log_1 \",\n \"*-- live log call --*\",\n \"*WARNING*log message from test_log_1*\",\n \"PASSED *100%*\",\n \"=* 1 passed in *=\",\n ]\n )\n assert \"INFO\" not in stdout\n else:\n result.stdout.fnmatch_lines(\n [\"*test_log_cli_auto_enable*100%*\", \"=* 1 passed in *=\"]\n )\n assert \"INFO\" not in stdout\n assert \"WARNING\" not in stdout\n\n\ndef test_log_file_cli(testdir):\n # Default log file level\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n def test_log_file(request):\n plugin = request.config.pluginmanager.getplugin('logging-plugin')\n assert plugin.log_file_handler.level == logging.WARNING\n logging.getLogger('catchlog').info(\"This log message won't be shown\")\n logging.getLogger('catchlog').warning(\"This log message will be shown\")\n print('PASSED')\n \"\"\"\n )\n\n log_file = testdir.tmpdir.join(\"pytest.log\").strpath\n\n result = testdir.runpytest(\n \"-s\", \"--log-file={}\".format(log_file), \"--log-file-level=WARNING\"\n )\n\n # fnmatch_lines does an assertion internally\n result.stdout.fnmatch_lines([\"test_log_file_cli.py PASSED\"])\n\n # make sure that that we get a '0' exit code for the testsuite\n assert result.ret == 0\n assert os.path.isfile(log_file)\n with open(log_file) as rfh:\n contents = rfh.read()\n assert \"This log message will be shown\" in contents\n assert \"This log message won't be shown\" not in contents\n\n\ndef test_log_file_cli_level(testdir):\n # Default log file level\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n def test_log_file(request):\n plugin = request.config.pluginmanager.getplugin('logging-plugin')\n assert plugin.log_file_handler.level == logging.INFO\n logging.getLogger('catchlog').debug(\"This log message won't be shown\")\n logging.getLogger('catchlog').info(\"This log message will be shown\")\n print('PASSED')\n \"\"\"\n )\n\n log_file = testdir.tmpdir.join(\"pytest.log\").strpath\n\n result = testdir.runpytest(\n \"-s\", \"--log-file={}\".format(log_file), \"--log-file-level=INFO\"\n )\n\n # fnmatch_lines does an assertion internally\n result.stdout.fnmatch_lines([\"test_log_file_cli_level.py PASSED\"])\n\n # make sure that that we get a '0' exit code for the testsuite\n assert result.ret == 0\n assert os.path.isfile(log_file)\n with open(log_file) as rfh:\n contents = rfh.read()\n assert \"This log message will be shown\" in contents\n assert \"This log message won't be shown\" not in contents\n\n\ndef test_log_level_not_changed_by_default(testdir):\n testdir.makepyfile(\n \"\"\"\n import logging\n def test_log_file():\n assert logging.getLogger().level == logging.WARNING\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines([\"* 1 passed in *\"])\n\n\ndef test_log_file_ini(testdir):\n log_file = testdir.tmpdir.join(\"pytest.log\").strpath\n\n testdir.makeini(\n \"\"\"\n [pytest]\n log_file={}\n log_file_level=WARNING\n \"\"\".format(\n log_file\n )\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n def test_log_file(request):\n plugin = request.config.pluginmanager.getplugin('logging-plugin')\n assert plugin.log_file_handler.level == logging.WARNING\n logging.getLogger('catchlog').info(\"This log message won't be shown\")\n logging.getLogger('catchlog').warning(\"This log message will be shown\")\n print('PASSED')\n \"\"\"\n )\n\n result = testdir.runpytest(\"-s\")\n\n # fnmatch_lines does an assertion internally\n result.stdout.fnmatch_lines([\"test_log_file_ini.py PASSED\"])\n\n # make sure that that we get a '0' exit code for the testsuite\n assert result.ret == 0\n assert os.path.isfile(log_file)\n with open(log_file) as rfh:\n contents = rfh.read()\n assert \"This log message will be shown\" in contents\n assert \"This log message won't be shown\" not in contents\n\n\ndef test_log_file_ini_level(testdir):\n log_file = testdir.tmpdir.join(\"pytest.log\").strpath\n\n testdir.makeini(\n \"\"\"\n [pytest]\n log_file={}\n log_file_level = INFO\n \"\"\".format(\n log_file\n )\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n def test_log_file(request):\n plugin = request.config.pluginmanager.getplugin('logging-plugin')\n assert plugin.log_file_handler.level == logging.INFO\n logging.getLogger('catchlog').debug(\"This log message won't be shown\")\n logging.getLogger('catchlog').info(\"This log message will be shown\")\n print('PASSED')\n \"\"\"\n )\n\n result = testdir.runpytest(\"-s\")\n\n # fnmatch_lines does an assertion internally\n result.stdout.fnmatch_lines([\"test_log_file_ini_level.py PASSED\"])\n\n # make sure that that we get a '0' exit code for the testsuite\n assert result.ret == 0\n assert os.path.isfile(log_file)\n with open(log_file) as rfh:\n contents = rfh.read()\n assert \"This log message will be shown\" in contents\n assert \"This log message won't be shown\" not in contents\n\n\ndef test_log_file_unicode(testdir):\n log_file = testdir.tmpdir.join(\"pytest.log\").strpath\n\n testdir.makeini(\n \"\"\"\n [pytest]\n log_file={}\n log_file_level = INFO\n \"\"\".format(\n log_file\n )\n )\n testdir.makepyfile(\n \"\"\"\n # -*- coding: utf-8 -*-\n from __future__ import unicode_literals\n import logging\n\n def test_log_file():\n logging.getLogger('catchlog').info(\"Normal message\")\n logging.getLogger('catchlog').info(\"├\")\n logging.getLogger('catchlog').info(\"Another normal message\")\n \"\"\"\n )\n\n result = testdir.runpytest()\n\n # make sure that that we get a '0' exit code for the testsuite\n assert result.ret == 0\n assert os.path.isfile(log_file)\n with open(log_file, encoding=\"utf-8\") as rfh:\n contents = rfh.read()\n assert \"Normal message\" in contents\n assert u\"├\" in contents\n assert \"Another normal message\" in contents\n\n\n@pytest.mark.parametrize(\"has_capture_manager\", [True, False])\ndef test_live_logging_suspends_capture(has_capture_manager, request):\n \"\"\"Test that capture manager is suspended when we emitting messages for live logging.\n\n This tests the implementation calls instead of behavior because it is difficult/impossible to do it using\n ``testdir`` facilities because they do their own capturing.\n\n We parametrize the test to also make sure _LiveLoggingStreamHandler works correctly if no capture manager plugin\n is installed.\n \"\"\"\n import logging\n import contextlib\n from functools import partial\n from _pytest.logging import _LiveLoggingStreamHandler\n\n class MockCaptureManager:\n calls = []\n\n @contextlib.contextmanager\n def global_and_fixture_disabled(self):\n self.calls.append(\"enter disabled\")\n yield\n self.calls.append(\"exit disabled\")\n\n class DummyTerminal(six.StringIO):\n def section(self, *args, **kwargs):\n pass\n\n out_file = DummyTerminal()\n capture_manager = MockCaptureManager() if has_capture_manager else None\n handler = _LiveLoggingStreamHandler(out_file, capture_manager)\n handler.set_when(\"call\")\n\n logger = logging.getLogger(__name__ + \".test_live_logging_suspends_capture\")\n logger.addHandler(handler)\n request.addfinalizer(partial(logger.removeHandler, handler))\n\n logger.critical(\"some message\")\n if has_capture_manager:\n assert MockCaptureManager.calls == [\"enter disabled\", \"exit disabled\"]\n else:\n assert MockCaptureManager.calls == []\n assert out_file.getvalue() == \"\\nsome message\\n\"\n\n\ndef test_collection_live_logging(testdir):\n testdir.makepyfile(\n \"\"\"\n import logging\n\n logging.getLogger().info(\"Normal message\")\n \"\"\"\n )\n\n result = testdir.runpytest(\"--log-cli-level=INFO\")\n result.stdout.fnmatch_lines(\n [\"*--- live log collection ---*\", \"*Normal message*\", \"collected 0 items\"]\n )\n\n\n@pytest.mark.parametrize(\"verbose\", [\"\", \"-q\", \"-qq\"])\ndef test_collection_collect_only_live_logging(testdir, verbose):\n testdir.makepyfile(\n \"\"\"\n def test_simple():\n pass\n \"\"\"\n )\n\n result = testdir.runpytest(\"--collect-only\", \"--log-cli-level=INFO\", verbose)\n\n expected_lines = []\n\n if not verbose:\n expected_lines.extend(\n [\n \"*collected 1 item*\",\n \"**\",\n \"*no tests ran*\",\n ]\n )\n elif verbose == \"-q\":\n assert \"collected 1 item*\" not in result.stdout.str()\n expected_lines.extend(\n [\n \"*test_collection_collect_only_live_logging.py::test_simple*\",\n \"no tests ran in * seconds\",\n ]\n )\n elif verbose == \"-qq\":\n assert \"collected 1 item*\" not in result.stdout.str()\n expected_lines.extend([\"*test_collection_collect_only_live_logging.py: 1*\"])\n\n result.stdout.fnmatch_lines(expected_lines)\n\n\ndef test_collection_logging_to_file(testdir):\n log_file = testdir.tmpdir.join(\"pytest.log\").strpath\n\n testdir.makeini(\n \"\"\"\n [pytest]\n log_file={}\n log_file_level = INFO\n \"\"\".format(\n log_file\n )\n )\n\n testdir.makepyfile(\n \"\"\"\n import logging\n\n logging.getLogger().info(\"Normal message\")\n\n def test_simple():\n logging.getLogger().debug(\"debug message in test_simple\")\n logging.getLogger().info(\"info message in test_simple\")\n \"\"\"\n )\n\n result = testdir.runpytest()\n\n assert \"--- live log collection ---\" not in result.stdout.str()\n\n assert result.ret == 0\n assert os.path.isfile(log_file)\n with open(log_file, encoding=\"utf-8\") as rfh:\n contents = rfh.read()\n assert \"Normal message\" in contents\n assert \"debug message in test_simple\" not in contents\n assert \"info message in test_simple\" in contents\n\n\ndef test_log_in_hooks(testdir):\n log_file = testdir.tmpdir.join(\"pytest.log\").strpath\n\n testdir.makeini(\n \"\"\"\n [pytest]\n log_file={}\n log_file_level = INFO\n log_cli=true\n \"\"\".format(\n log_file\n )\n )\n testdir.makeconftest(\n \"\"\"\n import logging\n\n def pytest_runtestloop(session):\n logging.info('runtestloop')\n\n def pytest_sessionstart(session):\n logging.info('sessionstart')\n\n def pytest_sessionfinish(session, exitstatus):\n logging.info('sessionfinish')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*sessionstart*\", \"*runtestloop*\", \"*sessionfinish*\"])\n with open(log_file) as rfh:\n contents = rfh.read()\n assert \"sessionstart\" in contents\n assert \"runtestloop\" in contents\n assert \"sessionfinish\" in contents\n\n\ndef test_log_in_runtest_logreport(testdir):\n log_file = testdir.tmpdir.join(\"pytest.log\").strpath\n\n testdir.makeini(\n \"\"\"\n [pytest]\n log_file={}\n log_file_level = INFO\n log_cli=true\n \"\"\".format(\n log_file\n )\n )\n testdir.makeconftest(\n \"\"\"\n import logging\n logger = logging.getLogger(__name__)\n\n def pytest_runtest_logreport(report):\n logger.info(\"logreport\")\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_first():\n assert True\n \"\"\"\n )\n testdir.runpytest()\n with open(log_file) as rfh:\n contents = rfh.read()\n assert contents.count(\"logreport\") == 3\n\n\ndef test_log_set_path(testdir):\n report_dir_base = testdir.tmpdir.strpath\n\n testdir.makeini(\n \"\"\"\n [pytest]\n log_file_level = DEBUG\n log_cli=true\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import os\n import pytest\n @pytest.hookimpl(hookwrapper=True, tryfirst=True)\n def pytest_runtest_setup(item):\n config = item.config\n logging_plugin = config.pluginmanager.get_plugin(\"logging-plugin\")\n report_file = os.path.join({}, item._request.node.name)\n logging_plugin.set_log_path(report_file)\n yield\n \"\"\".format(\n repr(report_dir_base)\n )\n )\n testdir.makepyfile(\n \"\"\"\n import logging\n logger = logging.getLogger(\"testcase-logger\")\n def test_first():\n logger.info(\"message from test 1\")\n assert True\n\n def test_second():\n logger.debug(\"message from test 2\")\n assert True\n \"\"\"\n )\n testdir.runpytest()\n with open(os.path.join(report_dir_base, \"test_first\"), \"r\") as rfh:\n content = rfh.read()\n assert \"message from test 1\" in content\n\n with open(os.path.join(report_dir_base, \"test_second\"), \"r\") as rfh:\n content = rfh.read()\n assert \"message from test 2\" in content\n\n\ndef test_colored_captured_log(testdir):\n \"\"\"\n Test that the level names of captured log messages of a failing test are\n colored.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import logging\n\n logger = logging.getLogger(__name__)\n\n def test_foo():\n logger.info('text going to logger from call')\n assert False\n \"\"\"\n )\n result = testdir.runpytest(\"--log-level=INFO\", \"--color=yes\")\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\n \"*-- Captured log call --*\",\n \"\\x1b[32mINFO \\x1b[0m*text going to logger from call\",\n ]\n )\n\n\ndef test_colored_ansi_esc_caplogtext(testdir):\n \"\"\"\n Make sure that caplog.text does not contain ANSI escape sequences.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import logging\n\n logger = logging.getLogger(__name__)\n\n def test_foo(caplog):\n logger.info('text going to logger from call')\n assert '\\x1b' not in caplog.text\n \"\"\"\n )\n result = testdir.runpytest(\"--log-level=INFO\", \"--color=yes\")\n assert result.ret == 0\n"},{"col":4,"comment":"null","endLoc":613,"header":"def test_python_pytest_package(self, testdir)","id":5733,"name":"test_python_pytest_package","nodeType":"Function","startLoc":609,"text":"def test_python_pytest_package(self, testdir):\n p1 = testdir.makepyfile(\"def test_pass(): pass\")\n res = testdir.run(sys.executable, \"-m\", \"pytest\", str(p1))\n assert res.ret == 0\n res.stdout.fnmatch_lines([\"*1 passed*\"])"},{"attributeType":"function | function | function | function | function | function | function | function","col":0,"comment":"null","endLoc":45,"id":5734,"name":"open","nodeType":"Attribute","startLoc":45,"text":"open"},{"col":4,"comment":"null","endLoc":78,"header":"def test_invalid_enter_exit(self)","id":5735,"name":"test_invalid_enter_exit","nodeType":"Function","startLoc":67,"text":"def test_invalid_enter_exit(self):\n # wrap this test in WarningsRecorder to ensure warning state gets reset\n with WarningsRecorder():\n with pytest.raises(RuntimeError):\n rec = WarningsRecorder()\n rec.__exit__(None, None, None) # can't exit before entering\n\n with pytest.raises(RuntimeError):\n rec = WarningsRecorder()\n with rec:\n with rec:\n pass # can't enter twice"},{"col":4,"comment":"null","endLoc":616,"header":"def test_equivalence_pytest_pytest(self)","id":5736,"name":"test_equivalence_pytest_pytest","nodeType":"Function","startLoc":615,"text":"def test_equivalence_pytest_pytest(self):\n assert pytest.main == py.test.cmdline.main"},{"col":4,"comment":"null","endLoc":622,"header":"def test_invoke_with_invalid_type(self, capsys)","id":5737,"name":"test_invoke_with_invalid_type","nodeType":"Function","startLoc":618,"text":"def test_invoke_with_invalid_type(self, capsys):\n with pytest.raises(\n TypeError, match=\"expected to be a list or tuple of strings, got: '-h'\"\n ):\n pytest.main(\"-h\")"},{"col":4,"comment":"null","endLoc":627,"header":"def test_invoke_with_path(self, tmpdir, capsys)","id":5738,"name":"test_invoke_with_path","nodeType":"Function","startLoc":624,"text":"def test_invoke_with_path(self, tmpdir, capsys):\n retcode = pytest.main(tmpdir)\n assert retcode == EXIT_NOTESTSCOLLECTED\n out, err = capsys.readouterr()"},{"col":4,"comment":"null","endLoc":35,"header":"def test_marked_no_args(self, testdir)","id":5739,"name":"test_marked_no_args","nodeType":"Function","startLoc":21,"text":"def test_marked_no_args(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xyz\n def test_func():\n pass\n \"\"\"\n )\n ev = MarkEvaluator(item, \"xyz\")\n assert ev\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"\"\n assert not ev.get(\"run\", False)"},{"col":0,"comment":"null","endLoc":27,"header":"def test_nothing_logged(testdir)","id":5740,"name":"test_nothing_logged","nodeType":"Function","startLoc":11,"text":"def test_nothing_logged(testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n\n def test_foo():\n sys.stdout.write('text going to stdout')\n sys.stderr.write('text going to stderr')\n assert False\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines([\"*- Captured stdout call -*\", \"text going to stdout\"])\n result.stdout.fnmatch_lines([\"*- Captured stderr call -*\", \"text going to stderr\"])\n with pytest.raises(pytest.fail.Exception):\n result.stdout.fnmatch_lines([\"*- Captured *log call -*\"])"},{"col":4,"comment":"null","endLoc":636,"header":"def test_invoke_plugin_api(self, testdir, capsys)","id":5741,"name":"test_invoke_plugin_api","nodeType":"Function","startLoc":629,"text":"def test_invoke_plugin_api(self, testdir, capsys):\n class MyPlugin(object):\n def pytest_addoption(self, parser):\n parser.addoption(\"--myopt\")\n\n pytest.main([\"-h\"], plugins=[MyPlugin()])\n out, err = capsys.readouterr()\n assert \"--myopt\" in out"},{"col":4,"comment":"null","endLoc":50,"header":"def test_marked_one_arg(self, testdir)","id":5742,"name":"test_marked_one_arg","nodeType":"Function","startLoc":37,"text":"def test_marked_one_arg(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xyz(\"hasattr(os, 'sep')\")\n def test_func():\n pass\n \"\"\"\n )\n ev = MarkEvaluator(item, \"xyz\")\n assert ev\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"condition: hasattr(os, 'sep')\""},{"col":4,"comment":"null","endLoc":646,"header":"def test_pyargs_importerror(self, testdir, monkeypatch)","id":5743,"name":"test_pyargs_importerror","nodeType":"Function","startLoc":638,"text":"def test_pyargs_importerror(self, testdir, monkeypatch):\n monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", False)\n path = testdir.mkpydir(\"tpkg\")\n path.join(\"test_hello.py\").write(\"raise ImportError\")\n\n result = testdir.runpytest(\"--pyargs\", \"tpkg.test_hello\", syspathinsert=True)\n assert result.ret != 0\n\n result.stdout.fnmatch_lines([\"collected*0*items*/*1*errors\"])"},{"col":0,"comment":"null","endLoc":49,"header":"def test_messages_logged(testdir)","id":5744,"name":"test_messages_logged","nodeType":"Function","startLoc":30,"text":"def test_messages_logged(testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n import logging\n\n logger = logging.getLogger(__name__)\n\n def test_foo():\n sys.stdout.write('text going to stdout')\n sys.stderr.write('text going to stderr')\n logger.info('text going to logger')\n assert False\n \"\"\"\n )\n result = testdir.runpytest(\"--log-level=INFO\")\n assert result.ret == 1\n result.stdout.fnmatch_lines([\"*- Captured *log call -*\", \"*text going to logger*\"])\n result.stdout.fnmatch_lines([\"*- Captured stdout call -*\", \"text going to stdout\"])\n result.stdout.fnmatch_lines([\"*- Captured stderr call -*\", \"text going to stderr\"])"},{"col":4,"comment":"null","endLoc":66,"header":"@pytest.mark.skipif(\"sys.version_info[0] >= 3\")\n def test_marked_one_arg_unicode(self, testdir)","id":5745,"name":"test_marked_one_arg_unicode","nodeType":"Function","startLoc":52,"text":"@pytest.mark.skipif(\"sys.version_info[0] >= 3\")\n def test_marked_one_arg_unicode(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xyz(u\"hasattr(os, 'sep')\")\n def test_func():\n pass\n \"\"\"\n )\n ev = MarkEvaluator(item, \"xyz\")\n assert ev\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"condition: hasattr(os, 'sep')\""},{"col":4,"comment":"null","endLoc":675,"header":"def test_cmdline_python_package(self, testdir, monkeypatch)","id":5746,"name":"test_cmdline_python_package","nodeType":"Function","startLoc":648,"text":"def test_cmdline_python_package(self, testdir, monkeypatch):\n import warnings\n\n monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", False)\n path = testdir.mkpydir(\"tpkg\")\n path.join(\"test_hello.py\").write(\"def test_hello(): pass\")\n path.join(\"test_world.py\").write(\"def test_world(): pass\")\n result = testdir.runpytest(\"--pyargs\", \"tpkg\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n result = testdir.runpytest(\"--pyargs\", \"tpkg.test_hello\", syspathinsert=True)\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n empty_package = testdir.mkpydir(\"empty_package\")\n monkeypatch.setenv(\"PYTHONPATH\", str(empty_package), prepend=os.pathsep)\n # the path which is not a package raises a warning on pypy;\n # no idea why only pypy and not normal python warn about it here\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", ImportWarning)\n result = testdir.runpytest(\"--pyargs\", \".\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n monkeypatch.setenv(\"PYTHONPATH\", str(testdir), prepend=os.pathsep)\n result = testdir.runpytest(\"--pyargs\", \"tpkg.test_missing\", syspathinsert=True)\n assert result.ret != 0\n result.stderr.fnmatch_lines([\"*not*found*test_missing*\"])"},{"col":0,"comment":"null","endLoc":85,"header":"def test_root_logger_affected(testdir)","id":5747,"name":"test_root_logger_affected","nodeType":"Function","startLoc":52,"text":"def test_root_logger_affected(testdir):\n testdir.makepyfile(\n \"\"\"\n import logging\n logger = logging.getLogger()\n\n def test_foo():\n logger.info('info text ' + 'going to logger')\n logger.warning('warning text ' + 'going to logger')\n logger.error('error text ' + 'going to logger')\n\n assert 0\n \"\"\"\n )\n log_file = testdir.tmpdir.join(\"pytest.log\").strpath\n result = testdir.runpytest(\"--log-level=ERROR\", \"--log-file=pytest.log\")\n assert result.ret == 1\n\n # The capture log calls in the stdout section only contain the\n # logger.error msg, because of --log-level=ERROR.\n result.stdout.fnmatch_lines([\"*error text going to logger*\"])\n stdout = result.stdout.str()\n assert \"warning text going to logger\" not in stdout\n assert \"info text going to logger\" not in stdout\n\n # The log file should contain the warning and the error log messages and\n # not the info one, because the default level of the root logger is\n # WARNING.\n assert os.path.isfile(log_file)\n with open(log_file) as rfh:\n contents = rfh.read()\n assert \"info text going to logger\" not in contents\n assert \"warning text going to logger\" in contents\n assert \"error text going to logger\" in contents"},{"className":"TestDeprecatedCall","col":0,"comment":"test pytest.deprecated_call()","endLoc":210,"id":5748,"nodeType":"Class","startLoc":81,"text":"class TestDeprecatedCall(object):\n \"\"\"test pytest.deprecated_call()\"\"\"\n\n def dep(self, i, j=None):\n if i == 0:\n warnings.warn(\"is deprecated\", DeprecationWarning, stacklevel=1)\n return 42\n\n def dep_explicit(self, i):\n if i == 0:\n warnings.warn_explicit(\n \"dep_explicit\", category=DeprecationWarning, filename=\"hello\", lineno=3\n )\n\n def test_deprecated_call_raises(self):\n with pytest.raises(pytest.fail.Exception, match=\"No warnings of type\"):\n pytest.deprecated_call(self.dep, 3, 5)\n\n def test_deprecated_call(self):\n pytest.deprecated_call(self.dep, 0, 5)\n\n def test_deprecated_call_ret(self):\n ret = pytest.deprecated_call(self.dep, 0)\n assert ret == 42\n\n def test_deprecated_call_preserves(self):\n onceregistry = warnings.onceregistry.copy()\n filters = warnings.filters[:]\n warn = warnings.warn\n warn_explicit = warnings.warn_explicit\n self.test_deprecated_call_raises()\n self.test_deprecated_call()\n assert onceregistry == warnings.onceregistry\n assert filters == warnings.filters\n assert warn is warnings.warn\n assert warn_explicit is warnings.warn_explicit\n\n def test_deprecated_explicit_call_raises(self):\n with pytest.raises(pytest.fail.Exception):\n pytest.deprecated_call(self.dep_explicit, 3)\n\n def test_deprecated_explicit_call(self):\n pytest.deprecated_call(self.dep_explicit, 0)\n pytest.deprecated_call(self.dep_explicit, 0)\n\n @pytest.mark.parametrize(\"mode\", [\"context_manager\", \"call\"])\n def test_deprecated_call_no_warning(self, mode):\n \"\"\"Ensure deprecated_call() raises the expected failure when its block/function does\n not raise a deprecation warning.\n \"\"\"\n\n def f():\n pass\n\n msg = \"No warnings of type (.*DeprecationWarning.*, .*PendingDeprecationWarning.*)\"\n with pytest.raises(pytest.fail.Exception, match=msg):\n if mode == \"call\":\n pytest.deprecated_call(f)\n else:\n with pytest.deprecated_call():\n f()\n\n @pytest.mark.parametrize(\n \"warning_type\", [PendingDeprecationWarning, DeprecationWarning]\n )\n @pytest.mark.parametrize(\"mode\", [\"context_manager\", \"call\"])\n @pytest.mark.parametrize(\"call_f_first\", [True, False])\n @pytest.mark.filterwarnings(\"ignore\")\n def test_deprecated_call_modes(self, warning_type, mode, call_f_first):\n \"\"\"Ensure deprecated_call() captures a deprecation warning as expected inside its\n block/function.\n \"\"\"\n\n def f():\n warnings.warn(warning_type(\"hi\"))\n return 10\n\n # ensure deprecated_call() can capture the warning even if it has already been triggered\n if call_f_first:\n assert f() == 10\n if mode == \"call\":\n assert pytest.deprecated_call(f) == 10\n else:\n with pytest.deprecated_call():\n assert f() == 10\n\n @pytest.mark.parametrize(\"mode\", [\"context_manager\", \"call\"])\n def test_deprecated_call_exception_is_raised(self, mode):\n \"\"\"If the block of the code being tested by deprecated_call() raises an exception,\n it must raise the exception undisturbed.\n \"\"\"\n\n def f():\n raise ValueError(\"some exception\")\n\n with pytest.raises(ValueError, match=\"some exception\"):\n if mode == \"call\":\n pytest.deprecated_call(f)\n else:\n with pytest.deprecated_call():\n f()\n\n def test_deprecated_call_specificity(self):\n other_warnings = [\n Warning,\n UserWarning,\n SyntaxWarning,\n RuntimeWarning,\n FutureWarning,\n ImportWarning,\n UnicodeWarning,\n ]\n for warning in other_warnings:\n\n def f():\n warnings.warn(warning(\"hi\"))\n\n with pytest.raises(pytest.fail.Exception):\n pytest.deprecated_call(f)\n with pytest.raises(pytest.fail.Exception):\n with pytest.deprecated_call():\n f()\n\n def test_deprecated_call_supports_match(self):\n with pytest.deprecated_call(match=r\"must be \\d+$\"):\n warnings.warn(\"value must be 42\", DeprecationWarning)\n\n with pytest.raises(pytest.fail.Exception):\n with pytest.deprecated_call(match=r\"must be \\d+$\"):\n warnings.warn(\"this is not here\", DeprecationWarning)"},{"col":4,"comment":"null","endLoc":87,"header":"def dep(self, i, j=None)","id":5749,"name":"dep","nodeType":"Function","startLoc":84,"text":"def dep(self, i, j=None):\n if i == 0:\n warnings.warn(\"is deprecated\", DeprecationWarning, stacklevel=1)\n return 42"},{"attributeType":"null","col":8,"comment":"null","endLoc":290,"id":5750,"name":"parser","nodeType":"Attribute","startLoc":290,"text":"self.parser"},{"attributeType":"null","col":8,"comment":"null","endLoc":287,"id":5751,"name":"name","nodeType":"Attribute","startLoc":287,"text":"self.name"},{"attributeType":"list","col":8,"comment":"null","endLoc":289,"id":5752,"name":"options","nodeType":"Attribute","startLoc":289,"text":"self.options"},{"attributeType":"str","col":8,"comment":"null","endLoc":288,"id":5753,"name":"description","nodeType":"Attribute","startLoc":288,"text":"self.description"},{"className":"MyOptionParser","col":0,"comment":"null","endLoc":358,"id":5754,"nodeType":"Class","startLoc":322,"text":"class MyOptionParser(argparse.ArgumentParser):\n def __init__(self, parser, extra_info=None, prog=None):\n if not extra_info:\n extra_info = {}\n self._parser = parser\n argparse.ArgumentParser.__init__(\n self,\n prog=prog,\n usage=parser._usage,\n add_help=False,\n formatter_class=DropShorterLongHelpFormatter,\n )\n # extra_info is a dict of (param -> value) to display if there's\n # an usage error to provide more contextual information to the user\n self.extra_info = extra_info\n\n def error(self, message):\n \"\"\"Transform argparse error message into UsageError.\"\"\"\n msg = \"%s: error: %s\" % (self.prog, message)\n\n if hasattr(self._parser, \"_config_source_hint\"):\n msg = \"%s (%s)\" % (msg, self._parser._config_source_hint)\n\n raise UsageError(self.format_usage() + msg)\n\n def parse_args(self, args=None, namespace=None):\n \"\"\"allow splitting of positional arguments\"\"\"\n args, argv = self.parse_known_args(args, namespace)\n if argv:\n for arg in argv:\n if arg and arg[0] == \"-\":\n lines = [\"unrecognized arguments: %s\" % (\" \".join(argv))]\n for k, v in sorted(self.extra_info.items()):\n lines.append(\" %s: %s\" % (k, v))\n self.error(\"\\n\".join(lines))\n getattr(args, FILE_OR_DIR).extend(argv)\n return args"},{"className":"ArgumentParser","col":0,"comment":"null","endLoc":251,"id":5756,"nodeType":"Class","startLoc":126,"text":"class ArgumentParser(_AttributeHolder, _ActionsContainer):\n prog: str\n usage: str | None\n epilog: str | None\n formatter_class: _FormatterClass\n fromfile_prefix_chars: str | None\n add_help: bool\n allow_abbrev: bool\n\n # undocumented\n _positionals: _ArgumentGroup\n _optionals: _ArgumentGroup\n _subparsers: _ArgumentGroup | None\n\n # Note: the constructor arguments are also used in _SubParsersAction.add_parser.\n if sys.version_info >= (3, 9):\n def __init__(\n self,\n prog: str | None = None,\n usage: str | None = None,\n description: str | None = None,\n epilog: str | None = None,\n parents: Sequence[ArgumentParser] = [],\n formatter_class: _FormatterClass = ...,\n prefix_chars: str = \"-\",\n fromfile_prefix_chars: str | None = None,\n argument_default: Any = None,\n conflict_handler: str = \"error\",\n add_help: bool = True,\n allow_abbrev: bool = True,\n exit_on_error: bool = True,\n ) -> None: ...\n else:\n def __init__(\n self,\n prog: str | None = None,\n usage: str | None = None,\n description: str | None = None,\n epilog: str | None = None,\n parents: Sequence[ArgumentParser] = [],\n formatter_class: _FormatterClass = ...,\n prefix_chars: str = \"-\",\n fromfile_prefix_chars: str | None = None,\n argument_default: Any = None,\n conflict_handler: str = \"error\",\n add_help: bool = True,\n allow_abbrev: bool = True,\n ) -> None: ...\n\n @overload\n def parse_args(self, args: Sequence[str] | None = None, namespace: None = None) -> Namespace: ...\n @overload\n def parse_args(self, args: Sequence[str] | None, namespace: _N) -> _N: ...\n @overload\n def parse_args(self, *, namespace: _N) -> _N: ...\n @overload\n def add_subparsers(\n self: _ArgumentParserT,\n *,\n title: str = ...,\n description: str | None = ...,\n prog: str = ...,\n action: type[Action] = ...,\n option_string: str = ...,\n dest: str | None = ...,\n required: bool = ...,\n help: str | None = ...,\n metavar: str | None = ...,\n ) -> _SubParsersAction[_ArgumentParserT]: ...\n @overload\n def add_subparsers(\n self,\n *,\n title: str = ...,\n description: str | None = ...,\n prog: str = ...,\n parser_class: type[_ArgumentParserT],\n action: type[Action] = ...,\n option_string: str = ...,\n dest: str | None = ...,\n required: bool = ...,\n help: str | None = ...,\n metavar: str | None = ...,\n ) -> _SubParsersAction[_ArgumentParserT]: ...\n def print_usage(self, file: IO[str] | None = None) -> None: ...\n def print_help(self, file: IO[str] | None = None) -> None: ...\n def format_usage(self) -> str: ...\n def format_help(self) -> str: ...\n @overload\n def parse_known_args(self, args: Sequence[str] | None = None, namespace: None = None) -> tuple[Namespace, list[str]]: ...\n @overload\n def parse_known_args(self, args: Sequence[str] | None, namespace: _N) -> tuple[_N, list[str]]: ...\n @overload\n def parse_known_args(self, *, namespace: _N) -> tuple[_N, list[str]]: ...\n def convert_arg_line_to_args(self, arg_line: str) -> list[str]: ...\n def exit(self, status: int = 0, message: str | None = None) -> NoReturn: ...\n def error(self, message: str) -> NoReturn: ...\n @overload\n def parse_intermixed_args(self, args: Sequence[str] | None = None, namespace: None = None) -> Namespace: ...\n @overload\n def parse_intermixed_args(self, args: Sequence[str] | None, namespace: _N) -> _N: ...\n @overload\n def parse_intermixed_args(self, *, namespace: _N) -> _N: ...\n @overload\n def parse_known_intermixed_args(\n self, args: Sequence[str] | None = None, namespace: None = None\n ) -> tuple[Namespace, list[str]]: ...\n @overload\n def parse_known_intermixed_args(self, args: Sequence[str] | None, namespace: _N) -> tuple[_N, list[str]]: ...\n @overload\n def parse_known_intermixed_args(self, *, namespace: _N) -> tuple[_N, list[str]]: ...\n # undocumented\n def _get_optional_actions(self) -> list[Action]: ...\n def _get_positional_actions(self) -> list[Action]: ...\n def _parse_known_args(self, arg_strings: list[str], namespace: Namespace) -> tuple[Namespace, list[str]]: ...\n def _read_args_from_files(self, arg_strings: list[str]) -> list[str]: ...\n def _match_argument(self, action: Action, arg_strings_pattern: str) -> int: ...\n def _match_arguments_partial(self, actions: Sequence[Action], arg_strings_pattern: str) -> list[int]: ...\n def _parse_optional(self, arg_string: str) -> tuple[Action | None, str, str | None] | None: ...\n def _get_option_tuples(self, option_string: str) -> list[tuple[Action, str, str | None]]: ...\n def _get_nargs_pattern(self, action: Action) -> str: ...\n def _get_values(self, action: Action, arg_strings: list[str]) -> Any: ...\n def _get_value(self, action: Action, arg_string: str) -> Any: ...\n def _check_value(self, action: Action, value: Any) -> None: ...\n def _get_formatter(self) -> HelpFormatter: ...\n def _print_message(self, message: str, file: IO[str] | None = None) -> None: ..."},{"col":4,"comment":"null","endLoc":82,"header":"def test_marked_one_arg_with_reason(self, testdir)","id":5757,"name":"test_marked_one_arg_with_reason","nodeType":"Function","startLoc":68,"text":"def test_marked_one_arg_with_reason(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xyz(\"hasattr(os, 'sep')\", attr=2, reason=\"hello world\")\n def test_func():\n pass\n \"\"\"\n )\n ev = MarkEvaluator(item, \"xyz\")\n assert ev\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"hello world\"\n assert ev.get(\"attr\") == 2"},{"className":"_ActionsContainer","col":0,"comment":"null","endLoc":121,"id":5758,"nodeType":"Class","startLoc":67,"text":"class _ActionsContainer:\n description: str | None\n prefix_chars: str\n argument_default: Any\n conflict_handler: str\n\n _registries: dict[str, dict[Any, Any]]\n _actions: list[Action]\n _option_string_actions: dict[str, Action]\n _action_groups: list[_ArgumentGroup]\n _mutually_exclusive_groups: list[_MutuallyExclusiveGroup]\n _defaults: dict[str, Any]\n _negative_number_matcher: Pattern[str]\n _has_negative_number_optionals: list[bool]\n def __init__(self, description: str | None, prefix_chars: str, argument_default: Any, conflict_handler: str) -> None: ...\n def register(self, registry_name: str, value: Any, object: Any) -> None: ...\n def _registry_get(self, registry_name: str, value: Any, default: Any = None) -> Any: ...\n def set_defaults(self, **kwargs: Any) -> None: ...\n def get_default(self, dest: str) -> Any: ...\n def add_argument(\n self,\n *name_or_flags: str,\n action: _ActionStr | type[Action] = ...,\n nargs: int | _NArgsStr | _SUPPRESS_T | None = None,\n const: Any = ...,\n default: Any = ...,\n type: _ActionType = ...,\n choices: Iterable[_T] | None = ...,\n required: bool = ...,\n help: str | None = ...,\n metavar: str | tuple[str, ...] | None = ...,\n dest: str | None = ...,\n version: str = ...,\n **kwargs: Any,\n ) -> Action: ...\n def add_argument_group(\n self,\n title: str | None = None,\n description: str | None = None,\n *,\n prefix_chars: str = ...,\n argument_default: Any = ...,\n conflict_handler: str = ...,\n ) -> _ArgumentGroup: ...\n def add_mutually_exclusive_group(self, *, required: bool = False) -> _MutuallyExclusiveGroup: ...\n def _add_action(self, action: _ActionT) -> _ActionT: ...\n def _remove_action(self, action: Action) -> None: ...\n def _add_container_actions(self, container: _ActionsContainer) -> None: ...\n def _get_positional_kwargs(self, dest: str, **kwargs: Any) -> dict[str, Any]: ...\n def _get_optional_kwargs(self, *args: Any, **kwargs: Any) -> dict[str, Any]: ...\n def _pop_action_class(self, kwargs: Any, default: type[Action] | None = None) -> type[Action]: ...\n def _get_handler(self) -> Callable[[Action, Iterable[tuple[str, Action]]], Any]: ...\n def _check_conflict(self, action: Action) -> None: ...\n def _handle_conflict_error(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> NoReturn: ...\n def _handle_conflict_resolve(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> None: ..."},{"col":4,"comment":"null","endLoc":977,"header":"def __str__(self)","id":5759,"name":"__str__","nodeType":"Function","startLoc":976,"text":"def __str__(self):\n return \"%s\\n%s\\n%s\" % (\"\\n\".join(self.lines), self.reprlocals, self.reprfileloc)"},{"col":4,"comment":"null","endLoc":81,"header":"def __init__(self, description: str | None, prefix_chars: str, argument_default: Any, conflict_handler: str) -> None","id":5760,"name":"__init__","nodeType":"Function","startLoc":81,"text":"def __init__(self, description: str | None, prefix_chars: str, argument_default: Any, conflict_handler: str) -> None: ..."},{"col":4,"comment":"null","endLoc":82,"header":"def register(self, registry_name: str, value: Any, object: Any) -> None","id":5761,"name":"register","nodeType":"Function","startLoc":82,"text":"def register(self, registry_name: str, value: Any, object: Any) -> None: ..."},{"col":4,"comment":"null","endLoc":83,"header":"def _registry_get(self, registry_name: str, value: Any, default: Any = None) -> Any","id":5762,"name":"_registry_get","nodeType":"Function","startLoc":83,"text":"def _registry_get(self, registry_name: str, value: Any, default: Any = None) -> Any: ..."},{"col":4,"comment":"null","endLoc":84,"header":"def set_defaults(self, **kwargs: Any) -> None","id":5763,"name":"set_defaults","nodeType":"Function","startLoc":84,"text":"def set_defaults(self, **kwargs: Any) -> None: ..."},{"col":4,"comment":"null","endLoc":85,"header":"def get_default(self, dest: str) -> Any","id":5764,"name":"get_default","nodeType":"Function","startLoc":85,"text":"def get_default(self, dest: str) -> Any: ..."},{"col":4,"comment":"null","endLoc":110,"header":"def add_argument_group(\n self,\n title: str | None = None,\n description: str | None = None,\n *,\n prefix_chars: str = ...,\n argument_default: Any = ...,\n conflict_handler: str = ...,\n ) -> _ArgumentGroup","id":5765,"name":"add_argument_group","nodeType":"Function","startLoc":102,"text":"def add_argument_group(\n self,\n title: str | None = None,\n description: str | None = None,\n *,\n prefix_chars: str = ...,\n argument_default: Any = ...,\n conflict_handler: str = ...,\n ) -> _ArgumentGroup: ..."},{"col":4,"comment":"null","endLoc":111,"header":"def add_mutually_exclusive_group(self, *, required: bool = False) -> _MutuallyExclusiveGroup","id":5766,"name":"add_mutually_exclusive_group","nodeType":"Function","startLoc":111,"text":"def add_mutually_exclusive_group(self, *, required: bool = False) -> _MutuallyExclusiveGroup: ..."},{"col":4,"comment":"null","endLoc":112,"header":"def _add_action(self, action: _ActionT) -> _ActionT","id":5767,"name":"_add_action","nodeType":"Function","startLoc":112,"text":"def _add_action(self, action: _ActionT) -> _ActionT: ..."},{"col":4,"comment":"null","endLoc":113,"header":"def _remove_action(self, action: Action) -> None","id":5768,"name":"_remove_action","nodeType":"Function","startLoc":113,"text":"def _remove_action(self, action: Action) -> None: ..."},{"col":4,"comment":"null","endLoc":114,"header":"def _add_container_actions(self, container: _ActionsContainer) -> None","id":5769,"name":"_add_container_actions","nodeType":"Function","startLoc":114,"text":"def _add_container_actions(self, container: _ActionsContainer) -> None: ..."},{"col":4,"comment":"null","endLoc":115,"header":"def _get_positional_kwargs(self, dest: str, **kwargs: Any) -> dict[str, Any]","id":5770,"name":"_get_positional_kwargs","nodeType":"Function","startLoc":115,"text":"def _get_positional_kwargs(self, dest: str, **kwargs: Any) -> dict[str, Any]: ..."},{"col":4,"comment":"null","endLoc":116,"header":"def _get_optional_kwargs(self, *args: Any, **kwargs: Any) -> dict[str, Any]","id":5771,"name":"_get_optional_kwargs","nodeType":"Function","startLoc":116,"text":"def _get_optional_kwargs(self, *args: Any, **kwargs: Any) -> dict[str, Any]: ..."},{"col":4,"comment":"null","endLoc":117,"header":"def _pop_action_class(self, kwargs: Any, default: type[Action] | None = None) -> type[Action]","id":5772,"name":"_pop_action_class","nodeType":"Function","startLoc":117,"text":"def _pop_action_class(self, kwargs: Any, default: type[Action] | None = None) -> type[Action]: ..."},{"attributeType":"null","col":8,"comment":"null","endLoc":951,"id":5773,"name":"reprlocals","nodeType":"Attribute","startLoc":951,"text":"self.reprlocals"},{"col":4,"comment":"null","endLoc":118,"header":"def _get_handler(self) -> Callable[[Action, Iterable[tuple[str, Action]]], Any]","id":5774,"name":"_get_handler","nodeType":"Function","startLoc":118,"text":"def _get_handler(self) -> Callable[[Action, Iterable[tuple[str, Action]]], Any]: ..."},{"attributeType":"null","col":8,"comment":"null","endLoc":953,"id":5775,"name":"style","nodeType":"Attribute","startLoc":953,"text":"self.style"},{"attributeType":"null","col":8,"comment":"null","endLoc":949,"id":5776,"name":"lines","nodeType":"Attribute","startLoc":949,"text":"self.lines"},{"attributeType":"null","col":8,"comment":"null","endLoc":950,"id":5777,"name":"reprfuncargs","nodeType":"Attribute","startLoc":950,"text":"self.reprfuncargs"},{"attributeType":"null","col":8,"comment":"null","endLoc":952,"id":5778,"name":"reprfileloc","nodeType":"Attribute","startLoc":952,"text":"self.reprfileloc"},{"col":4,"comment":"null","endLoc":119,"header":"def _check_conflict(self, action: Action) -> None","id":5779,"name":"_check_conflict","nodeType":"Function","startLoc":119,"text":"def _check_conflict(self, action: Action) -> None: ..."},{"className":"ReprFileLocation","col":0,"comment":"null","endLoc":994,"id":5780,"nodeType":"Class","startLoc":980,"text":"class ReprFileLocation(TerminalRepr):\n def __init__(self, path, lineno, message):\n self.path = str(path)\n self.lineno = lineno\n self.message = message\n\n def toterminal(self, tw):\n # filename and lineno output for each entry,\n # using an output format that most editors unterstand\n msg = self.message\n i = msg.find(\"\\n\")\n if i != -1:\n msg = msg[:i]\n tw.write(self.path, bold=True, red=True)\n tw.line(\":%s: %s\" % (self.lineno, msg))"},{"col":4,"comment":"null","endLoc":120,"header":"def _handle_conflict_error(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> NoReturn","id":5781,"name":"_handle_conflict_error","nodeType":"Function","startLoc":120,"text":"def _handle_conflict_error(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> NoReturn: ..."},{"col":4,"comment":"null","endLoc":121,"header":"def _handle_conflict_resolve(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> None","id":5782,"name":"_handle_conflict_resolve","nodeType":"Function","startLoc":121,"text":"def _handle_conflict_resolve(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> None: ..."},{"col":4,"comment":"null","endLoc":994,"header":"def toterminal(self, tw)","id":5783,"name":"toterminal","nodeType":"Function","startLoc":986,"text":"def toterminal(self, tw):\n # filename and lineno output for each entry,\n # using an output format that most editors unterstand\n msg = self.message\n i = msg.find(\"\\n\")\n if i != -1:\n msg = msg[:i]\n tw.write(self.path, bold=True, red=True)\n tw.line(\":%s: %s\" % (self.lineno, msg))"},{"attributeType":"str | None","col":4,"comment":"null","endLoc":68,"id":5784,"name":"description","nodeType":"Attribute","startLoc":68,"text":"description"},{"col":4,"comment":"null","endLoc":104,"header":"def test_marked_one_arg_twice(self, testdir)","id":5785,"name":"test_marked_one_arg_twice","nodeType":"Function","startLoc":84,"text":"def test_marked_one_arg_twice(self, testdir):\n lines = [\n \"\"\"@pytest.mark.skipif(\"not hasattr(os, 'murks')\")\"\"\",\n \"\"\"@pytest.mark.skipif(\"hasattr(os, 'murks')\")\"\"\",\n ]\n for i in range(0, 2):\n item = testdir.getitem(\n \"\"\"\n import pytest\n %s\n %s\n def test_func():\n pass\n \"\"\"\n % (lines[i], lines[(i + 1) % 2])\n )\n ev = MarkEvaluator(item, \"skipif\")\n assert ev\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"condition: not hasattr(os, 'murks')\""},{"col":4,"comment":"null","endLoc":93,"header":"def dep_explicit(self, i)","id":5786,"name":"dep_explicit","nodeType":"Function","startLoc":89,"text":"def dep_explicit(self, i):\n if i == 0:\n warnings.warn_explicit(\n \"dep_explicit\", category=DeprecationWarning, filename=\"hello\", lineno=3\n )"},{"col":4,"comment":"null","endLoc":97,"header":"def test_deprecated_call_raises(self)","id":5787,"name":"test_deprecated_call_raises","nodeType":"Function","startLoc":95,"text":"def test_deprecated_call_raises(self):\n with pytest.raises(pytest.fail.Exception, match=\"No warnings of type\"):\n pytest.deprecated_call(self.dep, 3, 5)"},{"col":4,"comment":"null","endLoc":100,"header":"def test_deprecated_call(self)","id":5788,"name":"test_deprecated_call","nodeType":"Function","startLoc":99,"text":"def test_deprecated_call(self):\n pytest.deprecated_call(self.dep, 0, 5)"},{"attributeType":"str","col":4,"comment":"null","endLoc":69,"id":5789,"name":"prefix_chars","nodeType":"Attribute","startLoc":69,"text":"prefix_chars"},{"attributeType":"null","col":4,"comment":"null","endLoc":70,"id":5790,"name":"argument_default","nodeType":"Attribute","startLoc":70,"text":"argument_default"},{"col":4,"comment":"null","endLoc":104,"header":"def test_deprecated_call_ret(self)","id":5791,"name":"test_deprecated_call_ret","nodeType":"Function","startLoc":102,"text":"def test_deprecated_call_ret(self):\n ret = pytest.deprecated_call(self.dep, 0)\n assert ret == 42"},{"col":4,"comment":"null","endLoc":116,"header":"def test_deprecated_call_preserves(self)","id":5792,"name":"test_deprecated_call_preserves","nodeType":"Function","startLoc":106,"text":"def test_deprecated_call_preserves(self):\n onceregistry = warnings.onceregistry.copy()\n filters = warnings.filters[:]\n warn = warnings.warn\n warn_explicit = warnings.warn_explicit\n self.test_deprecated_call_raises()\n self.test_deprecated_call()\n assert onceregistry == warnings.onceregistry\n assert filters == warnings.filters\n assert warn is warnings.warn\n assert warn_explicit is warnings.warn_explicit"},{"attributeType":"str","col":4,"comment":"null","endLoc":71,"id":5793,"name":"conflict_handler","nodeType":"Attribute","startLoc":71,"text":"conflict_handler"},{"col":4,"comment":"null","endLoc":120,"header":"def test_deprecated_explicit_call_raises(self)","id":5794,"name":"test_deprecated_explicit_call_raises","nodeType":"Function","startLoc":118,"text":"def test_deprecated_explicit_call_raises(self):\n with pytest.raises(pytest.fail.Exception):\n pytest.deprecated_call(self.dep_explicit, 3)"},{"attributeType":"dict","col":4,"comment":"null","endLoc":73,"id":5795,"name":"_registries","nodeType":"Attribute","startLoc":73,"text":"_registries"},{"col":4,"comment":"null","endLoc":124,"header":"def test_deprecated_explicit_call(self)","id":5796,"name":"test_deprecated_explicit_call","nodeType":"Function","startLoc":122,"text":"def test_deprecated_explicit_call(self):\n pytest.deprecated_call(self.dep_explicit, 0)\n pytest.deprecated_call(self.dep_explicit, 0)"},{"col":4,"comment":"Ensure deprecated_call() raises the expected failure when its block/function does\n not raise a deprecation warning.\n ","endLoc":141,"header":"@pytest.mark.parametrize(\"mode\", [\"context_manager\", \"call\"])\n def test_deprecated_call_no_warning(self, mode)","id":5797,"name":"test_deprecated_call_no_warning","nodeType":"Function","startLoc":126,"text":"@pytest.mark.parametrize(\"mode\", [\"context_manager\", \"call\"])\n def test_deprecated_call_no_warning(self, mode):\n \"\"\"Ensure deprecated_call() raises the expected failure when its block/function does\n not raise a deprecation warning.\n \"\"\"\n\n def f():\n pass\n\n msg = \"No warnings of type (.*DeprecationWarning.*, .*PendingDeprecationWarning.*)\"\n with pytest.raises(pytest.fail.Exception, match=msg):\n if mode == \"call\":\n pytest.deprecated_call(f)\n else:\n with pytest.deprecated_call():\n f()"},{"attributeType":"list","col":4,"comment":"null","endLoc":74,"id":5798,"name":"_actions","nodeType":"Attribute","startLoc":74,"text":"_actions"},{"attributeType":"dict","col":4,"comment":"null","endLoc":75,"id":5799,"name":"_option_string_actions","nodeType":"Attribute","startLoc":75,"text":"_option_string_actions"},{"col":4,"comment":"Ensure deprecated_call() captures a deprecation warning as expected inside its\n block/function.\n ","endLoc":165,"header":"@pytest.mark.parametrize(\n \"warning_type\", [PendingDeprecationWarning, DeprecationWarning]\n )\n @pytest.mark.parametrize(\"mode\", [\"context_manager\", \"call\"])\n @pytest.mark.parametrize(\"call_f_first\", [True, False])\n @pytest.mark.filterwarnings(\"ignore\")\n def test_deprecated_call_modes(self, warning_type, mode, call_f_first)","id":5801,"name":"test_deprecated_call_modes","nodeType":"Function","startLoc":143,"text":"@pytest.mark.parametrize(\n \"warning_type\", [PendingDeprecationWarning, DeprecationWarning]\n )\n @pytest.mark.parametrize(\"mode\", [\"context_manager\", \"call\"])\n @pytest.mark.parametrize(\"call_f_first\", [True, False])\n @pytest.mark.filterwarnings(\"ignore\")\n def test_deprecated_call_modes(self, warning_type, mode, call_f_first):\n \"\"\"Ensure deprecated_call() captures a deprecation warning as expected inside its\n block/function.\n \"\"\"\n\n def f():\n warnings.warn(warning_type(\"hi\"))\n return 10\n\n # ensure deprecated_call() can capture the warning even if it has already been triggered\n if call_f_first:\n assert f() == 10\n if mode == \"call\":\n assert pytest.deprecated_call(f) == 10\n else:\n with pytest.deprecated_call():\n assert f() == 10"},{"attributeType":"list","col":4,"comment":"null","endLoc":76,"id":5802,"name":"_action_groups","nodeType":"Attribute","startLoc":76,"text":"_action_groups"},{"attributeType":"list","col":4,"comment":"null","endLoc":77,"id":5803,"name":"_mutually_exclusive_groups","nodeType":"Attribute","startLoc":77,"text":"_mutually_exclusive_groups"},{"attributeType":"dict","col":4,"comment":"null","endLoc":78,"id":5804,"name":"_defaults","nodeType":"Attribute","startLoc":78,"text":"_defaults"},{"attributeType":"Pattern","col":4,"comment":"null","endLoc":79,"id":5805,"name":"_negative_number_matcher","nodeType":"Attribute","startLoc":79,"text":"_negative_number_matcher"},{"col":4,"comment":"null","endLoc":658,"header":"def test_header(self, testdir, request)","id":5807,"name":"test_header","nodeType":"Function","startLoc":631,"text":"def test_header(self, testdir, request):\n testdir.tmpdir.join(\"tests\").ensure_dir()\n testdir.tmpdir.join(\"gui\").ensure_dir()\n\n # no ini file\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"rootdir: *test_header0\"])\n\n # with inifile\n testdir.makeini(\"\"\"[pytest]\"\"\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"rootdir: *test_header0, inifile: tox.ini\"])\n\n # with testpaths option, and not passing anything in the command-line\n testdir.makeini(\n \"\"\"\n [pytest]\n testpaths = tests gui\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"rootdir: *test_header0, inifile: tox.ini, testpaths: tests, gui\"]\n )\n\n # with testpaths option, passing directory in command-line: do not show testpaths then\n result = testdir.runpytest(\"tests\")\n result.stdout.fnmatch_lines([\"rootdir: *test_header0, inifile: tox.ini\"])"},{"attributeType":"list","col":4,"comment":"null","endLoc":80,"id":5808,"name":"_has_negative_number_optionals","nodeType":"Attribute","startLoc":80,"text":"_has_negative_number_optionals"},{"attributeType":"str","col":8,"comment":"null","endLoc":982,"id":5809,"name":"path","nodeType":"Attribute","startLoc":982,"text":"self.path"},{"col":4,"comment":"null","endLoc":194,"header":"@overload\n def add_subparsers(\n self: _ArgumentParserT,\n *,\n title: str = ...,\n description: str | None = ...,\n prog: str = ...,\n action: type[Action] = ...,\n option_string: str = ...,\n dest: str | None = ...,\n required: bool = ...,\n help: str | None = ...,\n metavar: str | None = ...,\n ) -> _SubParsersAction[_ArgumentParserT]","id":5810,"name":"add_subparsers","nodeType":"Function","startLoc":181,"text":"@overload\n def add_subparsers(\n self: _ArgumentParserT,\n *,\n title: str = ...,\n description: str | None = ...,\n prog: str = ...,\n action: type[Action] = ...,\n option_string: str = ...,\n dest: str | None = ...,\n required: bool = ...,\n help: str | None = ...,\n metavar: str | None = ...,\n ) -> _SubParsersAction[_ArgumentParserT]: ..."},{"col":4,"comment":"null","endLoc":209,"header":"@overload\n def add_subparsers(\n self,\n *,\n title: str = ...,\n description: str | None = ...,\n prog: str = ...,\n parser_class: type[_ArgumentParserT],\n action: type[Action] = ...,\n option_string: str = ...,\n dest: str | None = ...,\n required: bool = ...,\n help: str | None = ...,\n metavar: str | None = ...,\n ) -> _SubParsersAction[_ArgumentParserT]","id":5811,"name":"add_subparsers","nodeType":"Function","startLoc":195,"text":"@overload\n def add_subparsers(\n self,\n *,\n title: str = ...,\n description: str | None = ...,\n prog: str = ...,\n parser_class: type[_ArgumentParserT],\n action: type[Action] = ...,\n option_string: str = ...,\n dest: str | None = ...,\n required: bool = ...,\n help: str | None = ...,\n metavar: str | None = ...,\n ) -> _SubParsersAction[_ArgumentParserT]: ..."},{"col":4,"comment":"null","endLoc":210,"header":"def print_usage(self, file: IO[str] | None = None) -> None","id":5812,"name":"print_usage","nodeType":"Function","startLoc":210,"text":"def print_usage(self, file: IO[str] | None = None) -> None: ..."},{"col":4,"comment":"null","endLoc":211,"header":"def print_help(self, file: IO[str] | None = None) -> None","id":5813,"name":"print_help","nodeType":"Function","startLoc":211,"text":"def print_help(self, file: IO[str] | None = None) -> None: ..."},{"col":4,"comment":"null","endLoc":212,"header":"def format_usage(self) -> str","id":5814,"name":"format_usage","nodeType":"Function","startLoc":212,"text":"def format_usage(self) -> str: ..."},{"col":4,"comment":"null","endLoc":213,"header":"def format_help(self) -> str","id":5815,"name":"format_help","nodeType":"Function","startLoc":213,"text":"def format_help(self) -> str: ..."},{"col":4,"comment":"null","endLoc":215,"header":"@overload\n def parse_known_args(self, args: Sequence[str] | None = None, namespace: None = None) -> tuple[Namespace, list[str]]","id":5816,"name":"parse_known_args","nodeType":"Function","startLoc":214,"text":"@overload\n def parse_known_args(self, args: Sequence[str] | None = None, namespace: None = None) -> tuple[Namespace, list[str]]: ..."},{"col":4,"comment":"null","endLoc":217,"header":"@overload\n def parse_known_args(self, args: Sequence[str] | None, namespace: _N) -> tuple[_N, list[str]]","id":5817,"name":"parse_known_args","nodeType":"Function","startLoc":216,"text":"@overload\n def parse_known_args(self, args: Sequence[str] | None, namespace: _N) -> tuple[_N, list[str]]: ..."},{"col":4,"comment":"null","endLoc":219,"header":"@overload\n def parse_known_args(self, *, namespace: _N) -> tuple[_N, list[str]]","id":5818,"name":"parse_known_args","nodeType":"Function","startLoc":218,"text":"@overload\n def parse_known_args(self, *, namespace: _N) -> tuple[_N, list[str]]: ..."},{"col":4,"comment":"null","endLoc":220,"header":"def convert_arg_line_to_args(self, arg_line: str) -> list[str]","id":5819,"name":"convert_arg_line_to_args","nodeType":"Function","startLoc":220,"text":"def convert_arg_line_to_args(self, arg_line: str) -> list[str]: ..."},{"col":4,"comment":"null","endLoc":221,"header":"def exit(self, status: int = 0, message: str | None = None) -> NoReturn","id":5820,"name":"exit","nodeType":"Function","startLoc":221,"text":"def exit(self, status: int = 0, message: str | None = None) -> NoReturn: ..."},{"col":4,"comment":"null","endLoc":222,"header":"def error(self, message: str) -> NoReturn","id":5821,"name":"error","nodeType":"Function","startLoc":222,"text":"def error(self, message: str) -> NoReturn: ..."},{"col":4,"comment":"null","endLoc":224,"header":"@overload\n def parse_intermixed_args(self, args: Sequence[str] | None = None, namespace: None = None) -> Namespace","id":5822,"name":"parse_intermixed_args","nodeType":"Function","startLoc":223,"text":"@overload\n def parse_intermixed_args(self, args: Sequence[str] | None = None, namespace: None = None) -> Namespace: ..."},{"col":4,"comment":"null","endLoc":226,"header":"@overload\n def parse_intermixed_args(self, args: Sequence[str] | None, namespace: _N) -> _N","id":5823,"name":"parse_intermixed_args","nodeType":"Function","startLoc":225,"text":"@overload\n def parse_intermixed_args(self, args: Sequence[str] | None, namespace: _N) -> _N: ..."},{"col":4,"comment":"null","endLoc":228,"header":"@overload\n def parse_intermixed_args(self, *, namespace: _N) -> _N","id":5824,"name":"parse_intermixed_args","nodeType":"Function","startLoc":227,"text":"@overload\n def parse_intermixed_args(self, *, namespace: _N) -> _N: ..."},{"col":4,"comment":"null","endLoc":232,"header":"@overload\n def parse_known_intermixed_args(\n self, args: Sequence[str] | None = None, namespace: None = None\n ) -> tuple[Namespace, list[str]]","id":5825,"name":"parse_known_intermixed_args","nodeType":"Function","startLoc":229,"text":"@overload\n def parse_known_intermixed_args(\n self, args: Sequence[str] | None = None, namespace: None = None\n ) -> tuple[Namespace, list[str]]: ..."},{"col":4,"comment":"null","endLoc":234,"header":"@overload\n def parse_known_intermixed_args(self, args: Sequence[str] | None, namespace: _N) -> tuple[_N, list[str]]","id":5826,"name":"parse_known_intermixed_args","nodeType":"Function","startLoc":233,"text":"@overload\n def parse_known_intermixed_args(self, args: Sequence[str] | None, namespace: _N) -> tuple[_N, list[str]]: ..."},{"col":4,"comment":"null","endLoc":236,"header":"@overload\n def parse_known_intermixed_args(self, *, namespace: _N) -> tuple[_N, list[str]]","id":5827,"name":"parse_known_intermixed_args","nodeType":"Function","startLoc":235,"text":"@overload\n def parse_known_intermixed_args(self, *, namespace: _N) -> tuple[_N, list[str]]: ..."},{"col":4,"comment":"null","endLoc":238,"header":"def _get_optional_actions(self) -> list[Action]","id":5828,"name":"_get_optional_actions","nodeType":"Function","startLoc":238,"text":"def _get_optional_actions(self) -> list[Action]: ..."},{"col":4,"comment":"null","endLoc":239,"header":"def _get_positional_actions(self) -> list[Action]","id":5829,"name":"_get_positional_actions","nodeType":"Function","startLoc":239,"text":"def _get_positional_actions(self) -> list[Action]: ..."},{"col":4,"comment":"null","endLoc":240,"header":"def _parse_known_args(self, arg_strings: list[str], namespace: Namespace) -> tuple[Namespace, list[str]]","id":5830,"name":"_parse_known_args","nodeType":"Function","startLoc":240,"text":"def _parse_known_args(self, arg_strings: list[str], namespace: Namespace) -> tuple[Namespace, list[str]]: ..."},{"col":4,"comment":"null","endLoc":241,"header":"def _read_args_from_files(self, arg_strings: list[str]) -> list[str]","id":5831,"name":"_read_args_from_files","nodeType":"Function","startLoc":241,"text":"def _read_args_from_files(self, arg_strings: list[str]) -> list[str]: ..."},{"col":4,"comment":"null","endLoc":242,"header":"def _match_argument(self, action: Action, arg_strings_pattern: str) -> int","id":5832,"name":"_match_argument","nodeType":"Function","startLoc":242,"text":"def _match_argument(self, action: Action, arg_strings_pattern: str) -> int: ..."},{"col":4,"comment":"null","endLoc":243,"header":"def _match_arguments_partial(self, actions: Sequence[Action], arg_strings_pattern: str) -> list[int]","id":5833,"name":"_match_arguments_partial","nodeType":"Function","startLoc":243,"text":"def _match_arguments_partial(self, actions: Sequence[Action], arg_strings_pattern: str) -> list[int]: ..."},{"col":4,"comment":"null","endLoc":244,"header":"def _parse_optional(self, arg_string: str) -> tuple[Action | None, str, str | None] | None","id":5834,"name":"_parse_optional","nodeType":"Function","startLoc":244,"text":"def _parse_optional(self, arg_string: str) -> tuple[Action | None, str, str | None] | None: ..."},{"col":4,"comment":"null","endLoc":245,"header":"def _get_option_tuples(self, option_string: str) -> list[tuple[Action, str, str | None]]","id":5835,"name":"_get_option_tuples","nodeType":"Function","startLoc":245,"text":"def _get_option_tuples(self, option_string: str) -> list[tuple[Action, str, str | None]]: ..."},{"col":4,"comment":"null","endLoc":246,"header":"def _get_nargs_pattern(self, action: Action) -> str","id":5836,"name":"_get_nargs_pattern","nodeType":"Function","startLoc":246,"text":"def _get_nargs_pattern(self, action: Action) -> str: ..."},{"col":4,"comment":"null","endLoc":247,"header":"def _get_values(self, action: Action, arg_strings: list[str]) -> Any","id":5837,"name":"_get_values","nodeType":"Function","startLoc":247,"text":"def _get_values(self, action: Action, arg_strings: list[str]) -> Any: ..."},{"col":4,"comment":"null","endLoc":248,"header":"def _get_value(self, action: Action, arg_string: str) -> Any","id":5838,"name":"_get_value","nodeType":"Function","startLoc":248,"text":"def _get_value(self, action: Action, arg_string: str) -> Any: ..."},{"col":4,"comment":"null","endLoc":249,"header":"def _check_value(self, action: Action, value: Any) -> None","id":5839,"name":"_check_value","nodeType":"Function","startLoc":249,"text":"def _check_value(self, action: Action, value: Any) -> None: ..."},{"col":4,"comment":"null","endLoc":250,"header":"def _get_formatter(self) -> HelpFormatter","id":5840,"name":"_get_formatter","nodeType":"Function","startLoc":250,"text":"def _get_formatter(self) -> HelpFormatter: ..."},{"col":4,"comment":"null","endLoc":251,"header":"def _print_message(self, message: str, file: IO[str] | None = None) -> None","id":5841,"name":"_print_message","nodeType":"Function","startLoc":251,"text":"def _print_message(self, message: str, file: IO[str] | None = None) -> None: ..."},{"attributeType":"str","col":4,"comment":"null","endLoc":127,"id":5842,"name":"prog","nodeType":"Attribute","startLoc":127,"text":"prog"},{"attributeType":"str | None","col":4,"comment":"null","endLoc":128,"id":5843,"name":"usage","nodeType":"Attribute","startLoc":128,"text":"usage"},{"col":4,"comment":"null","endLoc":676,"header":"def test_showlocals(self, testdir)","id":5844,"name":"test_showlocals","nodeType":"Function","startLoc":660,"text":"def test_showlocals(self, testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def test_showlocals():\n x = 3\n y = \"x\" * 5000\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p1, \"-l\")\n result.stdout.fnmatch_lines(\n [\n # \"_ _ * Locals *\",\n \"x* = 3\",\n \"y* = 'xxxxxx*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":695,"header":"@pytest.fixture\n def verbose_testfile(self, testdir)","id":5845,"name":"verbose_testfile","nodeType":"Function","startLoc":678,"text":"@pytest.fixture\n def verbose_testfile(self, testdir):\n return testdir.makepyfile(\n \"\"\"\n import pytest\n def test_fail():\n raise ValueError()\n def test_pass():\n pass\n class TestClass(object):\n def test_skip(self):\n pytest.skip(\"hello\")\n def test_gen():\n def check(x):\n assert x == 1\n yield check, 0\n \"\"\"\n )"},{"attributeType":"str | None","col":4,"comment":"null","endLoc":129,"id":5846,"name":"epilog","nodeType":"Attribute","startLoc":129,"text":"epilog"},{"attributeType":"_FormatterClass","col":4,"comment":"null","endLoc":130,"id":5847,"name":"formatter_class","nodeType":"Attribute","startLoc":130,"text":"formatter_class"},{"col":4,"comment":"null","endLoc":709,"header":"def test_verbose_reporting(self, verbose_testfile, testdir, pytestconfig)","id":5848,"name":"test_verbose_reporting","nodeType":"Function","startLoc":697,"text":"def test_verbose_reporting(self, verbose_testfile, testdir, pytestconfig):\n result = testdir.runpytest(\n verbose_testfile, \"-v\", \"-Walways::pytest.PytestWarning\"\n )\n result.stdout.fnmatch_lines(\n [\n \"*test_verbose_reporting.py::test_fail *FAIL*\",\n \"*test_verbose_reporting.py::test_pass *PASS*\",\n \"*test_verbose_reporting.py::TestClass::test_skip *SKIP*\",\n \"*test_verbose_reporting.py::test_gen *XFAIL*\",\n ]\n )\n assert result.ret == 1"},{"attributeType":"str | None","col":4,"comment":"null","endLoc":131,"id":5849,"name":"fromfile_prefix_chars","nodeType":"Attribute","startLoc":131,"text":"fromfile_prefix_chars"},{"col":4,"comment":"null","endLoc":721,"header":"def test_verbose_reporting_xdist(self, verbose_testfile, testdir, pytestconfig)","id":5850,"name":"test_verbose_reporting_xdist","nodeType":"Function","startLoc":711,"text":"def test_verbose_reporting_xdist(self, verbose_testfile, testdir, pytestconfig):\n if not pytestconfig.pluginmanager.get_plugin(\"xdist\"):\n pytest.skip(\"xdist plugin not installed\")\n\n result = testdir.runpytest(\n verbose_testfile, \"-v\", \"-n 1\", \"-Walways::pytest.PytestWarning\"\n )\n result.stdout.fnmatch_lines(\n [\"*FAIL*test_verbose_reporting_xdist.py::test_fail*\"]\n )\n assert result.ret == 1"},{"attributeType":"bool","col":4,"comment":"null","endLoc":132,"id":5851,"name":"add_help","nodeType":"Attribute","startLoc":132,"text":"add_help"},{"attributeType":"bool","col":4,"comment":"null","endLoc":133,"id":5852,"name":"allow_abbrev","nodeType":"Attribute","startLoc":133,"text":"allow_abbrev"},{"attributeType":"_ArgumentGroup","col":4,"comment":"null","endLoc":136,"id":5853,"name":"_positionals","nodeType":"Attribute","startLoc":136,"text":"_positionals"},{"col":4,"comment":"If the block of the code being tested by deprecated_call() raises an exception,\n it must raise the exception undisturbed.\n ","endLoc":181,"header":"@pytest.mark.parametrize(\"mode\", [\"context_manager\", \"call\"])\n def test_deprecated_call_exception_is_raised(self, mode)","id":5854,"name":"test_deprecated_call_exception_is_raised","nodeType":"Function","startLoc":167,"text":"@pytest.mark.parametrize(\"mode\", [\"context_manager\", \"call\"])\n def test_deprecated_call_exception_is_raised(self, mode):\n \"\"\"If the block of the code being tested by deprecated_call() raises an exception,\n it must raise the exception undisturbed.\n \"\"\"\n\n def f():\n raise ValueError(\"some exception\")\n\n with pytest.raises(ValueError, match=\"some exception\"):\n if mode == \"call\":\n pytest.deprecated_call(f)\n else:\n with pytest.deprecated_call():\n f()"},{"col":4,"comment":"null","endLoc":730,"header":"def test_quiet_reporting(self, testdir)","id":5855,"name":"test_quiet_reporting","nodeType":"Function","startLoc":723,"text":"def test_quiet_reporting(self, testdir):\n p1 = testdir.makepyfile(\"def test_pass(): pass\")\n result = testdir.runpytest(p1, \"-q\")\n s = result.stdout.str()\n assert \"test session starts\" not in s\n assert p1.basename not in s\n assert \"===\" not in s\n assert \"passed\" in s"},{"attributeType":"_ArgumentGroup","col":4,"comment":"null","endLoc":137,"id":5856,"name":"_optionals","nodeType":"Attribute","startLoc":137,"text":"_optionals"},{"attributeType":"_ArgumentGroup | None","col":4,"comment":"null","endLoc":138,"id":5857,"name":"_subparsers","nodeType":"Attribute","startLoc":138,"text":"_subparsers"},{"col":4,"comment":"null","endLoc":739,"header":"def test_more_quiet_reporting(self, testdir)","id":5858,"name":"test_more_quiet_reporting","nodeType":"Function","startLoc":732,"text":"def test_more_quiet_reporting(self, testdir):\n p1 = testdir.makepyfile(\"def test_pass(): pass\")\n result = testdir.runpytest(p1, \"-qq\")\n s = result.stdout.str()\n assert \"test session starts\" not in s\n assert p1.basename not in s\n assert \"===\" not in s\n assert \"passed\" not in s"},{"col":4,"comment":"Transform argparse error message into UsageError.","endLoc":345,"header":"def error(self, message)","id":5859,"name":"error","nodeType":"Function","startLoc":338,"text":"def error(self, message):\n \"\"\"Transform argparse error message into UsageError.\"\"\"\n msg = \"%s: error: %s\" % (self.prog, message)\n\n if hasattr(self._parser, \"_config_source_hint\"):\n msg = \"%s (%s)\" % (msg, self._parser._config_source_hint)\n\n raise UsageError(self.format_usage() + msg)"},{"col":4,"comment":"null","endLoc":760,"header":"@pytest.mark.parametrize(\n \"params\", [(), (\"--collect-only\",)], ids=[\"no-params\", \"collect-only\"]\n )\n def test_report_collectionfinish_hook(self, testdir, params)","id":5860,"name":"test_report_collectionfinish_hook","nodeType":"Function","startLoc":741,"text":"@pytest.mark.parametrize(\n \"params\", [(), (\"--collect-only\",)], ids=[\"no-params\", \"collect-only\"]\n )\n def test_report_collectionfinish_hook(self, testdir, params):\n testdir.makeconftest(\n \"\"\"\n def pytest_report_collectionfinish(config, startdir, items):\n return ['hello from hook: {0} items'.format(len(items))]\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('i', range(3))\n def test(i):\n pass\n \"\"\"\n )\n result = testdir.runpytest(*params)\n result.stdout.fnmatch_lines([\"collected 3 items\", \"hello from hook: 3 items\"])"},{"col":4,"comment":"null","endLoc":99,"header":"def _exec_lsof(self)","id":5861,"name":"_exec_lsof","nodeType":"Function","startLoc":93,"text":"def _exec_lsof(self):\n pid = os.getpid()\n # py3: use subprocess.DEVNULL directly.\n with open(os.devnull, \"wb\") as devnull:\n return subprocess.check_output(\n (\"lsof\", \"-Ffn0\", \"-p\", str(pid)), stderr=devnull\n ).decode()"},{"col":0,"comment":"Integration test for issue #3775","endLoc":839,"header":"def test_collect_pytest_prefix_bug_integration(testdir)","id":5862,"name":"test_collect_pytest_prefix_bug_integration","nodeType":"Function","startLoc":835,"text":"def test_collect_pytest_prefix_bug_integration(testdir):\n \"\"\"Integration test for issue #3775\"\"\"\n p = testdir.copy_example(\"config/collect_pytest_prefix\")\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"* 1 passed *\"])"},{"col":4,"comment":"null","endLoc":122,"header":"def _parse_lsof_output(self, out)","id":5863,"name":"_parse_lsof_output","nodeType":"Function","startLoc":101,"text":"def _parse_lsof_output(self, out):\n def isopen(line):\n return line.startswith(\"f\") and (\n \"deleted\" not in line\n and \"mem\" not in line\n and \"txt\" not in line\n and \"cwd\" not in line\n )\n\n open_files = []\n\n for line in out.split(\"\\n\"):\n if isopen(line):\n fields = line.split(\"\\0\")\n fd = fields[0][1:]\n filename = fields[1][1:]\n if filename in IGNORE_PAM:\n continue\n if filename.startswith(\"/\"):\n open_files.append((fd, filename))\n\n return open_files"},{"col":4,"comment":"null","endLoc":130,"header":"def matching_platform(self)","id":5865,"name":"matching_platform","nodeType":"Function","startLoc":124,"text":"def matching_platform(self):\n try:\n subprocess.check_output((\"lsof\", \"-v\"))\n except (OSError, subprocess.CalledProcessError):\n return False\n else:\n return True"},{"attributeType":"null","col":8,"comment":"null","endLoc":983,"id":5866,"name":"lineno","nodeType":"Attribute","startLoc":983,"text":"self.lineno"},{"col":4,"comment":"null","endLoc":153,"header":"@pytest.hookimpl(hookwrapper=True, tryfirst=True)\n def pytest_runtest_protocol(self, item)","id":5867,"name":"pytest_runtest_protocol","nodeType":"Function","startLoc":132,"text":"@pytest.hookimpl(hookwrapper=True, tryfirst=True)\n def pytest_runtest_protocol(self, item):\n lines1 = self.get_open_files()\n yield\n if hasattr(sys, \"pypy_version_info\"):\n gc.collect()\n lines2 = self.get_open_files()\n\n new_fds = {t[0] for t in lines2} - {t[0] for t in lines1}\n leaked_files = [t for t in lines2 if t[0] in new_fds]\n if leaked_files:\n error = []\n error.append(\"***** %s FD leakage detected\" % len(leaked_files))\n error.extend([str(f) for f in leaked_files])\n error.append(\"*** Before:\")\n error.extend([str(f) for f in lines1])\n error.append(\"*** After:\")\n error.extend([str(f) for f in lines2])\n error.append(error[0])\n error.append(\"*** function %s:%s: %s \" % item.location)\n error.append(\"See issue #2366\")\n item.warn(pytest.PytestWarning(\"\\n\".join(error)))"},{"col":4,"comment":"null","endLoc":120,"header":"def test_marked_one_arg_twice2(self, testdir)","id":5868,"name":"test_marked_one_arg_twice2","nodeType":"Function","startLoc":106,"text":"def test_marked_one_arg_twice2(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.skipif(\"hasattr(os, 'murks')\")\n @pytest.mark.skipif(\"not hasattr(os, 'murks')\")\n def test_func():\n pass\n \"\"\"\n )\n ev = MarkEvaluator(item, \"skipif\")\n assert ev\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"condition: not hasattr(os, 'murks')\""},{"attributeType":"null","col":8,"comment":"null","endLoc":984,"id":5869,"name":"message","nodeType":"Attribute","startLoc":984,"text":"self.message"},{"className":"ReprLocals","col":0,"comment":"null","endLoc":1003,"id":5870,"nodeType":"Class","startLoc":997,"text":"class ReprLocals(TerminalRepr):\n def __init__(self, lines):\n self.lines = lines\n\n def toterminal(self, tw):\n for line in self.lines:\n tw.line(line)"},{"className":"TestGenericReporting","col":0,"comment":" this test class can be subclassed with a different option\n provider to run e.g. distributed tests.\n ","endLoc":1131,"id":5871,"nodeType":"Class","startLoc":948,"text":"class TestGenericReporting(object):\n \"\"\" this test class can be subclassed with a different option\n provider to run e.g. distributed tests.\n \"\"\"\n\n def test_collect_fail(self, testdir, option):\n testdir.makepyfile(\"import xyz\\n\")\n result = testdir.runpytest(*option.args)\n result.stdout.fnmatch_lines(\n [\"ImportError while importing*\", \"*No module named *xyz*\", \"*1 error*\"]\n )\n\n def test_maxfailures(self, testdir, option):\n testdir.makepyfile(\n \"\"\"\n def test_1():\n assert 0\n def test_2():\n assert 0\n def test_3():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"--maxfail=2\", *option.args)\n result.stdout.fnmatch_lines(\n [\"*def test_1():*\", \"*def test_2():*\", \"*2 failed*\"]\n )\n\n def test_tb_option(self, testdir, option):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def g():\n raise IndexError\n def test_func():\n print(6*7)\n g() # --calling--\n \"\"\"\n )\n for tbopt in [\"long\", \"short\", \"no\"]:\n print(\"testing --tb=%s...\" % tbopt)\n result = testdir.runpytest(\"--tb=%s\" % tbopt)\n s = result.stdout.str()\n if tbopt == \"long\":\n assert \"print(6*7)\" in s\n else:\n assert \"print(6*7)\" not in s\n if tbopt != \"no\":\n assert \"--calling--\" in s\n assert \"IndexError\" in s\n else:\n assert \"FAILURES\" not in s\n assert \"--calling--\" not in s\n assert \"IndexError\" not in s\n\n def test_tb_crashline(self, testdir, option):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def g():\n raise IndexError\n def test_func1():\n print(6*7)\n g() # --calling--\n def test_func2():\n assert 0, \"hello\"\n \"\"\"\n )\n result = testdir.runpytest(\"--tb=line\")\n bn = p.basename\n result.stdout.fnmatch_lines(\n [\"*%s:3: IndexError*\" % bn, \"*%s:8: AssertionError: hello*\" % bn]\n )\n s = result.stdout.str()\n assert \"def test_func2\" not in s\n\n def test_pytest_report_header(self, testdir, option):\n testdir.makeconftest(\n \"\"\"\n def pytest_sessionstart(session):\n session.config._somevalue = 42\n def pytest_report_header(config):\n return \"hello: %s\" % config._somevalue\n \"\"\"\n )\n testdir.mkdir(\"a\").join(\"conftest.py\").write(\n \"\"\"\ndef pytest_report_header(config, startdir):\n return [\"line1\", str(startdir)]\n\"\"\"\n )\n result = testdir.runpytest(\"a\")\n result.stdout.fnmatch_lines([\"*hello: 42*\", \"line1\", str(testdir.tmpdir)])\n\n def test_show_capture(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n import logging\n def test_one():\n sys.stdout.write('!This is stdout!')\n sys.stderr.write('!This is stderr!')\n logging.warning('!This is a warning log msg!')\n assert False, 'Something failed'\n \"\"\"\n )\n\n result = testdir.runpytest(\"--tb=short\")\n result.stdout.fnmatch_lines(\n [\n \"!This is stdout!\",\n \"!This is stderr!\",\n \"*WARNING*!This is a warning log msg!\",\n ]\n )\n\n result = testdir.runpytest(\"--show-capture=all\", \"--tb=short\")\n result.stdout.fnmatch_lines(\n [\n \"!This is stdout!\",\n \"!This is stderr!\",\n \"*WARNING*!This is a warning log msg!\",\n ]\n )\n\n stdout = testdir.runpytest(\"--show-capture=stdout\", \"--tb=short\").stdout.str()\n assert \"!This is stderr!\" not in stdout\n assert \"!This is stdout!\" in stdout\n assert \"!This is a warning log msg!\" not in stdout\n\n stdout = testdir.runpytest(\"--show-capture=stderr\", \"--tb=short\").stdout.str()\n assert \"!This is stdout!\" not in stdout\n assert \"!This is stderr!\" in stdout\n assert \"!This is a warning log msg!\" not in stdout\n\n stdout = testdir.runpytest(\"--show-capture=log\", \"--tb=short\").stdout.str()\n assert \"!This is stdout!\" not in stdout\n assert \"!This is stderr!\" not in stdout\n assert \"!This is a warning log msg!\" in stdout\n\n stdout = testdir.runpytest(\"--show-capture=no\", \"--tb=short\").stdout.str()\n assert \"!This is stdout!\" not in stdout\n assert \"!This is stderr!\" not in stdout\n assert \"!This is a warning log msg!\" not in stdout\n\n def test_show_capture_with_teardown_logs(self, testdir):\n \"\"\"Ensure that the capturing of teardown logs honor --show-capture setting\"\"\"\n testdir.makepyfile(\n \"\"\"\n import logging\n import sys\n import pytest\n\n @pytest.fixture(scope=\"function\", autouse=\"True\")\n def hook_each_test(request):\n yield\n sys.stdout.write(\"!stdout!\")\n sys.stderr.write(\"!stderr!\")\n logging.warning(\"!log!\")\n\n def test_func():\n assert False\n \"\"\"\n )\n\n result = testdir.runpytest(\"--show-capture=stdout\", \"--tb=short\").stdout.str()\n assert \"!stdout!\" in result\n assert \"!stderr!\" not in result\n assert \"!log!\" not in result\n\n result = testdir.runpytest(\"--show-capture=stderr\", \"--tb=short\").stdout.str()\n assert \"!stdout!\" not in result\n assert \"!stderr!\" in result\n assert \"!log!\" not in result\n\n result = testdir.runpytest(\"--show-capture=log\", \"--tb=short\").stdout.str()\n assert \"!stdout!\" not in result\n assert \"!stderr!\" not in result\n assert \"!log!\" in result\n\n result = testdir.runpytest(\"--show-capture=no\", \"--tb=short\").stdout.str()\n assert \"!stdout!\" not in result\n assert \"!stderr!\" not in result\n assert \"!log!\" not in result"},{"col":4,"comment":"null","endLoc":1003,"header":"def toterminal(self, tw)","id":5872,"name":"toterminal","nodeType":"Function","startLoc":1001,"text":"def toterminal(self, tw):\n for line in self.lines:\n tw.line(line)"},{"attributeType":"null","col":8,"comment":"null","endLoc":999,"id":5873,"name":"lines","nodeType":"Attribute","startLoc":999,"text":"self.lines"},{"col":4,"comment":"null","endLoc":958,"header":"def test_collect_fail(self, testdir, option)","id":5874,"name":"test_collect_fail","nodeType":"Function","startLoc":953,"text":"def test_collect_fail(self, testdir, option):\n testdir.makepyfile(\"import xyz\\n\")\n result = testdir.runpytest(*option.args)\n result.stdout.fnmatch_lines(\n [\"ImportError while importing*\", \"*No module named *xyz*\", \"*1 error*\"]\n )"},{"col":0,"comment":"Ensure we collect only actual functions from conftest files (#3775)","endLoc":850,"header":"def test_collect_pytest_prefix_bug(pytestconfig)","id":5875,"name":"test_collect_pytest_prefix_bug","nodeType":"Function","startLoc":842,"text":"def test_collect_pytest_prefix_bug(pytestconfig):\n \"\"\"Ensure we collect only actual functions from conftest files (#3775)\"\"\"\n\n class Dummy(object):\n class pytest_something(object):\n pass\n\n pm = pytestconfig.pluginmanager\n assert pm.parse_hookimpl_opts(Dummy(), \"pytest_something\") is None"},{"col":4,"comment":"allow splitting of positional arguments","endLoc":358,"header":"def parse_args(self, args=None, namespace=None)","id":5876,"name":"parse_args","nodeType":"Function","startLoc":347,"text":"def parse_args(self, args=None, namespace=None):\n \"\"\"allow splitting of positional arguments\"\"\"\n args, argv = self.parse_known_args(args, namespace)\n if argv:\n for arg in argv:\n if arg and arg[0] == \"-\":\n lines = [\"unrecognized arguments: %s\" % (\" \".join(argv))]\n for k, v in sorted(self.extra_info.items()):\n lines.append(\" %s: %s\" % (k, v))\n self.error(\"\\n\".join(lines))\n getattr(args, FILE_OR_DIR).extend(argv)\n return args"},{"col":4,"comment":"null","endLoc":136,"header":"def test_marked_skip_with_not_string(self, testdir)","id":5877,"name":"test_marked_skip_with_not_string","nodeType":"Function","startLoc":122,"text":"def test_marked_skip_with_not_string(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.skipif(False)\n def test_func():\n pass\n \"\"\"\n )\n ev = MarkEvaluator(item, \"skipif\")\n exc = pytest.raises(pytest.fail.Exception, ev.istrue)\n assert (\n \"\"\"Failed: you need to specify reason=STRING when using booleans as conditions.\"\"\"\n in exc.value.msg\n )"},{"className":"ReprFuncArgs","col":0,"comment":"null","endLoc":1026,"id":5878,"nodeType":"Class","startLoc":1006,"text":"class ReprFuncArgs(TerminalRepr):\n def __init__(self, args):\n self.args = args\n\n def toterminal(self, tw):\n if self.args:\n linesofar = \"\"\n for name, value in self.args:\n ns = \"%s = %s\" % (safe_str(name), safe_str(value))\n if len(ns) + len(linesofar) + 2 > tw.fullwidth:\n if linesofar:\n tw.line(linesofar)\n linesofar = ns\n else:\n if linesofar:\n linesofar += \", \" + ns\n else:\n linesofar = ns\n if linesofar:\n tw.line(linesofar)\n tw.line(\"\")"},{"attributeType":"null","col":8,"comment":"null","endLoc":1008,"id":5879,"name":"args","nodeType":"Attribute","startLoc":1008,"text":"self.args"},{"col":4,"comment":"null","endLoc":152,"header":"def test_skipif_class(self, testdir)","id":5880,"name":"test_skipif_class","nodeType":"Function","startLoc":138,"text":"def test_skipif_class(self, testdir):\n item, = testdir.getitems(\n \"\"\"\n import pytest\n class TestClass(object):\n pytestmark = pytest.mark.skipif(\"config._hackxyz\")\n def test_func(self):\n pass\n \"\"\"\n )\n item.config._hackxyz = 3\n ev = MarkEvaluator(item, \"skipif\")\n assert ev.istrue()\n expl = ev.getexplanation()\n assert expl == \"condition: config._hackxyz\""},{"attributeType":"CodeType","col":0,"comment":"null","endLoc":383,"id":5881,"name":"co_equal","nodeType":"Attribute","startLoc":383,"text":"co_equal"},{"col":4,"comment":"null","endLoc":974,"header":"def test_maxfailures(self, testdir, option)","id":5882,"name":"test_maxfailures","nodeType":"Function","startLoc":960,"text":"def test_maxfailures(self, testdir, option):\n testdir.makepyfile(\n \"\"\"\n def test_1():\n assert 0\n def test_2():\n assert 0\n def test_3():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"--maxfail=2\", *option.args)\n result.stdout.fnmatch_lines(\n [\"*def test_1():*\", \"*def test_2():*\", \"*2 failed*\"]\n )"},{"col":0,"comment":"null","endLoc":1159,"header":"def test_help_via_addopts(testdir)","id":5883,"name":"test_help_via_addopts","nodeType":"Function","startLoc":1143,"text":"def test_help_via_addopts(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n addopts = --unknown-option-should-allow-for-help --help\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n [\n \"usage: *\",\n \"positional arguments:\",\n # Displays full/default help.\n \"to see available markers type: pytest --markers\",\n ]\n )"},{"className":"TestXFail","col":0,"comment":"null","endLoc":519,"id":5884,"nodeType":"Class","startLoc":155,"text":"class TestXFail(object):\n @pytest.mark.parametrize(\"strict\", [True, False])\n def test_xfail_simple(self, testdir, strict):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xfail(strict=%s)\n def test_func():\n assert 0\n \"\"\"\n % strict\n )\n reports = runtestprotocol(item, log=False)\n assert len(reports) == 3\n callreport = reports[1]\n assert callreport.skipped\n assert callreport.wasxfail == \"\"\n\n def test_xfail_xpassed(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xfail(reason=\"this is an xfail\")\n def test_func():\n assert 1\n \"\"\"\n )\n reports = runtestprotocol(item, log=False)\n assert len(reports) == 3\n callreport = reports[1]\n assert callreport.passed\n assert callreport.wasxfail == \"this is an xfail\"\n\n def test_xfail_using_platform(self, testdir):\n \"\"\"\n Verify that platform can be used with xfail statements.\n \"\"\"\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xfail(\"platform.platform() == platform.platform()\")\n def test_func():\n assert 0\n \"\"\"\n )\n reports = runtestprotocol(item, log=False)\n assert len(reports) == 3\n callreport = reports[1]\n assert callreport.wasxfail\n\n def test_xfail_xpassed_strict(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xfail(strict=True, reason=\"nope\")\n def test_func():\n assert 1\n \"\"\"\n )\n reports = runtestprotocol(item, log=False)\n assert len(reports) == 3\n callreport = reports[1]\n assert callreport.failed\n assert callreport.longrepr == \"[XPASS(strict)] nope\"\n assert not hasattr(callreport, \"wasxfail\")\n\n def test_xfail_run_anyway(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail\n def test_func():\n assert 0\n def test_func2():\n pytest.xfail(\"hello\")\n \"\"\"\n )\n result = testdir.runpytest(\"--runxfail\")\n result.stdout.fnmatch_lines(\n [\"*def test_func():*\", \"*assert 0*\", \"*1 failed*1 pass*\"]\n )\n\n def test_xfail_evalfalse_but_fails(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xfail('False')\n def test_func():\n assert 0\n \"\"\"\n )\n reports = runtestprotocol(item, log=False)\n callreport = reports[1]\n assert callreport.failed\n assert not hasattr(callreport, \"wasxfail\")\n assert \"xfail\" in callreport.keywords\n\n def test_xfail_not_report_default(self, testdir):\n p = testdir.makepyfile(\n test_one=\"\"\"\n import pytest\n @pytest.mark.xfail\n def test_this():\n assert 0\n \"\"\"\n )\n testdir.runpytest(p, \"-v\")\n # result.stdout.fnmatch_lines([\n # \"*HINT*use*-r*\"\n # ])\n\n def test_xfail_not_run_xfail_reporting(self, testdir):\n p = testdir.makepyfile(\n test_one=\"\"\"\n import pytest\n @pytest.mark.xfail(run=False, reason=\"noway\")\n def test_this():\n assert 0\n @pytest.mark.xfail(\"True\", run=False)\n def test_this_true():\n assert 0\n @pytest.mark.xfail(\"False\", run=False, reason=\"huh\")\n def test_this_false():\n assert 1\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rx\")\n result.stdout.fnmatch_lines(\n [\n \"*test_one*test_this*\",\n \"*NOTRUN*noway\",\n \"*test_one*test_this_true*\",\n \"*NOTRUN*condition:*True*\",\n \"*1 passed*\",\n ]\n )\n\n def test_xfail_not_run_no_setup_run(self, testdir):\n p = testdir.makepyfile(\n test_one=\"\"\"\n import pytest\n @pytest.mark.xfail(run=False, reason=\"hello\")\n def test_this():\n assert 0\n def setup_module(mod):\n raise ValueError(42)\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rx\")\n result.stdout.fnmatch_lines(\n [\"*test_one*test_this*\", \"*NOTRUN*hello\", \"*1 xfailed*\"]\n )\n\n def test_xfail_xpass(self, testdir):\n p = testdir.makepyfile(\n test_one=\"\"\"\n import pytest\n @pytest.mark.xfail\n def test_that():\n assert 1\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rX\")\n result.stdout.fnmatch_lines([\"*XPASS*test_that*\", \"*1 xpassed*\"])\n assert result.ret == 0\n\n def test_xfail_imperative(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_this():\n pytest.xfail(\"hello\")\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*1 xfailed*\"])\n result = testdir.runpytest(p, \"-rx\")\n result.stdout.fnmatch_lines([\"*XFAIL*test_this*\", \"*reason:*hello*\"])\n result = testdir.runpytest(p, \"--runxfail\")\n result.stdout.fnmatch_lines([\"*1 pass*\"])\n\n def test_xfail_imperative_in_setup_function(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def setup_function(function):\n pytest.xfail(\"hello\")\n\n def test_this():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*1 xfailed*\"])\n result = testdir.runpytest(p, \"-rx\")\n result.stdout.fnmatch_lines([\"*XFAIL*test_this*\", \"*reason:*hello*\"])\n result = testdir.runpytest(p, \"--runxfail\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *def test_this*\n *1 fail*\n \"\"\"\n )\n\n def xtest_dynamic_xfail_set_during_setup(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def setup_function(function):\n pytest.mark.xfail(function)\n def test_this():\n assert 0\n def test_that():\n assert 1\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rxX\")\n result.stdout.fnmatch_lines([\"*XFAIL*test_this*\", \"*XPASS*test_that*\"])\n\n def test_dynamic_xfail_no_run(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def arg(request):\n request.applymarker(pytest.mark.xfail(run=False))\n def test_this(arg):\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rxX\")\n result.stdout.fnmatch_lines([\"*XFAIL*test_this*\", \"*NOTRUN*\"])\n\n def test_dynamic_xfail_set_during_funcarg_setup(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def arg(request):\n request.applymarker(pytest.mark.xfail)\n def test_this2(arg):\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*1 xfailed*\"])\n\n @pytest.mark.parametrize(\n \"expected, actual, matchline\",\n [\n (\"TypeError\", \"TypeError\", \"*1 xfailed*\"),\n (\"(AttributeError, TypeError)\", \"TypeError\", \"*1 xfailed*\"),\n (\"TypeError\", \"IndexError\", \"*1 failed*\"),\n (\"(AttributeError, TypeError)\", \"IndexError\", \"*1 failed*\"),\n ],\n )\n def test_xfail_raises(self, expected, actual, matchline, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(raises=%s)\n def test_raises():\n raise %s()\n \"\"\"\n % (expected, actual)\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([matchline])\n\n def test_strict_sanity(self, testdir):\n \"\"\"sanity check for xfail(strict=True): a failing test should behave\n exactly like a normal xfail.\n \"\"\"\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(reason='unsupported feature', strict=True)\n def test_foo():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rxX\")\n result.stdout.fnmatch_lines([\"*XFAIL*\", \"*unsupported feature*\"])\n assert result.ret == 0\n\n @pytest.mark.parametrize(\"strict\", [True, False])\n def test_strict_xfail(self, testdir, strict):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.xfail(reason='unsupported feature', strict=%s)\n def test_foo():\n with open('foo_executed', 'w'): pass # make sure test executes\n \"\"\"\n % strict\n )\n result = testdir.runpytest(p, \"-rxX\")\n if strict:\n result.stdout.fnmatch_lines(\n [\"*test_foo*\", \"*XPASS(strict)*unsupported feature*\"]\n )\n else:\n result.stdout.fnmatch_lines(\n [\n \"*test_strict_xfail*\",\n \"XPASS test_strict_xfail.py::test_foo unsupported feature\",\n ]\n )\n assert result.ret == (1 if strict else 0)\n assert testdir.tmpdir.join(\"foo_executed\").isfile()\n\n @pytest.mark.parametrize(\"strict\", [True, False])\n def test_strict_xfail_condition(self, testdir, strict):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.xfail(False, reason='unsupported feature', strict=%s)\n def test_foo():\n pass\n \"\"\"\n % strict\n )\n result = testdir.runpytest(p, \"-rxX\")\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n assert result.ret == 0\n\n @pytest.mark.parametrize(\"strict\", [True, False])\n def test_xfail_condition_keyword(self, testdir, strict):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.xfail(condition=False, reason='unsupported feature', strict=%s)\n def test_foo():\n pass\n \"\"\"\n % strict\n )\n result = testdir.runpytest(p, \"-rxX\")\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n assert result.ret == 0\n\n @pytest.mark.parametrize(\"strict_val\", [\"true\", \"false\"])\n def test_strict_xfail_default_from_file(self, testdir, strict_val):\n testdir.makeini(\n \"\"\"\n [pytest]\n xfail_strict = %s\n \"\"\"\n % strict_val\n )\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(reason='unsupported feature')\n def test_foo():\n pass\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rxX\")\n strict = strict_val == \"true\"\n result.stdout.fnmatch_lines([\"*1 failed*\" if strict else \"*1 xpassed*\"])\n assert result.ret == (1 if strict else 0)"},{"col":4,"comment":"null","endLoc":171,"header":"@pytest.mark.parametrize(\"strict\", [True, False])\n def test_xfail_simple(self, testdir, strict)","id":5885,"name":"test_xfail_simple","nodeType":"Function","startLoc":156,"text":"@pytest.mark.parametrize(\"strict\", [True, False])\n def test_xfail_simple(self, testdir, strict):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xfail(strict=%s)\n def test_func():\n assert 0\n \"\"\"\n % strict\n )\n reports = runtestprotocol(item, log=False)\n assert len(reports) == 3\n callreport = reports[1]\n assert callreport.skipped\n assert callreport.wasxfail == \"\""},{"col":4,"comment":"null","endLoc":186,"header":"def test_xfail_xpassed(self, testdir)","id":5886,"name":"test_xfail_xpassed","nodeType":"Function","startLoc":173,"text":"def test_xfail_xpassed(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xfail(reason=\"this is an xfail\")\n def test_func():\n assert 1\n \"\"\"\n )\n reports = runtestprotocol(item, log=False)\n assert len(reports) == 3\n callreport = reports[1]\n assert callreport.passed\n assert callreport.wasxfail == \"this is an xfail\""},{"col":4,"comment":"null","endLoc":1001,"header":"def test_tb_option(self, testdir, option)","id":5887,"name":"test_tb_option","nodeType":"Function","startLoc":976,"text":"def test_tb_option(self, testdir, option):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def g():\n raise IndexError\n def test_func():\n print(6*7)\n g() # --calling--\n \"\"\"\n )\n for tbopt in [\"long\", \"short\", \"no\"]:\n print(\"testing --tb=%s...\" % tbopt)\n result = testdir.runpytest(\"--tb=%s\" % tbopt)\n s = result.stdout.str()\n if tbopt == \"long\":\n assert \"print(6*7)\" in s\n else:\n assert \"print(6*7)\" not in s\n if tbopt != \"no\":\n assert \"--calling--\" in s\n assert \"IndexError\" in s\n else:\n assert \"FAILURES\" not in s\n assert \"--calling--\" not in s\n assert \"IndexError\" not in s"},{"col":4,"comment":"\n Verify that platform can be used with xfail statements.\n ","endLoc":203,"header":"def test_xfail_using_platform(self, testdir)","id":5888,"name":"test_xfail_using_platform","nodeType":"Function","startLoc":188,"text":"def test_xfail_using_platform(self, testdir):\n \"\"\"\n Verify that platform can be used with xfail statements.\n \"\"\"\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xfail(\"platform.platform() == platform.platform()\")\n def test_func():\n assert 0\n \"\"\"\n )\n reports = runtestprotocol(item, log=False)\n assert len(reports) == 3\n callreport = reports[1]\n assert callreport.wasxfail"},{"col":0,"comment":"null","endLoc":1205,"header":"def test_help_and_version_after_argument_error(testdir)","id":5890,"name":"test_help_and_version_after_argument_error","nodeType":"Function","startLoc":1162,"text":"def test_help_and_version_after_argument_error(testdir):\n testdir.makeconftest(\n \"\"\"\n def validate(arg):\n raise argparse.ArgumentTypeError(\"argerror\")\n\n def pytest_addoption(parser):\n group = parser.getgroup('cov')\n group.addoption(\n \"--invalid-option-should-allow-for-help\",\n type=validate,\n )\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n addopts = --invalid-option-should-allow-for-help\n \"\"\"\n )\n result = testdir.runpytest(\"--help\")\n result.stdout.fnmatch_lines(\n [\n \"usage: *\",\n \"positional arguments:\",\n \"NOTE: displaying only minimal help due to UsageError.\",\n ]\n )\n result.stderr.fnmatch_lines(\n [\n \"ERROR: usage: *\",\n \"%s: error: argument --invalid-option-should-allow-for-help: expected one argument\"\n % (testdir.request.config._parser.optparser.prog,),\n ]\n )\n # Does not display full/default help.\n assert \"to see available markers type: pytest --markers\" not in result.stdout.lines\n assert result.ret == EXIT_USAGEERROR\n\n result = testdir.runpytest(\"--version\")\n result.stderr.fnmatch_lines(\n [\"*pytest*{}*imported from*\".format(pytest.__version__)]\n )\n assert result.ret == EXIT_USAGEERROR"},{"col":4,"comment":"null","endLoc":219,"header":"def test_xfail_xpassed_strict(self, testdir)","id":5891,"name":"test_xfail_xpassed_strict","nodeType":"Function","startLoc":205,"text":"def test_xfail_xpassed_strict(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xfail(strict=True, reason=\"nope\")\n def test_func():\n assert 1\n \"\"\"\n )\n reports = runtestprotocol(item, log=False)\n assert len(reports) == 3\n callreport = reports[1]\n assert callreport.failed\n assert callreport.longrepr == \"[XPASS(strict)] nope\"\n assert not hasattr(callreport, \"wasxfail\")"},{"col":4,"comment":"null","endLoc":202,"header":"def test_deprecated_call_specificity(self)","id":5893,"name":"test_deprecated_call_specificity","nodeType":"Function","startLoc":183,"text":"def test_deprecated_call_specificity(self):\n other_warnings = [\n Warning,\n UserWarning,\n SyntaxWarning,\n RuntimeWarning,\n FutureWarning,\n ImportWarning,\n UnicodeWarning,\n ]\n for warning in other_warnings:\n\n def f():\n warnings.warn(warning(\"hi\"))\n\n with pytest.raises(pytest.fail.Exception):\n pytest.deprecated_call(f)\n with pytest.raises(pytest.fail.Exception):\n with pytest.deprecated_call():\n f()"},{"col":4,"comment":"null","endLoc":235,"header":"def test_xfail_run_anyway(self, testdir)","id":5894,"name":"test_xfail_run_anyway","nodeType":"Function","startLoc":221,"text":"def test_xfail_run_anyway(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail\n def test_func():\n assert 0\n def test_func2():\n pytest.xfail(\"hello\")\n \"\"\"\n )\n result = testdir.runpytest(\"--runxfail\")\n result.stdout.fnmatch_lines(\n [\"*def test_func():*\", \"*assert 0*\", \"*1 failed*1 pass*\"]\n )"},{"fileName":"rewrite.py","filePath":"src/_pytest/assertion","id":5895,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"Rewrite assertion AST to produce nice error messages\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport ast\nimport errno\nimport imp\nimport itertools\nimport marshal\nimport os\nimport re\nimport string\nimport struct\nimport sys\nimport types\n\nimport atomicwrites\nimport py\nimport six\n\nfrom _pytest._io.saferepr import saferepr\nfrom _pytest.assertion import util\nfrom _pytest.assertion.util import ( # noqa: F401\n format_explanation as _format_explanation,\n)\nfrom _pytest.compat import spec_from_file_location\nfrom _pytest.pathlib import fnmatch_ex\nfrom _pytest.pathlib import PurePath\n\n# pytest caches rewritten pycs in __pycache__.\nif hasattr(imp, \"get_tag\"):\n PYTEST_TAG = imp.get_tag() + \"-PYTEST\"\nelse:\n if hasattr(sys, \"pypy_version_info\"):\n impl = \"pypy\"\n elif sys.platform == \"java\":\n impl = \"jython\"\n else:\n impl = \"cpython\"\n ver = sys.version_info\n PYTEST_TAG = \"%s-%s%s-PYTEST\" % (impl, ver[0], ver[1])\n del ver, impl\n\nPYC_EXT = \".py\" + (__debug__ and \"c\" or \"o\")\nPYC_TAIL = \".\" + PYTEST_TAG + PYC_EXT\n\nASCII_IS_DEFAULT_ENCODING = sys.version_info[0] < 3\n\nif sys.version_info >= (3, 5):\n ast_Call = ast.Call\nelse:\n\n def ast_Call(a, b, c):\n return ast.Call(a, b, c, None, None)\n\n\nclass AssertionRewritingHook(object):\n \"\"\"PEP302 Import hook which rewrites asserts.\"\"\"\n\n def __init__(self, config):\n self.config = config\n try:\n self.fnpats = config.getini(\"python_files\")\n except ValueError:\n self.fnpats = [\"test_*.py\", \"*_test.py\"]\n self.session = None\n self.modules = {}\n self._rewritten_names = set()\n self._must_rewrite = set()\n # flag to guard against trying to rewrite a pyc file while we are already writing another pyc file,\n # which might result in infinite recursion (#3506)\n self._writing_pyc = False\n self._basenames_to_check_rewrite = {\"conftest\"}\n self._marked_for_rewrite_cache = {}\n self._session_paths_checked = False\n\n def set_session(self, session):\n self.session = session\n self._session_paths_checked = False\n\n def _imp_find_module(self, name, path=None):\n \"\"\"Indirection so we can mock calls to find_module originated from the hook during testing\"\"\"\n return imp.find_module(name, path)\n\n def find_module(self, name, path=None):\n if self._writing_pyc:\n return None\n state = self.config._assertstate\n if self._early_rewrite_bailout(name, state):\n return None\n state.trace(\"find_module called for: %s\" % name)\n names = name.rsplit(\".\", 1)\n lastname = names[-1]\n pth = None\n if path is not None:\n # Starting with Python 3.3, path is a _NamespacePath(), which\n # causes problems if not converted to list.\n path = list(path)\n if len(path) == 1:\n pth = path[0]\n if pth is None:\n try:\n fd, fn, desc = self._imp_find_module(lastname, path)\n except ImportError:\n return None\n if fd is not None:\n fd.close()\n tp = desc[2]\n if tp == imp.PY_COMPILED:\n if hasattr(imp, \"source_from_cache\"):\n try:\n fn = imp.source_from_cache(fn)\n except ValueError:\n # Python 3 doesn't like orphaned but still-importable\n # .pyc files.\n fn = fn[:-1]\n else:\n fn = fn[:-1]\n elif tp != imp.PY_SOURCE:\n # Don't know what this is.\n return None\n else:\n fn = os.path.join(pth, name.rpartition(\".\")[2] + \".py\")\n\n fn_pypath = py.path.local(fn)\n if not self._should_rewrite(name, fn_pypath, state):\n return None\n\n self._rewritten_names.add(name)\n\n # The requested module looks like a test file, so rewrite it. This is\n # the most magical part of the process: load the source, rewrite the\n # asserts, and load the rewritten source. We also cache the rewritten\n # module code in a special pyc. We must be aware of the possibility of\n # concurrent pytest processes rewriting and loading pycs. To avoid\n # tricky race conditions, we maintain the following invariant: The\n # cached pyc is always a complete, valid pyc. Operations on it must be\n # atomic. POSIX's atomic rename comes in handy.\n write = not sys.dont_write_bytecode\n cache_dir = os.path.join(fn_pypath.dirname, \"__pycache__\")\n if write:\n try:\n os.mkdir(cache_dir)\n except OSError:\n e = sys.exc_info()[1].errno\n if e == errno.EEXIST:\n # Either the __pycache__ directory already exists (the\n # common case) or it's blocked by a non-dir node. In the\n # latter case, we'll ignore it in _write_pyc.\n pass\n elif e in [errno.ENOENT, errno.ENOTDIR]:\n # One of the path components was not a directory, likely\n # because we're in a zip file.\n write = False\n elif e in [errno.EACCES, errno.EROFS, errno.EPERM]:\n state.trace(\"read only directory: %r\" % fn_pypath.dirname)\n write = False\n else:\n raise\n cache_name = fn_pypath.basename[:-3] + PYC_TAIL\n pyc = os.path.join(cache_dir, cache_name)\n # Notice that even if we're in a read-only directory, I'm going\n # to check for a cached pyc. This may not be optimal...\n co = _read_pyc(fn_pypath, pyc, state.trace)\n if co is None:\n state.trace(\"rewriting %r\" % (fn,))\n source_stat, co = _rewrite_test(self.config, fn_pypath)\n if co is None:\n # Probably a SyntaxError in the test.\n return None\n if write:\n self._writing_pyc = True\n try:\n _write_pyc(state, co, source_stat, pyc)\n finally:\n self._writing_pyc = False\n else:\n state.trace(\"found cached rewritten pyc for %r\" % (fn,))\n self.modules[name] = co, pyc\n return self\n\n def _early_rewrite_bailout(self, name, state):\n \"\"\"\n This is a fast way to get out of rewriting modules. Profiling has\n shown that the call to imp.find_module (inside of the find_module\n from this class) is a major slowdown, so, this method tries to\n filter what we're sure won't be rewritten before getting to it.\n \"\"\"\n if self.session is not None and not self._session_paths_checked:\n self._session_paths_checked = True\n for path in self.session._initialpaths:\n # Make something as c:/projects/my_project/path.py ->\n # ['c:', 'projects', 'my_project', 'path.py']\n parts = str(path).split(os.path.sep)\n # add 'path' to basenames to be checked.\n self._basenames_to_check_rewrite.add(os.path.splitext(parts[-1])[0])\n\n # Note: conftest already by default in _basenames_to_check_rewrite.\n parts = name.split(\".\")\n if parts[-1] in self._basenames_to_check_rewrite:\n return False\n\n # For matching the name it must be as if it was a filename.\n path = PurePath(os.path.sep.join(parts) + \".py\")\n\n for pat in self.fnpats:\n # if the pattern contains subdirectories (\"tests/**.py\" for example) we can't bail out based\n # on the name alone because we need to match against the full path\n if os.path.dirname(pat):\n return False\n if fnmatch_ex(pat, path):\n return False\n\n if self._is_marked_for_rewrite(name, state):\n return False\n\n state.trace(\"early skip of rewriting module: %s\" % (name,))\n return True\n\n def _should_rewrite(self, name, fn_pypath, state):\n # always rewrite conftest files\n fn = str(fn_pypath)\n if fn_pypath.basename == \"conftest.py\":\n state.trace(\"rewriting conftest file: %r\" % (fn,))\n return True\n\n if self.session is not None:\n if self.session.isinitpath(fn):\n state.trace(\"matched test file (was specified on cmdline): %r\" % (fn,))\n return True\n\n # modules not passed explicitly on the command line are only\n # rewritten if they match the naming convention for test files\n for pat in self.fnpats:\n if fn_pypath.fnmatch(pat):\n state.trace(\"matched test file %r\" % (fn,))\n return True\n\n return self._is_marked_for_rewrite(name, state)\n\n def _is_marked_for_rewrite(self, name, state):\n try:\n return self._marked_for_rewrite_cache[name]\n except KeyError:\n for marked in self._must_rewrite:\n if name == marked or name.startswith(marked + \".\"):\n state.trace(\"matched marked file %r (from %r)\" % (name, marked))\n self._marked_for_rewrite_cache[name] = True\n return True\n\n self._marked_for_rewrite_cache[name] = False\n return False\n\n def mark_rewrite(self, *names):\n \"\"\"Mark import names as needing to be rewritten.\n\n The named module or package as well as any nested modules will\n be rewritten on import.\n \"\"\"\n already_imported = (\n set(names).intersection(sys.modules).difference(self._rewritten_names)\n )\n for name in already_imported:\n if not AssertionRewriter.is_rewrite_disabled(\n sys.modules[name].__doc__ or \"\"\n ):\n self._warn_already_imported(name)\n self._must_rewrite.update(names)\n self._marked_for_rewrite_cache.clear()\n\n def _warn_already_imported(self, name):\n from _pytest.warning_types import PytestAssertRewriteWarning\n from _pytest.warnings import _issue_warning_captured\n\n _issue_warning_captured(\n PytestAssertRewriteWarning(\n \"Module already imported so cannot be rewritten: %s\" % name\n ),\n self.config.hook,\n stacklevel=5,\n )\n\n def load_module(self, name):\n co, pyc = self.modules.pop(name)\n if name in sys.modules:\n # If there is an existing module object named 'fullname' in\n # sys.modules, the loader must use that existing module. (Otherwise,\n # the reload() builtin will not work correctly.)\n mod = sys.modules[name]\n else:\n # I wish I could just call imp.load_compiled here, but __file__ has to\n # be set properly. In Python 3.2+, this all would be handled correctly\n # by load_compiled.\n mod = sys.modules[name] = imp.new_module(name)\n try:\n mod.__file__ = co.co_filename\n # Normally, this attribute is 3.2+.\n mod.__cached__ = pyc\n mod.__loader__ = self\n # Normally, this attribute is 3.4+\n mod.__spec__ = spec_from_file_location(name, co.co_filename, loader=self)\n exec(co, mod.__dict__)\n except: # noqa\n if name in sys.modules:\n del sys.modules[name]\n raise\n return sys.modules[name]\n\n def is_package(self, name):\n try:\n fd, fn, desc = self._imp_find_module(name)\n except ImportError:\n return False\n if fd is not None:\n fd.close()\n tp = desc[2]\n return tp == imp.PKG_DIRECTORY\n\n def get_data(self, pathname):\n \"\"\"Optional PEP302 get_data API.\n \"\"\"\n with open(pathname, \"rb\") as f:\n return f.read()\n\n\ndef _write_pyc(state, co, source_stat, pyc):\n # Technically, we don't have to have the same pyc format as\n # (C)Python, since these \"pycs\" should never be seen by builtin\n # import. However, there's little reason deviate, and I hope\n # sometime to be able to use imp.load_compiled to load them. (See\n # the comment in load_module above.)\n try:\n with atomicwrites.atomic_write(pyc, mode=\"wb\", overwrite=True) as fp:\n fp.write(imp.get_magic())\n # as of now, bytecode header expects 32-bit numbers for size and mtime (#4903)\n mtime = int(source_stat.mtime) & 0xFFFFFFFF\n size = source_stat.size & 0xFFFFFFFF\n # \">\",\n ast.Add: \"+\",\n ast.Sub: \"-\",\n ast.Mult: \"*\",\n ast.Div: \"/\",\n ast.FloorDiv: \"//\",\n ast.Mod: \"%%\", # escaped for string formatting\n ast.Eq: \"==\",\n ast.NotEq: \"!=\",\n ast.Lt: \"<\",\n ast.LtE: \"<=\",\n ast.Gt: \">\",\n ast.GtE: \">=\",\n ast.Pow: \"**\",\n ast.Is: \"is\",\n ast.IsNot: \"is not\",\n ast.In: \"in\",\n ast.NotIn: \"not in\",\n}\n# Python 3.5+ compatibility\ntry:\n binop_map[ast.MatMult] = \"@\"\nexcept AttributeError:\n pass\n\n# Python 3.4+ compatibility\nif hasattr(ast, \"NameConstant\"):\n _NameConstant = ast.NameConstant\nelse:\n\n def _NameConstant(c):\n return ast.Name(str(c), ast.Load())\n\n\ndef set_location(node, lineno, col_offset):\n \"\"\"Set node location information recursively.\"\"\"\n\n def _fix(node, lineno, col_offset):\n if \"lineno\" in node._attributes:\n node.lineno = lineno\n if \"col_offset\" in node._attributes:\n node.col_offset = col_offset\n for child in ast.iter_child_nodes(node):\n _fix(child, lineno, col_offset)\n\n _fix(node, lineno, col_offset)\n return node\n\n\nclass AssertionRewriter(ast.NodeVisitor):\n \"\"\"Assertion rewriting implementation.\n\n The main entrypoint is to call .run() with an ast.Module instance,\n this will then find all the assert statements and rewrite them to\n provide intermediate values and a detailed assertion error. See\n http://pybites.blogspot.be/2011/07/behind-scenes-of-pytests-new-assertion.html\n for an overview of how this works.\n\n The entry point here is .run() which will iterate over all the\n statements in an ast.Module and for each ast.Assert statement it\n finds call .visit() with it. Then .visit_Assert() takes over and\n is responsible for creating new ast statements to replace the\n original assert statement: it rewrites the test of an assertion\n to provide intermediate values and replace it with an if statement\n which raises an assertion error with a detailed explanation in\n case the expression is false.\n\n For this .visit_Assert() uses the visitor pattern to visit all the\n AST nodes of the ast.Assert.test field, each visit call returning\n an AST node and the corresponding explanation string. During this\n state is kept in several instance attributes:\n\n :statements: All the AST statements which will replace the assert\n statement.\n\n :variables: This is populated by .variable() with each variable\n used by the statements so that they can all be set to None at\n the end of the statements.\n\n :variable_counter: Counter to create new unique variables needed\n by statements. Variables are created using .variable() and\n have the form of \"@py_assert0\".\n\n :on_failure: The AST statements which will be executed if the\n assertion test fails. This is the code which will construct\n the failure message and raises the AssertionError.\n\n :explanation_specifiers: A dict filled by .explanation_param()\n with %-formatting placeholders and their corresponding\n expressions to use in the building of an assertion message.\n This is used by .pop_format_context() to build a message.\n\n :stack: A stack of the explanation_specifiers dicts maintained by\n .push_format_context() and .pop_format_context() which allows\n to build another %-formatted string while already building one.\n\n This state is reset on every new assert statement visited and used\n by the other visitors.\n\n \"\"\"\n\n def __init__(self, module_path, config):\n super(AssertionRewriter, self).__init__()\n self.module_path = module_path\n self.config = config\n\n def run(self, mod):\n \"\"\"Find all assert statements in *mod* and rewrite them.\"\"\"\n if not mod.body:\n # Nothing to do.\n return\n # Insert some special imports at the top of the module but after any\n # docstrings and __future__ imports.\n aliases = [\n ast.alias(six.moves.builtins.__name__, \"@py_builtins\"),\n ast.alias(\"_pytest.assertion.rewrite\", \"@pytest_ar\"),\n ]\n doc = getattr(mod, \"docstring\", None)\n expect_docstring = doc is None\n if doc is not None and self.is_rewrite_disabled(doc):\n return\n pos = 0\n lineno = 1\n for item in mod.body:\n if (\n expect_docstring\n and isinstance(item, ast.Expr)\n and isinstance(item.value, ast.Str)\n ):\n doc = item.value.s\n if self.is_rewrite_disabled(doc):\n return\n expect_docstring = False\n elif (\n not isinstance(item, ast.ImportFrom)\n or item.level > 0\n or item.module != \"__future__\"\n ):\n lineno = item.lineno\n break\n pos += 1\n else:\n lineno = item.lineno\n imports = [\n ast.Import([alias], lineno=lineno, col_offset=0) for alias in aliases\n ]\n mod.body[pos:pos] = imports\n # Collect asserts.\n nodes = [mod]\n while nodes:\n node = nodes.pop()\n for name, field in ast.iter_fields(node):\n if isinstance(field, list):\n new = []\n for i, child in enumerate(field):\n if isinstance(child, ast.Assert):\n # Transform assert.\n new.extend(self.visit(child))\n else:\n new.append(child)\n if isinstance(child, ast.AST):\n nodes.append(child)\n setattr(node, name, new)\n elif (\n isinstance(field, ast.AST)\n # Don't recurse into expressions as they can't contain\n # asserts.\n and not isinstance(field, ast.expr)\n ):\n nodes.append(field)\n\n @staticmethod\n def is_rewrite_disabled(docstring):\n return \"PYTEST_DONT_REWRITE\" in docstring\n\n def variable(self):\n \"\"\"Get a new variable.\"\"\"\n # Use a character invalid in python identifiers to avoid clashing.\n name = \"@py_assert\" + str(next(self.variable_counter))\n self.variables.append(name)\n return name\n\n def assign(self, expr):\n \"\"\"Give *expr* a name.\"\"\"\n name = self.variable()\n self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr))\n return ast.Name(name, ast.Load())\n\n def display(self, expr):\n \"\"\"Call saferepr on the expression.\"\"\"\n return self.helper(\"_saferepr\", expr)\n\n def helper(self, name, *args):\n \"\"\"Call a helper in this module.\"\"\"\n py_name = ast.Name(\"@pytest_ar\", ast.Load())\n attr = ast.Attribute(py_name, name, ast.Load())\n return ast_Call(attr, list(args), [])\n\n def builtin(self, name):\n \"\"\"Return the builtin called *name*.\"\"\"\n builtin_name = ast.Name(\"@py_builtins\", ast.Load())\n return ast.Attribute(builtin_name, name, ast.Load())\n\n def explanation_param(self, expr):\n \"\"\"Return a new named %-formatting placeholder for expr.\n\n This creates a %-formatting placeholder for expr in the\n current formatting context, e.g. ``%(py0)s``. The placeholder\n and expr are placed in the current format context so that it\n can be used on the next call to .pop_format_context().\n\n \"\"\"\n specifier = \"py\" + str(next(self.variable_counter))\n self.explanation_specifiers[specifier] = expr\n return \"%(\" + specifier + \")s\"\n\n def push_format_context(self):\n \"\"\"Create a new formatting context.\n\n The format context is used for when an explanation wants to\n have a variable value formatted in the assertion message. In\n this case the value required can be added using\n .explanation_param(). Finally .pop_format_context() is used\n to format a string of %-formatted values as added by\n .explanation_param().\n\n \"\"\"\n self.explanation_specifiers = {}\n self.stack.append(self.explanation_specifiers)\n\n def pop_format_context(self, expl_expr):\n \"\"\"Format the %-formatted string with current format context.\n\n The expl_expr should be an ast.Str instance constructed from\n the %-placeholders created by .explanation_param(). This will\n add the required code to format said string to .on_failure and\n return the ast.Name instance of the formatted string.\n\n \"\"\"\n current = self.stack.pop()\n if self.stack:\n self.explanation_specifiers = self.stack[-1]\n keys = [ast.Str(key) for key in current.keys()]\n format_dict = ast.Dict(keys, list(current.values()))\n form = ast.BinOp(expl_expr, ast.Mod(), format_dict)\n name = \"@py_format\" + str(next(self.variable_counter))\n self.on_failure.append(ast.Assign([ast.Name(name, ast.Store())], form))\n return ast.Name(name, ast.Load())\n\n def generic_visit(self, node):\n \"\"\"Handle expressions we don't have custom code for.\"\"\"\n assert isinstance(node, ast.expr)\n res = self.assign(node)\n return res, self.explanation_param(self.display(res))\n\n def visit_Assert(self, assert_):\n \"\"\"Return the AST statements to replace the ast.Assert instance.\n\n This rewrites the test of an assertion to provide\n intermediate values and replace it with an if statement which\n raises an assertion error with a detailed explanation in case\n the expression is false.\n\n \"\"\"\n if isinstance(assert_.test, ast.Tuple) and len(assert_.test.elts) >= 1:\n from _pytest.warning_types import PytestAssertRewriteWarning\n import warnings\n\n warnings.warn_explicit(\n PytestAssertRewriteWarning(\n \"assertion is always true, perhaps remove parentheses?\"\n ),\n category=None,\n filename=str(self.module_path),\n lineno=assert_.lineno,\n )\n\n self.statements = []\n self.variables = []\n self.variable_counter = itertools.count()\n self.stack = []\n self.on_failure = []\n self.push_format_context()\n # Rewrite assert into a bunch of statements.\n top_condition, explanation = self.visit(assert_.test)\n # If in a test module, check if directly asserting None, in order to warn [Issue #3191]\n if self.module_path is not None:\n self.statements.append(\n self.warn_about_none_ast(\n top_condition, module_path=self.module_path, lineno=assert_.lineno\n )\n )\n # Create failure message.\n body = self.on_failure\n negation = ast.UnaryOp(ast.Not(), top_condition)\n self.statements.append(ast.If(negation, body, []))\n if assert_.msg:\n assertmsg = self.helper(\"_format_assertmsg\", assert_.msg)\n explanation = \"\\n>assert \" + explanation\n else:\n assertmsg = ast.Str(\"\")\n explanation = \"assert \" + explanation\n template = ast.BinOp(assertmsg, ast.Add(), ast.Str(explanation))\n msg = self.pop_format_context(template)\n fmt = self.helper(\"_format_explanation\", msg)\n err_name = ast.Name(\"AssertionError\", ast.Load())\n exc = ast_Call(err_name, [fmt], [])\n if sys.version_info[0] >= 3:\n raise_ = ast.Raise(exc, None)\n else:\n raise_ = ast.Raise(exc, None, None)\n body.append(raise_)\n # Clear temporary variables by setting them to None.\n if self.variables:\n variables = [ast.Name(name, ast.Store()) for name in self.variables]\n clear = ast.Assign(variables, _NameConstant(None))\n self.statements.append(clear)\n # Fix line numbers.\n for stmt in self.statements:\n set_location(stmt, assert_.lineno, assert_.col_offset)\n return self.statements\n\n def warn_about_none_ast(self, node, module_path, lineno):\n \"\"\"\n Returns an AST issuing a warning if the value of node is `None`.\n This is used to warn the user when asserting a function that asserts\n internally already.\n See issue #3191 for more details.\n \"\"\"\n\n # Using parse because it is different between py2 and py3.\n AST_NONE = ast.parse(\"None\").body[0].value\n val_is_none = ast.Compare(node, [ast.Is()], [AST_NONE])\n send_warning = ast.parse(\n \"\"\"\nfrom _pytest.warning_types import PytestAssertRewriteWarning\nfrom warnings import warn_explicit\nwarn_explicit(\n PytestAssertRewriteWarning('asserting the value None, please use \"assert is None\"'),\n category=None,\n filename={filename!r},\n lineno={lineno},\n)\n \"\"\".format(\n filename=module_path.strpath, lineno=lineno\n )\n ).body\n return ast.If(val_is_none, send_warning, [])\n\n def visit_Name(self, name):\n # Display the repr of the name if it's a local variable or\n # _should_repr_global_name() thinks it's acceptable.\n locs = ast_Call(self.builtin(\"locals\"), [], [])\n inlocs = ast.Compare(ast.Str(name.id), [ast.In()], [locs])\n dorepr = self.helper(\"_should_repr_global_name\", name)\n test = ast.BoolOp(ast.Or(), [inlocs, dorepr])\n expr = ast.IfExp(test, self.display(name), ast.Str(name.id))\n return name, self.explanation_param(expr)\n\n def visit_BoolOp(self, boolop):\n res_var = self.variable()\n expl_list = self.assign(ast.List([], ast.Load()))\n app = ast.Attribute(expl_list, \"append\", ast.Load())\n is_or = int(isinstance(boolop.op, ast.Or))\n body = save = self.statements\n fail_save = self.on_failure\n levels = len(boolop.values) - 1\n self.push_format_context()\n # Process each operand, short-circuting if needed.\n for i, v in enumerate(boolop.values):\n if i:\n fail_inner = []\n # cond is set in a prior loop iteration below\n self.on_failure.append(ast.If(cond, fail_inner, [])) # noqa\n self.on_failure = fail_inner\n self.push_format_context()\n res, expl = self.visit(v)\n body.append(ast.Assign([ast.Name(res_var, ast.Store())], res))\n expl_format = self.pop_format_context(ast.Str(expl))\n call = ast_Call(app, [expl_format], [])\n self.on_failure.append(ast.Expr(call))\n if i < levels:\n cond = res\n if is_or:\n cond = ast.UnaryOp(ast.Not(), cond)\n inner = []\n self.statements.append(ast.If(cond, inner, []))\n self.statements = body = inner\n self.statements = save\n self.on_failure = fail_save\n expl_template = self.helper(\"_format_boolop\", expl_list, ast.Num(is_or))\n expl = self.pop_format_context(expl_template)\n return ast.Name(res_var, ast.Load()), self.explanation_param(expl)\n\n def visit_UnaryOp(self, unary):\n pattern = unary_map[unary.op.__class__]\n operand_res, operand_expl = self.visit(unary.operand)\n res = self.assign(ast.UnaryOp(unary.op, operand_res))\n return res, pattern % (operand_expl,)\n\n def visit_BinOp(self, binop):\n symbol = binop_map[binop.op.__class__]\n left_expr, left_expl = self.visit(binop.left)\n right_expr, right_expl = self.visit(binop.right)\n explanation = \"(%s %s %s)\" % (left_expl, symbol, right_expl)\n res = self.assign(ast.BinOp(left_expr, binop.op, right_expr))\n return res, explanation\n\n def visit_Call_35(self, call):\n \"\"\"\n visit `ast.Call` nodes on Python3.5 and after\n \"\"\"\n new_func, func_expl = self.visit(call.func)\n arg_expls = []\n new_args = []\n new_kwargs = []\n for arg in call.args:\n res, expl = self.visit(arg)\n arg_expls.append(expl)\n new_args.append(res)\n for keyword in call.keywords:\n res, expl = self.visit(keyword.value)\n new_kwargs.append(ast.keyword(keyword.arg, res))\n if keyword.arg:\n arg_expls.append(keyword.arg + \"=\" + expl)\n else: # **args have `arg` keywords with an .arg of None\n arg_expls.append(\"**\" + expl)\n\n expl = \"%s(%s)\" % (func_expl, \", \".join(arg_expls))\n new_call = ast.Call(new_func, new_args, new_kwargs)\n res = self.assign(new_call)\n res_expl = self.explanation_param(self.display(res))\n outer_expl = \"%s\\n{%s = %s\\n}\" % (res_expl, res_expl, expl)\n return res, outer_expl\n\n def visit_Starred(self, starred):\n # From Python 3.5, a Starred node can appear in a function call\n res, expl = self.visit(starred.value)\n new_starred = ast.Starred(res, starred.ctx)\n return new_starred, \"*\" + expl\n\n def visit_Call_legacy(self, call):\n \"\"\"\n visit `ast.Call nodes on 3.4 and below`\n \"\"\"\n new_func, func_expl = self.visit(call.func)\n arg_expls = []\n new_args = []\n new_kwargs = []\n new_star = new_kwarg = None\n for arg in call.args:\n res, expl = self.visit(arg)\n new_args.append(res)\n arg_expls.append(expl)\n for keyword in call.keywords:\n res, expl = self.visit(keyword.value)\n new_kwargs.append(ast.keyword(keyword.arg, res))\n arg_expls.append(keyword.arg + \"=\" + expl)\n if call.starargs:\n new_star, expl = self.visit(call.starargs)\n arg_expls.append(\"*\" + expl)\n if call.kwargs:\n new_kwarg, expl = self.visit(call.kwargs)\n arg_expls.append(\"**\" + expl)\n expl = \"%s(%s)\" % (func_expl, \", \".join(arg_expls))\n new_call = ast.Call(new_func, new_args, new_kwargs, new_star, new_kwarg)\n res = self.assign(new_call)\n res_expl = self.explanation_param(self.display(res))\n outer_expl = \"%s\\n{%s = %s\\n}\" % (res_expl, res_expl, expl)\n return res, outer_expl\n\n # ast.Call signature changed on 3.5,\n # conditionally change which methods is named\n # visit_Call depending on Python version\n if sys.version_info >= (3, 5):\n visit_Call = visit_Call_35\n else:\n visit_Call = visit_Call_legacy\n\n def visit_Attribute(self, attr):\n if not isinstance(attr.ctx, ast.Load):\n return self.generic_visit(attr)\n value, value_expl = self.visit(attr.value)\n res = self.assign(ast.Attribute(value, attr.attr, ast.Load()))\n res_expl = self.explanation_param(self.display(res))\n pat = \"%s\\n{%s = %s.%s\\n}\"\n expl = pat % (res_expl, res_expl, value_expl, attr.attr)\n return res, expl\n\n def visit_Compare(self, comp):\n self.push_format_context()\n left_res, left_expl = self.visit(comp.left)\n if isinstance(comp.left, (ast.Compare, ast.BoolOp)):\n left_expl = \"({})\".format(left_expl)\n res_variables = [self.variable() for i in range(len(comp.ops))]\n load_names = [ast.Name(v, ast.Load()) for v in res_variables]\n store_names = [ast.Name(v, ast.Store()) for v in res_variables]\n it = zip(range(len(comp.ops)), comp.ops, comp.comparators)\n expls = []\n syms = []\n results = [left_res]\n for i, op, next_operand in it:\n next_res, next_expl = self.visit(next_operand)\n if isinstance(next_operand, (ast.Compare, ast.BoolOp)):\n next_expl = \"({})\".format(next_expl)\n results.append(next_res)\n sym = binop_map[op.__class__]\n syms.append(ast.Str(sym))\n expl = \"%s %s %s\" % (left_expl, sym, next_expl)\n expls.append(ast.Str(expl))\n res_expr = ast.Compare(left_res, [op], [next_res])\n self.statements.append(ast.Assign([store_names[i]], res_expr))\n left_res, left_expl = next_res, next_expl\n # Use pytest.assertion.util._reprcompare if that's available.\n expl_call = self.helper(\n \"_call_reprcompare\",\n ast.Tuple(syms, ast.Load()),\n ast.Tuple(load_names, ast.Load()),\n ast.Tuple(expls, ast.Load()),\n ast.Tuple(results, ast.Load()),\n )\n if len(comp.ops) > 1:\n res = ast.BoolOp(ast.And(), load_names)\n else:\n res = load_names[0]\n return res, self.explanation_param(self.pop_format_context(expl_call))\n"},{"col":4,"comment":"null","endLoc":250,"header":"def test_xfail_evalfalse_but_fails(self, testdir)","id":5896,"name":"test_xfail_evalfalse_but_fails","nodeType":"Function","startLoc":237,"text":"def test_xfail_evalfalse_but_fails(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.xfail('False')\n def test_func():\n assert 0\n \"\"\"\n )\n reports = runtestprotocol(item, log=False)\n callreport = reports[1]\n assert callreport.failed\n assert not hasattr(callreport, \"wasxfail\")\n assert \"xfail\" in callreport.keywords"},{"col":4,"comment":"null","endLoc":264,"header":"def test_xfail_not_report_default(self, testdir)","id":5897,"name":"test_xfail_not_report_default","nodeType":"Function","startLoc":252,"text":"def test_xfail_not_report_default(self, testdir):\n p = testdir.makepyfile(\n test_one=\"\"\"\n import pytest\n @pytest.mark.xfail\n def test_this():\n assert 0\n \"\"\"\n )\n testdir.runpytest(p, \"-v\")\n # result.stdout.fnmatch_lines([\n # \"*HINT*use*-r*\"\n # ])"},{"col":4,"comment":"null","endLoc":290,"header":"def test_xfail_not_run_xfail_reporting(self, testdir)","id":5898,"name":"test_xfail_not_run_xfail_reporting","nodeType":"Function","startLoc":266,"text":"def test_xfail_not_run_xfail_reporting(self, testdir):\n p = testdir.makepyfile(\n test_one=\"\"\"\n import pytest\n @pytest.mark.xfail(run=False, reason=\"noway\")\n def test_this():\n assert 0\n @pytest.mark.xfail(\"True\", run=False)\n def test_this_true():\n assert 0\n @pytest.mark.xfail(\"False\", run=False, reason=\"huh\")\n def test_this_false():\n assert 1\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rx\")\n result.stdout.fnmatch_lines(\n [\n \"*test_one*test_this*\",\n \"*NOTRUN*noway\",\n \"*test_one*test_this_true*\",\n \"*NOTRUN*condition:*True*\",\n \"*1 passed*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":306,"header":"def test_xfail_not_run_no_setup_run(self, testdir)","id":5899,"name":"test_xfail_not_run_no_setup_run","nodeType":"Function","startLoc":292,"text":"def test_xfail_not_run_no_setup_run(self, testdir):\n p = testdir.makepyfile(\n test_one=\"\"\"\n import pytest\n @pytest.mark.xfail(run=False, reason=\"hello\")\n def test_this():\n assert 0\n def setup_module(mod):\n raise ValueError(42)\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rx\")\n result.stdout.fnmatch_lines(\n [\"*test_one*test_this*\", \"*NOTRUN*hello\", \"*1 xfailed*\"]\n )"},{"col":4,"comment":"null","endLoc":1022,"header":"def test_tb_crashline(self, testdir, option)","id":5900,"name":"test_tb_crashline","nodeType":"Function","startLoc":1003,"text":"def test_tb_crashline(self, testdir, option):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def g():\n raise IndexError\n def test_func1():\n print(6*7)\n g() # --calling--\n def test_func2():\n assert 0, \"hello\"\n \"\"\"\n )\n result = testdir.runpytest(\"--tb=line\")\n bn = p.basename\n result.stdout.fnmatch_lines(\n [\"*%s:3: IndexError*\" % bn, \"*%s:8: AssertionError: hello*\" % bn]\n )\n s = result.stdout.str()\n assert \"def test_func2\" not in s"},{"col":0,"comment":"This formats an explanation\n\n Normally all embedded newlines are escaped, however there are\n three exceptions: \n{, \n} and \n~. The first two are intended\n cover nested explanations, see function and attribute explanations\n for examples (.visit_Call(), visit_Attribute()). The last one is\n for when one explanation needs to span multiple lines, e.g. when\n displaying diffs.\n ","endLoc":45,"header":"def format_explanation(explanation)","id":5901,"name":"format_explanation","nodeType":"Function","startLoc":32,"text":"def format_explanation(explanation):\n \"\"\"This formats an explanation\n\n Normally all embedded newlines are escaped, however there are\n three exceptions: \\n{, \\n} and \\n~. The first two are intended\n cover nested explanations, see function and attribute explanations\n for examples (.visit_Call(), visit_Attribute()). The last one is\n for when one explanation needs to span multiple lines, e.g. when\n displaying diffs.\n \"\"\"\n explanation = ecu(explanation)\n lines = _split_explanation(explanation)\n result = _format_lines(lines)\n return u\"\\n\".join(result)"},{"col":0,"comment":"null","endLoc":29,"header":"def ecu(s)","id":5902,"name":"ecu","nodeType":"Function","startLoc":25,"text":"def ecu(s):\n if isinstance(s, bytes):\n return s.decode(\"UTF-8\", \"replace\")\n else:\n return s"},{"col":4,"comment":"null","endLoc":319,"header":"def test_xfail_xpass(self, testdir)","id":5903,"name":"test_xfail_xpass","nodeType":"Function","startLoc":308,"text":"def test_xfail_xpass(self, testdir):\n p = testdir.makepyfile(\n test_one=\"\"\"\n import pytest\n @pytest.mark.xfail\n def test_that():\n assert 1\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rX\")\n result.stdout.fnmatch_lines([\"*XPASS*test_that*\", \"*1 xpassed*\"])\n assert result.ret == 0"},{"col":0,"comment":"Return a list of individual lines in the explanation\n\n This will return a list of lines split on '\n{', '\n}' and '\n~'.\n Any other newlines will be escaped and appear in the line as the\n literal '\n' characters.\n ","endLoc":62,"header":"def _split_explanation(explanation)","id":5904,"name":"_split_explanation","nodeType":"Function","startLoc":48,"text":"def _split_explanation(explanation):\n \"\"\"Return a list of individual lines in the explanation\n\n This will return a list of lines split on '\\n{', '\\n}' and '\\n~'.\n Any other newlines will be escaped and appear in the line as the\n literal '\\n' characters.\n \"\"\"\n raw_lines = (explanation or u\"\").split(\"\\n\")\n lines = [raw_lines[0]]\n for values in raw_lines[1:]:\n if values and values[0] in [\"{\", \"}\", \"~\", \">\"]:\n lines.append(values)\n else:\n lines[-1] += \"\\\\n\" + values\n return lines"},{"col":4,"comment":"null","endLoc":1040,"header":"def test_pytest_report_header(self, testdir, option)","id":5905,"name":"test_pytest_report_header","nodeType":"Function","startLoc":1024,"text":"def test_pytest_report_header(self, testdir, option):\n testdir.makeconftest(\n \"\"\"\n def pytest_sessionstart(session):\n session.config._somevalue = 42\n def pytest_report_header(config):\n return \"hello: %s\" % config._somevalue\n \"\"\"\n )\n testdir.mkdir(\"a\").join(\"conftest.py\").write(\n \"\"\"\ndef pytest_report_header(config, startdir):\n return [\"line1\", str(startdir)]\n\"\"\"\n )\n result = testdir.runpytest(\"a\")\n result.stdout.fnmatch_lines([\"*hello: 42*\", \"line1\", str(testdir.tmpdir)])"},{"col":4,"comment":"null","endLoc":334,"header":"def test_xfail_imperative(self, testdir)","id":5906,"name":"test_xfail_imperative","nodeType":"Function","startLoc":321,"text":"def test_xfail_imperative(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_this():\n pytest.xfail(\"hello\")\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*1 xfailed*\"])\n result = testdir.runpytest(p, \"-rx\")\n result.stdout.fnmatch_lines([\"*XFAIL*test_this*\", \"*reason:*hello*\"])\n result = testdir.runpytest(p, \"--runxfail\")\n result.stdout.fnmatch_lines([\"*1 pass*\"])"},{"col":4,"comment":"null","endLoc":357,"header":"def test_xfail_imperative_in_setup_function(self, testdir)","id":5907,"name":"test_xfail_imperative_in_setup_function","nodeType":"Function","startLoc":336,"text":"def test_xfail_imperative_in_setup_function(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def setup_function(function):\n pytest.xfail(\"hello\")\n\n def test_this():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*1 xfailed*\"])\n result = testdir.runpytest(p, \"-rx\")\n result.stdout.fnmatch_lines([\"*XFAIL*test_this*\", \"*reason:*hello*\"])\n result = testdir.runpytest(p, \"--runxfail\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *def test_this*\n *1 fail*\n \"\"\"\n )"},{"className":"AssertionRewriter","col":0,"comment":"Assertion rewriting implementation.\n\n The main entrypoint is to call .run() with an ast.Module instance,\n this will then find all the assert statements and rewrite them to\n provide intermediate values and a detailed assertion error. See\n http://pybites.blogspot.be/2011/07/behind-scenes-of-pytests-new-assertion.html\n for an overview of how this works.\n\n The entry point here is .run() which will iterate over all the\n statements in an ast.Module and for each ast.Assert statement it\n finds call .visit() with it. Then .visit_Assert() takes over and\n is responsible for creating new ast statements to replace the\n original assert statement: it rewrites the test of an assertion\n to provide intermediate values and replace it with an if statement\n which raises an assertion error with a detailed explanation in\n case the expression is false.\n\n For this .visit_Assert() uses the visitor pattern to visit all the\n AST nodes of the ast.Assert.test field, each visit call returning\n an AST node and the corresponding explanation string. During this\n state is kept in several instance attributes:\n\n :statements: All the AST statements which will replace the assert\n statement.\n\n :variables: This is populated by .variable() with each variable\n used by the statements so that they can all be set to None at\n the end of the statements.\n\n :variable_counter: Counter to create new unique variables needed\n by statements. Variables are created using .variable() and\n have the form of \"@py_assert0\".\n\n :on_failure: The AST statements which will be executed if the\n assertion test fails. This is the code which will construct\n the failure message and raises the AssertionError.\n\n :explanation_specifiers: A dict filled by .explanation_param()\n with %-formatting placeholders and their corresponding\n expressions to use in the building of an assertion message.\n This is used by .pop_format_context() to build a message.\n\n :stack: A stack of the explanation_specifiers dicts maintained by\n .push_format_context() and .pop_format_context() which allows\n to build another %-formatted string while already building one.\n\n This state is reset on every new assert statement visited and used\n by the other visitors.\n\n ","endLoc":1069,"id":5908,"nodeType":"Class","startLoc":593,"text":"class AssertionRewriter(ast.NodeVisitor):\n \"\"\"Assertion rewriting implementation.\n\n The main entrypoint is to call .run() with an ast.Module instance,\n this will then find all the assert statements and rewrite them to\n provide intermediate values and a detailed assertion error. See\n http://pybites.blogspot.be/2011/07/behind-scenes-of-pytests-new-assertion.html\n for an overview of how this works.\n\n The entry point here is .run() which will iterate over all the\n statements in an ast.Module and for each ast.Assert statement it\n finds call .visit() with it. Then .visit_Assert() takes over and\n is responsible for creating new ast statements to replace the\n original assert statement: it rewrites the test of an assertion\n to provide intermediate values and replace it with an if statement\n which raises an assertion error with a detailed explanation in\n case the expression is false.\n\n For this .visit_Assert() uses the visitor pattern to visit all the\n AST nodes of the ast.Assert.test field, each visit call returning\n an AST node and the corresponding explanation string. During this\n state is kept in several instance attributes:\n\n :statements: All the AST statements which will replace the assert\n statement.\n\n :variables: This is populated by .variable() with each variable\n used by the statements so that they can all be set to None at\n the end of the statements.\n\n :variable_counter: Counter to create new unique variables needed\n by statements. Variables are created using .variable() and\n have the form of \"@py_assert0\".\n\n :on_failure: The AST statements which will be executed if the\n assertion test fails. This is the code which will construct\n the failure message and raises the AssertionError.\n\n :explanation_specifiers: A dict filled by .explanation_param()\n with %-formatting placeholders and their corresponding\n expressions to use in the building of an assertion message.\n This is used by .pop_format_context() to build a message.\n\n :stack: A stack of the explanation_specifiers dicts maintained by\n .push_format_context() and .pop_format_context() which allows\n to build another %-formatted string while already building one.\n\n This state is reset on every new assert statement visited and used\n by the other visitors.\n\n \"\"\"\n\n def __init__(self, module_path, config):\n super(AssertionRewriter, self).__init__()\n self.module_path = module_path\n self.config = config\n\n def run(self, mod):\n \"\"\"Find all assert statements in *mod* and rewrite them.\"\"\"\n if not mod.body:\n # Nothing to do.\n return\n # Insert some special imports at the top of the module but after any\n # docstrings and __future__ imports.\n aliases = [\n ast.alias(six.moves.builtins.__name__, \"@py_builtins\"),\n ast.alias(\"_pytest.assertion.rewrite\", \"@pytest_ar\"),\n ]\n doc = getattr(mod, \"docstring\", None)\n expect_docstring = doc is None\n if doc is not None and self.is_rewrite_disabled(doc):\n return\n pos = 0\n lineno = 1\n for item in mod.body:\n if (\n expect_docstring\n and isinstance(item, ast.Expr)\n and isinstance(item.value, ast.Str)\n ):\n doc = item.value.s\n if self.is_rewrite_disabled(doc):\n return\n expect_docstring = False\n elif (\n not isinstance(item, ast.ImportFrom)\n or item.level > 0\n or item.module != \"__future__\"\n ):\n lineno = item.lineno\n break\n pos += 1\n else:\n lineno = item.lineno\n imports = [\n ast.Import([alias], lineno=lineno, col_offset=0) for alias in aliases\n ]\n mod.body[pos:pos] = imports\n # Collect asserts.\n nodes = [mod]\n while nodes:\n node = nodes.pop()\n for name, field in ast.iter_fields(node):\n if isinstance(field, list):\n new = []\n for i, child in enumerate(field):\n if isinstance(child, ast.Assert):\n # Transform assert.\n new.extend(self.visit(child))\n else:\n new.append(child)\n if isinstance(child, ast.AST):\n nodes.append(child)\n setattr(node, name, new)\n elif (\n isinstance(field, ast.AST)\n # Don't recurse into expressions as they can't contain\n # asserts.\n and not isinstance(field, ast.expr)\n ):\n nodes.append(field)\n\n @staticmethod\n def is_rewrite_disabled(docstring):\n return \"PYTEST_DONT_REWRITE\" in docstring\n\n def variable(self):\n \"\"\"Get a new variable.\"\"\"\n # Use a character invalid in python identifiers to avoid clashing.\n name = \"@py_assert\" + str(next(self.variable_counter))\n self.variables.append(name)\n return name\n\n def assign(self, expr):\n \"\"\"Give *expr* a name.\"\"\"\n name = self.variable()\n self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr))\n return ast.Name(name, ast.Load())\n\n def display(self, expr):\n \"\"\"Call saferepr on the expression.\"\"\"\n return self.helper(\"_saferepr\", expr)\n\n def helper(self, name, *args):\n \"\"\"Call a helper in this module.\"\"\"\n py_name = ast.Name(\"@pytest_ar\", ast.Load())\n attr = ast.Attribute(py_name, name, ast.Load())\n return ast_Call(attr, list(args), [])\n\n def builtin(self, name):\n \"\"\"Return the builtin called *name*.\"\"\"\n builtin_name = ast.Name(\"@py_builtins\", ast.Load())\n return ast.Attribute(builtin_name, name, ast.Load())\n\n def explanation_param(self, expr):\n \"\"\"Return a new named %-formatting placeholder for expr.\n\n This creates a %-formatting placeholder for expr in the\n current formatting context, e.g. ``%(py0)s``. The placeholder\n and expr are placed in the current format context so that it\n can be used on the next call to .pop_format_context().\n\n \"\"\"\n specifier = \"py\" + str(next(self.variable_counter))\n self.explanation_specifiers[specifier] = expr\n return \"%(\" + specifier + \")s\"\n\n def push_format_context(self):\n \"\"\"Create a new formatting context.\n\n The format context is used for when an explanation wants to\n have a variable value formatted in the assertion message. In\n this case the value required can be added using\n .explanation_param(). Finally .pop_format_context() is used\n to format a string of %-formatted values as added by\n .explanation_param().\n\n \"\"\"\n self.explanation_specifiers = {}\n self.stack.append(self.explanation_specifiers)\n\n def pop_format_context(self, expl_expr):\n \"\"\"Format the %-formatted string with current format context.\n\n The expl_expr should be an ast.Str instance constructed from\n the %-placeholders created by .explanation_param(). This will\n add the required code to format said string to .on_failure and\n return the ast.Name instance of the formatted string.\n\n \"\"\"\n current = self.stack.pop()\n if self.stack:\n self.explanation_specifiers = self.stack[-1]\n keys = [ast.Str(key) for key in current.keys()]\n format_dict = ast.Dict(keys, list(current.values()))\n form = ast.BinOp(expl_expr, ast.Mod(), format_dict)\n name = \"@py_format\" + str(next(self.variable_counter))\n self.on_failure.append(ast.Assign([ast.Name(name, ast.Store())], form))\n return ast.Name(name, ast.Load())\n\n def generic_visit(self, node):\n \"\"\"Handle expressions we don't have custom code for.\"\"\"\n assert isinstance(node, ast.expr)\n res = self.assign(node)\n return res, self.explanation_param(self.display(res))\n\n def visit_Assert(self, assert_):\n \"\"\"Return the AST statements to replace the ast.Assert instance.\n\n This rewrites the test of an assertion to provide\n intermediate values and replace it with an if statement which\n raises an assertion error with a detailed explanation in case\n the expression is false.\n\n \"\"\"\n if isinstance(assert_.test, ast.Tuple) and len(assert_.test.elts) >= 1:\n from _pytest.warning_types import PytestAssertRewriteWarning\n import warnings\n\n warnings.warn_explicit(\n PytestAssertRewriteWarning(\n \"assertion is always true, perhaps remove parentheses?\"\n ),\n category=None,\n filename=str(self.module_path),\n lineno=assert_.lineno,\n )\n\n self.statements = []\n self.variables = []\n self.variable_counter = itertools.count()\n self.stack = []\n self.on_failure = []\n self.push_format_context()\n # Rewrite assert into a bunch of statements.\n top_condition, explanation = self.visit(assert_.test)\n # If in a test module, check if directly asserting None, in order to warn [Issue #3191]\n if self.module_path is not None:\n self.statements.append(\n self.warn_about_none_ast(\n top_condition, module_path=self.module_path, lineno=assert_.lineno\n )\n )\n # Create failure message.\n body = self.on_failure\n negation = ast.UnaryOp(ast.Not(), top_condition)\n self.statements.append(ast.If(negation, body, []))\n if assert_.msg:\n assertmsg = self.helper(\"_format_assertmsg\", assert_.msg)\n explanation = \"\\n>assert \" + explanation\n else:\n assertmsg = ast.Str(\"\")\n explanation = \"assert \" + explanation\n template = ast.BinOp(assertmsg, ast.Add(), ast.Str(explanation))\n msg = self.pop_format_context(template)\n fmt = self.helper(\"_format_explanation\", msg)\n err_name = ast.Name(\"AssertionError\", ast.Load())\n exc = ast_Call(err_name, [fmt], [])\n if sys.version_info[0] >= 3:\n raise_ = ast.Raise(exc, None)\n else:\n raise_ = ast.Raise(exc, None, None)\n body.append(raise_)\n # Clear temporary variables by setting them to None.\n if self.variables:\n variables = [ast.Name(name, ast.Store()) for name in self.variables]\n clear = ast.Assign(variables, _NameConstant(None))\n self.statements.append(clear)\n # Fix line numbers.\n for stmt in self.statements:\n set_location(stmt, assert_.lineno, assert_.col_offset)\n return self.statements\n\n def warn_about_none_ast(self, node, module_path, lineno):\n \"\"\"\n Returns an AST issuing a warning if the value of node is `None`.\n This is used to warn the user when asserting a function that asserts\n internally already.\n See issue #3191 for more details.\n \"\"\"\n\n # Using parse because it is different between py2 and py3.\n AST_NONE = ast.parse(\"None\").body[0].value\n val_is_none = ast.Compare(node, [ast.Is()], [AST_NONE])\n send_warning = ast.parse(\n \"\"\"\nfrom _pytest.warning_types import PytestAssertRewriteWarning\nfrom warnings import warn_explicit\nwarn_explicit(\n PytestAssertRewriteWarning('asserting the value None, please use \"assert is None\"'),\n category=None,\n filename={filename!r},\n lineno={lineno},\n)\n \"\"\".format(\n filename=module_path.strpath, lineno=lineno\n )\n ).body\n return ast.If(val_is_none, send_warning, [])\n\n def visit_Name(self, name):\n # Display the repr of the name if it's a local variable or\n # _should_repr_global_name() thinks it's acceptable.\n locs = ast_Call(self.builtin(\"locals\"), [], [])\n inlocs = ast.Compare(ast.Str(name.id), [ast.In()], [locs])\n dorepr = self.helper(\"_should_repr_global_name\", name)\n test = ast.BoolOp(ast.Or(), [inlocs, dorepr])\n expr = ast.IfExp(test, self.display(name), ast.Str(name.id))\n return name, self.explanation_param(expr)\n\n def visit_BoolOp(self, boolop):\n res_var = self.variable()\n expl_list = self.assign(ast.List([], ast.Load()))\n app = ast.Attribute(expl_list, \"append\", ast.Load())\n is_or = int(isinstance(boolop.op, ast.Or))\n body = save = self.statements\n fail_save = self.on_failure\n levels = len(boolop.values) - 1\n self.push_format_context()\n # Process each operand, short-circuting if needed.\n for i, v in enumerate(boolop.values):\n if i:\n fail_inner = []\n # cond is set in a prior loop iteration below\n self.on_failure.append(ast.If(cond, fail_inner, [])) # noqa\n self.on_failure = fail_inner\n self.push_format_context()\n res, expl = self.visit(v)\n body.append(ast.Assign([ast.Name(res_var, ast.Store())], res))\n expl_format = self.pop_format_context(ast.Str(expl))\n call = ast_Call(app, [expl_format], [])\n self.on_failure.append(ast.Expr(call))\n if i < levels:\n cond = res\n if is_or:\n cond = ast.UnaryOp(ast.Not(), cond)\n inner = []\n self.statements.append(ast.If(cond, inner, []))\n self.statements = body = inner\n self.statements = save\n self.on_failure = fail_save\n expl_template = self.helper(\"_format_boolop\", expl_list, ast.Num(is_or))\n expl = self.pop_format_context(expl_template)\n return ast.Name(res_var, ast.Load()), self.explanation_param(expl)\n\n def visit_UnaryOp(self, unary):\n pattern = unary_map[unary.op.__class__]\n operand_res, operand_expl = self.visit(unary.operand)\n res = self.assign(ast.UnaryOp(unary.op, operand_res))\n return res, pattern % (operand_expl,)\n\n def visit_BinOp(self, binop):\n symbol = binop_map[binop.op.__class__]\n left_expr, left_expl = self.visit(binop.left)\n right_expr, right_expl = self.visit(binop.right)\n explanation = \"(%s %s %s)\" % (left_expl, symbol, right_expl)\n res = self.assign(ast.BinOp(left_expr, binop.op, right_expr))\n return res, explanation\n\n def visit_Call_35(self, call):\n \"\"\"\n visit `ast.Call` nodes on Python3.5 and after\n \"\"\"\n new_func, func_expl = self.visit(call.func)\n arg_expls = []\n new_args = []\n new_kwargs = []\n for arg in call.args:\n res, expl = self.visit(arg)\n arg_expls.append(expl)\n new_args.append(res)\n for keyword in call.keywords:\n res, expl = self.visit(keyword.value)\n new_kwargs.append(ast.keyword(keyword.arg, res))\n if keyword.arg:\n arg_expls.append(keyword.arg + \"=\" + expl)\n else: # **args have `arg` keywords with an .arg of None\n arg_expls.append(\"**\" + expl)\n\n expl = \"%s(%s)\" % (func_expl, \", \".join(arg_expls))\n new_call = ast.Call(new_func, new_args, new_kwargs)\n res = self.assign(new_call)\n res_expl = self.explanation_param(self.display(res))\n outer_expl = \"%s\\n{%s = %s\\n}\" % (res_expl, res_expl, expl)\n return res, outer_expl\n\n def visit_Starred(self, starred):\n # From Python 3.5, a Starred node can appear in a function call\n res, expl = self.visit(starred.value)\n new_starred = ast.Starred(res, starred.ctx)\n return new_starred, \"*\" + expl\n\n def visit_Call_legacy(self, call):\n \"\"\"\n visit `ast.Call nodes on 3.4 and below`\n \"\"\"\n new_func, func_expl = self.visit(call.func)\n arg_expls = []\n new_args = []\n new_kwargs = []\n new_star = new_kwarg = None\n for arg in call.args:\n res, expl = self.visit(arg)\n new_args.append(res)\n arg_expls.append(expl)\n for keyword in call.keywords:\n res, expl = self.visit(keyword.value)\n new_kwargs.append(ast.keyword(keyword.arg, res))\n arg_expls.append(keyword.arg + \"=\" + expl)\n if call.starargs:\n new_star, expl = self.visit(call.starargs)\n arg_expls.append(\"*\" + expl)\n if call.kwargs:\n new_kwarg, expl = self.visit(call.kwargs)\n arg_expls.append(\"**\" + expl)\n expl = \"%s(%s)\" % (func_expl, \", \".join(arg_expls))\n new_call = ast.Call(new_func, new_args, new_kwargs, new_star, new_kwarg)\n res = self.assign(new_call)\n res_expl = self.explanation_param(self.display(res))\n outer_expl = \"%s\\n{%s = %s\\n}\" % (res_expl, res_expl, expl)\n return res, outer_expl\n\n # ast.Call signature changed on 3.5,\n # conditionally change which methods is named\n # visit_Call depending on Python version\n if sys.version_info >= (3, 5):\n visit_Call = visit_Call_35\n else:\n visit_Call = visit_Call_legacy\n\n def visit_Attribute(self, attr):\n if not isinstance(attr.ctx, ast.Load):\n return self.generic_visit(attr)\n value, value_expl = self.visit(attr.value)\n res = self.assign(ast.Attribute(value, attr.attr, ast.Load()))\n res_expl = self.explanation_param(self.display(res))\n pat = \"%s\\n{%s = %s.%s\\n}\"\n expl = pat % (res_expl, res_expl, value_expl, attr.attr)\n return res, expl\n\n def visit_Compare(self, comp):\n self.push_format_context()\n left_res, left_expl = self.visit(comp.left)\n if isinstance(comp.left, (ast.Compare, ast.BoolOp)):\n left_expl = \"({})\".format(left_expl)\n res_variables = [self.variable() for i in range(len(comp.ops))]\n load_names = [ast.Name(v, ast.Load()) for v in res_variables]\n store_names = [ast.Name(v, ast.Store()) for v in res_variables]\n it = zip(range(len(comp.ops)), comp.ops, comp.comparators)\n expls = []\n syms = []\n results = [left_res]\n for i, op, next_operand in it:\n next_res, next_expl = self.visit(next_operand)\n if isinstance(next_operand, (ast.Compare, ast.BoolOp)):\n next_expl = \"({})\".format(next_expl)\n results.append(next_res)\n sym = binop_map[op.__class__]\n syms.append(ast.Str(sym))\n expl = \"%s %s %s\" % (left_expl, sym, next_expl)\n expls.append(ast.Str(expl))\n res_expr = ast.Compare(left_res, [op], [next_res])\n self.statements.append(ast.Assign([store_names[i]], res_expr))\n left_res, left_expl = next_res, next_expl\n # Use pytest.assertion.util._reprcompare if that's available.\n expl_call = self.helper(\n \"_call_reprcompare\",\n ast.Tuple(syms, ast.Load()),\n ast.Tuple(load_names, ast.Load()),\n ast.Tuple(expls, ast.Load()),\n ast.Tuple(results, ast.Load()),\n )\n if len(comp.ops) > 1:\n res = ast.BoolOp(ast.And(), load_names)\n else:\n res = load_names[0]\n return res, self.explanation_param(self.pop_format_context(expl_call))"},{"col":0,"comment":"This tests that pytest's config setup handles \"-p no:X\".","endLoc":1217,"header":"def test_config_does_not_load_blocked_plugin_from_args(testdir)","id":5909,"name":"test_config_does_not_load_blocked_plugin_from_args","nodeType":"Function","startLoc":1208,"text":"def test_config_does_not_load_blocked_plugin_from_args(testdir):\n \"\"\"This tests that pytest's config setup handles \"-p no:X\".\"\"\"\n p = testdir.makepyfile(\"def test(capfd): pass\")\n result = testdir.runpytest(str(p), \"-pno:capture\")\n result.stdout.fnmatch_lines([\"E fixture 'capfd' not found\"])\n assert result.ret == EXIT_TESTSFAILED\n\n result = testdir.runpytest(str(p), \"-pno:capture\", \"-s\")\n result.stderr.fnmatch_lines([\"*: error: unrecognized arguments: -s\"])\n assert result.ret == EXIT_USAGEERROR"},{"className":"NodeVisitor","col":0,"comment":"null","endLoc":174,"id":5910,"nodeType":"Class","startLoc":44,"text":"class NodeVisitor:\n def visit(self, node: AST) -> Any: ...\n def generic_visit(self, node: AST) -> Any: ...\n def visit_Module(self, node: Module) -> Any: ...\n def visit_Interactive(self, node: Interactive) -> Any: ...\n def visit_Expression(self, node: Expression) -> Any: ...\n def visit_FunctionDef(self, node: FunctionDef) -> Any: ...\n def visit_AsyncFunctionDef(self, node: AsyncFunctionDef) -> Any: ...\n def visit_ClassDef(self, node: ClassDef) -> Any: ...\n def visit_Return(self, node: Return) -> Any: ...\n def visit_Delete(self, node: Delete) -> Any: ...\n def visit_Assign(self, node: Assign) -> Any: ...\n def visit_AugAssign(self, node: AugAssign) -> Any: ...\n def visit_AnnAssign(self, node: AnnAssign) -> Any: ...\n def visit_For(self, node: For) -> Any: ...\n def visit_AsyncFor(self, node: AsyncFor) -> Any: ...\n def visit_While(self, node: While) -> Any: ...\n def visit_If(self, node: If) -> Any: ...\n def visit_With(self, node: With) -> Any: ...\n def visit_AsyncWith(self, node: AsyncWith) -> Any: ...\n def visit_Raise(self, node: Raise) -> Any: ...\n def visit_Try(self, node: Try) -> Any: ...\n def visit_Assert(self, node: Assert) -> Any: ...\n def visit_Import(self, node: Import) -> Any: ...\n def visit_ImportFrom(self, node: ImportFrom) -> Any: ...\n def visit_Global(self, node: Global) -> Any: ...\n def visit_Nonlocal(self, node: Nonlocal) -> Any: ...\n def visit_Expr(self, node: Expr) -> Any: ...\n def visit_Pass(self, node: Pass) -> Any: ...\n def visit_Break(self, node: Break) -> Any: ...\n def visit_Continue(self, node: Continue) -> Any: ...\n def visit_Slice(self, node: Slice) -> Any: ...\n def visit_BoolOp(self, node: BoolOp) -> Any: ...\n def visit_BinOp(self, node: BinOp) -> Any: ...\n def visit_UnaryOp(self, node: UnaryOp) -> Any: ...\n def visit_Lambda(self, node: Lambda) -> Any: ...\n def visit_IfExp(self, node: IfExp) -> Any: ...\n def visit_Dict(self, node: Dict) -> Any: ...\n def visit_Set(self, node: Set) -> Any: ...\n def visit_ListComp(self, node: ListComp) -> Any: ...\n def visit_SetComp(self, node: SetComp) -> Any: ...\n def visit_DictComp(self, node: DictComp) -> Any: ...\n def visit_GeneratorExp(self, node: GeneratorExp) -> Any: ...\n def visit_Await(self, node: Await) -> Any: ...\n def visit_Yield(self, node: Yield) -> Any: ...\n def visit_YieldFrom(self, node: YieldFrom) -> Any: ...\n def visit_Compare(self, node: Compare) -> Any: ...\n def visit_Call(self, node: Call) -> Any: ...\n def visit_FormattedValue(self, node: FormattedValue) -> Any: ...\n def visit_JoinedStr(self, node: JoinedStr) -> Any: ...\n def visit_Constant(self, node: Constant) -> Any: ...\n def visit_NamedExpr(self, node: NamedExpr) -> Any: ...\n def visit_TypeIgnore(self, node: TypeIgnore) -> Any: ...\n def visit_Attribute(self, node: Attribute) -> Any: ...\n def visit_Subscript(self, node: Subscript) -> Any: ...\n def visit_Starred(self, node: Starred) -> Any: ...\n def visit_Name(self, node: Name) -> Any: ...\n def visit_List(self, node: List) -> Any: ...\n def visit_Tuple(self, node: Tuple) -> Any: ...\n def visit_Del(self, node: Del) -> Any: ...\n def visit_Load(self, node: Load) -> Any: ...\n def visit_Store(self, node: Store) -> Any: ...\n def visit_And(self, node: And) -> Any: ...\n def visit_Or(self, node: Or) -> Any: ...\n def visit_Add(self, node: Add) -> Any: ...\n def visit_BitAnd(self, node: BitAnd) -> Any: ...\n def visit_BitOr(self, node: BitOr) -> Any: ...\n def visit_BitXor(self, node: BitXor) -> Any: ...\n def visit_Div(self, node: Div) -> Any: ...\n def visit_FloorDiv(self, node: FloorDiv) -> Any: ...\n def visit_LShift(self, node: LShift) -> Any: ...\n def visit_Mod(self, node: Mod) -> Any: ...\n def visit_Mult(self, node: Mult) -> Any: ...\n def visit_MatMult(self, node: MatMult) -> Any: ...\n def visit_Pow(self, node: Pow) -> Any: ...\n def visit_RShift(self, node: RShift) -> Any: ...\n def visit_Sub(self, node: Sub) -> Any: ...\n def visit_Invert(self, node: Invert) -> Any: ...\n def visit_Not(self, node: Not) -> Any: ...\n def visit_UAdd(self, node: UAdd) -> Any: ...\n def visit_USub(self, node: USub) -> Any: ...\n def visit_Eq(self, node: Eq) -> Any: ...\n def visit_Gt(self, node: Gt) -> Any: ...\n def visit_GtE(self, node: GtE) -> Any: ...\n def visit_In(self, node: In) -> Any: ...\n def visit_Is(self, node: Is) -> Any: ...\n def visit_IsNot(self, node: IsNot) -> Any: ...\n def visit_Lt(self, node: Lt) -> Any: ...\n def visit_LtE(self, node: LtE) -> Any: ...\n def visit_NotEq(self, node: NotEq) -> Any: ...\n def visit_NotIn(self, node: NotIn) -> Any: ...\n def visit_comprehension(self, node: comprehension) -> Any: ...\n def visit_ExceptHandler(self, node: ExceptHandler) -> Any: ...\n def visit_arguments(self, node: arguments) -> Any: ...\n def visit_arg(self, node: arg) -> Any: ...\n def visit_keyword(self, node: keyword) -> Any: ...\n def visit_alias(self, node: alias) -> Any: ...\n def visit_withitem(self, node: withitem) -> Any: ...\n if sys.version_info >= (3, 10):\n def visit_Match(self, node: Match) -> Any: ...\n def visit_match_case(self, node: match_case) -> Any: ...\n def visit_MatchValue(self, node: MatchValue) -> Any: ...\n def visit_MatchSequence(self, node: MatchSequence) -> Any: ...\n def visit_MatchSingleton(self, node: MatchSingleton) -> Any: ...\n def visit_MatchStar(self, node: MatchStar) -> Any: ...\n def visit_MatchMapping(self, node: MatchMapping) -> Any: ...\n def visit_MatchClass(self, node: MatchClass) -> Any: ...\n def visit_MatchAs(self, node: MatchAs) -> Any: ...\n def visit_MatchOr(self, node: MatchOr) -> Any: ...\n\n if sys.version_info >= (3, 11):\n def visit_TryStar(self, node: TryStar) -> Any: ...\n\n if sys.version_info >= (3, 12):\n def visit_TypeVar(self, node: TypeVar) -> Any: ...\n def visit_ParamSpec(self, node: ParamSpec) -> Any: ...\n def visit_TypeVarTuple(self, node: TypeVarTuple) -> Any: ...\n def visit_TypeAlias(self, node: TypeAlias) -> Any: ...\n\n # visit methods for deprecated nodes\n def visit_ExtSlice(self, node: ExtSlice) -> Any: ...\n def visit_Index(self, node: Index) -> Any: ...\n def visit_Suite(self, node: Suite) -> Any: ...\n def visit_AugLoad(self, node: AugLoad) -> Any: ...\n def visit_AugStore(self, node: AugStore) -> Any: ...\n def visit_Param(self, node: Param) -> Any: ...\n def visit_Num(self, node: Num) -> Any: ...\n def visit_Str(self, node: Str) -> Any: ...\n def visit_Bytes(self, node: Bytes) -> Any: ...\n def visit_NameConstant(self, node: NameConstant) -> Any: ...\n def visit_Ellipsis(self, node: Ellipsis) -> Any: ..."},{"col":4,"comment":"null","endLoc":372,"header":"def xtest_dynamic_xfail_set_during_setup(self, testdir)","id":5911,"name":"xtest_dynamic_xfail_set_during_setup","nodeType":"Function","startLoc":359,"text":"def xtest_dynamic_xfail_set_during_setup(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def setup_function(function):\n pytest.mark.xfail(function)\n def test_this():\n assert 0\n def test_that():\n assert 1\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rxX\")\n result.stdout.fnmatch_lines([\"*XFAIL*test_this*\", \"*XPASS*test_that*\"])"},{"col":4,"comment":"null","endLoc":386,"header":"def test_dynamic_xfail_no_run(self, testdir)","id":5912,"name":"test_dynamic_xfail_no_run","nodeType":"Function","startLoc":374,"text":"def test_dynamic_xfail_no_run(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def arg(request):\n request.applymarker(pytest.mark.xfail(run=False))\n def test_this(arg):\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rxX\")\n result.stdout.fnmatch_lines([\"*XFAIL*test_this*\", \"*NOTRUN*\"])"},{"col":0,"comment":"null","endLoc":1262,"header":"@pytest.mark.parametrize(\n \"plugin\",\n [\n x\n for x in _pytest.config.default_plugins\n if x not in _pytest.config.essential_plugins\n ],\n)\ndef test_config_blocked_default_plugins(testdir, plugin)","id":5913,"name":"test_config_blocked_default_plugins","nodeType":"Function","startLoc":1220,"text":"@pytest.mark.parametrize(\n \"plugin\",\n [\n x\n for x in _pytest.config.default_plugins\n if x not in _pytest.config.essential_plugins\n ],\n)\ndef test_config_blocked_default_plugins(testdir, plugin):\n if plugin == \"debugging\":\n # Fixed in xdist master (after 1.27.0).\n # https://github.com/pytest-dev/pytest-xdist/pull/422\n try:\n import xdist # noqa: F401\n except ImportError:\n pass\n else:\n pytest.skip(\"does not work with xdist currently\")\n\n p = testdir.makepyfile(\"def test(): pass\")\n result = testdir.runpytest(str(p), \"-pno:%s\" % plugin)\n\n if plugin == \"python\":\n assert result.ret == EXIT_USAGEERROR\n result.stderr.fnmatch_lines(\n [\n \"ERROR: not found: */test_config_blocked_default_plugins.py\",\n \"(no name '*/test_config_blocked_default_plugins.py' in any of [])\",\n ]\n )\n return\n\n assert result.ret == EXIT_OK\n if plugin != \"terminal\":\n result.stdout.fnmatch_lines([\"* 1 passed in *\"])\n\n p = testdir.makepyfile(\"def test(): assert 0\")\n result = testdir.runpytest(str(p), \"-pno:%s\" % plugin)\n assert result.ret == EXIT_TESTSFAILED\n if plugin != \"terminal\":\n result.stdout.fnmatch_lines([\"* 1 failed in *\"])\n else:\n assert result.stdout.lines == [\"\"]"},{"col":4,"comment":"null","endLoc":400,"header":"def test_dynamic_xfail_set_during_funcarg_setup(self, testdir)","id":5914,"name":"test_dynamic_xfail_set_during_funcarg_setup","nodeType":"Function","startLoc":388,"text":"def test_dynamic_xfail_set_during_funcarg_setup(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def arg(request):\n request.applymarker(pytest.mark.xfail)\n def test_this2(arg):\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*1 xfailed*\"])"},{"col":4,"comment":"null","endLoc":1091,"header":"def test_show_capture(self, testdir)","id":5915,"name":"test_show_capture","nodeType":"Function","startLoc":1042,"text":"def test_show_capture(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n import logging\n def test_one():\n sys.stdout.write('!This is stdout!')\n sys.stderr.write('!This is stderr!')\n logging.warning('!This is a warning log msg!')\n assert False, 'Something failed'\n \"\"\"\n )\n\n result = testdir.runpytest(\"--tb=short\")\n result.stdout.fnmatch_lines(\n [\n \"!This is stdout!\",\n \"!This is stderr!\",\n \"*WARNING*!This is a warning log msg!\",\n ]\n )\n\n result = testdir.runpytest(\"--show-capture=all\", \"--tb=short\")\n result.stdout.fnmatch_lines(\n [\n \"!This is stdout!\",\n \"!This is stderr!\",\n \"*WARNING*!This is a warning log msg!\",\n ]\n )\n\n stdout = testdir.runpytest(\"--show-capture=stdout\", \"--tb=short\").stdout.str()\n assert \"!This is stderr!\" not in stdout\n assert \"!This is stdout!\" in stdout\n assert \"!This is a warning log msg!\" not in stdout\n\n stdout = testdir.runpytest(\"--show-capture=stderr\", \"--tb=short\").stdout.str()\n assert \"!This is stdout!\" not in stdout\n assert \"!This is stderr!\" in stdout\n assert \"!This is a warning log msg!\" not in stdout\n\n stdout = testdir.runpytest(\"--show-capture=log\", \"--tb=short\").stdout.str()\n assert \"!This is stdout!\" not in stdout\n assert \"!This is stderr!\" not in stdout\n assert \"!This is a warning log msg!\" in stdout\n\n stdout = testdir.runpytest(\"--show-capture=no\", \"--tb=short\").stdout.str()\n assert \"!This is stdout!\" not in stdout\n assert \"!This is stderr!\" not in stdout\n assert \"!This is a warning log msg!\" not in stdout"},{"col":4,"comment":"null","endLoc":46,"header":"def generic_visit(self, node: AST) -> Any","id":5916,"name":"generic_visit","nodeType":"Function","startLoc":46,"text":"def generic_visit(self, node: AST) -> Any: ..."},{"col":4,"comment":"null","endLoc":47,"header":"def visit_Module(self, node: Module) -> Any","id":5917,"name":"visit_Module","nodeType":"Function","startLoc":47,"text":"def visit_Module(self, node: Module) -> Any: ..."},{"col":4,"comment":"null","endLoc":48,"header":"def visit_Interactive(self, node: Interactive) -> Any","id":5918,"name":"visit_Interactive","nodeType":"Function","startLoc":48,"text":"def visit_Interactive(self, node: Interactive) -> Any: ..."},{"col":4,"comment":"null","endLoc":49,"header":"def visit_Expression(self, node: Expression) -> Any","id":5919,"name":"visit_Expression","nodeType":"Function","startLoc":49,"text":"def visit_Expression(self, node: Expression) -> Any: ..."},{"col":4,"comment":"null","endLoc":50,"header":"def visit_FunctionDef(self, node: FunctionDef) -> Any","id":5920,"name":"visit_FunctionDef","nodeType":"Function","startLoc":50,"text":"def visit_FunctionDef(self, node: FunctionDef) -> Any: ..."},{"col":4,"comment":"null","endLoc":51,"header":"def visit_AsyncFunctionDef(self, node: AsyncFunctionDef) -> Any","id":5921,"name":"visit_AsyncFunctionDef","nodeType":"Function","startLoc":51,"text":"def visit_AsyncFunctionDef(self, node: AsyncFunctionDef) -> Any: ..."},{"col":4,"comment":"null","endLoc":52,"header":"def visit_ClassDef(self, node: ClassDef) -> Any","id":5922,"name":"visit_ClassDef","nodeType":"Function","startLoc":52,"text":"def visit_ClassDef(self, node: ClassDef) -> Any: ..."},{"col":4,"comment":"null","endLoc":53,"header":"def visit_Return(self, node: Return) -> Any","id":5923,"name":"visit_Return","nodeType":"Function","startLoc":53,"text":"def visit_Return(self, node: Return) -> Any: ..."},{"col":4,"comment":"null","endLoc":54,"header":"def visit_Delete(self, node: Delete) -> Any","id":5924,"name":"visit_Delete","nodeType":"Function","startLoc":54,"text":"def visit_Delete(self, node: Delete) -> Any: ..."},{"col":4,"comment":"null","endLoc":55,"header":"def visit_Assign(self, node: Assign) -> Any","id":5925,"name":"visit_Assign","nodeType":"Function","startLoc":55,"text":"def visit_Assign(self, node: Assign) -> Any: ..."},{"col":4,"comment":"null","endLoc":56,"header":"def visit_AugAssign(self, node: AugAssign) -> Any","id":5926,"name":"visit_AugAssign","nodeType":"Function","startLoc":56,"text":"def visit_AugAssign(self, node: AugAssign) -> Any: ..."},{"col":4,"comment":"null","endLoc":57,"header":"def visit_AnnAssign(self, node: AnnAssign) -> Any","id":5927,"name":"visit_AnnAssign","nodeType":"Function","startLoc":57,"text":"def visit_AnnAssign(self, node: AnnAssign) -> Any: ..."},{"col":4,"comment":"null","endLoc":58,"header":"def visit_For(self, node: For) -> Any","id":5928,"name":"visit_For","nodeType":"Function","startLoc":58,"text":"def visit_For(self, node: For) -> Any: ..."},{"col":4,"comment":"null","endLoc":59,"header":"def visit_AsyncFor(self, node: AsyncFor) -> Any","id":5929,"name":"visit_AsyncFor","nodeType":"Function","startLoc":59,"text":"def visit_AsyncFor(self, node: AsyncFor) -> Any: ..."},{"col":4,"comment":"null","endLoc":60,"header":"def visit_While(self, node: While) -> Any","id":5930,"name":"visit_While","nodeType":"Function","startLoc":60,"text":"def visit_While(self, node: While) -> Any: ..."},{"col":4,"comment":"null","endLoc":61,"header":"def visit_If(self, node: If) -> Any","id":5931,"name":"visit_If","nodeType":"Function","startLoc":61,"text":"def visit_If(self, node: If) -> Any: ..."},{"col":4,"comment":"null","endLoc":62,"header":"def visit_With(self, node: With) -> Any","id":5932,"name":"visit_With","nodeType":"Function","startLoc":62,"text":"def visit_With(self, node: With) -> Any: ..."},{"col":4,"comment":"null","endLoc":63,"header":"def visit_AsyncWith(self, node: AsyncWith) -> Any","id":5933,"name":"visit_AsyncWith","nodeType":"Function","startLoc":63,"text":"def visit_AsyncWith(self, node: AsyncWith) -> Any: ..."},{"col":4,"comment":"null","endLoc":64,"header":"def visit_Raise(self, node: Raise) -> Any","id":5934,"name":"visit_Raise","nodeType":"Function","startLoc":64,"text":"def visit_Raise(self, node: Raise) -> Any: ..."},{"col":4,"comment":"null","endLoc":65,"header":"def visit_Try(self, node: Try) -> Any","id":5935,"name":"visit_Try","nodeType":"Function","startLoc":65,"text":"def visit_Try(self, node: Try) -> Any: ..."},{"col":4,"comment":"null","endLoc":66,"header":"def visit_Assert(self, node: Assert) -> Any","id":5936,"name":"visit_Assert","nodeType":"Function","startLoc":66,"text":"def visit_Assert(self, node: Assert) -> Any: ..."},{"col":4,"comment":"null","endLoc":67,"header":"def visit_Import(self, node: Import) -> Any","id":5937,"name":"visit_Import","nodeType":"Function","startLoc":67,"text":"def visit_Import(self, node: Import) -> Any: ..."},{"col":4,"comment":"null","endLoc":68,"header":"def visit_ImportFrom(self, node: ImportFrom) -> Any","id":5938,"name":"visit_ImportFrom","nodeType":"Function","startLoc":68,"text":"def visit_ImportFrom(self, node: ImportFrom) -> Any: ..."},{"col":4,"comment":"null","endLoc":69,"header":"def visit_Global(self, node: Global) -> Any","id":5939,"name":"visit_Global","nodeType":"Function","startLoc":69,"text":"def visit_Global(self, node: Global) -> Any: ..."},{"col":4,"comment":"null","endLoc":70,"header":"def visit_Nonlocal(self, node: Nonlocal) -> Any","id":5940,"name":"visit_Nonlocal","nodeType":"Function","startLoc":70,"text":"def visit_Nonlocal(self, node: Nonlocal) -> Any: ..."},{"col":4,"comment":"null","endLoc":71,"header":"def visit_Expr(self, node: Expr) -> Any","id":5941,"name":"visit_Expr","nodeType":"Function","startLoc":71,"text":"def visit_Expr(self, node: Expr) -> Any: ..."},{"col":4,"comment":"null","endLoc":72,"header":"def visit_Pass(self, node: Pass) -> Any","id":5942,"name":"visit_Pass","nodeType":"Function","startLoc":72,"text":"def visit_Pass(self, node: Pass) -> Any: ..."},{"col":4,"comment":"null","endLoc":73,"header":"def visit_Break(self, node: Break) -> Any","id":5943,"name":"visit_Break","nodeType":"Function","startLoc":73,"text":"def visit_Break(self, node: Break) -> Any: ..."},{"col":4,"comment":"null","endLoc":74,"header":"def visit_Continue(self, node: Continue) -> Any","id":5944,"name":"visit_Continue","nodeType":"Function","startLoc":74,"text":"def visit_Continue(self, node: Continue) -> Any: ..."},{"col":4,"comment":"null","endLoc":75,"header":"def visit_Slice(self, node: Slice) -> Any","id":5945,"name":"visit_Slice","nodeType":"Function","startLoc":75,"text":"def visit_Slice(self, node: Slice) -> Any: ..."},{"col":4,"comment":"null","endLoc":76,"header":"def visit_BoolOp(self, node: BoolOp) -> Any","id":5946,"name":"visit_BoolOp","nodeType":"Function","startLoc":76,"text":"def visit_BoolOp(self, node: BoolOp) -> Any: ..."},{"col":4,"comment":"null","endLoc":77,"header":"def visit_BinOp(self, node: BinOp) -> Any","id":5947,"name":"visit_BinOp","nodeType":"Function","startLoc":77,"text":"def visit_BinOp(self, node: BinOp) -> Any: ..."},{"col":4,"comment":"null","endLoc":78,"header":"def visit_UnaryOp(self, node: UnaryOp) -> Any","id":5948,"name":"visit_UnaryOp","nodeType":"Function","startLoc":78,"text":"def visit_UnaryOp(self, node: UnaryOp) -> Any: ..."},{"col":4,"comment":"null","endLoc":79,"header":"def visit_Lambda(self, node: Lambda) -> Any","id":5949,"name":"visit_Lambda","nodeType":"Function","startLoc":79,"text":"def visit_Lambda(self, node: Lambda) -> Any: ..."},{"col":4,"comment":"null","endLoc":80,"header":"def visit_IfExp(self, node: IfExp) -> Any","id":5950,"name":"visit_IfExp","nodeType":"Function","startLoc":80,"text":"def visit_IfExp(self, node: IfExp) -> Any: ..."},{"col":4,"comment":"null","endLoc":81,"header":"def visit_Dict(self, node: Dict) -> Any","id":5951,"name":"visit_Dict","nodeType":"Function","startLoc":81,"text":"def visit_Dict(self, node: Dict) -> Any: ..."},{"col":4,"comment":"null","endLoc":82,"header":"def visit_Set(self, node: Set) -> Any","id":5952,"name":"visit_Set","nodeType":"Function","startLoc":82,"text":"def visit_Set(self, node: Set) -> Any: ..."},{"col":4,"comment":"null","endLoc":83,"header":"def visit_ListComp(self, node: ListComp) -> Any","id":5953,"name":"visit_ListComp","nodeType":"Function","startLoc":83,"text":"def visit_ListComp(self, node: ListComp) -> Any: ..."},{"col":4,"comment":"null","endLoc":84,"header":"def visit_SetComp(self, node: SetComp) -> Any","id":5954,"name":"visit_SetComp","nodeType":"Function","startLoc":84,"text":"def visit_SetComp(self, node: SetComp) -> Any: ..."},{"col":4,"comment":"null","endLoc":85,"header":"def visit_DictComp(self, node: DictComp) -> Any","id":5955,"name":"visit_DictComp","nodeType":"Function","startLoc":85,"text":"def visit_DictComp(self, node: DictComp) -> Any: ..."},{"col":4,"comment":"null","endLoc":86,"header":"def visit_GeneratorExp(self, node: GeneratorExp) -> Any","id":5956,"name":"visit_GeneratorExp","nodeType":"Function","startLoc":86,"text":"def visit_GeneratorExp(self, node: GeneratorExp) -> Any: ..."},{"col":4,"comment":"null","endLoc":87,"header":"def visit_Await(self, node: Await) -> Any","id":5957,"name":"visit_Await","nodeType":"Function","startLoc":87,"text":"def visit_Await(self, node: Await) -> Any: ..."},{"col":4,"comment":"null","endLoc":88,"header":"def visit_Yield(self, node: Yield) -> Any","id":5958,"name":"visit_Yield","nodeType":"Function","startLoc":88,"text":"def visit_Yield(self, node: Yield) -> Any: ..."},{"col":4,"comment":"null","endLoc":89,"header":"def visit_YieldFrom(self, node: YieldFrom) -> Any","id":5959,"name":"visit_YieldFrom","nodeType":"Function","startLoc":89,"text":"def visit_YieldFrom(self, node: YieldFrom) -> Any: ..."},{"col":4,"comment":"null","endLoc":90,"header":"def visit_Compare(self, node: Compare) -> Any","id":5960,"name":"visit_Compare","nodeType":"Function","startLoc":90,"text":"def visit_Compare(self, node: Compare) -> Any: ..."},{"col":4,"comment":"null","endLoc":91,"header":"def visit_Call(self, node: Call) -> Any","id":5961,"name":"visit_Call","nodeType":"Function","startLoc":91,"text":"def visit_Call(self, node: Call) -> Any: ..."},{"col":4,"comment":"null","endLoc":92,"header":"def visit_FormattedValue(self, node: FormattedValue) -> Any","id":5962,"name":"visit_FormattedValue","nodeType":"Function","startLoc":92,"text":"def visit_FormattedValue(self, node: FormattedValue) -> Any: ..."},{"col":4,"comment":"null","endLoc":93,"header":"def visit_JoinedStr(self, node: JoinedStr) -> Any","id":5963,"name":"visit_JoinedStr","nodeType":"Function","startLoc":93,"text":"def visit_JoinedStr(self, node: JoinedStr) -> Any: ..."},{"col":4,"comment":"null","endLoc":94,"header":"def visit_Constant(self, node: Constant) -> Any","id":5964,"name":"visit_Constant","nodeType":"Function","startLoc":94,"text":"def visit_Constant(self, node: Constant) -> Any: ..."},{"col":4,"comment":"null","endLoc":95,"header":"def visit_NamedExpr(self, node: NamedExpr) -> Any","id":5965,"name":"visit_NamedExpr","nodeType":"Function","startLoc":95,"text":"def visit_NamedExpr(self, node: NamedExpr) -> Any: ..."},{"col":4,"comment":"null","endLoc":96,"header":"def visit_TypeIgnore(self, node: TypeIgnore) -> Any","id":5966,"name":"visit_TypeIgnore","nodeType":"Function","startLoc":96,"text":"def visit_TypeIgnore(self, node: TypeIgnore) -> Any: ..."},{"col":4,"comment":"null","endLoc":97,"header":"def visit_Attribute(self, node: Attribute) -> Any","id":5967,"name":"visit_Attribute","nodeType":"Function","startLoc":97,"text":"def visit_Attribute(self, node: Attribute) -> Any: ..."},{"col":4,"comment":"null","endLoc":98,"header":"def visit_Subscript(self, node: Subscript) -> Any","id":5968,"name":"visit_Subscript","nodeType":"Function","startLoc":98,"text":"def visit_Subscript(self, node: Subscript) -> Any: ..."},{"col":4,"comment":"null","endLoc":99,"header":"def visit_Starred(self, node: Starred) -> Any","id":5969,"name":"visit_Starred","nodeType":"Function","startLoc":99,"text":"def visit_Starred(self, node: Starred) -> Any: ..."},{"col":4,"comment":"null","endLoc":100,"header":"def visit_Name(self, node: Name) -> Any","id":5970,"name":"visit_Name","nodeType":"Function","startLoc":100,"text":"def visit_Name(self, node: Name) -> Any: ..."},{"col":4,"comment":"null","endLoc":101,"header":"def visit_List(self, node: List) -> Any","id":5971,"name":"visit_List","nodeType":"Function","startLoc":101,"text":"def visit_List(self, node: List) -> Any: ..."},{"col":4,"comment":"null","endLoc":102,"header":"def visit_Tuple(self, node: Tuple) -> Any","id":5972,"name":"visit_Tuple","nodeType":"Function","startLoc":102,"text":"def visit_Tuple(self, node: Tuple) -> Any: ..."},{"col":4,"comment":"null","endLoc":103,"header":"def visit_Del(self, node: Del) -> Any","id":5973,"name":"visit_Del","nodeType":"Function","startLoc":103,"text":"def visit_Del(self, node: Del) -> Any: ..."},{"col":4,"comment":"null","endLoc":104,"header":"def visit_Load(self, node: Load) -> Any","id":5974,"name":"visit_Load","nodeType":"Function","startLoc":104,"text":"def visit_Load(self, node: Load) -> Any: ..."},{"col":4,"comment":"null","endLoc":105,"header":"def visit_Store(self, node: Store) -> Any","id":5975,"name":"visit_Store","nodeType":"Function","startLoc":105,"text":"def visit_Store(self, node: Store) -> Any: ..."},{"col":4,"comment":"null","endLoc":106,"header":"def visit_And(self, node: And) -> Any","id":5976,"name":"visit_And","nodeType":"Function","startLoc":106,"text":"def visit_And(self, node: And) -> Any: ..."},{"col":4,"comment":"null","endLoc":107,"header":"def visit_Or(self, node: Or) -> Any","id":5977,"name":"visit_Or","nodeType":"Function","startLoc":107,"text":"def visit_Or(self, node: Or) -> Any: ..."},{"col":4,"comment":"null","endLoc":108,"header":"def visit_Add(self, node: Add) -> Any","id":5978,"name":"visit_Add","nodeType":"Function","startLoc":108,"text":"def visit_Add(self, node: Add) -> Any: ..."},{"col":4,"comment":"null","endLoc":109,"header":"def visit_BitAnd(self, node: BitAnd) -> Any","id":5979,"name":"visit_BitAnd","nodeType":"Function","startLoc":109,"text":"def visit_BitAnd(self, node: BitAnd) -> Any: ..."},{"col":4,"comment":"null","endLoc":110,"header":"def visit_BitOr(self, node: BitOr) -> Any","id":5980,"name":"visit_BitOr","nodeType":"Function","startLoc":110,"text":"def visit_BitOr(self, node: BitOr) -> Any: ..."},{"col":4,"comment":"null","endLoc":111,"header":"def visit_BitXor(self, node: BitXor) -> Any","id":5981,"name":"visit_BitXor","nodeType":"Function","startLoc":111,"text":"def visit_BitXor(self, node: BitXor) -> Any: ..."},{"col":4,"comment":"null","endLoc":112,"header":"def visit_Div(self, node: Div) -> Any","id":5982,"name":"visit_Div","nodeType":"Function","startLoc":112,"text":"def visit_Div(self, node: Div) -> Any: ..."},{"col":4,"comment":"null","endLoc":113,"header":"def visit_FloorDiv(self, node: FloorDiv) -> Any","id":5983,"name":"visit_FloorDiv","nodeType":"Function","startLoc":113,"text":"def visit_FloorDiv(self, node: FloorDiv) -> Any: ..."},{"col":4,"comment":"null","endLoc":114,"header":"def visit_LShift(self, node: LShift) -> Any","id":5984,"name":"visit_LShift","nodeType":"Function","startLoc":114,"text":"def visit_LShift(self, node: LShift) -> Any: ..."},{"col":4,"comment":"null","endLoc":115,"header":"def visit_Mod(self, node: Mod) -> Any","id":5985,"name":"visit_Mod","nodeType":"Function","startLoc":115,"text":"def visit_Mod(self, node: Mod) -> Any: ..."},{"col":4,"comment":"null","endLoc":116,"header":"def visit_Mult(self, node: Mult) -> Any","id":5986,"name":"visit_Mult","nodeType":"Function","startLoc":116,"text":"def visit_Mult(self, node: Mult) -> Any: ..."},{"col":4,"comment":"null","endLoc":117,"header":"def visit_MatMult(self, node: MatMult) -> Any","id":5987,"name":"visit_MatMult","nodeType":"Function","startLoc":117,"text":"def visit_MatMult(self, node: MatMult) -> Any: ..."},{"col":4,"comment":"null","endLoc":118,"header":"def visit_Pow(self, node: Pow) -> Any","id":5988,"name":"visit_Pow","nodeType":"Function","startLoc":118,"text":"def visit_Pow(self, node: Pow) -> Any: ..."},{"col":4,"comment":"null","endLoc":119,"header":"def visit_RShift(self, node: RShift) -> Any","id":5989,"name":"visit_RShift","nodeType":"Function","startLoc":119,"text":"def visit_RShift(self, node: RShift) -> Any: ..."},{"col":4,"comment":"null","endLoc":120,"header":"def visit_Sub(self, node: Sub) -> Any","id":5990,"name":"visit_Sub","nodeType":"Function","startLoc":120,"text":"def visit_Sub(self, node: Sub) -> Any: ..."},{"col":4,"comment":"null","endLoc":121,"header":"def visit_Invert(self, node: Invert) -> Any","id":5991,"name":"visit_Invert","nodeType":"Function","startLoc":121,"text":"def visit_Invert(self, node: Invert) -> Any: ..."},{"col":4,"comment":"null","endLoc":122,"header":"def visit_Not(self, node: Not) -> Any","id":5992,"name":"visit_Not","nodeType":"Function","startLoc":122,"text":"def visit_Not(self, node: Not) -> Any: ..."},{"col":4,"comment":"null","endLoc":123,"header":"def visit_UAdd(self, node: UAdd) -> Any","id":5993,"name":"visit_UAdd","nodeType":"Function","startLoc":123,"text":"def visit_UAdd(self, node: UAdd) -> Any: ..."},{"col":4,"comment":"null","endLoc":124,"header":"def visit_USub(self, node: USub) -> Any","id":5994,"name":"visit_USub","nodeType":"Function","startLoc":124,"text":"def visit_USub(self, node: USub) -> Any: ..."},{"col":4,"comment":"null","endLoc":125,"header":"def visit_Eq(self, node: Eq) -> Any","id":5995,"name":"visit_Eq","nodeType":"Function","startLoc":125,"text":"def visit_Eq(self, node: Eq) -> Any: ..."},{"col":4,"comment":"null","endLoc":126,"header":"def visit_Gt(self, node: Gt) -> Any","id":5996,"name":"visit_Gt","nodeType":"Function","startLoc":126,"text":"def visit_Gt(self, node: Gt) -> Any: ..."},{"col":4,"comment":"null","endLoc":127,"header":"def visit_GtE(self, node: GtE) -> Any","id":5997,"name":"visit_GtE","nodeType":"Function","startLoc":127,"text":"def visit_GtE(self, node: GtE) -> Any: ..."},{"col":4,"comment":"null","endLoc":128,"header":"def visit_In(self, node: In) -> Any","id":5998,"name":"visit_In","nodeType":"Function","startLoc":128,"text":"def visit_In(self, node: In) -> Any: ..."},{"col":4,"comment":"null","endLoc":129,"header":"def visit_Is(self, node: Is) -> Any","id":5999,"name":"visit_Is","nodeType":"Function","startLoc":129,"text":"def visit_Is(self, node: Is) -> Any: ..."},{"col":4,"comment":"null","endLoc":130,"header":"def visit_IsNot(self, node: IsNot) -> Any","id":6000,"name":"visit_IsNot","nodeType":"Function","startLoc":130,"text":"def visit_IsNot(self, node: IsNot) -> Any: ..."},{"col":4,"comment":"null","endLoc":131,"header":"def visit_Lt(self, node: Lt) -> Any","id":6001,"name":"visit_Lt","nodeType":"Function","startLoc":131,"text":"def visit_Lt(self, node: Lt) -> Any: ..."},{"col":4,"comment":"null","endLoc":132,"header":"def visit_LtE(self, node: LtE) -> Any","id":6002,"name":"visit_LtE","nodeType":"Function","startLoc":132,"text":"def visit_LtE(self, node: LtE) -> Any: ..."},{"col":4,"comment":"null","endLoc":133,"header":"def visit_NotEq(self, node: NotEq) -> Any","id":6003,"name":"visit_NotEq","nodeType":"Function","startLoc":133,"text":"def visit_NotEq(self, node: NotEq) -> Any: ..."},{"col":4,"comment":"null","endLoc":134,"header":"def visit_NotIn(self, node: NotIn) -> Any","id":6004,"name":"visit_NotIn","nodeType":"Function","startLoc":134,"text":"def visit_NotIn(self, node: NotIn) -> Any: ..."},{"col":4,"comment":"null","endLoc":135,"header":"def visit_comprehension(self, node: comprehension) -> Any","id":6005,"name":"visit_comprehension","nodeType":"Function","startLoc":135,"text":"def visit_comprehension(self, node: comprehension) -> Any: ..."},{"col":4,"comment":"null","endLoc":136,"header":"def visit_ExceptHandler(self, node: ExceptHandler) -> Any","id":6006,"name":"visit_ExceptHandler","nodeType":"Function","startLoc":136,"text":"def visit_ExceptHandler(self, node: ExceptHandler) -> Any: ..."},{"col":4,"comment":"null","endLoc":137,"header":"def visit_arguments(self, node: arguments) -> Any","id":6007,"name":"visit_arguments","nodeType":"Function","startLoc":137,"text":"def visit_arguments(self, node: arguments) -> Any: ..."},{"col":4,"comment":"null","endLoc":138,"header":"def visit_arg(self, node: arg) -> Any","id":6008,"name":"visit_arg","nodeType":"Function","startLoc":138,"text":"def visit_arg(self, node: arg) -> Any: ..."},{"col":4,"comment":"null","endLoc":139,"header":"def visit_keyword(self, node: keyword) -> Any","id":6009,"name":"visit_keyword","nodeType":"Function","startLoc":139,"text":"def visit_keyword(self, node: keyword) -> Any: ..."},{"col":4,"comment":"null","endLoc":140,"header":"def visit_alias(self, node: alias) -> Any","id":6010,"name":"visit_alias","nodeType":"Function","startLoc":140,"text":"def visit_alias(self, node: alias) -> Any: ..."},{"col":4,"comment":"null","endLoc":141,"header":"def visit_withitem(self, node: withitem) -> Any","id":6011,"name":"visit_withitem","nodeType":"Function","startLoc":141,"text":"def visit_withitem(self, node: withitem) -> Any: ..."},{"col":4,"comment":"null","endLoc":164,"header":"def visit_ExtSlice(self, node: ExtSlice) -> Any","id":6012,"name":"visit_ExtSlice","nodeType":"Function","startLoc":164,"text":"def visit_ExtSlice(self, node: ExtSlice) -> Any: ..."},{"col":4,"comment":"null","endLoc":165,"header":"def visit_Index(self, node: Index) -> Any","id":6013,"name":"visit_Index","nodeType":"Function","startLoc":165,"text":"def visit_Index(self, node: Index) -> Any: ..."},{"col":4,"comment":"null","endLoc":166,"header":"def visit_Suite(self, node: Suite) -> Any","id":6014,"name":"visit_Suite","nodeType":"Function","startLoc":166,"text":"def visit_Suite(self, node: Suite) -> Any: ..."},{"col":4,"comment":"null","endLoc":167,"header":"def visit_AugLoad(self, node: AugLoad) -> Any","id":6015,"name":"visit_AugLoad","nodeType":"Function","startLoc":167,"text":"def visit_AugLoad(self, node: AugLoad) -> Any: ..."},{"col":4,"comment":"null","endLoc":168,"header":"def visit_AugStore(self, node: AugStore) -> Any","id":6016,"name":"visit_AugStore","nodeType":"Function","startLoc":168,"text":"def visit_AugStore(self, node: AugStore) -> Any: ..."},{"col":4,"comment":"null","endLoc":169,"header":"def visit_Param(self, node: Param) -> Any","id":6017,"name":"visit_Param","nodeType":"Function","startLoc":169,"text":"def visit_Param(self, node: Param) -> Any: ..."},{"col":4,"comment":"null","endLoc":170,"header":"def visit_Num(self, node: Num) -> Any","id":6018,"name":"visit_Num","nodeType":"Function","startLoc":170,"text":"def visit_Num(self, node: Num) -> Any: ..."},{"col":4,"comment":"null","endLoc":171,"header":"def visit_Str(self, node: Str) -> Any","id":6019,"name":"visit_Str","nodeType":"Function","startLoc":171,"text":"def visit_Str(self, node: Str) -> Any: ..."},{"col":4,"comment":"null","endLoc":172,"header":"def visit_Bytes(self, node: Bytes) -> Any","id":6020,"name":"visit_Bytes","nodeType":"Function","startLoc":172,"text":"def visit_Bytes(self, node: Bytes) -> Any: ..."},{"col":4,"comment":"null","endLoc":173,"header":"def visit_NameConstant(self, node: NameConstant) -> Any","id":6021,"name":"visit_NameConstant","nodeType":"Function","startLoc":173,"text":"def visit_NameConstant(self, node: NameConstant) -> Any: ..."},{"col":4,"comment":"null","endLoc":174,"header":"def visit_Ellipsis(self, node: Ellipsis) -> Any","id":6022,"name":"visit_Ellipsis","nodeType":"Function","startLoc":174,"text":"def visit_Ellipsis(self, node: Ellipsis) -> Any: ..."},{"col":4,"comment":"Get a new variable.","endLoc":724,"header":"def variable(self)","id":6023,"name":"variable","nodeType":"Function","startLoc":719,"text":"def variable(self):\n \"\"\"Get a new variable.\"\"\"\n # Use a character invalid in python identifiers to avoid clashing.\n name = \"@py_assert\" + str(next(self.variable_counter))\n self.variables.append(name)\n return name"},{"col":4,"comment":"null","endLoc":422,"header":"@pytest.mark.parametrize(\n \"expected, actual, matchline\",\n [\n (\"TypeError\", \"TypeError\", \"*1 xfailed*\"),\n (\"(AttributeError, TypeError)\", \"TypeError\", \"*1 xfailed*\"),\n (\"TypeError\", \"IndexError\", \"*1 failed*\"),\n (\"(AttributeError, TypeError)\", \"IndexError\", \"*1 failed*\"),\n ],\n )\n def test_xfail_raises(self, expected, actual, matchline, testdir)","id":6024,"name":"test_xfail_raises","nodeType":"Function","startLoc":402,"text":"@pytest.mark.parametrize(\n \"expected, actual, matchline\",\n [\n (\"TypeError\", \"TypeError\", \"*1 xfailed*\"),\n (\"(AttributeError, TypeError)\", \"TypeError\", \"*1 xfailed*\"),\n (\"TypeError\", \"IndexError\", \"*1 failed*\"),\n (\"(AttributeError, TypeError)\", \"IndexError\", \"*1 failed*\"),\n ],\n )\n def test_xfail_raises(self, expected, actual, matchline, testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(raises=%s)\n def test_raises():\n raise %s()\n \"\"\"\n % (expected, actual)\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([matchline])"},{"col":4,"comment":"Ensure that the capturing of teardown logs honor --show-capture setting","endLoc":1131,"header":"def test_show_capture_with_teardown_logs(self, testdir)","id":6025,"name":"test_show_capture_with_teardown_logs","nodeType":"Function","startLoc":1093,"text":"def test_show_capture_with_teardown_logs(self, testdir):\n \"\"\"Ensure that the capturing of teardown logs honor --show-capture setting\"\"\"\n testdir.makepyfile(\n \"\"\"\n import logging\n import sys\n import pytest\n\n @pytest.fixture(scope=\"function\", autouse=\"True\")\n def hook_each_test(request):\n yield\n sys.stdout.write(\"!stdout!\")\n sys.stderr.write(\"!stderr!\")\n logging.warning(\"!log!\")\n\n def test_func():\n assert False\n \"\"\"\n )\n\n result = testdir.runpytest(\"--show-capture=stdout\", \"--tb=short\").stdout.str()\n assert \"!stdout!\" in result\n assert \"!stderr!\" not in result\n assert \"!log!\" not in result\n\n result = testdir.runpytest(\"--show-capture=stderr\", \"--tb=short\").stdout.str()\n assert \"!stdout!\" not in result\n assert \"!stderr!\" in result\n assert \"!log!\" not in result\n\n result = testdir.runpytest(\"--show-capture=log\", \"--tb=short\").stdout.str()\n assert \"!stdout!\" not in result\n assert \"!stderr!\" not in result\n assert \"!log!\" in result\n\n result = testdir.runpytest(\"--show-capture=no\", \"--tb=short\").stdout.str()\n assert \"!stdout!\" not in result\n assert \"!stderr!\" not in result\n assert \"!log!\" not in result"},{"className":"TestClassicOutputStyle","col":0,"comment":"Ensure classic output style works as expected (#3883)","endLoc":1371,"id":6026,"nodeType":"Class","startLoc":1328,"text":"class TestClassicOutputStyle(object):\n \"\"\"Ensure classic output style works as expected (#3883)\"\"\"\n\n @pytest.fixture\n def test_files(self, testdir):\n testdir.makepyfile(\n **{\n \"test_one.py\": \"def test_one(): pass\",\n \"test_two.py\": \"def test_two(): assert 0\",\n \"sub/test_three.py\": \"\"\"\n def test_three_1(): pass\n def test_three_2(): assert 0\n def test_three_3(): pass\n \"\"\",\n }\n )\n\n def test_normal_verbosity(self, testdir, test_files):\n result = testdir.runpytest(\"-o\", \"console_output_style=classic\")\n result.stdout.fnmatch_lines(\n [\n \"test_one.py .\",\n \"test_two.py F\",\n \"sub{}test_three.py .F.\".format(os.sep),\n \"*2 failed, 3 passed in*\",\n ]\n )\n\n def test_verbose(self, testdir, test_files):\n result = testdir.runpytest(\"-o\", \"console_output_style=classic\", \"-v\")\n result.stdout.fnmatch_lines(\n [\n \"test_one.py::test_one PASSED\",\n \"test_two.py::test_two FAILED\",\n \"sub{}test_three.py::test_three_1 PASSED\".format(os.sep),\n \"sub{}test_three.py::test_three_2 FAILED\".format(os.sep),\n \"sub{}test_three.py::test_three_3 PASSED\".format(os.sep),\n \"*2 failed, 3 passed in*\",\n ]\n )\n\n def test_quiet(self, testdir, test_files):\n result = testdir.runpytest(\"-o\", \"console_output_style=classic\", \"-q\")\n result.stdout.fnmatch_lines([\".F.F.\", \"*2 failed, 3 passed in*\"])"},{"col":4,"comment":"null","endLoc":1343,"header":"@pytest.fixture\n def test_files(self, testdir)","id":6027,"name":"test_files","nodeType":"Function","startLoc":1331,"text":"@pytest.fixture\n def test_files(self, testdir):\n testdir.makepyfile(\n **{\n \"test_one.py\": \"def test_one(): pass\",\n \"test_two.py\": \"def test_two(): assert 0\",\n \"sub/test_three.py\": \"\"\"\n def test_three_1(): pass\n def test_three_2(): assert 0\n def test_three_3(): pass\n \"\"\",\n }\n )"},{"col":4,"comment":"null","endLoc":1354,"header":"def test_normal_verbosity(self, testdir, test_files)","id":6028,"name":"test_normal_verbosity","nodeType":"Function","startLoc":1345,"text":"def test_normal_verbosity(self, testdir, test_files):\n result = testdir.runpytest(\"-o\", \"console_output_style=classic\")\n result.stdout.fnmatch_lines(\n [\n \"test_one.py .\",\n \"test_two.py F\",\n \"sub{}test_three.py .F.\".format(os.sep),\n \"*2 failed, 3 passed in*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":210,"header":"def test_deprecated_call_supports_match(self)","id":6030,"name":"test_deprecated_call_supports_match","nodeType":"Function","startLoc":204,"text":"def test_deprecated_call_supports_match(self):\n with pytest.deprecated_call(match=r\"must be \\d+$\"):\n warnings.warn(\"value must be 42\", DeprecationWarning)\n\n with pytest.raises(pytest.fail.Exception):\n with pytest.deprecated_call(match=r\"must be \\d+$\"):\n warnings.warn(\"this is not here\", DeprecationWarning)"},{"col":4,"comment":"sanity check for xfail(strict=True): a failing test should behave\n exactly like a normal xfail.\n ","endLoc":438,"header":"def test_strict_sanity(self, testdir)","id":6031,"name":"test_strict_sanity","nodeType":"Function","startLoc":424,"text":"def test_strict_sanity(self, testdir):\n \"\"\"sanity check for xfail(strict=True): a failing test should behave\n exactly like a normal xfail.\n \"\"\"\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(reason='unsupported feature', strict=True)\n def test_foo():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rxX\")\n result.stdout.fnmatch_lines([\"*XFAIL*\", \"*unsupported feature*\"])\n assert result.ret == 0"},{"className":"TestWarns","col":0,"comment":"null","endLoc":387,"id":6032,"nodeType":"Class","startLoc":213,"text":"class TestWarns(object):\n def test_strings(self):\n # different messages, b/c Python suppresses multiple identical warnings\n source1 = \"warnings.warn('w1', RuntimeWarning)\"\n source2 = \"warnings.warn('w2', RuntimeWarning)\"\n source3 = \"warnings.warn('w3', RuntimeWarning)\"\n with pytest.warns(PytestDeprecationWarning) as warninfo: # yo dawg\n pytest.warns(RuntimeWarning, source1)\n pytest.raises(\n pytest.fail.Exception, lambda: pytest.warns(UserWarning, source2)\n )\n pytest.warns(RuntimeWarning, source3)\n assert len(warninfo) == 3\n for w in warninfo:\n assert w.filename == __file__\n msg, = w.message.args\n assert msg.startswith(\"warns(..., 'code(as_a_string)') is deprecated\")\n\n def test_function(self):\n pytest.warns(\n SyntaxWarning, lambda msg: warnings.warn(msg, SyntaxWarning), \"syntax\"\n )\n\n def test_warning_tuple(self):\n pytest.warns(\n (RuntimeWarning, SyntaxWarning), lambda: warnings.warn(\"w1\", RuntimeWarning)\n )\n pytest.warns(\n (RuntimeWarning, SyntaxWarning), lambda: warnings.warn(\"w2\", SyntaxWarning)\n )\n pytest.raises(\n pytest.fail.Exception,\n lambda: pytest.warns(\n (RuntimeWarning, SyntaxWarning),\n lambda: warnings.warn(\"w3\", UserWarning),\n ),\n )\n\n def test_as_contextmanager(self):\n with pytest.warns(RuntimeWarning):\n warnings.warn(\"runtime\", RuntimeWarning)\n\n with pytest.warns(UserWarning):\n warnings.warn(\"user\", UserWarning)\n\n with pytest.raises(pytest.fail.Exception) as excinfo:\n with pytest.warns(RuntimeWarning):\n warnings.warn(\"user\", UserWarning)\n excinfo.match(\n r\"DID NOT WARN. No warnings of type \\(.+RuntimeWarning.+,\\) was emitted. \"\n r\"The list of emitted warnings is: \\[UserWarning\\('user',?\\)\\].\"\n )\n\n with pytest.raises(pytest.fail.Exception) as excinfo:\n with pytest.warns(UserWarning):\n warnings.warn(\"runtime\", RuntimeWarning)\n excinfo.match(\n r\"DID NOT WARN. No warnings of type \\(.+UserWarning.+,\\) was emitted. \"\n r\"The list of emitted warnings is: \\[RuntimeWarning\\('runtime',?\\)\\].\"\n )\n\n with pytest.raises(pytest.fail.Exception) as excinfo:\n with pytest.warns(UserWarning):\n pass\n excinfo.match(\n r\"DID NOT WARN. No warnings of type \\(.+UserWarning.+,\\) was emitted. \"\n r\"The list of emitted warnings is: \\[\\].\"\n )\n\n warning_classes = (UserWarning, FutureWarning)\n with pytest.raises(pytest.fail.Exception) as excinfo:\n with pytest.warns(warning_classes) as warninfo:\n warnings.warn(\"runtime\", RuntimeWarning)\n warnings.warn(\"import\", ImportWarning)\n\n message_template = (\n \"DID NOT WARN. No warnings of type {0} was emitted. \"\n \"The list of emitted warnings is: {1}.\"\n )\n excinfo.match(\n re.escape(\n message_template.format(\n warning_classes, [each.message for each in warninfo]\n )\n )\n )\n\n def test_record(self):\n with pytest.warns(UserWarning) as record:\n warnings.warn(\"user\", UserWarning)\n\n assert len(record) == 1\n assert str(record[0].message) == \"user\"\n\n def test_record_only(self):\n with pytest.warns(None) as record:\n warnings.warn(\"user\", UserWarning)\n warnings.warn(\"runtime\", RuntimeWarning)\n\n assert len(record) == 2\n assert str(record[0].message) == \"user\"\n assert str(record[1].message) == \"runtime\"\n\n def test_record_by_subclass(self):\n with pytest.warns(Warning) as record:\n warnings.warn(\"user\", UserWarning)\n warnings.warn(\"runtime\", RuntimeWarning)\n\n assert len(record) == 2\n assert str(record[0].message) == \"user\"\n assert str(record[1].message) == \"runtime\"\n\n class MyUserWarning(UserWarning):\n pass\n\n class MyRuntimeWarning(RuntimeWarning):\n pass\n\n with pytest.warns((UserWarning, RuntimeWarning)) as record:\n warnings.warn(\"user\", MyUserWarning)\n warnings.warn(\"runtime\", MyRuntimeWarning)\n\n assert len(record) == 2\n assert str(record[0].message) == \"user\"\n assert str(record[1].message) == \"runtime\"\n\n def test_double_test(self, testdir):\n \"\"\"If a test is run again, the warning should still be raised\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n import warnings\n\n @pytest.mark.parametrize('run', [1, 2])\n def test(run):\n with pytest.warns(RuntimeWarning):\n warnings.warn(\"runtime\", RuntimeWarning)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 passed in*\"])\n\n def test_match_regex(self):\n with pytest.warns(UserWarning, match=r\"must be \\d+$\"):\n warnings.warn(\"value must be 42\", UserWarning)\n\n with pytest.raises(pytest.fail.Exception):\n with pytest.warns(UserWarning, match=r\"must be \\d+$\"):\n warnings.warn(\"this is not here\", UserWarning)\n\n with pytest.raises(pytest.fail.Exception):\n with pytest.warns(FutureWarning, match=r\"must be \\d+$\"):\n warnings.warn(\"value must be 42\", UserWarning)\n\n def test_one_from_multiple_warns(self):\n with pytest.warns(UserWarning, match=r\"aaa\"):\n warnings.warn(\"cccccccccc\", UserWarning)\n warnings.warn(\"bbbbbbbbbb\", UserWarning)\n warnings.warn(\"aaaaaaaaaa\", UserWarning)\n\n def test_none_of_multiple_warns(self):\n with pytest.raises(pytest.fail.Exception):\n with pytest.warns(UserWarning, match=r\"aaa\"):\n warnings.warn(\"bbbbbbbbbb\", UserWarning)\n warnings.warn(\"cccccccccc\", UserWarning)\n\n @pytest.mark.filterwarnings(\"ignore\")\n def test_can_capture_previously_warned(self):\n def f():\n warnings.warn(UserWarning(\"ohai\"))\n return 10\n\n assert f() == 10\n assert pytest.warns(UserWarning, f) == 10\n assert pytest.warns(UserWarning, f) == 10"},{"col":4,"comment":"null","endLoc":229,"header":"def test_strings(self)","id":6033,"name":"test_strings","nodeType":"Function","startLoc":214,"text":"def test_strings(self):\n # different messages, b/c Python suppresses multiple identical warnings\n source1 = \"warnings.warn('w1', RuntimeWarning)\"\n source2 = \"warnings.warn('w2', RuntimeWarning)\"\n source3 = \"warnings.warn('w3', RuntimeWarning)\"\n with pytest.warns(PytestDeprecationWarning) as warninfo: # yo dawg\n pytest.warns(RuntimeWarning, source1)\n pytest.raises(\n pytest.fail.Exception, lambda: pytest.warns(UserWarning, source2)\n )\n pytest.warns(RuntimeWarning, source3)\n assert len(warninfo) == 3\n for w in warninfo:\n assert w.filename == __file__\n msg, = w.message.args\n assert msg.startswith(\"warns(..., 'code(as_a_string)') is deprecated\")"},{"col":4,"comment":"null","endLoc":1367,"header":"def test_verbose(self, testdir, test_files)","id":6034,"name":"test_verbose","nodeType":"Function","startLoc":1356,"text":"def test_verbose(self, testdir, test_files):\n result = testdir.runpytest(\"-o\", \"console_output_style=classic\", \"-v\")\n result.stdout.fnmatch_lines(\n [\n \"test_one.py::test_one PASSED\",\n \"test_two.py::test_two FAILED\",\n \"sub{}test_three.py::test_three_1 PASSED\".format(os.sep),\n \"sub{}test_three.py::test_three_2 FAILED\".format(os.sep),\n \"sub{}test_three.py::test_three_3 PASSED\".format(os.sep),\n \"*2 failed, 3 passed in*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":465,"header":"@pytest.mark.parametrize(\"strict\", [True, False])\n def test_strict_xfail(self, testdir, strict)","id":6035,"name":"test_strict_xfail","nodeType":"Function","startLoc":440,"text":"@pytest.mark.parametrize(\"strict\", [True, False])\n def test_strict_xfail(self, testdir, strict):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.xfail(reason='unsupported feature', strict=%s)\n def test_foo():\n with open('foo_executed', 'w'): pass # make sure test executes\n \"\"\"\n % strict\n )\n result = testdir.runpytest(p, \"-rxX\")\n if strict:\n result.stdout.fnmatch_lines(\n [\"*test_foo*\", \"*XPASS(strict)*unsupported feature*\"]\n )\n else:\n result.stdout.fnmatch_lines(\n [\n \"*test_strict_xfail*\",\n \"XPASS test_strict_xfail.py::test_foo unsupported feature\",\n ]\n )\n assert result.ret == (1 if strict else 0)\n assert testdir.tmpdir.join(\"foo_executed\").isfile()"},{"col":4,"comment":"null","endLoc":1371,"header":"def test_quiet(self, testdir, test_files)","id":6036,"name":"test_quiet","nodeType":"Function","startLoc":1369,"text":"def test_quiet(self, testdir, test_files):\n result = testdir.runpytest(\"-o\", \"console_output_style=classic\", \"-q\")\n result.stdout.fnmatch_lines([\".F.F.\", \"*2 failed, 3 passed in*\"])"},{"col":39,"endLoc":222,"id":6037,"nodeType":"Lambda","startLoc":222,"text":"lambda: pytest.warns(UserWarning, source2)"},{"className":"TestProgressOutputStyle","col":0,"comment":"null","endLoc":1502,"id":6038,"nodeType":"Class","startLoc":1374,"text":"class TestProgressOutputStyle(object):\n @pytest.fixture\n def many_tests_files(self, testdir):\n testdir.makepyfile(\n test_bar=\"\"\"\n import pytest\n @pytest.mark.parametrize('i', range(10))\n def test_bar(i): pass\n \"\"\",\n test_foo=\"\"\"\n import pytest\n @pytest.mark.parametrize('i', range(5))\n def test_foo(i): pass\n \"\"\",\n test_foobar=\"\"\"\n import pytest\n @pytest.mark.parametrize('i', range(5))\n def test_foobar(i): pass\n \"\"\",\n )\n\n def test_zero_tests_collected(self, testdir):\n \"\"\"Some plugins (testmon for example) might issue pytest_runtest_logreport without any tests being\n actually collected (#2971).\"\"\"\n testdir.makeconftest(\n \"\"\"\n def pytest_collection_modifyitems(items, config):\n from _pytest.runner import CollectReport\n for node_id in ('nodeid1', 'nodeid2'):\n rep = CollectReport(node_id, 'passed', None, None)\n rep.when = 'passed'\n rep.duration = 0.1\n config.hook.pytest_runtest_logreport(report=rep)\n \"\"\"\n )\n output = testdir.runpytest()\n assert \"ZeroDivisionError\" not in output.stdout.str()\n output.stdout.fnmatch_lines([\"=* 2 passed in *=\"])\n\n def test_normal(self, many_tests_files, testdir):\n output = testdir.runpytest()\n output.stdout.re_match_lines(\n [\n r\"test_bar.py \\.{10} \\s+ \\[ 50%\\]\",\n r\"test_foo.py \\.{5} \\s+ \\[ 75%\\]\",\n r\"test_foobar.py \\.{5} \\s+ \\[100%\\]\",\n ]\n )\n\n def test_count(self, many_tests_files, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style = count\n \"\"\"\n )\n output = testdir.runpytest()\n output.stdout.re_match_lines(\n [\n r\"test_bar.py \\.{10} \\s+ \\[10/20\\]\",\n r\"test_foo.py \\.{5} \\s+ \\[15/20\\]\",\n r\"test_foobar.py \\.{5} \\s+ \\[20/20\\]\",\n ]\n )\n\n def test_verbose(self, many_tests_files, testdir):\n output = testdir.runpytest(\"-v\")\n output.stdout.re_match_lines(\n [\n r\"test_bar.py::test_bar\\[0\\] PASSED \\s+ \\[ 5%\\]\",\n r\"test_foo.py::test_foo\\[4\\] PASSED \\s+ \\[ 75%\\]\",\n r\"test_foobar.py::test_foobar\\[4\\] PASSED \\s+ \\[100%\\]\",\n ]\n )\n\n def test_verbose_count(self, many_tests_files, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style = count\n \"\"\"\n )\n output = testdir.runpytest(\"-v\")\n output.stdout.re_match_lines(\n [\n r\"test_bar.py::test_bar\\[0\\] PASSED \\s+ \\[ 1/20\\]\",\n r\"test_foo.py::test_foo\\[4\\] PASSED \\s+ \\[15/20\\]\",\n r\"test_foobar.py::test_foobar\\[4\\] PASSED \\s+ \\[20/20\\]\",\n ]\n )\n\n def test_xdist_normal(self, many_tests_files, testdir, monkeypatch):\n pytest.importorskip(\"xdist\")\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n output = testdir.runpytest(\"-n2\")\n output.stdout.re_match_lines([r\"\\.{20} \\s+ \\[100%\\]\"])\n\n def test_xdist_normal_count(self, many_tests_files, testdir, monkeypatch):\n pytest.importorskip(\"xdist\")\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style = count\n \"\"\"\n )\n output = testdir.runpytest(\"-n2\")\n output.stdout.re_match_lines([r\"\\.{20} \\s+ \\[20/20\\]\"])\n\n def test_xdist_verbose(self, many_tests_files, testdir, monkeypatch):\n pytest.importorskip(\"xdist\")\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n output = testdir.runpytest(\"-n2\", \"-v\")\n output.stdout.re_match_lines_random(\n [\n r\"\\[gw\\d\\] \\[\\s*\\d+%\\] PASSED test_bar.py::test_bar\\[1\\]\",\n r\"\\[gw\\d\\] \\[\\s*\\d+%\\] PASSED test_foo.py::test_foo\\[1\\]\",\n r\"\\[gw\\d\\] \\[\\s*\\d+%\\] PASSED test_foobar.py::test_foobar\\[1\\]\",\n ]\n )\n\n def test_capture_no(self, many_tests_files, testdir):\n output = testdir.runpytest(\"-s\")\n output.stdout.re_match_lines(\n [r\"test_bar.py \\.{10}\", r\"test_foo.py \\.{5}\", r\"test_foobar.py \\.{5}\"]\n )\n\n output = testdir.runpytest(\"--capture=no\")\n assert \"%]\" not in output.stdout.str()"},{"col":4,"comment":"null","endLoc":1393,"header":"@pytest.fixture\n def many_tests_files(self, testdir)","id":6039,"name":"many_tests_files","nodeType":"Function","startLoc":1375,"text":"@pytest.fixture\n def many_tests_files(self, testdir):\n testdir.makepyfile(\n test_bar=\"\"\"\n import pytest\n @pytest.mark.parametrize('i', range(10))\n def test_bar(i): pass\n \"\"\",\n test_foo=\"\"\"\n import pytest\n @pytest.mark.parametrize('i', range(5))\n def test_foo(i): pass\n \"\"\",\n test_foobar=\"\"\"\n import pytest\n @pytest.mark.parametrize('i', range(5))\n def test_foobar(i): pass\n \"\"\",\n )"},{"col":4,"comment":"Some plugins (testmon for example) might issue pytest_runtest_logreport without any tests being\n actually collected (#2971).","endLoc":1411,"header":"def test_zero_tests_collected(self, testdir)","id":6040,"name":"test_zero_tests_collected","nodeType":"Function","startLoc":1395,"text":"def test_zero_tests_collected(self, testdir):\n \"\"\"Some plugins (testmon for example) might issue pytest_runtest_logreport without any tests being\n actually collected (#2971).\"\"\"\n testdir.makeconftest(\n \"\"\"\n def pytest_collection_modifyitems(items, config):\n from _pytest.runner import CollectReport\n for node_id in ('nodeid1', 'nodeid2'):\n rep = CollectReport(node_id, 'passed', None, None)\n rep.when = 'passed'\n rep.duration = 0.1\n config.hook.pytest_runtest_logreport(report=rep)\n \"\"\"\n )\n output = testdir.runpytest()\n assert \"ZeroDivisionError\" not in output.stdout.str()\n output.stdout.fnmatch_lines([\"=* 2 passed in *=\"])"},{"col":4,"comment":"null","endLoc":1421,"header":"def test_normal(self, many_tests_files, testdir)","id":6041,"name":"test_normal","nodeType":"Function","startLoc":1413,"text":"def test_normal(self, many_tests_files, testdir):\n output = testdir.runpytest()\n output.stdout.re_match_lines(\n [\n r\"test_bar.py \\.{10} \\s+ \\[ 50%\\]\",\n r\"test_foo.py \\.{5} \\s+ \\[ 75%\\]\",\n r\"test_foobar.py \\.{5} \\s+ \\[100%\\]\",\n ]\n )"},{"col":4,"comment":"null","endLoc":1437,"header":"def test_count(self, many_tests_files, testdir)","id":6042,"name":"test_count","nodeType":"Function","startLoc":1423,"text":"def test_count(self, many_tests_files, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style = count\n \"\"\"\n )\n output = testdir.runpytest()\n output.stdout.re_match_lines(\n [\n r\"test_bar.py \\.{10} \\s+ \\[10/20\\]\",\n r\"test_foo.py \\.{5} \\s+ \\[15/20\\]\",\n r\"test_foobar.py \\.{5} \\s+ \\[20/20\\]\",\n ]\n )"},{"col":4,"comment":"null","endLoc":481,"header":"@pytest.mark.parametrize(\"strict\", [True, False])\n def test_strict_xfail_condition(self, testdir, strict)","id":6043,"name":"test_strict_xfail_condition","nodeType":"Function","startLoc":467,"text":"@pytest.mark.parametrize(\"strict\", [True, False])\n def test_strict_xfail_condition(self, testdir, strict):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.xfail(False, reason='unsupported feature', strict=%s)\n def test_foo():\n pass\n \"\"\"\n % strict\n )\n result = testdir.runpytest(p, \"-rxX\")\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n assert result.ret == 0"},{"col":4,"comment":"null","endLoc":1447,"header":"def test_verbose(self, many_tests_files, testdir)","id":6044,"name":"test_verbose","nodeType":"Function","startLoc":1439,"text":"def test_verbose(self, many_tests_files, testdir):\n output = testdir.runpytest(\"-v\")\n output.stdout.re_match_lines(\n [\n r\"test_bar.py::test_bar\\[0\\] PASSED \\s+ \\[ 5%\\]\",\n r\"test_foo.py::test_foo\\[4\\] PASSED \\s+ \\[ 75%\\]\",\n r\"test_foobar.py::test_foobar\\[4\\] PASSED \\s+ \\[100%\\]\",\n ]\n )"},{"col":4,"comment":"null","endLoc":234,"header":"def test_function(self)","id":6045,"name":"test_function","nodeType":"Function","startLoc":231,"text":"def test_function(self):\n pytest.warns(\n SyntaxWarning, lambda msg: warnings.warn(msg, SyntaxWarning), \"syntax\"\n )"},{"col":27,"endLoc":233,"id":6046,"nodeType":"Lambda","startLoc":233,"text":"lambda msg: warnings.warn(msg, SyntaxWarning)"},{"col":4,"comment":"null","endLoc":249,"header":"def test_warning_tuple(self)","id":6047,"name":"test_warning_tuple","nodeType":"Function","startLoc":236,"text":"def test_warning_tuple(self):\n pytest.warns(\n (RuntimeWarning, SyntaxWarning), lambda: warnings.warn(\"w1\", RuntimeWarning)\n )\n pytest.warns(\n (RuntimeWarning, SyntaxWarning), lambda: warnings.warn(\"w2\", SyntaxWarning)\n )\n pytest.raises(\n pytest.fail.Exception,\n lambda: pytest.warns(\n (RuntimeWarning, SyntaxWarning),\n lambda: warnings.warn(\"w3\", UserWarning),\n ),\n )"},{"col":4,"comment":"null","endLoc":1463,"header":"def test_verbose_count(self, many_tests_files, testdir)","id":6048,"name":"test_verbose_count","nodeType":"Function","startLoc":1449,"text":"def test_verbose_count(self, many_tests_files, testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style = count\n \"\"\"\n )\n output = testdir.runpytest(\"-v\")\n output.stdout.re_match_lines(\n [\n r\"test_bar.py::test_bar\\[0\\] PASSED \\s+ \\[ 1/20\\]\",\n r\"test_foo.py::test_foo\\[4\\] PASSED \\s+ \\[15/20\\]\",\n r\"test_foobar.py::test_foobar\\[4\\] PASSED \\s+ \\[20/20\\]\",\n ]\n )"},{"col":45,"endLoc":238,"id":6049,"nodeType":"Lambda","startLoc":238,"text":"lambda: warnings.warn(\"w1\", RuntimeWarning)"},{"col":4,"comment":"null","endLoc":1469,"header":"def test_xdist_normal(self, many_tests_files, testdir, monkeypatch)","id":6050,"name":"test_xdist_normal","nodeType":"Function","startLoc":1465,"text":"def test_xdist_normal(self, many_tests_files, testdir, monkeypatch):\n pytest.importorskip(\"xdist\")\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n output = testdir.runpytest(\"-n2\")\n output.stdout.re_match_lines([r\"\\.{20} \\s+ \\[100%\\]\"])"},{"col":45,"endLoc":241,"id":6051,"nodeType":"Lambda","startLoc":241,"text":"lambda: warnings.warn(\"w2\", SyntaxWarning)"},{"col":16,"endLoc":247,"id":6052,"nodeType":"Lambda","startLoc":247,"text":"lambda: warnings.warn(\"w3\", UserWarning)"},{"col":4,"comment":"null","endLoc":1481,"header":"def test_xdist_normal_count(self, many_tests_files, testdir, monkeypatch)","id":6053,"name":"test_xdist_normal_count","nodeType":"Function","startLoc":1471,"text":"def test_xdist_normal_count(self, many_tests_files, testdir, monkeypatch):\n pytest.importorskip(\"xdist\")\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n testdir.makeini(\n \"\"\"\n [pytest]\n console_output_style = count\n \"\"\"\n )\n output = testdir.runpytest(\"-n2\")\n output.stdout.re_match_lines([r\"\\.{20} \\s+ \\[20/20\\]\"])"},{"col":12,"endLoc":248,"id":6054,"nodeType":"Lambda","startLoc":245,"text":"lambda: pytest.warns(\n (RuntimeWarning, SyntaxWarning),\n lambda: warnings.warn(\"w3\", UserWarning),\n )"},{"col":4,"comment":"null","endLoc":298,"header":"def test_as_contextmanager(self)","id":6055,"name":"test_as_contextmanager","nodeType":"Function","startLoc":251,"text":"def test_as_contextmanager(self):\n with pytest.warns(RuntimeWarning):\n warnings.warn(\"runtime\", RuntimeWarning)\n\n with pytest.warns(UserWarning):\n warnings.warn(\"user\", UserWarning)\n\n with pytest.raises(pytest.fail.Exception) as excinfo:\n with pytest.warns(RuntimeWarning):\n warnings.warn(\"user\", UserWarning)\n excinfo.match(\n r\"DID NOT WARN. No warnings of type \\(.+RuntimeWarning.+,\\) was emitted. \"\n r\"The list of emitted warnings is: \\[UserWarning\\('user',?\\)\\].\"\n )\n\n with pytest.raises(pytest.fail.Exception) as excinfo:\n with pytest.warns(UserWarning):\n warnings.warn(\"runtime\", RuntimeWarning)\n excinfo.match(\n r\"DID NOT WARN. No warnings of type \\(.+UserWarning.+,\\) was emitted. \"\n r\"The list of emitted warnings is: \\[RuntimeWarning\\('runtime',?\\)\\].\"\n )\n\n with pytest.raises(pytest.fail.Exception) as excinfo:\n with pytest.warns(UserWarning):\n pass\n excinfo.match(\n r\"DID NOT WARN. No warnings of type \\(.+UserWarning.+,\\) was emitted. \"\n r\"The list of emitted warnings is: \\[\\].\"\n )\n\n warning_classes = (UserWarning, FutureWarning)\n with pytest.raises(pytest.fail.Exception) as excinfo:\n with pytest.warns(warning_classes) as warninfo:\n warnings.warn(\"runtime\", RuntimeWarning)\n warnings.warn(\"import\", ImportWarning)\n\n message_template = (\n \"DID NOT WARN. No warnings of type {0} was emitted. \"\n \"The list of emitted warnings is: {1}.\"\n )\n excinfo.match(\n re.escape(\n message_template.format(\n warning_classes, [each.message for each in warninfo]\n )\n )\n )"},{"attributeType":"null","col":0,"comment":"null","endLoc":1068,"id":6056,"name":"_PLUGGY_DIR","nodeType":"Attribute","startLoc":1068,"text":"_PLUGGY_DIR"},{"col":4,"comment":"null","endLoc":497,"header":"@pytest.mark.parametrize(\"strict\", [True, False])\n def test_xfail_condition_keyword(self, testdir, strict)","id":6057,"name":"test_xfail_condition_keyword","nodeType":"Function","startLoc":483,"text":"@pytest.mark.parametrize(\"strict\", [True, False])\n def test_xfail_condition_keyword(self, testdir, strict):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.mark.xfail(condition=False, reason='unsupported feature', strict=%s)\n def test_foo():\n pass\n \"\"\"\n % strict\n )\n result = testdir.runpytest(p, \"-rxX\")\n result.stdout.fnmatch_lines([\"*1 passed*\"])\n assert result.ret == 0"},{"col":4,"comment":"null","endLoc":519,"header":"@pytest.mark.parametrize(\"strict_val\", [\"true\", \"false\"])\n def test_strict_xfail_default_from_file(self, testdir, strict_val)","id":6058,"name":"test_strict_xfail_default_from_file","nodeType":"Function","startLoc":499,"text":"@pytest.mark.parametrize(\"strict_val\", [\"true\", \"false\"])\n def test_strict_xfail_default_from_file(self, testdir, strict_val):\n testdir.makeini(\n \"\"\"\n [pytest]\n xfail_strict = %s\n \"\"\"\n % strict_val\n )\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(reason='unsupported feature')\n def test_foo():\n pass\n \"\"\"\n )\n result = testdir.runpytest(p, \"-rxX\")\n strict = strict_val == \"true\"\n result.stdout.fnmatch_lines([\"*1 failed*\" if strict else \"*1 xpassed*\"])\n assert result.ret == (1 if strict else 0)"},{"col":4,"comment":"null","endLoc":1493,"header":"def test_xdist_verbose(self, many_tests_files, testdir, monkeypatch)","id":6059,"name":"test_xdist_verbose","nodeType":"Function","startLoc":1483,"text":"def test_xdist_verbose(self, many_tests_files, testdir, monkeypatch):\n pytest.importorskip(\"xdist\")\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n output = testdir.runpytest(\"-n2\", \"-v\")\n output.stdout.re_match_lines_random(\n [\n r\"\\[gw\\d\\] \\[\\s*\\d+%\\] PASSED test_bar.py::test_bar\\[1\\]\",\n r\"\\[gw\\d\\] \\[\\s*\\d+%\\] PASSED test_foo.py::test_foo\\[1\\]\",\n r\"\\[gw\\d\\] \\[\\s*\\d+%\\] PASSED test_foobar.py::test_foobar\\[1\\]\",\n ]\n )"},{"className":"TestXFailwithSetupTeardown","col":0,"comment":"null","endLoc":551,"id":6060,"nodeType":"Class","startLoc":522,"text":"class TestXFailwithSetupTeardown(object):\n def test_failing_setup_issue9(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def setup_function(func):\n assert 0\n\n @pytest.mark.xfail\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 xfail*\"])\n\n def test_failing_teardown_issue9(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def teardown_function(func):\n assert 0\n\n @pytest.mark.xfail\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 xfail*\"])"},{"attributeType":"null","col":4,"comment":"null","endLoc":1071,"id":6061,"name":"_PLUGGY_DIR","nodeType":"Attribute","startLoc":1071,"text":"_PLUGGY_DIR"},{"col":4,"comment":"null","endLoc":536,"header":"def test_failing_setup_issue9(self, testdir)","id":6062,"name":"test_failing_setup_issue9","nodeType":"Function","startLoc":523,"text":"def test_failing_setup_issue9(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def setup_function(func):\n assert 0\n\n @pytest.mark.xfail\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 xfail*\"])"},{"col":4,"comment":"null","endLoc":551,"header":"def test_failing_teardown_issue9(self, testdir)","id":6063,"name":"test_failing_teardown_issue9","nodeType":"Function","startLoc":538,"text":"def test_failing_teardown_issue9(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def teardown_function(func):\n assert 0\n\n @pytest.mark.xfail\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 xfail*\"])"},{"className":"TestSkip","col":0,"comment":"null","endLoc":648,"id":6064,"nodeType":"Class","startLoc":554,"text":"class TestSkip(object):\n def test_skip_class(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip\n class TestSomething(object):\n def test_foo(self):\n pass\n def test_bar(self):\n pass\n\n def test_baz():\n pass\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(skipped=2, passed=1)\n\n def test_skips_on_false_string(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip('False')\n def test_foo():\n pass\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(skipped=1)\n\n def test_arg_as_reason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip('testing stuff')\n def test_bar():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines([\"*testing stuff*\", \"*1 skipped*\"])\n\n def test_skip_no_reason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip\n def test_foo():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines([\"*unconditional skip*\", \"*1 skipped*\"])\n\n def test_skip_with_reason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip(reason=\"for lolz\")\n def test_bar():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines([\"*for lolz*\", \"*1 skipped*\"])\n\n def test_only_skips_marked_test(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip\n def test_foo():\n pass\n @pytest.mark.skip(reason=\"nothing in particular\")\n def test_bar():\n pass\n def test_baz():\n assert True\n \"\"\"\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines([\"*nothing in particular*\", \"*1 passed*2 skipped*\"])\n\n def test_strict_and_skip(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip\n def test_hello():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines([\"*unconditional skip*\", \"*1 skipped*\"])"},{"col":4,"comment":"null","endLoc":571,"header":"def test_skip_class(self, testdir)","id":6065,"name":"test_skip_class","nodeType":"Function","startLoc":555,"text":"def test_skip_class(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip\n class TestSomething(object):\n def test_foo(self):\n pass\n def test_bar(self):\n pass\n\n def test_baz():\n pass\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(skipped=2, passed=1)"},{"col":4,"comment":"null","endLoc":583,"header":"def test_skips_on_false_string(self, testdir)","id":6066,"name":"test_skips_on_false_string","nodeType":"Function","startLoc":573,"text":"def test_skips_on_false_string(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip('False')\n def test_foo():\n pass\n \"\"\"\n )\n rec = testdir.inline_run()\n rec.assertoutcome(skipped=1)"},{"col":4,"comment":"null","endLoc":595,"header":"def test_arg_as_reason(self, testdir)","id":6067,"name":"test_arg_as_reason","nodeType":"Function","startLoc":585,"text":"def test_arg_as_reason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip('testing stuff')\n def test_bar():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines([\"*testing stuff*\", \"*1 skipped*\"])"},{"col":4,"comment":"null","endLoc":1502,"header":"def test_capture_no(self, many_tests_files, testdir)","id":6068,"name":"test_capture_no","nodeType":"Function","startLoc":1495,"text":"def test_capture_no(self, many_tests_files, testdir):\n output = testdir.runpytest(\"-s\")\n output.stdout.re_match_lines(\n [r\"test_bar.py \\.{10}\", r\"test_foo.py \\.{5}\", r\"test_foobar.py \\.{5}\"]\n )\n\n output = testdir.runpytest(\"--capture=no\")\n assert \"%]\" not in output.stdout.str()"},{"col":4,"comment":"null","endLoc":607,"header":"def test_skip_no_reason(self, testdir)","id":6069,"name":"test_skip_no_reason","nodeType":"Function","startLoc":597,"text":"def test_skip_no_reason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip\n def test_foo():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines([\"*unconditional skip*\", \"*1 skipped*\"])"},{"col":4,"comment":"null","endLoc":619,"header":"def test_skip_with_reason(self, testdir)","id":6070,"name":"test_skip_with_reason","nodeType":"Function","startLoc":609,"text":"def test_skip_with_reason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip(reason=\"for lolz\")\n def test_bar():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines([\"*for lolz*\", \"*1 skipped*\"])"},{"attributeType":"null","col":0,"comment":"null","endLoc":1072,"id":6071,"name":"_PYTEST_DIR","nodeType":"Attribute","startLoc":1072,"text":"_PYTEST_DIR"},{"attributeType":"null","col":0,"comment":"null","endLoc":1073,"id":6072,"name":"_PY_DIR","nodeType":"Attribute","startLoc":1073,"text":"_PY_DIR"},{"col":0,"comment":"","endLoc":2,"header":"code.py#","id":6073,"name":"","nodeType":"Function","startLoc":2,"text":"if _PY3:\n from traceback import format_exception_only\nelse:\n from ._py2traceback import format_exception_only\n\nco_equal = compile(\n \"__recursioncache_locals_1 == __recursioncache_locals_2\", \"?\", \"eval\"\n)\n\nif PY35: # RecursionError introduced in 3.5\n\n def is_recursion_error(excinfo):\n return excinfo.errisinstance(RecursionError) # noqa\n\n\nelse:\n\n def is_recursion_error(excinfo):\n if not excinfo.errisinstance(RuntimeError):\n return False\n try:\n return \"maximum recursion depth exceeded\" in str(excinfo.value)\n except UnicodeError:\n return False\n\n_PLUGGY_DIR = py.path.local(pluggy.__file__.rstrip(\"oc\"))\n\nif _PLUGGY_DIR.basename == \"__init__.py\":\n _PLUGGY_DIR = _PLUGGY_DIR.dirpath()\n\n_PYTEST_DIR = py.path.local(_pytest.__file__).dirpath()\n\n_PY_DIR = py.path.local(py.__file__).dirpath()"},{"fileName":"recwarn.py","filePath":"src/_pytest","id":6074,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\" recording warnings during test function execution. \"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport inspect\nimport re\nimport sys\nimport warnings\n\nimport six\n\nimport _pytest._code\nfrom _pytest.deprecated import PYTEST_WARNS_UNKNOWN_KWARGS\nfrom _pytest.deprecated import WARNS_EXEC\nfrom _pytest.fixtures import yield_fixture\nfrom _pytest.outcomes import fail\n\n\n@yield_fixture\ndef recwarn():\n \"\"\"Return a :class:`WarningsRecorder` instance that records all warnings emitted by test functions.\n\n See http://docs.python.org/library/warnings.html for information\n on warning categories.\n \"\"\"\n wrec = WarningsRecorder()\n with wrec:\n warnings.simplefilter(\"default\")\n yield wrec\n\n\ndef deprecated_call(func=None, *args, **kwargs):\n \"\"\"context manager that can be used to ensure a block of code triggers a\n ``DeprecationWarning`` or ``PendingDeprecationWarning``::\n\n >>> import warnings\n >>> def api_call_v2():\n ... warnings.warn('use v3 of this api', DeprecationWarning)\n ... return 200\n\n >>> with deprecated_call():\n ... assert api_call_v2() == 200\n\n ``deprecated_call`` can also be used by passing a function and ``*args`` and ``*kwargs``,\n in which case it will ensure calling ``func(*args, **kwargs)`` produces one of the warnings\n types above.\n \"\"\"\n __tracebackhide__ = True\n if func is not None:\n args = (func,) + args\n return warns((DeprecationWarning, PendingDeprecationWarning), *args, **kwargs)\n\n\ndef warns(expected_warning, *args, **kwargs):\n r\"\"\"Assert that code raises a particular class of warning.\n\n Specifically, the parameter ``expected_warning`` can be a warning class or\n sequence of warning classes, and the inside the ``with`` block must issue a warning of that class or\n classes.\n\n This helper produces a list of :class:`warnings.WarningMessage` objects,\n one for each warning raised.\n\n This function can be used as a context manager, or any of the other ways\n ``pytest.raises`` can be used::\n\n >>> with warns(RuntimeWarning):\n ... warnings.warn(\"my warning\", RuntimeWarning)\n\n In the context manager form you may use the keyword argument ``match`` to assert\n that the exception matches a text or regex::\n\n >>> with warns(UserWarning, match='must be 0 or None'):\n ... warnings.warn(\"value must be 0 or None\", UserWarning)\n\n >>> with warns(UserWarning, match=r'must be \\d+$'):\n ... warnings.warn(\"value must be 42\", UserWarning)\n\n >>> with warns(UserWarning, match=r'must be \\d+$'):\n ... warnings.warn(\"this is not here\", UserWarning)\n Traceback (most recent call last):\n ...\n Failed: DID NOT WARN. No warnings of type ...UserWarning... was emitted...\n\n \"\"\"\n __tracebackhide__ = True\n if not args:\n match_expr = kwargs.pop(\"match\", None)\n if kwargs:\n warnings.warn(\n PYTEST_WARNS_UNKNOWN_KWARGS.format(args=sorted(kwargs)), stacklevel=2\n )\n return WarningsChecker(expected_warning, match_expr=match_expr)\n elif isinstance(args[0], str):\n warnings.warn(WARNS_EXEC, stacklevel=2)\n code, = args\n assert isinstance(code, str)\n frame = sys._getframe(1)\n loc = frame.f_locals.copy()\n loc.update(kwargs)\n\n with WarningsChecker(expected_warning):\n code = _pytest._code.Source(code).compile()\n exec(code, frame.f_globals, loc)\n else:\n func = args[0]\n with WarningsChecker(expected_warning):\n return func(*args[1:], **kwargs)\n\n\nclass WarningsRecorder(warnings.catch_warnings):\n \"\"\"A context manager to record raised warnings.\n\n Adapted from `warnings.catch_warnings`.\n \"\"\"\n\n def __init__(self):\n super(WarningsRecorder, self).__init__(record=True)\n self._entered = False\n self._list = []\n\n @property\n def list(self):\n \"\"\"The list of recorded warnings.\"\"\"\n return self._list\n\n def __getitem__(self, i):\n \"\"\"Get a recorded warning by index.\"\"\"\n return self._list[i]\n\n def __iter__(self):\n \"\"\"Iterate through the recorded warnings.\"\"\"\n return iter(self._list)\n\n def __len__(self):\n \"\"\"The number of recorded warnings.\"\"\"\n return len(self._list)\n\n def pop(self, cls=Warning):\n \"\"\"Pop the first recorded warning, raise exception if not exists.\"\"\"\n for i, w in enumerate(self._list):\n if issubclass(w.category, cls):\n return self._list.pop(i)\n __tracebackhide__ = True\n raise AssertionError(\"%r not found in warning list\" % cls)\n\n def clear(self):\n \"\"\"Clear the list of recorded warnings.\"\"\"\n self._list[:] = []\n\n def __enter__(self):\n if self._entered:\n __tracebackhide__ = True\n raise RuntimeError(\"Cannot enter %r twice\" % self)\n self._list = super(WarningsRecorder, self).__enter__()\n warnings.simplefilter(\"always\")\n # python3 keeps track of a \"filter version\", when the filters are\n # updated previously seen warnings can be re-warned. python2 has no\n # concept of this so we must reset the warnings registry manually.\n # trivial patching of `warnings.warn` seems to be enough somehow?\n if six.PY2:\n\n def warn(message, category=None, stacklevel=1):\n # duplicate the stdlib logic due to\n # bad handing in the c version of warnings\n if isinstance(message, Warning):\n category = message.__class__\n # Check category argument\n if category is None:\n category = UserWarning\n assert issubclass(category, Warning)\n\n # emulate resetting the warn registry\n f_globals = sys._getframe(stacklevel).f_globals\n if \"__warningregistry__\" in f_globals:\n orig = f_globals[\"__warningregistry__\"]\n f_globals[\"__warningregistry__\"] = None\n try:\n return self._saved_warn(message, category, stacklevel + 1)\n finally:\n f_globals[\"__warningregistry__\"] = orig\n else:\n return self._saved_warn(message, category, stacklevel + 1)\n\n warnings.warn, self._saved_warn = warn, warnings.warn\n return self\n\n def __exit__(self, *exc_info):\n if not self._entered:\n __tracebackhide__ = True\n raise RuntimeError(\"Cannot exit %r without entering first\" % self)\n # see above where `self._saved_warn` is assigned\n if six.PY2:\n warnings.warn = self._saved_warn\n super(WarningsRecorder, self).__exit__(*exc_info)\n\n # Built-in catch_warnings does not reset entered state so we do it\n # manually here for this context manager to become reusable.\n self._entered = False\n\n\nclass WarningsChecker(WarningsRecorder):\n def __init__(self, expected_warning=None, match_expr=None):\n super(WarningsChecker, self).__init__()\n\n msg = \"exceptions must be old-style classes or derived from Warning, not %s\"\n if isinstance(expected_warning, tuple):\n for exc in expected_warning:\n if not inspect.isclass(exc):\n raise TypeError(msg % type(exc))\n elif inspect.isclass(expected_warning):\n expected_warning = (expected_warning,)\n elif expected_warning is not None:\n raise TypeError(msg % type(expected_warning))\n\n self.expected_warning = expected_warning\n self.match_expr = match_expr\n\n def __exit__(self, *exc_info):\n super(WarningsChecker, self).__exit__(*exc_info)\n\n __tracebackhide__ = True\n\n # only check if we're not currently handling an exception\n if all(a is None for a in exc_info):\n if self.expected_warning is not None:\n if not any(issubclass(r.category, self.expected_warning) for r in self):\n __tracebackhide__ = True\n fail(\n \"DID NOT WARN. No warnings of type {} was emitted. \"\n \"The list of emitted warnings is: {}.\".format(\n self.expected_warning, [each.message for each in self]\n )\n )\n elif self.match_expr is not None:\n for r in self:\n if issubclass(r.category, self.expected_warning):\n if re.compile(self.match_expr).search(str(r.message)):\n break\n else:\n fail(\n \"DID NOT WARN. No warnings of type {} matching\"\n \" ('{}') was emitted. The list of emitted warnings\"\n \" is: {}.\".format(\n self.expected_warning,\n self.match_expr,\n [each.message for each in self],\n )\n )\n"},{"className":"TestProgressWithTeardown","col":0,"comment":"Ensure we show the correct percentages for tests that fail during teardown (#3088)","endLoc":1583,"id":6075,"nodeType":"Class","startLoc":1505,"text":"class TestProgressWithTeardown(object):\n \"\"\"Ensure we show the correct percentages for tests that fail during teardown (#3088)\"\"\"\n\n @pytest.fixture\n def contest_with_teardown_fixture(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def fail_teardown():\n yield\n assert False\n \"\"\"\n )\n\n @pytest.fixture\n def many_files(self, testdir, contest_with_teardown_fixture):\n testdir.makepyfile(\n test_bar=\"\"\"\n import pytest\n @pytest.mark.parametrize('i', range(5))\n def test_bar(fail_teardown, i):\n pass\n \"\"\",\n test_foo=\"\"\"\n import pytest\n @pytest.mark.parametrize('i', range(15))\n def test_foo(fail_teardown, i):\n pass\n \"\"\",\n )\n\n def test_teardown_simple(self, testdir, contest_with_teardown_fixture):\n testdir.makepyfile(\n \"\"\"\n def test_foo(fail_teardown):\n pass\n \"\"\"\n )\n output = testdir.runpytest()\n output.stdout.re_match_lines([r\"test_teardown_simple.py \\.E\\s+\\[100%\\]\"])\n\n def test_teardown_with_test_also_failing(\n self, testdir, contest_with_teardown_fixture\n ):\n testdir.makepyfile(\n \"\"\"\n def test_foo(fail_teardown):\n assert False\n \"\"\"\n )\n output = testdir.runpytest()\n output.stdout.re_match_lines(\n [r\"test_teardown_with_test_also_failing.py FE\\s+\\[100%\\]\"]\n )\n\n def test_teardown_many(self, testdir, many_files):\n output = testdir.runpytest()\n output.stdout.re_match_lines(\n [r\"test_bar.py (\\.E){5}\\s+\\[ 25%\\]\", r\"test_foo.py (\\.E){15}\\s+\\[100%\\]\"]\n )\n\n def test_teardown_many_verbose(self, testdir, many_files):\n output = testdir.runpytest(\"-v\")\n output.stdout.re_match_lines(\n [\n r\"test_bar.py::test_bar\\[0\\] PASSED\\s+\\[ 5%\\]\",\n r\"test_bar.py::test_bar\\[0\\] ERROR\\s+\\[ 5%\\]\",\n r\"test_bar.py::test_bar\\[4\\] PASSED\\s+\\[ 25%\\]\",\n r\"test_bar.py::test_bar\\[4\\] ERROR\\s+\\[ 25%\\]\",\n ]\n )\n\n def test_xdist_normal(self, many_files, testdir, monkeypatch):\n pytest.importorskip(\"xdist\")\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n output = testdir.runpytest(\"-n2\")\n output.stdout.re_match_lines([r\"[\\.E]{40} \\s+ \\[100%\\]\"])"},{"col":4,"comment":"null","endLoc":1519,"header":"@pytest.fixture\n def contest_with_teardown_fixture(self, testdir)","id":6076,"name":"contest_with_teardown_fixture","nodeType":"Function","startLoc":1508,"text":"@pytest.fixture\n def contest_with_teardown_fixture(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def fail_teardown():\n yield\n assert False\n \"\"\"\n )"},{"col":4,"comment":"null","endLoc":636,"header":"def test_only_skips_marked_test(self, testdir)","id":6077,"name":"test_only_skips_marked_test","nodeType":"Function","startLoc":621,"text":"def test_only_skips_marked_test(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip\n def test_foo():\n pass\n @pytest.mark.skip(reason=\"nothing in particular\")\n def test_bar():\n pass\n def test_baz():\n assert True\n \"\"\"\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines([\"*nothing in particular*\", \"*1 passed*2 skipped*\"])"},{"col":4,"comment":"null","endLoc":1536,"header":"@pytest.fixture\n def many_files(self, testdir, contest_with_teardown_fixture)","id":6078,"name":"many_files","nodeType":"Function","startLoc":1521,"text":"@pytest.fixture\n def many_files(self, testdir, contest_with_teardown_fixture):\n testdir.makepyfile(\n test_bar=\"\"\"\n import pytest\n @pytest.mark.parametrize('i', range(5))\n def test_bar(fail_teardown, i):\n pass\n \"\"\",\n test_foo=\"\"\"\n import pytest\n @pytest.mark.parametrize('i', range(15))\n def test_foo(fail_teardown, i):\n pass\n \"\"\",\n )"},{"col":4,"comment":"null","endLoc":1546,"header":"def test_teardown_simple(self, testdir, contest_with_teardown_fixture)","id":6079,"name":"test_teardown_simple","nodeType":"Function","startLoc":1538,"text":"def test_teardown_simple(self, testdir, contest_with_teardown_fixture):\n testdir.makepyfile(\n \"\"\"\n def test_foo(fail_teardown):\n pass\n \"\"\"\n )\n output = testdir.runpytest()\n output.stdout.re_match_lines([r\"test_teardown_simple.py \\.E\\s+\\[100%\\]\"])"},{"col":4,"comment":"null","endLoc":648,"header":"def test_strict_and_skip(self, testdir)","id":6080,"name":"test_strict_and_skip","nodeType":"Function","startLoc":638,"text":"def test_strict_and_skip(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skip\n def test_hello():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines([\"*unconditional skip*\", \"*1 skipped*\"])"},{"col":4,"comment":"null","endLoc":1560,"header":"def test_teardown_with_test_also_failing(\n self, testdir, contest_with_teardown_fixture\n )","id":6081,"name":"test_teardown_with_test_also_failing","nodeType":"Function","startLoc":1548,"text":"def test_teardown_with_test_also_failing(\n self, testdir, contest_with_teardown_fixture\n ):\n testdir.makepyfile(\n \"\"\"\n def test_foo(fail_teardown):\n assert False\n \"\"\"\n )\n output = testdir.runpytest()\n output.stdout.re_match_lines(\n [r\"test_teardown_with_test_also_failing.py FE\\s+\\[100%\\]\"]\n )"},{"className":"TestSkipif","col":0,"comment":"null","endLoc":715,"id":6082,"nodeType":"Class","startLoc":651,"text":"class TestSkipif(object):\n def test_skipif_conditional(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.skipif(\"hasattr(os, 'sep')\")\n def test_func():\n pass\n \"\"\"\n )\n x = pytest.raises(pytest.skip.Exception, lambda: pytest_runtest_setup(item))\n assert x.value.msg == \"condition: hasattr(os, 'sep')\"\n\n @pytest.mark.parametrize(\n \"params\", [\"\\\"hasattr(sys, 'platform')\\\"\", 'True, reason=\"invalid platform\"']\n )\n def test_skipif_reporting(self, testdir, params):\n p = testdir.makepyfile(\n test_foo=\"\"\"\n import pytest\n @pytest.mark.skipif(%(params)s)\n def test_that():\n assert 0\n \"\"\"\n % dict(params=params)\n )\n result = testdir.runpytest(p, \"-s\", \"-rs\")\n result.stdout.fnmatch_lines([\"*SKIP*1*test_foo.py*platform*\", \"*1 skipped*\"])\n assert result.ret == 0\n\n def test_skipif_using_platform(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.skipif(\"platform.platform() == platform.platform()\")\n def test_func():\n pass\n \"\"\"\n )\n pytest.raises(pytest.skip.Exception, lambda: pytest_runtest_setup(item))\n\n @pytest.mark.parametrize(\n \"marker, msg1, msg2\",\n [(\"skipif\", \"SKIP\", \"skipped\"), (\"xfail\", \"XPASS\", \"xpassed\")],\n )\n def test_skipif_reporting_multiple(self, testdir, marker, msg1, msg2):\n testdir.makepyfile(\n test_foo=\"\"\"\n import pytest\n @pytest.mark.{marker}(False, reason='first_condition')\n @pytest.mark.{marker}(True, reason='second_condition')\n def test_foobar():\n assert 1\n \"\"\".format(\n marker=marker\n )\n )\n result = testdir.runpytest(\"-s\", \"-rsxX\")\n result.stdout.fnmatch_lines(\n [\n \"*{msg1}*test_foo.py*second_condition*\".format(msg1=msg1),\n \"*1 {msg2}*\".format(msg2=msg2),\n ]\n )\n assert result.ret == 0"},{"col":4,"comment":"null","endLoc":1566,"header":"def test_teardown_many(self, testdir, many_files)","id":6083,"name":"test_teardown_many","nodeType":"Function","startLoc":1562,"text":"def test_teardown_many(self, testdir, many_files):\n output = testdir.runpytest()\n output.stdout.re_match_lines(\n [r\"test_bar.py (\\.E){5}\\s+\\[ 25%\\]\", r\"test_foo.py (\\.E){15}\\s+\\[100%\\]\"]\n )"},{"className":"WarningsChecker","col":0,"comment":"null","endLoc":251,"id":6084,"nodeType":"Class","startLoc":204,"text":"class WarningsChecker(WarningsRecorder):\n def __init__(self, expected_warning=None, match_expr=None):\n super(WarningsChecker, self).__init__()\n\n msg = \"exceptions must be old-style classes or derived from Warning, not %s\"\n if isinstance(expected_warning, tuple):\n for exc in expected_warning:\n if not inspect.isclass(exc):\n raise TypeError(msg % type(exc))\n elif inspect.isclass(expected_warning):\n expected_warning = (expected_warning,)\n elif expected_warning is not None:\n raise TypeError(msg % type(expected_warning))\n\n self.expected_warning = expected_warning\n self.match_expr = match_expr\n\n def __exit__(self, *exc_info):\n super(WarningsChecker, self).__exit__(*exc_info)\n\n __tracebackhide__ = True\n\n # only check if we're not currently handling an exception\n if all(a is None for a in exc_info):\n if self.expected_warning is not None:\n if not any(issubclass(r.category, self.expected_warning) for r in self):\n __tracebackhide__ = True\n fail(\n \"DID NOT WARN. No warnings of type {} was emitted. \"\n \"The list of emitted warnings is: {}.\".format(\n self.expected_warning, [each.message for each in self]\n )\n )\n elif self.match_expr is not None:\n for r in self:\n if issubclass(r.category, self.expected_warning):\n if re.compile(self.match_expr).search(str(r.message)):\n break\n else:\n fail(\n \"DID NOT WARN. No warnings of type {} matching\"\n \" ('{}') was emitted. The list of emitted warnings\"\n \" is: {}.\".format(\n self.expected_warning,\n self.match_expr,\n [each.message for each in self],\n )\n )"},{"col":4,"comment":"null","endLoc":662,"header":"def test_skipif_conditional(self, testdir)","id":6085,"name":"test_skipif_conditional","nodeType":"Function","startLoc":652,"text":"def test_skipif_conditional(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.skipif(\"hasattr(os, 'sep')\")\n def test_func():\n pass\n \"\"\"\n )\n x = pytest.raises(pytest.skip.Exception, lambda: pytest_runtest_setup(item))\n assert x.value.msg == \"condition: hasattr(os, 'sep')\""},{"col":4,"comment":"null","endLoc":1577,"header":"def test_teardown_many_verbose(self, testdir, many_files)","id":6086,"name":"test_teardown_many_verbose","nodeType":"Function","startLoc":1568,"text":"def test_teardown_many_verbose(self, testdir, many_files):\n output = testdir.runpytest(\"-v\")\n output.stdout.re_match_lines(\n [\n r\"test_bar.py::test_bar\\[0\\] PASSED\\s+\\[ 5%\\]\",\n r\"test_bar.py::test_bar\\[0\\] ERROR\\s+\\[ 5%\\]\",\n r\"test_bar.py::test_bar\\[4\\] PASSED\\s+\\[ 25%\\]\",\n r\"test_bar.py::test_bar\\[4\\] ERROR\\s+\\[ 25%\\]\",\n ]\n )"},{"col":4,"comment":"null","endLoc":251,"header":"def __exit__(self, *exc_info)","id":6087,"name":"__exit__","nodeType":"Function","startLoc":221,"text":"def __exit__(self, *exc_info):\n super(WarningsChecker, self).__exit__(*exc_info)\n\n __tracebackhide__ = True\n\n # only check if we're not currently handling an exception\n if all(a is None for a in exc_info):\n if self.expected_warning is not None:\n if not any(issubclass(r.category, self.expected_warning) for r in self):\n __tracebackhide__ = True\n fail(\n \"DID NOT WARN. No warnings of type {} was emitted. \"\n \"The list of emitted warnings is: {}.\".format(\n self.expected_warning, [each.message for each in self]\n )\n )\n elif self.match_expr is not None:\n for r in self:\n if issubclass(r.category, self.expected_warning):\n if re.compile(self.match_expr).search(str(r.message)):\n break\n else:\n fail(\n \"DID NOT WARN. No warnings of type {} matching\"\n \" ('{}') was emitted. The list of emitted warnings\"\n \" is: {}.\".format(\n self.expected_warning,\n self.match_expr,\n [each.message for each in self],\n )\n )"},{"col":4,"comment":"null","endLoc":1583,"header":"def test_xdist_normal(self, many_files, testdir, monkeypatch)","id":6088,"name":"test_xdist_normal","nodeType":"Function","startLoc":1579,"text":"def test_xdist_normal(self, many_files, testdir, monkeypatch):\n pytest.importorskip(\"xdist\")\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n output = testdir.runpytest(\"-n2\")\n output.stdout.re_match_lines([r\"[\\.E]{40} \\s+ \\[100%\\]\"])"},{"col":0,"comment":"null","endLoc":54,"header":"@pytest.fixture(\n params=[\n Option(verbosity=0),\n Option(verbosity=1),\n Option(verbosity=-1),\n Option(fulltrace=True),\n ],\n ids=[\"default\", \"verbose\", \"quiet\", \"fulltrace\"],\n)\ndef option(request)","id":6089,"name":"option","nodeType":"Function","startLoc":44,"text":"@pytest.fixture(\n params=[\n Option(verbosity=0),\n Option(verbosity=1),\n Option(verbosity=-1),\n Option(fulltrace=True),\n ],\n ids=[\"default\", \"verbose\", \"quiet\", \"fulltrace\"],\n)\ndef option(request):\n return request.param"},{"col":49,"endLoc":661,"id":6090,"nodeType":"Lambda","startLoc":661,"text":"lambda: pytest_runtest_setup(item)"},{"className":"PytestArg","col":0,"comment":"null","endLoc":176,"id":6091,"nodeType":"Class","startLoc":169,"text":"class PytestArg(object):\n def __init__(self, request):\n self.request = request\n\n def gethookrecorder(self, hook):\n hookrecorder = HookRecorder(hook._pm)\n self.request.addfinalizer(hookrecorder.finish_recording)\n return hookrecorder"},{"col":4,"comment":"null","endLoc":171,"header":"def __init__(self, request)","id":6092,"name":"__init__","nodeType":"Function","startLoc":170,"text":"def __init__(self, request):\n self.request = request"},{"col":4,"comment":"null","endLoc":176,"header":"def gethookrecorder(self, hook)","id":6093,"name":"gethookrecorder","nodeType":"Function","startLoc":173,"text":"def gethookrecorder(self, hook):\n hookrecorder = HookRecorder(hook._pm)\n self.request.addfinalizer(hookrecorder.finish_recording)\n return hookrecorder"},{"col":4,"comment":"null","endLoc":679,"header":"@pytest.mark.parametrize(\n \"params\", [\"\\\"hasattr(sys, 'platform')\\\"\", 'True, reason=\"invalid platform\"']\n )\n def test_skipif_reporting(self, testdir, params)","id":6094,"name":"test_skipif_reporting","nodeType":"Function","startLoc":664,"text":"@pytest.mark.parametrize(\n \"params\", [\"\\\"hasattr(sys, 'platform')\\\"\", 'True, reason=\"invalid platform\"']\n )\n def test_skipif_reporting(self, testdir, params):\n p = testdir.makepyfile(\n test_foo=\"\"\"\n import pytest\n @pytest.mark.skipif(%(params)s)\n def test_that():\n assert 0\n \"\"\"\n % dict(params=params)\n )\n result = testdir.runpytest(p, \"-s\", \"-rs\")\n result.stdout.fnmatch_lines([\"*SKIP*1*test_foo.py*platform*\", \"*1 skipped*\"])\n assert result.ret == 0"},{"col":0,"comment":"null","endLoc":75,"header":"@pytest.mark.parametrize(\n \"input,expected\",\n [\n ([DistInfo(project_name=\"test\", version=1)], [\"test-1\"]),\n ([DistInfo(project_name=\"pytest-test\", version=1)], [\"test-1\"]),\n (\n [\n DistInfo(project_name=\"test\", version=1),\n DistInfo(project_name=\"test\", version=1),\n ],\n [\"test-1\"],\n ),\n ],\n ids=[\"normal\", \"prefix-strip\", \"deduplicate\"],\n)\ndef test_plugin_nameversion(input, expected)","id":6095,"name":"test_plugin_nameversion","nodeType":"Function","startLoc":57,"text":"@pytest.mark.parametrize(\n \"input,expected\",\n [\n ([DistInfo(project_name=\"test\", version=1)], [\"test-1\"]),\n ([DistInfo(project_name=\"pytest-test\", version=1)], [\"test-1\"]),\n (\n [\n DistInfo(project_name=\"test\", version=1),\n DistInfo(project_name=\"test\", version=1),\n ],\n [\"test-1\"],\n ),\n ],\n ids=[\"normal\", \"prefix-strip\", \"deduplicate\"],\n)\ndef test_plugin_nameversion(input, expected):\n pluginlist = [(None, x) for x in input]\n result = _plugin_nameversions(pluginlist)\n assert result == expected"},{"attributeType":"null","col":8,"comment":"null","endLoc":171,"id":6096,"name":"request","nodeType":"Attribute","startLoc":171,"text":"self.request"},{"className":"ParsedCall","col":0,"comment":"null","endLoc":192,"id":6097,"nodeType":"Class","startLoc":184,"text":"class ParsedCall(object):\n def __init__(self, name, kwargs):\n self.__dict__.update(kwargs)\n self._name = name\n\n def __repr__(self):\n d = self.__dict__.copy()\n del d[\"_name\"]\n return \"\" % (self._name, d)"},{"col":4,"comment":"null","endLoc":192,"header":"def __repr__(self)","id":6098,"name":"__repr__","nodeType":"Function","startLoc":189,"text":"def __repr__(self):\n d = self.__dict__.copy()\n del d[\"_name\"]\n return \"\" % (self._name, d)"},{"col":0,"comment":"null","endLoc":774,"header":"def test_fail_extra_reporting(testdir, monkeypatch)","id":6099,"name":"test_fail_extra_reporting","nodeType":"Function","startLoc":763,"text":"def test_fail_extra_reporting(testdir, monkeypatch):\n monkeypatch.setenv(\"COLUMNS\", \"80\")\n testdir.makepyfile(\"def test_this(): assert 0, 'this_failed' * 100\")\n result = testdir.runpytest()\n assert \"short test summary\" not in result.stdout.str()\n result = testdir.runpytest(\"-rf\")\n result.stdout.fnmatch_lines(\n [\n \"*test summary*\",\n \"FAILED test_fail_extra_reporting.py::test_this - AssertionError: this_failedt...\",\n ]\n )"},{"col":0,"comment":"null","endLoc":780,"header":"def test_fail_reporting_on_pass(testdir)","id":6100,"name":"test_fail_reporting_on_pass","nodeType":"Function","startLoc":777,"text":"def test_fail_reporting_on_pass(testdir):\n testdir.makepyfile(\"def test_this(): assert 1\")\n result = testdir.runpytest(\"-rf\")\n assert \"short test summary\" not in result.stdout.str()"},{"col":0,"comment":"null","endLoc":788,"header":"def test_pass_extra_reporting(testdir)","id":6101,"name":"test_pass_extra_reporting","nodeType":"Function","startLoc":783,"text":"def test_pass_extra_reporting(testdir):\n testdir.makepyfile(\"def test_this(): assert 1\")\n result = testdir.runpytest()\n assert \"short test summary\" not in result.stdout.str()\n result = testdir.runpytest(\"-rp\")\n result.stdout.fnmatch_lines([\"*test summary*\", \"PASS*test_pass_extra_reporting*\"])"},{"attributeType":"null","col":8,"comment":"null","endLoc":187,"id":6103,"name":"_name","nodeType":"Attribute","startLoc":187,"text":"self._name"},{"col":4,"comment":"null","endLoc":305,"header":"def test_record(self)","id":6104,"name":"test_record","nodeType":"Function","startLoc":300,"text":"def test_record(self):\n with pytest.warns(UserWarning) as record:\n warnings.warn(\"user\", UserWarning)\n\n assert len(record) == 1\n assert str(record[0].message) == \"user\""},{"col":0,"comment":"null","endLoc":794,"header":"def test_pass_reporting_on_fail(testdir)","id":6105,"name":"test_pass_reporting_on_fail","nodeType":"Function","startLoc":791,"text":"def test_pass_reporting_on_fail(testdir):\n testdir.makepyfile(\"def test_this(): assert 0\")\n result = testdir.runpytest(\"-rp\")\n assert \"short test summary\" not in result.stdout.str()"},{"className":"RunResult","col":0,"comment":"The result of running a command.\n\n Attributes:\n\n :ret: the return value\n :outlines: list of lines captured from stdout\n :errlines: list of lines captures from stderr\n :stdout: :py:class:`LineMatcher` of stdout, use ``stdout.str()`` to\n reconstruct stdout or the commonly used ``stdout.fnmatch_lines()``\n method\n :stderr: :py:class:`LineMatcher` of stderr\n :duration: duration in seconds\n\n ","endLoc":430,"id":6106,"nodeType":"Class","startLoc":361,"text":"class RunResult(object):\n \"\"\"The result of running a command.\n\n Attributes:\n\n :ret: the return value\n :outlines: list of lines captured from stdout\n :errlines: list of lines captures from stderr\n :stdout: :py:class:`LineMatcher` of stdout, use ``stdout.str()`` to\n reconstruct stdout or the commonly used ``stdout.fnmatch_lines()``\n method\n :stderr: :py:class:`LineMatcher` of stderr\n :duration: duration in seconds\n\n \"\"\"\n\n def __init__(self, ret, outlines, errlines, duration):\n self.ret = ret\n self.outlines = outlines\n self.errlines = errlines\n self.stdout = LineMatcher(outlines)\n self.stderr = LineMatcher(errlines)\n self.duration = duration\n\n def __repr__(self):\n return (\n \"\"\n % (self.ret, len(self.stdout.lines), len(self.stderr.lines), self.duration)\n )\n\n def parseoutcomes(self):\n \"\"\"Return a dictionary of outcomestring->num from parsing the terminal\n output that the test process produced.\n\n \"\"\"\n for line in reversed(self.outlines):\n if \"seconds\" in line:\n outcomes = rex_outcome.findall(line)\n if outcomes:\n d = {}\n for num, cat in outcomes:\n d[cat] = int(num)\n return d\n raise ValueError(\"Pytest terminal report not found\")\n\n def assert_outcomes(\n self, passed=0, skipped=0, failed=0, error=0, xpassed=0, xfailed=0\n ):\n \"\"\"Assert that the specified outcomes appear with the respective\n numbers (0 means it didn't occur) in the text output from a test run.\n\n \"\"\"\n d = self.parseoutcomes()\n obtained = {\n \"passed\": d.get(\"passed\", 0),\n \"skipped\": d.get(\"skipped\", 0),\n \"failed\": d.get(\"failed\", 0),\n \"error\": d.get(\"error\", 0),\n \"xpassed\": d.get(\"xpassed\", 0),\n \"xfailed\": d.get(\"xfailed\", 0),\n }\n expected = {\n \"passed\": passed,\n \"skipped\": skipped,\n \"failed\": failed,\n \"error\": error,\n \"xpassed\": xpassed,\n \"xfailed\": xfailed,\n }\n assert obtained == expected"},{"col":4,"comment":"null","endLoc":389,"header":"def __repr__(self)","id":6107,"name":"__repr__","nodeType":"Function","startLoc":385,"text":"def __repr__(self):\n return (\n \"\"\n % (self.ret, len(self.stdout.lines), len(self.stderr.lines), self.duration)\n )"},{"col":4,"comment":"Return a dictionary of outcomestring->num from parsing the terminal\n output that the test process produced.\n\n ","endLoc":404,"header":"def parseoutcomes(self)","id":6108,"name":"parseoutcomes","nodeType":"Function","startLoc":391,"text":"def parseoutcomes(self):\n \"\"\"Return a dictionary of outcomestring->num from parsing the terminal\n output that the test process produced.\n\n \"\"\"\n for line in reversed(self.outlines):\n if \"seconds\" in line:\n outcomes = rex_outcome.findall(line)\n if outcomes:\n d = {}\n for num, cat in outcomes:\n d[cat] = int(num)\n return d\n raise ValueError(\"Pytest terminal report not found\")"},{"col":0,"comment":"null","endLoc":823,"header":"def test_pass_output_reporting(testdir)","id":6109,"name":"test_pass_output_reporting","nodeType":"Function","startLoc":797,"text":"def test_pass_output_reporting(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_pass_has_output():\n print(\"Four score and seven years ago...\")\n def test_pass_no_output():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n s = result.stdout.str()\n assert \"test_pass_has_output\" not in s\n assert \"Four score and seven years ago...\" not in s\n assert \"test_pass_no_output\" not in s\n result = testdir.runpytest(\"-rPp\")\n result.stdout.fnmatch_lines(\n [\n \"*= PASSES =*\",\n \"*_ test_pass_has_output _*\",\n \"*- Captured stdout call -*\",\n \"Four score and seven years ago...\",\n \"*= short test summary info =*\",\n \"PASSED test_pass_output_reporting.py::test_pass_has_output\",\n \"PASSED test_pass_output_reporting.py::test_pass_no_output\",\n \"*= 2 passed in *\",\n ]\n )"},{"col":4,"comment":"null","endLoc":314,"header":"def test_record_only(self)","id":6110,"name":"test_record_only","nodeType":"Function","startLoc":307,"text":"def test_record_only(self):\n with pytest.warns(None) as record:\n warnings.warn(\"user\", UserWarning)\n warnings.warn(\"runtime\", RuntimeWarning)\n\n assert len(record) == 2\n assert str(record[0].message) == \"user\"\n assert str(record[1].message) == \"runtime\""},{"fileName":"_argcomplete.py","filePath":"src/_pytest","id":6111,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"allow bash-completion for argparse with argcomplete if installed\nneeds argcomplete>=0.5.6 for python 3.2/3.3 (older versions fail\nto find the magic string, so _ARGCOMPLETE env. var is never set, and\nthis does not need special code.\n\nFunction try_argcomplete(parser) should be called directly before\nthe call to ArgumentParser.parse_args().\n\nThe filescompleter is what you normally would use on the positional\narguments specification, in order to get \"dirname/\" after \"dirn\"\ninstead of the default \"dirname \":\n\n optparser.add_argument(Config._file_or_dir, nargs='*'\n ).completer=filescompleter\n\nOther, application specific, completers should go in the file\ndoing the add_argument calls as they need to be specified as .completer\nattributes as well. (If argcomplete is not installed, the function the\nattribute points to will not be used).\n\nSPEEDUP\n=======\nThe generic argcomplete script for bash-completion\n(/etc/bash_completion.d/python-argcomplete.sh )\nuses a python program to determine startup script generated by pip.\nYou can speed up completion somewhat by changing this script to include\n # PYTHON_ARGCOMPLETE_OK\nso the the python-argcomplete-check-easy-install-script does not\nneed to be called to find the entry point of the code and see if that is\nmarked with PYTHON_ARGCOMPLETE_OK\n\nINSTALL/DEBUGGING\n=================\nTo include this support in another application that has setup.py generated\nscripts:\n- add the line:\n # PYTHON_ARGCOMPLETE_OK\n near the top of the main python entry point\n- include in the file calling parse_args():\n from _argcomplete import try_argcomplete, filescompleter\n , call try_argcomplete just before parse_args(), and optionally add\n filescompleter to the positional arguments' add_argument()\nIf things do not work right away:\n- switch on argcomplete debugging with (also helpful when doing custom\n completers):\n export _ARC_DEBUG=1\n- run:\n python-argcomplete-check-easy-install-script $(which appname)\n echo $?\n will echo 0 if the magic line has been found, 1 if not\n- sometimes it helps to find early on errors using:\n _ARGCOMPLETE=1 _ARC_DEBUG=1 appname\n which should throw a KeyError: 'COMPLINE' (which is properly set by the\n global argcomplete script).\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\nfrom glob import glob\n\n\nclass FastFilesCompleter(object):\n \"Fast file completer class\"\n\n def __init__(self, directories=True):\n self.directories = directories\n\n def __call__(self, prefix, **kwargs):\n \"\"\"only called on non option completions\"\"\"\n if os.path.sep in prefix[1:]:\n prefix_dir = len(os.path.dirname(prefix) + os.path.sep)\n else:\n prefix_dir = 0\n completion = []\n globbed = []\n if \"*\" not in prefix and \"?\" not in prefix:\n # we are on unix, otherwise no bash\n if not prefix or prefix[-1] == os.path.sep:\n globbed.extend(glob(prefix + \".*\"))\n prefix += \"*\"\n globbed.extend(glob(prefix))\n for x in sorted(globbed):\n if os.path.isdir(x):\n x += \"/\"\n # append stripping the prefix (like bash, not like compgen)\n completion.append(x[prefix_dir:])\n return completion\n\n\nif os.environ.get(\"_ARGCOMPLETE\"):\n try:\n import argcomplete.completers\n except ImportError:\n sys.exit(-1)\n filescompleter = FastFilesCompleter()\n\n def try_argcomplete(parser):\n argcomplete.autocomplete(parser, always_complete_options=False)\n\n\nelse:\n\n def try_argcomplete(parser):\n pass\n\n filescompleter = None\n"},{"col":0,"comment":"null","endLoc":830,"header":"def test_color_yes(testdir)","id":6112,"name":"test_color_yes","nodeType":"Function","startLoc":826,"text":"def test_color_yes(testdir):\n testdir.makepyfile(\"def test_this(): assert 1\")\n result = testdir.runpytest(\"--color=yes\")\n assert \"test session starts\" in result.stdout.str()\n assert \"\\x1b[1m\" in result.stdout.str()"},{"col":0,"comment":"null","endLoc":837,"header":"def test_color_no(testdir)","id":6113,"name":"test_color_no","nodeType":"Function","startLoc":833,"text":"def test_color_no(testdir):\n testdir.makepyfile(\"def test_this(): assert 1\")\n result = testdir.runpytest(\"--color=no\")\n assert \"test session starts\" in result.stdout.str()\n assert \"\\x1b[1m\" not in result.stdout.str()"},{"className":"FastFilesCompleter","col":0,"comment":"Fast file completer class","endLoc":91,"id":6114,"nodeType":"Class","startLoc":66,"text":"class FastFilesCompleter(object):\n \"Fast file completer class\"\n\n def __init__(self, directories=True):\n self.directories = directories\n\n def __call__(self, prefix, **kwargs):\n \"\"\"only called on non option completions\"\"\"\n if os.path.sep in prefix[1:]:\n prefix_dir = len(os.path.dirname(prefix) + os.path.sep)\n else:\n prefix_dir = 0\n completion = []\n globbed = []\n if \"*\" not in prefix and \"?\" not in prefix:\n # we are on unix, otherwise no bash\n if not prefix or prefix[-1] == os.path.sep:\n globbed.extend(glob(prefix + \".*\"))\n prefix += \"*\"\n globbed.extend(glob(prefix))\n for x in sorted(globbed):\n if os.path.isdir(x):\n x += \"/\"\n # append stripping the prefix (like bash, not like compgen)\n completion.append(x[prefix_dir:])\n return completion"},{"col":4,"comment":"only called on non option completions","endLoc":91,"header":"def __call__(self, prefix, **kwargs)","id":6115,"name":"__call__","nodeType":"Function","startLoc":72,"text":"def __call__(self, prefix, **kwargs):\n \"\"\"only called on non option completions\"\"\"\n if os.path.sep in prefix[1:]:\n prefix_dir = len(os.path.dirname(prefix) + os.path.sep)\n else:\n prefix_dir = 0\n completion = []\n globbed = []\n if \"*\" not in prefix and \"?\" not in prefix:\n # we are on unix, otherwise no bash\n if not prefix or prefix[-1] == os.path.sep:\n globbed.extend(glob(prefix + \".*\"))\n prefix += \"*\"\n globbed.extend(glob(prefix))\n for x in sorted(globbed):\n if os.path.isdir(x):\n x += \"/\"\n # append stripping the prefix (like bash, not like compgen)\n completion.append(x[prefix_dir:])\n return completion"},{"col":0,"comment":"skip collect progress report when working on non-terminals.\n #1397\n ","endLoc":862,"header":"@pytest.mark.parametrize(\"verbose\", [True, False])\ndef test_color_yes_collection_on_non_atty(testdir, verbose)","id":6116,"name":"test_color_yes_collection_on_non_atty","nodeType":"Function","startLoc":840,"text":"@pytest.mark.parametrize(\"verbose\", [True, False])\ndef test_color_yes_collection_on_non_atty(testdir, verbose):\n \"\"\"skip collect progress report when working on non-terminals.\n #1397\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize('i', range(10))\n def test_this(i):\n assert 1\n \"\"\"\n )\n args = [\"--color=yes\"]\n if verbose:\n args.append(\"-vv\")\n result = testdir.runpytest(*args)\n assert \"test session starts\" in result.stdout.str()\n assert \"\\x1b[1m\" in result.stdout.str()\n assert \"collecting 10 items\" not in result.stdout.str()\n if verbose:\n assert \"collecting ...\" in result.stdout.str()\n assert \"collected 10 items\" in result.stdout.str()"},{"col":4,"comment":"null","endLoc":337,"header":"def test_record_by_subclass(self)","id":6117,"name":"test_record_by_subclass","nodeType":"Function","startLoc":316,"text":"def test_record_by_subclass(self):\n with pytest.warns(Warning) as record:\n warnings.warn(\"user\", UserWarning)\n warnings.warn(\"runtime\", RuntimeWarning)\n\n assert len(record) == 2\n assert str(record[0].message) == \"user\"\n assert str(record[1].message) == \"runtime\"\n\n class MyUserWarning(UserWarning):\n pass\n\n class MyRuntimeWarning(RuntimeWarning):\n pass\n\n with pytest.warns((UserWarning, RuntimeWarning)) as record:\n warnings.warn(\"user\", MyUserWarning)\n warnings.warn(\"runtime\", MyRuntimeWarning)\n\n assert len(record) == 2\n assert str(record[0].message) == \"user\"\n assert str(record[1].message) == \"runtime\""},{"col":0,"comment":"null","endLoc":896,"header":"def test_getreportopt()","id":6118,"name":"test_getreportopt","nodeType":"Function","startLoc":865,"text":"def test_getreportopt():\n class Config(object):\n class Option(object):\n reportchars = \"\"\n disable_warnings = True\n\n option = Option()\n\n config = Config()\n\n config.option.reportchars = \"sf\"\n assert getreportopt(config) == \"sf\"\n\n config.option.reportchars = \"sfxw\"\n assert getreportopt(config) == \"sfx\"\n\n # Now with --disable-warnings.\n config.option.disable_warnings = False\n config.option.reportchars = \"a\"\n assert getreportopt(config) == \"sxXwEf\" # NOTE: \"w\" included!\n\n config.option.reportchars = \"sfx\"\n assert getreportopt(config) == \"sfxw\"\n\n config.option.reportchars = \"sfxw\"\n assert getreportopt(config) == \"sfxw\"\n\n config.option.reportchars = \"a\"\n assert getreportopt(config) == \"sxXwEf\" # NOTE: \"w\" included!\n\n config.option.reportchars = \"A\"\n assert getreportopt(config) == \"PpsxXwEf\""},{"col":0,"comment":"null","endLoc":915,"header":"def test_terminalreporter_reportopt_addopts(testdir)","id":6119,"name":"test_terminalreporter_reportopt_addopts","nodeType":"Function","startLoc":899,"text":"def test_terminalreporter_reportopt_addopts(testdir):\n testdir.makeini(\"[pytest]\\naddopts=-rs\")\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def tr(request):\n tr = request.config.pluginmanager.getplugin(\"terminalreporter\")\n return tr\n def test_opt(tr):\n assert tr.hasopt('skipped')\n assert not tr.hasopt('qwe')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":0,"comment":"null","endLoc":939,"header":"def test_tbstyle_short(testdir)","id":6120,"name":"test_tbstyle_short","nodeType":"Function","startLoc":918,"text":"def test_tbstyle_short(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n @pytest.fixture\n def arg(request):\n return 42\n def test_opt(arg):\n x = 0\n assert x\n \"\"\"\n )\n result = testdir.runpytest(\"--tb=short\")\n s = result.stdout.str()\n assert \"arg = 42\" not in s\n assert \"x = 0\" not in s\n result.stdout.fnmatch_lines([\"*%s:8*\" % p.basename, \" assert x\", \"E assert*\"])\n result = testdir.runpytest()\n s = result.stdout.str()\n assert \"x = 0\" in s\n assert \"assert x\" in s"},{"col":0,"comment":"null","endLoc":115,"header":"def test_log_cli_level_log_level_interaction(testdir)","id":6121,"name":"test_log_cli_level_log_level_interaction","nodeType":"Function","startLoc":88,"text":"def test_log_cli_level_log_level_interaction(testdir):\n testdir.makepyfile(\n \"\"\"\n import logging\n logger = logging.getLogger()\n\n def test_foo():\n logger.debug('debug text ' + 'going to logger')\n logger.info('info text ' + 'going to logger')\n logger.warning('warning text ' + 'going to logger')\n logger.error('error text ' + 'going to logger')\n assert 0\n \"\"\"\n )\n\n result = testdir.runpytest(\"--log-cli-level=INFO\", \"--log-level=ERROR\")\n assert result.ret == 1\n\n result.stdout.fnmatch_lines(\n [\n \"*-- live log call --*\",\n \"*INFO*info text going to logger\",\n \"*WARNING*warning text going to logger\",\n \"*ERROR*error text going to logger\",\n \"=* 1 failed in *=\",\n ]\n )\n assert \"DEBUG\" not in result.stdout.str()"},{"col":0,"comment":"null","endLoc":945,"header":"def test_traceconfig(testdir, monkeypatch)","id":6122,"name":"test_traceconfig","nodeType":"Function","startLoc":942,"text":"def test_traceconfig(testdir, monkeypatch):\n result = testdir.runpytest(\"--traceconfig\")\n result.stdout.fnmatch_lines([\"*active plugins*\"])\n assert result.ret == EXIT_NOTESTSCOLLECTED"},{"col":0,"comment":"null","endLoc":1150,"header":"@pytest.mark.xfail(\"not hasattr(os, 'dup')\")\ndef test_fdopen_kept_alive_issue124(testdir)","id":6123,"name":"test_fdopen_kept_alive_issue124","nodeType":"Function","startLoc":1134,"text":"@pytest.mark.xfail(\"not hasattr(os, 'dup')\")\ndef test_fdopen_kept_alive_issue124(testdir):\n testdir.makepyfile(\n \"\"\"\n import os, sys\n k = []\n def test_open_file_and_keep_alive(capfd):\n stdout = os.fdopen(1, 'w', 1)\n k.append(stdout)\n\n def test_close_kept_alive_file():\n stdout = k.pop()\n stdout.close()\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 passed*\"])"},{"col":0,"comment":"null","endLoc":1168,"header":"def test_tbstyle_native_setup_error(testdir)","id":6124,"name":"test_tbstyle_native_setup_error","nodeType":"Function","startLoc":1153,"text":"def test_tbstyle_native_setup_error(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture\n def setup_error_fixture():\n raise Exception(\"error in exception\")\n\n def test_error_fixture(setup_error_fixture):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"--tb=native\")\n result.stdout.fnmatch_lines(\n ['*File *test_tbstyle_native_setup_error.py\", line *, in setup_error_fixture*']\n )"},{"col":0,"comment":"null","endLoc":1188,"header":"def test_terminal_summary(testdir)","id":6125,"name":"test_terminal_summary","nodeType":"Function","startLoc":1171,"text":"def test_terminal_summary(testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_terminal_summary(terminalreporter, exitstatus):\n w = terminalreporter\n w.section(\"hello\")\n w.line(\"world\")\n w.line(\"exitstatus: {0}\".format(exitstatus))\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n \"\"\"\n *==== hello ====*\n world\n exitstatus: 5\n \"\"\"\n )"},{"col":4,"comment":"If a test is run again, the warning should still be raised","endLoc":353,"header":"def test_double_test(self, testdir)","id":6126,"name":"test_double_test","nodeType":"Function","startLoc":339,"text":"def test_double_test(self, testdir):\n \"\"\"If a test is run again, the warning should still be raised\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n import warnings\n\n @pytest.mark.parametrize('run', [1, 2])\n def test(run):\n with pytest.warns(RuntimeWarning):\n warnings.warn(\"runtime\", RuntimeWarning)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 passed in*\"])"},{"col":0,"comment":"Test that warnings emitted during pytest_terminal_summary are displayed.\n (#1305).\n ","endLoc":1225,"header":"@pytest.mark.filterwarnings(\"default\")\ndef test_terminal_summary_warnings_are_displayed(testdir)","id":6127,"name":"test_terminal_summary_warnings_are_displayed","nodeType":"Function","startLoc":1191,"text":"@pytest.mark.filterwarnings(\"default\")\ndef test_terminal_summary_warnings_are_displayed(testdir):\n \"\"\"Test that warnings emitted during pytest_terminal_summary are displayed.\n (#1305).\n \"\"\"\n testdir.makeconftest(\n \"\"\"\n import warnings\n def pytest_terminal_summary(terminalreporter):\n warnings.warn(UserWarning('internal warning'))\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_failure():\n import warnings\n warnings.warn(\"warning_from_\" + \"test\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"-ra\")\n result.stdout.fnmatch_lines(\n [\n \"*= warnings summary =*\",\n \"*warning_from_test*\",\n \"*= short test summary info =*\",\n \"*= warnings summary (final) =*\",\n \"*conftest.py:3:*internal warning\",\n \"*== 1 failed, 2 warnings in *\",\n ]\n )\n assert \"None\" not in result.stdout.str()\n stdout = result.stdout.str()\n assert stdout.count(\"warning_from_test\") == 1\n assert stdout.count(\"=== warnings summary \") == 2"},{"col":0,"comment":"null","endLoc":142,"header":"def test_setup_logging(testdir)","id":6128,"name":"test_setup_logging","nodeType":"Function","startLoc":118,"text":"def test_setup_logging(testdir):\n testdir.makepyfile(\n \"\"\"\n import logging\n\n logger = logging.getLogger(__name__)\n\n def setup_function(function):\n logger.info('text going to logger from setup')\n\n def test_foo():\n logger.info('text going to logger from call')\n assert False\n \"\"\"\n )\n result = testdir.runpytest(\"--log-level=INFO\")\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\n \"*- Captured *log setup -*\",\n \"*text going to logger from setup*\",\n \"*- Captured *log call -*\",\n \"*text going to logger from call*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":365,"header":"def test_match_regex(self)","id":6129,"name":"test_match_regex","nodeType":"Function","startLoc":355,"text":"def test_match_regex(self):\n with pytest.warns(UserWarning, match=r\"must be \\d+$\"):\n warnings.warn(\"value must be 42\", UserWarning)\n\n with pytest.raises(pytest.fail.Exception):\n with pytest.warns(UserWarning, match=r\"must be \\d+$\"):\n warnings.warn(\"this is not here\", UserWarning)\n\n with pytest.raises(pytest.fail.Exception):\n with pytest.warns(FutureWarning, match=r\"must be \\d+$\"):\n warnings.warn(\"value must be 42\", UserWarning)"},{"col":0,"comment":"null","endLoc":1250,"header":"@pytest.mark.filterwarnings(\"default\")\ndef test_terminal_summary_warnings_header_once(testdir)","id":6130,"name":"test_terminal_summary_warnings_header_once","nodeType":"Function","startLoc":1228,"text":"@pytest.mark.filterwarnings(\"default\")\ndef test_terminal_summary_warnings_header_once(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_failure():\n import warnings\n warnings.warn(\"warning_from_\" + \"test\")\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"-ra\")\n result.stdout.fnmatch_lines(\n [\n \"*= warnings summary =*\",\n \"*warning_from_test*\",\n \"*= short test summary info =*\",\n \"*== 1 failed, 1 warnings in *\",\n ]\n )\n assert \"None\" not in result.stdout.str()\n stdout = result.stdout.str()\n assert stdout.count(\"warning_from_test\") == 1\n assert stdout.count(\"=== warnings summary \") == 1"},{"col":0,"comment":"null","endLoc":169,"header":"def test_teardown_logging(testdir)","id":6131,"name":"test_teardown_logging","nodeType":"Function","startLoc":145,"text":"def test_teardown_logging(testdir):\n testdir.makepyfile(\n \"\"\"\n import logging\n\n logger = logging.getLogger(__name__)\n\n def test_foo():\n logger.info('text going to logger from call')\n\n def teardown_function(function):\n logger.info('text going to logger from teardown')\n assert False\n \"\"\"\n )\n result = testdir.runpytest(\"--log-level=INFO\")\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\n \"*- Captured *log call -*\",\n \"*text going to logger from call*\",\n \"*- Captured *log teardown -*\",\n \"*text going to logger from teardown*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":371,"header":"def test_one_from_multiple_warns(self)","id":6132,"name":"test_one_from_multiple_warns","nodeType":"Function","startLoc":367,"text":"def test_one_from_multiple_warns(self):\n with pytest.warns(UserWarning, match=r\"aaa\"):\n warnings.warn(\"cccccccccc\", UserWarning)\n warnings.warn(\"bbbbbbbbbb\", UserWarning)\n warnings.warn(\"aaaaaaaaaa\", UserWarning)"},{"col":0,"comment":"null","endLoc":193,"header":"def test_disable_log_capturing(testdir)","id":6133,"name":"test_disable_log_capturing","nodeType":"Function","startLoc":172,"text":"def test_disable_log_capturing(testdir):\n testdir.makepyfile(\n \"\"\"\n import sys\n import logging\n\n logger = logging.getLogger(__name__)\n\n def test_foo():\n sys.stdout.write('text going to stdout')\n logger.warning('catch me if you can!')\n sys.stderr.write('text going to stderr')\n assert False\n \"\"\"\n )\n result = testdir.runpytest(\"--no-print-logs\")\n print(result.stdout)\n assert result.ret == 1\n result.stdout.fnmatch_lines([\"*- Captured stdout call -*\", \"text going to stdout\"])\n result.stdout.fnmatch_lines([\"*- Captured stderr call -*\", \"text going to stderr\"])\n with pytest.raises(pytest.fail.Exception):\n result.stdout.fnmatch_lines([\"*- Captured *log call -*\"])"},{"col":0,"comment":"null","endLoc":1311,"header":"@pytest.mark.parametrize(\n \"exp_color, exp_line, stats_arg\",\n [\n # The method under test only cares about the length of each\n # dict value, not the actual contents, so tuples of anything\n # suffice\n # Important statuses -- the highest priority of these always wins\n (\"red\", \"1 failed\", {\"failed\": (1,)}),\n (\"red\", \"1 failed, 1 passed\", {\"failed\"","id":6134,"name":"test_summary_stats","nodeType":"Function","startLoc":1253,"text":"@pytest.mark.parametrize(\n \"exp_color, exp_line, stats_arg\",\n [\n # The method under test only cares about the length of each\n # dict value, not the actual contents, so tuples of anything\n # suffice\n # Important statuses -- the highest priority of these always wins\n (\"red\", \"1 failed\", {\"failed\": (1,)}),\n (\"red\", \"1 failed, 1 passed\", {\"failed\": (1,), \"passed\": (1,)}),\n (\"red\", \"1 error\", {\"error\": (1,)}),\n (\"red\", \"1 passed, 1 error\", {\"error\": (1,), \"passed\": (1,)}),\n # (a status that's not known to the code)\n (\"yellow\", \"1 weird\", {\"weird\": (1,)}),\n (\"yellow\", \"1 passed, 1 weird\", {\"weird\": (1,), \"passed\": (1,)}),\n (\"yellow\", \"1 warnings\", {\"warnings\": (1,)}),\n (\"yellow\", \"1 passed, 1 warnings\", {\"warnings\": (1,), \"passed\": (1,)}),\n (\"green\", \"5 passed\", {\"passed\": (1, 2, 3, 4, 5)}),\n # \"Boring\" statuses. These have no effect on the color of the summary\n # line. Thus, if *every* test has a boring status, the summary line stays\n # at its default color, i.e. yellow, to warn the user that the test run\n # produced no useful information\n (\"yellow\", \"1 skipped\", {\"skipped\": (1,)}),\n (\"green\", \"1 passed, 1 skipped\", {\"skipped\": (1,), \"passed\": (1,)}),\n (\"yellow\", \"1 deselected\", {\"deselected\": (1,)}),\n (\"green\", \"1 passed, 1 deselected\", {\"deselected\": (1,), \"passed\": (1,)}),\n (\"yellow\", \"1 xfailed\", {\"xfailed\": (1,)}),\n (\"green\", \"1 passed, 1 xfailed\", {\"xfailed\": (1,), \"passed\": (1,)}),\n (\"yellow\", \"1 xpassed\", {\"xpassed\": (1,)}),\n (\"green\", \"1 passed, 1 xpassed\", {\"xpassed\": (1,), \"passed\": (1,)}),\n # Likewise if no tests were found at all\n (\"yellow\", \"no tests ran\", {}),\n # Test the empty-key special case\n (\"yellow\", \"no tests ran\", {\"\": (1,)}),\n (\"green\", \"1 passed\", {\"\": (1,), \"passed\": (1,)}),\n # A couple more complex combinations\n (\n \"red\",\n \"1 failed, 2 passed, 3 xfailed\",\n {\"passed\": (1, 2), \"failed\": (1,), \"xfailed\": (1, 2, 3)},\n ),\n (\n \"green\",\n \"1 passed, 2 skipped, 3 deselected, 2 xfailed\",\n {\n \"passed\": (1,),\n \"skipped\": (1, 2),\n \"deselected\": (1, 2, 3),\n \"xfailed\": (1, 2),\n },\n ),\n ],\n)\ndef test_summary_stats(exp_line, exp_color, stats_arg):\n print(\"Based on stats: %s\" % stats_arg)\n print('Expect summary: \"{}\"; with color \"{}\"'.format(exp_line, exp_color))\n (line, color) = build_summary_stats_line(stats_arg)\n print('Actually got: \"{}\"; with color \"{}\"'.format(line, color))\n assert line == exp_line\n assert color == exp_color"},{"col":4,"comment":"null","endLoc":377,"header":"def test_none_of_multiple_warns(self)","id":6135,"name":"test_none_of_multiple_warns","nodeType":"Function","startLoc":373,"text":"def test_none_of_multiple_warns(self):\n with pytest.raises(pytest.fail.Exception):\n with pytest.warns(UserWarning, match=r\"aaa\"):\n warnings.warn(\"bbbbbbbbbb\", UserWarning)\n warnings.warn(\"cccccccccc\", UserWarning)"},{"col":0,"comment":"null","endLoc":223,"header":"def test_disable_log_capturing_ini(testdir)","id":6136,"name":"test_disable_log_capturing_ini","nodeType":"Function","startLoc":196,"text":"def test_disable_log_capturing_ini(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n log_print=False\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import sys\n import logging\n\n logger = logging.getLogger(__name__)\n\n def test_foo():\n sys.stdout.write('text going to stdout')\n logger.warning('catch me if you can!')\n sys.stderr.write('text going to stderr')\n assert False\n \"\"\"\n )\n result = testdir.runpytest()\n print(result.stdout)\n assert result.ret == 1\n result.stdout.fnmatch_lines([\"*- Captured stdout call -*\", \"text going to stdout\"])\n result.stdout.fnmatch_lines([\"*- Captured stderr call -*\", \"text going to stderr\"])\n with pytest.raises(pytest.fail.Exception):\n result.stdout.fnmatch_lines([\"*- Captured *log call -*\"])"},{"col":0,"comment":"null","endLoc":256,"header":"@pytest.mark.parametrize(\"enabled\", [True, False])\ndef test_log_cli_enabled_disabled(testdir, enabled)","id":6137,"name":"test_log_cli_enabled_disabled","nodeType":"Function","startLoc":226,"text":"@pytest.mark.parametrize(\"enabled\", [True, False])\ndef test_log_cli_enabled_disabled(testdir, enabled):\n msg = \"critical message logged by test\"\n testdir.makepyfile(\n \"\"\"\n import logging\n def test_log_cli():\n logging.critical(\"{}\")\n \"\"\".format(\n msg\n )\n )\n if enabled:\n testdir.makeini(\n \"\"\"\n [pytest]\n log_cli=true\n \"\"\"\n )\n result = testdir.runpytest()\n if enabled:\n result.stdout.fnmatch_lines(\n [\n \"test_log_cli_enabled_disabled.py::test_log_cli \",\n \"*-- live log call --*\",\n \"CRITICAL *test_log_cli_enabled_disabled.py* critical message logged by test\",\n \"PASSED*\",\n ]\n )\n else:\n assert msg not in result.stdout.str()"},{"col":4,"comment":"null","endLoc":387,"header":"@pytest.mark.filterwarnings(\"ignore\")\n def test_can_capture_previously_warned(self)","id":6138,"name":"test_can_capture_previously_warned","nodeType":"Function","startLoc":379,"text":"@pytest.mark.filterwarnings(\"ignore\")\n def test_can_capture_previously_warned(self):\n def f():\n warnings.warn(UserWarning(\"ohai\"))\n return 10\n\n assert f() == 10\n assert pytest.warns(UserWarning, f) == 10\n assert pytest.warns(UserWarning, f) == 10"},{"col":0,"comment":"null","endLoc":290,"header":"def test_log_cli_default_level(testdir)","id":6139,"name":"test_log_cli_default_level","nodeType":"Function","startLoc":259,"text":"def test_log_cli_default_level(testdir):\n # Default log file level\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n def test_log_cli(request):\n plugin = request.config.pluginmanager.getplugin('logging-plugin')\n assert plugin.log_cli_handler.level == logging.NOTSET\n logging.getLogger('catchlog').info(\"INFO message won't be shown\")\n logging.getLogger('catchlog').warning(\"WARNING message will be shown\")\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n log_cli=true\n \"\"\"\n )\n\n result = testdir.runpytest()\n\n # fnmatch_lines does an assertion internally\n result.stdout.fnmatch_lines(\n [\n \"test_log_cli_default_level.py::test_log_cli \",\n \"WARNING*test_log_cli_default_level.py* message will be shown*\",\n ]\n )\n assert \"INFO message won't be shown\" not in result.stdout.str()\n # make sure that that we get a '0' exit code for the testsuite\n assert result.ret == 0"},{"col":0,"comment":"Ensure we reset the first newline added by the live logger between tests","endLoc":325,"header":"def test_log_cli_default_level_multiple_tests(testdir, request)","id":6140,"name":"test_log_cli_default_level_multiple_tests","nodeType":"Function","startLoc":293,"text":"def test_log_cli_default_level_multiple_tests(testdir, request):\n \"\"\"Ensure we reset the first newline added by the live logger between tests\"\"\"\n filename = request.node.name + \".py\"\n testdir.makepyfile(\n \"\"\"\n import logging\n\n def test_log_1():\n logging.warning(\"log message from test_log_1\")\n\n def test_log_2():\n logging.warning(\"log message from test_log_2\")\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n log_cli=true\n \"\"\"\n )\n\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"{}::test_log_1 \".format(filename),\n \"*WARNING*log message from test_log_1*\",\n \"PASSED *50%*\",\n \"{}::test_log_2 \".format(filename),\n \"*WARNING*log message from test_log_2*\",\n \"PASSED *100%*\",\n \"=* 2 passed in *=\",\n ]\n )"},{"col":0,"comment":"Check that with live logging enable we are printing the correct headers during\n start/setup/call/teardown/finish.","endLoc":399,"header":"def test_log_cli_default_level_sections(testdir, request)","id":6141,"name":"test_log_cli_default_level_sections","nodeType":"Function","startLoc":328,"text":"def test_log_cli_default_level_sections(testdir, request):\n \"\"\"Check that with live logging enable we are printing the correct headers during\n start/setup/call/teardown/finish.\"\"\"\n filename = request.node.name + \".py\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n import logging\n\n def pytest_runtest_logstart():\n logging.warning('>>>>> START >>>>>')\n\n def pytest_runtest_logfinish():\n logging.warning('<<<<< END <<<<<<<')\n \"\"\"\n )\n\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n\n @pytest.fixture\n def fix(request):\n logging.warning(\"log message from setup of {}\".format(request.node.name))\n yield\n logging.warning(\"log message from teardown of {}\".format(request.node.name))\n\n def test_log_1(fix):\n logging.warning(\"log message from test_log_1\")\n\n def test_log_2(fix):\n logging.warning(\"log message from test_log_2\")\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n log_cli=true\n \"\"\"\n )\n\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"{}::test_log_1 \".format(filename),\n \"*-- live log start --*\",\n \"*WARNING* >>>>> START >>>>>*\",\n \"*-- live log setup --*\",\n \"*WARNING*log message from setup of test_log_1*\",\n \"*-- live log call --*\",\n \"*WARNING*log message from test_log_1*\",\n \"PASSED *50%*\",\n \"*-- live log teardown --*\",\n \"*WARNING*log message from teardown of test_log_1*\",\n \"*-- live log finish --*\",\n \"*WARNING* <<<<< END <<<<<<<*\",\n \"{}::test_log_2 \".format(filename),\n \"*-- live log start --*\",\n \"*WARNING* >>>>> START >>>>>*\",\n \"*-- live log setup --*\",\n \"*WARNING*log message from setup of test_log_2*\",\n \"*-- live log call --*\",\n \"*WARNING*log message from test_log_2*\",\n \"PASSED *100%*\",\n \"*-- live log teardown --*\",\n \"*WARNING*log message from teardown of test_log_2*\",\n \"*-- live log finish --*\",\n \"*WARNING* <<<<< END <<<<<<<*\",\n \"=* 2 passed in *=\",\n ]\n )"},{"col":4,"comment":"\n test --pyargs option with namespace packages (#1567)\n\n Ref: https://packaging.python.org/guides/packaging-namespace-packages/\n ","endLoc":741,"header":"def test_cmdline_python_namespace_package(self, testdir, monkeypatch)","id":6145,"name":"test_cmdline_python_namespace_package","nodeType":"Function","startLoc":677,"text":"def test_cmdline_python_namespace_package(self, testdir, monkeypatch):\n \"\"\"\n test --pyargs option with namespace packages (#1567)\n\n Ref: https://packaging.python.org/guides/packaging-namespace-packages/\n \"\"\"\n monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", raising=False)\n\n search_path = []\n for dirname in \"hello\", \"world\":\n d = testdir.mkdir(dirname)\n search_path.append(d)\n ns = d.mkdir(\"ns_pkg\")\n ns.join(\"__init__.py\").write(\n \"__import__('pkg_resources').declare_namespace(__name__)\"\n )\n lib = ns.mkdir(dirname)\n lib.ensure(\"__init__.py\")\n lib.join(\"test_{}.py\".format(dirname)).write(\n \"def test_{}(): pass\\ndef test_other():pass\".format(dirname)\n )\n\n # The structure of the test directory is now:\n # .\n # ├── hello\n # │ └── ns_pkg\n # │ ├── __init__.py\n # │ └── hello\n # │ ├── __init__.py\n # │ └── test_hello.py\n # └── world\n # └── ns_pkg\n # ├── __init__.py\n # └── world\n # ├── __init__.py\n # └── test_world.py\n\n # NOTE: the different/reversed ordering is intentional here.\n monkeypatch.setenv(\"PYTHONPATH\", prepend_pythonpath(*search_path))\n for p in search_path:\n monkeypatch.syspath_prepend(p)\n\n # mixed module and filenames:\n monkeypatch.chdir(\"world\")\n result = testdir.runpytest(\"--pyargs\", \"-v\", \"ns_pkg.hello\", \"ns_pkg/world\")\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n [\n \"test_hello.py::test_hello*PASSED*\",\n \"test_hello.py::test_other*PASSED*\",\n \"ns_pkg/world/test_world.py::test_world*PASSED*\",\n \"ns_pkg/world/test_world.py::test_other*PASSED*\",\n \"*4 passed in*\",\n ]\n )\n\n # specify tests within a module\n testdir.chdir()\n result = testdir.runpytest(\n \"--pyargs\", \"-v\", \"ns_pkg.world.test_world::test_other\"\n )\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n [\"*test_world.py::test_other*PASSED*\", \"*1 passed*\"]\n )"},{"col":0,"comment":"Check that with live logging enable we are printing the correct headers during\n start/setup/call/teardown/finish.","endLoc":461,"header":"def test_live_logs_unknown_sections(testdir, request)","id":6146,"name":"test_live_logs_unknown_sections","nodeType":"Function","startLoc":402,"text":"def test_live_logs_unknown_sections(testdir, request):\n \"\"\"Check that with live logging enable we are printing the correct headers during\n start/setup/call/teardown/finish.\"\"\"\n filename = request.node.name + \".py\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n import logging\n\n def pytest_runtest_protocol(item, nextitem):\n logging.warning('Unknown Section!')\n\n def pytest_runtest_logstart():\n logging.warning('>>>>> START >>>>>')\n\n def pytest_runtest_logfinish():\n logging.warning('<<<<< END <<<<<<<')\n \"\"\"\n )\n\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n\n @pytest.fixture\n def fix(request):\n logging.warning(\"log message from setup of {}\".format(request.node.name))\n yield\n logging.warning(\"log message from teardown of {}\".format(request.node.name))\n\n def test_log_1(fix):\n logging.warning(\"log message from test_log_1\")\n\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n log_cli=true\n \"\"\"\n )\n\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*WARNING*Unknown Section*\",\n \"{}::test_log_1 \".format(filename),\n \"*WARNING* >>>>> START >>>>>*\",\n \"*-- live log setup --*\",\n \"*WARNING*log message from setup of test_log_1*\",\n \"*-- live log call --*\",\n \"*WARNING*log message from test_log_1*\",\n \"PASSED *100%*\",\n \"*-- live log teardown --*\",\n \"*WARNING*log message from teardown of test_log_1*\",\n \"*WARNING* <<<<< END <<<<<<<*\",\n \"=* 1 passed in *=\",\n ]\n )"},{"col":0,"comment":"Check that only a single new line is written between log messages during\n teardown/finish.","endLoc":539,"header":"def test_sections_single_new_line_after_test_outcome(testdir, request)","id":6147,"name":"test_sections_single_new_line_after_test_outcome","nodeType":"Function","startLoc":464,"text":"def test_sections_single_new_line_after_test_outcome(testdir, request):\n \"\"\"Check that only a single new line is written between log messages during\n teardown/finish.\"\"\"\n filename = request.node.name + \".py\"\n testdir.makeconftest(\n \"\"\"\n import pytest\n import logging\n\n def pytest_runtest_logstart():\n logging.warning('>>>>> START >>>>>')\n\n def pytest_runtest_logfinish():\n logging.warning('<<<<< END <<<<<<<')\n logging.warning('<<<<< END <<<<<<<')\n \"\"\"\n )\n\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n\n @pytest.fixture\n def fix(request):\n logging.warning(\"log message from setup of {}\".format(request.node.name))\n yield\n logging.warning(\"log message from teardown of {}\".format(request.node.name))\n logging.warning(\"log message from teardown of {}\".format(request.node.name))\n\n def test_log_1(fix):\n logging.warning(\"log message from test_log_1\")\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n log_cli=true\n \"\"\"\n )\n\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"{}::test_log_1 \".format(filename),\n \"*-- live log start --*\",\n \"*WARNING* >>>>> START >>>>>*\",\n \"*-- live log setup --*\",\n \"*WARNING*log message from setup of test_log_1*\",\n \"*-- live log call --*\",\n \"*WARNING*log message from test_log_1*\",\n \"PASSED *100%*\",\n \"*-- live log teardown --*\",\n \"*WARNING*log message from teardown of test_log_1*\",\n \"*-- live log finish --*\",\n \"*WARNING* <<<<< END <<<<<<<*\",\n \"*WARNING* <<<<< END <<<<<<<*\",\n \"=* 1 passed in *=\",\n ]\n )\n assert (\n re.search(\n r\"(.+)live log teardown(.+)\\nWARNING(.+)\\nWARNING(.+)\",\n result.stdout.str(),\n re.MULTILINE,\n )\n is not None\n )\n assert (\n re.search(\n r\"(.+)live log finish(.+)\\nWARNING(.+)\\nWARNING(.+)\",\n result.stdout.str(),\n re.MULTILINE,\n )\n is not None\n )"},{"col":0,"comment":"null","endLoc":1325,"header":"def test_skip_counting_towards_summary()","id":6148,"name":"test_skip_counting_towards_summary","nodeType":"Function","startLoc":1314,"text":"def test_skip_counting_towards_summary():\n class DummyReport(BaseReport):\n count_towards_summary = True\n\n r1 = DummyReport()\n r2 = DummyReport()\n res = build_summary_stats_line({\"failed\": (r1, r2)})\n assert res == (\"2 failed\", \"red\")\n\n r1.count_towards_summary = False\n res = build_summary_stats_line({\"failed\": (r1, r2)})\n assert res == (\"1 failed\", \"red\")"},{"col":0,"comment":"null","endLoc":589,"header":"def test_log_cli_level(testdir)","id":6150,"name":"test_log_cli_level","nodeType":"Function","startLoc":542,"text":"def test_log_cli_level(testdir):\n # Default log file level\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n def test_log_cli(request):\n plugin = request.config.pluginmanager.getplugin('logging-plugin')\n assert plugin.log_cli_handler.level == logging.INFO\n logging.getLogger('catchlog').debug(\"This log message won't be shown\")\n logging.getLogger('catchlog').info(\"This log message will be shown\")\n print('PASSED')\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n log_cli=true\n \"\"\"\n )\n\n result = testdir.runpytest(\"-s\", \"--log-cli-level=INFO\")\n\n # fnmatch_lines does an assertion internally\n result.stdout.fnmatch_lines(\n [\n \"*test_log_cli_level.py*This log message will be shown\",\n \"PASSED\", # 'PASSED' on its own line because the log message prints a new line\n ]\n )\n assert \"This log message won't be shown\" not in result.stdout.str()\n\n # make sure that that we get a '0' exit code for the testsuite\n assert result.ret == 0\n\n result = testdir.runpytest(\"-s\", \"--log-level=INFO\")\n\n # fnmatch_lines does an assertion internally\n result.stdout.fnmatch_lines(\n [\n \"*test_log_cli_level.py* This log message will be shown\",\n \"PASSED\", # 'PASSED' on its own line because the log message prints a new line\n ]\n )\n assert \"This log message won't be shown\" not in result.stdout.str()\n\n # make sure that that we get a '0' exit code for the testsuite\n assert result.ret == 0"},{"col":0,"comment":"null","endLoc":17,"header":"def test_recwarn_stacklevel(recwarn)","id":6151,"name":"test_recwarn_stacklevel","nodeType":"Function","startLoc":14,"text":"def test_recwarn_stacklevel(recwarn):\n warnings.warn(\"hello\")\n warn = recwarn.pop()\n assert warn.filename == __file__"},{"col":0,"comment":"null","endLoc":26,"header":"def prepend_pythonpath(*dirs)","id":6152,"name":"prepend_pythonpath","nodeType":"Function","startLoc":22,"text":"def prepend_pythonpath(*dirs):\n cur = os.getenv(\"PYTHONPATH\")\n if cur:\n dirs += (cur,)\n return os.pathsep.join(str(p) for p in dirs)"},{"col":0,"comment":"null","endLoc":31,"header":"def test_recwarn_functional(testdir)","id":6153,"name":"test_recwarn_functional","nodeType":"Function","startLoc":20,"text":"def test_recwarn_functional(testdir):\n testdir.makepyfile(\n \"\"\"\n import warnings\n def test_method(recwarn):\n warnings.warn(\"hello\")\n warn = recwarn.pop()\n assert isinstance(warn.message, UserWarning)\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":0,"comment":"null","endLoc":625,"header":"def test_log_cli_ini_level(testdir)","id":6156,"name":"test_log_cli_ini_level","nodeType":"Function","startLoc":592,"text":"def test_log_cli_ini_level(testdir):\n testdir.makeini(\n \"\"\"\n [pytest]\n log_cli=true\n log_cli_level = INFO\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n def test_log_cli(request):\n plugin = request.config.pluginmanager.getplugin('logging-plugin')\n assert plugin.log_cli_handler.level == logging.INFO\n logging.getLogger('catchlog').debug(\"This log message won't be shown\")\n logging.getLogger('catchlog').info(\"This log message will be shown\")\n print('PASSED')\n \"\"\"\n )\n\n result = testdir.runpytest(\"-s\")\n\n # fnmatch_lines does an assertion internally\n result.stdout.fnmatch_lines(\n [\n \"*test_log_cli_ini_level.py* This log message will be shown\",\n \"PASSED\", # 'PASSED' on its own line because the log message prints a new line\n ]\n )\n assert \"This log message won't be shown\" not in result.stdout.str()\n\n # make sure that that we get a '0' exit code for the testsuite\n assert result.ret == 0"},{"col":0,"comment":"null","endLoc":1617,"header":"def test_skip_reasons_folding()","id":6157,"name":"test_skip_reasons_folding","nodeType":"Function","startLoc":1586,"text":"def test_skip_reasons_folding():\n path = \"xyz\"\n lineno = 3\n message = \"justso\"\n longrepr = (path, lineno, message)\n\n class X(object):\n pass\n\n ev1 = X()\n ev1.when = \"execute\"\n ev1.skipped = True\n ev1.longrepr = longrepr\n\n ev2 = X()\n ev2.when = \"execute\"\n ev2.longrepr = longrepr\n ev2.skipped = True\n\n # ev3 might be a collection report\n ev3 = X()\n ev3.when = \"collect\"\n ev3.longrepr = longrepr\n ev3.skipped = True\n\n values = _folded_skips([ev1, ev2, ev3])\n assert len(values) == 1\n num, fspath, lineno, reason = values[0]\n assert num == 3\n assert fspath == path\n assert lineno == lineno\n assert reason == message"},{"id":6158,"name":"retry.cmd","nodeType":"TextFile","path":"scripts","text":"@echo off\nrem Source: https://github.com/appveyor/ci/blob/master/scripts/appveyor-retry.cmd\nrem initiate the retry number\nset retryNumber=0\nset maxRetries=3\n\n:RUN\n%*\nset LastErrorLevel=%ERRORLEVEL%\nIF %LastErrorLevel% == 0 GOTO :EOF\nset /a retryNumber=%retryNumber%+1\nIF %reTryNumber% == %maxRetries% (GOTO :FAILED)\n\n:RETRY\nset /a retryNumberDisp=%retryNumber%+1\n@echo Command \"%*\" failed with exit code %LastErrorLevel%. Retrying %retryNumberDisp% of %maxRetries%\nGOTO :RUN\n\n: FAILED\n@echo Sorry, we tried running command for %maxRetries% times and all attempts were unsuccessful!\nEXIT /B %LastErrorLevel%\n"},{"col":0,"comment":"Check that live logs are enabled if --log-level or --log-cli-level is passed on the CLI.\n It should not be auto enabled if the same configs are set on the INI file.\n ","endLoc":672,"header":"@pytest.mark.parametrize(\n \"cli_args\",\n [\"\", \"--log-level=WARNING\", \"--log-file-level=WARNING\", \"--log-cli-level=WARNING\"],\n)\ndef test_log_cli_auto_enable(testdir, request, cli_args)","id":6159,"name":"test_log_cli_auto_enable","nodeType":"Function","startLoc":628,"text":"@pytest.mark.parametrize(\n \"cli_args\",\n [\"\", \"--log-level=WARNING\", \"--log-file-level=WARNING\", \"--log-cli-level=WARNING\"],\n)\ndef test_log_cli_auto_enable(testdir, request, cli_args):\n \"\"\"Check that live logs are enabled if --log-level or --log-cli-level is passed on the CLI.\n It should not be auto enabled if the same configs are set on the INI file.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import logging\n\n def test_log_1():\n logging.info(\"log message from test_log_1 not to be shown\")\n logging.warning(\"log message from test_log_1\")\n\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n log_level=INFO\n log_cli_level=INFO\n \"\"\"\n )\n\n result = testdir.runpytest(cli_args)\n stdout = result.stdout.str()\n if cli_args == \"--log-cli-level=WARNING\":\n result.stdout.fnmatch_lines(\n [\n \"*::test_log_1 \",\n \"*-- live log call --*\",\n \"*WARNING*log message from test_log_1*\",\n \"PASSED *100%*\",\n \"=* 1 passed in *=\",\n ]\n )\n assert \"INFO\" not in stdout\n else:\n result.stdout.fnmatch_lines(\n [\"*test_log_cli_auto_enable*100%*\", \"=* 1 passed in *=\"]\n )\n assert \"INFO\" not in stdout\n assert \"WARNING\" not in stdout"},{"id":6160,"name":"testing/example_scripts/collect/collect_init_tests/tests","nodeType":"Package"},{"fileName":"__init__.py","filePath":"testing/example_scripts/collect/collect_init_tests/tests","id":6161,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ndef test_init():\n pass\n"},{"col":0,"comment":"null","endLoc":3,"header":"def test_init()","id":6162,"name":"test_init","nodeType":"Function","startLoc":2,"text":"def test_init():\n pass"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":336,"id":6163,"name":"extra_info","nodeType":"Attribute","startLoc":336,"text":"self.extra_info"},{"attributeType":"{_usage}","col":8,"comment":"null","endLoc":326,"id":6164,"name":"_parser","nodeType":"Attribute","startLoc":326,"text":"self._parser"},{"className":"DropShorterLongHelpFormatter","col":0,"comment":"shorten help for long options that differ only in extra hyphens\n\n - collapse **long** options that are the same except for extra hyphens\n - special action attribute map_long_option allows surpressing additional\n long options\n - shortcut if there are only two options and one of them is a short one\n - cache result on action object as this is called at least 2 times\n ","endLoc":410,"id":6165,"nodeType":"Class","startLoc":361,"text":"class DropShorterLongHelpFormatter(argparse.HelpFormatter):\n \"\"\"shorten help for long options that differ only in extra hyphens\n\n - collapse **long** options that are the same except for extra hyphens\n - special action attribute map_long_option allows surpressing additional\n long options\n - shortcut if there are only two options and one of them is a short one\n - cache result on action object as this is called at least 2 times\n \"\"\"\n\n def _format_action_invocation(self, action):\n orgstr = argparse.HelpFormatter._format_action_invocation(self, action)\n if orgstr and orgstr[0] != \"-\": # only optional arguments\n return orgstr\n res = getattr(action, \"_formatted_action_invocation\", None)\n if res:\n return res\n options = orgstr.split(\", \")\n if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2):\n # a shortcut for '-h, --help' or '--abc', '-a'\n action._formatted_action_invocation = orgstr\n return orgstr\n return_list = []\n option_map = getattr(action, \"map_long_option\", {})\n if option_map is None:\n option_map = {}\n short_long = {}\n for option in options:\n if len(option) == 2 or option[2] == \" \":\n continue\n if not option.startswith(\"--\"):\n raise ArgumentError(\n 'long optional argument without \"--\": [%s]' % (option), self\n )\n xxoption = option[2:]\n if xxoption.split()[0] not in option_map:\n shortened = xxoption.replace(\"-\", \"\")\n if shortened not in short_long or len(short_long[shortened]) < len(\n xxoption\n ):\n short_long[shortened] = xxoption\n # now short_long has been filled out to the longest with dashes\n # **and** we keep the right option ordering from add_argument\n for option in options:\n if len(option) == 2 or option[2] == \" \":\n return_list.append(option)\n if option[2:] == short_long.get(option.replace(\"-\", \"\")):\n return_list.append(option.replace(\" \", \"=\", 1))\n action._formatted_action_invocation = \", \".join(return_list)\n return action._formatted_action_invocation"},{"className":"HelpFormatter","col":0,"comment":"null","endLoc":304,"id":6166,"nodeType":"Class","startLoc":253,"text":"class HelpFormatter:\n # undocumented\n _prog: str\n _indent_increment: int\n _max_help_position: int\n _width: int\n _current_indent: int\n _level: int\n _action_max_length: int\n _root_section: _Section\n _current_section: _Section\n _whitespace_matcher: Pattern[str]\n _long_break_matcher: Pattern[str]\n\n class _Section:\n formatter: HelpFormatter\n heading: str | None\n parent: Self | None\n items: list[tuple[Callable[..., str], Iterable[Any]]]\n def __init__(self, formatter: HelpFormatter, parent: Self | None, heading: str | None = None) -> None: ...\n def format_help(self) -> str: ...\n\n def __init__(self, prog: str, indent_increment: int = 2, max_help_position: int = 24, width: int | None = None) -> None: ...\n def _indent(self) -> None: ...\n def _dedent(self) -> None: ...\n def _add_item(self, func: Callable[..., str], args: Iterable[Any]) -> None: ...\n def start_section(self, heading: str | None) -> None: ...\n def end_section(self) -> None: ...\n def add_text(self, text: str | None) -> None: ...\n def add_usage(\n self, usage: str | None, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup], prefix: str | None = None\n ) -> None: ...\n def add_argument(self, action: Action) -> None: ...\n def add_arguments(self, actions: Iterable[Action]) -> None: ...\n def format_help(self) -> str: ...\n def _join_parts(self, part_strings: Iterable[str]) -> str: ...\n def _format_usage(\n self, usage: str | None, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup], prefix: str | None\n ) -> str: ...\n def _format_actions_usage(self, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup]) -> str: ...\n def _format_text(self, text: str) -> str: ...\n def _format_action(self, action: Action) -> str: ...\n def _format_action_invocation(self, action: Action) -> str: ...\n def _metavar_formatter(self, action: Action, default_metavar: str) -> Callable[[int], tuple[str, ...]]: ...\n def _format_args(self, action: Action, default_metavar: str) -> str: ...\n def _expand_help(self, action: Action) -> str: ...\n def _iter_indented_subactions(self, action: Action) -> Generator[Action, None, None]: ...\n def _split_lines(self, text: str, width: int) -> list[str]: ...\n def _fill_text(self, text: str, width: int, indent: str) -> str: ...\n def _get_help_string(self, action: Action) -> str | None: ...\n def _get_default_metavar_for_optional(self, action: Action) -> str: ...\n def _get_default_metavar_for_positional(self, action: Action) -> str: ..."},{"col":4,"comment":"null","endLoc":275,"header":"def __init__(self, prog: str, indent_increment: int = 2, max_help_position: int = 24, width: int | None = None) -> None","id":6167,"name":"__init__","nodeType":"Function","startLoc":275,"text":"def __init__(self, prog: str, indent_increment: int = 2, max_help_position: int = 24, width: int | None = None) -> None: ..."},{"col":4,"comment":"null","endLoc":276,"header":"def _indent(self) -> None","id":6168,"name":"_indent","nodeType":"Function","startLoc":276,"text":"def _indent(self) -> None: ..."},{"col":4,"comment":"null","endLoc":277,"header":"def _dedent(self) -> None","id":6169,"name":"_dedent","nodeType":"Function","startLoc":277,"text":"def _dedent(self) -> None: ..."},{"col":4,"comment":"null","endLoc":278,"header":"def _add_item(self, func: Callable[..., str], args: Iterable[Any]) -> None","id":6170,"name":"_add_item","nodeType":"Function","startLoc":278,"text":"def _add_item(self, func: Callable[..., str], args: Iterable[Any]) -> None: ..."},{"col":4,"comment":"null","endLoc":279,"header":"def start_section(self, heading: str | None) -> None","id":6171,"name":"start_section","nodeType":"Function","startLoc":279,"text":"def start_section(self, heading: str | None) -> None: ..."},{"col":4,"comment":"null","endLoc":280,"header":"def end_section(self) -> None","id":6172,"name":"end_section","nodeType":"Function","startLoc":280,"text":"def end_section(self) -> None: ..."},{"col":4,"comment":"null","endLoc":281,"header":"def add_text(self, text: str | None) -> None","id":6173,"name":"add_text","nodeType":"Function","startLoc":281,"text":"def add_text(self, text: str | None) -> None: ..."},{"col":4,"comment":"null","endLoc":284,"header":"def add_usage(\n self, usage: str | None, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup], prefix: str | None = None\n ) -> None","id":6174,"name":"add_usage","nodeType":"Function","startLoc":282,"text":"def add_usage(\n self, usage: str | None, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup], prefix: str | None = None\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":285,"header":"def add_argument(self, action: Action) -> None","id":6175,"name":"add_argument","nodeType":"Function","startLoc":285,"text":"def add_argument(self, action: Action) -> None: ..."},{"col":4,"comment":"null","endLoc":286,"header":"def add_arguments(self, actions: Iterable[Action]) -> None","id":6176,"name":"add_arguments","nodeType":"Function","startLoc":286,"text":"def add_arguments(self, actions: Iterable[Action]) -> None: ..."},{"col":4,"comment":"null","endLoc":287,"header":"def format_help(self) -> str","id":6177,"name":"format_help","nodeType":"Function","startLoc":287,"text":"def format_help(self) -> str: ..."},{"col":4,"comment":"null","endLoc":288,"header":"def _join_parts(self, part_strings: Iterable[str]) -> str","id":6178,"name":"_join_parts","nodeType":"Function","startLoc":288,"text":"def _join_parts(self, part_strings: Iterable[str]) -> str: ..."},{"col":4,"comment":"null","endLoc":291,"header":"def _format_usage(\n self, usage: str | None, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup], prefix: str | None\n ) -> str","id":6179,"name":"_format_usage","nodeType":"Function","startLoc":289,"text":"def _format_usage(\n self, usage: str | None, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup], prefix: str | None\n ) -> str: ..."},{"col":4,"comment":"null","endLoc":292,"header":"def _format_actions_usage(self, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup]) -> str","id":6180,"name":"_format_actions_usage","nodeType":"Function","startLoc":292,"text":"def _format_actions_usage(self, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup]) -> str: ..."},{"col":4,"comment":"null","endLoc":293,"header":"def _format_text(self, text: str) -> str","id":6181,"name":"_format_text","nodeType":"Function","startLoc":293,"text":"def _format_text(self, text: str) -> str: ..."},{"col":4,"comment":"null","endLoc":294,"header":"def _format_action(self, action: Action) -> str","id":6182,"name":"_format_action","nodeType":"Function","startLoc":294,"text":"def _format_action(self, action: Action) -> str: ..."},{"col":4,"comment":"null","endLoc":295,"header":"def _format_action_invocation(self, action: Action) -> str","id":6183,"name":"_format_action_invocation","nodeType":"Function","startLoc":295,"text":"def _format_action_invocation(self, action: Action) -> str: ..."},{"col":4,"comment":"null","endLoc":296,"header":"def _metavar_formatter(self, action: Action, default_metavar: str) -> Callable[[int], tuple[str, ...]]","id":6184,"name":"_metavar_formatter","nodeType":"Function","startLoc":296,"text":"def _metavar_formatter(self, action: Action, default_metavar: str) -> Callable[[int], tuple[str, ...]]: ..."},{"col":4,"comment":"null","endLoc":297,"header":"def _format_args(self, action: Action, default_metavar: str) -> str","id":6185,"name":"_format_args","nodeType":"Function","startLoc":297,"text":"def _format_args(self, action: Action, default_metavar: str) -> str: ..."},{"col":4,"comment":"null","endLoc":298,"header":"def _expand_help(self, action: Action) -> str","id":6186,"name":"_expand_help","nodeType":"Function","startLoc":298,"text":"def _expand_help(self, action: Action) -> str: ..."},{"col":4,"comment":"null","endLoc":299,"header":"def _iter_indented_subactions(self, action: Action) -> Generator[Action, None, None]","id":6187,"name":"_iter_indented_subactions","nodeType":"Function","startLoc":299,"text":"def _iter_indented_subactions(self, action: Action) -> Generator[Action, None, None]: ..."},{"col":4,"comment":"null","endLoc":300,"header":"def _split_lines(self, text: str, width: int) -> list[str]","id":6188,"name":"_split_lines","nodeType":"Function","startLoc":300,"text":"def _split_lines(self, text: str, width: int) -> list[str]: ..."},{"col":4,"comment":"null","endLoc":301,"header":"def _fill_text(self, text: str, width: int, indent: str) -> str","id":6189,"name":"_fill_text","nodeType":"Function","startLoc":301,"text":"def _fill_text(self, text: str, width: int, indent: str) -> str: ..."},{"col":4,"comment":"null","endLoc":302,"header":"def _get_help_string(self, action: Action) -> str | None","id":6190,"name":"_get_help_string","nodeType":"Function","startLoc":302,"text":"def _get_help_string(self, action: Action) -> str | None: ..."},{"col":4,"comment":"null","endLoc":303,"header":"def _get_default_metavar_for_optional(self, action: Action) -> str","id":6191,"name":"_get_default_metavar_for_optional","nodeType":"Function","startLoc":303,"text":"def _get_default_metavar_for_optional(self, action: Action) -> str: ..."},{"col":4,"comment":"null","endLoc":304,"header":"def _get_default_metavar_for_positional(self, action: Action) -> str","id":6192,"name":"_get_default_metavar_for_positional","nodeType":"Function","startLoc":304,"text":"def _get_default_metavar_for_positional(self, action: Action) -> str: ..."},{"attributeType":"str","col":4,"comment":"null","endLoc":255,"id":6193,"name":"_prog","nodeType":"Attribute","startLoc":255,"text":"_prog"},{"col":0,"comment":"null","endLoc":1686,"header":"def test_line_with_reprcrash(monkeypatch)","id":6194,"name":"test_line_with_reprcrash","nodeType":"Function","startLoc":1620,"text":"def test_line_with_reprcrash(monkeypatch):\n import _pytest.terminal\n from wcwidth import wcswidth\n\n mocked_verbose_word = \"FAILED\"\n\n mocked_pos = \"some::nodeid\"\n\n def mock_get_pos(*args):\n return mocked_pos\n\n monkeypatch.setattr(_pytest.terminal, \"_get_pos\", mock_get_pos)\n\n class config(object):\n pass\n\n class rep(object):\n def _get_verbose_word(self, *args):\n return mocked_verbose_word\n\n class longrepr:\n class reprcrash:\n pass\n\n def check(msg, width, expected):\n __tracebackhide__ = True\n if msg:\n rep.longrepr.reprcrash.message = msg\n actual = _get_line_with_reprcrash_message(config, rep(), width)\n\n assert actual == expected\n if actual != \"%s %s\" % (mocked_verbose_word, mocked_pos):\n assert len(actual) <= width\n assert wcswidth(actual) <= width\n\n # AttributeError with message\n check(None, 80, \"FAILED some::nodeid\")\n\n check(\"msg\", 80, \"FAILED some::nodeid - msg\")\n check(\"msg\", 3, \"FAILED some::nodeid\")\n\n check(\"msg\", 24, \"FAILED some::nodeid\")\n check(\"msg\", 25, \"FAILED some::nodeid - msg\")\n\n check(\"some longer msg\", 24, \"FAILED some::nodeid\")\n check(\"some longer msg\", 25, \"FAILED some::nodeid - ...\")\n check(\"some longer msg\", 26, \"FAILED some::nodeid - s...\")\n\n check(\"some\\nmessage\", 25, \"FAILED some::nodeid - ...\")\n check(\"some\\nmessage\", 26, \"FAILED some::nodeid - some\")\n check(\"some\\nmessage\", 80, \"FAILED some::nodeid - some\")\n\n # Test unicode safety.\n check(u\"😄😄😄😄😄\\n2nd line\", 25, u\"FAILED some::nodeid - ...\")\n check(u\"😄😄😄😄😄\\n2nd line\", 26, u\"FAILED some::nodeid - ...\")\n check(u\"😄😄😄😄😄\\n2nd line\", 27, u\"FAILED some::nodeid - 😄...\")\n check(u\"😄😄😄😄😄\\n2nd line\", 28, u\"FAILED some::nodeid - 😄...\")\n check(u\"😄😄😄😄😄\\n2nd line\", 29, u\"FAILED some::nodeid - 😄😄...\")\n\n # NOTE: constructed, not sure if this is supported.\n # It would fail if not using u\"\" in Python 2 for mocked_pos.\n mocked_pos = u\"nodeid::😄::withunicode\"\n check(u\"😄😄😄😄😄\\n2nd line\", 29, u\"FAILED nodeid::😄::withunicode\")\n check(u\"😄😄😄😄😄\\n2nd line\", 40, u\"FAILED nodeid::😄::withunicode - 😄😄...\")\n check(u\"😄😄😄😄😄\\n2nd line\", 41, u\"FAILED nodeid::😄::withunicode - 😄😄...\")\n check(u\"😄😄😄😄😄\\n2nd line\", 42, u\"FAILED nodeid::😄::withunicode - 😄😄😄...\")\n check(u\"😄😄😄😄😄\\n2nd line\", 80, u\"FAILED nodeid::😄::withunicode - 😄😄😄😄😄\")"},{"attributeType":"int","col":4,"comment":"null","endLoc":256,"id":6195,"name":"_indent_increment","nodeType":"Attribute","startLoc":256,"text":"_indent_increment"},{"attributeType":"int","col":4,"comment":"null","endLoc":257,"id":6196,"name":"_max_help_position","nodeType":"Attribute","startLoc":257,"text":"_max_help_position"},{"attributeType":"int","col":4,"comment":"null","endLoc":258,"id":6197,"name":"_width","nodeType":"Attribute","startLoc":258,"text":"_width"},{"attributeType":"int","col":4,"comment":"null","endLoc":259,"id":6198,"name":"_current_indent","nodeType":"Attribute","startLoc":259,"text":"_current_indent"},{"attributeType":"int","col":4,"comment":"null","endLoc":260,"id":6199,"name":"_level","nodeType":"Attribute","startLoc":260,"text":"_level"},{"attributeType":"int","col":4,"comment":"null","endLoc":261,"id":6200,"name":"_action_max_length","nodeType":"Attribute","startLoc":261,"text":"_action_max_length"},{"attributeType":"_Section","col":4,"comment":"null","endLoc":262,"id":6201,"name":"_root_section","nodeType":"Attribute","startLoc":262,"text":"_root_section"},{"attributeType":"_Section","col":4,"comment":"null","endLoc":263,"id":6203,"name":"_current_section","nodeType":"Attribute","startLoc":263,"text":"_current_section"},{"attributeType":"Pattern","col":4,"comment":"null","endLoc":264,"id":6204,"name":"_whitespace_matcher","nodeType":"Attribute","startLoc":264,"text":"_whitespace_matcher"},{"attributeType":"Pattern","col":4,"comment":"null","endLoc":265,"id":6205,"name":"_long_break_matcher","nodeType":"Attribute","startLoc":265,"text":"_long_break_matcher"},{"col":4,"comment":"null","endLoc":410,"header":"def _format_action_invocation(self, action)","id":6206,"name":"_format_action_invocation","nodeType":"Function","startLoc":371,"text":"def _format_action_invocation(self, action):\n orgstr = argparse.HelpFormatter._format_action_invocation(self, action)\n if orgstr and orgstr[0] != \"-\": # only optional arguments\n return orgstr\n res = getattr(action, \"_formatted_action_invocation\", None)\n if res:\n return res\n options = orgstr.split(\", \")\n if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2):\n # a shortcut for '-h, --help' or '--abc', '-a'\n action._formatted_action_invocation = orgstr\n return orgstr\n return_list = []\n option_map = getattr(action, \"map_long_option\", {})\n if option_map is None:\n option_map = {}\n short_long = {}\n for option in options:\n if len(option) == 2 or option[2] == \" \":\n continue\n if not option.startswith(\"--\"):\n raise ArgumentError(\n 'long optional argument without \"--\": [%s]' % (option), self\n )\n xxoption = option[2:]\n if xxoption.split()[0] not in option_map:\n shortened = xxoption.replace(\"-\", \"\")\n if shortened not in short_long or len(short_long[shortened]) < len(\n xxoption\n ):\n short_long[shortened] = xxoption\n # now short_long has been filled out to the longest with dashes\n # **and** we keep the right option ordering from add_argument\n for option in options:\n if len(option) == 2 or option[2] == \" \":\n return_list.append(option)\n if option[2:] == short_long.get(option.replace(\"-\", \"\")):\n return_list.append(option.replace(\" \", \"=\", 1))\n action._formatted_action_invocation = \", \".join(return_list)\n return action._formatted_action_invocation"},{"col":0,"comment":"null","endLoc":705,"header":"def test_log_file_cli(testdir)","id":6207,"name":"test_log_file_cli","nodeType":"Function","startLoc":675,"text":"def test_log_file_cli(testdir):\n # Default log file level\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n def test_log_file(request):\n plugin = request.config.pluginmanager.getplugin('logging-plugin')\n assert plugin.log_file_handler.level == logging.WARNING\n logging.getLogger('catchlog').info(\"This log message won't be shown\")\n logging.getLogger('catchlog').warning(\"This log message will be shown\")\n print('PASSED')\n \"\"\"\n )\n\n log_file = testdir.tmpdir.join(\"pytest.log\").strpath\n\n result = testdir.runpytest(\n \"-s\", \"--log-file={}\".format(log_file), \"--log-file-level=WARNING\"\n )\n\n # fnmatch_lines does an assertion internally\n result.stdout.fnmatch_lines([\"test_log_file_cli.py PASSED\"])\n\n # make sure that that we get a '0' exit code for the testsuite\n assert result.ret == 0\n assert os.path.isfile(log_file)\n with open(log_file) as rfh:\n contents = rfh.read()\n assert \"This log message will be shown\" in contents\n assert \"This log message won't be shown\" not in contents"},{"attributeType":"DistInfo","col":0,"comment":"null","endLoc":27,"id":6208,"name":"DistInfo","nodeType":"Attribute","startLoc":27,"text":"DistInfo"},{"col":0,"comment":"","endLoc":4,"header":"test_terminal.py#","id":6209,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"\nterminal reporting of the full testing process.\n\"\"\"\n\nDistInfo = collections.namedtuple(\"DistInfo\", [\"project_name\", \"version\"])"},{"col":4,"comment":"null","endLoc":690,"header":"def test_skipif_using_platform(self, testdir)","id":6210,"name":"test_skipif_using_platform","nodeType":"Function","startLoc":681,"text":"def test_skipif_using_platform(self, testdir):\n item = testdir.getitem(\n \"\"\"\n import pytest\n @pytest.mark.skipif(\"platform.platform() == platform.platform()\")\n def test_func():\n pass\n \"\"\"\n )\n pytest.raises(pytest.skip.Exception, lambda: pytest_runtest_setup(item))"},{"id":6211,"name":"AUTHORS","nodeType":"TextFile","path":"","text":"Holger Krekel, holger at merlinux eu\nmerlinux GmbH, Germany, office at merlinux eu\n\nContributors include::\n\nAaron Coleman\nAbdeali JK\nAbhijeet Kasurde\nAdam Johnson\nAdam Uhlir\nAhn Ki-Wook\nAkiomi Kamakura\nAlan Velasco\nAlexander Johnson\nAlexei Kozlenok\nAllan Feldman\nAly Sivji\nAnatoly Bubenkoff\nAnders Hovmöller\nAndras Mitzki\nAndras Tim\nAndrea Cimatoribus\nAndreas Zeidler\nAndrey Paramonov\nAndrzej Ostrowski\nAndy Freeland\nAnthon van der Neut\nAnthony Shaw\nAnthony Sottile\nAnton Lodder\nAntony Lee\nArel Cordero\nArmin Rigo\nAron Coyle\nAron Curzon\nAviral Verma\nAviv Palivoda\nBarney Gale\nBen Webb\nBenjamin Peterson\nBernard Pratz\nBob Ippolito\nBrian Dorsey\nBrian Maissy\nBrian Okken\nBrianna Laugher\nBruno Oliveira\nCal Leeming\nCarl Friedrich Bolz\nCarlos Jenkins\nCeridwen\nCharles Cloud\nCharnjit SiNGH (CCSJ)\nChris Lamb\nChristian Boelsen\nChristian Fetzer\nChristian Theunert\nChristian Tismer\nChristopher Gilling\nChristopher Dignam\nCrazyMerlyn\nCyrus Maden\nDamian Skrzypczak\nDhiren Serai\nDaniel Grana\nDaniel Hahler\nDaniel Nuri\nDaniel Wandschneider\nDanielle Jenkins\nDave Hunt\nDavid Díaz-Barquero\nDavid Mohr\nDavid Szotten\nDavid Vierra\nDaw-Ran Liou\nDenis Kirisov\nDiego Russo\nDmitry Dygalo\nDmitry Pribysh\nDuncan Betts\nEdison Gustavo Muenz\nEdoardo Batini\nEduardo Schettino\nEli Boyarski\nElizaveta Shashkova\nEndre Galaczi\nEric Hunsberger\nEric Siegerman\nErik M. Bray\nEvan Kepner\nFabien Zarifian\nFabio Zadrozny\nFeng Ma\nFlorian Bruhin\nFloris Bruynooghe\nGabriel Reis\nGeorge Kussumoto\nGeorgy Dyuldin\nGraham Horler\nGreg Price\nGrig Gheorghiu\nGrigorii Eremeev (budulianin)\nGuido Wesdorp\nGuoqiang Zhang\nHarald Armin Massa\nHenk-Jaap Wagenaar\nHugo van Kemenade\nHui Wang (coldnight)\nIan Bicking\nIan Lesperance\nIlya Konstantinov\nIonuț Turturică\nIwan Briquemont\nJaap Broekhuizen\nJan Balster\nJanne Vanhala\nJason R. Coombs\nJavier Domingo Cansino\nJavier Romero\nJeff Rackauckas\nJeff Widman\nJenni Rinker\nJohn Eddie Ayson\nJohn Towler\nJon Sonesen\nJonas Obrist\nJordan Guymon\nJordan Moldow\nJordan Speicher\nJoseph Hunkeler\nJoshua Bronson\nJurko Gospodnetić\nJustyna Janczyszyn\nKale Kundert\nKatarzyna Jachim\nKaterina Koukiou\nKevin Cox\nKevin J. Foley\nKodi B. Arfer\nKostis Anagnostopoulos\nKristoffer Nordström\nKyle Altendorf\nLawrence Mitchell\nLee Kamentsky\nLev Maximov\nLlandy Riveron Del Risco\nLoic Esteve\nLukas Bednar\nLuke Murphy\nMaciek Fijalkowski\nMaho\nMaik Figura\nMandeep Bhutani\nManuel Krebber\nMarc Schlaich\nMarcelo Duarte Trevisani\nMarcin Bachry\nMark Abramowitz\nMarkus Unterwaditzer\nMartijn Faassen\nMartin Altmayer\nMartin K. Scherer\nMartin Prusse\nMathieu Clabaut\nMatt Bachmann\nMatt Duck\nMatt Williams\nMatthias Hafner\nMaxim Filipenko\nmbyt\nMichael Aquilina\nMichael Birtwell\nMichael Droettboom\nMichael Seifert\nMichal Wajszczuk\nMihai Capotă\nMike Hoyle (hoylemd)\nMike Lundy\nMiro Hrončok\nNathaniel Waisbrot\nNed Batchelder\nNeven Mundar\nNicholas Devenish\nNicholas Murphy\nNiclas Olofsson\nNicolas Delaby\nNikolay Kondratyev\nOleg Pidsadnyi\nOleg Sushchenko\nOliver Bestwalter\nOmar Kohl\nOmer Hadari\nOndřej Súkup\nOscar Benjamin\nPatrick Hayes\nPaweł Adamczak\nPedro Algarvio\nPieter Mulder\nPiotr Banaszkiewicz\nPulkit Goyal\nPunyashloka Biswal\nQuentin Pradet\nRalf Schmitt\nRan Benita\nRaphael Castaneda\nRaphael Pierzina\nRaquel Alegre\nRavi Chandra\nRoberto Polli\nRoland Puntaier\nRomain Dorgueil\nRoman Bolshakov\nRonny Pfannschmidt\nRoss Lawley\nRussel Winder\nRyan Wooden\nSamuel Dion-Girardeau\nSamuel Searles-Bryant\nSamuele Pedroni\nSankt Petersbug\nSegev Finer\nSerhii Mozghovyi\nSimon Gomizelj\nSkylar Downes\nSrinivas Reddy Thatiparthy\nStefan Farmbauer\nStefan Zimmermann\nStefano Taschini\nSteffen Allner\nStephan Obermann\nSven-Hendrik Haase\nTadek Teleżyński\nTakafumi Arakaki\nTarcisio Fischer\nTareq Alayan\nTed Xiao\nThomas Grainger\nThomas Hisch\nTim Strazny\nTom Dalton\nTom Viner\nTomer Keren\nTrevor Bekolay\nTyler Goodlet\nTzu-ping Chung\nVasily Kuznetsov\nVictor Maryama\nVictor Uriarte\nVidar T. Fauske\nVirgil Dupras\nVitaly Lashmanov\nVlad Dragos\nVolodymyr Piskun\nWil Cooley\nWilliam Lee\nWim Glenn\nWouter van Ackooy\nXuan Luong\nXuecong Liao\nZac Hatfield-Dodds\nZoltán Máté\n"},{"col":45,"endLoc":690,"id":6212,"nodeType":"Lambda","startLoc":690,"text":"lambda: pytest_runtest_setup(item)"},{"fileName":"test_unittest.py","filePath":"testing","id":6213,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport gc\n\nimport pytest\nfrom _pytest.main import EXIT_NOTESTSCOLLECTED\n\n\ndef test_simple_unittest(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n class MyTestCase(unittest.TestCase):\n def testpassing(self):\n self.assertEqual('foo', 'foo')\n def test_failing(self):\n self.assertEqual('foo', 'bar')\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n assert reprec.matchreport(\"testpassing\").passed\n assert reprec.matchreport(\"test_failing\").failed\n\n\ndef test_runTest_method(testdir):\n testdir.makepyfile(\n \"\"\"\n import unittest\n class MyTestCaseWithRunTest(unittest.TestCase):\n def runTest(self):\n self.assertEqual('foo', 'foo')\n class MyTestCaseWithoutRunTest(unittest.TestCase):\n def runTest(self):\n self.assertEqual('foo', 'foo')\n def test_something(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *MyTestCaseWithRunTest::runTest*\n *MyTestCaseWithoutRunTest::test_something*\n *2 passed*\n \"\"\"\n )\n\n\ndef test_isclasscheck_issue53(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n class _E(object):\n def __getattr__(self, tag):\n pass\n E = _E()\n \"\"\"\n )\n result = testdir.runpytest(testpath)\n assert result.ret == EXIT_NOTESTSCOLLECTED\n\n\ndef test_setup(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n class MyTestCase(unittest.TestCase):\n def setUp(self):\n self.foo = 1\n def setup_method(self, method):\n self.foo2 = 1\n def test_both(self):\n self.assertEqual(1, self.foo)\n assert self.foo2 == 1\n def teardown_method(self, method):\n assert 0, \"42\"\n\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\", testpath)\n assert reprec.matchreport(\"test_both\", when=\"call\").passed\n rep = reprec.matchreport(\"test_both\", when=\"teardown\")\n assert rep.failed and \"42\" in str(rep.longrepr)\n\n\ndef test_setUpModule(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n values = []\n\n def setUpModule():\n values.append(1)\n\n def tearDownModule():\n del values[0]\n\n def test_hello():\n assert values == [1]\n\n def test_world():\n assert values == [1]\n \"\"\"\n )\n result = testdir.runpytest(testpath)\n result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n\ndef test_setUpModule_failing_no_teardown(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n values = []\n\n def setUpModule():\n 0/0\n\n def tearDownModule():\n values.append(1)\n\n def test_hello():\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n reprec.assertoutcome(passed=0, failed=1)\n call = reprec.getcalls(\"pytest_runtest_setup\")[0]\n assert not call.item.module.values\n\n\ndef test_new_instances(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n class MyTestCase(unittest.TestCase):\n def test_func1(self):\n self.x = 2\n def test_func2(self):\n assert not hasattr(self, 'x')\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n reprec.assertoutcome(passed=2)\n\n\ndef test_function_item_obj_is_instance(testdir):\n \"\"\"item.obj should be a bound method on unittest.TestCase function items (#5390).\"\"\"\n testdir.makeconftest(\n \"\"\"\n def pytest_runtest_makereport(item, call):\n if call.when == 'call':\n class_ = item.parent.obj\n assert isinstance(item.obj.__self__, class_)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import unittest\n\n class Test(unittest.TestCase):\n def test_foo(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest_inprocess()\n result.stdout.fnmatch_lines([\"* 1 passed in*\"])\n\n\ndef test_teardown(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n class MyTestCase(unittest.TestCase):\n values = []\n def test_one(self):\n pass\n def tearDown(self):\n self.values.append(None)\n class Second(unittest.TestCase):\n def test_check(self):\n self.assertEqual(MyTestCase.values, [None])\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n passed, skipped, failed = reprec.countoutcomes()\n assert failed == 0, failed\n assert passed == 2\n assert passed + skipped + failed == 2\n\n\ndef test_teardown_issue1649(testdir):\n \"\"\"\n Are TestCase objects cleaned up? Often unittest TestCase objects set\n attributes that are large and expensive during setUp.\n\n The TestCase will not be cleaned up if the test fails, because it\n would then exist in the stackframe.\n \"\"\"\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n class TestCaseObjectsShouldBeCleanedUp(unittest.TestCase):\n def setUp(self):\n self.an_expensive_object = 1\n def test_demo(self):\n pass\n\n \"\"\"\n )\n testdir.inline_run(\"-s\", testpath)\n gc.collect()\n for obj in gc.get_objects():\n assert type(obj).__name__ != \"TestCaseObjectsShouldBeCleanedUp\"\n\n\ndef test_unittest_skip_issue148(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n\n @unittest.skip(\"hello\")\n class MyTestCase(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n xxx\n def test_one(self):\n pass\n @classmethod\n def tearDownClass(self):\n xxx\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n reprec.assertoutcome(skipped=1)\n\n\ndef test_method_and_teardown_failing_reporting(testdir):\n testdir.makepyfile(\n \"\"\"\n import unittest, pytest\n class TC(unittest.TestCase):\n def tearDown(self):\n assert 0, \"down1\"\n def test_method(self):\n assert False, \"down2\"\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\n \"*tearDown*\",\n \"*assert 0*\",\n \"*test_method*\",\n \"*assert False*\",\n \"*1 failed*1 error*\",\n ]\n )\n\n\ndef test_setup_failure_is_shown(testdir):\n testdir.makepyfile(\n \"\"\"\n import unittest\n import pytest\n class TC(unittest.TestCase):\n def setUp(self):\n assert 0, \"down1\"\n def test_method(self):\n print(\"never42\")\n xyz\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n assert result.ret == 1\n result.stdout.fnmatch_lines([\"*setUp*\", \"*assert 0*down1*\", \"*1 failed*\"])\n assert \"never42\" not in result.stdout.str()\n\n\ndef test_setup_setUpClass(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n import pytest\n class MyTestCase(unittest.TestCase):\n x = 0\n @classmethod\n def setUpClass(cls):\n cls.x += 1\n def test_func1(self):\n assert self.x == 1\n def test_func2(self):\n assert self.x == 1\n @classmethod\n def tearDownClass(cls):\n cls.x -= 1\n def test_teareddown():\n assert MyTestCase.x == 0\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n reprec.assertoutcome(passed=3)\n\n\ndef test_setup_class(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n import pytest\n class MyTestCase(unittest.TestCase):\n x = 0\n def setup_class(cls):\n cls.x += 1\n def test_func1(self):\n assert self.x == 1\n def test_func2(self):\n assert self.x == 1\n def teardown_class(cls):\n cls.x -= 1\n def test_teareddown():\n assert MyTestCase.x == 0\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n reprec.assertoutcome(passed=3)\n\n\n@pytest.mark.parametrize(\"type\", [\"Error\", \"Failure\"])\ndef test_testcase_adderrorandfailure_defers(testdir, type):\n testdir.makepyfile(\n \"\"\"\n from unittest import TestCase\n import pytest\n class MyTestCase(TestCase):\n def run(self, result):\n excinfo = pytest.raises(ZeroDivisionError, lambda: 0/0)\n try:\n result.add%s(self, excinfo._excinfo)\n except KeyboardInterrupt:\n raise\n except:\n pytest.fail(\"add%s should not raise\")\n def test_hello(self):\n pass\n \"\"\"\n % (type, type)\n )\n result = testdir.runpytest()\n assert \"should not raise\" not in result.stdout.str()\n\n\n@pytest.mark.parametrize(\"type\", [\"Error\", \"Failure\"])\ndef test_testcase_custom_exception_info(testdir, type):\n testdir.makepyfile(\n \"\"\"\n from unittest import TestCase\n import py, pytest\n import _pytest._code\n class MyTestCase(TestCase):\n def run(self, result):\n excinfo = pytest.raises(ZeroDivisionError, lambda: 0/0)\n # we fake an incompatible exception info\n from _pytest.monkeypatch import MonkeyPatch\n mp = MonkeyPatch()\n def t(*args):\n mp.undo()\n raise TypeError()\n mp.setattr(_pytest._code, 'ExceptionInfo', t)\n try:\n excinfo = excinfo._excinfo\n result.add%(type)s(self, excinfo)\n finally:\n mp.undo()\n def test_hello(self):\n pass\n \"\"\"\n % locals()\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"NOTE: Incompatible Exception Representation*\",\n \"*ZeroDivisionError*\",\n \"*1 failed*\",\n ]\n )\n\n\ndef test_testcase_totally_incompatible_exception_info(testdir):\n item, = testdir.getitems(\n \"\"\"\n from unittest import TestCase\n class MyTestCase(TestCase):\n def test_hello(self):\n pass\n \"\"\"\n )\n item.addError(None, 42)\n excinfo = item._excinfo.pop(0)\n assert \"ERROR: Unknown Incompatible\" in str(excinfo.getrepr())\n\n\ndef test_module_level_pytestmark(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n import pytest\n pytestmark = pytest.mark.xfail\n class MyTestCase(unittest.TestCase):\n def test_func1(self):\n assert 0\n \"\"\"\n )\n reprec = testdir.inline_run(testpath, \"-s\")\n reprec.assertoutcome(skipped=1)\n\n\nclass TestTrialUnittest(object):\n def setup_class(cls):\n cls.ut = pytest.importorskip(\"twisted.trial.unittest\")\n # on windows trial uses a socket for a reactor and apparently doesn't close it properly\n # https://twistedmatrix.com/trac/ticket/9227\n cls.ignore_unclosed_socket_warning = (\"-W\", \"always\")\n\n def test_trial_testcase_runtest_not_collected(self, testdir):\n testdir.makepyfile(\n \"\"\"\n from twisted.trial.unittest import TestCase\n\n class TC(TestCase):\n def test_hello(self):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(*self.ignore_unclosed_socket_warning)\n reprec.assertoutcome(passed=1)\n testdir.makepyfile(\n \"\"\"\n from twisted.trial.unittest import TestCase\n\n class TC(TestCase):\n def runTest(self):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(*self.ignore_unclosed_socket_warning)\n reprec.assertoutcome(passed=1)\n\n def test_trial_exceptions_with_skips(self, testdir):\n testdir.makepyfile(\n \"\"\"\n from twisted.trial import unittest\n import pytest\n class TC(unittest.TestCase):\n def test_hello(self):\n pytest.skip(\"skip_in_method\")\n @pytest.mark.skipif(\"sys.version_info != 1\")\n def test_hello2(self):\n pass\n @pytest.mark.xfail(reason=\"iwanto\")\n def test_hello3(self):\n assert 0\n def test_hello4(self):\n pytest.xfail(\"i2wanto\")\n def test_trial_skip(self):\n pass\n test_trial_skip.skip = \"trialselfskip\"\n\n def test_trial_todo(self):\n assert 0\n test_trial_todo.todo = \"mytodo\"\n\n def test_trial_todo_success(self):\n pass\n test_trial_todo_success.todo = \"mytodo\"\n\n class TC2(unittest.TestCase):\n def setup_class(cls):\n pytest.skip(\"skip_in_setup_class\")\n def test_method(self):\n pass\n \"\"\"\n )\n from _pytest.compat import _is_unittest_unexpected_success_a_failure\n\n should_fail = _is_unittest_unexpected_success_a_failure()\n result = testdir.runpytest(\"-rxs\", *self.ignore_unclosed_socket_warning)\n result.stdout.fnmatch_lines_random(\n [\n \"*XFAIL*test_trial_todo*\",\n \"*trialselfskip*\",\n \"*skip_in_setup_class*\",\n \"*iwanto*\",\n \"*i2wanto*\",\n \"*sys.version_info*\",\n \"*skip_in_method*\",\n \"*1 failed*4 skipped*3 xfailed*\"\n if should_fail\n else \"*4 skipped*3 xfail*1 xpass*\",\n ]\n )\n assert result.ret == (1 if should_fail else 0)\n\n def test_trial_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n from twisted.trial.unittest import TestCase\n from twisted.internet.defer import Deferred\n from twisted.internet import reactor\n\n class TC(TestCase):\n def test_one(self):\n crash\n\n def test_two(self):\n def f(_):\n crash\n\n d = Deferred()\n d.addCallback(f)\n reactor.callLater(0.3, d.callback, None)\n return d\n\n def test_three(self):\n def f():\n pass # will never get called\n reactor.callLater(0.3, f)\n # will crash at teardown\n\n def test_four(self):\n def f(_):\n reactor.callLater(0.3, f)\n crash\n\n d = Deferred()\n d.addCallback(f)\n reactor.callLater(0.3, d.callback, None)\n return d\n # will crash both at test time and at teardown\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*ERRORS*\",\n \"*DelayedCalls*\",\n \"*test_four*\",\n \"*NameError*crash*\",\n \"*test_one*\",\n \"*NameError*crash*\",\n \"*test_three*\",\n \"*DelayedCalls*\",\n \"*test_two*\",\n \"*crash*\",\n ]\n )\n\n def test_trial_pdb(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n from twisted.trial import unittest\n import pytest\n class TC(unittest.TestCase):\n def test_hello(self):\n assert 0, \"hellopdb\"\n \"\"\"\n )\n child = testdir.spawn_pytest(p)\n child.expect(\"hellopdb\")\n child.sendeof()\n\n def test_trial_testcase_skip_property(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n from twisted.trial import unittest\n class MyTestCase(unittest.TestCase):\n skip = 'dont run'\n def test_func(self):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(testpath, \"-s\")\n reprec.assertoutcome(skipped=1)\n\n def test_trial_testfunction_skip_property(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n from twisted.trial import unittest\n class MyTestCase(unittest.TestCase):\n def test_func(self):\n pass\n test_func.skip = 'dont run'\n \"\"\"\n )\n reprec = testdir.inline_run(testpath, \"-s\")\n reprec.assertoutcome(skipped=1)\n\n def test_trial_testcase_todo_property(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n from twisted.trial import unittest\n class MyTestCase(unittest.TestCase):\n todo = 'dont run'\n def test_func(self):\n assert 0\n \"\"\"\n )\n reprec = testdir.inline_run(testpath, \"-s\")\n reprec.assertoutcome(skipped=1)\n\n def test_trial_testfunction_todo_property(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n from twisted.trial import unittest\n class MyTestCase(unittest.TestCase):\n def test_func(self):\n assert 0\n test_func.todo = 'dont run'\n \"\"\"\n )\n reprec = testdir.inline_run(\n testpath, \"-s\", *self.ignore_unclosed_socket_warning\n )\n reprec.assertoutcome(skipped=1)\n\n\ndef test_djangolike_testcase(testdir):\n # contributed from Morten Breekevold\n testdir.makepyfile(\n \"\"\"\n from unittest import TestCase, main\n\n class DjangoLikeTestCase(TestCase):\n\n def setUp(self):\n print(\"setUp()\")\n\n def test_presetup_has_been_run(self):\n print(\"test_thing()\")\n self.assertTrue(hasattr(self, 'was_presetup'))\n\n def tearDown(self):\n print(\"tearDown()\")\n\n def __call__(self, result=None):\n try:\n self._pre_setup()\n except (KeyboardInterrupt, SystemExit):\n raise\n except Exception:\n import sys\n result.addError(self, sys.exc_info())\n return\n super(DjangoLikeTestCase, self).__call__(result)\n try:\n self._post_teardown()\n except (KeyboardInterrupt, SystemExit):\n raise\n except Exception:\n import sys\n result.addError(self, sys.exc_info())\n return\n\n def _pre_setup(self):\n print(\"_pre_setup()\")\n self.was_presetup = True\n\n def _post_teardown(self):\n print(\"_post_teardown()\")\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n [\n \"*_pre_setup()*\",\n \"*setUp()*\",\n \"*test_thing()*\",\n \"*tearDown()*\",\n \"*_post_teardown()*\",\n ]\n )\n\n\ndef test_unittest_not_shown_in_traceback(testdir):\n testdir.makepyfile(\n \"\"\"\n import unittest\n class t(unittest.TestCase):\n def test_hello(self):\n x = 3\n self.assertEqual(x, 4)\n \"\"\"\n )\n res = testdir.runpytest()\n assert \"failUnlessEqual\" not in res.stdout.str()\n\n\ndef test_unorderable_types(testdir):\n testdir.makepyfile(\n \"\"\"\n import unittest\n class TestJoinEmpty(unittest.TestCase):\n pass\n\n def make_test():\n class Test(unittest.TestCase):\n pass\n Test.__name__ = \"TestFoo\"\n return Test\n TestFoo = make_test()\n \"\"\"\n )\n result = testdir.runpytest()\n assert \"TypeError\" not in result.stdout.str()\n assert result.ret == EXIT_NOTESTSCOLLECTED\n\n\ndef test_unittest_typerror_traceback(testdir):\n testdir.makepyfile(\n \"\"\"\n import unittest\n class TestJoinEmpty(unittest.TestCase):\n def test_hello(self, arg1):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n assert \"TypeError\" in result.stdout.str()\n assert result.ret == 1\n\n\n@pytest.mark.parametrize(\"runner\", [\"pytest\", \"unittest\"])\ndef test_unittest_expected_failure_for_failing_test_is_xfail(testdir, runner):\n script = testdir.makepyfile(\n \"\"\"\n import unittest\n class MyTestCase(unittest.TestCase):\n @unittest.expectedFailure\n def test_failing_test_is_xfail(self):\n assert False\n if __name__ == '__main__':\n unittest.main()\n \"\"\"\n )\n if runner == \"pytest\":\n result = testdir.runpytest(\"-rxX\")\n result.stdout.fnmatch_lines(\n [\"*XFAIL*MyTestCase*test_failing_test_is_xfail*\", \"*1 xfailed*\"]\n )\n else:\n result = testdir.runpython(script)\n result.stderr.fnmatch_lines([\"*1 test in*\", \"*OK*(expected failures=1)*\"])\n assert result.ret == 0\n\n\n@pytest.mark.parametrize(\"runner\", [\"pytest\", \"unittest\"])\ndef test_unittest_expected_failure_for_passing_test_is_fail(testdir, runner):\n script = testdir.makepyfile(\n \"\"\"\n import unittest\n class MyTestCase(unittest.TestCase):\n @unittest.expectedFailure\n def test_passing_test_is_fail(self):\n assert True\n if __name__ == '__main__':\n unittest.main()\n \"\"\"\n )\n from _pytest.compat import _is_unittest_unexpected_success_a_failure\n\n should_fail = _is_unittest_unexpected_success_a_failure()\n if runner == \"pytest\":\n result = testdir.runpytest(\"-rxX\")\n result.stdout.fnmatch_lines(\n [\n \"*MyTestCase*test_passing_test_is_fail*\",\n \"*1 failed*\" if should_fail else \"*1 xpassed*\",\n ]\n )\n else:\n result = testdir.runpython(script)\n result.stderr.fnmatch_lines([\"*1 test in*\", \"*(unexpected successes=1)*\"])\n\n assert result.ret == (1 if should_fail else 0)\n\n\n@pytest.mark.parametrize(\n \"fix_type, stmt\", [(\"fixture\", \"return\"), (\"yield_fixture\", \"yield\")]\n)\ndef test_unittest_setup_interaction(testdir, fix_type, stmt):\n testdir.makepyfile(\n \"\"\"\n import unittest\n import pytest\n class MyTestCase(unittest.TestCase):\n @pytest.{fix_type}(scope=\"class\", autouse=True)\n def perclass(self, request):\n request.cls.hello = \"world\"\n {stmt}\n @pytest.{fix_type}(scope=\"function\", autouse=True)\n def perfunction(self, request):\n request.instance.funcname = request.function.__name__\n {stmt}\n\n def test_method1(self):\n assert self.funcname == \"test_method1\"\n assert self.hello == \"world\"\n\n def test_method2(self):\n assert self.funcname == \"test_method2\"\n\n def test_classattr(self):\n assert self.__class__.hello == \"world\"\n \"\"\".format(\n fix_type=fix_type, stmt=stmt\n )\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n\n\ndef test_non_unittest_no_setupclass_support(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n class TestFoo(object):\n x = 0\n\n @classmethod\n def setUpClass(cls):\n cls.x = 1\n\n def test_method1(self):\n assert self.x == 0\n\n @classmethod\n def tearDownClass(cls):\n cls.x = 1\n\n def test_not_teareddown():\n assert TestFoo.x == 0\n\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n reprec.assertoutcome(passed=2)\n\n\ndef test_no_teardown_if_setupclass_failed(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n\n class MyTestCase(unittest.TestCase):\n x = 0\n\n @classmethod\n def setUpClass(cls):\n cls.x = 1\n assert False\n\n def test_func1(self):\n cls.x = 10\n\n @classmethod\n def tearDownClass(cls):\n cls.x = 100\n\n def test_notTornDown():\n assert MyTestCase.x == 1\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n reprec.assertoutcome(passed=1, failed=1)\n\n\ndef test_issue333_result_clearing(testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_call(item):\n yield\n assert 0\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import unittest\n class TestIt(unittest.TestCase):\n def test_func(self):\n 0/0\n \"\"\"\n )\n\n reprec = testdir.inline_run()\n reprec.assertoutcome(failed=1)\n\n\ndef test_unittest_raise_skip_issue748(testdir):\n testdir.makepyfile(\n test_foo=\"\"\"\n import unittest\n\n class MyTestCase(unittest.TestCase):\n def test_one(self):\n raise unittest.SkipTest('skipping due to reasons')\n \"\"\"\n )\n result = testdir.runpytest(\"-v\", \"-rs\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *SKIP*[1]*test_foo.py*skipping due to reasons*\n *1 skipped*\n \"\"\"\n )\n\n\ndef test_unittest_skip_issue1169(testdir):\n testdir.makepyfile(\n test_foo=\"\"\"\n import unittest\n\n class MyTestCase(unittest.TestCase):\n @unittest.skip(\"skipping due to reasons\")\n def test_skip(self):\n self.fail()\n \"\"\"\n )\n result = testdir.runpytest(\"-v\", \"-rs\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *SKIP*[1]*skipping due to reasons*\n *1 skipped*\n \"\"\"\n )\n\n\ndef test_class_method_containing_test_issue1558(testdir):\n testdir.makepyfile(\n test_foo=\"\"\"\n import unittest\n\n class MyTestCase(unittest.TestCase):\n def test_should_run(self):\n pass\n def test_should_not_run(self):\n pass\n test_should_not_run.__test__ = False\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n\n@pytest.mark.parametrize(\n \"base\", [\"six.moves.builtins.object\", \"unittest.TestCase\", \"unittest2.TestCase\"]\n)\ndef test_usefixtures_marker_on_unittest(base, testdir):\n \"\"\"#3498\"\"\"\n module = base.rsplit(\".\", 1)[0]\n pytest.importorskip(module)\n testdir.makepyfile(\n conftest=\"\"\"\n import pytest\n\n @pytest.fixture(scope='function')\n def fixture1(request, monkeypatch):\n monkeypatch.setattr(request.instance, 'fixture1', True )\n\n\n @pytest.fixture(scope='function')\n def fixture2(request, monkeypatch):\n monkeypatch.setattr(request.instance, 'fixture2', True )\n\n def node_and_marks(item):\n print(item.nodeid)\n for mark in item.iter_markers():\n print(\" \", mark)\n\n @pytest.fixture(autouse=True)\n def my_marks(request):\n node_and_marks(request.node)\n\n def pytest_collection_modifyitems(items):\n for item in items:\n node_and_marks(item)\n\n \"\"\"\n )\n\n testdir.makepyfile(\n \"\"\"\n import pytest\n import {module}\n\n class Tests({base}):\n fixture1 = False\n fixture2 = False\n\n @pytest.mark.usefixtures(\"fixture1\")\n def test_one(self):\n assert self.fixture1\n assert not self.fixture2\n\n @pytest.mark.usefixtures(\"fixture1\", \"fixture2\")\n def test_two(self):\n assert self.fixture1\n assert self.fixture2\n\n\n \"\"\".format(\n module=module, base=base\n )\n )\n\n result = testdir.runpytest(\"-s\")\n result.assert_outcomes(passed=2)\n\n\ndef test_testcase_handles_init_exceptions(testdir):\n \"\"\"\n Regression test to make sure exceptions in the __init__ method are bubbled up correctly.\n See https://github.com/pytest-dev/pytest/issues/3788\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n from unittest import TestCase\n import pytest\n class MyTestCase(TestCase):\n def __init__(self, *args, **kwargs):\n raise Exception(\"should raise this exception\")\n def test_hello(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n assert \"should raise this exception\" in result.stdout.str()\n assert \"ERROR at teardown of MyTestCase.test_hello\" not in result.stdout.str()\n\n\ndef test_error_message_with_parametrized_fixtures(testdir):\n testdir.copy_example(\"unittest/test_parametrized_fixture_error_message.py\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*test_two does not support fixtures*\",\n \"*TestSomethingElse::test_two\",\n \"*Function type: TestCaseFunction\",\n ]\n )\n\n\n@pytest.mark.parametrize(\n \"test_name, expected_outcome\",\n [\n (\"test_setup_skip.py\", \"1 skipped\"),\n (\"test_setup_skip_class.py\", \"1 skipped\"),\n (\"test_setup_skip_module.py\", \"1 error\"),\n ],\n)\ndef test_setup_inheritance_skipping(testdir, test_name, expected_outcome):\n \"\"\"Issue #4700\"\"\"\n testdir.copy_example(\"unittest/{}\".format(test_name))\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* {} in *\".format(expected_outcome)])\n"},{"className":"TestTrialUnittest","col":0,"comment":"null","endLoc":625,"id":6214,"nodeType":"Class","startLoc":419,"text":"class TestTrialUnittest(object):\n def setup_class(cls):\n cls.ut = pytest.importorskip(\"twisted.trial.unittest\")\n # on windows trial uses a socket for a reactor and apparently doesn't close it properly\n # https://twistedmatrix.com/trac/ticket/9227\n cls.ignore_unclosed_socket_warning = (\"-W\", \"always\")\n\n def test_trial_testcase_runtest_not_collected(self, testdir):\n testdir.makepyfile(\n \"\"\"\n from twisted.trial.unittest import TestCase\n\n class TC(TestCase):\n def test_hello(self):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(*self.ignore_unclosed_socket_warning)\n reprec.assertoutcome(passed=1)\n testdir.makepyfile(\n \"\"\"\n from twisted.trial.unittest import TestCase\n\n class TC(TestCase):\n def runTest(self):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(*self.ignore_unclosed_socket_warning)\n reprec.assertoutcome(passed=1)\n\n def test_trial_exceptions_with_skips(self, testdir):\n testdir.makepyfile(\n \"\"\"\n from twisted.trial import unittest\n import pytest\n class TC(unittest.TestCase):\n def test_hello(self):\n pytest.skip(\"skip_in_method\")\n @pytest.mark.skipif(\"sys.version_info != 1\")\n def test_hello2(self):\n pass\n @pytest.mark.xfail(reason=\"iwanto\")\n def test_hello3(self):\n assert 0\n def test_hello4(self):\n pytest.xfail(\"i2wanto\")\n def test_trial_skip(self):\n pass\n test_trial_skip.skip = \"trialselfskip\"\n\n def test_trial_todo(self):\n assert 0\n test_trial_todo.todo = \"mytodo\"\n\n def test_trial_todo_success(self):\n pass\n test_trial_todo_success.todo = \"mytodo\"\n\n class TC2(unittest.TestCase):\n def setup_class(cls):\n pytest.skip(\"skip_in_setup_class\")\n def test_method(self):\n pass\n \"\"\"\n )\n from _pytest.compat import _is_unittest_unexpected_success_a_failure\n\n should_fail = _is_unittest_unexpected_success_a_failure()\n result = testdir.runpytest(\"-rxs\", *self.ignore_unclosed_socket_warning)\n result.stdout.fnmatch_lines_random(\n [\n \"*XFAIL*test_trial_todo*\",\n \"*trialselfskip*\",\n \"*skip_in_setup_class*\",\n \"*iwanto*\",\n \"*i2wanto*\",\n \"*sys.version_info*\",\n \"*skip_in_method*\",\n \"*1 failed*4 skipped*3 xfailed*\"\n if should_fail\n else \"*4 skipped*3 xfail*1 xpass*\",\n ]\n )\n assert result.ret == (1 if should_fail else 0)\n\n def test_trial_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n from twisted.trial.unittest import TestCase\n from twisted.internet.defer import Deferred\n from twisted.internet import reactor\n\n class TC(TestCase):\n def test_one(self):\n crash\n\n def test_two(self):\n def f(_):\n crash\n\n d = Deferred()\n d.addCallback(f)\n reactor.callLater(0.3, d.callback, None)\n return d\n\n def test_three(self):\n def f():\n pass # will never get called\n reactor.callLater(0.3, f)\n # will crash at teardown\n\n def test_four(self):\n def f(_):\n reactor.callLater(0.3, f)\n crash\n\n d = Deferred()\n d.addCallback(f)\n reactor.callLater(0.3, d.callback, None)\n return d\n # will crash both at test time and at teardown\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*ERRORS*\",\n \"*DelayedCalls*\",\n \"*test_four*\",\n \"*NameError*crash*\",\n \"*test_one*\",\n \"*NameError*crash*\",\n \"*test_three*\",\n \"*DelayedCalls*\",\n \"*test_two*\",\n \"*crash*\",\n ]\n )\n\n def test_trial_pdb(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n from twisted.trial import unittest\n import pytest\n class TC(unittest.TestCase):\n def test_hello(self):\n assert 0, \"hellopdb\"\n \"\"\"\n )\n child = testdir.spawn_pytest(p)\n child.expect(\"hellopdb\")\n child.sendeof()\n\n def test_trial_testcase_skip_property(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n from twisted.trial import unittest\n class MyTestCase(unittest.TestCase):\n skip = 'dont run'\n def test_func(self):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(testpath, \"-s\")\n reprec.assertoutcome(skipped=1)\n\n def test_trial_testfunction_skip_property(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n from twisted.trial import unittest\n class MyTestCase(unittest.TestCase):\n def test_func(self):\n pass\n test_func.skip = 'dont run'\n \"\"\"\n )\n reprec = testdir.inline_run(testpath, \"-s\")\n reprec.assertoutcome(skipped=1)\n\n def test_trial_testcase_todo_property(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n from twisted.trial import unittest\n class MyTestCase(unittest.TestCase):\n todo = 'dont run'\n def test_func(self):\n assert 0\n \"\"\"\n )\n reprec = testdir.inline_run(testpath, \"-s\")\n reprec.assertoutcome(skipped=1)\n\n def test_trial_testfunction_todo_property(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n from twisted.trial import unittest\n class MyTestCase(unittest.TestCase):\n def test_func(self):\n assert 0\n test_func.todo = 'dont run'\n \"\"\"\n )\n reprec = testdir.inline_run(\n testpath, \"-s\", *self.ignore_unclosed_socket_warning\n )\n reprec.assertoutcome(skipped=1)"},{"col":0,"comment":"null","endLoc":738,"header":"def test_log_file_cli_level(testdir)","id":6215,"name":"test_log_file_cli_level","nodeType":"Function","startLoc":708,"text":"def test_log_file_cli_level(testdir):\n # Default log file level\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n def test_log_file(request):\n plugin = request.config.pluginmanager.getplugin('logging-plugin')\n assert plugin.log_file_handler.level == logging.INFO\n logging.getLogger('catchlog').debug(\"This log message won't be shown\")\n logging.getLogger('catchlog').info(\"This log message will be shown\")\n print('PASSED')\n \"\"\"\n )\n\n log_file = testdir.tmpdir.join(\"pytest.log\").strpath\n\n result = testdir.runpytest(\n \"-s\", \"--log-file={}\".format(log_file), \"--log-file-level=INFO\"\n )\n\n # fnmatch_lines does an assertion internally\n result.stdout.fnmatch_lines([\"test_log_file_cli_level.py PASSED\"])\n\n # make sure that that we get a '0' exit code for the testsuite\n assert result.ret == 0\n assert os.path.isfile(log_file)\n with open(log_file) as rfh:\n contents = rfh.read()\n assert \"This log message will be shown\" in contents\n assert \"This log message won't be shown\" not in contents"},{"col":4,"comment":"null","endLoc":424,"header":"def setup_class(cls)","id":6216,"name":"setup_class","nodeType":"Function","startLoc":420,"text":"def setup_class(cls):\n cls.ut = pytest.importorskip(\"twisted.trial.unittest\")\n # on windows trial uses a socket for a reactor and apparently doesn't close it properly\n # https://twistedmatrix.com/trac/ticket/9227\n cls.ignore_unclosed_socket_warning = (\"-W\", \"always\")"},{"col":4,"comment":"null","endLoc":448,"header":"def test_trial_testcase_runtest_not_collected(self, testdir)","id":6217,"name":"test_trial_testcase_runtest_not_collected","nodeType":"Function","startLoc":426,"text":"def test_trial_testcase_runtest_not_collected(self, testdir):\n testdir.makepyfile(\n \"\"\"\n from twisted.trial.unittest import TestCase\n\n class TC(TestCase):\n def test_hello(self):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(*self.ignore_unclosed_socket_warning)\n reprec.assertoutcome(passed=1)\n testdir.makepyfile(\n \"\"\"\n from twisted.trial.unittest import TestCase\n\n class TC(TestCase):\n def runTest(self):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(*self.ignore_unclosed_socket_warning)\n reprec.assertoutcome(passed=1)"},{"attributeType":"bool","col":8,"comment":"null","endLoc":70,"id":6218,"name":"directories","nodeType":"Attribute","startLoc":70,"text":"self.directories"},{"col":4,"comment":"null","endLoc":503,"header":"def test_trial_exceptions_with_skips(self, testdir)","id":6219,"name":"test_trial_exceptions_with_skips","nodeType":"Function","startLoc":450,"text":"def test_trial_exceptions_with_skips(self, testdir):\n testdir.makepyfile(\n \"\"\"\n from twisted.trial import unittest\n import pytest\n class TC(unittest.TestCase):\n def test_hello(self):\n pytest.skip(\"skip_in_method\")\n @pytest.mark.skipif(\"sys.version_info != 1\")\n def test_hello2(self):\n pass\n @pytest.mark.xfail(reason=\"iwanto\")\n def test_hello3(self):\n assert 0\n def test_hello4(self):\n pytest.xfail(\"i2wanto\")\n def test_trial_skip(self):\n pass\n test_trial_skip.skip = \"trialselfskip\"\n\n def test_trial_todo(self):\n assert 0\n test_trial_todo.todo = \"mytodo\"\n\n def test_trial_todo_success(self):\n pass\n test_trial_todo_success.todo = \"mytodo\"\n\n class TC2(unittest.TestCase):\n def setup_class(cls):\n pytest.skip(\"skip_in_setup_class\")\n def test_method(self):\n pass\n \"\"\"\n )\n from _pytest.compat import _is_unittest_unexpected_success_a_failure\n\n should_fail = _is_unittest_unexpected_success_a_failure()\n result = testdir.runpytest(\"-rxs\", *self.ignore_unclosed_socket_warning)\n result.stdout.fnmatch_lines_random(\n [\n \"*XFAIL*test_trial_todo*\",\n \"*trialselfskip*\",\n \"*skip_in_setup_class*\",\n \"*iwanto*\",\n \"*i2wanto*\",\n \"*sys.version_info*\",\n \"*skip_in_method*\",\n \"*1 failed*4 skipped*3 xfailed*\"\n if should_fail\n else \"*4 skipped*3 xfail*1 xpass*\",\n ]\n )\n assert result.ret == (1 if should_fail else 0)"},{"attributeType":"FastFilesCompleter","col":4,"comment":"null","endLoc":99,"id":6220,"name":"filescompleter","nodeType":"Attribute","startLoc":99,"text":"filescompleter"},{"attributeType":"None","col":4,"comment":"null","endLoc":110,"id":6221,"name":"filescompleter","nodeType":"Attribute","startLoc":110,"text":"filescompleter"},{"col":0,"comment":"","endLoc":56,"header":"_argcomplete.py#","id":6222,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"allow bash-completion for argparse with argcomplete if installed\nneeds argcomplete>=0.5.6 for python 3.2/3.3 (older versions fail\nto find the magic string, so _ARGCOMPLETE env. var is never set, and\nthis does not need special code.\n\nFunction try_argcomplete(parser) should be called directly before\nthe call to ArgumentParser.parse_args().\n\nThe filescompleter is what you normally would use on the positional\narguments specification, in order to get \"dirname/\" after \"dirn\"\ninstead of the default \"dirname \":\n\n optparser.add_argument(Config._file_or_dir, nargs='*'\n ).completer=filescompleter\n\nOther, application specific, completers should go in the file\ndoing the add_argument calls as they need to be specified as .completer\nattributes as well. (If argcomplete is not installed, the function the\nattribute points to will not be used).\n\nSPEEDUP\n=======\nThe generic argcomplete script for bash-completion\n(/etc/bash_completion.d/python-argcomplete.sh )\nuses a python program to determine startup script generated by pip.\nYou can speed up completion somewhat by changing this script to include\n # PYTHON_ARGCOMPLETE_OK\nso the the python-argcomplete-check-easy-install-script does not\nneed to be called to find the entry point of the code and see if that is\nmarked with PYTHON_ARGCOMPLETE_OK\n\nINSTALL/DEBUGGING\n=================\nTo include this support in another application that has setup.py generated\nscripts:\n- add the line:\n # PYTHON_ARGCOMPLETE_OK\n near the top of the main python entry point\n- include in the file calling parse_args():\n from _argcomplete import try_argcomplete, filescompleter\n , call try_argcomplete just before parse_args(), and optionally add\n filescompleter to the positional arguments' add_argument()\nIf things do not work right away:\n- switch on argcomplete debugging with (also helpful when doing custom\n completers):\n export _ARC_DEBUG=1\n- run:\n python-argcomplete-check-easy-install-script $(which appname)\n echo $?\n will echo 0 if the magic line has been found, 1 if not\n- sometimes it helps to find early on errors using:\n _ARGCOMPLETE=1 _ARC_DEBUG=1 appname\n which should throw a KeyError: 'COMPLINE' (which is properly set by the\n global argcomplete script).\n\"\"\"\n\nif os.environ.get(\"_ARGCOMPLETE\"):\n try:\n import argcomplete.completers\n except ImportError:\n sys.exit(-1)\n filescompleter = FastFilesCompleter()\n\n def try_argcomplete(parser):\n argcomplete.autocomplete(parser, always_complete_options=False)\n\n\nelse:\n\n def try_argcomplete(parser):\n pass\n\n filescompleter = None"},{"col":4,"comment":"null","endLoc":557,"header":"def test_trial_error(self, testdir)","id":6223,"name":"test_trial_error","nodeType":"Function","startLoc":505,"text":"def test_trial_error(self, testdir):\n testdir.makepyfile(\n \"\"\"\n from twisted.trial.unittest import TestCase\n from twisted.internet.defer import Deferred\n from twisted.internet import reactor\n\n class TC(TestCase):\n def test_one(self):\n crash\n\n def test_two(self):\n def f(_):\n crash\n\n d = Deferred()\n d.addCallback(f)\n reactor.callLater(0.3, d.callback, None)\n return d\n\n def test_three(self):\n def f():\n pass # will never get called\n reactor.callLater(0.3, f)\n # will crash at teardown\n\n def test_four(self):\n def f(_):\n reactor.callLater(0.3, f)\n crash\n\n d = Deferred()\n d.addCallback(f)\n reactor.callLater(0.3, d.callback, None)\n return d\n # will crash both at test time and at teardown\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*ERRORS*\",\n \"*DelayedCalls*\",\n \"*test_four*\",\n \"*NameError*crash*\",\n \"*test_one*\",\n \"*NameError*crash*\",\n \"*test_three*\",\n \"*DelayedCalls*\",\n \"*test_two*\",\n \"*crash*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":571,"header":"def test_trial_pdb(self, testdir)","id":6224,"name":"test_trial_pdb","nodeType":"Function","startLoc":559,"text":"def test_trial_pdb(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n from twisted.trial import unittest\n import pytest\n class TC(unittest.TestCase):\n def test_hello(self):\n assert 0, \"hellopdb\"\n \"\"\"\n )\n child = testdir.spawn_pytest(p)\n child.expect(\"hellopdb\")\n child.sendeof()"},{"col":4,"comment":"null","endLoc":584,"header":"def test_trial_testcase_skip_property(self, testdir)","id":6225,"name":"test_trial_testcase_skip_property","nodeType":"Function","startLoc":573,"text":"def test_trial_testcase_skip_property(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n from twisted.trial import unittest\n class MyTestCase(unittest.TestCase):\n skip = 'dont run'\n def test_func(self):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(testpath, \"-s\")\n reprec.assertoutcome(skipped=1)"},{"col":4,"comment":"null","endLoc":751,"header":"def test_invoke_test_and_doctestmodules(self, testdir)","id":6226,"name":"test_invoke_test_and_doctestmodules","nodeType":"Function","startLoc":743,"text":"def test_invoke_test_and_doctestmodules(self, testdir):\n p = testdir.makepyfile(\n \"\"\"\n def test():\n pass\n \"\"\"\n )\n result = testdir.runpytest(str(p) + \"::test\", \"--doctest-modules\")\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":4,"comment":"null","endLoc":597,"header":"def test_trial_testfunction_skip_property(self, testdir)","id":6227,"name":"test_trial_testfunction_skip_property","nodeType":"Function","startLoc":586,"text":"def test_trial_testfunction_skip_property(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n from twisted.trial import unittest\n class MyTestCase(unittest.TestCase):\n def test_func(self):\n pass\n test_func.skip = 'dont run'\n \"\"\"\n )\n reprec = testdir.inline_run(testpath, \"-s\")\n reprec.assertoutcome(skipped=1)"},{"col":4,"comment":"null","endLoc":610,"header":"def test_trial_testcase_todo_property(self, testdir)","id":6228,"name":"test_trial_testcase_todo_property","nodeType":"Function","startLoc":599,"text":"def test_trial_testcase_todo_property(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n from twisted.trial import unittest\n class MyTestCase(unittest.TestCase):\n todo = 'dont run'\n def test_func(self):\n assert 0\n \"\"\"\n )\n reprec = testdir.inline_run(testpath, \"-s\")\n reprec.assertoutcome(skipped=1)"},{"col":4,"comment":"null","endLoc":625,"header":"def test_trial_testfunction_todo_property(self, testdir)","id":6229,"name":"test_trial_testfunction_todo_property","nodeType":"Function","startLoc":612,"text":"def test_trial_testfunction_todo_property(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n from twisted.trial import unittest\n class MyTestCase(unittest.TestCase):\n def test_func(self):\n assert 0\n test_func.todo = 'dont run'\n \"\"\"\n )\n reprec = testdir.inline_run(\n testpath, \"-s\", *self.ignore_unclosed_socket_warning\n )\n reprec.assertoutcome(skipped=1)"},{"attributeType":"(str, str)","col":8,"comment":"null","endLoc":424,"id":6230,"name":"ignore_unclosed_socket_warning","nodeType":"Attribute","startLoc":424,"text":"cls.ignore_unclosed_socket_warning"},{"attributeType":"null","col":8,"comment":"null","endLoc":421,"id":6231,"name":"ut","nodeType":"Attribute","startLoc":421,"text":"cls.ut"},{"col":0,"comment":"null","endLoc":25,"header":"def test_simple_unittest(testdir)","id":6232,"name":"test_simple_unittest","nodeType":"Function","startLoc":12,"text":"def test_simple_unittest(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n class MyTestCase(unittest.TestCase):\n def testpassing(self):\n self.assertEqual('foo', 'foo')\n def test_failing(self):\n self.assertEqual('foo', 'bar')\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n assert reprec.matchreport(\"testpassing\").passed\n assert reprec.matchreport(\"test_failing\").failed"},{"col":4,"comment":"null","endLoc":715,"header":"@pytest.mark.parametrize(\n \"marker, msg1, msg2\",\n [(\"skipif\", \"SKIP\", \"skipped\"), (\"xfail\", \"XPASS\", \"xpassed\")],\n )\n def test_skipif_reporting_multiple(self, testdir, marker, msg1, msg2)","id":6233,"name":"test_skipif_reporting_multiple","nodeType":"Function","startLoc":692,"text":"@pytest.mark.parametrize(\n \"marker, msg1, msg2\",\n [(\"skipif\", \"SKIP\", \"skipped\"), (\"xfail\", \"XPASS\", \"xpassed\")],\n )\n def test_skipif_reporting_multiple(self, testdir, marker, msg1, msg2):\n testdir.makepyfile(\n test_foo=\"\"\"\n import pytest\n @pytest.mark.{marker}(False, reason='first_condition')\n @pytest.mark.{marker}(True, reason='second_condition')\n def test_foobar():\n assert 1\n \"\"\".format(\n marker=marker\n )\n )\n result = testdir.runpytest(\"-s\", \"-rsxX\")\n result.stdout.fnmatch_lines(\n [\n \"*{msg1}*test_foo.py*second_condition*\".format(msg1=msg1),\n \"*1 {msg2}*\".format(msg2=msg2),\n ]\n )\n assert result.ret == 0"},{"col":0,"comment":"null","endLoc":49,"header":"def test_runTest_method(testdir)","id":6234,"name":"test_runTest_method","nodeType":"Function","startLoc":28,"text":"def test_runTest_method(testdir):\n testdir.makepyfile(\n \"\"\"\n import unittest\n class MyTestCaseWithRunTest(unittest.TestCase):\n def runTest(self):\n self.assertEqual('foo', 'foo')\n class MyTestCaseWithoutRunTest(unittest.TestCase):\n def runTest(self):\n self.assertEqual('foo', 'foo')\n def test_something(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *MyTestCaseWithRunTest::runTest*\n *MyTestCaseWithoutRunTest::test_something*\n *2 passed*\n \"\"\"\n )"},{"id":6235,"name":"release-3.8.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.8.0\n=======================================\n\nThe pytest team is proud to announce the 3.8.0 release!\n\npytest is a mature Python testing tool with more than a 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n https://docs.pytest.org/en/latest/changelog.html\n\nFor complete documentation, please visit:\n\n https://docs.pytest.org/en/latest/\n\nAs usual, you can upgrade from pypi via:\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* CrazyMerlyn\n* Daniel Hahler\n* Fabio Zadrozny\n* Jeffrey Rackauckas\n* Ronny Pfannschmidt\n* Virgil Dupras\n* dhirensr\n* hoefling\n* wim glenn\n\n\nHappy testing,\nThe Pytest Development Team\n"},{"col":0,"comment":"null","endLoc":63,"header":"def test_isclasscheck_issue53(testdir)","id":6236,"name":"test_isclasscheck_issue53","nodeType":"Function","startLoc":52,"text":"def test_isclasscheck_issue53(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n class _E(object):\n def __getattr__(self, tag):\n pass\n E = _E()\n \"\"\"\n )\n result = testdir.runpytest(testpath)\n assert result.ret == EXIT_NOTESTSCOLLECTED"},{"col":0,"comment":"null","endLoc":86,"header":"def test_setup(testdir)","id":6237,"name":"test_setup","nodeType":"Function","startLoc":66,"text":"def test_setup(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n class MyTestCase(unittest.TestCase):\n def setUp(self):\n self.foo = 1\n def setup_method(self, method):\n self.foo2 = 1\n def test_both(self):\n self.assertEqual(1, self.foo)\n assert self.foo2 == 1\n def teardown_method(self, method):\n assert 0, \"42\"\n\n \"\"\"\n )\n reprec = testdir.inline_run(\"-s\", testpath)\n assert reprec.matchreport(\"test_both\", when=\"call\").passed\n rep = reprec.matchreport(\"test_both\", when=\"teardown\")\n assert rep.failed and \"42\" in str(rep.longrepr)"},{"id":6238,"name":"funcarg_compare.rst","nodeType":"TextFile","path":"doc/en","text":":orphan:\n\n.. _`funcargcompare`:\n\npytest-2.3: reasoning for fixture/funcarg evolution\n=============================================================\n\n**Target audience**: Reading this document requires basic knowledge of\npython testing, xUnit setup methods and the (previous) basic pytest\nfuncarg mechanism, see https://docs.pytest.org/en/latest/historical-notes.html#funcargs-and-pytest-funcarg.\nIf you are new to pytest, then you can simply ignore this\nsection and read the other sections.\n\n.. currentmodule:: _pytest\n\nShortcomings of the previous ``pytest_funcarg__`` mechanism\n--------------------------------------------------------------\n\nThe pre pytest-2.3 funcarg mechanism calls a factory each time a\nfuncarg for a test function is required. If a factory wants to\nre-use a resource across different scopes, it often used\nthe ``request.cached_setup()`` helper to manage caching of\nresources. Here is a basic example how we could implement\na per-session Database object::\n\n # content of conftest.py\n class Database(object):\n def __init__(self):\n print(\"database instance created\")\n def destroy(self):\n print(\"database instance destroyed\")\n\n def pytest_funcarg__db(request):\n return request.cached_setup(setup=DataBase,\n teardown=lambda db: db.destroy,\n scope=\"session\")\n\nThere are several limitations and difficulties with this approach:\n\n1. Scoping funcarg resource creation is not straight forward, instead one must\n understand the intricate cached_setup() method mechanics.\n\n2. parametrizing the \"db\" resource is not straight forward:\n you need to apply a \"parametrize\" decorator or implement a\n :py:func:`~hookspec.pytest_generate_tests` hook\n calling :py:func:`~python.Metafunc.parametrize` which\n performs parametrization at the places where the resource\n is used. Moreover, you need to modify the factory to use an\n ``extrakey`` parameter containing ``request.param`` to the\n :py:func:`~python.Request.cached_setup` call.\n\n3. Multiple parametrized session-scoped resources will be active\n at the same time, making it hard for them to affect global state\n of the application under test.\n\n4. there is no way how you can make use of funcarg factories\n in xUnit setup methods.\n\n5. A non-parametrized fixture function cannot use a parametrized\n funcarg resource if it isn't stated in the test function signature.\n\nAll of these limitations are addressed with pytest-2.3 and its\nimproved :ref:`fixture mechanism `.\n\n\nDirect scoping of fixture/funcarg factories\n--------------------------------------------------------\n\nInstead of calling cached_setup() with a cache scope, you can use the\n:ref:`@pytest.fixture ` decorator and directly state\nthe scope::\n\n @pytest.fixture(scope=\"session\")\n def db(request):\n # factory will only be invoked once per session -\n db = DataBase()\n request.addfinalizer(db.destroy) # destroy when session is finished\n return db\n\nThis factory implementation does not need to call ``cached_setup()`` anymore\nbecause it will only be invoked once per session. Moreover, the\n``request.addfinalizer()`` registers a finalizer according to the specified\nresource scope on which the factory function is operating.\n\n\nDirect parametrization of funcarg resource factories\n----------------------------------------------------------\n\nPreviously, funcarg factories could not directly cause parametrization.\nYou needed to specify a ``@parametrize`` decorator on your test function\nor implement a ``pytest_generate_tests`` hook to perform\nparametrization, i.e. calling a test multiple times with different value\nsets. pytest-2.3 introduces a decorator for use on the factory itself::\n\n @pytest.fixture(params=[\"mysql\", \"pg\"])\n def db(request):\n ... # use request.param\n\nHere the factory will be invoked twice (with the respective \"mysql\"\nand \"pg\" values set as ``request.param`` attributes) and all of\nthe tests requiring \"db\" will run twice as well. The \"mysql\" and\n\"pg\" values will also be used for reporting the test-invocation variants.\n\nThis new way of parametrizing funcarg factories should in many cases\nallow to re-use already written factories because effectively\n``request.param`` was already used when test functions/classes were\nparametrized via\n:py:func:`~_pytest.python.Metafunc.parametrize(indirect=True)` calls.\n\nOf course it's perfectly fine to combine parametrization and scoping::\n\n @pytest.fixture(scope=\"session\", params=[\"mysql\", \"pg\"])\n def db(request):\n if request.param == \"mysql\":\n db = MySQL()\n elif request.param == \"pg\":\n db = PG()\n request.addfinalizer(db.destroy) # destroy when session is finished\n return db\n\nThis would execute all tests requiring the per-session \"db\" resource twice,\nreceiving the values created by the two respective invocations to the\nfactory function.\n\n\nNo ``pytest_funcarg__`` prefix when using @fixture decorator\n-------------------------------------------------------------------\n\nWhen using the ``@fixture`` decorator the name of the function\ndenotes the name under which the resource can be accessed as a function\nargument::\n\n @pytest.fixture()\n def db(request):\n ...\n\nThe name under which the funcarg resource can be requested is ``db``.\n\nYou can still use the \"old\" non-decorator way of specifying funcarg factories\naka::\n\n def pytest_funcarg__db(request):\n ...\n\n\nBut it is then not possible to define scoping and parametrization.\nIt is thus recommended to use the factory decorator.\n\n\nsolving per-session setup / autouse fixtures\n--------------------------------------------------------------\n\npytest for a long time offered a pytest_configure and a pytest_sessionstart\nhook which are often used to setup global resources. This suffers from\nseveral problems:\n\n1. in distributed testing the master process would setup test resources\n that are never needed because it only co-ordinates the test run\n activities of the slave processes.\n\n2. if you only perform a collection (with \"--collect-only\")\n resource-setup will still be executed.\n\n3. If a pytest_sessionstart is contained in some subdirectories\n conftest.py file, it will not be called. This stems from the\n fact that this hook is actually used for reporting, in particular\n the test-header with platform/custom information.\n\nMoreover, it was not easy to define a scoped setup from plugins or\nconftest files other than to implement a ``pytest_runtest_setup()`` hook\nand caring for scoping/caching yourself. And it's virtually impossible\nto do this with parametrization as ``pytest_runtest_setup()`` is called\nduring test execution and parametrization happens at collection time.\n\nIt follows that pytest_configure/session/runtest_setup are often not\nappropriate for implementing common fixture needs. Therefore,\npytest-2.3 introduces :ref:`autouse fixtures` which fully\nintegrate with the generic :ref:`fixture mechanism `\nand obsolete many prior uses of pytest hooks.\n\nfuncargs/fixture discovery now happens at collection time\n---------------------------------------------------------------------\n\nSince pytest-2.3, discovery of fixture/funcarg factories are taken care of\nat collection time. This is more efficient especially for large test suites.\nMoreover, a call to \"pytest --collect-only\" should be able to in the future\nshow a lot of setup-information and thus presents a nice method to get an\noverview of fixture management in your project.\n\n.. _`compatibility notes`:\n\n.. _`funcargscompat`:\n\nConclusion and compatibility notes\n---------------------------------------------------------\n\n**funcargs** were originally introduced to pytest-2.0. In pytest-2.3\nthe mechanism was extended and refined and is now described as\nfixtures:\n\n* previously funcarg factories were specified with a special\n ``pytest_funcarg__NAME`` prefix instead of using the\n ``@pytest.fixture`` decorator.\n\n* Factories received a ``request`` object which managed caching through\n ``request.cached_setup()`` calls and allowed using other funcargs via\n ``request.getfuncargvalue()`` calls. These intricate APIs made it hard\n to do proper parametrization and implement resource caching. The\n new :py:func:`pytest.fixture` decorator allows to declare the scope\n and let pytest figure things out for you.\n\n* if you used parametrization and funcarg factories which made use of\n ``request.cached_setup()`` it is recommended to invest a few minutes\n and simplify your fixture function code to use the :ref:`@pytest.fixture`\n decorator instead. This will also allow to take advantage of\n the automatic per-resource grouping of tests.\n"},{"id":6239,"name":"reportingdemo.rst","nodeType":"TextFile","path":"doc/en/example","text":".. _`tbreportdemo`:\n\nDemo of Python failure reports with pytest\n==========================================\n\nHere is a nice run of several failures and how ``pytest`` presents things:\n\n.. code-block:: pytest\n\n assertion $ pytest failure_demo.py\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR/assertion\n collected 44 items\n\n failure_demo.py FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF [100%]\n\n ================================= FAILURES =================================\n ___________________________ test_generative[3-6] ___________________________\n\n param1 = 3, param2 = 6\n\n @pytest.mark.parametrize(\"param1, param2\", [(3, 6)])\n def test_generative(param1, param2):\n > assert param1 * 2 < param2\n E assert (3 * 2) < 6\n\n failure_demo.py:21: AssertionError\n _________________________ TestFailing.test_simple __________________________\n\n self = \n\n def test_simple(self):\n def f():\n return 42\n\n def g():\n return 43\n\n > assert f() == g()\n E assert 42 == 43\n E + where 42 = .f at 0xdeadbeef>()\n E + and 43 = .g at 0xdeadbeef>()\n\n failure_demo.py:32: AssertionError\n ____________________ TestFailing.test_simple_multiline _____________________\n\n self = \n\n def test_simple_multiline(self):\n > otherfunc_multi(42, 6 * 9)\n\n failure_demo.py:35:\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n\n a = 42, b = 54\n\n def otherfunc_multi(a, b):\n > assert a == b\n E assert 42 == 54\n\n failure_demo.py:16: AssertionError\n ___________________________ TestFailing.test_not ___________________________\n\n self = \n\n def test_not(self):\n def f():\n return 42\n\n > assert not f()\n E assert not 42\n E + where 42 = .f at 0xdeadbeef>()\n\n failure_demo.py:41: AssertionError\n _________________ TestSpecialisedExplanations.test_eq_text _________________\n\n self = \n\n def test_eq_text(self):\n > assert \"spam\" == \"eggs\"\n E AssertionError: assert 'spam' == 'eggs'\n E - spam\n E + eggs\n\n failure_demo.py:46: AssertionError\n _____________ TestSpecialisedExplanations.test_eq_similar_text _____________\n\n self = \n\n def test_eq_similar_text(self):\n > assert \"foo 1 bar\" == \"foo 2 bar\"\n E AssertionError: assert 'foo 1 bar' == 'foo 2 bar'\n E - foo 1 bar\n E ? ^\n E + foo 2 bar\n E ? ^\n\n failure_demo.py:49: AssertionError\n ____________ TestSpecialisedExplanations.test_eq_multiline_text ____________\n\n self = \n\n def test_eq_multiline_text(self):\n > assert \"foo\\nspam\\nbar\" == \"foo\\neggs\\nbar\"\n E AssertionError: assert 'foo\\nspam\\nbar' == 'foo\\neggs\\nbar'\n E foo\n E - spam\n E + eggs\n E bar\n\n failure_demo.py:52: AssertionError\n ______________ TestSpecialisedExplanations.test_eq_long_text _______________\n\n self = \n\n def test_eq_long_text(self):\n a = \"1\" * 100 + \"a\" + \"2\" * 100\n b = \"1\" * 100 + \"b\" + \"2\" * 100\n > assert a == b\n E AssertionError: assert '111111111111...2222222222222' == '1111111111111...2222222222222'\n E Skipping 90 identical leading characters in diff, use -v to show\n E Skipping 91 identical trailing characters in diff, use -v to show\n E - 1111111111a222222222\n E ? ^\n E + 1111111111b222222222\n E ? ^\n\n failure_demo.py:57: AssertionError\n _________ TestSpecialisedExplanations.test_eq_long_text_multiline __________\n\n self = \n\n def test_eq_long_text_multiline(self):\n a = \"1\\n\" * 100 + \"a\" + \"2\\n\" * 100\n b = \"1\\n\" * 100 + \"b\" + \"2\\n\" * 100\n > assert a == b\n E AssertionError: assert '1\\n1\\n1\\n1\\n...n2\\n2\\n2\\n2\\n' == '1\\n1\\n1\\n1\\n1...n2\\n2\\n2\\n2\\n'\n E Skipping 190 identical leading characters in diff, use -v to show\n E Skipping 191 identical trailing characters in diff, use -v to show\n E 1\n E 1\n E 1\n E 1\n E 1...\n E\n E ...Full output truncated (7 lines hidden), use '-vv' to show\n\n failure_demo.py:62: AssertionError\n _________________ TestSpecialisedExplanations.test_eq_list _________________\n\n self = \n\n def test_eq_list(self):\n > assert [0, 1, 2] == [0, 1, 3]\n E assert [0, 1, 2] == [0, 1, 3]\n E At index 2 diff: 2 != 3\n E Use -v to get the full diff\n\n failure_demo.py:65: AssertionError\n ______________ TestSpecialisedExplanations.test_eq_list_long _______________\n\n self = \n\n def test_eq_list_long(self):\n a = [0] * 100 + [1] + [3] * 100\n b = [0] * 100 + [2] + [3] * 100\n > assert a == b\n E assert [0, 0, 0, 0, 0, 0, ...] == [0, 0, 0, 0, 0, 0, ...]\n E At index 100 diff: 1 != 2\n E Use -v to get the full diff\n\n failure_demo.py:70: AssertionError\n _________________ TestSpecialisedExplanations.test_eq_dict _________________\n\n self = \n\n def test_eq_dict(self):\n > assert {\"a\": 0, \"b\": 1, \"c\": 0} == {\"a\": 0, \"b\": 2, \"d\": 0}\n E AssertionError: assert {'a': 0, 'b': 1, 'c': 0} == {'a': 0, 'b': 2, 'd': 0}\n E Omitting 1 identical items, use -vv to show\n E Differing items:\n E {'b': 1} != {'b': 2}\n E Left contains 1 more item:\n E {'c': 0}\n E Right contains 1 more item:\n E {'d': 0}...\n E\n E ...Full output truncated (2 lines hidden), use '-vv' to show\n\n failure_demo.py:73: AssertionError\n _________________ TestSpecialisedExplanations.test_eq_set __________________\n\n self = \n\n def test_eq_set(self):\n > assert {0, 10, 11, 12} == {0, 20, 21}\n E AssertionError: assert {0, 10, 11, 12} == {0, 20, 21}\n E Extra items in the left set:\n E 10\n E 11\n E 12\n E Extra items in the right set:\n E 20\n E 21...\n E\n E ...Full output truncated (2 lines hidden), use '-vv' to show\n\n failure_demo.py:76: AssertionError\n _____________ TestSpecialisedExplanations.test_eq_longer_list ______________\n\n self = \n\n def test_eq_longer_list(self):\n > assert [1, 2] == [1, 2, 3]\n E assert [1, 2] == [1, 2, 3]\n E Right contains one more item: 3\n E Use -v to get the full diff\n\n failure_demo.py:79: AssertionError\n _________________ TestSpecialisedExplanations.test_in_list _________________\n\n self = \n\n def test_in_list(self):\n > assert 1 in [0, 2, 3, 4, 5]\n E assert 1 in [0, 2, 3, 4, 5]\n\n failure_demo.py:82: AssertionError\n __________ TestSpecialisedExplanations.test_not_in_text_multiline __________\n\n self = \n\n def test_not_in_text_multiline(self):\n text = \"some multiline\\ntext\\nwhich\\nincludes foo\\nand a\\ntail\"\n > assert \"foo\" not in text\n E AssertionError: assert 'foo' not in 'some multiline\\ntext\\nw...ncludes foo\\nand a\\ntail'\n E 'foo' is contained here:\n E some multiline\n E text\n E which\n E includes foo\n E ? +++\n E and a...\n E\n E ...Full output truncated (2 lines hidden), use '-vv' to show\n\n failure_demo.py:86: AssertionError\n ___________ TestSpecialisedExplanations.test_not_in_text_single ____________\n\n self = \n\n def test_not_in_text_single(self):\n text = \"single foo line\"\n > assert \"foo\" not in text\n E AssertionError: assert 'foo' not in 'single foo line'\n E 'foo' is contained here:\n E single foo line\n E ? +++\n\n failure_demo.py:90: AssertionError\n _________ TestSpecialisedExplanations.test_not_in_text_single_long _________\n\n self = \n\n def test_not_in_text_single_long(self):\n text = \"head \" * 50 + \"foo \" + \"tail \" * 20\n > assert \"foo\" not in text\n E AssertionError: assert 'foo' not in 'head head head head hea...ail tail tail tail tail '\n E 'foo' is contained here:\n E head head foo tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail\n E ? +++\n\n failure_demo.py:94: AssertionError\n ______ TestSpecialisedExplanations.test_not_in_text_single_long_term _______\n\n self = \n\n def test_not_in_text_single_long_term(self):\n text = \"head \" * 50 + \"f\" * 70 + \"tail \" * 20\n > assert \"f\" * 70 not in text\n E AssertionError: assert 'fffffffffff...ffffffffffff' not in 'head head he...l tail tail '\n E 'ffffffffffffffffff...fffffffffffffffffff' is contained here:\n E head head fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffftail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail\n E ? ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n failure_demo.py:98: AssertionError\n ______________ TestSpecialisedExplanations.test_eq_dataclass _______________\n\n self = \n\n def test_eq_dataclass(self):\n from dataclasses import dataclass\n\n @dataclass\n class Foo(object):\n a: int\n b: str\n\n left = Foo(1, \"b\")\n right = Foo(1, \"c\")\n > assert left == right\n E AssertionError: assert TestSpecialis...oo(a=1, b='b') == TestSpecialise...oo(a=1, b='c')\n E Omitting 1 identical items, use -vv to show\n E Differing attributes:\n E b: 'b' != 'c'\n\n failure_demo.py:110: AssertionError\n ________________ TestSpecialisedExplanations.test_eq_attrs _________________\n\n self = \n\n def test_eq_attrs(self):\n import attr\n\n @attr.s\n class Foo(object):\n a = attr.ib()\n b = attr.ib()\n\n left = Foo(1, \"b\")\n right = Foo(1, \"c\")\n > assert left == right\n E AssertionError: assert Foo(a=1, b='b') == Foo(a=1, b='c')\n E Omitting 1 identical items, use -vv to show\n E Differing attributes:\n E b: 'b' != 'c'\n\n failure_demo.py:122: AssertionError\n ______________________________ test_attribute ______________________________\n\n def test_attribute():\n class Foo(object):\n b = 1\n\n i = Foo()\n > assert i.b == 2\n E assert 1 == 2\n E + where 1 = .Foo object at 0xdeadbeef>.b\n\n failure_demo.py:130: AssertionError\n _________________________ test_attribute_instance __________________________\n\n def test_attribute_instance():\n class Foo(object):\n b = 1\n\n > assert Foo().b == 2\n E AssertionError: assert 1 == 2\n E + where 1 = .Foo object at 0xdeadbeef>.b\n E + where .Foo object at 0xdeadbeef> = .Foo'>()\n\n failure_demo.py:137: AssertionError\n __________________________ test_attribute_failure __________________________\n\n def test_attribute_failure():\n class Foo(object):\n def _get_b(self):\n raise Exception(\"Failed to get attrib\")\n\n b = property(_get_b)\n\n i = Foo()\n > assert i.b == 2\n\n failure_demo.py:148:\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n\n self = .Foo object at 0xdeadbeef>\n\n def _get_b(self):\n > raise Exception(\"Failed to get attrib\")\n E Exception: Failed to get attrib\n\n failure_demo.py:143: Exception\n _________________________ test_attribute_multiple __________________________\n\n def test_attribute_multiple():\n class Foo(object):\n b = 1\n\n class Bar(object):\n b = 2\n\n > assert Foo().b == Bar().b\n E AssertionError: assert 1 == 2\n E + where 1 = .Foo object at 0xdeadbeef>.b\n E + where .Foo object at 0xdeadbeef> = .Foo'>()\n E + and 2 = .Bar object at 0xdeadbeef>.b\n E + where .Bar object at 0xdeadbeef> = .Bar'>()\n\n failure_demo.py:158: AssertionError\n __________________________ TestRaises.test_raises __________________________\n\n self = \n\n def test_raises(self):\n s = \"qwe\"\n > raises(TypeError, int, s)\n E ValueError: invalid literal for int() with base 10: 'qwe'\n\n failure_demo.py:168: ValueError\n ______________________ TestRaises.test_raises_doesnt _______________________\n\n self = \n\n def test_raises_doesnt(self):\n > raises(IOError, int, \"3\")\n E Failed: DID NOT RAISE \n\n failure_demo.py:171: Failed\n __________________________ TestRaises.test_raise ___________________________\n\n self = \n\n def test_raise(self):\n > raise ValueError(\"demo error\")\n E ValueError: demo error\n\n failure_demo.py:174: ValueError\n ________________________ TestRaises.test_tupleerror ________________________\n\n self = \n\n def test_tupleerror(self):\n > a, b = [1] # NOQA\n E ValueError: not enough values to unpack (expected 2, got 1)\n\n failure_demo.py:177: ValueError\n ______ TestRaises.test_reinterpret_fails_with_print_for_the_fun_of_it ______\n\n self = \n\n def test_reinterpret_fails_with_print_for_the_fun_of_it(self):\n items = [1, 2, 3]\n print(\"items is %r\" % items)\n > a, b = items.pop()\n E TypeError: 'int' object is not iterable\n\n failure_demo.py:182: TypeError\n --------------------------- Captured stdout call ---------------------------\n items is [1, 2, 3]\n ________________________ TestRaises.test_some_error ________________________\n\n self = \n\n def test_some_error(self):\n > if namenotexi: # NOQA\n E NameError: name 'namenotexi' is not defined\n\n failure_demo.py:185: NameError\n ____________________ test_dynamic_compile_shows_nicely _____________________\n\n def test_dynamic_compile_shows_nicely():\n import imp\n import sys\n\n src = \"def foo():\\n assert 1 == 0\\n\"\n name = \"abc-123\"\n module = imp.new_module(name)\n code = _pytest._code.compile(src, name, \"exec\")\n exec(code, module.__dict__)\n sys.modules[name] = module\n > module.foo()\n\n failure_demo.py:203:\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n\n def foo():\n > assert 1 == 0\n E AssertionError\n\n <0-codegen 'abc-123' $REGENDOC_TMPDIR/assertion/failure_demo.py:200>:2: AssertionError\n ____________________ TestMoreErrors.test_complex_error _____________________\n\n self = \n\n def test_complex_error(self):\n def f():\n return 44\n\n def g():\n return 43\n\n > somefunc(f(), g())\n\n failure_demo.py:214:\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n failure_demo.py:12: in somefunc\n otherfunc(x, y)\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n\n a = 44, b = 43\n\n def otherfunc(a, b):\n > assert a == b\n E assert 44 == 43\n\n failure_demo.py:8: AssertionError\n ___________________ TestMoreErrors.test_z1_unpack_error ____________________\n\n self = \n\n def test_z1_unpack_error(self):\n items = []\n > a, b = items\n E ValueError: not enough values to unpack (expected 2, got 0)\n\n failure_demo.py:218: ValueError\n ____________________ TestMoreErrors.test_z2_type_error _____________________\n\n self = \n\n def test_z2_type_error(self):\n items = 3\n > a, b = items\n E TypeError: 'int' object is not iterable\n\n failure_demo.py:222: TypeError\n ______________________ TestMoreErrors.test_startswith ______________________\n\n self = \n\n def test_startswith(self):\n s = \"123\"\n g = \"456\"\n > assert s.startswith(g)\n E AssertionError: assert False\n E + where False = ('456')\n E + where = '123'.startswith\n\n failure_demo.py:227: AssertionError\n __________________ TestMoreErrors.test_startswith_nested ___________________\n\n self = \n\n def test_startswith_nested(self):\n def f():\n return \"123\"\n\n def g():\n return \"456\"\n\n > assert f().startswith(g())\n E AssertionError: assert False\n E + where False = ('456')\n E + where = '123'.startswith\n E + where '123' = .f at 0xdeadbeef>()\n E + and '456' = .g at 0xdeadbeef>()\n\n failure_demo.py:236: AssertionError\n _____________________ TestMoreErrors.test_global_func ______________________\n\n self = \n\n def test_global_func(self):\n > assert isinstance(globf(42), float)\n E assert False\n E + where False = isinstance(43, float)\n E + where 43 = globf(42)\n\n failure_demo.py:239: AssertionError\n _______________________ TestMoreErrors.test_instance _______________________\n\n self = \n\n def test_instance(self):\n self.x = 6 * 7\n > assert self.x != 42\n E assert 42 != 42\n E + where 42 = .x\n\n failure_demo.py:243: AssertionError\n _______________________ TestMoreErrors.test_compare ________________________\n\n self = \n\n def test_compare(self):\n > assert globf(10) < 5\n E assert 11 < 5\n E + where 11 = globf(10)\n\n failure_demo.py:246: AssertionError\n _____________________ TestMoreErrors.test_try_finally ______________________\n\n self = \n\n def test_try_finally(self):\n x = 1\n try:\n > assert x == 0\n E assert 1 == 0\n\n failure_demo.py:251: AssertionError\n ___________________ TestCustomAssertMsg.test_single_line ___________________\n\n self = \n\n def test_single_line(self):\n class A(object):\n a = 1\n\n b = 2\n > assert A.a == b, \"A.a appears not to be b\"\n E AssertionError: A.a appears not to be b\n E assert 1 == 2\n E + where 1 = .A'>.a\n\n failure_demo.py:262: AssertionError\n ____________________ TestCustomAssertMsg.test_multiline ____________________\n\n self = \n\n def test_multiline(self):\n class A(object):\n a = 1\n\n b = 2\n > assert (\n A.a == b\n ), \"A.a appears not to be b\\nor does not appear to be b\\none of those\"\n E AssertionError: A.a appears not to be b\n E or does not appear to be b\n E one of those\n E assert 1 == 2\n E + where 1 = .A'>.a\n\n failure_demo.py:269: AssertionError\n ___________________ TestCustomAssertMsg.test_custom_repr ___________________\n\n self = \n\n def test_custom_repr(self):\n class JSON(object):\n a = 1\n\n def __repr__(self):\n return \"This is JSON\\n{\\n 'foo': 'bar'\\n}\"\n\n a = JSON()\n b = 2\n > assert a.a == b, a\n E AssertionError: This is JSON\n E {\n E 'foo': 'bar'\n E }\n E assert 1 == 2\n E + where 1 = This is JSON\\n{\\n 'foo': 'bar'\\n}.a\n\n failure_demo.py:282: AssertionError\n ======================== 44 failed in 0.12 seconds =========================\n"},{"col":0,"comment":"null","endLoc":750,"header":"def test_log_level_not_changed_by_default(testdir)","id":6240,"name":"test_log_level_not_changed_by_default","nodeType":"Function","startLoc":741,"text":"def test_log_level_not_changed_by_default(testdir):\n testdir.makepyfile(\n \"\"\"\n import logging\n def test_log_file():\n assert logging.getLogger().level == logging.WARNING\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines([\"* 1 passed in *\"])"},{"col":4,"comment":"\n test --pyargs option with packages with path containing symlink can\n have conftest.py in their package (#2985)\n ","endLoc":829,"header":"@pytest.mark.skipif(not hasattr(os, \"symlink\"), reason=\"requires symlinks\")\n def test_cmdline_python_package_symlink(self, testdir, monkeypatch)","id":6241,"name":"test_cmdline_python_package_symlink","nodeType":"Function","startLoc":753,"text":"@pytest.mark.skipif(not hasattr(os, \"symlink\"), reason=\"requires symlinks\")\n def test_cmdline_python_package_symlink(self, testdir, monkeypatch):\n \"\"\"\n test --pyargs option with packages with path containing symlink can\n have conftest.py in their package (#2985)\n \"\"\"\n # dummy check that we can actually create symlinks: on Windows `os.symlink` is available,\n # but normal users require special admin privileges to create symlinks.\n if sys.platform == \"win32\":\n try:\n os.symlink(\n str(testdir.tmpdir.ensure(\"tmpfile\")),\n str(testdir.tmpdir.join(\"tmpfile2\")),\n )\n except OSError as e:\n pytest.skip(six.text_type(e.args[0]))\n monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", raising=False)\n\n dirname = \"lib\"\n d = testdir.mkdir(dirname)\n foo = d.mkdir(\"foo\")\n foo.ensure(\"__init__.py\")\n lib = foo.mkdir(\"bar\")\n lib.ensure(\"__init__.py\")\n lib.join(\"test_bar.py\").write(\n \"def test_bar(): pass\\ndef test_other(a_fixture):pass\"\n )\n lib.join(\"conftest.py\").write(\n \"import pytest\\n@pytest.fixture\\ndef a_fixture():pass\"\n )\n\n d_local = testdir.mkdir(\"local\")\n symlink_location = os.path.join(str(d_local), \"lib\")\n if six.PY2:\n os.symlink(str(d), symlink_location)\n else:\n os.symlink(str(d), symlink_location, target_is_directory=True)\n\n # The structure of the test directory is now:\n # .\n # ├── local\n # │ └── lib -> ../lib\n # └── lib\n # └── foo\n # ├── __init__.py\n # └── bar\n # ├── __init__.py\n # ├── conftest.py\n # └── test_bar.py\n\n # NOTE: the different/reversed ordering is intentional here.\n search_path = [\"lib\", os.path.join(\"local\", \"lib\")]\n monkeypatch.setenv(\"PYTHONPATH\", prepend_pythonpath(*search_path))\n for p in search_path:\n monkeypatch.syspath_prepend(p)\n\n # module picked up in symlink-ed directory:\n # It picks up local/lib/foo/bar (symlink) via sys.path.\n result = testdir.runpytest(\"--pyargs\", \"-v\", \"foo.bar\")\n testdir.chdir()\n assert result.ret == 0\n if hasattr(py.path.local, \"mksymlinkto\"):\n result.stdout.fnmatch_lines(\n [\n \"lib/foo/bar/test_bar.py::test_bar PASSED*\",\n \"lib/foo/bar/test_bar.py::test_other PASSED*\",\n \"*2 passed*\",\n ]\n )\n else:\n result.stdout.fnmatch_lines(\n [\n \"*lib/foo/bar/test_bar.py::test_bar PASSED*\",\n \"*lib/foo/bar/test_bar.py::test_other PASSED*\",\n \"*2 passed*\",\n ]\n )"},{"col":0,"comment":"null","endLoc":789,"header":"def test_log_file_ini(testdir)","id":6242,"name":"test_log_file_ini","nodeType":"Function","startLoc":753,"text":"def test_log_file_ini(testdir):\n log_file = testdir.tmpdir.join(\"pytest.log\").strpath\n\n testdir.makeini(\n \"\"\"\n [pytest]\n log_file={}\n log_file_level=WARNING\n \"\"\".format(\n log_file\n )\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n def test_log_file(request):\n plugin = request.config.pluginmanager.getplugin('logging-plugin')\n assert plugin.log_file_handler.level == logging.WARNING\n logging.getLogger('catchlog').info(\"This log message won't be shown\")\n logging.getLogger('catchlog').warning(\"This log message will be shown\")\n print('PASSED')\n \"\"\"\n )\n\n result = testdir.runpytest(\"-s\")\n\n # fnmatch_lines does an assertion internally\n result.stdout.fnmatch_lines([\"test_log_file_ini.py PASSED\"])\n\n # make sure that that we get a '0' exit code for the testsuite\n assert result.ret == 0\n assert os.path.isfile(log_file)\n with open(log_file) as rfh:\n contents = rfh.read()\n assert \"This log message will be shown\" in contents\n assert \"This log message won't be shown\" not in contents"},{"col":4,"comment":"Assert that the specified outcomes appear with the respective\n numbers (0 means it didn't occur) in the text output from a test run.\n\n ","endLoc":430,"header":"def assert_outcomes(\n self, passed=0, skipped=0, failed=0, error=0, xpassed=0, xfailed=0\n )","id":6243,"name":"assert_outcomes","nodeType":"Function","startLoc":406,"text":"def assert_outcomes(\n self, passed=0, skipped=0, failed=0, error=0, xpassed=0, xfailed=0\n ):\n \"\"\"Assert that the specified outcomes appear with the respective\n numbers (0 means it didn't occur) in the text output from a test run.\n\n \"\"\"\n d = self.parseoutcomes()\n obtained = {\n \"passed\": d.get(\"passed\", 0),\n \"skipped\": d.get(\"skipped\", 0),\n \"failed\": d.get(\"failed\", 0),\n \"error\": d.get(\"error\", 0),\n \"xpassed\": d.get(\"xpassed\", 0),\n \"xfailed\": d.get(\"xfailed\", 0),\n }\n expected = {\n \"passed\": passed,\n \"skipped\": skipped,\n \"failed\": failed,\n \"error\": error,\n \"xpassed\": xpassed,\n \"xfailed\": xfailed,\n }\n assert obtained == expected"},{"fileName":"skipping.py","filePath":"src/_pytest","id":6245,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\" support for skip/xfail functions and markers. \"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom _pytest.config import hookimpl\nfrom _pytest.mark.evaluate import MarkEvaluator\nfrom _pytest.outcomes import fail\nfrom _pytest.outcomes import skip\nfrom _pytest.outcomes import xfail\n\n\ndef pytest_addoption(parser):\n group = parser.getgroup(\"general\")\n group.addoption(\n \"--runxfail\",\n action=\"store_true\",\n dest=\"runxfail\",\n default=False,\n help=\"report the results of xfail tests as if they were not marked\",\n )\n\n parser.addini(\n \"xfail_strict\",\n \"default for the strict parameter of xfail \"\n \"markers when not given explicitly (default: False)\",\n default=False,\n type=\"bool\",\n )\n\n\ndef pytest_configure(config):\n if config.option.runxfail:\n # yay a hack\n import pytest\n\n old = pytest.xfail\n config._cleanup.append(lambda: setattr(pytest, \"xfail\", old))\n\n def nop(*args, **kwargs):\n pass\n\n nop.Exception = xfail.Exception\n setattr(pytest, \"xfail\", nop)\n\n config.addinivalue_line(\n \"markers\",\n \"skip(reason=None): skip the given test function with an optional reason. \"\n 'Example: skip(reason=\"no way of currently testing this\") skips the '\n \"test.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"skipif(condition): skip the given test function if eval(condition) \"\n \"results in a True value. Evaluation happens within the \"\n \"module global context. Example: skipif('sys.platform == \\\"win32\\\"') \"\n \"skips the test if we are on the win32 platform. see \"\n \"https://docs.pytest.org/en/latest/skipping.html\",\n )\n config.addinivalue_line(\n \"markers\",\n \"xfail(condition, reason=None, run=True, raises=None, strict=False): \"\n \"mark the test function as an expected failure if eval(condition) \"\n \"has a True value. Optionally specify a reason for better reporting \"\n \"and run=False if you don't even want to execute the test function. \"\n \"If only specific exception(s) are expected, you can list them in \"\n \"raises, and if the test fails in other ways, it will be reported as \"\n \"a true failure. See https://docs.pytest.org/en/latest/skipping.html\",\n )\n\n\n@hookimpl(tryfirst=True)\ndef pytest_runtest_setup(item):\n # Check if skip or skipif are specified as pytest marks\n item._skipped_by_mark = False\n eval_skipif = MarkEvaluator(item, \"skipif\")\n if eval_skipif.istrue():\n item._skipped_by_mark = True\n skip(eval_skipif.getexplanation())\n\n for skip_info in item.iter_markers(name=\"skip\"):\n item._skipped_by_mark = True\n if \"reason\" in skip_info.kwargs:\n skip(skip_info.kwargs[\"reason\"])\n elif skip_info.args:\n skip(skip_info.args[0])\n else:\n skip(\"unconditional skip\")\n\n item._evalxfail = MarkEvaluator(item, \"xfail\")\n check_xfail_no_run(item)\n\n\n@hookimpl(hookwrapper=True)\ndef pytest_pyfunc_call(pyfuncitem):\n check_xfail_no_run(pyfuncitem)\n outcome = yield\n passed = outcome.excinfo is None\n if passed:\n check_strict_xfail(pyfuncitem)\n\n\ndef check_xfail_no_run(item):\n \"\"\"check xfail(run=False)\"\"\"\n if not item.config.option.runxfail:\n evalxfail = item._evalxfail\n if evalxfail.istrue():\n if not evalxfail.get(\"run\", True):\n xfail(\"[NOTRUN] \" + evalxfail.getexplanation())\n\n\ndef check_strict_xfail(pyfuncitem):\n \"\"\"check xfail(strict=True) for the given PASSING test\"\"\"\n evalxfail = pyfuncitem._evalxfail\n if evalxfail.istrue():\n strict_default = pyfuncitem.config.getini(\"xfail_strict\")\n is_strict_xfail = evalxfail.get(\"strict\", strict_default)\n if is_strict_xfail:\n del pyfuncitem._evalxfail\n explanation = evalxfail.getexplanation()\n fail(\"[XPASS(strict)] \" + explanation, pytrace=False)\n\n\n@hookimpl(hookwrapper=True)\ndef pytest_runtest_makereport(item, call):\n outcome = yield\n rep = outcome.get_result()\n evalxfail = getattr(item, \"_evalxfail\", None)\n # unitttest special case, see setting of _unexpectedsuccess\n if hasattr(item, \"_unexpectedsuccess\") and rep.when == \"call\":\n from _pytest.compat import _is_unittest_unexpected_success_a_failure\n\n if item._unexpectedsuccess:\n rep.longrepr = \"Unexpected success: {}\".format(item._unexpectedsuccess)\n else:\n rep.longrepr = \"Unexpected success\"\n if _is_unittest_unexpected_success_a_failure():\n rep.outcome = \"failed\"\n else:\n rep.outcome = \"passed\"\n rep.wasxfail = rep.longrepr\n elif item.config.option.runxfail:\n pass # don't interefere\n elif call.excinfo and call.excinfo.errisinstance(xfail.Exception):\n rep.wasxfail = \"reason: \" + call.excinfo.value.msg\n rep.outcome = \"skipped\"\n elif evalxfail and not rep.skipped and evalxfail.wasvalid() and evalxfail.istrue():\n if call.excinfo:\n if evalxfail.invalidraise(call.excinfo.value):\n rep.outcome = \"failed\"\n else:\n rep.outcome = \"skipped\"\n rep.wasxfail = evalxfail.getexplanation()\n elif call.when == \"call\":\n strict_default = item.config.getini(\"xfail_strict\")\n is_strict_xfail = evalxfail.get(\"strict\", strict_default)\n explanation = evalxfail.getexplanation()\n if is_strict_xfail:\n rep.outcome = \"failed\"\n rep.longrepr = \"[XPASS(strict)] {}\".format(explanation)\n else:\n rep.outcome = \"passed\"\n rep.wasxfail = explanation\n elif (\n getattr(item, \"_skipped_by_mark\", False)\n and rep.skipped\n and type(rep.longrepr) is tuple\n ):\n # skipped by mark.skipif; change the location of the failure\n # to point to the item definition, otherwise it will display\n # the location of where the skip exception was raised within pytest\n filename, line, reason = rep.longrepr\n filename, line = item.location[:2]\n rep.longrepr = filename, line, reason\n\n\n# called by terminalreporter progress reporting\n\n\ndef pytest_report_teststatus(report):\n if hasattr(report, \"wasxfail\"):\n if report.skipped:\n return \"xfailed\", \"x\", \"XFAIL\"\n elif report.passed:\n return \"xpassed\", \"X\", \"XPASS\"\n"},{"col":0,"comment":"null","endLoc":30,"header":"def pytest_addoption(parser)","id":6246,"name":"pytest_addoption","nodeType":"Function","startLoc":14,"text":"def pytest_addoption(parser):\n group = parser.getgroup(\"general\")\n group.addoption(\n \"--runxfail\",\n action=\"store_true\",\n dest=\"runxfail\",\n default=False,\n help=\"report the results of xfail tests as if they were not marked\",\n )\n\n parser.addini(\n \"xfail_strict\",\n \"default for the strict parameter of xfail \"\n \"markers when not given explicitly (default: False)\",\n default=False,\n type=\"bool\",\n )"},{"col":0,"comment":"null","endLoc":70,"header":"def pytest_configure(config)","id":6247,"name":"pytest_configure","nodeType":"Function","startLoc":33,"text":"def pytest_configure(config):\n if config.option.runxfail:\n # yay a hack\n import pytest\n\n old = pytest.xfail\n config._cleanup.append(lambda: setattr(pytest, \"xfail\", old))\n\n def nop(*args, **kwargs):\n pass\n\n nop.Exception = xfail.Exception\n setattr(pytest, \"xfail\", nop)\n\n config.addinivalue_line(\n \"markers\",\n \"skip(reason=None): skip the given test function with an optional reason. \"\n 'Example: skip(reason=\"no way of currently testing this\") skips the '\n \"test.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"skipif(condition): skip the given test function if eval(condition) \"\n \"results in a True value. Evaluation happens within the \"\n \"module global context. Example: skipif('sys.platform == \\\"win32\\\"') \"\n \"skips the test if we are on the win32 platform. see \"\n \"https://docs.pytest.org/en/latest/skipping.html\",\n )\n config.addinivalue_line(\n \"markers\",\n \"xfail(condition, reason=None, run=True, raises=None, strict=False): \"\n \"mark the test function as an expected failure if eval(condition) \"\n \"has a True value. Optionally specify a reason for better reporting \"\n \"and run=False if you don't even want to execute the test function. \"\n \"If only specific exception(s) are expected, you can list them in \"\n \"raises, and if the test fails in other ways, it will be reported as \"\n \"a true failure. See https://docs.pytest.org/en/latest/skipping.html\",\n )"},{"col":31,"endLoc":39,"id":6248,"nodeType":"Lambda","startLoc":39,"text":"lambda: setattr(pytest, \"xfail\", old)"},{"col":0,"comment":"null","endLoc":828,"header":"def test_log_file_ini_level(testdir)","id":6249,"name":"test_log_file_ini_level","nodeType":"Function","startLoc":792,"text":"def test_log_file_ini_level(testdir):\n log_file = testdir.tmpdir.join(\"pytest.log\").strpath\n\n testdir.makeini(\n \"\"\"\n [pytest]\n log_file={}\n log_file_level = INFO\n \"\"\".format(\n log_file\n )\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n import logging\n def test_log_file(request):\n plugin = request.config.pluginmanager.getplugin('logging-plugin')\n assert plugin.log_file_handler.level == logging.INFO\n logging.getLogger('catchlog').debug(\"This log message won't be shown\")\n logging.getLogger('catchlog').info(\"This log message will be shown\")\n print('PASSED')\n \"\"\"\n )\n\n result = testdir.runpytest(\"-s\")\n\n # fnmatch_lines does an assertion internally\n result.stdout.fnmatch_lines([\"test_log_file_ini_level.py PASSED\"])\n\n # make sure that that we get a '0' exit code for the testsuite\n assert result.ret == 0\n assert os.path.isfile(log_file)\n with open(log_file) as rfh:\n contents = rfh.read()\n assert \"This log message will be shown\" in contents\n assert \"This log message won't be shown\" not in contents"},{"className":"TestBooleanCondition","col":0,"comment":"null","endLoc":1061,"id":6250,"nodeType":"Class","startLoc":1009,"text":"class TestBooleanCondition(object):\n def test_skipif(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skipif(True, reason=\"True123\")\n def test_func1():\n pass\n @pytest.mark.skipif(False, reason=\"True123\")\n def test_func2():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n \"\"\"\n *1 passed*1 skipped*\n \"\"\"\n )\n\n def test_skipif_noreason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skipif(True)\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *1 error*\n \"\"\"\n )\n\n def test_xfail(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(True, reason=\"True123\")\n def test_func():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"-rxs\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *XFAIL*\n *True123*\n *1 xfail*\n \"\"\"\n )"},{"col":4,"comment":"null","endLoc":1027,"header":"def test_skipif(self, testdir)","id":6251,"name":"test_skipif","nodeType":"Function","startLoc":1010,"text":"def test_skipif(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skipif(True, reason=\"True123\")\n def test_func1():\n pass\n @pytest.mark.skipif(False, reason=\"True123\")\n def test_func2():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n \"\"\"\n *1 passed*1 skipped*\n \"\"\"\n )"},{"col":0,"comment":"null","endLoc":101,"header":"@hookimpl(hookwrapper=True)\ndef pytest_pyfunc_call(pyfuncitem)","id":6252,"name":"pytest_pyfunc_call","nodeType":"Function","startLoc":95,"text":"@hookimpl(hookwrapper=True)\ndef pytest_pyfunc_call(pyfuncitem):\n check_xfail_no_run(pyfuncitem)\n outcome = yield\n passed = outcome.excinfo is None\n if passed:\n check_strict_xfail(pyfuncitem)"},{"col":4,"comment":"null","endLoc":1043,"header":"def test_skipif_noreason(self, testdir)","id":6253,"name":"test_skipif_noreason","nodeType":"Function","startLoc":1029,"text":"def test_skipif_noreason(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skipif(True)\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *1 error*\n \"\"\"\n )"},{"col":4,"comment":"null","endLoc":1061,"header":"def test_xfail(self, testdir)","id":6254,"name":"test_xfail","nodeType":"Function","startLoc":1045,"text":"def test_xfail(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail(True, reason=\"True123\")\n def test_func():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"-rxs\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *XFAIL*\n *True123*\n *1 xfail*\n \"\"\"\n )"},{"col":0,"comment":"check xfail(strict=True) for the given PASSING test","endLoc":122,"header":"def check_strict_xfail(pyfuncitem)","id":6255,"name":"check_strict_xfail","nodeType":"Function","startLoc":113,"text":"def check_strict_xfail(pyfuncitem):\n \"\"\"check xfail(strict=True) for the given PASSING test\"\"\"\n evalxfail = pyfuncitem._evalxfail\n if evalxfail.istrue():\n strict_default = pyfuncitem.config.getini(\"xfail_strict\")\n is_strict_xfail = evalxfail.get(\"strict\", strict_default)\n if is_strict_xfail:\n del pyfuncitem._evalxfail\n explanation = evalxfail.getexplanation()\n fail(\"[XPASS(strict)] \" + explanation, pytrace=False)"},{"col":0,"comment":"null","endLoc":732,"header":"def test_skip_not_report_default(testdir)","id":6256,"name":"test_skip_not_report_default","nodeType":"Function","startLoc":718,"text":"def test_skip_not_report_default(testdir):\n p = testdir.makepyfile(\n test_one=\"\"\"\n import pytest\n def test_this():\n pytest.skip(\"hello\")\n \"\"\"\n )\n result = testdir.runpytest(p, \"-v\")\n result.stdout.fnmatch_lines(\n [\n # \"*HINT*use*-r*\",\n \"*1 skipped*\"\n ]\n )"},{"col":0,"comment":"null","endLoc":749,"header":"def test_skipif_class(testdir)","id":6257,"name":"test_skipif_class","nodeType":"Function","startLoc":735,"text":"def test_skipif_class(testdir):\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n\n class TestClass(object):\n pytestmark = pytest.mark.skipif(\"True\")\n def test_that(self):\n assert 0\n def test_though(self):\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*2 skipped*\"])"},{"col":0,"comment":"null","endLoc":175,"header":"@hookimpl(hookwrapper=True)\ndef pytest_runtest_makereport(item, call)","id":6258,"name":"pytest_runtest_makereport","nodeType":"Function","startLoc":125,"text":"@hookimpl(hookwrapper=True)\ndef pytest_runtest_makereport(item, call):\n outcome = yield\n rep = outcome.get_result()\n evalxfail = getattr(item, \"_evalxfail\", None)\n # unitttest special case, see setting of _unexpectedsuccess\n if hasattr(item, \"_unexpectedsuccess\") and rep.when == \"call\":\n from _pytest.compat import _is_unittest_unexpected_success_a_failure\n\n if item._unexpectedsuccess:\n rep.longrepr = \"Unexpected success: {}\".format(item._unexpectedsuccess)\n else:\n rep.longrepr = \"Unexpected success\"\n if _is_unittest_unexpected_success_a_failure():\n rep.outcome = \"failed\"\n else:\n rep.outcome = \"passed\"\n rep.wasxfail = rep.longrepr\n elif item.config.option.runxfail:\n pass # don't interefere\n elif call.excinfo and call.excinfo.errisinstance(xfail.Exception):\n rep.wasxfail = \"reason: \" + call.excinfo.value.msg\n rep.outcome = \"skipped\"\n elif evalxfail and not rep.skipped and evalxfail.wasvalid() and evalxfail.istrue():\n if call.excinfo:\n if evalxfail.invalidraise(call.excinfo.value):\n rep.outcome = \"failed\"\n else:\n rep.outcome = \"skipped\"\n rep.wasxfail = evalxfail.getexplanation()\n elif call.when == \"call\":\n strict_default = item.config.getini(\"xfail_strict\")\n is_strict_xfail = evalxfail.get(\"strict\", strict_default)\n explanation = evalxfail.getexplanation()\n if is_strict_xfail:\n rep.outcome = \"failed\"\n rep.longrepr = \"[XPASS(strict)] {}\".format(explanation)\n else:\n rep.outcome = \"passed\"\n rep.wasxfail = explanation\n elif (\n getattr(item, \"_skipped_by_mark\", False)\n and rep.skipped\n and type(rep.longrepr) is tuple\n ):\n # skipped by mark.skipif; change the location of the failure\n # to point to the item definition, otherwise it will display\n # the location of where the skip exception was raised within pytest\n filename, line, reason = rep.longrepr\n filename, line = item.location[:2]\n rep.longrepr = filename, line, reason"},{"col":0,"comment":"null","endLoc":772,"header":"def test_skipped_reasons_functional(testdir)","id":6259,"name":"test_skipped_reasons_functional","nodeType":"Function","startLoc":752,"text":"def test_skipped_reasons_functional(testdir):\n testdir.makepyfile(\n test_one=\"\"\"\n from conftest import doskip\n def setup_function(func):\n doskip()\n def test_func():\n pass\n class TestClass(object):\n def test_method(self):\n doskip()\n \"\"\",\n conftest=\"\"\"\n import pytest\n def doskip():\n pytest.skip('test')\n \"\"\",\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines([\"*SKIP*2*conftest.py:4: test\"])\n assert result.ret == 0"},{"col":0,"comment":"null","endLoc":791,"header":"def test_skipped_folding(testdir)","id":6260,"name":"test_skipped_folding","nodeType":"Function","startLoc":775,"text":"def test_skipped_folding(testdir):\n testdir.makepyfile(\n test_one=\"\"\"\n import pytest\n pytestmark = pytest.mark.skip(\"Folding\")\n def setup_function(func):\n pass\n def test_func():\n pass\n class TestClass(object):\n def test_method(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-rs\")\n result.stdout.fnmatch_lines([\"*SKIP*2*test_one.py: Folding\"])\n assert result.ret == 0"},{"col":0,"comment":"null","endLoc":813,"header":"def test_reportchars(testdir)","id":6261,"name":"test_reportchars","nodeType":"Function","startLoc":794,"text":"def test_reportchars(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1():\n assert 0\n @pytest.mark.xfail\n def test_2():\n assert 0\n @pytest.mark.xfail\n def test_3():\n pass\n def test_4():\n pytest.skip(\"four\")\n \"\"\"\n )\n result = testdir.runpytest(\"-rfxXs\")\n result.stdout.fnmatch_lines(\n [\"FAIL*test_1*\", \"XFAIL*test_2*\", \"XPASS*test_3*\", \"SKIP*four*\"]\n )"},{"col":0,"comment":"null","endLoc":828,"header":"def test_reportchars_error(testdir)","id":6262,"name":"test_reportchars_error","nodeType":"Function","startLoc":816,"text":"def test_reportchars_error(testdir):\n testdir.makepyfile(\n conftest=\"\"\"\n def pytest_runtest_teardown():\n assert 0\n \"\"\",\n test_simple=\"\"\"\n def test_foo():\n pass\n \"\"\",\n )\n result = testdir.runpytest(\"-rE\")\n result.stdout.fnmatch_lines([\"ERROR*test_foo*\"])"},{"col":0,"comment":"null","endLoc":861,"header":"def test_reportchars_all(testdir)","id":6263,"name":"test_reportchars_all","nodeType":"Function","startLoc":831,"text":"def test_reportchars_all(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1():\n assert 0\n @pytest.mark.xfail\n def test_2():\n assert 0\n @pytest.mark.xfail\n def test_3():\n pass\n def test_4():\n pytest.skip(\"four\")\n @pytest.fixture\n def fail():\n assert 0\n def test_5(fail):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-ra\")\n result.stdout.fnmatch_lines(\n [\n \"SKIP*four*\",\n \"XFAIL*test_2*\",\n \"XPASS*test_3*\",\n \"ERROR*test_5*\",\n \"FAIL*test_1*\",\n ]\n )"},{"col":0,"comment":"null","endLoc":876,"header":"def test_reportchars_all_error(testdir)","id":6264,"name":"test_reportchars_all_error","nodeType":"Function","startLoc":864,"text":"def test_reportchars_all_error(testdir):\n testdir.makepyfile(\n conftest=\"\"\"\n def pytest_runtest_teardown():\n assert 0\n \"\"\",\n test_simple=\"\"\"\n def test_foo():\n pass\n \"\"\",\n )\n result = testdir.runpytest(\"-ra\")\n result.stdout.fnmatch_lines([\"ERROR*test_foo*\"])"},{"col":0,"comment":"null","endLoc":915,"header":"def test_errors_in_xfail_skip_expressions(testdir)","id":6265,"name":"test_errors_in_xfail_skip_expressions","nodeType":"Function","startLoc":879,"text":"def test_errors_in_xfail_skip_expressions(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skipif(\"asd\")\n def test_nameerror():\n pass\n @pytest.mark.xfail(\"syntax error\")\n def test_syntax():\n pass\n\n def test_func():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n markline = \" ^\"\n if sys.platform.startswith(\"java\"):\n # XXX report this to java\n markline = \"*\" + markline[8:]\n elif hasattr(sys, \"pypy_version_info\") and sys.pypy_version_info < (6,):\n markline = markline[5:]\n elif sys.version_info >= (3, 8) or hasattr(sys, \"pypy_version_info\"):\n markline = markline[4:]\n result.stdout.fnmatch_lines(\n [\n \"*ERROR*test_nameerror*\",\n \"*evaluating*skipif*expression*\",\n \"*asd*\",\n \"*ERROR*test_syntax*\",\n \"*evaluating*xfail*expression*\",\n \" syntax error\",\n markline,\n \"SyntaxError: invalid syntax\",\n \"*1 pass*2 error*\",\n ]\n )"},{"col":0,"comment":"null","endLoc":108,"header":"def test_setUpModule(testdir)","id":6266,"name":"test_setUpModule","nodeType":"Function","startLoc":89,"text":"def test_setUpModule(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n values = []\n\n def setUpModule():\n values.append(1)\n\n def tearDownModule():\n del values[0]\n\n def test_hello():\n assert values == [1]\n\n def test_world():\n assert values == [1]\n \"\"\"\n )\n result = testdir.runpytest(testpath)\n result.stdout.fnmatch_lines([\"*2 passed*\"])"},{"col":0,"comment":"null","endLoc":129,"header":"def test_setUpModule_failing_no_teardown(testdir)","id":6267,"name":"test_setUpModule_failing_no_teardown","nodeType":"Function","startLoc":111,"text":"def test_setUpModule_failing_no_teardown(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n values = []\n\n def setUpModule():\n 0/0\n\n def tearDownModule():\n values.append(1)\n\n def test_hello():\n pass\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n reprec.assertoutcome(passed=0, failed=1)\n call = reprec.getcalls(\"pytest_runtest_setup\")[0]\n assert not call.item.module.values"},{"col":0,"comment":"null","endLoc":144,"header":"def test_new_instances(testdir)","id":6268,"name":"test_new_instances","nodeType":"Function","startLoc":132,"text":"def test_new_instances(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n class MyTestCase(unittest.TestCase):\n def test_func1(self):\n self.x = 2\n def test_func2(self):\n assert not hasattr(self, 'x')\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n reprec.assertoutcome(passed=2)"},{"attributeType":"null","col":8,"comment":"null","endLoc":378,"id":6269,"name":"ret","nodeType":"Attribute","startLoc":378,"text":"self.ret"},{"col":0,"comment":"item.obj should be a bound method on unittest.TestCase function items (#5390).","endLoc":167,"header":"def test_function_item_obj_is_instance(testdir)","id":6270,"name":"test_function_item_obj_is_instance","nodeType":"Function","startLoc":147,"text":"def test_function_item_obj_is_instance(testdir):\n \"\"\"item.obj should be a bound method on unittest.TestCase function items (#5390).\"\"\"\n testdir.makeconftest(\n \"\"\"\n def pytest_runtest_makereport(item, call):\n if call.when == 'call':\n class_ = item.parent.obj\n assert isinstance(item.obj.__self__, class_)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import unittest\n\n class Test(unittest.TestCase):\n def test_foo(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest_inprocess()\n result.stdout.fnmatch_lines([\"* 1 passed in*\"])"},{"col":0,"comment":"null","endLoc":189,"header":"def test_teardown(testdir)","id":6271,"name":"test_teardown","nodeType":"Function","startLoc":170,"text":"def test_teardown(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n class MyTestCase(unittest.TestCase):\n values = []\n def test_one(self):\n pass\n def tearDown(self):\n self.values.append(None)\n class Second(unittest.TestCase):\n def test_check(self):\n self.assertEqual(MyTestCase.values, [None])\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n passed, skipped, failed = reprec.countoutcomes()\n assert failed == 0, failed\n assert passed == 2\n assert passed + skipped + failed == 2"},{"attributeType":"null","col":8,"comment":"null","endLoc":379,"id":6272,"name":"outlines","nodeType":"Attribute","startLoc":379,"text":"self.outlines"},{"attributeType":"null","col":8,"comment":"null","endLoc":383,"id":6273,"name":"duration","nodeType":"Attribute","startLoc":383,"text":"self.duration"},{"col":0,"comment":"\n Are TestCase objects cleaned up? Often unittest TestCase objects set\n attributes that are large and expensive during setUp.\n\n The TestCase will not be cleaned up if the test fails, because it\n would then exist in the stackframe.\n ","endLoc":214,"header":"def test_teardown_issue1649(testdir)","id":6274,"name":"test_teardown_issue1649","nodeType":"Function","startLoc":192,"text":"def test_teardown_issue1649(testdir):\n \"\"\"\n Are TestCase objects cleaned up? Often unittest TestCase objects set\n attributes that are large and expensive during setUp.\n\n The TestCase will not be cleaned up if the test fails, because it\n would then exist in the stackframe.\n \"\"\"\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n class TestCaseObjectsShouldBeCleanedUp(unittest.TestCase):\n def setUp(self):\n self.an_expensive_object = 1\n def test_demo(self):\n pass\n\n \"\"\"\n )\n testdir.inline_run(\"-s\", testpath)\n gc.collect()\n for obj in gc.get_objects():\n assert type(obj).__name__ != \"TestCaseObjectsShouldBeCleanedUp\""},{"attributeType":"null","col":8,"comment":"null","endLoc":380,"id":6276,"name":"errlines","nodeType":"Attribute","startLoc":380,"text":"self.errlines"},{"col":0,"comment":"null","endLoc":865,"header":"def test_log_file_unicode(testdir)","id":6277,"name":"test_log_file_unicode","nodeType":"Function","startLoc":831,"text":"def test_log_file_unicode(testdir):\n log_file = testdir.tmpdir.join(\"pytest.log\").strpath\n\n testdir.makeini(\n \"\"\"\n [pytest]\n log_file={}\n log_file_level = INFO\n \"\"\".format(\n log_file\n )\n )\n testdir.makepyfile(\n \"\"\"\n # -*- coding: utf-8 -*-\n from __future__ import unicode_literals\n import logging\n\n def test_log_file():\n logging.getLogger('catchlog').info(\"Normal message\")\n logging.getLogger('catchlog').info(\"├\")\n logging.getLogger('catchlog').info(\"Another normal message\")\n \"\"\"\n )\n\n result = testdir.runpytest()\n\n # make sure that that we get a '0' exit code for the testsuite\n assert result.ret == 0\n assert os.path.isfile(log_file)\n with open(log_file, encoding=\"utf-8\") as rfh:\n contents = rfh.read()\n assert \"Normal message\" in contents\n assert u\"├\" in contents\n assert \"Another normal message\" in contents"},{"attributeType":"LineMatcher","col":8,"comment":"null","endLoc":381,"id":6278,"name":"stdout","nodeType":"Attribute","startLoc":381,"text":"self.stdout"},{"attributeType":"LineMatcher","col":8,"comment":"null","endLoc":382,"id":6279,"name":"stderr","nodeType":"Attribute","startLoc":382,"text":"self.stderr"},{"className":"Testdir","col":0,"comment":"Temporary test directory with tools to test/run pytest itself.\n\n This is based on the ``tmpdir`` fixture but provides a number of methods\n which aid with testing pytest itself. Unless :py:meth:`chdir` is used all\n methods will use :py:attr:`tmpdir` as their current working directory.\n\n Attributes:\n\n :tmpdir: The :py:class:`py.path.local` instance of the temporary directory.\n\n :plugins: A list of plugins to use with :py:meth:`parseconfig` and\n :py:meth:`runpytest`. Initially this is an empty list but plugins can\n be added to the list. The type of items to add to the list depends on\n the method using them so refer to them for details.\n\n ","endLoc":1246,"id":6280,"nodeType":"Class","startLoc":463,"text":"class Testdir(object):\n \"\"\"Temporary test directory with tools to test/run pytest itself.\n\n This is based on the ``tmpdir`` fixture but provides a number of methods\n which aid with testing pytest itself. Unless :py:meth:`chdir` is used all\n methods will use :py:attr:`tmpdir` as their current working directory.\n\n Attributes:\n\n :tmpdir: The :py:class:`py.path.local` instance of the temporary directory.\n\n :plugins: A list of plugins to use with :py:meth:`parseconfig` and\n :py:meth:`runpytest`. Initially this is an empty list but plugins can\n be added to the list. The type of items to add to the list depends on\n the method using them so refer to them for details.\n\n \"\"\"\n\n CLOSE_STDIN = object\n\n class TimeoutExpired(Exception):\n pass\n\n def __init__(self, request, tmpdir_factory):\n self.request = request\n self._mod_collections = WeakKeyDictionary()\n name = request.function.__name__\n self.tmpdir = tmpdir_factory.mktemp(name, numbered=True)\n self.test_tmproot = tmpdir_factory.mktemp(\"tmp-\" + name, numbered=True)\n self.plugins = []\n self._cwd_snapshot = CwdSnapshot()\n self._sys_path_snapshot = SysPathsSnapshot()\n self._sys_modules_snapshot = self.__take_sys_modules_snapshot()\n self.chdir()\n self.request.addfinalizer(self.finalize)\n method = self.request.config.getoption(\"--runpytest\")\n if method == \"inprocess\":\n self._runpytest_method = self.runpytest_inprocess\n elif method == \"subprocess\":\n self._runpytest_method = self.runpytest_subprocess\n\n mp = self.monkeypatch = MonkeyPatch()\n mp.setenv(\"PYTEST_DEBUG_TEMPROOT\", str(self.test_tmproot))\n # Ensure no unexpected caching via tox.\n mp.delenv(\"TOX_ENV_DIR\", raising=False)\n # Discard outer pytest options.\n mp.delenv(\"PYTEST_ADDOPTS\", raising=False)\n\n # Environment (updates) for inner runs.\n tmphome = str(self.tmpdir)\n self._env_run_update = {\"HOME\": tmphome, \"USERPROFILE\": tmphome}\n\n def __repr__(self):\n return \"\" % (self.tmpdir,)\n\n def __str__(self):\n return str(self.tmpdir)\n\n def finalize(self):\n \"\"\"Clean up global state artifacts.\n\n Some methods modify the global interpreter state and this tries to\n clean this up. It does not remove the temporary directory however so\n it can be looked at after the test run has finished.\n\n \"\"\"\n self._sys_modules_snapshot.restore()\n self._sys_path_snapshot.restore()\n self._cwd_snapshot.restore()\n self.monkeypatch.undo()\n\n def __take_sys_modules_snapshot(self):\n # some zope modules used by twisted-related tests keep internal state\n # and can't be deleted; we had some trouble in the past with\n # `zope.interface` for example\n def preserve_module(name):\n return name.startswith(\"zope\")\n\n return SysModulesSnapshot(preserve=preserve_module)\n\n def make_hook_recorder(self, pluginmanager):\n \"\"\"Create a new :py:class:`HookRecorder` for a PluginManager.\"\"\"\n pluginmanager.reprec = reprec = HookRecorder(pluginmanager)\n self.request.addfinalizer(reprec.finish_recording)\n return reprec\n\n def chdir(self):\n \"\"\"Cd into the temporary directory.\n\n This is done automatically upon instantiation.\n\n \"\"\"\n self.tmpdir.chdir()\n\n def _makefile(self, ext, args, kwargs, encoding=\"utf-8\"):\n items = list(kwargs.items())\n\n def to_text(s):\n return s.decode(encoding) if isinstance(s, bytes) else six.text_type(s)\n\n if args:\n source = u\"\\n\".join(to_text(x) for x in args)\n basename = self.request.function.__name__\n items.insert(0, (basename, source))\n\n ret = None\n for basename, value in items:\n p = self.tmpdir.join(basename).new(ext=ext)\n p.dirpath().ensure_dir()\n source = Source(value)\n source = u\"\\n\".join(to_text(line) for line in source.lines)\n p.write(source.strip().encode(encoding), \"wb\")\n if ret is None:\n ret = p\n return ret\n\n def makefile(self, ext, *args, **kwargs):\n r\"\"\"Create new file(s) in the testdir.\n\n :param str ext: The extension the file(s) should use, including the dot, e.g. `.py`.\n :param list[str] args: All args will be treated as strings and joined using newlines.\n The result will be written as contents to the file. The name of the\n file will be based on the test function requesting this fixture.\n :param kwargs: Each keyword is the name of a file, while the value of it will\n be written as contents of the file.\n\n Examples:\n\n .. code-block:: python\n\n testdir.makefile(\".txt\", \"line1\", \"line2\")\n\n testdir.makefile(\".ini\", pytest=\"[pytest]\\naddopts=-rs\\n\")\n\n \"\"\"\n return self._makefile(ext, args, kwargs)\n\n def makeconftest(self, source):\n \"\"\"Write a contest.py file with 'source' as contents.\"\"\"\n return self.makepyfile(conftest=source)\n\n def makeini(self, source):\n \"\"\"Write a tox.ini file with 'source' as contents.\"\"\"\n return self.makefile(\".ini\", tox=source)\n\n def getinicfg(self, source):\n \"\"\"Return the pytest section from the tox.ini config file.\"\"\"\n p = self.makeini(source)\n return py.iniconfig.IniConfig(p)[\"pytest\"]\n\n def makepyfile(self, *args, **kwargs):\n \"\"\"Shortcut for .makefile() with a .py extension.\"\"\"\n return self._makefile(\".py\", args, kwargs)\n\n def maketxtfile(self, *args, **kwargs):\n \"\"\"Shortcut for .makefile() with a .txt extension.\"\"\"\n return self._makefile(\".txt\", args, kwargs)\n\n def syspathinsert(self, path=None):\n \"\"\"Prepend a directory to sys.path, defaults to :py:attr:`tmpdir`.\n\n This is undone automatically when this object dies at the end of each\n test.\n \"\"\"\n if path is None:\n path = self.tmpdir\n\n self.monkeypatch.syspath_prepend(str(path))\n\n def mkdir(self, name):\n \"\"\"Create a new (sub)directory.\"\"\"\n return self.tmpdir.mkdir(name)\n\n def mkpydir(self, name):\n \"\"\"Create a new python package.\n\n This creates a (sub)directory with an empty ``__init__.py`` file so it\n gets recognised as a python package.\n\n \"\"\"\n p = self.mkdir(name)\n p.ensure(\"__init__.py\")\n return p\n\n def copy_example(self, name=None):\n import warnings\n from _pytest.warning_types import PYTESTER_COPY_EXAMPLE\n\n warnings.warn(PYTESTER_COPY_EXAMPLE, stacklevel=2)\n example_dir = self.request.config.getini(\"pytester_example_dir\")\n if example_dir is None:\n raise ValueError(\"pytester_example_dir is unset, can't copy examples\")\n example_dir = self.request.config.rootdir.join(example_dir)\n\n for extra_element in self.request.node.iter_markers(\"pytester_example_path\"):\n assert extra_element.args\n example_dir = example_dir.join(*extra_element.args)\n\n if name is None:\n func_name = self.request.function.__name__\n maybe_dir = example_dir / func_name\n maybe_file = example_dir / (func_name + \".py\")\n\n if maybe_dir.isdir():\n example_path = maybe_dir\n elif maybe_file.isfile():\n example_path = maybe_file\n else:\n raise LookupError(\n \"{} cant be found as module or package in {}\".format(\n func_name, example_dir.bestrelpath(self.request.config.rootdir)\n )\n )\n else:\n example_path = example_dir.join(name)\n\n if example_path.isdir() and not example_path.join(\"__init__.py\").isfile():\n example_path.copy(self.tmpdir)\n return self.tmpdir\n elif example_path.isfile():\n result = self.tmpdir.join(example_path.basename)\n example_path.copy(result)\n return result\n else:\n raise LookupError(\n 'example \"{}\" is not found as a file or directory'.format(example_path)\n )\n\n Session = Session\n\n def getnode(self, config, arg):\n \"\"\"Return the collection node of a file.\n\n :param config: :py:class:`_pytest.config.Config` instance, see\n :py:meth:`parseconfig` and :py:meth:`parseconfigure` to create the\n configuration\n\n :param arg: a :py:class:`py.path.local` instance of the file\n\n \"\"\"\n session = Session(config)\n assert \"::\" not in str(arg)\n p = py.path.local(arg)\n config.hook.pytest_sessionstart(session=session)\n res = session.perform_collect([str(p)], genitems=False)[0]\n config.hook.pytest_sessionfinish(session=session, exitstatus=EXIT_OK)\n return res\n\n def getpathnode(self, path):\n \"\"\"Return the collection node of a file.\n\n This is like :py:meth:`getnode` but uses :py:meth:`parseconfigure` to\n create the (configured) pytest Config instance.\n\n :param path: a :py:class:`py.path.local` instance of the file\n\n \"\"\"\n config = self.parseconfigure(path)\n session = Session(config)\n x = session.fspath.bestrelpath(path)\n config.hook.pytest_sessionstart(session=session)\n res = session.perform_collect([x], genitems=False)[0]\n config.hook.pytest_sessionfinish(session=session, exitstatus=EXIT_OK)\n return res\n\n def genitems(self, colitems):\n \"\"\"Generate all test items from a collection node.\n\n This recurses into the collection node and returns a list of all the\n test items contained within.\n\n \"\"\"\n session = colitems[0].session\n result = []\n for colitem in colitems:\n result.extend(session.genitems(colitem))\n return result\n\n def runitem(self, source):\n \"\"\"Run the \"test_func\" Item.\n\n The calling test instance (class containing the test method) must\n provide a ``.getrunner()`` method which should return a runner which\n can run the test protocol for a single item, e.g.\n :py:func:`_pytest.runner.runtestprotocol`.\n\n \"\"\"\n # used from runner functional tests\n item = self.getitem(source)\n # the test class where we are called from wants to provide the runner\n testclassinstance = self.request.instance\n runner = testclassinstance.getrunner()\n return runner(item)\n\n def inline_runsource(self, source, *cmdlineargs):\n \"\"\"Run a test module in process using ``pytest.main()``.\n\n This run writes \"source\" into a temporary file and runs\n ``pytest.main()`` on it, returning a :py:class:`HookRecorder` instance\n for the result.\n\n :param source: the source code of the test module\n\n :param cmdlineargs: any extra command line arguments to use\n\n :return: :py:class:`HookRecorder` instance of the result\n\n \"\"\"\n p = self.makepyfile(source)\n values = list(cmdlineargs) + [p]\n return self.inline_run(*values)\n\n def inline_genitems(self, *args):\n \"\"\"Run ``pytest.main(['--collectonly'])`` in-process.\n\n Runs the :py:func:`pytest.main` function to run all of pytest inside\n the test process itself like :py:meth:`inline_run`, but returns a\n tuple of the collected items and a :py:class:`HookRecorder` instance.\n\n \"\"\"\n rec = self.inline_run(\"--collect-only\", *args)\n items = [x.item for x in rec.getcalls(\"pytest_itemcollected\")]\n return items, rec\n\n def inline_run(self, *args, **kwargs):\n \"\"\"Run ``pytest.main()`` in-process, returning a HookRecorder.\n\n Runs the :py:func:`pytest.main` function to run all of pytest inside\n the test process itself. This means it can return a\n :py:class:`HookRecorder` instance which gives more detailed results\n from that run than can be done by matching stdout/stderr from\n :py:meth:`runpytest`.\n\n :param args: command line arguments to pass to :py:func:`pytest.main`\n\n :param plugins: (keyword-only) extra plugin instances the\n ``pytest.main()`` instance should use\n\n :return: a :py:class:`HookRecorder` instance\n \"\"\"\n plugins = kwargs.pop(\"plugins\", [])\n no_reraise_ctrlc = kwargs.pop(\"no_reraise_ctrlc\", None)\n raise_on_kwargs(kwargs)\n\n finalizers = []\n try:\n # Do not load user config (during runs only).\n mp_run = MonkeyPatch()\n for k, v in self._env_run_update.items():\n mp_run.setenv(k, v)\n finalizers.append(mp_run.undo)\n\n # When running pytest inline any plugins active in the main test\n # process are already imported. So this disables the warning which\n # will trigger to say they can no longer be rewritten, which is\n # fine as they have already been rewritten.\n orig_warn = AssertionRewritingHook._warn_already_imported\n\n def revert_warn_already_imported():\n AssertionRewritingHook._warn_already_imported = orig_warn\n\n finalizers.append(revert_warn_already_imported)\n AssertionRewritingHook._warn_already_imported = lambda *a: None\n\n # Any sys.module or sys.path changes done while running pytest\n # inline should be reverted after the test run completes to avoid\n # clashing with later inline tests run within the same pytest test,\n # e.g. just because they use matching test module names.\n finalizers.append(self.__take_sys_modules_snapshot().restore)\n finalizers.append(SysPathsSnapshot().restore)\n\n # Important note:\n # - our tests should not leave any other references/registrations\n # laying around other than possibly loaded test modules\n # referenced from sys.modules, as nothing will clean those up\n # automatically\n\n rec = []\n\n class Collect(object):\n def pytest_configure(x, config):\n rec.append(self.make_hook_recorder(config.pluginmanager))\n\n plugins.append(Collect())\n ret = pytest.main(list(args), plugins=plugins)\n if len(rec) == 1:\n reprec = rec.pop()\n else:\n\n class reprec(object):\n pass\n\n reprec.ret = ret\n\n # typically we reraise keyboard interrupts from the child run\n # because it's our user requesting interruption of the testing\n if ret == EXIT_INTERRUPTED and not no_reraise_ctrlc:\n calls = reprec.getcalls(\"pytest_keyboard_interrupt\")\n if calls and calls[-1].excinfo.type == KeyboardInterrupt:\n raise KeyboardInterrupt()\n return reprec\n finally:\n for finalizer in finalizers:\n finalizer()\n\n def runpytest_inprocess(self, *args, **kwargs):\n \"\"\"Return result of running pytest in-process, providing a similar\n interface to what self.runpytest() provides.\n \"\"\"\n syspathinsert = kwargs.pop(\"syspathinsert\", False)\n\n if syspathinsert:\n self.syspathinsert()\n now = time.time()\n capture = MultiCapture(Capture=SysCapture)\n capture.start_capturing()\n try:\n try:\n reprec = self.inline_run(*args, **kwargs)\n except SystemExit as e:\n\n class reprec(object):\n ret = e.args[0]\n\n except Exception:\n traceback.print_exc()\n\n class reprec(object):\n ret = 3\n\n finally:\n out, err = capture.readouterr()\n capture.stop_capturing()\n sys.stdout.write(out)\n sys.stderr.write(err)\n\n res = RunResult(reprec.ret, out.split(\"\\n\"), err.split(\"\\n\"), time.time() - now)\n res.reprec = reprec\n return res\n\n def runpytest(self, *args, **kwargs):\n \"\"\"Run pytest inline or in a subprocess, depending on the command line\n option \"--runpytest\" and return a :py:class:`RunResult`.\n\n \"\"\"\n args = self._ensure_basetemp(args)\n return self._runpytest_method(*args, **kwargs)\n\n def _ensure_basetemp(self, args):\n args = list(args)\n for x in args:\n if safe_str(x).startswith(\"--basetemp\"):\n break\n else:\n args.append(\"--basetemp=%s\" % self.tmpdir.dirpath(\"basetemp\"))\n return args\n\n def parseconfig(self, *args):\n \"\"\"Return a new pytest Config instance from given commandline args.\n\n This invokes the pytest bootstrapping code in _pytest.config to create\n a new :py:class:`_pytest.core.PluginManager` and call the\n pytest_cmdline_parse hook to create a new\n :py:class:`_pytest.config.Config` instance.\n\n If :py:attr:`plugins` has been populated they should be plugin modules\n to be registered with the PluginManager.\n\n \"\"\"\n args = self._ensure_basetemp(args)\n\n import _pytest.config\n\n config = _pytest.config._prepareconfig(args, self.plugins)\n # we don't know what the test will do with this half-setup config\n # object and thus we make sure it gets unconfigured properly in any\n # case (otherwise capturing could still be active, for example)\n self.request.addfinalizer(config._ensure_unconfigure)\n return config\n\n def parseconfigure(self, *args):\n \"\"\"Return a new pytest configured Config instance.\n\n This returns a new :py:class:`_pytest.config.Config` instance like\n :py:meth:`parseconfig`, but also calls the pytest_configure hook.\n\n \"\"\"\n config = self.parseconfig(*args)\n config._do_configure()\n self.request.addfinalizer(config._ensure_unconfigure)\n return config\n\n def getitem(self, source, funcname=\"test_func\"):\n \"\"\"Return the test item for a test function.\n\n This writes the source to a python file and runs pytest's collection on\n the resulting module, returning the test item for the requested\n function name.\n\n :param source: the module source\n\n :param funcname: the name of the test function for which to return a\n test item\n\n \"\"\"\n items = self.getitems(source)\n for item in items:\n if item.name == funcname:\n return item\n assert 0, \"%r item not found in module:\\n%s\\nitems: %s\" % (\n funcname,\n source,\n items,\n )\n\n def getitems(self, source):\n \"\"\"Return all test items collected from the module.\n\n This writes the source to a python file and runs pytest's collection on\n the resulting module, returning all test items contained within.\n\n \"\"\"\n modcol = self.getmodulecol(source)\n return self.genitems([modcol])\n\n def getmodulecol(self, source, configargs=(), withinit=False):\n \"\"\"Return the module collection node for ``source``.\n\n This writes ``source`` to a file using :py:meth:`makepyfile` and then\n runs the pytest collection on it, returning the collection node for the\n test module.\n\n :param source: the source code of the module to collect\n\n :param configargs: any extra arguments to pass to\n :py:meth:`parseconfigure`\n\n :param withinit: whether to also write an ``__init__.py`` file to the\n same directory to ensure it is a package\n\n \"\"\"\n if isinstance(source, Path):\n path = self.tmpdir.join(str(source))\n assert not withinit, \"not supported for paths\"\n else:\n kw = {self.request.function.__name__: Source(source).strip()}\n path = self.makepyfile(**kw)\n if withinit:\n self.makepyfile(__init__=\"#\")\n self.config = config = self.parseconfigure(path, *configargs)\n return self.getnode(config, path)\n\n def collect_by_name(self, modcol, name):\n \"\"\"Return the collection node for name from the module collection.\n\n This will search a module collection node for a collection node\n matching the given name.\n\n :param modcol: a module collection node; see :py:meth:`getmodulecol`\n\n :param name: the name of the node to return\n\n \"\"\"\n if modcol not in self._mod_collections:\n self._mod_collections[modcol] = list(modcol.collect())\n for colitem in self._mod_collections[modcol]:\n if colitem.name == name:\n return colitem\n\n def popen(\n self,\n cmdargs,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n stdin=CLOSE_STDIN,\n **kw\n ):\n \"\"\"Invoke subprocess.Popen.\n\n This calls subprocess.Popen making sure the current working directory\n is in the PYTHONPATH.\n\n You probably want to use :py:meth:`run` instead.\n\n \"\"\"\n env = os.environ.copy()\n env[\"PYTHONPATH\"] = os.pathsep.join(\n filter(None, [os.getcwd(), env.get(\"PYTHONPATH\", \"\")])\n )\n env.update(self._env_run_update)\n kw[\"env\"] = env\n\n if stdin is Testdir.CLOSE_STDIN:\n kw[\"stdin\"] = subprocess.PIPE\n elif isinstance(stdin, bytes):\n kw[\"stdin\"] = subprocess.PIPE\n else:\n kw[\"stdin\"] = stdin\n\n popen = subprocess.Popen(cmdargs, stdout=stdout, stderr=stderr, **kw)\n if stdin is Testdir.CLOSE_STDIN:\n popen.stdin.close()\n elif isinstance(stdin, bytes):\n popen.stdin.write(stdin)\n\n return popen\n\n def run(self, *cmdargs, **kwargs):\n \"\"\"Run a command with arguments.\n\n Run a process using subprocess.Popen saving the stdout and stderr.\n\n :param args: the sequence of arguments to pass to `subprocess.Popen()`\n :param timeout: the period in seconds after which to timeout and raise\n :py:class:`Testdir.TimeoutExpired`\n :param stdin: optional standard input. Bytes are being send, closing\n the pipe, otherwise it is passed through to ``popen``.\n Defaults to ``CLOSE_STDIN``, which translates to using a pipe\n (``subprocess.PIPE``) that gets closed.\n\n Returns a :py:class:`RunResult`.\n\n \"\"\"\n __tracebackhide__ = True\n\n timeout = kwargs.pop(\"timeout\", None)\n stdin = kwargs.pop(\"stdin\", Testdir.CLOSE_STDIN)\n raise_on_kwargs(kwargs)\n\n cmdargs = [\n str(arg) if isinstance(arg, py.path.local) else arg for arg in cmdargs\n ]\n p1 = self.tmpdir.join(\"stdout\")\n p2 = self.tmpdir.join(\"stderr\")\n print(\"running:\", *cmdargs)\n print(\" in:\", py.path.local())\n f1 = codecs.open(str(p1), \"w\", encoding=\"utf8\")\n f2 = codecs.open(str(p2), \"w\", encoding=\"utf8\")\n try:\n now = time.time()\n popen = self.popen(\n cmdargs,\n stdin=stdin,\n stdout=f1,\n stderr=f2,\n close_fds=(sys.platform != \"win32\"),\n )\n if isinstance(stdin, bytes):\n popen.stdin.close()\n\n def handle_timeout():\n __tracebackhide__ = True\n\n timeout_message = (\n \"{seconds} second timeout expired running:\"\n \" {command}\".format(seconds=timeout, command=cmdargs)\n )\n\n popen.kill()\n popen.wait()\n raise self.TimeoutExpired(timeout_message)\n\n if timeout is None:\n ret = popen.wait()\n elif not six.PY2:\n try:\n ret = popen.wait(timeout)\n except subprocess.TimeoutExpired:\n handle_timeout()\n else:\n end = time.time() + timeout\n\n resolution = min(0.1, timeout / 10)\n\n while True:\n ret = popen.poll()\n if ret is not None:\n break\n\n if time.time() > end:\n handle_timeout()\n\n time.sleep(resolution)\n finally:\n f1.close()\n f2.close()\n f1 = codecs.open(str(p1), \"r\", encoding=\"utf8\")\n f2 = codecs.open(str(p2), \"r\", encoding=\"utf8\")\n try:\n out = f1.read().splitlines()\n err = f2.read().splitlines()\n finally:\n f1.close()\n f2.close()\n self._dump_lines(out, sys.stdout)\n self._dump_lines(err, sys.stderr)\n return RunResult(ret, out, err, time.time() - now)\n\n def _dump_lines(self, lines, fp):\n try:\n for line in lines:\n print(line, file=fp)\n except UnicodeEncodeError:\n print(\"couldn't print to %s because of encoding\" % (fp,))\n\n def _getpytestargs(self):\n return sys.executable, \"-mpytest\"\n\n def runpython(self, script):\n \"\"\"Run a python script using sys.executable as interpreter.\n\n Returns a :py:class:`RunResult`.\n\n \"\"\"\n return self.run(sys.executable, script)\n\n def runpython_c(self, command):\n \"\"\"Run python -c \"command\", return a :py:class:`RunResult`.\"\"\"\n return self.run(sys.executable, \"-c\", command)\n\n def runpytest_subprocess(self, *args, **kwargs):\n \"\"\"Run pytest as a subprocess with given arguments.\n\n Any plugins added to the :py:attr:`plugins` list will be added using the\n ``-p`` command line option. Additionally ``--basetemp`` is used to put\n any temporary files and directories in a numbered directory prefixed\n with \"runpytest-\" to not conflict with the normal numbered pytest\n location for temporary files and directories.\n\n :param args: the sequence of arguments to pass to the pytest subprocess\n :param timeout: the period in seconds after which to timeout and raise\n :py:class:`Testdir.TimeoutExpired`\n\n Returns a :py:class:`RunResult`.\n \"\"\"\n __tracebackhide__ = True\n timeout = kwargs.pop(\"timeout\", None)\n raise_on_kwargs(kwargs)\n\n p = py.path.local.make_numbered_dir(\n prefix=\"runpytest-\", keep=None, rootdir=self.tmpdir\n )\n args = (\"--basetemp=%s\" % p,) + args\n plugins = [x for x in self.plugins if isinstance(x, str)]\n if plugins:\n args = (\"-p\", plugins[0]) + args\n args = self._getpytestargs() + args\n return self.run(*args, timeout=timeout)\n\n def spawn_pytest(self, string, expect_timeout=10.0):\n \"\"\"Run pytest using pexpect.\n\n This makes sure to use the right pytest and sets up the temporary\n directory locations.\n\n The pexpect child is returned.\n\n \"\"\"\n basetemp = self.tmpdir.mkdir(\"temp-pexpect\")\n invoke = \" \".join(map(str, self._getpytestargs()))\n cmd = \"%s --basetemp=%s %s\" % (invoke, basetemp, string)\n return self.spawn(cmd, expect_timeout=expect_timeout)\n\n def spawn(self, cmd, expect_timeout=10.0):\n \"\"\"Run a command using pexpect.\n\n The pexpect child is returned.\n\n \"\"\"\n pexpect = pytest.importorskip(\"pexpect\", \"3.0\")\n if hasattr(sys, \"pypy_version_info\") and \"64\" in platform.machine():\n pytest.skip(\"pypy-64 bit not supported\")\n if sys.platform.startswith(\"freebsd\"):\n pytest.xfail(\"pexpect does not work reliably on freebsd\")\n logfile = self.tmpdir.join(\"spawn.out\").open(\"wb\")\n\n # Do not load user config.\n env = os.environ.copy()\n env.update(self._env_run_update)\n\n child = pexpect.spawn(cmd, logfile=logfile, env=env)\n self.request.addfinalizer(logfile.close)\n child.timeout = expect_timeout\n return child"},{"col":4,"comment":"null","endLoc":513,"header":"def __init__(self, request, tmpdir_factory)","id":6281,"name":"__init__","nodeType":"Function","startLoc":486,"text":"def __init__(self, request, tmpdir_factory):\n self.request = request\n self._mod_collections = WeakKeyDictionary()\n name = request.function.__name__\n self.tmpdir = tmpdir_factory.mktemp(name, numbered=True)\n self.test_tmproot = tmpdir_factory.mktemp(\"tmp-\" + name, numbered=True)\n self.plugins = []\n self._cwd_snapshot = CwdSnapshot()\n self._sys_path_snapshot = SysPathsSnapshot()\n self._sys_modules_snapshot = self.__take_sys_modules_snapshot()\n self.chdir()\n self.request.addfinalizer(self.finalize)\n method = self.request.config.getoption(\"--runpytest\")\n if method == \"inprocess\":\n self._runpytest_method = self.runpytest_inprocess\n elif method == \"subprocess\":\n self._runpytest_method = self.runpytest_subprocess\n\n mp = self.monkeypatch = MonkeyPatch()\n mp.setenv(\"PYTEST_DEBUG_TEMPROOT\", str(self.test_tmproot))\n # Ensure no unexpected caching via tox.\n mp.delenv(\"TOX_ENV_DIR\", raising=False)\n # Discard outer pytest options.\n mp.delenv(\"PYTEST_ADDOPTS\", raising=False)\n\n # Environment (updates) for inner runs.\n tmphome = str(self.tmpdir)\n self._env_run_update = {\"HOME\": tmphome, \"USERPROFILE\": tmphome}"},{"col":4,"comment":"null","endLoc":541,"header":"def __take_sys_modules_snapshot(self)","id":6282,"name":"__take_sys_modules_snapshot","nodeType":"Function","startLoc":534,"text":"def __take_sys_modules_snapshot(self):\n # some zope modules used by twisted-related tests keep internal state\n # and can't be deleted; we had some trouble in the past with\n # `zope.interface` for example\n def preserve_module(name):\n return name.startswith(\"zope\")\n\n return SysModulesSnapshot(preserve=preserve_module)"},{"col":4,"comment":"Cd into the temporary directory.\n\n This is done automatically upon instantiation.\n\n ","endLoc":555,"header":"def chdir(self)","id":6283,"name":"chdir","nodeType":"Function","startLoc":549,"text":"def chdir(self):\n \"\"\"Cd into the temporary directory.\n\n This is done automatically upon instantiation.\n\n \"\"\"\n self.tmpdir.chdir()"},{"col":4,"comment":"null","endLoc":516,"header":"def __repr__(self)","id":6284,"name":"__repr__","nodeType":"Function","startLoc":515,"text":"def __repr__(self):\n return \"\" % (self.tmpdir,)"},{"col":4,"comment":"null","endLoc":519,"header":"def __str__(self)","id":6285,"name":"__str__","nodeType":"Function","startLoc":518,"text":"def __str__(self):\n return str(self.tmpdir)"},{"fileName":"reports.py","filePath":"src/_pytest","id":6286,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom pprint import pprint\n\nimport py\nimport six\n\nfrom _pytest._code.code import ExceptionInfo\nfrom _pytest._code.code import ReprEntry\nfrom _pytest._code.code import ReprEntryNative\nfrom _pytest._code.code import ReprExceptionInfo\nfrom _pytest._code.code import ReprFileLocation\nfrom _pytest._code.code import ReprFuncArgs\nfrom _pytest._code.code import ReprLocals\nfrom _pytest._code.code import ReprTraceback\nfrom _pytest._code.code import TerminalRepr\nfrom _pytest.outcomes import skip\nfrom _pytest.pathlib import Path\n\n\ndef getslaveinfoline(node):\n try:\n return node._slaveinfocache\n except AttributeError:\n d = node.slaveinfo\n ver = \"%s.%s.%s\" % d[\"version_info\"][:3]\n node._slaveinfocache = s = \"[%s] %s -- Python %s %s\" % (\n d[\"id\"],\n d[\"sysplatform\"],\n ver,\n d[\"executable\"],\n )\n return s\n\n\nclass BaseReport(object):\n when = None\n location = None\n\n def __init__(self, **kw):\n self.__dict__.update(kw)\n\n def toterminal(self, out):\n if hasattr(self, \"node\"):\n out.line(getslaveinfoline(self.node))\n\n longrepr = self.longrepr\n if longrepr is None:\n return\n\n if hasattr(longrepr, \"toterminal\"):\n longrepr.toterminal(out)\n else:\n try:\n out.line(longrepr)\n except UnicodeEncodeError:\n out.line(\"\")\n\n def get_sections(self, prefix):\n for name, content in self.sections:\n if name.startswith(prefix):\n yield prefix, content\n\n @property\n def longreprtext(self):\n \"\"\"\n Read-only property that returns the full string representation\n of ``longrepr``.\n\n .. versionadded:: 3.0\n \"\"\"\n tw = py.io.TerminalWriter(stringio=True)\n tw.hasmarkup = False\n self.toterminal(tw)\n exc = tw.stringio.getvalue()\n return exc.strip()\n\n @property\n def caplog(self):\n \"\"\"Return captured log lines, if log capturing is enabled\n\n .. versionadded:: 3.5\n \"\"\"\n return \"\\n\".join(\n content for (prefix, content) in self.get_sections(\"Captured log\")\n )\n\n @property\n def capstdout(self):\n \"\"\"Return captured text from stdout, if capturing is enabled\n\n .. versionadded:: 3.0\n \"\"\"\n return \"\".join(\n content for (prefix, content) in self.get_sections(\"Captured stdout\")\n )\n\n @property\n def capstderr(self):\n \"\"\"Return captured text from stderr, if capturing is enabled\n\n .. versionadded:: 3.0\n \"\"\"\n return \"\".join(\n content for (prefix, content) in self.get_sections(\"Captured stderr\")\n )\n\n passed = property(lambda x: x.outcome == \"passed\")\n failed = property(lambda x: x.outcome == \"failed\")\n skipped = property(lambda x: x.outcome == \"skipped\")\n\n @property\n def fspath(self):\n return self.nodeid.split(\"::\")[0]\n\n @property\n def count_towards_summary(self):\n \"\"\"\n **Experimental**\n\n Returns True if this report should be counted towards the totals shown at the end of the\n test session: \"1 passed, 1 failure, etc\".\n\n .. note::\n\n This function is considered **experimental**, so beware that it is subject to changes\n even in patch releases.\n \"\"\"\n return True\n\n @property\n def head_line(self):\n \"\"\"\n **Experimental**\n\n Returns the head line shown with longrepr output for this report, more commonly during\n traceback representation during failures::\n\n ________ Test.foo ________\n\n\n In the example above, the head_line is \"Test.foo\".\n\n .. note::\n\n This function is considered **experimental**, so beware that it is subject to changes\n even in patch releases.\n \"\"\"\n if self.location is not None:\n fspath, lineno, domain = self.location\n return domain\n\n def _get_verbose_word(self, config):\n _category, _short, verbose = config.hook.pytest_report_teststatus(\n report=self, config=config\n )\n return verbose\n\n def _to_json(self):\n \"\"\"\n This was originally the serialize_report() function from xdist (ca03269).\n\n Returns the contents of this report as a dict of builtin entries, suitable for\n serialization.\n\n Experimental method.\n \"\"\"\n\n def disassembled_report(rep):\n reprtraceback = rep.longrepr.reprtraceback.__dict__.copy()\n reprcrash = rep.longrepr.reprcrash.__dict__.copy()\n\n new_entries = []\n for entry in reprtraceback[\"reprentries\"]:\n entry_data = {\n \"type\": type(entry).__name__,\n \"data\": entry.__dict__.copy(),\n }\n for key, value in entry_data[\"data\"].items():\n if hasattr(value, \"__dict__\"):\n entry_data[\"data\"][key] = value.__dict__.copy()\n new_entries.append(entry_data)\n\n reprtraceback[\"reprentries\"] = new_entries\n\n return {\n \"reprcrash\": reprcrash,\n \"reprtraceback\": reprtraceback,\n \"sections\": rep.longrepr.sections,\n }\n\n d = self.__dict__.copy()\n if hasattr(self.longrepr, \"toterminal\"):\n if hasattr(self.longrepr, \"reprtraceback\") and hasattr(\n self.longrepr, \"reprcrash\"\n ):\n d[\"longrepr\"] = disassembled_report(self)\n else:\n d[\"longrepr\"] = six.text_type(self.longrepr)\n else:\n d[\"longrepr\"] = self.longrepr\n for name in d:\n if isinstance(d[name], (py.path.local, Path)):\n d[name] = str(d[name])\n elif name == \"result\":\n d[name] = None # for now\n return d\n\n @classmethod\n def _from_json(cls, reportdict):\n \"\"\"\n This was originally the serialize_report() function from xdist (ca03269).\n\n Factory method that returns either a TestReport or CollectReport, depending on the calling\n class. It's the callers responsibility to know which class to pass here.\n\n Experimental method.\n \"\"\"\n if reportdict[\"longrepr\"]:\n if (\n \"reprcrash\" in reportdict[\"longrepr\"]\n and \"reprtraceback\" in reportdict[\"longrepr\"]\n ):\n\n reprtraceback = reportdict[\"longrepr\"][\"reprtraceback\"]\n reprcrash = reportdict[\"longrepr\"][\"reprcrash\"]\n\n unserialized_entries = []\n reprentry = None\n for entry_data in reprtraceback[\"reprentries\"]:\n data = entry_data[\"data\"]\n entry_type = entry_data[\"type\"]\n if entry_type == \"ReprEntry\":\n reprfuncargs = None\n reprfileloc = None\n reprlocals = None\n if data[\"reprfuncargs\"]:\n reprfuncargs = ReprFuncArgs(**data[\"reprfuncargs\"])\n if data[\"reprfileloc\"]:\n reprfileloc = ReprFileLocation(**data[\"reprfileloc\"])\n if data[\"reprlocals\"]:\n reprlocals = ReprLocals(data[\"reprlocals\"][\"lines\"])\n\n reprentry = ReprEntry(\n lines=data[\"lines\"],\n reprfuncargs=reprfuncargs,\n reprlocals=reprlocals,\n filelocrepr=reprfileloc,\n style=data[\"style\"],\n )\n elif entry_type == \"ReprEntryNative\":\n reprentry = ReprEntryNative(data[\"lines\"])\n else:\n _report_unserialization_failure(entry_type, cls, reportdict)\n unserialized_entries.append(reprentry)\n reprtraceback[\"reprentries\"] = unserialized_entries\n\n exception_info = ReprExceptionInfo(\n reprtraceback=ReprTraceback(**reprtraceback),\n reprcrash=ReprFileLocation(**reprcrash),\n )\n\n for section in reportdict[\"longrepr\"][\"sections\"]:\n exception_info.addsection(*section)\n reportdict[\"longrepr\"] = exception_info\n\n return cls(**reportdict)\n\n\ndef _report_unserialization_failure(type_name, report_class, reportdict):\n url = \"https://github.com/pytest-dev/pytest/issues\"\n stream = py.io.TextIO()\n pprint(\"-\" * 100, stream=stream)\n pprint(\"INTERNALERROR: Unknown entry type returned: %s\" % type_name, stream=stream)\n pprint(\"report_name: %s\" % report_class, stream=stream)\n pprint(reportdict, stream=stream)\n pprint(\"Please report this bug at %s\" % url, stream=stream)\n pprint(\"-\" * 100, stream=stream)\n raise RuntimeError(stream.getvalue())\n\n\nclass TestReport(BaseReport):\n \"\"\" Basic test report object (also used for setup and teardown calls if\n they fail).\n \"\"\"\n\n __test__ = False\n\n def __init__(\n self,\n nodeid,\n location,\n keywords,\n outcome,\n longrepr,\n when,\n sections=(),\n duration=0,\n user_properties=None,\n **extra\n ):\n #: normalized collection node id\n self.nodeid = nodeid\n\n #: a (filesystempath, lineno, domaininfo) tuple indicating the\n #: actual location of a test item - it might be different from the\n #: collected one e.g. if a method is inherited from a different module.\n self.location = location\n\n #: a name -> value dictionary containing all keywords and\n #: markers associated with a test invocation.\n self.keywords = keywords\n\n #: test outcome, always one of \"passed\", \"failed\", \"skipped\".\n self.outcome = outcome\n\n #: None or a failure representation.\n self.longrepr = longrepr\n\n #: one of 'setup', 'call', 'teardown' to indicate runtest phase.\n self.when = when\n\n #: user properties is a list of tuples (name, value) that holds user\n #: defined properties of the test\n self.user_properties = list(user_properties or [])\n\n #: list of pairs ``(str, str)`` of extra information which needs to\n #: marshallable. Used by pytest to add captured text\n #: from ``stdout`` and ``stderr``, but may be used by other plugins\n #: to add arbitrary information to reports.\n self.sections = list(sections)\n\n #: time it took to run just the test\n self.duration = duration\n\n self.__dict__.update(extra)\n\n def __repr__(self):\n return \"<%s %r when=%r outcome=%r>\" % (\n self.__class__.__name__,\n self.nodeid,\n self.when,\n self.outcome,\n )\n\n @classmethod\n def from_item_and_call(cls, item, call):\n \"\"\"\n Factory method to create and fill a TestReport with standard item and call info.\n \"\"\"\n when = call.when\n duration = call.stop - call.start\n keywords = {x: 1 for x in item.keywords}\n excinfo = call.excinfo\n sections = []\n if not call.excinfo:\n outcome = \"passed\"\n longrepr = None\n else:\n if not isinstance(excinfo, ExceptionInfo):\n outcome = \"failed\"\n longrepr = excinfo\n elif excinfo.errisinstance(skip.Exception):\n outcome = \"skipped\"\n r = excinfo._getreprcrash()\n longrepr = (str(r.path), r.lineno, r.message)\n else:\n outcome = \"failed\"\n if call.when == \"call\":\n longrepr = item.repr_failure(excinfo)\n else: # exception in setup or teardown\n longrepr = item._repr_failure_py(\n excinfo, style=item.config.getoption(\"tbstyle\", \"auto\")\n )\n for rwhen, key, content in item._report_sections:\n sections.append((\"Captured %s %s\" % (key, rwhen), content))\n return cls(\n item.nodeid,\n item.location,\n keywords,\n outcome,\n longrepr,\n when,\n sections,\n duration,\n user_properties=item.user_properties,\n )\n\n\nclass CollectReport(BaseReport):\n when = \"collect\"\n\n def __init__(self, nodeid, outcome, longrepr, result, sections=(), **extra):\n self.nodeid = nodeid\n self.outcome = outcome\n self.longrepr = longrepr\n self.result = result or []\n self.sections = list(sections)\n self.__dict__.update(extra)\n\n @property\n def location(self):\n return (self.fspath, None, self.fspath)\n\n def __repr__(self):\n return \"\" % (\n self.nodeid,\n len(self.result),\n self.outcome,\n )\n\n\nclass CollectErrorRepr(TerminalRepr):\n def __init__(self, msg):\n self.longrepr = msg\n\n def toterminal(self, out):\n out.line(self.longrepr, red=True)\n\n\ndef pytest_report_to_serializable(report):\n if isinstance(report, (TestReport, CollectReport)):\n data = report._to_json()\n data[\"_report_type\"] = report.__class__.__name__\n return data\n\n\ndef pytest_report_from_serializable(data):\n if \"_report_type\" in data:\n if data[\"_report_type\"] == \"TestReport\":\n return TestReport._from_json(data)\n elif data[\"_report_type\"] == \"CollectReport\":\n return CollectReport._from_json(data)\n assert False, \"Unknown report_type unserialize data: {}\".format(\n data[\"_report_type\"]\n )\n"},{"col":0,"comment":"null","endLoc":424,"header":"def pytest_report_to_serializable(report)","id":6287,"name":"pytest_report_to_serializable","nodeType":"Function","startLoc":420,"text":"def pytest_report_to_serializable(report):\n if isinstance(report, (TestReport, CollectReport)):\n data = report._to_json()\n data[\"_report_type\"] = report.__class__.__name__\n return data"},{"col":0,"comment":"null","endLoc":235,"header":"def test_unittest_skip_issue148(testdir)","id":6288,"name":"test_unittest_skip_issue148","nodeType":"Function","startLoc":217,"text":"def test_unittest_skip_issue148(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n\n @unittest.skip(\"hello\")\n class MyTestCase(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n xxx\n def test_one(self):\n pass\n @classmethod\n def tearDownClass(self):\n xxx\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n reprec.assertoutcome(skipped=1)"},{"col":4,"comment":"Clean up global state artifacts.\n\n Some methods modify the global interpreter state and this tries to\n clean this up. It does not remove the temporary directory however so\n it can be looked at after the test run has finished.\n\n ","endLoc":532,"header":"def finalize(self)","id":6289,"name":"finalize","nodeType":"Function","startLoc":521,"text":"def finalize(self):\n \"\"\"Clean up global state artifacts.\n\n Some methods modify the global interpreter state and this tries to\n clean this up. It does not remove the temporary directory however so\n it can be looked at after the test run has finished.\n\n \"\"\"\n self._sys_modules_snapshot.restore()\n self._sys_path_snapshot.restore()\n self._cwd_snapshot.restore()\n self.monkeypatch.undo()"},{"col":0,"comment":"null","endLoc":259,"header":"def test_method_and_teardown_failing_reporting(testdir)","id":6290,"name":"test_method_and_teardown_failing_reporting","nodeType":"Function","startLoc":238,"text":"def test_method_and_teardown_failing_reporting(testdir):\n testdir.makepyfile(\n \"\"\"\n import unittest, pytest\n class TC(unittest.TestCase):\n def tearDown(self):\n assert 0, \"down1\"\n def test_method(self):\n assert False, \"down2\"\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\n \"*tearDown*\",\n \"*assert 0*\",\n \"*test_method*\",\n \"*assert False*\",\n \"*1 failed*1 error*\",\n ]\n )"},{"col":0,"comment":"null","endLoc":278,"header":"def test_setup_failure_is_shown(testdir)","id":6291,"name":"test_setup_failure_is_shown","nodeType":"Function","startLoc":262,"text":"def test_setup_failure_is_shown(testdir):\n testdir.makepyfile(\n \"\"\"\n import unittest\n import pytest\n class TC(unittest.TestCase):\n def setUp(self):\n assert 0, \"down1\"\n def test_method(self):\n print(\"never42\")\n xyz\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n assert result.ret == 1\n result.stdout.fnmatch_lines([\"*setUp*\", \"*assert 0*down1*\", \"*1 failed*\"])\n assert \"never42\" not in result.stdout.str()"},{"col":0,"comment":"null","endLoc":303,"header":"def test_setup_setUpClass(testdir)","id":6292,"name":"test_setup_setUpClass","nodeType":"Function","startLoc":281,"text":"def test_setup_setUpClass(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n import pytest\n class MyTestCase(unittest.TestCase):\n x = 0\n @classmethod\n def setUpClass(cls):\n cls.x += 1\n def test_func1(self):\n assert self.x == 1\n def test_func2(self):\n assert self.x == 1\n @classmethod\n def tearDownClass(cls):\n cls.x -= 1\n def test_teareddown():\n assert MyTestCase.x == 0\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n reprec.assertoutcome(passed=3)"},{"col":0,"comment":"null","endLoc":326,"header":"def test_setup_class(testdir)","id":6293,"name":"test_setup_class","nodeType":"Function","startLoc":306,"text":"def test_setup_class(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n import pytest\n class MyTestCase(unittest.TestCase):\n x = 0\n def setup_class(cls):\n cls.x += 1\n def test_func1(self):\n assert self.x == 1\n def test_func2(self):\n assert self.x == 1\n def teardown_class(cls):\n cls.x -= 1\n def test_teareddown():\n assert MyTestCase.x == 0\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n reprec.assertoutcome(passed=3)"},{"col":0,"comment":"null","endLoc":350,"header":"@pytest.mark.parametrize(\"type\", [\"Error\", \"Failure\"])\ndef test_testcase_adderrorandfailure_defers(testdir, type)","id":6294,"name":"test_testcase_adderrorandfailure_defers","nodeType":"Function","startLoc":329,"text":"@pytest.mark.parametrize(\"type\", [\"Error\", \"Failure\"])\ndef test_testcase_adderrorandfailure_defers(testdir, type):\n testdir.makepyfile(\n \"\"\"\n from unittest import TestCase\n import pytest\n class MyTestCase(TestCase):\n def run(self, result):\n excinfo = pytest.raises(ZeroDivisionError, lambda: 0/0)\n try:\n result.add%s(self, excinfo._excinfo)\n except KeyboardInterrupt:\n raise\n except:\n pytest.fail(\"add%s should not raise\")\n def test_hello(self):\n pass\n \"\"\"\n % (type, type)\n )\n result = testdir.runpytest()\n assert \"should not raise\" not in result.stdout.str()"},{"col":0,"comment":"null","endLoc":387,"header":"@pytest.mark.parametrize(\"type\", [\"Error\", \"Failure\"])\ndef test_testcase_custom_exception_info(testdir, type)","id":6295,"name":"test_testcase_custom_exception_info","nodeType":"Function","startLoc":353,"text":"@pytest.mark.parametrize(\"type\", [\"Error\", \"Failure\"])\ndef test_testcase_custom_exception_info(testdir, type):\n testdir.makepyfile(\n \"\"\"\n from unittest import TestCase\n import py, pytest\n import _pytest._code\n class MyTestCase(TestCase):\n def run(self, result):\n excinfo = pytest.raises(ZeroDivisionError, lambda: 0/0)\n # we fake an incompatible exception info\n from _pytest.monkeypatch import MonkeyPatch\n mp = MonkeyPatch()\n def t(*args):\n mp.undo()\n raise TypeError()\n mp.setattr(_pytest._code, 'ExceptionInfo', t)\n try:\n excinfo = excinfo._excinfo\n result.add%(type)s(self, excinfo)\n finally:\n mp.undo()\n def test_hello(self):\n pass\n \"\"\"\n % locals()\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"NOTE: Incompatible Exception Representation*\",\n \"*ZeroDivisionError*\",\n \"*1 failed*\",\n ]\n )"},{"col":0,"comment":"Test that capture manager is suspended when we emitting messages for live logging.\n\n This tests the implementation calls instead of behavior because it is difficult/impossible to do it using\n ``testdir`` facilities because they do their own capturing.\n\n We parametrize the test to also make sure _LiveLoggingStreamHandler works correctly if no capture manager plugin\n is installed.\n ","endLoc":910,"header":"@pytest.mark.parametrize(\"has_capture_manager\", [True, False])\ndef test_live_logging_suspends_capture(has_capture_manager, request)","id":6296,"name":"test_live_logging_suspends_capture","nodeType":"Function","startLoc":868,"text":"@pytest.mark.parametrize(\"has_capture_manager\", [True, False])\ndef test_live_logging_suspends_capture(has_capture_manager, request):\n \"\"\"Test that capture manager is suspended when we emitting messages for live logging.\n\n This tests the implementation calls instead of behavior because it is difficult/impossible to do it using\n ``testdir`` facilities because they do their own capturing.\n\n We parametrize the test to also make sure _LiveLoggingStreamHandler works correctly if no capture manager plugin\n is installed.\n \"\"\"\n import logging\n import contextlib\n from functools import partial\n from _pytest.logging import _LiveLoggingStreamHandler\n\n class MockCaptureManager:\n calls = []\n\n @contextlib.contextmanager\n def global_and_fixture_disabled(self):\n self.calls.append(\"enter disabled\")\n yield\n self.calls.append(\"exit disabled\")\n\n class DummyTerminal(six.StringIO):\n def section(self, *args, **kwargs):\n pass\n\n out_file = DummyTerminal()\n capture_manager = MockCaptureManager() if has_capture_manager else None\n handler = _LiveLoggingStreamHandler(out_file, capture_manager)\n handler.set_when(\"call\")\n\n logger = logging.getLogger(__name__ + \".test_live_logging_suspends_capture\")\n logger.addHandler(handler)\n request.addfinalizer(partial(logger.removeHandler, handler))\n\n logger.critical(\"some message\")\n if has_capture_manager:\n assert MockCaptureManager.calls == [\"enter disabled\", \"exit disabled\"]\n else:\n assert MockCaptureManager.calls == []\n assert out_file.getvalue() == \"\\nsome message\\n\""},{"col":0,"comment":"null","endLoc":186,"header":"def pytest_report_teststatus(report)","id":6297,"name":"pytest_report_teststatus","nodeType":"Function","startLoc":181,"text":"def pytest_report_teststatus(report):\n if hasattr(report, \"wasxfail\"):\n if report.skipped:\n return \"xfailed\", \"x\", \"XFAIL\"\n elif report.passed:\n return \"xpassed\", \"X\", \"XPASS\""},{"col":0,"comment":"","endLoc":2,"header":"skipping.py#","id":6298,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" support for skip/xfail functions and markers. \"\"\""},{"col":4,"comment":"null","endLoc":834,"header":"def test_cmdline_python_package_not_exists(self, testdir)","id":6299,"name":"test_cmdline_python_package_not_exists","nodeType":"Function","startLoc":831,"text":"def test_cmdline_python_package_not_exists(self, testdir):\n result = testdir.runpytest(\"--pyargs\", \"tpkgwhatv\")\n assert result.ret\n result.stderr.fnmatch_lines([\"ERROR*file*or*package*not*found*\"])"},{"col":4,"comment":"null","endLoc":850,"header":"@pytest.mark.xfail(reason=\"decide: feature or bug\")\n def test_noclass_discovery_if_not_testcase(self, testdir)","id":6300,"name":"test_noclass_discovery_if_not_testcase","nodeType":"Function","startLoc":836,"text":"@pytest.mark.xfail(reason=\"decide: feature or bug\")\n def test_noclass_discovery_if_not_testcase(self, testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n class TestHello(object):\n def test_hello(self):\n assert self.attr\n\n class RealTest(unittest.TestCase, TestHello):\n attr = 42\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":"null","endLoc":870,"header":"def test_doctest_id(self, testdir)","id":6301,"name":"test_doctest_id","nodeType":"Function","startLoc":852,"text":"def test_doctest_id(self, testdir):\n testdir.makefile(\n \".txt\",\n \"\"\"\n >>> x=3\n >>> x\n 4\n \"\"\",\n )\n result = testdir.runpytest(\"-rf\")\n lines = result.stdout.str().splitlines()\n for line in lines:\n if line.startswith((\"FAIL \", \"FAILED \")):\n _fail, _sep, testid = line.partition(\" \")\n break\n result = testdir.runpytest(testid, \"-rf\")\n result.stdout.fnmatch_lines(\n [\"FAILED test_doctest_id.txt::test_doctest_id.txt\", \"*1 failed*\"]\n )"},{"id":6302,"name":"release-3.3.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.3.2\n=======================================\n\npytest 3.3.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Antony Lee\n* Austin\n* Bruno Oliveira\n* Florian Bruhin\n* Floris Bruynooghe\n* Henk-Jaap Wagenaar\n* Jurko Gospodnetić\n* Ronny Pfannschmidt\n* Srinivas Reddy Thatiparthy\n* Thomas Hisch\n\n\nHappy testing,\nThe pytest Development Team\n"},{"col":4,"comment":"Test backward compatibility for get_plugin_manager function. See #787.","endLoc":879,"header":"def test_core_backward_compatibility(self)","id":6303,"name":"test_core_backward_compatibility","nodeType":"Function","startLoc":872,"text":"def test_core_backward_compatibility(self):\n \"\"\"Test backward compatibility for get_plugin_manager function. See #787.\"\"\"\n import _pytest.config\n\n assert (\n type(_pytest.config.get_plugin_manager())\n is _pytest.config.PytestPluginManager\n )"},{"col":0,"comment":"null","endLoc":401,"header":"def test_testcase_totally_incompatible_exception_info(testdir)","id":6304,"name":"test_testcase_totally_incompatible_exception_info","nodeType":"Function","startLoc":390,"text":"def test_testcase_totally_incompatible_exception_info(testdir):\n item, = testdir.getitems(\n \"\"\"\n from unittest import TestCase\n class MyTestCase(TestCase):\n def test_hello(self):\n pass\n \"\"\"\n )\n item.addError(None, 42)\n excinfo = item._excinfo.pop(0)\n assert \"ERROR: Unknown Incompatible\" in str(excinfo.getrepr())"},{"id":6305,"name":"release-3.7.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.7.1\n=======================================\n\npytest 3.7.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Kale Kundert\n* Ronny Pfannschmidt\n\n\nHappy testing,\nThe pytest Development Team\n"},{"attributeType":"str","col":0,"comment":"null","endLoc":10,"id":6306,"name":"FILE_OR_DIR","nodeType":"Attribute","startLoc":10,"text":"FILE_OR_DIR"},{"col":0,"comment":"","endLoc":2,"header":"argparsing.py#","id":6307,"name":"","nodeType":"Function","startLoc":2,"text":"FILE_OR_DIR = \"file_or_dir\""},{"id":6308,"name":"release-3.9.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.9.0\n=======================================\n\nThe pytest team is proud to announce the 3.9.0 release!\n\npytest is a mature Python testing tool with more than a 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n https://docs.pytest.org/en/latest/changelog.html\n\nFor complete documentation, please visit:\n\n https://docs.pytest.org/en/latest/\n\nAs usual, you can upgrade from pypi via:\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Andrea Cimatoribus\n* Ankit Goel\n* Anthony Sottile\n* Ben Eyal\n* Bruno Oliveira\n* Daniel Hahler\n* Jeffrey Rackauckas\n* Jose Carlos Menezes\n* Kyle Altendorf\n* Niklas JQ\n* Palash Chatterjee\n* Ronny Pfannschmidt\n* Thomas Hess\n* Thomas Hisch\n* Tomer Keren\n* Victor Maryama\n\n\nHappy testing,\nThe Pytest Development Team\n"},{"col":0,"comment":"null","endLoc":932,"header":"def test_xfail_skipif_with_globals(testdir)","id":6309,"name":"test_xfail_skipif_with_globals","nodeType":"Function","startLoc":918,"text":"def test_xfail_skipif_with_globals(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n x = 3\n @pytest.mark.skipif(\"x == 3\")\n def test_skip1():\n pass\n @pytest.mark.xfail(\"x == 3\")\n def test_boolean():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"-rsx\")\n result.stdout.fnmatch_lines([\"*SKIP*x == 3*\", \"*XFAIL*test_boolean*\", \"*x == 3*\"])"},{"id":6310,"name":"index.rst","nodeType":"TextFile","path":"doc/en/announce","text":"\nRelease announcements\n===========================================\n\n.. toctree::\n :maxdepth: 2\n\n\n release-4.6.5\n release-4.6.4\n release-4.6.3\n release-4.6.2\n release-4.6.1\n release-4.6.0\n release-4.5.0\n release-4.4.2\n release-4.4.1\n release-4.4.0\n release-4.3.1\n release-4.3.0\n release-4.2.1\n release-4.2.0\n release-4.1.1\n release-4.1.0\n release-4.0.2\n release-4.0.1\n release-4.0.0\n release-3.10.1\n release-3.10.0\n release-3.9.3\n release-3.9.2\n release-3.9.1\n release-3.9.0\n release-3.8.2\n release-3.8.1\n release-3.8.0\n release-3.7.4\n release-3.7.3\n release-3.7.2\n release-3.7.1\n release-3.7.0\n release-3.6.4\n release-3.6.3\n release-3.6.2\n release-3.6.1\n release-3.6.0\n release-3.5.1\n release-3.5.0\n release-3.4.2\n release-3.4.1\n release-3.4.0\n release-3.3.2\n release-3.3.1\n release-3.3.0\n release-3.2.5\n release-3.2.4\n release-3.2.3\n release-3.2.2\n release-3.2.1\n release-3.2.0\n release-3.1.3\n release-3.1.2\n release-3.1.1\n release-3.1.0\n release-3.0.7\n release-3.0.6\n release-3.0.5\n release-3.0.4\n release-3.0.3\n release-3.0.2\n release-3.0.1\n release-3.0.0\n sprint2016\n release-2.9.2\n release-2.9.1\n release-2.9.0\n release-2.8.7\n release-2.8.6\n release-2.8.5\n release-2.8.4\n release-2.8.3\n release-2.8.2\n release-2.7.2\n release-2.7.1\n release-2.7.0\n release-2.6.3\n release-2.6.2\n release-2.6.1\n release-2.6.0\n release-2.5.2\n release-2.5.1\n release-2.5.0\n release-2.4.2\n release-2.4.1\n release-2.4.0\n release-2.3.5\n release-2.3.4\n release-2.3.3\n release-2.3.2\n release-2.3.1\n release-2.3.0\n release-2.2.4\n release-2.2.2\n release-2.2.1\n release-2.2.0\n release-2.1.3\n release-2.1.2\n release-2.1.1\n release-2.1.0\n release-2.0.3\n release-2.0.2\n release-2.0.1\n release-2.0.0\n"},{"id":6311,"name":"customize.rst","nodeType":"TextFile","path":"doc/en","text":"Configuration\n=============\n\nCommand line options and configuration file settings\n-----------------------------------------------------------------\n\nYou can get help on command line options and values in INI-style\nconfigurations files by using the general help option:\n\n.. code-block:: bash\n\n pytest -h # prints options _and_ config file settings\n\nThis will display command line and configuration file settings\nwhich were registered by installed plugins.\n\n.. _rootdir:\n.. _inifiles:\n\nInitialization: determining rootdir and inifile\n-----------------------------------------------\n\n\n\npytest determines a ``rootdir`` for each test run which depends on\nthe command line arguments (specified test files, paths) and on\nthe existence of *ini-files*. The determined ``rootdir`` and *ini-file* are\nprinted as part of the pytest header during startup.\n\nHere's a summary what ``pytest`` uses ``rootdir`` for:\n\n* Construct *nodeids* during collection; each test is assigned\n a unique *nodeid* which is rooted at the ``rootdir`` and takes in account full path,\n class name, function name and parametrization (if any).\n\n* Is used by plugins as a stable location to store project/test run specific information;\n for example, the internal :ref:`cache ` plugin creates a ``.pytest_cache`` subdirectory\n in ``rootdir`` to store its cross-test run state.\n\nImportant to emphasize that ``rootdir`` is **NOT** used to modify ``sys.path``/``PYTHONPATH`` or\ninfluence how modules are imported. See :ref:`pythonpath` for more details.\n\n``--rootdir=path`` command-line option can be used to force a specific directory.\nThe directory passed may contain environment variables when it is used in conjunction\nwith ``addopts`` in a ``pytest.ini`` file.\n\nFinding the ``rootdir``\n~~~~~~~~~~~~~~~~~~~~~~~\n\nHere is the algorithm which finds the rootdir from ``args``:\n\n- determine the common ancestor directory for the specified ``args`` that are\n recognised as paths that exist in the file system. If no such paths are\n found, the common ancestor directory is set to the current working directory.\n\n- look for ``pytest.ini``, ``tox.ini`` and ``setup.cfg`` files in the ancestor\n directory and upwards. If one is matched, it becomes the ini-file and its\n directory becomes the rootdir.\n\n- if no ini-file was found, look for ``setup.py`` upwards from the common\n ancestor directory to determine the ``rootdir``.\n\n- if no ``setup.py`` was found, look for ``pytest.ini``, ``tox.ini`` and\n ``setup.cfg`` in each of the specified ``args`` and upwards. If one is\n matched, it becomes the ini-file and its directory becomes the rootdir.\n\n- if no ini-file was found, use the already determined common ancestor as root\n directory. This allows the use of pytest in structures that are not part of\n a package and don't have any particular ini-file configuration.\n\nIf no ``args`` are given, pytest collects test below the current working\ndirectory and also starts determining the rootdir from there.\n\n:warning: custom pytest plugin commandline arguments may include a path, as in\n ``pytest --log-output ../../test.log args``. Then ``args`` is mandatory,\n otherwise pytest uses the folder of test.log for rootdir determination\n (see also `issue 1435 `_).\n A dot ``.`` for referencing to the current working directory is also\n possible.\n\nNote that an existing ``pytest.ini`` file will always be considered a match,\nwhereas ``tox.ini`` and ``setup.cfg`` will only match if they contain a\n``[pytest]`` or ``[tool:pytest]`` section, respectively. Options from multiple ini-files candidates are never\nmerged - the first one wins (``pytest.ini`` always wins, even if it does not\ncontain a ``[pytest]`` section).\n\nThe ``config`` object will subsequently carry these attributes:\n\n- ``config.rootdir``: the determined root directory, guaranteed to exist.\n\n- ``config.inifile``: the determined ini-file, may be ``None``.\n\nThe rootdir is used as a reference directory for constructing test\naddresses (\"nodeids\") and can be used also by plugins for storing\nper-testrun information.\n\nExample:\n\n.. code-block:: bash\n\n pytest path/to/testdir path/other/\n\nwill determine the common ancestor as ``path`` and then\ncheck for ini-files as follows:\n\n.. code-block:: text\n\n # first look for pytest.ini files\n path/pytest.ini\n path/setup.cfg # must also contain [tool:pytest] section to match\n path/tox.ini # must also contain [pytest] section to match\n pytest.ini\n ... # all the way down to the root\n\n # now look for setup.py\n path/setup.py\n setup.py\n ... # all the way down to the root\n\n\n.. _`how to change command line options defaults`:\n.. _`adding default options`:\n\n\n\nHow to change command line options defaults\n------------------------------------------------\n\nIt can be tedious to type the same series of command line options\nevery time you use ``pytest``. For example, if you always want to see\ndetailed info on skipped and xfailed tests, as well as have terser \"dot\"\nprogress output, you can write it into a configuration file:\n\n.. code-block:: ini\n\n # content of pytest.ini or tox.ini\n # setup.cfg files should use [tool:pytest] section instead\n [pytest]\n addopts = -ra -q\n\nAlternatively, you can set a ``PYTEST_ADDOPTS`` environment variable to add command\nline options while the environment is in use:\n\n.. code-block:: bash\n\n export PYTEST_ADDOPTS=\"-v\"\n\nHere's how the command-line is built in the presence of ``addopts`` or the environment variable:\n\n.. code-block:: text\n\n $PYTEST_ADDOPTS \n\nSo if the user executes in the command-line:\n\n.. code-block:: bash\n\n pytest -m slow\n\nThe actual command line executed is:\n\n.. code-block:: bash\n\n pytest -ra -q -v -m slow\n\nNote that as usual for other command-line applications, in case of conflicting options the last one wins, so the example\nabove will show verbose output because ``-v`` overwrites ``-q``.\n\n\nBuiltin configuration file options\n----------------------------------------------\n\nFor the full list of options consult the :ref:`reference documentation `.\n"},{"col":0,"comment":"null","endLoc":945,"header":"def test_direct_gives_error(testdir)","id":6312,"name":"test_direct_gives_error","nodeType":"Function","startLoc":935,"text":"def test_direct_gives_error(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.skipif(True)\n def test_skip1():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 error*\"])"},{"col":0,"comment":"null","endLoc":955,"header":"def test_default_markers(testdir)","id":6313,"name":"test_default_markers","nodeType":"Function","startLoc":948,"text":"def test_default_markers(testdir):\n result = testdir.runpytest(\"--markers\")\n result.stdout.fnmatch_lines(\n [\n \"*skipif(*condition)*skip*\",\n \"*xfail(*condition, reason=None, run=True, raises=None, strict=False)*expected failure*\",\n ]\n )"},{"id":6314,"name":"index.rst","nodeType":"TextFile","path":"doc/en","text":":orphan:\n\n.. _features:\n\npytest: helps you write better programs\n=======================================\n\n\nThe ``pytest`` framework makes it easy to write small tests, yet\nscales to support complex functional testing for applications and libraries.\n\nAn example of a simple test:\n\n.. code-block:: python\n\n # content of test_sample.py\n def inc(x):\n return x + 1\n\n\n def test_answer():\n assert inc(3) == 5\n\n\nTo execute it:\n\n.. code-block:: pytest\n\n $ pytest\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 1 item\n\n test_sample.py F [100%]\n\n ================================= FAILURES =================================\n _______________________________ test_answer ________________________________\n\n def test_answer():\n > assert inc(3) == 5\n E assert 4 == 5\n E + where 4 = inc(3)\n\n test_sample.py:6: AssertionError\n ========================= 1 failed in 0.12 seconds =========================\n\nDue to ``pytest``'s detailed assertion introspection, only plain ``assert`` statements are used.\nSee :ref:`Getting Started ` for more examples.\n\n\nFeatures\n--------\n\n- Detailed info on failing :ref:`assert statements ` (no need to remember ``self.assert*`` names);\n\n- :ref:`Auto-discovery ` of test modules and functions;\n\n- :ref:`Modular fixtures ` for managing small or parametrized long-lived test resources;\n\n- Can run :ref:`unittest ` (including trial) and :ref:`nose ` test suites out of the box;\n\n- Python 2.7, Python 3.4+, PyPy 2.3, Jython 2.5 (untested);\n\n- Rich plugin architecture, with over 315+ `external plugins `_ and thriving community;\n\n\nDocumentation\n-------------\n\nPlease see :ref:`Contents ` for full documentation, including installation, tutorials and PDF documents.\n\n\nBugs/Requests\n-------------\n\nPlease use the `GitHub issue tracker `_ to submit bugs or request features.\n\n\nChangelog\n---------\n\nConsult the :ref:`Changelog ` page for fixes and enhancements of each version.\n\n\nLicense\n-------\n\nCopyright Holger Krekel and others, 2004-2017.\n\nDistributed under the terms of the `MIT`_ license, pytest is free and open source software.\n\n.. _`MIT`: https://github.com/pytest-dev/pytest/blob/master/LICENSE\n"},{"id":6315,"name":"relations.html","nodeType":"TextFile","path":"doc/en/_themes/flask","text":"

Related Topics

\n\n"},{"col":0,"comment":"null","endLoc":976,"header":"def test_xfail_test_setup_exception(testdir)","id":6316,"name":"test_xfail_test_setup_exception","nodeType":"Function","startLoc":958,"text":"def test_xfail_test_setup_exception(testdir):\n testdir.makeconftest(\n \"\"\"\n def pytest_runtest_setup():\n 0 / 0\n \"\"\"\n )\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail\n def test_func():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(p)\n assert result.ret == 0\n assert \"xfailed\" in result.stdout.str()\n assert \"xpassed\" not in result.stdout.str()"},{"id":6317,"name":"tox.ini","nodeType":"TextFile","path":"","text":"[tox]\nisolated_build = True\nminversion = 3.5.3\ndistshare = {homedir}/.tox/distshare\n# make sure to update environment list in travis.yml and appveyor.yml\nenvlist =\n linting\n py27\n py34\n py35\n py36\n py37\n py38\n pypy\n pypy3\n {py27,py37}-{pexpect,xdist,twisted,numpy,pluggymaster}\n py27-nobyte-xdist\n doctesting\n py37-freeze\n docs\n\n[testenv]\ncommands =\n {env:_PYTEST_TOX_COVERAGE_RUN:} pytest {posargs:{env:_PYTEST_TOX_DEFAULT_POSARGS:}}\n coverage: coverage combine\n coverage: coverage report\npassenv = USER USERNAME COVERAGE_* TRAVIS PYTEST_ADDOPTS\nsetenv =\n _PYTEST_TOX_DEFAULT_POSARGS={env:_PYTEST_TOX_POSARGS_LSOF:} {env:_PYTEST_TOX_POSARGS_PEXPECT:} {env:_PYTEST_TOX_POSARGS_TWISTED:} {env:_PYTEST_TOX_POSARGS_XDIST:}\n\n # Configuration to run with coverage similar to Travis/Appveyor, e.g.\n # \"tox -e py37-coverage\".\n coverage: _PYTEST_TOX_COVERAGE_RUN=coverage run -m\n coverage: _PYTEST_TOX_EXTRA_DEP=coverage-enable-subprocess\n coverage: COVERAGE_FILE={toxinidir}/.coverage\n coverage: COVERAGE_PROCESS_START={toxinidir}/.coveragerc\n\n nobyte: PYTHONDONTWRITEBYTECODE=1\n\n lsof: _PYTEST_TOX_POSARGS_LSOF=--lsof\n\n pexpect: _PYTEST_TOX_PLATFORM=linux|darwin\n pexpect: _PYTEST_TOX_POSARGS_PEXPECT=-m uses_pexpect\n\n twisted: _PYTEST_TOX_POSARGS_TWISTED=testing/test_unittest.py\n\n xdist: _PYTEST_TOX_POSARGS_XDIST=-n auto\nextras = testing\ndeps =\n numpy: numpy\n pexpect: pexpect\n pluggymaster: git+https://github.com/pytest-dev/pluggy.git@master\n twisted: twisted\n twisted: unittest2\n xdist: pytest-xdist>=1.13\n {env:_PYTEST_TOX_EXTRA_DEP:}\nplatform = {env:_PYTEST_TOX_PLATFORM:.*}\n\n[testenv:py27-subprocess]\ndeps =\n pytest-xdist>=1.13\n py27: mock\n nose\ncommands =\n pytest -n auto --runpytest=subprocess {posargs}\n\n\n[testenv:linting]\nskip_install = True\nbasepython = python3\ndeps = pre-commit>=1.11.0\ncommands = pre-commit run --all-files --show-diff-on-failure\n\n[testenv:docs]\nbasepython = python3\nusedevelop = True\nchangedir = doc/en\ndeps = -r{toxinidir}/doc/en/requirements.txt\n\ncommands =\n sphinx-build -W -b html . _build\n\n[testenv:doctesting]\nbasepython = python3\nskipsdist = True\ndeps =\n {[testenv]deps}\n PyYAML\ncommands =\n {env:_PYTEST_TOX_COVERAGE_RUN:} pytest doc/en\n {env:_PYTEST_TOX_COVERAGE_RUN:} pytest --doctest-modules --pyargs _pytest\n\n[testenv:regen]\nchangedir = doc/en\nskipsdist = True\nbasepython = python3.6\ndeps =\n sphinx\n PyYAML\n regendoc>=0.6.1\n dataclasses\nwhitelist_externals =\n rm\n make\ncommands =\n # don't show hypothesis plugin info in docs, see #4602\n pip uninstall hypothesis -y\n rm -rf /tmp/doc-exec*\n rm -rf {envdir}/.pytest_cache\n make regen\n\n[testenv:jython]\nchangedir = testing\ncommands =\n {envpython} {envbindir}/py.test-jython {posargs}\n\n[testenv:py37-freeze]\nchangedir = testing/freeze\n# Disable PEP 517 with pip, which does not work with PyInstaller currently.\ndeps =\n pyinstaller\ncommands =\n {envpython} create_executable.py\n {envpython} tox_run.py\n\n[testenv:release]\ndecription = do a release, required posarg of the version number\nbasepython = python3.6\nusedevelop = True\npassenv = *\ndeps =\n colorama\n gitpython\n pre-commit>=1.11.0\n towncrier\n wheel\ncommands = python scripts/release.py {posargs}\n\n[testenv:publish_gh_release_notes]\ndescription = create GitHub release after deployment\nbasepython = python3.6\nusedevelop = True\npassenv = GH_RELEASE_NOTES_TOKEN TRAVIS_TAG TRAVIS_REPO_SLUG\ndeps =\n github3.py\n pypandoc\ncommands = python scripts/publish_gh_release_notes.py\n\n\n[pytest]\nminversion = 2.0\naddopts = -ra -p pytester --strict-markers\nrsyncdirs = tox.ini doc src testing\npython_files = test_*.py *_test.py testing/*/*.py\npython_classes = Test Acceptance\npython_functions = test\n# NOTE: \"doc\" is not included here, but gets tested explicitly via \"doctesting\".\ntestpaths = testing\nnorecursedirs = testing/example_scripts\nxfail_strict=true\nfilterwarnings =\n error\n ignore:yield tests are deprecated, and scheduled to be removed in pytest 4.0:pytest.RemovedInPytest4Warning\n ignore:Metafunc.addcall is deprecated and scheduled to be removed in pytest 4.0:pytest.RemovedInPytest4Warning\n ignore::pytest.RemovedInPytest4Warning\n ignore:Module already imported so cannot be rewritten:pytest.PytestWarning\n # produced by path.local\n ignore:bad escape.*:DeprecationWarning:re\n # produced by path.readlines\n ignore:.*U.*mode is deprecated:DeprecationWarning\n # produced by pytest-xdist\n ignore:.*type argument to addoption.*:DeprecationWarning\n # produced by python >=3.5 on execnet (pytest-xdist)\n ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning\n # pytest's own futurewarnings\n ignore::pytest.PytestExperimentalApiWarning\n # Do not cause SyntaxError for invalid escape sequences in py37.\n default:invalid escape sequence:DeprecationWarning\n # ignore use of unregistered marks, because we use many to test the implementation\n ignore::_pytest.warning_types.PytestUnknownMarkWarning\npytester_example_dir = testing/example_scripts\nmarkers =\n # dummy markers for testing\n foo\n bar\n baz\n # conftest.py reorders tests moving slow ones to the end of the list\n slow\n # experimental mark for all tests using pexpect\n uses_pexpect\n\n[flake8]\nmax-line-length = 120\nignore = E203,W503\n\n[isort]\n; This config mimics what reorder-python-imports does.\nforce_single_line = 1\nknown_localfolder = pytest,_pytest\nknown_third_party = test_source,test_excinfo\nforce_alphabetical_sort_within_sections = 1\n"},{"col":0,"comment":"null","endLoc":1006,"header":"def test_imperativeskip_on_xfail_test(testdir)","id":6318,"name":"test_imperativeskip_on_xfail_test","nodeType":"Function","startLoc":979,"text":"def test_imperativeskip_on_xfail_test(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.xfail\n def test_that_fails():\n assert 0\n\n @pytest.mark.skipif(\"True\")\n def test_hello():\n pass\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_runtest_setup(item):\n pytest.skip(\"abc\")\n \"\"\"\n )\n result = testdir.runpytest(\"-rsxX\")\n result.stdout.fnmatch_lines_random(\n \"\"\"\n *SKIP*abc*\n *SKIP*condition: True*\n *2 skipped*\n \"\"\"\n )"},{"fileName":"test_compare_dataclasses.py","filePath":"testing/example_scripts/dataclasses","id":6319,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom dataclasses import dataclass\nfrom dataclasses import field\n\n\ndef test_dataclasses():\n @dataclass\n class SimpleDataObject(object):\n field_a: int = field()\n field_b: int = field()\n\n left = SimpleDataObject(1, \"b\")\n right = SimpleDataObject(1, \"c\")\n\n assert left == right\n"},{"col":0,"comment":"null","endLoc":416,"header":"def test_module_level_pytestmark(testdir)","id":6320,"name":"test_module_level_pytestmark","nodeType":"Function","startLoc":404,"text":"def test_module_level_pytestmark(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n import pytest\n pytestmark = pytest.mark.xfail\n class MyTestCase(unittest.TestCase):\n def test_func1(self):\n assert 0\n \"\"\"\n )\n reprec = testdir.inline_run(testpath, \"-s\")\n reprec.assertoutcome(skipped=1)"},{"col":0,"comment":"null","endLoc":1083,"header":"def test_xfail_item(testdir)","id":6321,"name":"test_xfail_item","nodeType":"Function","startLoc":1064,"text":"def test_xfail_item(testdir):\n # Ensure pytest.xfail works with non-Python Item\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n class MyItem(pytest.Item):\n nodeid = 'foo'\n def runtest(self):\n pytest.xfail(\"Expected Failure\")\n\n def pytest_collect_file(path, parent):\n return MyItem(\"foo\", parent)\n \"\"\"\n )\n result = testdir.inline_run()\n passed, skipped, failed = result.listoutcomes()\n assert not failed\n xfailed = [r for r in skipped if hasattr(r, \"wasxfail\")]\n assert xfailed"},{"fileName":"test_compare_dataclasses_field_comparison_off.py","filePath":"testing/example_scripts/dataclasses","id":6322,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom dataclasses import dataclass\nfrom dataclasses import field\n\n\ndef test_dataclasses_with_attribute_comparison_off():\n @dataclass\n class SimpleDataObject(object):\n field_a: int = field()\n field_b: int = field(compare=False)\n\n left = SimpleDataObject(1, \"b\")\n right = SimpleDataObject(1, \"c\")\n\n assert left == right\n"},{"col":0,"comment":"null","endLoc":683,"header":"def test_djangolike_testcase(testdir)","id":6323,"name":"test_djangolike_testcase","nodeType":"Function","startLoc":628,"text":"def test_djangolike_testcase(testdir):\n # contributed from Morten Breekevold\n testdir.makepyfile(\n \"\"\"\n from unittest import TestCase, main\n\n class DjangoLikeTestCase(TestCase):\n\n def setUp(self):\n print(\"setUp()\")\n\n def test_presetup_has_been_run(self):\n print(\"test_thing()\")\n self.assertTrue(hasattr(self, 'was_presetup'))\n\n def tearDown(self):\n print(\"tearDown()\")\n\n def __call__(self, result=None):\n try:\n self._pre_setup()\n except (KeyboardInterrupt, SystemExit):\n raise\n except Exception:\n import sys\n result.addError(self, sys.exc_info())\n return\n super(DjangoLikeTestCase, self).__call__(result)\n try:\n self._post_teardown()\n except (KeyboardInterrupt, SystemExit):\n raise\n except Exception:\n import sys\n result.addError(self, sys.exc_info())\n return\n\n def _pre_setup(self):\n print(\"_pre_setup()\")\n self.was_presetup = True\n\n def _post_teardown(self):\n print(\"_post_teardown()\")\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n assert result.ret == 0\n result.stdout.fnmatch_lines(\n [\n \"*_pre_setup()*\",\n \"*setUp()*\",\n \"*test_thing()*\",\n \"*tearDown()*\",\n \"*_post_teardown()*\",\n ]\n )"},{"col":0,"comment":"null","endLoc":697,"header":"def test_unittest_not_shown_in_traceback(testdir)","id":6324,"name":"test_unittest_not_shown_in_traceback","nodeType":"Function","startLoc":686,"text":"def test_unittest_not_shown_in_traceback(testdir):\n testdir.makepyfile(\n \"\"\"\n import unittest\n class t(unittest.TestCase):\n def test_hello(self):\n x = 3\n self.assertEqual(x, 4)\n \"\"\"\n )\n res = testdir.runpytest()\n assert \"failUnlessEqual\" not in res.stdout.str()"},{"col":0,"comment":"\n Verify that using pytest.skip at module level causes a collection error\n ","endLoc":1101,"header":"def test_module_level_skip_error(testdir)","id":6325,"name":"test_module_level_skip_error","nodeType":"Function","startLoc":1086,"text":"def test_module_level_skip_error(testdir):\n \"\"\"\n Verify that using pytest.skip at module level causes a collection error\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.skip\n def test_func():\n assert True\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"*Using pytest.skip outside of a test is not allowed*\"]\n )"},{"col":0,"comment":"null","endLoc":717,"header":"def test_unorderable_types(testdir)","id":6326,"name":"test_unorderable_types","nodeType":"Function","startLoc":700,"text":"def test_unorderable_types(testdir):\n testdir.makepyfile(\n \"\"\"\n import unittest\n class TestJoinEmpty(unittest.TestCase):\n pass\n\n def make_test():\n class Test(unittest.TestCase):\n pass\n Test.__name__ = \"TestFoo\"\n return Test\n TestFoo = make_test()\n \"\"\"\n )\n result = testdir.runpytest()\n assert \"TypeError\" not in result.stdout.str()\n assert result.ret == EXIT_NOTESTSCOLLECTED"},{"col":0,"comment":"null","endLoc":15,"header":"def test_dataclasses()","id":6327,"name":"test_dataclasses","nodeType":"Function","startLoc":6,"text":"def test_dataclasses():\n @dataclass\n class SimpleDataObject(object):\n field_a: int = field()\n field_b: int = field()\n\n left = SimpleDataObject(1, \"b\")\n right = SimpleDataObject(1, \"c\")\n\n assert left == right"},{"col":0,"comment":"\n Verify that using pytest.skip(allow_module_level=True) is allowed\n ","endLoc":1118,"header":"def test_module_level_skip_with_allow_module_level(testdir)","id":6328,"name":"test_module_level_skip_with_allow_module_level","nodeType":"Function","startLoc":1104,"text":"def test_module_level_skip_with_allow_module_level(testdir):\n \"\"\"\n Verify that using pytest.skip(allow_module_level=True) is allowed\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n pytest.skip(\"skip_module_level\", allow_module_level=True)\n\n def test_func():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"-rxs\")\n result.stdout.fnmatch_lines([\"*SKIP*skip_module_level\"])"},{"col":0,"comment":"null","endLoc":731,"header":"def test_unittest_typerror_traceback(testdir)","id":6330,"name":"test_unittest_typerror_traceback","nodeType":"Function","startLoc":720,"text":"def test_unittest_typerror_traceback(testdir):\n testdir.makepyfile(\n \"\"\"\n import unittest\n class TestJoinEmpty(unittest.TestCase):\n def test_hello(self, arg1):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n assert \"TypeError\" in result.stdout.str()\n assert result.ret == 1"},{"col":0,"comment":"\n Verify that using pytest.skip() with unknown parameter raises an error\n ","endLoc":1135,"header":"def test_invalid_skip_keyword_parameter(testdir)","id":6331,"name":"test_invalid_skip_keyword_parameter","nodeType":"Function","startLoc":1121,"text":"def test_invalid_skip_keyword_parameter(testdir):\n \"\"\"\n Verify that using pytest.skip() with unknown parameter raises an error\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n pytest.skip(\"skip_module_level\", unknown=1)\n\n def test_func():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*TypeError:*['unknown']*\"])"},{"col":0,"comment":"null","endLoc":755,"header":"@pytest.mark.parametrize(\"runner\", [\"pytest\", \"unittest\"])\ndef test_unittest_expected_failure_for_failing_test_is_xfail(testdir, runner)","id":6332,"name":"test_unittest_expected_failure_for_failing_test_is_xfail","nodeType":"Function","startLoc":734,"text":"@pytest.mark.parametrize(\"runner\", [\"pytest\", \"unittest\"])\ndef test_unittest_expected_failure_for_failing_test_is_xfail(testdir, runner):\n script = testdir.makepyfile(\n \"\"\"\n import unittest\n class MyTestCase(unittest.TestCase):\n @unittest.expectedFailure\n def test_failing_test_is_xfail(self):\n assert False\n if __name__ == '__main__':\n unittest.main()\n \"\"\"\n )\n if runner == \"pytest\":\n result = testdir.runpytest(\"-rxX\")\n result.stdout.fnmatch_lines(\n [\"*XFAIL*MyTestCase*test_failing_test_is_xfail*\", \"*1 xfailed*\"]\n )\n else:\n result = testdir.runpython(script)\n result.stderr.fnmatch_lines([\"*1 test in*\", \"*OK*(expected failures=1)*\"])\n assert result.ret == 0"},{"col":0,"comment":"null","endLoc":1160,"header":"def test_mark_xfail_item(testdir)","id":6333,"name":"test_mark_xfail_item","nodeType":"Function","startLoc":1138,"text":"def test_mark_xfail_item(testdir):\n # Ensure pytest.mark.xfail works with non-Python Item\n testdir.makeconftest(\n \"\"\"\n import pytest\n\n class MyItem(pytest.Item):\n nodeid = 'foo'\n def setup(self):\n marker = pytest.mark.xfail(True, reason=\"Expected failure\")\n self.add_marker(marker)\n def runtest(self):\n assert False\n\n def pytest_collect_file(path, parent):\n return MyItem(\"foo\", parent)\n \"\"\"\n )\n result = testdir.inline_run()\n passed, skipped, failed = result.listoutcomes()\n assert not failed\n xfailed = [r for r in skipped if hasattr(r, \"wasxfail\")]\n assert xfailed"},{"col":0,"comment":"null","endLoc":15,"header":"def test_dataclasses_with_attribute_comparison_off()","id":6334,"name":"test_dataclasses_with_attribute_comparison_off","nodeType":"Function","startLoc":6,"text":"def test_dataclasses_with_attribute_comparison_off():\n @dataclass\n class SimpleDataObject(object):\n field_a: int = field()\n field_b: int = field(compare=False)\n\n left = SimpleDataObject(1, \"b\")\n right = SimpleDataObject(1, \"c\")\n\n assert left == right"},{"col":0,"comment":"Ensure the list of errors/fails/xfails/skips appears after tracebacks in terminal reporting.","endLoc":1179,"header":"def test_summary_list_after_errors(testdir)","id":6335,"name":"test_summary_list_after_errors","nodeType":"Function","startLoc":1163,"text":"def test_summary_list_after_errors(testdir):\n \"\"\"Ensure the list of errors/fails/xfails/skips appears after tracebacks in terminal reporting.\"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_fail():\n assert 0\n \"\"\"\n )\n result = testdir.runpytest(\"-ra\")\n result.stdout.fnmatch_lines(\n [\n \"=* FAILURES *=\",\n \"*= short test summary info =*\",\n \"FAILED test_summary_list_after_errors.py::test_fail - assert 0\",\n ]\n )"},{"col":0,"comment":"null","endLoc":1187,"header":"def test_importorskip()","id":6336,"name":"test_importorskip","nodeType":"Function","startLoc":1182,"text":"def test_importorskip():\n with pytest.raises(\n pytest.skip.Exception,\n match=\"^could not import 'doesnotexist': No module named .*\",\n ):\n pytest.importorskip(\"doesnotexist\")"},{"col":4,"comment":"Test hasplugin function of the plugin manager (#932).","endLoc":883,"header":"def test_has_plugin(self, request)","id":6337,"name":"test_has_plugin","nodeType":"Function","startLoc":881,"text":"def test_has_plugin(self, request):\n \"\"\"Test hasplugin function of the plugin manager (#932).\"\"\"\n assert request.config.pluginmanager.hasplugin(\"python\")"},{"id":6338,"name":"talks.rst","nodeType":"TextFile","path":"doc/en","text":"\nTalks and Tutorials\n==========================\n\n..\n .. sidebar:: Next Open Trainings\n\n `Professional Testing with Python\n `_,\n 26-28 April 2017, Leipzig, Germany.\n\n.. _`funcargs`: funcargs.html\n\nBooks\n---------------------------------------------\n\n- `pytest Quick Start Guide, by Bruno Oliveira (2018)\n `_.\n\n- `Python Testing with pytest, by Brian Okken (2017)\n `_.\n\nTalks and blog postings\n---------------------------------------------\n\n- pytest: recommendations, basic packages for testing in Python and Django, Andreu Vallbona, PyconES 2017 (`slides in english `_, `video in spanish `_)\n\n- `pytest advanced, Andrew Svetlov (Russian, PyCon Russia, 2016)\n `_.\n\n- `Pythonic testing, Igor Starikov (Russian, PyNsk, November 2016)\n `_.\n\n- `pytest - Rapid Simple Testing, Florian Bruhin, Swiss Python Summit 2016\n `_.\n\n- `Improve your testing with Pytest and Mock, Gabe Hollombe, PyCon SG 2015\n `_.\n\n- `Introduction to pytest, Andreas Pelme, EuroPython 2014\n `_.\n\n- `Advanced Uses of py.test Fixtures, Floris Bruynooghe, EuroPython\n 2014 `_.\n\n- `Why i use py.test and maybe you should too, Andy Todd, Pycon AU 2013\n `_\n\n- `3-part blog series about pytest from @pydanny alias Daniel Greenfeld (January\n 2014) `_\n\n- `pytest: helps you write better Django apps, Andreas Pelme, DjangoCon\n Europe 2014 `_.\n\n- :ref:`fixtures`\n\n- `Testing Django Applications with pytest, Andreas Pelme, EuroPython\n 2013 `_.\n\n- `Testes pythonics com py.test, Vinicius Belchior Assef Neto, Plone\n Conf 2013, Brazil `_.\n\n- `Introduction to py.test fixtures, FOSDEM 2013, Floris Bruynooghe\n `_.\n\n- `pytest feature and release highlights, Holger Krekel (GERMAN, October 2013)\n `_\n\n- `pytest introduction from Brian Okken (January 2013)\n `_\n\n- pycon australia 2012 pytest talk from Brianna Laugher (`video `_, `slides `_, `code `_)\n- `pycon 2012 US talk video from Holger Krekel `_\n\n- `monkey patching done right`_ (blog post, consult `monkeypatch plugin`_ for up-to-date API)\n\nTest parametrization:\n\n- `generating parametrized tests with fixtures`_.\n- `test generators and cached setup`_\n- `parametrizing tests, generalized`_ (blog post)\n- `putting test-hooks into local or global plugins`_ (blog post)\n\nAssertion introspection:\n\n- `(07/2011) Behind the scenes of pytest's new assertion rewriting\n `_\n\nDistributed testing:\n\n- `simultaneously test your code on all platforms`_ (blog entry)\n\nPlugin specific examples:\n\n- `skipping slow tests by default in pytest`_ (blog entry)\n\n- `many examples in the docs for plugins`_\n\n.. _`skipping slow tests by default in pytest`: http://bruynooghe.blogspot.com/2009/12/skipping-slow-test-by-default-in-pytest.html\n.. _`many examples in the docs for plugins`: plugins.html\n.. _`monkeypatch plugin`: monkeypatch.html\n.. _`application setup in test functions with fixtures`: fixture.html#interdependent-fixtures\n.. _`simultaneously test your code on all platforms`: http://tetamap.wordpress.com/2009/03/23/new-simultanously-test-your-code-on-all-platforms/\n.. _`monkey patching done right`: http://tetamap.wordpress.com/2009/03/03/monkeypatching-in-unit-tests-done-right/\n.. _`putting test-hooks into local or global plugins`: http://tetamap.wordpress.com/2009/05/14/putting-test-hooks-into-local-and-global-plugins/\n.. _`parametrizing tests, generalized`: http://tetamap.wordpress.com/2009/05/13/parametrizing-python-tests-generalized/\n.. _`generating parametrized tests with fixtures`: parametrize.html#test-generators\n.. _`test generators and cached setup`: http://bruynooghe.blogspot.com/2010/06/pytest-test-generators-and-cached-setup.html\n"},{"id":6339,"name":"naming20.rst","nodeType":"TextFile","path":"doc/en","text":"\n.. _naming20:\n\nNew pytest names in 2.0 (flat is better than nested)\n----------------------------------------------------\n\nIf you used older version of the ``py`` distribution (which\nincluded the py.test command line tool and Python name space)\nyou accessed helpers and possibly collection classes through\nthe ``py.test`` Python namespaces. The new ``pytest``\nPython module flaty provides the same objects, following\nthese renaming rules::\n\n py.test.XYZ -> pytest.XYZ\n py.test.collect.XYZ -> pytest.XYZ\n py.test.cmdline.main -> pytest.main\n\nThe old ``py.test.*`` ways to access functionality remain\nvalid but you are encouraged to do global renaming according\nto the above rules in your test code.\n"},{"id":6340,"name":"plugins.rst","nodeType":"TextFile","path":"doc/en","text":".. _`external plugins`:\n.. _`extplugins`:\n.. _`using plugins`:\n\nInstalling and Using plugins\n============================\n\nThis section talks about installing and using third party plugins.\nFor writing your own plugins, please refer to :ref:`writing-plugins`.\n\nInstalling a third party plugin can be easily done with ``pip``::\n\n pip install pytest-NAME\n pip uninstall pytest-NAME\n\nIf a plugin is installed, ``pytest`` automatically finds and integrates it,\nthere is no need to activate it.\n\nHere is a little annotated list for some popular plugins:\n\n.. _`django`: https://www.djangoproject.com/\n\n* `pytest-django `_: write tests\n for `django`_ apps, using pytest integration.\n\n* `pytest-twisted `_: write tests\n for `twisted `_ apps, starting a reactor and\n processing deferreds from test functions.\n\n* `pytest-cov `__:\n coverage reporting, compatible with distributed testing\n\n* `pytest-xdist `_:\n to distribute tests to CPUs and remote hosts, to run in boxed\n mode which allows to survive segmentation faults, to run in\n looponfailing mode, automatically re-running failing tests\n on file changes.\n\n* `pytest-instafail `_:\n to report failures while the test run is happening.\n\n* `pytest-bdd `_ and\n `pytest-konira `_\n to write tests using behaviour-driven testing.\n\n* `pytest-timeout `_:\n to timeout tests based on function marks or global definitions.\n\n* `pytest-pep8 `_:\n a ``--pep8`` option to enable PEP8 compliance checking.\n\n* `pytest-flakes `_:\n check source code with pyflakes.\n\n* `oejskit `_:\n a plugin to run javascript unittests in live browsers.\n\nTo see a complete list of all plugins with their latest testing\nstatus against different pytest and Python versions, please visit\n`plugincompat `_.\n\nYou may also discover more plugins through a `pytest- pypi.org search`_.\n\n.. _`pytest- pypi.org search`: https://pypi.org/search/?q=pytest-\n\n\n.. _`available installable plugins`:\n\nRequiring/Loading plugins in a test module or conftest file\n-----------------------------------------------------------\n\nYou can require plugins in a test module or a conftest file like this:\n\n.. code-block:: python\n\n pytest_plugins = (\"myapp.testsupport.myplugin\",)\n\nWhen the test module or conftest plugin is loaded the specified plugins\nwill be loaded as well.\n\n.. note::\n Requiring plugins using a ``pytest_plugins`` variable in non-root\n ``conftest.py`` files is deprecated. See\n :ref:`full explanation `\n in the Writing plugins section.\n\n.. note::\n The name ``pytest_plugins`` is reserved and should not be used as a\n name for a custom plugin module.\n\n\n.. _`findpluginname`:\n\nFinding out which plugins are active\n------------------------------------\n\nIf you want to find out which plugins are active in your\nenvironment you can type::\n\n pytest --trace-config\n\nand will get an extended test header which shows activated plugins\nand their names. It will also print local plugins aka\n:ref:`conftest.py ` files when they are loaded.\n\n.. _`cmdunregister`:\n\nDeactivating / unregistering a plugin by name\n---------------------------------------------\n\nYou can prevent plugins from loading or unregister them::\n\n pytest -p no:NAME\n\nThis means that any subsequent try to activate/load the named\nplugin will not work.\n\nIf you want to unconditionally disable a plugin for a project, you can add\nthis option to your ``pytest.ini`` file:\n\n.. code-block:: ini\n\n [pytest]\n addopts = -p no:NAME\n\nAlternatively to disable it only in certain environments (for example in a\nCI server), you can set ``PYTEST_ADDOPTS`` environment variable to\n``-p no:name``.\n\nSee :ref:`findpluginname` for how to obtain the name of a plugin.\n\n.. _`builtin plugins`:\n"},{"id":6341,"name":"parametrize.rst","nodeType":"TextFile","path":"doc/en/example","text":"\n.. _paramexamples:\n\nParametrizing tests\n=================================================\n\n.. currentmodule:: _pytest.python\n\n``pytest`` allows to easily parametrize test functions.\nFor basic docs, see :ref:`parametrize-basics`.\n\nIn the following we provide some examples using\nthe builtin mechanisms.\n\nGenerating parameters combinations, depending on command line\n----------------------------------------------------------------------------\n\n.. regendoc:wipe\n\nLet's say we want to execute a test with different computation\nparameters and the parameter range shall be determined by a command\nline argument. Let's first write a simple (do-nothing) computation test::\n\n # content of test_compute.py\n\n def test_compute(param1):\n assert param1 < 4\n\nNow we add a test configuration like this::\n\n # content of conftest.py\n\n def pytest_addoption(parser):\n parser.addoption(\"--all\", action=\"store_true\",\n help=\"run all combinations\")\n\n def pytest_generate_tests(metafunc):\n if 'param1' in metafunc.fixturenames:\n if metafunc.config.getoption('all'):\n end = 5\n else:\n end = 2\n metafunc.parametrize(\"param1\", range(end))\n\nThis means that we only run 2 tests if we do not pass ``--all``:\n\n.. code-block:: pytest\n\n $ pytest -q test_compute.py\n .. [100%]\n 2 passed in 0.12 seconds\n\nWe run only two computations, so we see two dots.\nlet's run the full monty:\n\n.. code-block:: pytest\n\n $ pytest -q --all\n ....F [100%]\n ================================= FAILURES =================================\n _____________________________ test_compute[4] ______________________________\n\n param1 = 4\n\n def test_compute(param1):\n > assert param1 < 4\n E assert 4 < 4\n\n test_compute.py:3: AssertionError\n 1 failed, 4 passed in 0.12 seconds\n\nAs expected when running the full range of ``param1`` values\nwe'll get an error on the last one.\n\n\nDifferent options for test IDs\n------------------------------------\n\npytest will build a string that is the test ID for each set of values in a\nparametrized test. These IDs can be used with ``-k`` to select specific cases\nto run, and they will also identify the specific case when one is failing.\nRunning pytest with ``--collect-only`` will show the generated IDs.\n\nNumbers, strings, booleans and None will have their usual string representation\nused in the test ID. For other objects, pytest will make a string based on\nthe argument name::\n\n # content of test_time.py\n\n import pytest\n\n from datetime import datetime, timedelta\n\n testdata = [\n (datetime(2001, 12, 12), datetime(2001, 12, 11), timedelta(1)),\n (datetime(2001, 12, 11), datetime(2001, 12, 12), timedelta(-1)),\n ]\n\n\n @pytest.mark.parametrize(\"a,b,expected\", testdata)\n def test_timedistance_v0(a, b, expected):\n diff = a - b\n assert diff == expected\n\n\n @pytest.mark.parametrize(\"a,b,expected\", testdata, ids=[\"forward\", \"backward\"])\n def test_timedistance_v1(a, b, expected):\n diff = a - b\n assert diff == expected\n\n\n def idfn(val):\n if isinstance(val, (datetime,)):\n # note this wouldn't show any hours/minutes/seconds\n return val.strftime('%Y%m%d')\n\n\n @pytest.mark.parametrize(\"a,b,expected\", testdata, ids=idfn)\n def test_timedistance_v2(a, b, expected):\n diff = a - b\n assert diff == expected\n\n @pytest.mark.parametrize(\"a,b,expected\", [\n pytest.param(datetime(2001, 12, 12), datetime(2001, 12, 11),\n timedelta(1), id='forward'),\n pytest.param(datetime(2001, 12, 11), datetime(2001, 12, 12),\n timedelta(-1), id='backward'),\n ])\n def test_timedistance_v3(a, b, expected):\n diff = a - b\n assert diff == expected\n\nIn ``test_timedistance_v0``, we let pytest generate the test IDs.\n\nIn ``test_timedistance_v1``, we specified ``ids`` as a list of strings which were\nused as the test IDs. These are succinct, but can be a pain to maintain.\n\nIn ``test_timedistance_v2``, we specified ``ids`` as a function that can generate a\nstring representation to make part of the test ID. So our ``datetime`` values use the\nlabel generated by ``idfn``, but because we didn't generate a label for ``timedelta``\nobjects, they are still using the default pytest representation:\n\n.. code-block:: pytest\n\n $ pytest test_time.py --collect-only\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 8 items\n \n \n \n \n \n \n \n \n \n\n ======================= no tests ran in 0.12 seconds =======================\n\nIn ``test_timedistance_v3``, we used ``pytest.param`` to specify the test IDs\ntogether with the actual data, instead of listing them separately.\n\nA quick port of \"testscenarios\"\n------------------------------------\n\n.. _`test scenarios`: https://pypi.org/project/testscenarios/\n\nHere is a quick port to run tests configured with `test scenarios`_,\nan add-on from Robert Collins for the standard unittest framework. We\nonly have to work a bit to construct the correct arguments for pytest's\n:py:func:`Metafunc.parametrize`::\n\n # content of test_scenarios.py\n\n def pytest_generate_tests(metafunc):\n idlist = []\n argvalues = []\n for scenario in metafunc.cls.scenarios:\n idlist.append(scenario[0])\n items = scenario[1].items()\n argnames = [x[0] for x in items]\n argvalues.append(([x[1] for x in items]))\n metafunc.parametrize(argnames, argvalues, ids=idlist, scope=\"class\")\n\n scenario1 = ('basic', {'attribute': 'value'})\n scenario2 = ('advanced', {'attribute': 'value2'})\n\n class TestSampleWithScenarios(object):\n scenarios = [scenario1, scenario2]\n\n def test_demo1(self, attribute):\n assert isinstance(attribute, str)\n\n def test_demo2(self, attribute):\n assert isinstance(attribute, str)\n\nthis is a fully self-contained example which you can run with:\n\n.. code-block:: pytest\n\n $ pytest test_scenarios.py\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 4 items\n\n test_scenarios.py .... [100%]\n\n ========================= 4 passed in 0.12 seconds =========================\n\nIf you just collect tests you'll also nicely see 'advanced' and 'basic' as variants for the test function:\n\n.. code-block:: pytest\n\n $ pytest --collect-only test_scenarios.py\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 4 items\n \n \n \n \n \n \n\n ======================= no tests ran in 0.12 seconds =======================\n\nNote that we told ``metafunc.parametrize()`` that your scenario values\nshould be considered class-scoped. With pytest-2.3 this leads to a\nresource-based ordering.\n\nDeferring the setup of parametrized resources\n---------------------------------------------------\n\n.. regendoc:wipe\n\nThe parametrization of test functions happens at collection\ntime. It is a good idea to setup expensive resources like DB\nconnections or subprocess only when the actual test is run.\nHere is a simple example how you can achieve that, first\nthe actual test requiring a ``db`` object::\n\n # content of test_backends.py\n\n import pytest\n def test_db_initialized(db):\n # a dummy test\n if db.__class__.__name__ == \"DB2\":\n pytest.fail(\"deliberately failing for demo purposes\")\n\nWe can now add a test configuration that generates two invocations of\nthe ``test_db_initialized`` function and also implements a factory that\ncreates a database object for the actual test invocations::\n\n # content of conftest.py\n import pytest\n\n def pytest_generate_tests(metafunc):\n if 'db' in metafunc.fixturenames:\n metafunc.parametrize(\"db\", ['d1', 'd2'], indirect=True)\n\n class DB1(object):\n \"one database object\"\n class DB2(object):\n \"alternative database object\"\n\n @pytest.fixture\n def db(request):\n if request.param == \"d1\":\n return DB1()\n elif request.param == \"d2\":\n return DB2()\n else:\n raise ValueError(\"invalid internal test config\")\n\nLet's first see how it looks like at collection time:\n\n.. code-block:: pytest\n\n $ pytest test_backends.py --collect-only\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 2 items\n \n \n \n\n ======================= no tests ran in 0.12 seconds =======================\n\nAnd then when we run the test:\n\n.. code-block:: pytest\n\n $ pytest -q test_backends.py\n .F [100%]\n ================================= FAILURES =================================\n _________________________ test_db_initialized[d2] __________________________\n\n db = \n\n def test_db_initialized(db):\n # a dummy test\n if db.__class__.__name__ == \"DB2\":\n > pytest.fail(\"deliberately failing for demo purposes\")\n E Failed: deliberately failing for demo purposes\n\n test_backends.py:6: Failed\n 1 failed, 1 passed in 0.12 seconds\n\nThe first invocation with ``db == \"DB1\"`` passed while the second with ``db == \"DB2\"`` failed. Our ``db`` fixture function has instantiated each of the DB values during the setup phase while the ``pytest_generate_tests`` generated two according calls to the ``test_db_initialized`` during the collection phase.\n\n.. regendoc:wipe\n\nApply indirect on particular arguments\n---------------------------------------------------\n\nVery often parametrization uses more than one argument name. There is opportunity to apply ``indirect``\nparameter on particular arguments. It can be done by passing list or tuple of\narguments' names to ``indirect``. In the example below there is a function ``test_indirect`` which uses\ntwo fixtures: ``x`` and ``y``. Here we give to indirect the list, which contains the name of the\nfixture ``x``. The indirect parameter will be applied to this argument only, and the value ``a``\nwill be passed to respective fixture function::\n\n # content of test_indirect_list.py\n\n import pytest\n @pytest.fixture(scope='function')\n def x(request):\n return request.param * 3\n\n @pytest.fixture(scope='function')\n def y(request):\n return request.param * 2\n\n @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x'])\n def test_indirect(x,y):\n assert x == 'aaa'\n assert y == 'b'\n\nThe result of this test will be successful:\n\n.. code-block:: pytest\n\n $ pytest test_indirect_list.py --collect-only\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 1 item\n \n \n\n ======================= no tests ran in 0.12 seconds =======================\n\n.. regendoc:wipe\n\nParametrizing test methods through per-class configuration\n--------------------------------------------------------------\n\n.. _`unittest parametrizer`: https://github.com/testing-cabal/unittest-ext/blob/master/params.py\n\n\nHere is an example ``pytest_generate_tests`` function implementing a\nparametrization scheme similar to Michael Foord's `unittest\nparametrizer`_ but in a lot less code::\n\n # content of ./test_parametrize.py\n import pytest\n\n def pytest_generate_tests(metafunc):\n # called once per each test function\n funcarglist = metafunc.cls.params[metafunc.function.__name__]\n argnames = sorted(funcarglist[0])\n metafunc.parametrize(argnames, [[funcargs[name] for name in argnames]\n for funcargs in funcarglist])\n\n class TestClass(object):\n # a map specifying multiple argument sets for a test method\n params = {\n 'test_equals': [dict(a=1, b=2), dict(a=3, b=3), ],\n 'test_zerodivision': [dict(a=1, b=0), ],\n }\n\n def test_equals(self, a, b):\n assert a == b\n\n def test_zerodivision(self, a, b):\n with pytest.raises(ZeroDivisionError):\n a / b\n\nOur test generator looks up a class-level definition which specifies which\nargument sets to use for each test function. Let's run it:\n\n.. code-block:: pytest\n\n $ pytest -q\n F.. [100%]\n ================================= FAILURES =================================\n ________________________ TestClass.test_equals[1-2] ________________________\n\n self = , a = 1, b = 2\n\n def test_equals(self, a, b):\n > assert a == b\n E assert 1 == 2\n\n test_parametrize.py:18: AssertionError\n 1 failed, 2 passed in 0.12 seconds\n\nIndirect parametrization with multiple fixtures\n--------------------------------------------------------------\n\nHere is a stripped down real-life example of using parametrized\ntesting for testing serialization of objects between different python\ninterpreters. We define a ``test_basic_objects`` function which\nis to be run with different sets of arguments for its three arguments:\n\n* ``python1``: first python interpreter, run to pickle-dump an object to a file\n* ``python2``: second interpreter, run to pickle-load an object from a file\n* ``obj``: object to be dumped/loaded\n\n.. literalinclude:: multipython.py\n\nRunning it results in some skips if we don't have all the python interpreters installed and otherwise runs all combinations (5 interpreters times 5 interpreters times 3 objects to serialize/deserialize):\n\n.. code-block:: pytest\n\n . $ pytest -rs -q multipython.py\n ...ssssssssssssssssssssssss [100%]\n ========================= short test summary info ==========================\n SKIPPED [12] $REGENDOC_TMPDIR/CWD/multipython.py:31: 'python3.4' not found\n SKIPPED [12] $REGENDOC_TMPDIR/CWD/multipython.py:31: 'python3.5' not found\n 3 passed, 24 skipped in 0.12 seconds\n\nIndirect parametrization of optional implementations/imports\n--------------------------------------------------------------------\n\nIf you want to compare the outcomes of several implementations of a given\nAPI, you can write test functions that receive the already imported implementations\nand get skipped in case the implementation is not importable/available. Let's\nsay we have a \"base\" implementation and the other (possibly optimized ones)\nneed to provide similar results::\n\n # content of conftest.py\n\n import pytest\n\n @pytest.fixture(scope=\"session\")\n def basemod(request):\n return pytest.importorskip(\"base\")\n\n @pytest.fixture(scope=\"session\", params=[\"opt1\", \"opt2\"])\n def optmod(request):\n return pytest.importorskip(request.param)\n\nAnd then a base implementation of a simple function::\n\n # content of base.py\n def func1():\n return 1\n\nAnd an optimized version::\n\n # content of opt1.py\n def func1():\n return 1.0001\n\nAnd finally a little test module::\n\n # content of test_module.py\n\n def test_func1(basemod, optmod):\n assert round(basemod.func1(), 3) == round(optmod.func1(), 3)\n\n\nIf you run this with reporting for skips enabled:\n\n.. code-block:: pytest\n\n $ pytest -rs test_module.py\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 2 items\n\n test_module.py .s [100%]\n\n ========================= short test summary info ==========================\n SKIPPED [1] $REGENDOC_TMPDIR/conftest.py:11: could not import 'opt2': No module named 'opt2'\n =================== 1 passed, 1 skipped in 0.12 seconds ====================\n\nYou'll see that we don't have an ``opt2`` module and thus the second test run\nof our ``test_func1`` was skipped. A few notes:\n\n- the fixture functions in the ``conftest.py`` file are \"session-scoped\" because we\n don't need to import more than once\n\n- if you have multiple test functions and a skipped import, you will see\n the ``[1]`` count increasing in the report\n\n- you can put :ref:`@pytest.mark.parametrize <@pytest.mark.parametrize>` style\n parametrization on the test functions to parametrize input/output\n values as well.\n\n\nSet marks or test ID for individual parametrized test\n--------------------------------------------------------------------\n\nUse ``pytest.param`` to apply marks or set test ID to individual parametrized test.\nFor example:\n\n.. code-block:: python\n\n # content of test_pytest_param_example.py\n import pytest\n\n\n @pytest.mark.parametrize(\n \"test_input,expected\",\n [\n (\"3+5\", 8),\n pytest.param(\"1+7\", 8, marks=pytest.mark.basic),\n pytest.param(\"2+4\", 6, marks=pytest.mark.basic, id=\"basic_2+4\"),\n pytest.param(\n \"6*9\", 42, marks=[pytest.mark.basic, pytest.mark.xfail], id=\"basic_6*9\"\n ),\n ],\n )\n def test_eval(test_input, expected):\n assert eval(test_input) == expected\n\nIn this example, we have 4 parametrized tests. Except for the first test,\nwe mark the rest three parametrized tests with the custom marker ``basic``,\nand for the fourth test we also use the built-in mark ``xfail`` to indicate this\ntest is expected to fail. For explicitness, we set test ids for some tests.\n\nThen run ``pytest`` with verbose mode and with only the ``basic`` marker:\n\n.. code-block:: pytest\n\n $ pytest -v -m basic\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collecting ... collected 17 items / 14 deselected / 3 selected\n\n test_pytest_param_example.py::test_eval[1+7-8] PASSED [ 33%]\n test_pytest_param_example.py::test_eval[basic_2+4] PASSED [ 66%]\n test_pytest_param_example.py::test_eval[basic_6*9] XFAIL [100%]\n\n ============ 2 passed, 14 deselected, 1 xfailed in 0.12 seconds ============\n\nAs the result:\n\n- Four tests were collected\n- One test was deselected because it doesn't have the ``basic`` mark.\n- Three tests with the ``basic`` mark was selected.\n- The test ``test_eval[1+7-8]`` passed, but the name is autogenerated and confusing.\n- The test ``test_eval[basic_2+4]`` passed.\n- The test ``test_eval[basic_6*9]`` was expected to fail and did fail.\n\n.. _`parametrizing_conditional_raising`:\n\nParametrizing conditional raising\n--------------------------------------------------------------------\n\nUse :func:`pytest.raises` with the\n:ref:`pytest.mark.parametrize ref` decorator to write parametrized tests\nin which some tests raise exceptions and others do not.\n\nIt is helpful to define a no-op context manager ``does_not_raise`` to serve\nas a complement to ``raises``. For example::\n\n from contextlib import contextmanager\n import pytest\n\n @contextmanager\n def does_not_raise():\n yield\n\n\n @pytest.mark.parametrize('example_input,expectation', [\n (3, does_not_raise()),\n (2, does_not_raise()),\n (1, does_not_raise()),\n (0, pytest.raises(ZeroDivisionError)),\n ])\n def test_division(example_input, expectation):\n \"\"\"Test how much I know division.\"\"\"\n with expectation:\n assert (6 / example_input) is not None\n\nIn the example above, the first three test cases should run unexceptionally,\nwhile the fourth should raise ``ZeroDivisionError``.\n\nIf you're only supporting Python 3.7+, you can simply use ``nullcontext``\nto define ``does_not_raise``::\n\n from contextlib import nullcontext as does_not_raise\n\nOr, if you're supporting Python 3.3+ you can use::\n\n from contextlib import ExitStack as does_not_raise\n\nOr, if desired, you can ``pip install contextlib2`` and use::\n\n from contextlib2 import ExitStack as does_not_raise\n"},{"fileName":"test_detect_recursive_dependency_error.py","filePath":"testing/example_scripts/fixtures/fill_fixtures","id":6342,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\n@pytest.fixture\ndef fix1(fix2):\n return 1\n\n\n@pytest.fixture\ndef fix2(fix1):\n return 1\n\n\ndef test(fix1):\n pass\n"},{"col":0,"comment":"null","endLoc":7,"header":"@pytest.fixture\ndef fix1(fix2)","id":6343,"name":"fix1","nodeType":"Function","startLoc":5,"text":"@pytest.fixture\ndef fix1(fix2):\n return 1"},{"col":0,"comment":"null","endLoc":12,"header":"@pytest.fixture\ndef fix2(fix1)","id":6344,"name":"fix2","nodeType":"Function","startLoc":10,"text":"@pytest.fixture\ndef fix2(fix1):\n return 1"},{"col":0,"comment":"null","endLoc":16,"header":"def test(fix1)","id":6345,"name":"test","nodeType":"Function","startLoc":15,"text":"def test(fix1):\n pass"},{"col":0,"comment":"null","endLoc":786,"header":"@pytest.mark.parametrize(\"runner\", [\"pytest\", \"unittest\"])\ndef test_unittest_expected_failure_for_passing_test_is_fail(testdir, runner)","id":6346,"name":"test_unittest_expected_failure_for_passing_test_is_fail","nodeType":"Function","startLoc":758,"text":"@pytest.mark.parametrize(\"runner\", [\"pytest\", \"unittest\"])\ndef test_unittest_expected_failure_for_passing_test_is_fail(testdir, runner):\n script = testdir.makepyfile(\n \"\"\"\n import unittest\n class MyTestCase(unittest.TestCase):\n @unittest.expectedFailure\n def test_passing_test_is_fail(self):\n assert True\n if __name__ == '__main__':\n unittest.main()\n \"\"\"\n )\n from _pytest.compat import _is_unittest_unexpected_success_a_failure\n\n should_fail = _is_unittest_unexpected_success_a_failure()\n if runner == \"pytest\":\n result = testdir.runpytest(\"-rxX\")\n result.stdout.fnmatch_lines(\n [\n \"*MyTestCase*test_passing_test_is_fail*\",\n \"*1 failed*\" if should_fail else \"*1 xpassed*\",\n ]\n )\n else:\n result = testdir.runpython(script)\n result.stderr.fnmatch_lines([\"*1 test in*\", \"*(unexpected successes=1)*\"])\n\n assert result.ret == (1 if should_fail else 0)"},{"fileName":"__init__.py","filePath":"doc/en/example/nonpython","id":6347,"nodeType":"File","text":""},{"id":6348,"name":"release-4.2.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-4.2.1\n=======================================\n\npytest 4.2.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Arel Cordero\n* Bruno Oliveira\n* Daniel Hahler\n* Holger Kohr\n* Kevin J. Foley\n* Nick Murphy\n* Paweł Stradomski\n* Raphael Pierzina\n* Ronny Pfannschmidt\n* Sam Brightman\n* Thomas Hisch\n* Zac Hatfield-Dodds\n\n\nHappy testing,\nThe pytest Development Team\n"},{"fileName":"test_funcarg_basic.py","filePath":"testing/example_scripts/fixtures/fill_fixtures","id":6349,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\n@pytest.fixture\ndef some(request):\n return request.function.__name__\n\n\n@pytest.fixture\ndef other(request):\n return 42\n\n\ndef test_func(some, other):\n pass\n"},{"className":"TestDurations","col":0,"comment":"null","endLoc":961,"id":6350,"nodeType":"Class","startLoc":886,"text":"class TestDurations(object):\n source = \"\"\"\n import time\n frag = 0.002\n def test_something():\n pass\n def test_2():\n time.sleep(frag*5)\n def test_1():\n time.sleep(frag)\n def test_3():\n time.sleep(frag*10)\n \"\"\"\n\n def test_calls(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"--durations=10\")\n assert result.ret == 0\n result.stdout.fnmatch_lines_random(\n [\"*durations*\", \"*call*test_3*\", \"*call*test_2*\"]\n )\n result.stdout.fnmatch_lines(\n [\"(0.00 durations hidden. Use -vv to show these durations.)\"]\n )\n\n def test_calls_show_2(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"--durations=2\")\n assert result.ret == 0\n lines = result.stdout.get_lines_after(\"*slowest*durations*\")\n assert \"4 passed\" in lines[2]\n\n def test_calls_showall(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"--durations=0\")\n assert result.ret == 0\n for x in \"23\":\n for y in (\"call\",): # 'setup', 'call', 'teardown':\n for line in result.stdout.lines:\n if (\"test_%s\" % x) in line and y in line:\n break\n else:\n raise AssertionError(\"not found {} {}\".format(x, y))\n\n def test_calls_showall_verbose(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"--durations=0\", \"-vv\")\n assert result.ret == 0\n for x in \"123\":\n for y in (\"call\",): # 'setup', 'call', 'teardown':\n for line in result.stdout.lines:\n if (\"test_%s\" % x) in line and y in line:\n break\n else:\n raise AssertionError(\"not found {} {}\".format(x, y))\n\n def test_with_deselected(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"--durations=2\", \"-k test_2\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*durations*\", \"*call*test_2*\"])\n\n def test_with_failing_collection(self, testdir):\n testdir.makepyfile(self.source)\n testdir.makepyfile(test_collecterror=\"\"\"xyz\"\"\")\n result = testdir.runpytest(\"--durations=2\", \"-k test_1\")\n assert result.ret == 2\n result.stdout.fnmatch_lines([\"*Interrupted: 1 errors during collection*\"])\n # Collection errors abort test execution, therefore no duration is\n # output\n assert \"duration\" not in result.stdout.str()\n\n def test_with_not(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"-k not 1\")\n assert result.ret == 0"},{"col":0,"comment":"null","endLoc":7,"header":"@pytest.fixture\ndef some(request)","id":6351,"name":"some","nodeType":"Function","startLoc":5,"text":"@pytest.fixture\ndef some(request):\n return request.function.__name__"},{"col":0,"comment":"null","endLoc":12,"header":"@pytest.fixture\ndef other(request)","id":6352,"name":"other","nodeType":"Function","startLoc":10,"text":"@pytest.fixture\ndef other(request):\n return 42"},{"col":0,"comment":"null","endLoc":16,"header":"def test_func(some, other)","id":6353,"name":"test_func","nodeType":"Function","startLoc":15,"text":"def test_func(some, other):\n pass"},{"col":4,"comment":"null","endLoc":909,"header":"def test_calls(self, testdir)","id":6354,"name":"test_calls","nodeType":"Function","startLoc":900,"text":"def test_calls(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"--durations=10\")\n assert result.ret == 0\n result.stdout.fnmatch_lines_random(\n [\"*durations*\", \"*call*test_3*\", \"*call*test_2*\"]\n )\n result.stdout.fnmatch_lines(\n [\"(0.00 durations hidden. Use -vv to show these durations.)\"]\n )"},{"id":6355,"name":"release-2.6.3.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.6.3: fixes and little improvements\n===========================================================================\n\npytest is a mature Python testing tool with more than a 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is drop-in compatible to 2.5.2 and 2.6.X.\nSee below for the changes and see docs at:\n\n http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n pip install -U pytest\n\nThanks to all who contributed, among them:\n\n Floris Bruynooghe\n Oleg Sinyavskiy\n Uwe Schmitt\n Charles Cloud\n Wolfgang Schnerring\n\nhave fun,\nholger krekel\n\nChanges 2.6.3\n======================\n\n- fix issue575: xunit-xml was reporting collection errors as failures\n instead of errors, thanks Oleg Sinyavskiy.\n\n- fix issue582: fix setuptools example, thanks Laszlo Papp and Ronny\n Pfannschmidt.\n\n- Fix infinite recursion bug when pickling capture.EncodedFile, thanks\n Uwe Schmitt.\n\n- fix issue589: fix bad interaction with numpy and others when showing\n exceptions. Check for precise \"maximum recursion depth exceed\" exception\n instead of presuming any RuntimeError is that one (implemented in py\n dep). Thanks Charles Cloud for analysing the issue.\n\n- fix conftest related fixture visibility issue: when running with a\n CWD outside of a test package pytest would get fixture discovery wrong.\n Thanks to Wolfgang Schnerring for figuring out a reproducible example.\n\n- Introduce pytest_enter_pdb hook (needed e.g. by pytest_timeout to cancel the\n timeout when interactively entering pdb). Thanks Wolfgang Schnerring.\n\n- check xfail/skip also with non-python function test items. Thanks\n Floris Bruynooghe.\n"},{"col":4,"comment":"null","endLoc":916,"header":"def test_calls_show_2(self, testdir)","id":6356,"name":"test_calls_show_2","nodeType":"Function","startLoc":911,"text":"def test_calls_show_2(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"--durations=2\")\n assert result.ret == 0\n lines = result.stdout.get_lines_after(\"*slowest*durations*\")\n assert \"4 passed\" in lines[2]"},{"col":4,"comment":"null","endLoc":928,"header":"def test_calls_showall(self, testdir)","id":6357,"name":"test_calls_showall","nodeType":"Function","startLoc":918,"text":"def test_calls_showall(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"--durations=0\")\n assert result.ret == 0\n for x in \"23\":\n for y in (\"call\",): # 'setup', 'call', 'teardown':\n for line in result.stdout.lines:\n if (\"test_%s\" % x) in line and y in line:\n break\n else:\n raise AssertionError(\"not found {} {}\".format(x, y))"},{"col":0,"comment":"null","endLoc":821,"header":"@pytest.mark.parametrize(\n \"fix_type, stmt\", [(\"fixture\", \"return\"), (\"yield_fixture\", \"yield\")]\n)\ndef test_unittest_setup_interaction(testdir, fix_type, stmt)","id":6358,"name":"test_unittest_setup_interaction","nodeType":"Function","startLoc":789,"text":"@pytest.mark.parametrize(\n \"fix_type, stmt\", [(\"fixture\", \"return\"), (\"yield_fixture\", \"yield\")]\n)\ndef test_unittest_setup_interaction(testdir, fix_type, stmt):\n testdir.makepyfile(\n \"\"\"\n import unittest\n import pytest\n class MyTestCase(unittest.TestCase):\n @pytest.{fix_type}(scope=\"class\", autouse=True)\n def perclass(self, request):\n request.cls.hello = \"world\"\n {stmt}\n @pytest.{fix_type}(scope=\"function\", autouse=True)\n def perfunction(self, request):\n request.instance.funcname = request.function.__name__\n {stmt}\n\n def test_method1(self):\n assert self.funcname == \"test_method1\"\n assert self.hello == \"world\"\n\n def test_method2(self):\n assert self.funcname == \"test_method2\"\n\n def test_classattr(self):\n assert self.__class__.hello == \"world\"\n \"\"\".format(\n fix_type=fix_type, stmt=stmt\n )\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*3 passed*\"])"},{"fileName":"empty.py","filePath":"bench","id":6359,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfor i in range(1000):\n exec(\"def test_func_%d(): pass\" % i)\n"},{"attributeType":"int","col":4,"comment":"null","endLoc":2,"id":6360,"name":"i","nodeType":"Attribute","startLoc":2,"text":"i"},{"col":4,"comment":"null","endLoc":940,"header":"def test_calls_showall_verbose(self, testdir)","id":6361,"name":"test_calls_showall_verbose","nodeType":"Function","startLoc":930,"text":"def test_calls_showall_verbose(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"--durations=0\", \"-vv\")\n assert result.ret == 0\n for x in \"123\":\n for y in (\"call\",): # 'setup', 'call', 'teardown':\n for line in result.stdout.lines:\n if (\"test_%s\" % x) in line and y in line:\n break\n else:\n raise AssertionError(\"not found {} {}\".format(x, y))"},{"col":4,"comment":"null","endLoc":946,"header":"def test_with_deselected(self, testdir)","id":6362,"name":"test_with_deselected","nodeType":"Function","startLoc":942,"text":"def test_with_deselected(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"--durations=2\", \"-k test_2\")\n assert result.ret == 0\n result.stdout.fnmatch_lines([\"*durations*\", \"*call*test_2*\"])"},{"col":0,"comment":"null","endLoc":847,"header":"def test_non_unittest_no_setupclass_support(testdir)","id":6363,"name":"test_non_unittest_no_setupclass_support","nodeType":"Function","startLoc":824,"text":"def test_non_unittest_no_setupclass_support(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n class TestFoo(object):\n x = 0\n\n @classmethod\n def setUpClass(cls):\n cls.x = 1\n\n def test_method1(self):\n assert self.x == 0\n\n @classmethod\n def tearDownClass(cls):\n cls.x = 1\n\n def test_not_teareddown():\n assert TestFoo.x == 0\n\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n reprec.assertoutcome(passed=2)"},{"col":0,"comment":"null","endLoc":875,"header":"def test_no_teardown_if_setupclass_failed(testdir)","id":6364,"name":"test_no_teardown_if_setupclass_failed","nodeType":"Function","startLoc":850,"text":"def test_no_teardown_if_setupclass_failed(testdir):\n testpath = testdir.makepyfile(\n \"\"\"\n import unittest\n\n class MyTestCase(unittest.TestCase):\n x = 0\n\n @classmethod\n def setUpClass(cls):\n cls.x = 1\n assert False\n\n def test_func1(self):\n cls.x = 10\n\n @classmethod\n def tearDownClass(cls):\n cls.x = 100\n\n def test_notTornDown():\n assert MyTestCase.x == 1\n \"\"\"\n )\n reprec = testdir.inline_run(testpath)\n reprec.assertoutcome(passed=1, failed=1)"},{"col":0,"comment":"null","endLoc":898,"header":"def test_issue333_result_clearing(testdir)","id":6365,"name":"test_issue333_result_clearing","nodeType":"Function","startLoc":878,"text":"def test_issue333_result_clearing(testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_call(item):\n yield\n assert 0\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import unittest\n class TestIt(unittest.TestCase):\n def test_func(self):\n 0/0\n \"\"\"\n )\n\n reprec = testdir.inline_run()\n reprec.assertoutcome(failed=1)"},{"col":4,"comment":"Create a new :py:class:`HookRecorder` for a PluginManager.","endLoc":547,"header":"def make_hook_recorder(self, pluginmanager)","id":6366,"name":"make_hook_recorder","nodeType":"Function","startLoc":543,"text":"def make_hook_recorder(self, pluginmanager):\n \"\"\"Create a new :py:class:`HookRecorder` for a PluginManager.\"\"\"\n pluginmanager.reprec = reprec = HookRecorder(pluginmanager)\n self.request.addfinalizer(reprec.finish_recording)\n return reprec"},{"col":0,"comment":"null","endLoc":917,"header":"def test_unittest_raise_skip_issue748(testdir)","id":6367,"name":"test_unittest_raise_skip_issue748","nodeType":"Function","startLoc":901,"text":"def test_unittest_raise_skip_issue748(testdir):\n testdir.makepyfile(\n test_foo=\"\"\"\n import unittest\n\n class MyTestCase(unittest.TestCase):\n def test_one(self):\n raise unittest.SkipTest('skipping due to reasons')\n \"\"\"\n )\n result = testdir.runpytest(\"-v\", \"-rs\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *SKIP*[1]*test_foo.py*skipping due to reasons*\n *1 skipped*\n \"\"\"\n )"},{"col":4,"comment":"null","endLoc":956,"header":"def test_with_failing_collection(self, testdir)","id":6368,"name":"test_with_failing_collection","nodeType":"Function","startLoc":948,"text":"def test_with_failing_collection(self, testdir):\n testdir.makepyfile(self.source)\n testdir.makepyfile(test_collecterror=\"\"\"xyz\"\"\")\n result = testdir.runpytest(\"--durations=2\", \"-k test_1\")\n assert result.ret == 2\n result.stdout.fnmatch_lines([\"*Interrupted: 1 errors during collection*\"])\n # Collection errors abort test execution, therefore no duration is\n # output\n assert \"duration\" not in result.stdout.str()"},{"col":0,"comment":"null","endLoc":937,"header":"def test_unittest_skip_issue1169(testdir)","id":6369,"name":"test_unittest_skip_issue1169","nodeType":"Function","startLoc":920,"text":"def test_unittest_skip_issue1169(testdir):\n testdir.makepyfile(\n test_foo=\"\"\"\n import unittest\n\n class MyTestCase(unittest.TestCase):\n @unittest.skip(\"skipping due to reasons\")\n def test_skip(self):\n self.fail()\n \"\"\"\n )\n result = testdir.runpytest(\"-v\", \"-rs\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *SKIP*[1]*skipping due to reasons*\n *1 skipped*\n \"\"\"\n )"},{"col":0,"comment":"null","endLoc":954,"header":"def test_class_method_containing_test_issue1558(testdir)","id":6370,"name":"test_class_method_containing_test_issue1558","nodeType":"Function","startLoc":940,"text":"def test_class_method_containing_test_issue1558(testdir):\n testdir.makepyfile(\n test_foo=\"\"\"\n import unittest\n\n class MyTestCase(unittest.TestCase):\n def test_should_run(self):\n pass\n def test_should_not_run(self):\n pass\n test_should_not_run.__test__ = False\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":0,"comment":"#3498","endLoc":1019,"header":"@pytest.mark.parametrize(\n \"base\", [\"six.moves.builtins.object\", \"unittest.TestCase\", \"unittest2.TestCase\"]\n)\ndef test_usefixtures_marker_on_unittest(base, testdir)","id":6371,"name":"test_usefixtures_marker_on_unittest","nodeType":"Function","startLoc":957,"text":"@pytest.mark.parametrize(\n \"base\", [\"six.moves.builtins.object\", \"unittest.TestCase\", \"unittest2.TestCase\"]\n)\ndef test_usefixtures_marker_on_unittest(base, testdir):\n \"\"\"#3498\"\"\"\n module = base.rsplit(\".\", 1)[0]\n pytest.importorskip(module)\n testdir.makepyfile(\n conftest=\"\"\"\n import pytest\n\n @pytest.fixture(scope='function')\n def fixture1(request, monkeypatch):\n monkeypatch.setattr(request.instance, 'fixture1', True )\n\n\n @pytest.fixture(scope='function')\n def fixture2(request, monkeypatch):\n monkeypatch.setattr(request.instance, 'fixture2', True )\n\n def node_and_marks(item):\n print(item.nodeid)\n for mark in item.iter_markers():\n print(\" \", mark)\n\n @pytest.fixture(autouse=True)\n def my_marks(request):\n node_and_marks(request.node)\n\n def pytest_collection_modifyitems(items):\n for item in items:\n node_and_marks(item)\n\n \"\"\"\n )\n\n testdir.makepyfile(\n \"\"\"\n import pytest\n import {module}\n\n class Tests({base}):\n fixture1 = False\n fixture2 = False\n\n @pytest.mark.usefixtures(\"fixture1\")\n def test_one(self):\n assert self.fixture1\n assert not self.fixture2\n\n @pytest.mark.usefixtures(\"fixture1\", \"fixture2\")\n def test_two(self):\n assert self.fixture1\n assert self.fixture2\n\n\n \"\"\".format(\n module=module, base=base\n )\n )\n\n result = testdir.runpytest(\"-s\")\n result.assert_outcomes(passed=2)"},{"col":4,"comment":"null","endLoc":961,"header":"def test_with_not(self, testdir)","id":6372,"name":"test_with_not","nodeType":"Function","startLoc":958,"text":"def test_with_not(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"-k not 1\")\n assert result.ret == 0"},{"fileName":"raises.py","filePath":"testing/python","id":6373,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport sys\n\nimport six\n\nimport pytest\nfrom _pytest.compat import dummy_context_manager\nfrom _pytest.outcomes import Failed\nfrom _pytest.warning_types import PytestDeprecationWarning\n\n\nclass TestRaises(object):\n def test_raises(self):\n source = \"int('qwe')\"\n with pytest.warns(PytestDeprecationWarning):\n excinfo = pytest.raises(ValueError, source)\n code = excinfo.traceback[-1].frame.code\n s = str(code.fullsource)\n assert s == source\n\n def test_raises_exec(self):\n with pytest.warns(PytestDeprecationWarning) as warninfo:\n pytest.raises(ValueError, \"a,x = []\")\n assert warninfo[0].filename == __file__\n\n def test_raises_exec_correct_filename(self):\n with pytest.warns(PytestDeprecationWarning):\n excinfo = pytest.raises(ValueError, 'int(\"s\")')\n assert __file__ in excinfo.traceback[-1].path\n\n def test_raises_syntax_error(self):\n with pytest.warns(PytestDeprecationWarning) as warninfo:\n pytest.raises(SyntaxError, \"qwe qwe qwe\")\n assert warninfo[0].filename == __file__\n\n def test_raises_function(self):\n pytest.raises(ValueError, int, \"hello\")\n\n def test_raises_callable_no_exception(self):\n class A(object):\n def __call__(self):\n pass\n\n try:\n pytest.raises(ValueError, A())\n except pytest.raises.Exception:\n pass\n\n def test_raises_falsey_type_error(self):\n with pytest.raises(TypeError):\n with pytest.raises(AssertionError, match=0):\n raise AssertionError(\"ohai\")\n\n def test_raises_repr_inflight(self):\n \"\"\"Ensure repr() on an exception info inside a pytest.raises with block works (#4386)\"\"\"\n\n class E(Exception):\n pass\n\n with pytest.raises(E) as excinfo:\n # this test prints the inflight uninitialized object\n # using repr and str as well as pprint to demonstrate\n # it works\n print(str(excinfo))\n print(repr(excinfo))\n import pprint\n\n pprint.pprint(excinfo)\n raise E()\n\n def test_raises_as_contextmanager(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n import _pytest._code\n\n def test_simple():\n with pytest.raises(ZeroDivisionError) as excinfo:\n assert isinstance(excinfo, _pytest._code.ExceptionInfo)\n 1/0\n print(excinfo)\n assert excinfo.type == ZeroDivisionError\n assert isinstance(excinfo.value, ZeroDivisionError)\n\n def test_noraise():\n with pytest.raises(pytest.raises.Exception):\n with pytest.raises(ValueError):\n int()\n\n def test_raise_wrong_exception_passes_by():\n with pytest.raises(ZeroDivisionError):\n with pytest.raises(ValueError):\n 1/0\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n\n def test_does_not_raise(self, testdir):\n testdir.makepyfile(\n \"\"\"\n from contextlib import contextmanager\n import pytest\n\n @contextmanager\n def does_not_raise():\n yield\n\n @pytest.mark.parametrize('example_input,expectation', [\n (3, does_not_raise()),\n (2, does_not_raise()),\n (1, does_not_raise()),\n (0, pytest.raises(ZeroDivisionError)),\n ])\n def test_division(example_input, expectation):\n '''Test how much I know division.'''\n with expectation:\n assert (6 / example_input) is not None\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*4 passed*\"])\n\n def test_does_not_raise_does_raise(self, testdir):\n testdir.makepyfile(\n \"\"\"\n from contextlib import contextmanager\n import pytest\n\n @contextmanager\n def does_not_raise():\n yield\n\n @pytest.mark.parametrize('example_input,expectation', [\n (0, does_not_raise()),\n (1, pytest.raises(ZeroDivisionError)),\n ])\n def test_division(example_input, expectation):\n '''Test how much I know division.'''\n with expectation:\n assert (6 / example_input) is not None\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 failed*\"])\n\n def test_noclass(self):\n with pytest.raises(TypeError):\n pytest.raises(\"wrong\", lambda: None)\n\n def test_invalid_arguments_to_raises(self):\n with pytest.raises(TypeError, match=\"unknown\"):\n with pytest.raises(TypeError, unknown=\"bogus\"):\n raise ValueError()\n\n def test_tuple(self):\n with pytest.raises((KeyError, ValueError)):\n raise KeyError(\"oops\")\n\n def test_no_raise_message(self):\n try:\n pytest.raises(ValueError, int, \"0\")\n except pytest.raises.Exception as e:\n assert e.msg == \"DID NOT RAISE {}\".format(repr(ValueError))\n else:\n assert False, \"Expected pytest.raises.Exception\"\n\n try:\n with pytest.raises(ValueError):\n pass\n except pytest.raises.Exception as e:\n assert e.msg == \"DID NOT RAISE {}\".format(repr(ValueError))\n else:\n assert False, \"Expected pytest.raises.Exception\"\n\n def test_custom_raise_message(self):\n message = \"TEST_MESSAGE\"\n try:\n with pytest.warns(PytestDeprecationWarning):\n with pytest.raises(ValueError, message=message):\n pass\n except pytest.raises.Exception as e:\n assert e.msg == message\n else:\n assert False, \"Expected pytest.raises.Exception\"\n\n @pytest.mark.parametrize(\"method\", [\"function\", \"with\"])\n def test_raises_cyclic_reference(self, method):\n \"\"\"\n Ensure pytest.raises does not leave a reference cycle (#1965).\n \"\"\"\n import gc\n\n class T(object):\n def __call__(self):\n raise ValueError\n\n t = T()\n if method == \"function\":\n pytest.raises(ValueError, t)\n else:\n with pytest.raises(ValueError):\n t()\n\n # ensure both forms of pytest.raises don't leave exceptions in sys.exc_info()\n assert sys.exc_info() == (None, None, None)\n\n del t\n\n # ensure the t instance is not stuck in a cyclic reference\n for o in gc.get_objects():\n assert type(o) is not T\n\n def test_raises_match(self):\n msg = r\"with base \\d+\"\n with pytest.raises(ValueError, match=msg):\n int(\"asdf\")\n\n msg = \"with base 10\"\n with pytest.raises(ValueError, match=msg):\n int(\"asdf\")\n\n msg = \"with base 16\"\n expr = r\"Pattern '{}' not found in \\\"invalid literal for int\\(\\) with base 10: 'asdf'\\\"\".format(\n msg\n )\n with pytest.raises(AssertionError, match=expr):\n with pytest.raises(ValueError, match=msg):\n int(\"asdf\", base=10)\n\n def test_raises_match_wrong_type(self):\n \"\"\"Raising an exception with the wrong type and match= given.\n\n pytest should throw the unexpected exception - the pattern match is not\n really relevant if we got a different exception.\n \"\"\"\n with pytest.raises(ValueError):\n with pytest.raises(IndexError, match=\"nomatch\"):\n int(\"asdf\")\n\n def test_raises_exception_looks_iterable(self):\n from six import add_metaclass\n\n class Meta(type(object)):\n def __getitem__(self, item):\n return 1 / 0\n\n def __len__(self):\n return 1\n\n @add_metaclass(Meta)\n class ClassLooksIterableException(Exception):\n pass\n\n with pytest.raises(\n Failed,\n match=r\"DID NOT RAISE \",\n ):\n pytest.raises(ClassLooksIterableException, lambda: None)\n\n def test_raises_with_raising_dunder_class(self):\n \"\"\"Test current behavior with regard to exceptions via __class__ (#4284).\"\"\"\n\n class CrappyClass(Exception):\n @property\n def __class__(self):\n assert False, \"via __class__\"\n\n if six.PY2:\n with pytest.raises(pytest.fail.Exception) as excinfo:\n with pytest.raises(CrappyClass()):\n pass\n assert \"DID NOT RAISE\" in excinfo.value.args[0]\n\n with pytest.raises(CrappyClass) as excinfo:\n raise CrappyClass()\n else:\n with pytest.raises(AssertionError) as excinfo:\n with pytest.raises(CrappyClass()):\n pass\n assert \"via __class__\" in excinfo.value.args[0]\n\n\nclass TestUnicodeHandling:\n \"\"\"Test various combinations of bytes and unicode with pytest.raises (#5478)\n\n https://github.com/pytest-dev/pytest/pull/5479#discussion_r298852433\n \"\"\"\n\n success = dummy_context_manager\n py2_only = pytest.mark.skipif(\n not six.PY2, reason=\"bytes in raises only supported in Python 2\"\n )\n\n @pytest.mark.parametrize(\n \"message, match, expectation\",\n [\n (u\"\\u2603\", u\"\\u2603\", success()),\n (u\"\\u2603\", u\"\\u2603foo\", pytest.raises(AssertionError)),\n pytest.param(b\"hello\", b\"hello\", success(), marks=py2_only),\n pytest.param(\n b\"hello\", b\"world\", pytest.raises(AssertionError), marks=py2_only\n ),\n pytest.param(u\"hello\", b\"hello\", success(), marks=py2_only),\n pytest.param(\n u\"hello\", b\"world\", pytest.raises(AssertionError), marks=py2_only\n ),\n pytest.param(\n u\"😊\".encode(\"UTF-8\"),\n b\"world\",\n pytest.raises(AssertionError),\n marks=py2_only,\n ),\n pytest.param(\n u\"world\",\n u\"😊\".encode(\"UTF-8\"),\n pytest.raises(AssertionError),\n marks=py2_only,\n ),\n ],\n )\n def test_handling(self, message, match, expectation):\n with expectation:\n with pytest.raises(RuntimeError, match=match):\n raise RuntimeError(message)\n"},{"col":4,"comment":"null","endLoc":577,"header":"def _makefile(self, ext, args, kwargs, encoding=\"utf-8\")","id":6374,"name":"_makefile","nodeType":"Function","startLoc":557,"text":"def _makefile(self, ext, args, kwargs, encoding=\"utf-8\"):\n items = list(kwargs.items())\n\n def to_text(s):\n return s.decode(encoding) if isinstance(s, bytes) else six.text_type(s)\n\n if args:\n source = u\"\\n\".join(to_text(x) for x in args)\n basename = self.request.function.__name__\n items.insert(0, (basename, source))\n\n ret = None\n for basename, value in items:\n p = self.tmpdir.join(basename).new(ext=ext)\n p.dirpath().ensure_dir()\n source = Source(value)\n source = u\"\\n\".join(to_text(line) for line in source.lines)\n p.write(source.strip().encode(encoding), \"wb\")\n if ret is None:\n ret = p\n return ret"},{"className":"TestRaises","col":0,"comment":"null","endLoc":281,"id":6375,"nodeType":"Class","startLoc":12,"text":"class TestRaises(object):\n def test_raises(self):\n source = \"int('qwe')\"\n with pytest.warns(PytestDeprecationWarning):\n excinfo = pytest.raises(ValueError, source)\n code = excinfo.traceback[-1].frame.code\n s = str(code.fullsource)\n assert s == source\n\n def test_raises_exec(self):\n with pytest.warns(PytestDeprecationWarning) as warninfo:\n pytest.raises(ValueError, \"a,x = []\")\n assert warninfo[0].filename == __file__\n\n def test_raises_exec_correct_filename(self):\n with pytest.warns(PytestDeprecationWarning):\n excinfo = pytest.raises(ValueError, 'int(\"s\")')\n assert __file__ in excinfo.traceback[-1].path\n\n def test_raises_syntax_error(self):\n with pytest.warns(PytestDeprecationWarning) as warninfo:\n pytest.raises(SyntaxError, \"qwe qwe qwe\")\n assert warninfo[0].filename == __file__\n\n def test_raises_function(self):\n pytest.raises(ValueError, int, \"hello\")\n\n def test_raises_callable_no_exception(self):\n class A(object):\n def __call__(self):\n pass\n\n try:\n pytest.raises(ValueError, A())\n except pytest.raises.Exception:\n pass\n\n def test_raises_falsey_type_error(self):\n with pytest.raises(TypeError):\n with pytest.raises(AssertionError, match=0):\n raise AssertionError(\"ohai\")\n\n def test_raises_repr_inflight(self):\n \"\"\"Ensure repr() on an exception info inside a pytest.raises with block works (#4386)\"\"\"\n\n class E(Exception):\n pass\n\n with pytest.raises(E) as excinfo:\n # this test prints the inflight uninitialized object\n # using repr and str as well as pprint to demonstrate\n # it works\n print(str(excinfo))\n print(repr(excinfo))\n import pprint\n\n pprint.pprint(excinfo)\n raise E()\n\n def test_raises_as_contextmanager(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n import _pytest._code\n\n def test_simple():\n with pytest.raises(ZeroDivisionError) as excinfo:\n assert isinstance(excinfo, _pytest._code.ExceptionInfo)\n 1/0\n print(excinfo)\n assert excinfo.type == ZeroDivisionError\n assert isinstance(excinfo.value, ZeroDivisionError)\n\n def test_noraise():\n with pytest.raises(pytest.raises.Exception):\n with pytest.raises(ValueError):\n int()\n\n def test_raise_wrong_exception_passes_by():\n with pytest.raises(ZeroDivisionError):\n with pytest.raises(ValueError):\n 1/0\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*3 passed*\"])\n\n def test_does_not_raise(self, testdir):\n testdir.makepyfile(\n \"\"\"\n from contextlib import contextmanager\n import pytest\n\n @contextmanager\n def does_not_raise():\n yield\n\n @pytest.mark.parametrize('example_input,expectation', [\n (3, does_not_raise()),\n (2, does_not_raise()),\n (1, does_not_raise()),\n (0, pytest.raises(ZeroDivisionError)),\n ])\n def test_division(example_input, expectation):\n '''Test how much I know division.'''\n with expectation:\n assert (6 / example_input) is not None\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*4 passed*\"])\n\n def test_does_not_raise_does_raise(self, testdir):\n testdir.makepyfile(\n \"\"\"\n from contextlib import contextmanager\n import pytest\n\n @contextmanager\n def does_not_raise():\n yield\n\n @pytest.mark.parametrize('example_input,expectation', [\n (0, does_not_raise()),\n (1, pytest.raises(ZeroDivisionError)),\n ])\n def test_division(example_input, expectation):\n '''Test how much I know division.'''\n with expectation:\n assert (6 / example_input) is not None\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 failed*\"])\n\n def test_noclass(self):\n with pytest.raises(TypeError):\n pytest.raises(\"wrong\", lambda: None)\n\n def test_invalid_arguments_to_raises(self):\n with pytest.raises(TypeError, match=\"unknown\"):\n with pytest.raises(TypeError, unknown=\"bogus\"):\n raise ValueError()\n\n def test_tuple(self):\n with pytest.raises((KeyError, ValueError)):\n raise KeyError(\"oops\")\n\n def test_no_raise_message(self):\n try:\n pytest.raises(ValueError, int, \"0\")\n except pytest.raises.Exception as e:\n assert e.msg == \"DID NOT RAISE {}\".format(repr(ValueError))\n else:\n assert False, \"Expected pytest.raises.Exception\"\n\n try:\n with pytest.raises(ValueError):\n pass\n except pytest.raises.Exception as e:\n assert e.msg == \"DID NOT RAISE {}\".format(repr(ValueError))\n else:\n assert False, \"Expected pytest.raises.Exception\"\n\n def test_custom_raise_message(self):\n message = \"TEST_MESSAGE\"\n try:\n with pytest.warns(PytestDeprecationWarning):\n with pytest.raises(ValueError, message=message):\n pass\n except pytest.raises.Exception as e:\n assert e.msg == message\n else:\n assert False, \"Expected pytest.raises.Exception\"\n\n @pytest.mark.parametrize(\"method\", [\"function\", \"with\"])\n def test_raises_cyclic_reference(self, method):\n \"\"\"\n Ensure pytest.raises does not leave a reference cycle (#1965).\n \"\"\"\n import gc\n\n class T(object):\n def __call__(self):\n raise ValueError\n\n t = T()\n if method == \"function\":\n pytest.raises(ValueError, t)\n else:\n with pytest.raises(ValueError):\n t()\n\n # ensure both forms of pytest.raises don't leave exceptions in sys.exc_info()\n assert sys.exc_info() == (None, None, None)\n\n del t\n\n # ensure the t instance is not stuck in a cyclic reference\n for o in gc.get_objects():\n assert type(o) is not T\n\n def test_raises_match(self):\n msg = r\"with base \\d+\"\n with pytest.raises(ValueError, match=msg):\n int(\"asdf\")\n\n msg = \"with base 10\"\n with pytest.raises(ValueError, match=msg):\n int(\"asdf\")\n\n msg = \"with base 16\"\n expr = r\"Pattern '{}' not found in \\\"invalid literal for int\\(\\) with base 10: 'asdf'\\\"\".format(\n msg\n )\n with pytest.raises(AssertionError, match=expr):\n with pytest.raises(ValueError, match=msg):\n int(\"asdf\", base=10)\n\n def test_raises_match_wrong_type(self):\n \"\"\"Raising an exception with the wrong type and match= given.\n\n pytest should throw the unexpected exception - the pattern match is not\n really relevant if we got a different exception.\n \"\"\"\n with pytest.raises(ValueError):\n with pytest.raises(IndexError, match=\"nomatch\"):\n int(\"asdf\")\n\n def test_raises_exception_looks_iterable(self):\n from six import add_metaclass\n\n class Meta(type(object)):\n def __getitem__(self, item):\n return 1 / 0\n\n def __len__(self):\n return 1\n\n @add_metaclass(Meta)\n class ClassLooksIterableException(Exception):\n pass\n\n with pytest.raises(\n Failed,\n match=r\"DID NOT RAISE \",\n ):\n pytest.raises(ClassLooksIterableException, lambda: None)\n\n def test_raises_with_raising_dunder_class(self):\n \"\"\"Test current behavior with regard to exceptions via __class__ (#4284).\"\"\"\n\n class CrappyClass(Exception):\n @property\n def __class__(self):\n assert False, \"via __class__\"\n\n if six.PY2:\n with pytest.raises(pytest.fail.Exception) as excinfo:\n with pytest.raises(CrappyClass()):\n pass\n assert \"DID NOT RAISE\" in excinfo.value.args[0]\n\n with pytest.raises(CrappyClass) as excinfo:\n raise CrappyClass()\n else:\n with pytest.raises(AssertionError) as excinfo:\n with pytest.raises(CrappyClass()):\n pass\n assert \"via __class__\" in excinfo.value.args[0]"},{"attributeType":"str","col":4,"comment":"null","endLoc":887,"id":6376,"name":"source","nodeType":"Attribute","startLoc":887,"text":"source"},{"className":"TestDurationWithFixture","col":0,"comment":"null","endLoc":989,"id":6377,"nodeType":"Class","startLoc":964,"text":"class TestDurationWithFixture(object):\n source = \"\"\"\n import pytest\n import time\n frag = 0.01\n\n @pytest.fixture\n def setup_fixt():\n time.sleep(frag)\n\n def test_1(setup_fixt):\n time.sleep(frag)\n \"\"\"\n\n def test_setup_function(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"--durations=10\")\n assert result.ret == 0\n\n result.stdout.fnmatch_lines_random(\n \"\"\"\n *durations*\n * setup *test_1*\n * call *test_1*\n \"\"\"\n )"},{"col":4,"comment":"null","endLoc":19,"header":"def test_raises(self)","id":6378,"name":"test_raises","nodeType":"Function","startLoc":13,"text":"def test_raises(self):\n source = \"int('qwe')\"\n with pytest.warns(PytestDeprecationWarning):\n excinfo = pytest.raises(ValueError, source)\n code = excinfo.traceback[-1].frame.code\n s = str(code.fullsource)\n assert s == source"},{"col":4,"comment":"null","endLoc":989,"header":"def test_setup_function(self, testdir)","id":6379,"name":"test_setup_function","nodeType":"Function","startLoc":978,"text":"def test_setup_function(self, testdir):\n testdir.makepyfile(self.source)\n result = testdir.runpytest(\"--durations=10\")\n assert result.ret == 0\n\n result.stdout.fnmatch_lines_random(\n \"\"\"\n *durations*\n * setup *test_1*\n * call *test_1*\n \"\"\"\n )"},{"attributeType":"str","col":4,"comment":"null","endLoc":965,"id":6380,"name":"source","nodeType":"Attribute","startLoc":965,"text":"source"},{"col":0,"comment":"Test package loader is being used correctly (see #1837).","endLoc":1010,"header":"def test_zipimport_hook(testdir, tmpdir)","id":6381,"name":"test_zipimport_hook","nodeType":"Function","startLoc":992,"text":"def test_zipimport_hook(testdir, tmpdir):\n \"\"\"Test package loader is being used correctly (see #1837).\"\"\"\n zipapp = pytest.importorskip(\"zipapp\")\n testdir.tmpdir.join(\"app\").ensure(dir=1)\n testdir.makepyfile(\n **{\n \"app/foo.py\": \"\"\"\n import pytest\n def main():\n pytest.main(['--pyarg', 'foo'])\n \"\"\"\n }\n )\n target = tmpdir.join(\"foo.zip\")\n zipapp.create_archive(str(testdir.tmpdir.join(\"app\")), str(target), main=\"foo:main\")\n result = testdir.runpython(target)\n assert result.ret == 0\n result.stderr.fnmatch_lines([\"*not found*foo*\"])\n assert \"INTERNALERROR>\" not in result.stdout.str()"},{"col":0,"comment":"null","endLoc":925,"header":"def test_collection_live_logging(testdir)","id":6383,"name":"test_collection_live_logging","nodeType":"Function","startLoc":913,"text":"def test_collection_live_logging(testdir):\n testdir.makepyfile(\n \"\"\"\n import logging\n\n logging.getLogger().info(\"Normal message\")\n \"\"\"\n )\n\n result = testdir.runpytest(\"--log-cli-level=INFO\")\n result.stdout.fnmatch_lines(\n [\"*--- live log collection ---*\", \"*Normal message*\", \"collected 0 items\"]\n )"},{"col":0,"comment":"null","endLoc":961,"header":"@pytest.mark.parametrize(\"verbose\", [\"\", \"-q\", \"-qq\"])\ndef test_collection_collect_only_live_logging(testdir, verbose)","id":6384,"name":"test_collection_collect_only_live_logging","nodeType":"Function","startLoc":928,"text":"@pytest.mark.parametrize(\"verbose\", [\"\", \"-q\", \"-qq\"])\ndef test_collection_collect_only_live_logging(testdir, verbose):\n testdir.makepyfile(\n \"\"\"\n def test_simple():\n pass\n \"\"\"\n )\n\n result = testdir.runpytest(\"--collect-only\", \"--log-cli-level=INFO\", verbose)\n\n expected_lines = []\n\n if not verbose:\n expected_lines.extend(\n [\n \"*collected 1 item*\",\n \"**\",\n \"*no tests ran*\",\n ]\n )\n elif verbose == \"-q\":\n assert \"collected 1 item*\" not in result.stdout.str()\n expected_lines.extend(\n [\n \"*test_collection_collect_only_live_logging.py::test_simple*\",\n \"no tests ran in * seconds\",\n ]\n )\n elif verbose == \"-qq\":\n assert \"collected 1 item*\" not in result.stdout.str()\n expected_lines.extend([\"*test_collection_collect_only_live_logging.py: 1*\"])\n\n result.stdout.fnmatch_lines(expected_lines)"},{"col":4,"comment":"Give *expr* a name.","endLoc":730,"header":"def assign(self, expr)","id":6385,"name":"assign","nodeType":"Function","startLoc":726,"text":"def assign(self, expr):\n \"\"\"Give *expr* a name.\"\"\"\n name = self.variable()\n self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr))\n return ast.Name(name, ast.Load())"},{"col":0,"comment":"null","endLoc":1026,"header":"def test_import_plugin_unicode_name(testdir)","id":6386,"name":"test_import_plugin_unicode_name","nodeType":"Function","startLoc":1013,"text":"def test_import_plugin_unicode_name(testdir):\n testdir.makepyfile(myplugin=\"\")\n testdir.makepyfile(\n \"\"\"\n def test(): pass\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n pytest_plugins = [u'myplugin']\n \"\"\"\n )\n r = testdir.runpytest()\n assert r.ret == 0"},{"col":0,"comment":"Do not raise an error if pytest_plugins attribute is a module (#3899)","endLoc":1040,"header":"def test_pytest_plugins_as_module(testdir)","id":6387,"name":"test_pytest_plugins_as_module","nodeType":"Function","startLoc":1029,"text":"def test_pytest_plugins_as_module(testdir):\n \"\"\"Do not raise an error if pytest_plugins attribute is a module (#3899)\"\"\"\n testdir.makepyfile(\n **{\n \"__init__.py\": \"\",\n \"pytest_plugins.py\": \"\",\n \"conftest.py\": \"from . import pytest_plugins\",\n \"test_foo.py\": \"def test(): pass\",\n }\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 passed in *\"])"},{"col":0,"comment":"\n Check hooks as late as possible (#1821).\n ","endLoc":1070,"header":"def test_deferred_hook_checking(testdir)","id":6388,"name":"test_deferred_hook_checking","nodeType":"Function","startLoc":1043,"text":"def test_deferred_hook_checking(testdir):\n \"\"\"\n Check hooks as late as possible (#1821).\n \"\"\"\n testdir.syspathinsert()\n testdir.makepyfile(\n **{\n \"plugin.py\": \"\"\"\n class Hooks(object):\n def pytest_my_hook(self, config):\n pass\n\n def pytest_configure(config):\n config.pluginmanager.add_hookspecs(Hooks)\n \"\"\",\n \"conftest.py\": \"\"\"\n pytest_plugins = ['plugin']\n def pytest_my_hook(config):\n return 40\n \"\"\",\n \"test_foo.py\": \"\"\"\n def test(request):\n assert request.config.hook.pytest_my_hook(config=request.config) == [40]\n \"\"\",\n }\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 passed *\"])"},{"col":0,"comment":"Ensure that fixture objects are properly destroyed by the garbage collector at the end of their expected\n life-times (#2981).\n ","endLoc":1115,"header":"def test_fixture_values_leak(testdir)","id":6389,"name":"test_fixture_values_leak","nodeType":"Function","startLoc":1073,"text":"def test_fixture_values_leak(testdir):\n \"\"\"Ensure that fixture objects are properly destroyed by the garbage collector at the end of their expected\n life-times (#2981).\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import attr\n import gc\n import pytest\n import weakref\n\n @attr.s\n class SomeObj(object):\n name = attr.ib()\n\n fix_of_test1_ref = None\n session_ref = None\n\n @pytest.fixture(scope='session')\n def session_fix():\n global session_ref\n obj = SomeObj(name='session-fixture')\n session_ref = weakref.ref(obj)\n return obj\n\n @pytest.fixture\n def fix(session_fix):\n global fix_of_test1_ref\n obj = SomeObj(name='local-fixture')\n fix_of_test1_ref = weakref.ref(obj)\n return obj\n\n def test1(fix):\n assert fix_of_test1_ref() is fix\n\n def test2():\n gc.collect()\n # fixture \"fix\" created during test1 must have been destroyed by now\n assert fix_of_test1_ref() is None\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 2 passed *\"])"},{"col":0,"comment":"Ensure that fixtures are created according to scope order, regression test for #2405\n ","endLoc":1141,"header":"def test_fixture_order_respects_scope(testdir)","id":6390,"name":"test_fixture_order_respects_scope","nodeType":"Function","startLoc":1118,"text":"def test_fixture_order_respects_scope(testdir):\n \"\"\"Ensure that fixtures are created according to scope order, regression test for #2405\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n data = {}\n\n @pytest.fixture(scope='module')\n def clean_data():\n data.clear()\n\n @pytest.fixture(autouse=True)\n def add_data():\n data.update(value=True)\n\n @pytest.mark.usefixtures('clean_data')\n def test_value():\n assert data.get('value')\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 0"},{"col":0,"comment":"pytest would leak garbage referencing the frames of tests that failed that could never be reclaimed (#2798)\n\n Unfortunately it was not possible to remove the actual circles because most of them\n are made of traceback objects which cannot be weakly referenced. Those objects at least\n can be eventually claimed by the garbage collector.\n ","endLoc":1173,"header":"def test_frame_leak_on_failing_test(testdir)","id":6391,"name":"test_frame_leak_on_failing_test","nodeType":"Function","startLoc":1144,"text":"def test_frame_leak_on_failing_test(testdir):\n \"\"\"pytest would leak garbage referencing the frames of tests that failed that could never be reclaimed (#2798)\n\n Unfortunately it was not possible to remove the actual circles because most of them\n are made of traceback objects which cannot be weakly referenced. Those objects at least\n can be eventually claimed by the garbage collector.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import gc\n import weakref\n\n class Obj:\n pass\n\n ref = None\n\n def test1():\n obj = Obj()\n global ref\n ref = weakref.ref(obj)\n assert 0\n\n def test2():\n gc.collect()\n assert ref() is None\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*1 failed, 1 passed in*\"])"},{"col":0,"comment":"Test that decorators applied to fixture are left working (#3774)","endLoc":1180,"header":"def test_fixture_mock_integration(testdir)","id":6392,"name":"test_fixture_mock_integration","nodeType":"Function","startLoc":1176,"text":"def test_fixture_mock_integration(testdir):\n \"\"\"Test that decorators applied to fixture are left working (#3774)\"\"\"\n p = testdir.copy_example(\"acceptance/fixture_mock_integration.py\")\n result = testdir.runpytest(p)\n result.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":0,"comment":"","endLoc":3,"header":"empty.py#","id":6393,"name":"","nodeType":"Function","startLoc":2,"text":"for i in range(1000):\n exec(\"def test_func_%d(): pass\" % i)"},{"col":0,"comment":"null","endLoc":1185,"header":"def test_usage_error_code(testdir)","id":6394,"name":"test_usage_error_code","nodeType":"Function","startLoc":1183,"text":"def test_usage_error_code(testdir):\n result = testdir.runpytest(\"-unknown-option-\")\n assert result.ret == EXIT_USAGEERROR"},{"col":0,"comment":"null","endLoc":1213,"header":"@pytest.mark.skipif(\n sys.version_info[:2] < (3, 5), reason=\"async def syntax python 3.5+ only\"\n)\n@pytest.mark.filterwarnings(\"default\")\ndef test_warn_on_async_function(testdir)","id":6395,"name":"test_warn_on_async_function","nodeType":"Function","startLoc":1188,"text":"@pytest.mark.skipif(\n sys.version_info[:2] < (3, 5), reason=\"async def syntax python 3.5+ only\"\n)\n@pytest.mark.filterwarnings(\"default\")\ndef test_warn_on_async_function(testdir):\n testdir.makepyfile(\n test_async=\"\"\"\n async def test_1():\n pass\n async def test_2():\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"test_async.py::test_1\",\n \"test_async.py::test_2\",\n \"*Coroutine functions are not natively supported*\",\n \"*2 skipped, 2 warnings in*\",\n ]\n )\n # ensure our warning message appears only once\n assert (\n result.stdout.str().count(\"Coroutine functions are not natively supported\") == 1\n )"},{"id":6396,"name":"release-3.0.6.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.0.6\n============\n\npytest 3.0.6 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\n\nThanks to all who contributed to this release, among them:\n\n* Andreas Pelme\n* Bruno Oliveira\n* Dmitry Malinovsky\n* Eli Boyarski\n* Jakub Wilk\n* Jeff Widman\n* Loïc Estève\n* Luke Murphy\n* Miro Hrončok\n* Oscar Hellström\n* Peter Heatwole\n* Philippe Ombredanne\n* Ronny Pfannschmidt\n* Rutger Prins\n* Stefan Scherfke\n\n\nHappy testing,\nThe pytest Development Team\n"},{"id":6397,"name":"release-2.2.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-2.2.1: bug fixes, perfect teardowns\n===========================================================================\n\n\npytest-2.2.1 is a minor backward-compatible release of the py.test\ntesting tool. It contains bug fixes and little improvements, including\ndocumentation fixes. If you are using the distributed testing\npluginmake sure to upgrade it to pytest-xdist-1.8.\n\nFor general information see here:\n\n http://pytest.org/\n\nTo install or upgrade pytest:\n\n pip install -U pytest # or\n easy_install -U pytest\n\nSpecial thanks for helping on this release to Ronny Pfannschmidt, Jurko\nGospodnetic and Ralf Schmitt.\n\nbest,\nholger krekel\n\n\nChanges between 2.2.0 and 2.2.1\n----------------------------------------\n\n- fix issue99 (in pytest and py) internallerrors with resultlog now\n produce better output - fixed by normalizing pytest_internalerror\n input arguments.\n- fix issue97 / traceback issues (in pytest and py) improve traceback output\n in conjunction with jinja2 and cython which hack tracebacks\n- fix issue93 (in pytest and pytest-xdist) avoid \"delayed teardowns\":\n the final test in a test node will now run its teardown directly\n instead of waiting for the end of the session. Thanks Dave Hunt for\n the good reporting and feedback. The pytest_runtest_protocol as well\n as the pytest_runtest_teardown hooks now have \"nextitem\" available\n which will be None indicating the end of the test run.\n- fix collection crash due to unknown-source collected items, thanks\n to Ralf Schmitt (fixed by depending on a more recent pylib)\n"},{"id":6399,"name":"test_simple.yml","nodeType":"TextFile","path":"doc/en/example/nonpython","text":"# test_simple.yml\nok:\n sub1: sub1\n\nhello:\n world: world\n some: other\n"},{"col":4,"comment":"null","endLoc":24,"header":"def test_raises_exec(self)","id":6400,"name":"test_raises_exec","nodeType":"Function","startLoc":21,"text":"def test_raises_exec(self):\n with pytest.warns(PytestDeprecationWarning) as warninfo:\n pytest.raises(ValueError, \"a,x = []\")\n assert warninfo[0].filename == __file__"},{"col":4,"comment":"null","endLoc":29,"header":"def test_raises_exec_correct_filename(self)","id":6401,"name":"test_raises_exec_correct_filename","nodeType":"Function","startLoc":26,"text":"def test_raises_exec_correct_filename(self):\n with pytest.warns(PytestDeprecationWarning):\n excinfo = pytest.raises(ValueError, 'int(\"s\")')\n assert __file__ in excinfo.traceback[-1].path"},{"col":4,"comment":"null","endLoc":34,"header":"def test_raises_syntax_error(self)","id":6402,"name":"test_raises_syntax_error","nodeType":"Function","startLoc":31,"text":"def test_raises_syntax_error(self):\n with pytest.warns(PytestDeprecationWarning) as warninfo:\n pytest.raises(SyntaxError, \"qwe qwe qwe\")\n assert warninfo[0].filename == __file__"},{"col":0,"comment":"\n Regression test to make sure exceptions in the __init__ method are bubbled up correctly.\n See https://github.com/pytest-dev/pytest/issues/3788\n ","endLoc":1040,"header":"def test_testcase_handles_init_exceptions(testdir)","id":6403,"name":"test_testcase_handles_init_exceptions","nodeType":"Function","startLoc":1022,"text":"def test_testcase_handles_init_exceptions(testdir):\n \"\"\"\n Regression test to make sure exceptions in the __init__ method are bubbled up correctly.\n See https://github.com/pytest-dev/pytest/issues/3788\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n from unittest import TestCase\n import pytest\n class MyTestCase(TestCase):\n def __init__(self, *args, **kwargs):\n raise Exception(\"should raise this exception\")\n def test_hello(self):\n pass\n \"\"\"\n )\n result = testdir.runpytest()\n assert \"should raise this exception\" in result.stdout.str()\n assert \"ERROR at teardown of MyTestCase.test_hello\" not in result.stdout.str()"},{"col":4,"comment":"null","endLoc":37,"header":"def test_raises_function(self)","id":6404,"name":"test_raises_function","nodeType":"Function","startLoc":36,"text":"def test_raises_function(self):\n pytest.raises(ValueError, int, \"hello\")"},{"col":4,"comment":"null","endLoc":47,"header":"def test_raises_callable_no_exception(self)","id":6405,"name":"test_raises_callable_no_exception","nodeType":"Function","startLoc":39,"text":"def test_raises_callable_no_exception(self):\n class A(object):\n def __call__(self):\n pass\n\n try:\n pytest.raises(ValueError, A())\n except pytest.raises.Exception:\n pass"},{"col":0,"comment":"null","endLoc":1052,"header":"def test_error_message_with_parametrized_fixtures(testdir)","id":6406,"name":"test_error_message_with_parametrized_fixtures","nodeType":"Function","startLoc":1043,"text":"def test_error_message_with_parametrized_fixtures(testdir):\n testdir.copy_example(\"unittest/test_parametrized_fixture_error_message.py\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*test_two does not support fixtures*\",\n \"*TestSomethingElse::test_two\",\n \"*Function type: TestCaseFunction\",\n ]\n )"},{"col":0,"comment":"Issue #4700","endLoc":1067,"header":"@pytest.mark.parametrize(\n \"test_name, expected_outcome\",\n [\n (\"test_setup_skip.py\", \"1 skipped\"),\n (\"test_setup_skip_class.py\", \"1 skipped\"),\n (\"test_setup_skip_module.py\", \"1 error\"),\n ],\n)\ndef test_setup_inheritance_skipping(testdir, test_name, expected_outcome)","id":6407,"name":"test_setup_inheritance_skipping","nodeType":"Function","startLoc":1055,"text":"@pytest.mark.parametrize(\n \"test_name, expected_outcome\",\n [\n (\"test_setup_skip.py\", \"1 skipped\"),\n (\"test_setup_skip_class.py\", \"1 skipped\"),\n (\"test_setup_skip_module.py\", \"1 error\"),\n ],\n)\ndef test_setup_inheritance_skipping(testdir, test_name, expected_outcome):\n \"\"\"Issue #4700\"\"\"\n testdir.copy_example(\"unittest/{}\".format(test_name))\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* {} in *\".format(expected_outcome)])"},{"col":4,"comment":"null","endLoc":52,"header":"def test_raises_falsey_type_error(self)","id":6408,"name":"test_raises_falsey_type_error","nodeType":"Function","startLoc":49,"text":"def test_raises_falsey_type_error(self):\n with pytest.raises(TypeError):\n with pytest.raises(AssertionError, match=0):\n raise AssertionError(\"ohai\")"},{"col":0,"comment":"null","endLoc":999,"header":"def test_collection_logging_to_file(testdir)","id":6409,"name":"test_collection_logging_to_file","nodeType":"Function","startLoc":964,"text":"def test_collection_logging_to_file(testdir):\n log_file = testdir.tmpdir.join(\"pytest.log\").strpath\n\n testdir.makeini(\n \"\"\"\n [pytest]\n log_file={}\n log_file_level = INFO\n \"\"\".format(\n log_file\n )\n )\n\n testdir.makepyfile(\n \"\"\"\n import logging\n\n logging.getLogger().info(\"Normal message\")\n\n def test_simple():\n logging.getLogger().debug(\"debug message in test_simple\")\n logging.getLogger().info(\"info message in test_simple\")\n \"\"\"\n )\n\n result = testdir.runpytest()\n\n assert \"--- live log collection ---\" not in result.stdout.str()\n\n assert result.ret == 0\n assert os.path.isfile(log_file)\n with open(log_file, encoding=\"utf-8\") as rfh:\n contents = rfh.read()\n assert \"Normal message\" in contents\n assert \"debug message in test_simple\" not in contents\n assert \"info message in test_simple\" in contents"},{"col":4,"comment":"Ensure repr() on an exception info inside a pytest.raises with block works (#4386)","endLoc":69,"header":"def test_raises_repr_inflight(self)","id":6410,"name":"test_raises_repr_inflight","nodeType":"Function","startLoc":54,"text":"def test_raises_repr_inflight(self):\n \"\"\"Ensure repr() on an exception info inside a pytest.raises with block works (#4386)\"\"\"\n\n class E(Exception):\n pass\n\n with pytest.raises(E) as excinfo:\n # this test prints the inflight uninitialized object\n # using repr and str as well as pprint to demonstrate\n # it works\n print(str(excinfo))\n print(repr(excinfo))\n import pprint\n\n pprint.pprint(excinfo)\n raise E()"},{"id":6411,"name":"doctest.rst","nodeType":"TextFile","path":"doc/en","text":"\nDoctest integration for modules and test files\n=========================================================\n\nBy default all files matching the ``test*.txt`` pattern will\nbe run through the python standard ``doctest`` module. You\ncan change the pattern by issuing:\n\n.. code-block:: bash\n\n pytest --doctest-glob='*.rst'\n\non the command line. ``--doctest-glob`` can be given multiple times in the command-line.\n\nIf you then have a text file like this:\n\n.. code-block:: text\n\n # content of test_example.txt\n\n hello this is a doctest\n >>> x = 3\n >>> x\n 3\n\nthen you can just invoke ``pytest`` directly:\n\n.. code-block:: pytest\n\n $ pytest\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 1 item\n\n test_example.txt . [100%]\n\n ========================= 1 passed in 0.12 seconds =========================\n\nBy default, pytest will collect ``test*.txt`` files looking for doctest directives, but you\ncan pass additional globs using the ``--doctest-glob`` option (multi-allowed).\n\nIn addition to text files, you can also execute doctests directly from docstrings of your classes\nand functions, including from test modules:\n\n.. code-block:: python\n\n # content of mymodule.py\n def something():\n \"\"\" a doctest in a docstring\n >>> something()\n 42\n \"\"\"\n return 42\n\n.. code-block:: bash\n\n $ pytest --doctest-modules\n =========================== test session starts ============================\n platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y\n cachedir: $PYTHON_PREFIX/.pytest_cache\n rootdir: $REGENDOC_TMPDIR\n collected 2 items\n\n mymodule.py . [ 50%]\n test_example.txt . [100%]\n\n ========================= 2 passed in 0.12 seconds =========================\n\nYou can make these changes permanent in your project by\nputting them into a pytest.ini file like this:\n\n.. code-block:: ini\n\n # content of pytest.ini\n [pytest]\n addopts = --doctest-modules\n\n.. note::\n\n The builtin pytest doctest supports only ``doctest`` blocks, but if you are looking\n for more advanced checking over *all* your documentation,\n including doctests, ``.. codeblock:: python`` Sphinx directive support,\n and any other examples your documentation may include, you may wish to\n consider `Sybil `__.\n It provides pytest integration out of the box.\n\n\nEncoding\n--------\n\nThe default encoding is **UTF-8**, but you can specify the encoding\nthat will be used for those doctest files using the\n``doctest_encoding`` ini option:\n\n.. code-block:: ini\n\n # content of pytest.ini\n [pytest]\n doctest_encoding = latin1\n\nUsing 'doctest' options\n-----------------------\n\nThe standard ``doctest`` module provides some `options `__\nto configure the strictness of doctest tests. In pytest, you can enable those flags using the\nconfiguration file.\n\nFor example, to make pytest ignore trailing whitespaces and ignore\nlengthy exception stack traces you can just write:\n\n.. code-block:: ini\n\n [pytest]\n doctest_optionflags= NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL\n\npytest also introduces new options to allow doctests to run in Python 2 and\nPython 3 unchanged:\n\n* ``ALLOW_UNICODE``: when enabled, the ``u`` prefix is stripped from unicode\n strings in expected doctest output.\n\n* ``ALLOW_BYTES``: when enabled, the ``b`` prefix is stripped from byte strings\n in expected doctest output.\n\nAlternatively, options can be enabled by an inline comment in the doc test\nitself:\n\n.. code-block:: rst\n\n # content of example.rst\n >>> get_unicode_greeting() # doctest: +ALLOW_UNICODE\n 'Hello'\n\nBy default, pytest would report only the first failure for a given doctest. If\nyou want to continue the test even when you have failures, do:\n\n.. code-block:: bash\n\n pytest --doctest-modules --doctest-continue-on-failure\n\n\nOutput format\n-------------\n\nYou can change the diff output format on failure for your doctests\nby using one of standard doctest modules format in options\n(see :data:`python:doctest.REPORT_UDIFF`, :data:`python:doctest.REPORT_CDIFF`,\n:data:`python:doctest.REPORT_NDIFF`, :data:`python:doctest.REPORT_ONLY_FIRST_FAILURE`):\n\n.. code-block:: bash\n\n pytest --doctest-modules --doctest-report none\n pytest --doctest-modules --doctest-report udiff\n pytest --doctest-modules --doctest-report cdiff\n pytest --doctest-modules --doctest-report ndiff\n pytest --doctest-modules --doctest-report only_first_failure\n\n\npytest-specific features\n------------------------\n\nSome features are provided to make writing doctests easier or with better integration with\nyour existing test suite. Keep in mind however that by using those features you will make\nyour doctests incompatible with the standard ``doctests`` module.\n\nUsing fixtures\n^^^^^^^^^^^^^^\n\nIt is possible to use fixtures using the ``getfixture`` helper:\n\n.. code-block:: text\n\n # content of example.rst\n >>> tmp = getfixture('tmpdir')\n >>> ...\n >>>\n\nAlso, :ref:`usefixtures` and :ref:`autouse` fixtures are supported\nwhen executing text doctest files.\n\n\n.. _`doctest_namespace`:\n\n'doctest_namespace' fixture\n^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nThe ``doctest_namespace`` fixture can be used to inject items into the\nnamespace in which your doctests run. It is intended to be used within\nyour own fixtures to provide the tests that use them with context.\n\n``doctest_namespace`` is a standard ``dict`` object into which you\nplace the objects you want to appear in the doctest namespace::\n\n # content of conftest.py\n import numpy\n @pytest.fixture(autouse=True)\n def add_np(doctest_namespace):\n doctest_namespace['np'] = numpy\n\nwhich can then be used in your doctests directly::\n\n # content of numpy.py\n def arange():\n \"\"\"\n >>> a = np.arange(10)\n >>> len(a)\n 10\n \"\"\"\n pass\n\nNote that like the normal ``conftest.py``, the fixtures are discovered in the directory tree conftest is in.\nMeaning that if you put your doctest with your source code, the relevant conftest.py needs to be in the same directory tree.\nFixtures will not be discovered in a sibling directory tree!\n\nSkipping tests dynamically\n^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. versionadded:: 4.4\n\nYou can use ``pytest.skip`` to dynamically skip doctests. For example::\n\n >>> import sys, pytest\n >>> if sys.platform.startswith('win'):\n ... pytest.skip('this doctest does not work on Windows')\n ...\n"},{"col":4,"comment":"Create new file(s) in the testdir.\n\n :param str ext: The extension the file(s) should use, including the dot, e.g. `.py`.\n :param list[str] args: All args will be treated as strings and joined using newlines.\n The result will be written as contents to the file. The name of the\n file will be based on the test function requesting this fixture.\n :param kwargs: Each keyword is the name of a file, while the value of it will\n be written as contents of the file.\n\n Examples:\n\n .. code-block:: python\n\n testdir.makefile(\".txt\", \"line1\", \"line2\")\n\n testdir.makefile(\".ini\", pytest=\"[pytest]\\naddopts=-rs\\n\")\n\n ","endLoc":598,"header":"def makefile(self, ext, *args, **kwargs)","id":6413,"name":"makefile","nodeType":"Function","startLoc":579,"text":"def makefile(self, ext, *args, **kwargs):\n r\"\"\"Create new file(s) in the testdir.\n\n :param str ext: The extension the file(s) should use, including the dot, e.g. `.py`.\n :param list[str] args: All args will be treated as strings and joined using newlines.\n The result will be written as contents to the file. The name of the\n file will be based on the test function requesting this fixture.\n :param kwargs: Each keyword is the name of a file, while the value of it will\n be written as contents of the file.\n\n Examples:\n\n .. code-block:: python\n\n testdir.makefile(\".txt\", \"line1\", \"line2\")\n\n testdir.makefile(\".ini\", pytest=\"[pytest]\\naddopts=-rs\\n\")\n\n \"\"\"\n return self._makefile(ext, args, kwargs)"},{"col":4,"comment":"Write a contest.py file with 'source' as contents.","endLoc":602,"header":"def makeconftest(self, source)","id":6414,"name":"makeconftest","nodeType":"Function","startLoc":600,"text":"def makeconftest(self, source):\n \"\"\"Write a contest.py file with 'source' as contents.\"\"\"\n return self.makepyfile(conftest=source)"},{"col":4,"comment":"Shortcut for .makefile() with a .py extension.","endLoc":615,"header":"def makepyfile(self, *args, **kwargs)","id":6415,"name":"makepyfile","nodeType":"Function","startLoc":613,"text":"def makepyfile(self, *args, **kwargs):\n \"\"\"Shortcut for .makefile() with a .py extension.\"\"\"\n return self._makefile(\".py\", args, kwargs)"},{"col":4,"comment":"Write a tox.ini file with 'source' as contents.","endLoc":606,"header":"def makeini(self, source)","id":6416,"name":"makeini","nodeType":"Function","startLoc":604,"text":"def makeini(self, source):\n \"\"\"Write a tox.ini file with 'source' as contents.\"\"\"\n return self.makefile(\".ini\", tox=source)"},{"col":4,"comment":"Return the pytest section from the tox.ini config file.","endLoc":611,"header":"def getinicfg(self, source)","id":6417,"name":"getinicfg","nodeType":"Function","startLoc":608,"text":"def getinicfg(self, source):\n \"\"\"Return the pytest section from the tox.ini config file.\"\"\"\n p = self.makeini(source)\n return py.iniconfig.IniConfig(p)[\"pytest\"]"},{"col":0,"comment":"null","endLoc":435,"header":"def pytest_report_from_serializable(data)","id":6418,"name":"pytest_report_from_serializable","nodeType":"Function","startLoc":427,"text":"def pytest_report_from_serializable(data):\n if \"_report_type\" in data:\n if data[\"_report_type\"] == \"TestReport\":\n return TestReport._from_json(data)\n elif data[\"_report_type\"] == \"CollectReport\":\n return CollectReport._from_json(data)\n assert False, \"Unknown report_type unserialize data: {}\".format(\n data[\"_report_type\"]\n )"},{"col":0,"comment":"null","endLoc":1035,"header":"def test_log_in_hooks(testdir)","id":6419,"name":"test_log_in_hooks","nodeType":"Function","startLoc":1002,"text":"def test_log_in_hooks(testdir):\n log_file = testdir.tmpdir.join(\"pytest.log\").strpath\n\n testdir.makeini(\n \"\"\"\n [pytest]\n log_file={}\n log_file_level = INFO\n log_cli=true\n \"\"\".format(\n log_file\n )\n )\n testdir.makeconftest(\n \"\"\"\n import logging\n\n def pytest_runtestloop(session):\n logging.info('runtestloop')\n\n def pytest_sessionstart(session):\n logging.info('sessionstart')\n\n def pytest_sessionfinish(session, exitstatus):\n logging.info('sessionfinish')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*sessionstart*\", \"*runtestloop*\", \"*sessionfinish*\"])\n with open(log_file) as rfh:\n contents = rfh.read()\n assert \"sessionstart\" in contents\n assert \"runtestloop\" in contents\n assert \"sessionfinish\" in contents"},{"col":4,"comment":"Shortcut for .makefile() with a .txt extension.","endLoc":619,"header":"def maketxtfile(self, *args, **kwargs)","id":6420,"name":"maketxtfile","nodeType":"Function","startLoc":617,"text":"def maketxtfile(self, *args, **kwargs):\n \"\"\"Shortcut for .makefile() with a .txt extension.\"\"\"\n return self._makefile(\".txt\", args, kwargs)"},{"col":4,"comment":"Prepend a directory to sys.path, defaults to :py:attr:`tmpdir`.\n\n This is undone automatically when this object dies at the end of each\n test.\n ","endLoc":630,"header":"def syspathinsert(self, path=None)","id":6421,"name":"syspathinsert","nodeType":"Function","startLoc":621,"text":"def syspathinsert(self, path=None):\n \"\"\"Prepend a directory to sys.path, defaults to :py:attr:`tmpdir`.\n\n This is undone automatically when this object dies at the end of each\n test.\n \"\"\"\n if path is None:\n path = self.tmpdir\n\n self.monkeypatch.syspath_prepend(str(path))"},{"col":4,"comment":"Create a new (sub)directory.","endLoc":634,"header":"def mkdir(self, name)","id":6422,"name":"mkdir","nodeType":"Function","startLoc":632,"text":"def mkdir(self, name):\n \"\"\"Create a new (sub)directory.\"\"\"\n return self.tmpdir.mkdir(name)"},{"col":0,"comment":"null","endLoc":1069,"header":"def test_log_in_runtest_logreport(testdir)","id":6423,"name":"test_log_in_runtest_logreport","nodeType":"Function","startLoc":1038,"text":"def test_log_in_runtest_logreport(testdir):\n log_file = testdir.tmpdir.join(\"pytest.log\").strpath\n\n testdir.makeini(\n \"\"\"\n [pytest]\n log_file={}\n log_file_level = INFO\n log_cli=true\n \"\"\".format(\n log_file\n )\n )\n testdir.makeconftest(\n \"\"\"\n import logging\n logger = logging.getLogger(__name__)\n\n def pytest_runtest_logreport(report):\n logger.info(\"logreport\")\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_first():\n assert True\n \"\"\"\n )\n testdir.runpytest()\n with open(log_file) as rfh:\n contents = rfh.read()\n assert contents.count(\"logreport\") == 3"},{"col":4,"comment":"Create a new python package.\n\n This creates a (sub)directory with an empty ``__init__.py`` file so it\n gets recognised as a python package.\n\n ","endLoc":645,"header":"def mkpydir(self, name)","id":6424,"name":"mkpydir","nodeType":"Function","startLoc":636,"text":"def mkpydir(self, name):\n \"\"\"Create a new python package.\n\n This creates a (sub)directory with an empty ``__init__.py`` file so it\n gets recognised as a python package.\n\n \"\"\"\n p = self.mkdir(name)\n p.ensure(\"__init__.py\")\n return p"},{"col":4,"comment":"null","endLoc":689,"header":"def copy_example(self, name=None)","id":6425,"name":"copy_example","nodeType":"Function","startLoc":647,"text":"def copy_example(self, name=None):\n import warnings\n from _pytest.warning_types import PYTESTER_COPY_EXAMPLE\n\n warnings.warn(PYTESTER_COPY_EXAMPLE, stacklevel=2)\n example_dir = self.request.config.getini(\"pytester_example_dir\")\n if example_dir is None:\n raise ValueError(\"pytester_example_dir is unset, can't copy examples\")\n example_dir = self.request.config.rootdir.join(example_dir)\n\n for extra_element in self.request.node.iter_markers(\"pytester_example_path\"):\n assert extra_element.args\n example_dir = example_dir.join(*extra_element.args)\n\n if name is None:\n func_name = self.request.function.__name__\n maybe_dir = example_dir / func_name\n maybe_file = example_dir / (func_name + \".py\")\n\n if maybe_dir.isdir():\n example_path = maybe_dir\n elif maybe_file.isfile():\n example_path = maybe_file\n else:\n raise LookupError(\n \"{} cant be found as module or package in {}\".format(\n func_name, example_dir.bestrelpath(self.request.config.rootdir)\n )\n )\n else:\n example_path = example_dir.join(name)\n\n if example_path.isdir() and not example_path.join(\"__init__.py\").isfile():\n example_path.copy(self.tmpdir)\n return self.tmpdir\n elif example_path.isfile():\n result = self.tmpdir.join(example_path.basename)\n example_path.copy(result)\n return result\n else:\n raise LookupError(\n 'example \"{}\" is not found as a file or directory'.format(example_path)\n )"},{"col":4,"comment":"null","endLoc":97,"header":"def test_raises_as_contextmanager(self, testdir)","id":6426,"name":"test_raises_as_contextmanager","nodeType":"Function","startLoc":71,"text":"def test_raises_as_contextmanager(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n import _pytest._code\n\n def test_simple():\n with pytest.raises(ZeroDivisionError) as excinfo:\n assert isinstance(excinfo, _pytest._code.ExceptionInfo)\n 1/0\n print(excinfo)\n assert excinfo.type == ZeroDivisionError\n assert isinstance(excinfo.value, ZeroDivisionError)\n\n def test_noraise():\n with pytest.raises(pytest.raises.Exception):\n with pytest.raises(ValueError):\n int()\n\n def test_raise_wrong_exception_passes_by():\n with pytest.raises(ZeroDivisionError):\n with pytest.raises(ValueError):\n 1/0\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*3 passed*\"])"},{"col":4,"comment":"null","endLoc":122,"header":"def test_does_not_raise(self, testdir)","id":6427,"name":"test_does_not_raise","nodeType":"Function","startLoc":99,"text":"def test_does_not_raise(self, testdir):\n testdir.makepyfile(\n \"\"\"\n from contextlib import contextmanager\n import pytest\n\n @contextmanager\n def does_not_raise():\n yield\n\n @pytest.mark.parametrize('example_input,expectation', [\n (3, does_not_raise()),\n (2, does_not_raise()),\n (1, does_not_raise()),\n (0, pytest.raises(ZeroDivisionError)),\n ])\n def test_division(example_input, expectation):\n '''Test how much I know division.'''\n with expectation:\n assert (6 / example_input) is not None\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*4 passed*\"])"},{"col":4,"comment":"null","endLoc":145,"header":"def test_does_not_raise_does_raise(self, testdir)","id":6428,"name":"test_does_not_raise_does_raise","nodeType":"Function","startLoc":124,"text":"def test_does_not_raise_does_raise(self, testdir):\n testdir.makepyfile(\n \"\"\"\n from contextlib import contextmanager\n import pytest\n\n @contextmanager\n def does_not_raise():\n yield\n\n @pytest.mark.parametrize('example_input,expectation', [\n (0, does_not_raise()),\n (1, pytest.raises(ZeroDivisionError)),\n ])\n def test_division(example_input, expectation):\n '''Test how much I know division.'''\n with expectation:\n assert (6 / example_input) is not None\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*2 failed*\"])"},{"col":4,"comment":"null","endLoc":149,"header":"def test_noclass(self)","id":6429,"name":"test_noclass","nodeType":"Function","startLoc":147,"text":"def test_noclass(self):\n with pytest.raises(TypeError):\n pytest.raises(\"wrong\", lambda: None)"},{"col":35,"endLoc":149,"id":6430,"nodeType":"Lambda","startLoc":149,"text":"lambda: None"},{"col":4,"comment":"null","endLoc":154,"header":"def test_invalid_arguments_to_raises(self)","id":6431,"name":"test_invalid_arguments_to_raises","nodeType":"Function","startLoc":151,"text":"def test_invalid_arguments_to_raises(self):\n with pytest.raises(TypeError, match=\"unknown\"):\n with pytest.raises(TypeError, unknown=\"bogus\"):\n raise ValueError()"},{"fileName":"test_excinfo.py","filePath":"testing/code","id":6432,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport operator\nimport os\nimport sys\nimport textwrap\n\nimport py\nimport six\nfrom six.moves import queue\n\nimport _pytest\nimport pytest\nfrom _pytest._code.code import ExceptionChainRepr\nfrom _pytest._code.code import ExceptionInfo\nfrom _pytest._code.code import FormattedExcinfo\nfrom _pytest._code.code import ReprExceptionInfo\n\ntry:\n import importlib\nexcept ImportError:\n invalidate_import_caches = None\nelse:\n invalidate_import_caches = getattr(importlib, \"invalidate_caches\", None)\n\nfailsonjython = pytest.mark.xfail(\"sys.platform.startswith('java')\")\n\npytest_version_info = tuple(map(int, pytest.__version__.split(\".\")[:3]))\n\n\n@pytest.fixture\ndef limited_recursion_depth():\n before = sys.getrecursionlimit()\n sys.setrecursionlimit(150)\n yield\n sys.setrecursionlimit(before)\n\n\nclass TWMock(object):\n WRITE = object()\n\n def __init__(self):\n self.lines = []\n self.is_writing = False\n\n def sep(self, sep, line=None):\n self.lines.append((sep, line))\n\n def write(self, msg, **kw):\n self.lines.append((TWMock.WRITE, msg))\n\n def line(self, line, **kw):\n self.lines.append(line)\n\n def markup(self, text, **kw):\n return text\n\n def get_write_msg(self, idx):\n flag, msg = self.lines[idx]\n assert flag == TWMock.WRITE\n return msg\n\n fullwidth = 80\n\n\ndef test_excinfo_simple():\n try:\n raise ValueError\n except ValueError:\n info = _pytest._code.ExceptionInfo.from_current()\n assert info.type == ValueError\n\n\ndef test_excinfo_getstatement():\n def g():\n raise ValueError\n\n def f():\n g()\n\n try:\n f()\n except ValueError:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n linenumbers = [\n _pytest._code.getrawcode(f).co_firstlineno - 1 + 4,\n _pytest._code.getrawcode(f).co_firstlineno - 1 + 1,\n _pytest._code.getrawcode(g).co_firstlineno - 1 + 1,\n ]\n values = list(excinfo.traceback)\n foundlinenumbers = [x.lineno for x in values]\n assert foundlinenumbers == linenumbers\n # for x in info:\n # print \"%s:%d %s\" %(x.path.relto(root), x.lineno, x.statement)\n # xxx\n\n\n# testchain for getentries test below\n\n\ndef f():\n #\n raise ValueError\n #\n\n\ndef g():\n #\n __tracebackhide__ = True\n f()\n #\n\n\ndef h():\n #\n g()\n #\n\n\nclass TestTraceback_f_g_h(object):\n def setup_method(self, method):\n try:\n h()\n except ValueError:\n self.excinfo = _pytest._code.ExceptionInfo.from_current()\n\n def test_traceback_entries(self):\n tb = self.excinfo.traceback\n entries = list(tb)\n assert len(tb) == 4 # maybe fragile test\n assert len(entries) == 4 # maybe fragile test\n names = [\"f\", \"g\", \"h\"]\n for entry in entries:\n try:\n names.remove(entry.frame.code.name)\n except ValueError:\n pass\n assert not names\n\n def test_traceback_entry_getsource(self):\n tb = self.excinfo.traceback\n s = str(tb[-1].getsource())\n assert s.startswith(\"def f():\")\n assert s.endswith(\"raise ValueError\")\n\n @failsonjython\n def test_traceback_entry_getsource_in_construct(self):\n source = _pytest._code.Source(\n \"\"\"\\\n def xyz():\n try:\n raise ValueError\n except somenoname:\n pass\n xyz()\n \"\"\"\n )\n try:\n exec(source.compile())\n except NameError:\n tb = _pytest._code.ExceptionInfo.from_current().traceback\n print(tb[-1].getsource())\n s = str(tb[-1].getsource())\n assert s.startswith(\"def xyz():\\n try:\")\n assert s.strip().endswith(\"except somenoname:\")\n\n def test_traceback_cut(self):\n co = _pytest._code.Code(f)\n path, firstlineno = co.path, co.firstlineno\n traceback = self.excinfo.traceback\n newtraceback = traceback.cut(path=path, firstlineno=firstlineno)\n assert len(newtraceback) == 1\n newtraceback = traceback.cut(path=path, lineno=firstlineno + 2)\n assert len(newtraceback) == 1\n\n def test_traceback_cut_excludepath(self, testdir):\n p = testdir.makepyfile(\"def f(): raise ValueError\")\n with pytest.raises(ValueError) as excinfo:\n p.pyimport().f()\n basedir = py.path.local(pytest.__file__).dirpath()\n newtraceback = excinfo.traceback.cut(excludepath=basedir)\n for x in newtraceback:\n if hasattr(x, \"path\"):\n assert not py.path.local(x.path).relto(basedir)\n assert newtraceback[-1].frame.code.path == p\n\n def test_traceback_filter(self):\n traceback = self.excinfo.traceback\n ntraceback = traceback.filter()\n assert len(ntraceback) == len(traceback) - 1\n\n @pytest.mark.parametrize(\n \"tracebackhide, matching\",\n [\n (lambda info: True, True),\n (lambda info: False, False),\n (operator.methodcaller(\"errisinstance\", ValueError), True),\n (operator.methodcaller(\"errisinstance\", IndexError), False),\n ],\n )\n def test_traceback_filter_selective(self, tracebackhide, matching):\n def f():\n #\n raise ValueError\n #\n\n def g():\n #\n __tracebackhide__ = tracebackhide\n f()\n #\n\n def h():\n #\n g()\n #\n\n excinfo = pytest.raises(ValueError, h)\n traceback = excinfo.traceback\n ntraceback = traceback.filter()\n print(\"old: {!r}\".format(traceback))\n print(\"new: {!r}\".format(ntraceback))\n\n if matching:\n assert len(ntraceback) == len(traceback) - 2\n else:\n # -1 because of the __tracebackhide__ in pytest.raises\n assert len(ntraceback) == len(traceback) - 1\n\n def test_traceback_recursion_index(self):\n def f(n):\n if n < 10:\n n += 1\n f(n)\n\n excinfo = pytest.raises(RuntimeError, f, 8)\n traceback = excinfo.traceback\n recindex = traceback.recursionindex()\n assert recindex == 3\n\n def test_traceback_only_specific_recursion_errors(self, monkeypatch):\n def f(n):\n if n == 0:\n raise RuntimeError(\"hello\")\n f(n - 1)\n\n excinfo = pytest.raises(RuntimeError, f, 25)\n monkeypatch.delattr(excinfo.traceback.__class__, \"recursionindex\")\n repr = excinfo.getrepr()\n assert \"RuntimeError: hello\" in str(repr.reprcrash)\n\n def test_traceback_no_recursion_index(self):\n def do_stuff():\n raise RuntimeError\n\n def reraise_me():\n import sys\n\n exc, val, tb = sys.exc_info()\n six.reraise(exc, val, tb)\n\n def f(n):\n try:\n do_stuff()\n except: # noqa\n reraise_me()\n\n excinfo = pytest.raises(RuntimeError, f, 8)\n traceback = excinfo.traceback\n recindex = traceback.recursionindex()\n assert recindex is None\n\n def test_traceback_messy_recursion(self):\n # XXX: simplified locally testable version\n decorator = pytest.importorskip(\"decorator\").decorator\n\n def log(f, *k, **kw):\n print(\"{} {}\".format(k, kw))\n f(*k, **kw)\n\n log = decorator(log)\n\n def fail():\n raise ValueError(\"\")\n\n fail = log(log(fail))\n\n excinfo = pytest.raises(ValueError, fail)\n assert excinfo.traceback.recursionindex() is None\n\n def test_traceback_getcrashentry(self):\n def i():\n __tracebackhide__ = True\n raise ValueError\n\n def h():\n i()\n\n def g():\n __tracebackhide__ = True\n h()\n\n def f():\n g()\n\n excinfo = pytest.raises(ValueError, f)\n tb = excinfo.traceback\n entry = tb.getcrashentry()\n co = _pytest._code.Code(h)\n assert entry.frame.code.path == co.path\n assert entry.lineno == co.firstlineno + 1\n assert entry.frame.code.name == \"h\"\n\n def test_traceback_getcrashentry_empty(self):\n def g():\n __tracebackhide__ = True\n raise ValueError\n\n def f():\n __tracebackhide__ = True\n g()\n\n excinfo = pytest.raises(ValueError, f)\n tb = excinfo.traceback\n entry = tb.getcrashentry()\n co = _pytest._code.Code(g)\n assert entry.frame.code.path == co.path\n assert entry.lineno == co.firstlineno + 2\n assert entry.frame.code.name == \"g\"\n\n\ndef test_excinfo_exconly():\n excinfo = pytest.raises(ValueError, h)\n assert excinfo.exconly().startswith(\"ValueError\")\n with pytest.raises(ValueError) as excinfo:\n raise ValueError(\"hello\\nworld\")\n msg = excinfo.exconly(tryshort=True)\n assert msg.startswith(\"ValueError\")\n assert msg.endswith(\"world\")\n\n\ndef test_excinfo_repr():\n excinfo = pytest.raises(ValueError, h)\n s = repr(excinfo)\n assert s == \"\"\n\n\ndef test_excinfo_str():\n excinfo = pytest.raises(ValueError, h)\n s = str(excinfo)\n assert s.startswith(__file__[:-9]) # pyc file and $py.class\n assert s.endswith(\"ValueError\")\n assert len(s.split(\":\")) >= 3 # on windows it's 4\n\n\ndef test_excinfo_for_later():\n e = ExceptionInfo.for_later()\n assert \"for raises\" in repr(e)\n assert \"for raises\" in str(e)\n\n\ndef test_excinfo_errisinstance():\n excinfo = pytest.raises(ValueError, h)\n assert excinfo.errisinstance(ValueError)\n\n\ndef test_excinfo_no_sourcecode():\n try:\n exec(\"raise ValueError()\")\n except ValueError:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n s = str(excinfo.traceback[-1])\n assert s == \" File '':1 in \\n ???\\n\"\n\n\ndef test_excinfo_no_python_sourcecode(tmpdir):\n # XXX: simplified locally testable version\n tmpdir.join(\"test.txt\").write(\"{{ h()}}:\")\n\n jinja2 = pytest.importorskip(\"jinja2\")\n loader = jinja2.FileSystemLoader(str(tmpdir))\n env = jinja2.Environment(loader=loader)\n template = env.get_template(\"test.txt\")\n excinfo = pytest.raises(ValueError, template.render, h=h)\n for item in excinfo.traceback:\n print(item) # XXX: for some reason jinja.Template.render is printed in full\n item.source # shouldnt fail\n if item.path.basename == \"test.txt\":\n assert str(item.source) == \"{{ h()}}:\"\n\n\ndef test_entrysource_Queue_example():\n try:\n queue.Queue().get(timeout=0.001)\n except queue.Empty:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n entry = excinfo.traceback[-1]\n source = entry.getsource()\n assert source is not None\n s = str(source).strip()\n assert s.startswith(\"def get\")\n\n\ndef test_codepath_Queue_example():\n try:\n queue.Queue().get(timeout=0.001)\n except queue.Empty:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n entry = excinfo.traceback[-1]\n path = entry.path\n assert isinstance(path, py.path.local)\n assert path.basename.lower() == \"queue.py\"\n assert path.check()\n\n\ndef test_match_succeeds():\n with pytest.raises(ZeroDivisionError) as excinfo:\n 0 // 0\n excinfo.match(r\".*zero.*\")\n\n\ndef test_match_raises_error(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_division_zero():\n with pytest.raises(ZeroDivisionError) as excinfo:\n 0 / 0\n excinfo.match(r'[123]+')\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret != 0\n result.stdout.fnmatch_lines([\"*AssertionError*Pattern*[123]*not found*\"])\n\n\nclass TestFormattedExcinfo(object):\n @pytest.fixture\n def importasmod(self, request, _sys_snapshot):\n def importasmod(source):\n source = textwrap.dedent(source)\n tmpdir = request.getfixturevalue(\"tmpdir\")\n modpath = tmpdir.join(\"mod.py\")\n tmpdir.ensure(\"__init__.py\")\n modpath.write(source)\n if invalidate_import_caches is not None:\n invalidate_import_caches()\n return modpath.pyimport()\n\n return importasmod\n\n def excinfo_from_exec(self, source):\n source = _pytest._code.Source(source).strip()\n try:\n exec(source.compile())\n except KeyboardInterrupt:\n raise\n except: # noqa\n return _pytest._code.ExceptionInfo.from_current()\n assert 0, \"did not raise\"\n\n def test_repr_source(self):\n pr = FormattedExcinfo()\n source = _pytest._code.Source(\n \"\"\"\\\n def f(x):\n pass\n \"\"\"\n ).strip()\n pr.flow_marker = \"|\"\n lines = pr.get_source(source, 0)\n assert len(lines) == 2\n assert lines[0] == \"| def f(x):\"\n assert lines[1] == \" pass\"\n\n def test_repr_source_excinfo(self):\n \"\"\" check if indentation is right \"\"\"\n pr = FormattedExcinfo()\n excinfo = self.excinfo_from_exec(\n \"\"\"\n def f():\n assert 0\n f()\n \"\"\"\n )\n pr = FormattedExcinfo()\n source = pr._getentrysource(excinfo.traceback[-1])\n lines = pr.get_source(source, 1, excinfo)\n assert lines == [\" def f():\", \"> assert 0\", \"E AssertionError\"]\n\n def test_repr_source_not_existing(self):\n pr = FormattedExcinfo()\n co = compile(\"raise ValueError()\", \"\", \"exec\")\n try:\n exec(co)\n except ValueError:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n repr = pr.repr_excinfo(excinfo)\n assert repr.reprtraceback.reprentries[1].lines[0] == \"> ???\"\n if sys.version_info[0] >= 3:\n assert repr.chain[0][0].reprentries[1].lines[0] == \"> ???\"\n\n def test_repr_many_line_source_not_existing(self):\n pr = FormattedExcinfo()\n co = compile(\n \"\"\"\na = 1\nraise ValueError()\n\"\"\",\n \"\",\n \"exec\",\n )\n try:\n exec(co)\n except ValueError:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n repr = pr.repr_excinfo(excinfo)\n assert repr.reprtraceback.reprentries[1].lines[0] == \"> ???\"\n if sys.version_info[0] >= 3:\n assert repr.chain[0][0].reprentries[1].lines[0] == \"> ???\"\n\n def test_repr_source_failing_fullsource(self):\n pr = FormattedExcinfo()\n\n class FakeCode(object):\n class raw(object):\n co_filename = \"?\"\n\n path = \"?\"\n firstlineno = 5\n\n def fullsource(self):\n return None\n\n fullsource = property(fullsource)\n\n class FakeFrame(object):\n code = FakeCode()\n f_locals = {}\n f_globals = {}\n\n class FakeTracebackEntry(_pytest._code.Traceback.Entry):\n def __init__(self, tb, excinfo=None):\n self.lineno = 5 + 3\n\n @property\n def frame(self):\n return FakeFrame()\n\n class Traceback(_pytest._code.Traceback):\n Entry = FakeTracebackEntry\n\n class FakeExcinfo(_pytest._code.ExceptionInfo):\n typename = \"Foo\"\n value = Exception()\n\n def __init__(self):\n pass\n\n def exconly(self, tryshort):\n return \"EXC\"\n\n def errisinstance(self, cls):\n return False\n\n excinfo = FakeExcinfo()\n\n class FakeRawTB(object):\n tb_next = None\n\n tb = FakeRawTB()\n excinfo.traceback = Traceback(tb)\n\n fail = IOError()\n repr = pr.repr_excinfo(excinfo)\n assert repr.reprtraceback.reprentries[0].lines[0] == \"> ???\"\n if sys.version_info[0] >= 3:\n assert repr.chain[0][0].reprentries[0].lines[0] == \"> ???\"\n\n fail = py.error.ENOENT # noqa\n repr = pr.repr_excinfo(excinfo)\n assert repr.reprtraceback.reprentries[0].lines[0] == \"> ???\"\n if sys.version_info[0] >= 3:\n assert repr.chain[0][0].reprentries[0].lines[0] == \"> ???\"\n\n def test_repr_local(self):\n p = FormattedExcinfo(showlocals=True)\n loc = {\"y\": 5, \"z\": 7, \"x\": 3, \"@x\": 2, \"__builtins__\": {}}\n reprlocals = p.repr_locals(loc)\n assert reprlocals.lines\n assert reprlocals.lines[0] == \"__builtins__ = \"\n assert reprlocals.lines[1] == \"x = 3\"\n assert reprlocals.lines[2] == \"y = 5\"\n assert reprlocals.lines[3] == \"z = 7\"\n\n def test_repr_local_with_error(self):\n class ObjWithErrorInRepr:\n def __repr__(self):\n raise NotImplementedError\n\n p = FormattedExcinfo(showlocals=True, truncate_locals=False)\n loc = {\"x\": ObjWithErrorInRepr(), \"__builtins__\": {}}\n reprlocals = p.repr_locals(loc)\n assert reprlocals.lines\n assert reprlocals.lines[0] == \"__builtins__ = \"\n assert '[NotImplementedError(\"\") raised in repr()]' in reprlocals.lines[1]\n\n def test_repr_local_with_exception_in_class_property(self):\n class ExceptionWithBrokenClass(Exception):\n @property\n def __class__(self):\n raise TypeError(\"boom!\")\n\n class ObjWithErrorInRepr:\n def __repr__(self):\n raise ExceptionWithBrokenClass()\n\n p = FormattedExcinfo(showlocals=True, truncate_locals=False)\n loc = {\"x\": ObjWithErrorInRepr(), \"__builtins__\": {}}\n reprlocals = p.repr_locals(loc)\n assert reprlocals.lines\n assert reprlocals.lines[0] == \"__builtins__ = \"\n assert '[ExceptionWithBrokenClass(\"\") raised in repr()]' in reprlocals.lines[1]\n\n def test_repr_local_truncated(self):\n loc = {\"l\": [i for i in range(10)]}\n p = FormattedExcinfo(showlocals=True)\n truncated_reprlocals = p.repr_locals(loc)\n assert truncated_reprlocals.lines\n assert truncated_reprlocals.lines[0] == \"l = [0, 1, 2, 3, 4, 5, ...]\"\n\n q = FormattedExcinfo(showlocals=True, truncate_locals=False)\n full_reprlocals = q.repr_locals(loc)\n assert full_reprlocals.lines\n assert full_reprlocals.lines[0] == \"l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\"\n\n def test_repr_tracebackentry_lines(self, importasmod):\n mod = importasmod(\n \"\"\"\n def func1():\n raise ValueError(\"hello\\\\nworld\")\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.func1)\n excinfo.traceback = excinfo.traceback.filter()\n p = FormattedExcinfo()\n reprtb = p.repr_traceback_entry(excinfo.traceback[-1])\n\n # test as intermittent entry\n lines = reprtb.lines\n assert lines[0] == \" def func1():\"\n assert lines[1] == '> raise ValueError(\"hello\\\\nworld\")'\n\n # test as last entry\n p = FormattedExcinfo(showlocals=True)\n repr_entry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)\n lines = repr_entry.lines\n assert lines[0] == \" def func1():\"\n assert lines[1] == '> raise ValueError(\"hello\\\\nworld\")'\n assert lines[2] == \"E ValueError: hello\"\n assert lines[3] == \"E world\"\n assert not lines[4:]\n\n loc = repr_entry.reprlocals is not None\n loc = repr_entry.reprfileloc\n assert loc.path == mod.__file__\n assert loc.lineno == 3\n # assert loc.message == \"ValueError: hello\"\n\n def test_repr_tracebackentry_lines2(self, importasmod):\n mod = importasmod(\n \"\"\"\n def func1(m, x, y, z):\n raise ValueError(\"hello\\\\nworld\")\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.func1, \"m\" * 90, 5, 13, \"z\" * 120)\n excinfo.traceback = excinfo.traceback.filter()\n entry = excinfo.traceback[-1]\n p = FormattedExcinfo(funcargs=True)\n reprfuncargs = p.repr_args(entry)\n assert reprfuncargs.args[0] == (\"m\", repr(\"m\" * 90))\n assert reprfuncargs.args[1] == (\"x\", \"5\")\n assert reprfuncargs.args[2] == (\"y\", \"13\")\n assert reprfuncargs.args[3] == (\"z\", repr(\"z\" * 120))\n\n p = FormattedExcinfo(funcargs=True)\n repr_entry = p.repr_traceback_entry(entry)\n assert repr_entry.reprfuncargs.args == reprfuncargs.args\n tw = TWMock()\n repr_entry.toterminal(tw)\n assert tw.lines[0] == \"m = \" + repr(\"m\" * 90)\n assert tw.lines[1] == \"x = 5, y = 13\"\n assert tw.lines[2] == \"z = \" + repr(\"z\" * 120)\n\n def test_repr_tracebackentry_lines_var_kw_args(self, importasmod):\n mod = importasmod(\n \"\"\"\n def func1(x, *y, **z):\n raise ValueError(\"hello\\\\nworld\")\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.func1, \"a\", \"b\", c=\"d\")\n excinfo.traceback = excinfo.traceback.filter()\n entry = excinfo.traceback[-1]\n p = FormattedExcinfo(funcargs=True)\n reprfuncargs = p.repr_args(entry)\n assert reprfuncargs.args[0] == (\"x\", repr(\"a\"))\n assert reprfuncargs.args[1] == (\"y\", repr((\"b\",)))\n assert reprfuncargs.args[2] == (\"z\", repr({\"c\": \"d\"}))\n\n p = FormattedExcinfo(funcargs=True)\n repr_entry = p.repr_traceback_entry(entry)\n assert repr_entry.reprfuncargs.args == reprfuncargs.args\n tw = TWMock()\n repr_entry.toterminal(tw)\n assert tw.lines[0] == \"x = 'a', y = ('b',), z = {'c': 'd'}\"\n\n def test_repr_tracebackentry_short(self, importasmod):\n mod = importasmod(\n \"\"\"\n def func1():\n raise ValueError(\"hello\")\n def entry():\n func1()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n p = FormattedExcinfo(style=\"short\")\n reprtb = p.repr_traceback_entry(excinfo.traceback[-2])\n lines = reprtb.lines\n basename = py.path.local(mod.__file__).basename\n assert lines[0] == \" func1()\"\n assert basename in str(reprtb.reprfileloc.path)\n assert reprtb.reprfileloc.lineno == 5\n\n # test last entry\n p = FormattedExcinfo(style=\"short\")\n reprtb = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)\n lines = reprtb.lines\n assert lines[0] == ' raise ValueError(\"hello\")'\n assert lines[1] == \"E ValueError: hello\"\n assert basename in str(reprtb.reprfileloc.path)\n assert reprtb.reprfileloc.lineno == 3\n\n def test_repr_tracebackentry_no(self, importasmod):\n mod = importasmod(\n \"\"\"\n def func1():\n raise ValueError(\"hello\")\n def entry():\n func1()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n p = FormattedExcinfo(style=\"no\")\n p.repr_traceback_entry(excinfo.traceback[-2])\n\n p = FormattedExcinfo(style=\"no\")\n reprentry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)\n lines = reprentry.lines\n assert lines[0] == \"E ValueError: hello\"\n assert not lines[1:]\n\n def test_repr_traceback_tbfilter(self, importasmod):\n mod = importasmod(\n \"\"\"\n def f(x):\n raise ValueError(x)\n def entry():\n f(0)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n p = FormattedExcinfo(tbfilter=True)\n reprtb = p.repr_traceback(excinfo)\n assert len(reprtb.reprentries) == 2\n p = FormattedExcinfo(tbfilter=False)\n reprtb = p.repr_traceback(excinfo)\n assert len(reprtb.reprentries) == 3\n\n def test_traceback_short_no_source(self, importasmod, monkeypatch):\n mod = importasmod(\n \"\"\"\n def func1():\n raise ValueError(\"hello\")\n def entry():\n func1()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n from _pytest._code.code import Code\n\n monkeypatch.setattr(Code, \"path\", \"bogus\")\n excinfo.traceback[0].frame.code.path = \"bogus\"\n p = FormattedExcinfo(style=\"short\")\n reprtb = p.repr_traceback_entry(excinfo.traceback[-2])\n lines = reprtb.lines\n last_p = FormattedExcinfo(style=\"short\")\n last_reprtb = last_p.repr_traceback_entry(excinfo.traceback[-1], excinfo)\n last_lines = last_reprtb.lines\n monkeypatch.undo()\n assert lines[0] == \" func1()\"\n\n assert last_lines[0] == ' raise ValueError(\"hello\")'\n assert last_lines[1] == \"E ValueError: hello\"\n\n def test_repr_traceback_and_excinfo(self, importasmod):\n mod = importasmod(\n \"\"\"\n def f(x):\n raise ValueError(x)\n def entry():\n f(0)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n\n for style in (\"long\", \"short\"):\n p = FormattedExcinfo(style=style)\n reprtb = p.repr_traceback(excinfo)\n assert len(reprtb.reprentries) == 2\n assert reprtb.style == style\n assert not reprtb.extraline\n repr = p.repr_excinfo(excinfo)\n assert repr.reprtraceback\n assert len(repr.reprtraceback.reprentries) == len(reprtb.reprentries)\n if sys.version_info[0] >= 3:\n assert repr.chain[0][0]\n assert len(repr.chain[0][0].reprentries) == len(reprtb.reprentries)\n assert repr.reprcrash.path.endswith(\"mod.py\")\n assert repr.reprcrash.message == \"ValueError: 0\"\n\n def test_repr_traceback_with_invalid_cwd(self, importasmod, monkeypatch):\n mod = importasmod(\n \"\"\"\n def f(x):\n raise ValueError(x)\n def entry():\n f(0)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n\n p = FormattedExcinfo()\n\n def raiseos():\n raise OSError(2)\n\n monkeypatch.setattr(os, \"getcwd\", raiseos)\n assert p._makepath(__file__) == __file__\n p.repr_traceback(excinfo)\n\n def test_repr_excinfo_addouterr(self, importasmod):\n mod = importasmod(\n \"\"\"\n def entry():\n raise ValueError()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n repr = excinfo.getrepr()\n repr.addsection(\"title\", \"content\")\n twmock = TWMock()\n repr.toterminal(twmock)\n assert twmock.lines[-1] == \"content\"\n assert twmock.lines[-2] == (\"-\", \"title\")\n\n def test_repr_excinfo_reprcrash(self, importasmod):\n mod = importasmod(\n \"\"\"\n def entry():\n raise ValueError()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n repr = excinfo.getrepr()\n assert repr.reprcrash.path.endswith(\"mod.py\")\n assert repr.reprcrash.lineno == 3\n assert repr.reprcrash.message == \"ValueError\"\n assert str(repr.reprcrash).endswith(\"mod.py:3: ValueError\")\n\n def test_repr_traceback_recursion(self, importasmod):\n mod = importasmod(\n \"\"\"\n def rec2(x):\n return rec1(x+1)\n def rec1(x):\n return rec2(x-1)\n def entry():\n rec1(42)\n \"\"\"\n )\n excinfo = pytest.raises(RuntimeError, mod.entry)\n\n for style in (\"short\", \"long\", \"no\"):\n p = FormattedExcinfo(style=\"short\")\n reprtb = p.repr_traceback(excinfo)\n assert reprtb.extraline == \"!!! Recursion detected (same locals & position)\"\n assert str(reprtb)\n\n def test_reprexcinfo_getrepr(self, importasmod):\n mod = importasmod(\n \"\"\"\n def f(x):\n raise ValueError(x)\n def entry():\n f(0)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n\n for style in (\"short\", \"long\", \"no\"):\n for showlocals in (True, False):\n repr = excinfo.getrepr(style=style, showlocals=showlocals)\n if sys.version_info[0] < 3:\n assert isinstance(repr, ReprExceptionInfo)\n assert repr.reprtraceback.style == style\n if sys.version_info[0] >= 3:\n assert isinstance(repr, ExceptionChainRepr)\n for repr in repr.chain:\n assert repr[0].style == style\n\n def test_reprexcinfo_unicode(self):\n from _pytest._code.code import TerminalRepr\n\n class MyRepr(TerminalRepr):\n def toterminal(self, tw):\n tw.line(u\"я\")\n\n x = six.text_type(MyRepr())\n assert x == u\"я\"\n\n def test_toterminal_long(self, importasmod):\n mod = importasmod(\n \"\"\"\n def g(x):\n raise ValueError(x)\n def f():\n g(3)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.f)\n excinfo.traceback = excinfo.traceback.filter()\n repr = excinfo.getrepr()\n tw = TWMock()\n repr.toterminal(tw)\n assert tw.lines[0] == \"\"\n tw.lines.pop(0)\n assert tw.lines[0] == \" def f():\"\n assert tw.lines[1] == \"> g(3)\"\n assert tw.lines[2] == \"\"\n line = tw.get_write_msg(3)\n assert line.endswith(\"mod.py\")\n assert tw.lines[4] == (\":5: \")\n assert tw.lines[5] == (\"_ \", None)\n assert tw.lines[6] == \"\"\n assert tw.lines[7] == \" def g(x):\"\n assert tw.lines[8] == \"> raise ValueError(x)\"\n assert tw.lines[9] == \"E ValueError: 3\"\n assert tw.lines[10] == \"\"\n line = tw.get_write_msg(11)\n assert line.endswith(\"mod.py\")\n assert tw.lines[12] == \":3: ValueError\"\n\n def test_toterminal_long_missing_source(self, importasmod, tmpdir):\n mod = importasmod(\n \"\"\"\n def g(x):\n raise ValueError(x)\n def f():\n g(3)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.f)\n tmpdir.join(\"mod.py\").remove()\n excinfo.traceback = excinfo.traceback.filter()\n repr = excinfo.getrepr()\n tw = TWMock()\n repr.toterminal(tw)\n assert tw.lines[0] == \"\"\n tw.lines.pop(0)\n assert tw.lines[0] == \"> ???\"\n assert tw.lines[1] == \"\"\n line = tw.get_write_msg(2)\n assert line.endswith(\"mod.py\")\n assert tw.lines[3] == \":5: \"\n assert tw.lines[4] == (\"_ \", None)\n assert tw.lines[5] == \"\"\n assert tw.lines[6] == \"> ???\"\n assert tw.lines[7] == \"E ValueError: 3\"\n assert tw.lines[8] == \"\"\n line = tw.get_write_msg(9)\n assert line.endswith(\"mod.py\")\n assert tw.lines[10] == \":3: ValueError\"\n\n def test_toterminal_long_incomplete_source(self, importasmod, tmpdir):\n mod = importasmod(\n \"\"\"\n def g(x):\n raise ValueError(x)\n def f():\n g(3)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.f)\n tmpdir.join(\"mod.py\").write(\"asdf\")\n excinfo.traceback = excinfo.traceback.filter()\n repr = excinfo.getrepr()\n tw = TWMock()\n repr.toterminal(tw)\n assert tw.lines[0] == \"\"\n tw.lines.pop(0)\n assert tw.lines[0] == \"> ???\"\n assert tw.lines[1] == \"\"\n line = tw.get_write_msg(2)\n assert line.endswith(\"mod.py\")\n assert tw.lines[3] == \":5: \"\n assert tw.lines[4] == (\"_ \", None)\n assert tw.lines[5] == \"\"\n assert tw.lines[6] == \"> ???\"\n assert tw.lines[7] == \"E ValueError: 3\"\n assert tw.lines[8] == \"\"\n line = tw.get_write_msg(9)\n assert line.endswith(\"mod.py\")\n assert tw.lines[10] == \":3: ValueError\"\n\n def test_toterminal_long_filenames(self, importasmod):\n mod = importasmod(\n \"\"\"\n def f():\n raise ValueError()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.f)\n tw = TWMock()\n path = py.path.local(mod.__file__)\n old = path.dirpath().chdir()\n try:\n repr = excinfo.getrepr(abspath=False)\n repr.toterminal(tw)\n x = py.path.local().bestrelpath(path)\n if len(x) < len(str(path)):\n msg = tw.get_write_msg(-2)\n assert msg == \"mod.py\"\n assert tw.lines[-1] == \":3: ValueError\"\n\n repr = excinfo.getrepr(abspath=True)\n repr.toterminal(tw)\n msg = tw.get_write_msg(-2)\n assert msg == path\n line = tw.lines[-1]\n assert line == \":3: ValueError\"\n finally:\n old.chdir()\n\n @pytest.mark.parametrize(\n \"reproptions\",\n [\n {\n \"style\": style,\n \"showlocals\": showlocals,\n \"funcargs\": funcargs,\n \"tbfilter\": tbfilter,\n }\n for style in (\"long\", \"short\", \"no\")\n for showlocals in (True, False)\n for tbfilter in (True, False)\n for funcargs in (True, False)\n ],\n )\n def test_format_excinfo(self, importasmod, reproptions):\n mod = importasmod(\n \"\"\"\n def g(x):\n raise ValueError(x)\n def f():\n g(3)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.f)\n tw = py.io.TerminalWriter(stringio=True)\n repr = excinfo.getrepr(**reproptions)\n repr.toterminal(tw)\n assert tw.stringio.getvalue()\n\n def test_traceback_repr_style(self, importasmod):\n mod = importasmod(\n \"\"\"\n def f():\n g()\n def g():\n h()\n def h():\n i()\n def i():\n raise ValueError()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.f)\n excinfo.traceback = excinfo.traceback.filter()\n excinfo.traceback[1].set_repr_style(\"short\")\n excinfo.traceback[2].set_repr_style(\"short\")\n r = excinfo.getrepr(style=\"long\")\n tw = TWMock()\n r.toterminal(tw)\n for line in tw.lines:\n print(line)\n assert tw.lines[0] == \"\"\n assert tw.lines[1] == \" def f():\"\n assert tw.lines[2] == \"> g()\"\n assert tw.lines[3] == \"\"\n msg = tw.get_write_msg(4)\n assert msg.endswith(\"mod.py\")\n assert tw.lines[5] == \":3: \"\n assert tw.lines[6] == (\"_ \", None)\n tw.get_write_msg(7)\n assert tw.lines[8].endswith(\"in g\")\n assert tw.lines[9] == \" h()\"\n tw.get_write_msg(10)\n assert tw.lines[11].endswith(\"in h\")\n assert tw.lines[12] == \" i()\"\n assert tw.lines[13] == (\"_ \", None)\n assert tw.lines[14] == \"\"\n assert tw.lines[15] == \" def i():\"\n assert tw.lines[16] == \"> raise ValueError()\"\n assert tw.lines[17] == \"E ValueError\"\n assert tw.lines[18] == \"\"\n msg = tw.get_write_msg(19)\n msg.endswith(\"mod.py\")\n assert tw.lines[20] == \":9: ValueError\"\n\n @pytest.mark.skipif(\"sys.version_info[0] < 3\")\n def test_exc_chain_repr(self, importasmod):\n mod = importasmod(\n \"\"\"\n class Err(Exception):\n pass\n def f():\n try:\n g()\n except Exception as e:\n raise Err() from e\n finally:\n h()\n def g():\n raise ValueError()\n\n def h():\n raise AttributeError()\n \"\"\"\n )\n excinfo = pytest.raises(AttributeError, mod.f)\n r = excinfo.getrepr(style=\"long\")\n tw = TWMock()\n r.toterminal(tw)\n for line in tw.lines:\n print(line)\n assert tw.lines[0] == \"\"\n assert tw.lines[1] == \" def f():\"\n assert tw.lines[2] == \" try:\"\n assert tw.lines[3] == \"> g()\"\n assert tw.lines[4] == \"\"\n line = tw.get_write_msg(5)\n assert line.endswith(\"mod.py\")\n assert tw.lines[6] == \":6: \"\n assert tw.lines[7] == (\"_ \", None)\n assert tw.lines[8] == \"\"\n assert tw.lines[9] == \" def g():\"\n assert tw.lines[10] == \"> raise ValueError()\"\n assert tw.lines[11] == \"E ValueError\"\n assert tw.lines[12] == \"\"\n line = tw.get_write_msg(13)\n assert line.endswith(\"mod.py\")\n assert tw.lines[14] == \":12: ValueError\"\n assert tw.lines[15] == \"\"\n assert (\n tw.lines[16]\n == \"The above exception was the direct cause of the following exception:\"\n )\n assert tw.lines[17] == \"\"\n assert tw.lines[18] == \" def f():\"\n assert tw.lines[19] == \" try:\"\n assert tw.lines[20] == \" g()\"\n assert tw.lines[21] == \" except Exception as e:\"\n assert tw.lines[22] == \"> raise Err() from e\"\n assert tw.lines[23] == \"E test_exc_chain_repr0.mod.Err\"\n assert tw.lines[24] == \"\"\n line = tw.get_write_msg(25)\n assert line.endswith(\"mod.py\")\n assert tw.lines[26] == \":8: Err\"\n assert tw.lines[27] == \"\"\n assert (\n tw.lines[28]\n == \"During handling of the above exception, another exception occurred:\"\n )\n assert tw.lines[29] == \"\"\n assert tw.lines[30] == \" def f():\"\n assert tw.lines[31] == \" try:\"\n assert tw.lines[32] == \" g()\"\n assert tw.lines[33] == \" except Exception as e:\"\n assert tw.lines[34] == \" raise Err() from e\"\n assert tw.lines[35] == \" finally:\"\n assert tw.lines[36] == \"> h()\"\n assert tw.lines[37] == \"\"\n line = tw.get_write_msg(38)\n assert line.endswith(\"mod.py\")\n assert tw.lines[39] == \":10: \"\n assert tw.lines[40] == (\"_ \", None)\n assert tw.lines[41] == \"\"\n assert tw.lines[42] == \" def h():\"\n assert tw.lines[43] == \"> raise AttributeError()\"\n assert tw.lines[44] == \"E AttributeError\"\n assert tw.lines[45] == \"\"\n line = tw.get_write_msg(46)\n assert line.endswith(\"mod.py\")\n assert tw.lines[47] == \":15: AttributeError\"\n\n @pytest.mark.skipif(\"sys.version_info[0] < 3\")\n @pytest.mark.parametrize(\"mode\", [\"from_none\", \"explicit_suppress\"])\n def test_exc_repr_chain_suppression(self, importasmod, mode):\n \"\"\"Check that exc repr does not show chained exceptions in Python 3.\n - When the exception is raised with \"from None\"\n - Explicitly suppressed with \"chain=False\" to ExceptionInfo.getrepr().\n \"\"\"\n raise_suffix = \" from None\" if mode == \"from_none\" else \"\"\n mod = importasmod(\n \"\"\"\n def f():\n try:\n g()\n except Exception:\n raise AttributeError(){raise_suffix}\n def g():\n raise ValueError()\n \"\"\".format(\n raise_suffix=raise_suffix\n )\n )\n excinfo = pytest.raises(AttributeError, mod.f)\n r = excinfo.getrepr(style=\"long\", chain=mode != \"explicit_suppress\")\n tw = TWMock()\n r.toterminal(tw)\n for line in tw.lines:\n print(line)\n assert tw.lines[0] == \"\"\n assert tw.lines[1] == \" def f():\"\n assert tw.lines[2] == \" try:\"\n assert tw.lines[3] == \" g()\"\n assert tw.lines[4] == \" except Exception:\"\n assert tw.lines[5] == \"> raise AttributeError(){}\".format(\n raise_suffix\n )\n assert tw.lines[6] == \"E AttributeError\"\n assert tw.lines[7] == \"\"\n line = tw.get_write_msg(8)\n assert line.endswith(\"mod.py\")\n assert tw.lines[9] == \":6: AttributeError\"\n assert len(tw.lines) == 10\n\n @pytest.mark.skipif(\"sys.version_info[0] < 3\")\n @pytest.mark.parametrize(\n \"reason, description\",\n [\n (\n \"cause\",\n \"The above exception was the direct cause of the following exception:\",\n ),\n (\n \"context\",\n \"During handling of the above exception, another exception occurred:\",\n ),\n ],\n )\n def test_exc_chain_repr_without_traceback(self, importasmod, reason, description):\n \"\"\"\n Handle representation of exception chains where one of the exceptions doesn't have a\n real traceback, such as those raised in a subprocess submitted by the multiprocessing\n module (#1984).\n \"\"\"\n from _pytest.pytester import LineMatcher\n\n exc_handling_code = \" from e\" if reason == \"cause\" else \"\"\n mod = importasmod(\n \"\"\"\n def f():\n try:\n g()\n except Exception as e:\n raise RuntimeError('runtime problem'){exc_handling_code}\n def g():\n raise ValueError('invalid value')\n \"\"\".format(\n exc_handling_code=exc_handling_code\n )\n )\n\n with pytest.raises(RuntimeError) as excinfo:\n mod.f()\n\n # emulate the issue described in #1984\n attr = \"__%s__\" % reason\n getattr(excinfo.value, attr).__traceback__ = None\n\n r = excinfo.getrepr()\n tw = py.io.TerminalWriter(stringio=True)\n tw.hasmarkup = False\n r.toterminal(tw)\n\n matcher = LineMatcher(tw.stringio.getvalue().splitlines())\n matcher.fnmatch_lines(\n [\n \"ValueError: invalid value\",\n description,\n \"* except Exception as e:\",\n \"> * raise RuntimeError('runtime problem')\" + exc_handling_code,\n \"E *RuntimeError: runtime problem\",\n ]\n )\n\n @pytest.mark.skipif(\"sys.version_info[0] < 3\")\n def test_exc_chain_repr_cycle(self, importasmod):\n mod = importasmod(\n \"\"\"\n class Err(Exception):\n pass\n def fail():\n return 0 / 0\n def reraise():\n try:\n fail()\n except ZeroDivisionError as e:\n raise Err() from e\n def unreraise():\n try:\n reraise()\n except Err as e:\n raise e.__cause__\n \"\"\"\n )\n excinfo = pytest.raises(ZeroDivisionError, mod.unreraise)\n r = excinfo.getrepr(style=\"short\")\n tw = TWMock()\n r.toterminal(tw)\n out = \"\\n\".join(line for line in tw.lines if isinstance(line, str))\n expected_out = textwrap.dedent(\n \"\"\"\\\n :13: in unreraise\n reraise()\n :10: in reraise\n raise Err() from e\n E test_exc_chain_repr_cycle0.mod.Err\n\n During handling of the above exception, another exception occurred:\n :15: in unreraise\n raise e.__cause__\n :8: in reraise\n fail()\n :5: in fail\n return 0 / 0\n E ZeroDivisionError: division by zero\"\"\"\n )\n assert out == expected_out\n\n\n@pytest.mark.parametrize(\"style\", [\"short\", \"long\"])\n@pytest.mark.parametrize(\"encoding\", [None, \"utf8\", \"utf16\"])\ndef test_repr_traceback_with_unicode(style, encoding):\n msg = u\"☹\"\n if encoding is not None:\n msg = msg.encode(encoding)\n try:\n raise RuntimeError(msg)\n except RuntimeError:\n e_info = ExceptionInfo.from_current()\n formatter = FormattedExcinfo(style=style)\n repr_traceback = formatter.repr_traceback(e_info)\n assert repr_traceback is not None\n\n\ndef test_cwd_deleted(testdir):\n testdir.makepyfile(\n \"\"\"\n def test(tmpdir):\n tmpdir.chdir()\n tmpdir.remove()\n assert False\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 failed in *\"])\n assert \"INTERNALERROR\" not in result.stdout.str() + result.stderr.str()\n\n\n@pytest.mark.usefixtures(\"limited_recursion_depth\")\ndef test_exception_repr_extraction_error_on_recursion():\n \"\"\"\n Ensure we can properly detect a recursion error even\n if some locals raise error on comparison (#2459).\n \"\"\"\n from _pytest.pytester import LineMatcher\n\n class numpy_like(object):\n def __eq__(self, other):\n if type(other) is numpy_like:\n raise ValueError(\n \"The truth value of an array \"\n \"with more than one element is ambiguous.\"\n )\n\n def a(x):\n return b(numpy_like())\n\n def b(x):\n return a(numpy_like())\n\n with pytest.raises(RuntimeError) as excinfo:\n a(numpy_like())\n\n matcher = LineMatcher(str(excinfo.getrepr()).splitlines())\n matcher.fnmatch_lines(\n [\n \"!!! Recursion error detected, but an error occurred locating the origin of recursion.\",\n \"*The following exception happened*\",\n \"*ValueError: The truth value of an array*\",\n ]\n )\n\n\n@pytest.mark.usefixtures(\"limited_recursion_depth\")\ndef test_no_recursion_index_on_recursion_error():\n \"\"\"\n Ensure that we don't break in case we can't find the recursion index\n during a recursion error (#2486).\n \"\"\"\n\n class RecursionDepthError(object):\n def __getattr__(self, attr):\n return getattr(self, \"_\" + attr)\n\n with pytest.raises(RuntimeError) as excinfo:\n RecursionDepthError().trigger\n assert \"maximum recursion\" in str(excinfo.getrepr())\n"},{"col":4,"comment":"null","endLoc":158,"header":"def test_tuple(self)","id":6433,"name":"test_tuple","nodeType":"Function","startLoc":156,"text":"def test_tuple(self):\n with pytest.raises((KeyError, ValueError)):\n raise KeyError(\"oops\")"},{"col":0,"comment":"null","endLoc":1117,"header":"def test_log_set_path(testdir)","id":6435,"name":"test_log_set_path","nodeType":"Function","startLoc":1072,"text":"def test_log_set_path(testdir):\n report_dir_base = testdir.tmpdir.strpath\n\n testdir.makeini(\n \"\"\"\n [pytest]\n log_file_level = DEBUG\n log_cli=true\n \"\"\"\n )\n testdir.makeconftest(\n \"\"\"\n import os\n import pytest\n @pytest.hookimpl(hookwrapper=True, tryfirst=True)\n def pytest_runtest_setup(item):\n config = item.config\n logging_plugin = config.pluginmanager.get_plugin(\"logging-plugin\")\n report_file = os.path.join({}, item._request.node.name)\n logging_plugin.set_log_path(report_file)\n yield\n \"\"\".format(\n repr(report_dir_base)\n )\n )\n testdir.makepyfile(\n \"\"\"\n import logging\n logger = logging.getLogger(\"testcase-logger\")\n def test_first():\n logger.info(\"message from test 1\")\n assert True\n\n def test_second():\n logger.debug(\"message from test 2\")\n assert True\n \"\"\"\n )\n testdir.runpytest()\n with open(os.path.join(report_dir_base, \"test_first\"), \"r\") as rfh:\n content = rfh.read()\n assert \"message from test 1\" in content\n\n with open(os.path.join(report_dir_base, \"test_second\"), \"r\") as rfh:\n content = rfh.read()\n assert \"message from test 2\" in content"},{"col":4,"comment":"null","endLoc":174,"header":"def test_no_raise_message(self)","id":6436,"name":"test_no_raise_message","nodeType":"Function","startLoc":160,"text":"def test_no_raise_message(self):\n try:\n pytest.raises(ValueError, int, \"0\")\n except pytest.raises.Exception as e:\n assert e.msg == \"DID NOT RAISE {}\".format(repr(ValueError))\n else:\n assert False, \"Expected pytest.raises.Exception\"\n\n try:\n with pytest.raises(ValueError):\n pass\n except pytest.raises.Exception as e:\n assert e.msg == \"DID NOT RAISE {}\".format(repr(ValueError))\n else:\n assert False, \"Expected pytest.raises.Exception\""},{"fileName":"evaluate.py","filePath":"src/_pytest/mark","id":6437,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport os\nimport platform\nimport sys\nimport traceback\n\nimport six\n\nfrom ..outcomes import fail\nfrom ..outcomes import TEST_OUTCOME\n\n\ndef cached_eval(config, expr, d):\n if not hasattr(config, \"_evalcache\"):\n config._evalcache = {}\n try:\n return config._evalcache[expr]\n except KeyError:\n import _pytest._code\n\n exprcode = _pytest._code.compile(expr, mode=\"eval\")\n config._evalcache[expr] = x = eval(exprcode, d)\n return x\n\n\nclass MarkEvaluator(object):\n def __init__(self, item, name):\n self.item = item\n self._marks = None\n self._mark = None\n self._mark_name = name\n\n def __bool__(self):\n # dont cache here to prevent staleness\n return bool(self._get_marks())\n\n __nonzero__ = __bool__\n\n def wasvalid(self):\n return not hasattr(self, \"exc\")\n\n def _get_marks(self):\n return list(self.item.iter_markers(name=self._mark_name))\n\n def invalidraise(self, exc):\n raises = self.get(\"raises\")\n if not raises:\n return\n return not isinstance(exc, raises)\n\n def istrue(self):\n try:\n return self._istrue()\n except TEST_OUTCOME:\n self.exc = sys.exc_info()\n if isinstance(self.exc[1], SyntaxError):\n msg = [\" \" * (self.exc[1].offset + 4) + \"^\"]\n msg.append(\"SyntaxError: invalid syntax\")\n else:\n msg = traceback.format_exception_only(*self.exc[:2])\n fail(\n \"Error evaluating %r expression\\n\"\n \" %s\\n\"\n \"%s\" % (self._mark_name, self.expr, \"\\n\".join(msg)),\n pytrace=False,\n )\n\n def _getglobals(self):\n d = {\"os\": os, \"sys\": sys, \"platform\": platform, \"config\": self.item.config}\n if hasattr(self.item, \"obj\"):\n d.update(self.item.obj.__globals__)\n return d\n\n def _istrue(self):\n if hasattr(self, \"result\"):\n return self.result\n self._marks = self._get_marks()\n\n if self._marks:\n self.result = False\n for mark in self._marks:\n self._mark = mark\n if \"condition\" in mark.kwargs:\n args = (mark.kwargs[\"condition\"],)\n else:\n args = mark.args\n\n for expr in args:\n self.expr = expr\n if isinstance(expr, six.string_types):\n d = self._getglobals()\n result = cached_eval(self.item.config, expr, d)\n else:\n if \"reason\" not in mark.kwargs:\n # XXX better be checked at collection time\n msg = (\n \"you need to specify reason=STRING \"\n \"when using booleans as conditions.\"\n )\n fail(msg)\n result = bool(expr)\n if result:\n self.result = True\n self.reason = mark.kwargs.get(\"reason\", None)\n self.expr = expr\n return self.result\n\n if not args:\n self.result = True\n self.reason = mark.kwargs.get(\"reason\", None)\n return self.result\n return False\n\n def get(self, attr, default=None):\n if self._mark is None:\n return default\n return self._mark.kwargs.get(attr, default)\n\n def getexplanation(self):\n expl = getattr(self, \"reason\", None) or self.get(\"reason\", None)\n if not expl:\n if not hasattr(self, \"expr\"):\n return \"\"\n else:\n return \"condition: \" + str(self.expr)\n return expl\n"},{"fileName":"integration.py","filePath":"testing/python","id":6438,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport pytest\nfrom _pytest import python\nfrom _pytest import runner\n\n\nclass TestOEJSKITSpecials(object):\n def test_funcarg_non_pycollectobj(self, testdir): # rough jstests usage\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_pycollect_makeitem(collector, name, obj):\n if name == \"MyClass\":\n return MyCollector(name, parent=collector)\n class MyCollector(pytest.Collector):\n def reportinfo(self):\n return self.fspath, 3, \"xyz\"\n \"\"\"\n )\n modcol = testdir.getmodulecol(\n \"\"\"\n import pytest\n @pytest.fixture\n def arg1(request):\n return 42\n class MyClass(object):\n pass\n \"\"\"\n )\n # this hook finds funcarg factories\n rep = runner.collect_one_node(collector=modcol)\n clscol = rep.result[0]\n clscol.obj = lambda arg1: None\n clscol.funcargs = {}\n pytest._fillfuncargs(clscol)\n assert clscol.funcargs[\"arg1\"] == 42\n\n def test_autouse_fixture(self, testdir): # rough jstests usage\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_pycollect_makeitem(collector, name, obj):\n if name == \"MyClass\":\n return MyCollector(name, parent=collector)\n class MyCollector(pytest.Collector):\n def reportinfo(self):\n return self.fspath, 3, \"xyz\"\n \"\"\"\n )\n modcol = testdir.getmodulecol(\n \"\"\"\n import pytest\n @pytest.fixture(autouse=True)\n def hello():\n pass\n @pytest.fixture\n def arg1(request):\n return 42\n class MyClass(object):\n pass\n \"\"\"\n )\n # this hook finds funcarg factories\n rep = runner.collect_one_node(modcol)\n clscol = rep.result[0]\n clscol.obj = lambda: None\n clscol.funcargs = {}\n pytest._fillfuncargs(clscol)\n assert not clscol.funcargs\n\n\ndef test_wrapped_getfslineno():\n def func():\n pass\n\n def wrap(f):\n func.__wrapped__ = f\n func.patchings = [\"qwe\"]\n return func\n\n @wrap\n def wrapped_func(x, y, z):\n pass\n\n fs, lineno = python.getfslineno(wrapped_func)\n fs2, lineno2 = python.getfslineno(wrap)\n assert lineno > lineno2, \"getfslineno does not unwrap correctly\"\n\n\nclass TestMockDecoration(object):\n def test_wrapped_getfuncargnames(self):\n from _pytest.compat import getfuncargnames\n\n def wrap(f):\n def func():\n pass\n\n func.__wrapped__ = f\n return func\n\n @wrap\n def f(x):\n pass\n\n values = getfuncargnames(f)\n assert values == (\"x\",)\n\n @pytest.mark.xfail(\n strict=False, reason=\"getfuncargnames breaks if mock is imported\"\n )\n def test_wrapped_getfuncargnames_patching(self):\n from _pytest.compat import getfuncargnames\n\n def wrap(f):\n def func():\n pass\n\n func.__wrapped__ = f\n func.patchings = [\"qwe\"]\n return func\n\n @wrap\n def f(x, y, z):\n pass\n\n values = getfuncargnames(f)\n assert values == (\"y\", \"z\")\n\n def test_unittest_mock(self, testdir):\n pytest.importorskip(\"unittest.mock\")\n testdir.makepyfile(\n \"\"\"\n import unittest.mock\n class T(unittest.TestCase):\n @unittest.mock.patch(\"os.path.abspath\")\n def test_hello(self, abspath):\n import os\n os.path.abspath(\"hello\")\n abspath.assert_any_call(\"hello\")\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_unittest_mock_and_fixture(self, testdir):\n pytest.importorskip(\"unittest.mock\")\n testdir.makepyfile(\n \"\"\"\n import os.path\n import unittest.mock\n import pytest\n\n @pytest.fixture\n def inject_me():\n pass\n\n @unittest.mock.patch.object(os.path, \"abspath\",\n new=unittest.mock.MagicMock)\n def test_hello(inject_me):\n import os\n os.path.abspath(\"hello\")\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_unittest_mock_and_pypi_mock(self, testdir):\n pytest.importorskip(\"unittest.mock\")\n pytest.importorskip(\"mock\", \"1.0.1\")\n testdir.makepyfile(\n \"\"\"\n import mock\n import unittest.mock\n class TestBoth(object):\n @unittest.mock.patch(\"os.path.abspath\")\n def test_hello(self, abspath):\n import os\n os.path.abspath(\"hello\")\n abspath.assert_any_call(\"hello\")\n\n @mock.patch(\"os.path.abspath\")\n def test_hello_mock(self, abspath):\n import os\n os.path.abspath(\"hello\")\n abspath.assert_any_call(\"hello\")\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_mock(self, testdir):\n pytest.importorskip(\"mock\", \"1.0.1\")\n testdir.makepyfile(\n \"\"\"\n import os\n import unittest\n import mock\n\n class T(unittest.TestCase):\n @mock.patch(\"os.path.abspath\")\n def test_hello(self, abspath):\n os.path.abspath(\"hello\")\n abspath.assert_any_call(\"hello\")\n def mock_basename(path):\n return \"mock_basename\"\n @mock.patch(\"os.path.abspath\")\n @mock.patch(\"os.path.normpath\")\n @mock.patch(\"os.path.basename\", new=mock_basename)\n def test_someting(normpath, abspath, tmpdir):\n abspath.return_value = \"this\"\n os.path.normpath(os.path.abspath(\"hello\"))\n normpath.assert_any_call(\"this\")\n assert os.path.basename(\"123\") == \"mock_basename\"\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n calls = reprec.getcalls(\"pytest_runtest_logreport\")\n funcnames = [\n call.report.location[2] for call in calls if call.report.when == \"call\"\n ]\n assert funcnames == [\"T.test_hello\", \"test_someting\"]\n\n def test_mock_sorting(self, testdir):\n pytest.importorskip(\"mock\", \"1.0.1\")\n testdir.makepyfile(\n \"\"\"\n import os\n import mock\n\n @mock.patch(\"os.path.abspath\")\n def test_one(abspath):\n pass\n @mock.patch(\"os.path.abspath\")\n def test_two(abspath):\n pass\n @mock.patch(\"os.path.abspath\")\n def test_three(abspath):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n calls = reprec.getreports(\"pytest_runtest_logreport\")\n calls = [x for x in calls if x.when == \"call\"]\n names = [x.nodeid.split(\"::\")[-1] for x in calls]\n assert names == [\"test_one\", \"test_two\", \"test_three\"]\n\n def test_mock_double_patch_issue473(self, testdir):\n pytest.importorskip(\"mock\", \"1.0.1\")\n testdir.makepyfile(\n \"\"\"\n from mock import patch\n from pytest import mark\n\n @patch('os.getcwd')\n @patch('os.path')\n @mark.slow\n class TestSimple(object):\n def test_simple_thing(self, mock_path, mock_getcwd):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n\nclass TestReRunTests(object):\n def test_rerun(self, testdir):\n testdir.makeconftest(\n \"\"\"\n from _pytest.runner import runtestprotocol\n def pytest_runtest_protocol(item, nextitem):\n runtestprotocol(item, log=False, nextitem=nextitem)\n runtestprotocol(item, log=True, nextitem=nextitem)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n count = 0\n req = None\n @pytest.fixture\n def fix(request):\n global count, req\n assert request != req\n req = request\n print(\"fix count %s\" % count)\n count += 1\n def test_fix(fix):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *fix count 0*\n *fix count 1*\n \"\"\"\n )\n result.stdout.fnmatch_lines(\n \"\"\"\n *2 passed*\n \"\"\"\n )\n\n\ndef test_pytestconfig_is_session_scoped():\n from _pytest.fixtures import pytestconfig\n\n assert pytestconfig._pytestfixturefunction.scope == \"session\"\n\n\nclass TestNoselikeTestAttribute(object):\n def test_module_with_global_test(self, testdir):\n testdir.makepyfile(\n \"\"\"\n __test__ = False\n def test_hello():\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n assert not reprec.getfailedcollections()\n calls = reprec.getreports(\"pytest_runtest_logreport\")\n assert not calls\n\n def test_class_and_method(self, testdir):\n testdir.makepyfile(\n \"\"\"\n __test__ = True\n def test_func():\n pass\n test_func.__test__ = False\n\n class TestSome(object):\n __test__ = False\n def test_method(self):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n assert not reprec.getfailedcollections()\n calls = reprec.getreports(\"pytest_runtest_logreport\")\n assert not calls\n\n def test_unittest_class(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import unittest\n class TC(unittest.TestCase):\n def test_1(self):\n pass\n class TC2(unittest.TestCase):\n __test__ = False\n def test_2(self):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n assert not reprec.getfailedcollections()\n call = reprec.getcalls(\"pytest_collection_modifyitems\")[0]\n assert len(call.items) == 1\n assert call.items[0].cls.__name__ == \"TC\"\n\n def test_class_with_nasty_getattr(self, testdir):\n \"\"\"Make sure we handle classes with a custom nasty __getattr__ right.\n\n With a custom __getattr__ which e.g. returns a function (like with a\n RPC wrapper), we shouldn't assume this meant \"__test__ = True\".\n \"\"\"\n # https://github.com/pytest-dev/pytest/issues/1204\n testdir.makepyfile(\n \"\"\"\n class MetaModel(type):\n\n def __getattr__(cls, key):\n return lambda: None\n\n\n BaseModel = MetaModel('Model', (), {})\n\n\n class Model(BaseModel):\n\n __metaclass__ = MetaModel\n\n def test_blah(self):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n assert not reprec.getfailedcollections()\n call = reprec.getcalls(\"pytest_collection_modifyitems\")[0]\n assert not call.items\n\n\nclass TestParameterize(object):\n \"\"\"#351\"\"\"\n\n def test_idfn_marker(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n def idfn(param):\n if param == 0:\n return 'spam'\n elif param == 1:\n return 'ham'\n else:\n return None\n\n @pytest.mark.parametrize('a,b', [(0, 2), (1, 2)], ids=idfn)\n def test_params(a, b):\n pass\n \"\"\"\n )\n res = testdir.runpytest(\"--collect-only\")\n res.stdout.fnmatch_lines([\"*spam-2*\", \"*ham-2*\"])\n\n def test_idfn_fixture(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n def idfn(param):\n if param == 0:\n return 'spam'\n elif param == 1:\n return 'ham'\n else:\n return None\n\n @pytest.fixture(params=[0, 1], ids=idfn)\n def a(request):\n return request.param\n\n @pytest.fixture(params=[1, 2], ids=idfn)\n def b(request):\n return request.param\n\n def test_params(a, b):\n pass\n \"\"\"\n )\n res = testdir.runpytest(\"--collect-only\")\n res.stdout.fnmatch_lines([\"*spam-2*\", \"*ham-2*\"])\n"},{"className":"TestOEJSKITSpecials","col":0,"comment":"null","endLoc":69,"id":6439,"nodeType":"Class","startLoc":7,"text":"class TestOEJSKITSpecials(object):\n def test_funcarg_non_pycollectobj(self, testdir): # rough jstests usage\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_pycollect_makeitem(collector, name, obj):\n if name == \"MyClass\":\n return MyCollector(name, parent=collector)\n class MyCollector(pytest.Collector):\n def reportinfo(self):\n return self.fspath, 3, \"xyz\"\n \"\"\"\n )\n modcol = testdir.getmodulecol(\n \"\"\"\n import pytest\n @pytest.fixture\n def arg1(request):\n return 42\n class MyClass(object):\n pass\n \"\"\"\n )\n # this hook finds funcarg factories\n rep = runner.collect_one_node(collector=modcol)\n clscol = rep.result[0]\n clscol.obj = lambda arg1: None\n clscol.funcargs = {}\n pytest._fillfuncargs(clscol)\n assert clscol.funcargs[\"arg1\"] == 42\n\n def test_autouse_fixture(self, testdir): # rough jstests usage\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_pycollect_makeitem(collector, name, obj):\n if name == \"MyClass\":\n return MyCollector(name, parent=collector)\n class MyCollector(pytest.Collector):\n def reportinfo(self):\n return self.fspath, 3, \"xyz\"\n \"\"\"\n )\n modcol = testdir.getmodulecol(\n \"\"\"\n import pytest\n @pytest.fixture(autouse=True)\n def hello():\n pass\n @pytest.fixture\n def arg1(request):\n return 42\n class MyClass(object):\n pass\n \"\"\"\n )\n # this hook finds funcarg factories\n rep = runner.collect_one_node(modcol)\n clscol = rep.result[0]\n clscol.obj = lambda: None\n clscol.funcargs = {}\n pytest._fillfuncargs(clscol)\n assert not clscol.funcargs"},{"col":4,"comment":"null","endLoc":36,"header":"def test_funcarg_non_pycollectobj(self, testdir)","id":6440,"name":"test_funcarg_non_pycollectobj","nodeType":"Function","startLoc":8,"text":"def test_funcarg_non_pycollectobj(self, testdir): # rough jstests usage\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_pycollect_makeitem(collector, name, obj):\n if name == \"MyClass\":\n return MyCollector(name, parent=collector)\n class MyCollector(pytest.Collector):\n def reportinfo(self):\n return self.fspath, 3, \"xyz\"\n \"\"\"\n )\n modcol = testdir.getmodulecol(\n \"\"\"\n import pytest\n @pytest.fixture\n def arg1(request):\n return 42\n class MyClass(object):\n pass\n \"\"\"\n )\n # this hook finds funcarg factories\n rep = runner.collect_one_node(collector=modcol)\n clscol = rep.result[0]\n clscol.obj = lambda arg1: None\n clscol.funcargs = {}\n pytest._fillfuncargs(clscol)\n assert clscol.funcargs[\"arg1\"] == 42"},{"col":21,"endLoc":33,"id":6441,"nodeType":"Lambda","startLoc":33,"text":"lambda arg1: None"},{"col":4,"comment":"null","endLoc":69,"header":"def test_autouse_fixture(self, testdir)","id":6442,"name":"test_autouse_fixture","nodeType":"Function","startLoc":38,"text":"def test_autouse_fixture(self, testdir): # rough jstests usage\n testdir.makeconftest(\n \"\"\"\n import pytest\n def pytest_pycollect_makeitem(collector, name, obj):\n if name == \"MyClass\":\n return MyCollector(name, parent=collector)\n class MyCollector(pytest.Collector):\n def reportinfo(self):\n return self.fspath, 3, \"xyz\"\n \"\"\"\n )\n modcol = testdir.getmodulecol(\n \"\"\"\n import pytest\n @pytest.fixture(autouse=True)\n def hello():\n pass\n @pytest.fixture\n def arg1(request):\n return 42\n class MyClass(object):\n pass\n \"\"\"\n )\n # this hook finds funcarg factories\n rep = runner.collect_one_node(modcol)\n clscol = rep.result[0]\n clscol.obj = lambda: None\n clscol.funcargs = {}\n pytest._fillfuncargs(clscol)\n assert not clscol.funcargs"},{"col":4,"comment":"null","endLoc":185,"header":"def test_custom_raise_message(self)","id":6444,"name":"test_custom_raise_message","nodeType":"Function","startLoc":176,"text":"def test_custom_raise_message(self):\n message = \"TEST_MESSAGE\"\n try:\n with pytest.warns(PytestDeprecationWarning):\n with pytest.raises(ValueError, message=message):\n pass\n except pytest.raises.Exception as e:\n assert e.msg == message\n else:\n assert False, \"Expected pytest.raises.Exception\""},{"col":4,"comment":"\n Ensure pytest.raises does not leave a reference cycle (#1965).\n ","endLoc":212,"header":"@pytest.mark.parametrize(\"method\", [\"function\", \"with\"])\n def test_raises_cyclic_reference(self, method)","id":6445,"name":"test_raises_cyclic_reference","nodeType":"Function","startLoc":187,"text":"@pytest.mark.parametrize(\"method\", [\"function\", \"with\"])\n def test_raises_cyclic_reference(self, method):\n \"\"\"\n Ensure pytest.raises does not leave a reference cycle (#1965).\n \"\"\"\n import gc\n\n class T(object):\n def __call__(self):\n raise ValueError\n\n t = T()\n if method == \"function\":\n pytest.raises(ValueError, t)\n else:\n with pytest.raises(ValueError):\n t()\n\n # ensure both forms of pytest.raises don't leave exceptions in sys.exc_info()\n assert sys.exc_info() == (None, None, None)\n\n del t\n\n # ensure the t instance is not stuck in a cyclic reference\n for o in gc.get_objects():\n assert type(o) is not T"},{"id":6446,"name":"tidelift.rst","nodeType":"TextFile","path":"doc/en","text":"\n\n\n.. include:: ../../TIDELIFT.rst\n"},{"col":21,"endLoc":66,"id":6447,"nodeType":"Lambda","startLoc":66,"text":"lambda: None"},{"className":"TestMockDecoration","col":0,"comment":"null","endLoc":264,"id":6448,"nodeType":"Class","startLoc":90,"text":"class TestMockDecoration(object):\n def test_wrapped_getfuncargnames(self):\n from _pytest.compat import getfuncargnames\n\n def wrap(f):\n def func():\n pass\n\n func.__wrapped__ = f\n return func\n\n @wrap\n def f(x):\n pass\n\n values = getfuncargnames(f)\n assert values == (\"x\",)\n\n @pytest.mark.xfail(\n strict=False, reason=\"getfuncargnames breaks if mock is imported\"\n )\n def test_wrapped_getfuncargnames_patching(self):\n from _pytest.compat import getfuncargnames\n\n def wrap(f):\n def func():\n pass\n\n func.__wrapped__ = f\n func.patchings = [\"qwe\"]\n return func\n\n @wrap\n def f(x, y, z):\n pass\n\n values = getfuncargnames(f)\n assert values == (\"y\", \"z\")\n\n def test_unittest_mock(self, testdir):\n pytest.importorskip(\"unittest.mock\")\n testdir.makepyfile(\n \"\"\"\n import unittest.mock\n class T(unittest.TestCase):\n @unittest.mock.patch(\"os.path.abspath\")\n def test_hello(self, abspath):\n import os\n os.path.abspath(\"hello\")\n abspath.assert_any_call(\"hello\")\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_unittest_mock_and_fixture(self, testdir):\n pytest.importorskip(\"unittest.mock\")\n testdir.makepyfile(\n \"\"\"\n import os.path\n import unittest.mock\n import pytest\n\n @pytest.fixture\n def inject_me():\n pass\n\n @unittest.mock.patch.object(os.path, \"abspath\",\n new=unittest.mock.MagicMock)\n def test_hello(inject_me):\n import os\n os.path.abspath(\"hello\")\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n def test_unittest_mock_and_pypi_mock(self, testdir):\n pytest.importorskip(\"unittest.mock\")\n pytest.importorskip(\"mock\", \"1.0.1\")\n testdir.makepyfile(\n \"\"\"\n import mock\n import unittest.mock\n class TestBoth(object):\n @unittest.mock.patch(\"os.path.abspath\")\n def test_hello(self, abspath):\n import os\n os.path.abspath(\"hello\")\n abspath.assert_any_call(\"hello\")\n\n @mock.patch(\"os.path.abspath\")\n def test_hello_mock(self, abspath):\n import os\n os.path.abspath(\"hello\")\n abspath.assert_any_call(\"hello\")\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n\n def test_mock(self, testdir):\n pytest.importorskip(\"mock\", \"1.0.1\")\n testdir.makepyfile(\n \"\"\"\n import os\n import unittest\n import mock\n\n class T(unittest.TestCase):\n @mock.patch(\"os.path.abspath\")\n def test_hello(self, abspath):\n os.path.abspath(\"hello\")\n abspath.assert_any_call(\"hello\")\n def mock_basename(path):\n return \"mock_basename\"\n @mock.patch(\"os.path.abspath\")\n @mock.patch(\"os.path.normpath\")\n @mock.patch(\"os.path.basename\", new=mock_basename)\n def test_someting(normpath, abspath, tmpdir):\n abspath.return_value = \"this\"\n os.path.normpath(os.path.abspath(\"hello\"))\n normpath.assert_any_call(\"this\")\n assert os.path.basename(\"123\") == \"mock_basename\"\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n calls = reprec.getcalls(\"pytest_runtest_logreport\")\n funcnames = [\n call.report.location[2] for call in calls if call.report.when == \"call\"\n ]\n assert funcnames == [\"T.test_hello\", \"test_someting\"]\n\n def test_mock_sorting(self, testdir):\n pytest.importorskip(\"mock\", \"1.0.1\")\n testdir.makepyfile(\n \"\"\"\n import os\n import mock\n\n @mock.patch(\"os.path.abspath\")\n def test_one(abspath):\n pass\n @mock.patch(\"os.path.abspath\")\n def test_two(abspath):\n pass\n @mock.patch(\"os.path.abspath\")\n def test_three(abspath):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n calls = reprec.getreports(\"pytest_runtest_logreport\")\n calls = [x for x in calls if x.when == \"call\"]\n names = [x.nodeid.split(\"::\")[-1] for x in calls]\n assert names == [\"test_one\", \"test_two\", \"test_three\"]\n\n def test_mock_double_patch_issue473(self, testdir):\n pytest.importorskip(\"mock\", \"1.0.1\")\n testdir.makepyfile(\n \"\"\"\n from mock import patch\n from pytest import mark\n\n @patch('os.getcwd')\n @patch('os.path')\n @mark.slow\n class TestSimple(object):\n def test_simple_thing(self, mock_path, mock_getcwd):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":"null","endLoc":106,"header":"def test_wrapped_getfuncargnames(self)","id":6449,"name":"test_wrapped_getfuncargnames","nodeType":"Function","startLoc":91,"text":"def test_wrapped_getfuncargnames(self):\n from _pytest.compat import getfuncargnames\n\n def wrap(f):\n def func():\n pass\n\n func.__wrapped__ = f\n return func\n\n @wrap\n def f(x):\n pass\n\n values = getfuncargnames(f)\n assert values == (\"x\",)"},{"className":"TestTraceback_f_g_h","col":0,"comment":"null","endLoc":332,"id":6450,"nodeType":"Class","startLoc":123,"text":"class TestTraceback_f_g_h(object):\n def setup_method(self, method):\n try:\n h()\n except ValueError:\n self.excinfo = _pytest._code.ExceptionInfo.from_current()\n\n def test_traceback_entries(self):\n tb = self.excinfo.traceback\n entries = list(tb)\n assert len(tb) == 4 # maybe fragile test\n assert len(entries) == 4 # maybe fragile test\n names = [\"f\", \"g\", \"h\"]\n for entry in entries:\n try:\n names.remove(entry.frame.code.name)\n except ValueError:\n pass\n assert not names\n\n def test_traceback_entry_getsource(self):\n tb = self.excinfo.traceback\n s = str(tb[-1].getsource())\n assert s.startswith(\"def f():\")\n assert s.endswith(\"raise ValueError\")\n\n @failsonjython\n def test_traceback_entry_getsource_in_construct(self):\n source = _pytest._code.Source(\n \"\"\"\\\n def xyz():\n try:\n raise ValueError\n except somenoname:\n pass\n xyz()\n \"\"\"\n )\n try:\n exec(source.compile())\n except NameError:\n tb = _pytest._code.ExceptionInfo.from_current().traceback\n print(tb[-1].getsource())\n s = str(tb[-1].getsource())\n assert s.startswith(\"def xyz():\\n try:\")\n assert s.strip().endswith(\"except somenoname:\")\n\n def test_traceback_cut(self):\n co = _pytest._code.Code(f)\n path, firstlineno = co.path, co.firstlineno\n traceback = self.excinfo.traceback\n newtraceback = traceback.cut(path=path, firstlineno=firstlineno)\n assert len(newtraceback) == 1\n newtraceback = traceback.cut(path=path, lineno=firstlineno + 2)\n assert len(newtraceback) == 1\n\n def test_traceback_cut_excludepath(self, testdir):\n p = testdir.makepyfile(\"def f(): raise ValueError\")\n with pytest.raises(ValueError) as excinfo:\n p.pyimport().f()\n basedir = py.path.local(pytest.__file__).dirpath()\n newtraceback = excinfo.traceback.cut(excludepath=basedir)\n for x in newtraceback:\n if hasattr(x, \"path\"):\n assert not py.path.local(x.path).relto(basedir)\n assert newtraceback[-1].frame.code.path == p\n\n def test_traceback_filter(self):\n traceback = self.excinfo.traceback\n ntraceback = traceback.filter()\n assert len(ntraceback) == len(traceback) - 1\n\n @pytest.mark.parametrize(\n \"tracebackhide, matching\",\n [\n (lambda info: True, True),\n (lambda info: False, False),\n (operator.methodcaller(\"errisinstance\", ValueError), True),\n (operator.methodcaller(\"errisinstance\", IndexError), False),\n ],\n )\n def test_traceback_filter_selective(self, tracebackhide, matching):\n def f():\n #\n raise ValueError\n #\n\n def g():\n #\n __tracebackhide__ = tracebackhide\n f()\n #\n\n def h():\n #\n g()\n #\n\n excinfo = pytest.raises(ValueError, h)\n traceback = excinfo.traceback\n ntraceback = traceback.filter()\n print(\"old: {!r}\".format(traceback))\n print(\"new: {!r}\".format(ntraceback))\n\n if matching:\n assert len(ntraceback) == len(traceback) - 2\n else:\n # -1 because of the __tracebackhide__ in pytest.raises\n assert len(ntraceback) == len(traceback) - 1\n\n def test_traceback_recursion_index(self):\n def f(n):\n if n < 10:\n n += 1\n f(n)\n\n excinfo = pytest.raises(RuntimeError, f, 8)\n traceback = excinfo.traceback\n recindex = traceback.recursionindex()\n assert recindex == 3\n\n def test_traceback_only_specific_recursion_errors(self, monkeypatch):\n def f(n):\n if n == 0:\n raise RuntimeError(\"hello\")\n f(n - 1)\n\n excinfo = pytest.raises(RuntimeError, f, 25)\n monkeypatch.delattr(excinfo.traceback.__class__, \"recursionindex\")\n repr = excinfo.getrepr()\n assert \"RuntimeError: hello\" in str(repr.reprcrash)\n\n def test_traceback_no_recursion_index(self):\n def do_stuff():\n raise RuntimeError\n\n def reraise_me():\n import sys\n\n exc, val, tb = sys.exc_info()\n six.reraise(exc, val, tb)\n\n def f(n):\n try:\n do_stuff()\n except: # noqa\n reraise_me()\n\n excinfo = pytest.raises(RuntimeError, f, 8)\n traceback = excinfo.traceback\n recindex = traceback.recursionindex()\n assert recindex is None\n\n def test_traceback_messy_recursion(self):\n # XXX: simplified locally testable version\n decorator = pytest.importorskip(\"decorator\").decorator\n\n def log(f, *k, **kw):\n print(\"{} {}\".format(k, kw))\n f(*k, **kw)\n\n log = decorator(log)\n\n def fail():\n raise ValueError(\"\")\n\n fail = log(log(fail))\n\n excinfo = pytest.raises(ValueError, fail)\n assert excinfo.traceback.recursionindex() is None\n\n def test_traceback_getcrashentry(self):\n def i():\n __tracebackhide__ = True\n raise ValueError\n\n def h():\n i()\n\n def g():\n __tracebackhide__ = True\n h()\n\n def f():\n g()\n\n excinfo = pytest.raises(ValueError, f)\n tb = excinfo.traceback\n entry = tb.getcrashentry()\n co = _pytest._code.Code(h)\n assert entry.frame.code.path == co.path\n assert entry.lineno == co.firstlineno + 1\n assert entry.frame.code.name == \"h\"\n\n def test_traceback_getcrashentry_empty(self):\n def g():\n __tracebackhide__ = True\n raise ValueError\n\n def f():\n __tracebackhide__ = True\n g()\n\n excinfo = pytest.raises(ValueError, f)\n tb = excinfo.traceback\n entry = tb.getcrashentry()\n co = _pytest._code.Code(g)\n assert entry.frame.code.path == co.path\n assert entry.lineno == co.firstlineno + 2\n assert entry.frame.code.name == \"g\""},{"col":4,"comment":"null","endLoc":128,"header":"def setup_method(self, method)","id":6451,"name":"setup_method","nodeType":"Function","startLoc":124,"text":"def setup_method(self, method):\n try:\n h()\n except ValueError:\n self.excinfo = _pytest._code.ExceptionInfo.from_current()"},{"col":0,"comment":"null","endLoc":120,"header":"def h()","id":6452,"name":"h","nodeType":"Function","startLoc":117,"text":"def h():\n #\n g()\n #"},{"col":0,"comment":"null","endLoc":114,"header":"def g()","id":6453,"name":"g","nodeType":"Function","startLoc":110,"text":"def g():\n #\n __tracebackhide__ = True\n f()\n #"},{"col":0,"comment":"null","endLoc":107,"header":"def f()","id":6454,"name":"f","nodeType":"Function","startLoc":104,"text":"def f():\n #\n raise ValueError\n #"},{"col":4,"comment":"null","endLoc":127,"header":"@pytest.mark.xfail(\n strict=False, reason=\"getfuncargnames breaks if mock is imported\"\n )\n def test_wrapped_getfuncargnames_patching(self)","id":6455,"name":"test_wrapped_getfuncargnames_patching","nodeType":"Function","startLoc":108,"text":"@pytest.mark.xfail(\n strict=False, reason=\"getfuncargnames breaks if mock is imported\"\n )\n def test_wrapped_getfuncargnames_patching(self):\n from _pytest.compat import getfuncargnames\n\n def wrap(f):\n def func():\n pass\n\n func.__wrapped__ = f\n func.patchings = [\"qwe\"]\n return func\n\n @wrap\n def f(x, y, z):\n pass\n\n values = getfuncargnames(f)\n assert values == (\"y\", \"z\")"},{"col":4,"comment":"null","endLoc":141,"header":"def test_traceback_entries(self)","id":6456,"name":"test_traceback_entries","nodeType":"Function","startLoc":130,"text":"def test_traceback_entries(self):\n tb = self.excinfo.traceback\n entries = list(tb)\n assert len(tb) == 4 # maybe fragile test\n assert len(entries) == 4 # maybe fragile test\n names = [\"f\", \"g\", \"h\"]\n for entry in entries:\n try:\n names.remove(entry.frame.code.name)\n except ValueError:\n pass\n assert not names"},{"col":4,"comment":"null","endLoc":143,"header":"def test_unittest_mock(self, testdir)","id":6458,"name":"test_unittest_mock","nodeType":"Function","startLoc":129,"text":"def test_unittest_mock(self, testdir):\n pytest.importorskip(\"unittest.mock\")\n testdir.makepyfile(\n \"\"\"\n import unittest.mock\n class T(unittest.TestCase):\n @unittest.mock.patch(\"os.path.abspath\")\n def test_hello(self, abspath):\n import os\n os.path.abspath(\"hello\")\n abspath.assert_any_call(\"hello\")\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"fileName":"test_source.py","filePath":"testing/code","id":6459,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n# flake8: noqa\n# disable flake check on this file because some constructs are strange\n# or redundant on purpose and can't be disable on a line-by-line basis\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport ast\nimport inspect\nimport sys\n\nimport six\n\nimport _pytest._code\nimport pytest\nfrom _pytest._code import Source\n\nfailsonjython = pytest.mark.xfail(\"sys.platform.startswith('java')\")\n\n\ndef test_source_str_function():\n x = Source(\"3\")\n assert str(x) == \"3\"\n\n x = Source(\" 3\")\n assert str(x) == \"3\"\n\n x = Source(\n \"\"\"\n 3\n \"\"\"\n )\n assert str(x) == \"\\n3\"\n\n\ndef test_unicode():\n x = Source(u\"4\")\n assert str(x) == \"4\"\n co = _pytest._code.compile(u'u\"å\"', mode=\"eval\")\n val = eval(co)\n assert isinstance(val, six.text_type)\n\n\ndef test_source_from_function():\n source = _pytest._code.Source(test_source_str_function)\n assert str(source).startswith(\"def test_source_str_function():\")\n\n\ndef test_source_from_method():\n class TestClass(object):\n def test_method(self):\n pass\n\n source = _pytest._code.Source(TestClass().test_method)\n assert source.lines == [\"def test_method(self):\", \" pass\"]\n\n\ndef test_source_from_lines():\n lines = [\"a \\n\", \"b\\n\", \"c\"]\n source = _pytest._code.Source(lines)\n assert source.lines == [\"a \", \"b\", \"c\"]\n\n\ndef test_source_from_inner_function():\n def f():\n pass\n\n source = _pytest._code.Source(f, deindent=False)\n assert str(source).startswith(\" def f():\")\n source = _pytest._code.Source(f)\n assert str(source).startswith(\"def f():\")\n\n\ndef test_source_putaround_simple():\n source = Source(\"raise ValueError\")\n source = source.putaround(\n \"try:\",\n \"\"\"\\\n except ValueError:\n x = 42\n else:\n x = 23\"\"\",\n )\n assert (\n str(source)\n == \"\"\"\\\ntry:\n raise ValueError\nexcept ValueError:\n x = 42\nelse:\n x = 23\"\"\"\n )\n\n\ndef test_source_putaround():\n source = Source()\n source = source.putaround(\n \"\"\"\n if 1:\n x=1\n \"\"\"\n )\n assert str(source).strip() == \"if 1:\\n x=1\"\n\n\ndef test_source_strips():\n source = Source(\"\")\n assert source == Source()\n assert str(source) == \"\"\n assert source.strip() == source\n\n\ndef test_source_strip_multiline():\n source = Source()\n source.lines = [\"\", \" hello\", \" \"]\n source2 = source.strip()\n assert source2.lines == [\" hello\"]\n\n\ndef test_syntaxerror_rerepresentation():\n ex = pytest.raises(SyntaxError, _pytest._code.compile, \"xyz xyz\")\n assert ex.value.lineno == 1\n assert ex.value.offset in (4, 5, 7) # XXX pypy/jython versus cpython?\n assert ex.value.text.strip(), \"x x\"\n\n\ndef test_isparseable():\n assert Source(\"hello\").isparseable()\n assert Source(\"if 1:\\n pass\").isparseable()\n assert Source(\" \\nif 1:\\n pass\").isparseable()\n assert not Source(\"if 1:\\n\").isparseable()\n assert not Source(\" \\nif 1:\\npass\").isparseable()\n assert not Source(chr(0)).isparseable()\n\n\nclass TestAccesses(object):\n source = Source(\n \"\"\"\\\n def f(x):\n pass\n def g(x):\n pass\n \"\"\"\n )\n\n def test_getrange(self):\n x = self.source[0:2]\n assert x.isparseable()\n assert len(x.lines) == 2\n assert str(x) == \"def f(x):\\n pass\"\n\n def test_getline(self):\n x = self.source[0]\n assert x == \"def f(x):\"\n\n def test_len(self):\n assert len(self.source) == 4\n\n def test_iter(self):\n values = [x for x in self.source]\n assert len(values) == 4\n\n\nclass TestSourceParsingAndCompiling(object):\n source = Source(\n \"\"\"\\\n def f(x):\n assert (x ==\n 3 +\n 4)\n \"\"\"\n ).strip()\n\n def test_compile(self):\n co = _pytest._code.compile(\"x=3\")\n d = {}\n exec(co, d)\n assert d[\"x\"] == 3\n\n def test_compile_and_getsource_simple(self):\n co = _pytest._code.compile(\"x=3\")\n exec(co)\n source = _pytest._code.Source(co)\n assert str(source) == \"x=3\"\n\n def test_compile_and_getsource_through_same_function(self):\n def gensource(source):\n return _pytest._code.compile(source)\n\n co1 = gensource(\n \"\"\"\n def f():\n raise KeyError()\n \"\"\"\n )\n co2 = gensource(\n \"\"\"\n def f():\n raise ValueError()\n \"\"\"\n )\n source1 = inspect.getsource(co1)\n assert \"KeyError\" in source1\n source2 = inspect.getsource(co2)\n assert \"ValueError\" in source2\n\n def test_getstatement(self):\n # print str(self.source)\n ass = str(self.source[1:])\n for i in range(1, 4):\n # print \"trying start in line %r\" % self.source[i]\n s = self.source.getstatement(i)\n # x = s.deindent()\n assert str(s) == ass\n\n def test_getstatementrange_triple_quoted(self):\n # print str(self.source)\n source = Source(\n \"\"\"hello('''\n ''')\"\"\"\n )\n s = source.getstatement(0)\n assert s == str(source)\n s = source.getstatement(1)\n assert s == str(source)\n\n def test_getstatementrange_within_constructs(self):\n source = Source(\n \"\"\"\\\n try:\n try:\n raise ValueError\n except SomeThing:\n pass\n finally:\n 42\n \"\"\"\n )\n assert len(source) == 7\n # check all lineno's that could occur in a traceback\n # assert source.getstatementrange(0) == (0, 7)\n # assert source.getstatementrange(1) == (1, 5)\n assert source.getstatementrange(2) == (2, 3)\n assert source.getstatementrange(3) == (3, 4)\n assert source.getstatementrange(4) == (4, 5)\n # assert source.getstatementrange(5) == (0, 7)\n assert source.getstatementrange(6) == (6, 7)\n\n def test_getstatementrange_bug(self):\n source = Source(\n \"\"\"\\\n try:\n x = (\n y +\n z)\n except:\n pass\n \"\"\"\n )\n assert len(source) == 6\n assert source.getstatementrange(2) == (1, 4)\n\n def test_getstatementrange_bug2(self):\n source = Source(\n \"\"\"\\\n assert (\n 33\n ==\n [\n X(3,\n b=1, c=2\n ),\n ]\n )\n \"\"\"\n )\n assert len(source) == 9\n assert source.getstatementrange(5) == (0, 9)\n\n def test_getstatementrange_ast_issue58(self):\n source = Source(\n \"\"\"\\\n\n def test_some():\n for a in [a for a in\n CAUSE_ERROR]: pass\n\n x = 3\n \"\"\"\n )\n assert getstatement(2, source).lines == source.lines[2:3]\n assert getstatement(3, source).lines == source.lines[3:4]\n\n def test_getstatementrange_out_of_bounds_py3(self):\n source = Source(\"if xxx:\\n from .collections import something\")\n r = source.getstatementrange(1)\n assert r == (1, 2)\n\n def test_getstatementrange_with_syntaxerror_issue7(self):\n source = Source(\":\")\n pytest.raises(SyntaxError, lambda: source.getstatementrange(0))\n\n def test_compile_to_ast(self):\n source = Source(\"x = 4\")\n mod = source.compile(flag=ast.PyCF_ONLY_AST)\n assert isinstance(mod, ast.Module)\n compile(mod, \"\", \"exec\")\n\n def test_compile_and_getsource(self):\n co = self.source.compile()\n exec(co, globals())\n f(7)\n excinfo = pytest.raises(AssertionError, f, 6)\n frame = excinfo.traceback[-1].frame\n stmt = frame.code.fullsource.getstatement(frame.lineno)\n assert str(stmt).strip().startswith(\"assert\")\n\n @pytest.mark.parametrize(\"name\", [\"\", None, \"my\"])\n def test_compilefuncs_and_path_sanity(self, name):\n def check(comp, name):\n co = comp(self.source, name)\n if not name:\n expected = \"codegen %s:%d>\" % (mypath, mylineno + 2 + 2)\n else:\n expected = \"codegen %r %s:%d>\" % (name, mypath, mylineno + 2 + 2)\n fn = co.co_filename\n assert fn.endswith(expected)\n\n mycode = _pytest._code.Code(self.test_compilefuncs_and_path_sanity)\n mylineno = mycode.firstlineno\n mypath = mycode.path\n\n for comp in _pytest._code.compile, _pytest._code.Source.compile:\n check(comp, name)\n\n def test_offsetless_synerr(self):\n pytest.raises(SyntaxError, _pytest._code.compile, \"lambda a,a: 0\", mode=\"eval\")\n\n\ndef test_getstartingblock_singleline():\n class A(object):\n def __init__(self, *args):\n frame = sys._getframe(1)\n self.source = _pytest._code.Frame(frame).statement\n\n x = A(\"x\", \"y\")\n\n values = [i for i in x.source.lines if i.strip()]\n assert len(values) == 1\n\n\ndef test_getline_finally():\n def c():\n pass\n\n with pytest.raises(TypeError) as excinfo:\n teardown = None\n try:\n c(1)\n finally:\n if teardown:\n teardown()\n source = excinfo.traceback[-1].statement\n assert str(source).strip() == \"c(1)\"\n\n\ndef test_getfuncsource_dynamic():\n source = \"\"\"\n def f():\n raise ValueError\n\n def g(): pass\n \"\"\"\n co = _pytest._code.compile(source)\n exec(co, globals())\n assert str(_pytest._code.Source(f)).strip() == \"def f():\\n raise ValueError\"\n assert str(_pytest._code.Source(g)).strip() == \"def g(): pass\"\n\n\ndef test_getfuncsource_with_multine_string():\n def f():\n c = \"\"\"while True:\n pass\n\"\"\"\n\n expected = '''\\\n def f():\n c = \"\"\"while True:\n pass\n\"\"\"\n'''\n assert str(_pytest._code.Source(f)) == expected.rstrip()\n\n\ndef test_deindent():\n from _pytest._code.source import deindent as deindent\n\n assert deindent([\"\\tfoo\", \"\\tbar\"]) == [\"foo\", \"bar\"]\n\n source = \"\"\"\\\n def f():\n def g():\n pass\n \"\"\"\n lines = deindent(source.splitlines())\n assert lines == [\"def f():\", \" def g():\", \" pass\"]\n\n\ndef test_source_of_class_at_eof_without_newline(tmpdir, _sys_snapshot):\n # this test fails because the implicit inspect.getsource(A) below\n # does not return the \"x = 1\" last line.\n source = _pytest._code.Source(\n \"\"\"\n class A(object):\n def method(self):\n x = 1\n \"\"\"\n )\n path = tmpdir.join(\"a.py\")\n path.write(source)\n s2 = _pytest._code.Source(tmpdir.join(\"a.py\").pyimport().A)\n assert str(source).strip() == str(s2).strip()\n\n\nif True:\n\n def x():\n pass\n\n\ndef test_getsource_fallback():\n from _pytest._code.source import getsource\n\n expected = \"\"\"def x():\n pass\"\"\"\n src = getsource(x)\n assert src == expected\n\n\ndef test_idem_compile_and_getsource():\n from _pytest._code.source import getsource\n\n expected = \"def x(): pass\"\n co = _pytest._code.compile(expected)\n src = getsource(co)\n assert src == expected\n\n\ndef test_findsource_fallback():\n from _pytest._code.source import findsource\n\n src, lineno = findsource(x)\n assert \"test_findsource_simple\" in str(src)\n assert src[lineno] == \" def x():\"\n\n\ndef test_findsource():\n from _pytest._code.source import findsource\n\n co = _pytest._code.compile(\n \"\"\"if 1:\n def x():\n pass\n\"\"\"\n )\n\n src, lineno = findsource(co)\n assert \"if 1:\" in str(src)\n\n d = {}\n eval(co, d)\n src, lineno = findsource(d[\"x\"])\n assert \"if 1:\" in str(src)\n assert src[lineno] == \" def x():\"\n\n\ndef test_getfslineno():\n from _pytest._code import getfslineno\n\n def f(x):\n pass\n\n fspath, lineno = getfslineno(f)\n\n assert fspath.basename == \"test_source.py\"\n assert lineno == _pytest._code.getrawcode(f).co_firstlineno - 1 # see findsource\n\n class A(object):\n pass\n\n fspath, lineno = getfslineno(A)\n\n _, A_lineno = inspect.findsource(A)\n assert fspath.basename == \"test_source.py\"\n assert lineno == A_lineno\n\n assert getfslineno(3) == (\"\", -1)\n\n class B(object):\n pass\n\n B.__name__ = \"B2\"\n assert getfslineno(B)[1] == -1\n\n\ndef test_code_of_object_instance_with_call():\n class A(object):\n pass\n\n pytest.raises(TypeError, lambda: _pytest._code.Source(A()))\n\n class WithCall(object):\n def __call__(self):\n pass\n\n code = _pytest._code.Code(WithCall())\n assert \"pass\" in str(code.source())\n\n class Hello(object):\n def __call__(self):\n pass\n\n pytest.raises(TypeError, lambda: _pytest._code.Code(Hello))\n\n\ndef getstatement(lineno, source):\n from _pytest._code.source import getstatementrange_ast\n\n source = _pytest._code.Source(source, deindent=False)\n ast, start, end = getstatementrange_ast(lineno, source)\n return source[start:end]\n\n\ndef test_oneline():\n source = getstatement(0, \"raise ValueError\")\n assert str(source) == \"raise ValueError\"\n\n\ndef test_comment_and_no_newline_at_end():\n from _pytest._code.source import getstatementrange_ast\n\n source = Source(\n [\n \"def test_basic_complex():\",\n \" assert 1 == 2\",\n \"# vim: filetype=pyopencl:fdm=marker\",\n ]\n )\n ast, start, end = getstatementrange_ast(1, source)\n assert end == 2\n\n\ndef test_oneline_and_comment():\n source = getstatement(0, \"raise ValueError\\n#hello\")\n assert str(source) == \"raise ValueError\"\n\n\ndef test_comments():\n source = '''def test():\n \"comment 1\"\n x = 1\n # comment 2\n # comment 3\n\n assert False\n\n\"\"\"\ncomment 4\n\"\"\"\n'''\n for line in range(2, 6):\n assert str(getstatement(line, source)) == \" x = 1\"\n if sys.version_info >= (3, 8) or hasattr(sys, \"pypy_version_info\"):\n tqs_start = 8\n else:\n tqs_start = 10\n assert str(getstatement(10, source)) == '\"\"\"'\n for line in range(6, tqs_start):\n assert str(getstatement(line, source)) == \" assert False\"\n for line in range(tqs_start, 10):\n assert str(getstatement(line, source)) == '\"\"\"\\ncomment 4\\n\"\"\"'\n\n\ndef test_comment_in_statement():\n source = \"\"\"test(foo=1,\n # comment 1\n bar=2)\n\"\"\"\n for line in range(1, 3):\n assert (\n str(getstatement(line, source))\n == \"test(foo=1,\\n # comment 1\\n bar=2)\"\n )\n\n\ndef test_single_line_else():\n source = getstatement(1, \"if False: 2\\nelse: 3\")\n assert str(source) == \"else: 3\"\n\n\ndef test_single_line_finally():\n source = getstatement(1, \"try: 1\\nfinally: 3\")\n assert str(source) == \"finally: 3\"\n\n\ndef test_issue55():\n source = (\n \"def round_trip(dinp):\\n assert 1 == dinp\\n\"\n 'def test_rt():\\n round_trip(\"\"\"\\n\"\"\")\\n'\n )\n s = getstatement(3, source)\n assert str(s) == ' round_trip(\"\"\"\\n\"\"\")'\n\n\ndef test_multiline():\n source = getstatement(\n 0,\n \"\"\"\\\nraise ValueError(\n 23\n)\nx = 3\n\"\"\",\n )\n assert str(source) == \"raise ValueError(\\n 23\\n)\"\n\n\nclass TestTry(object):\n source = \"\"\"\\\ntry:\n raise ValueError\nexcept Something:\n raise IndexError(1)\nelse:\n raise KeyError()\n\"\"\"\n\n def test_body(self):\n source = getstatement(1, self.source)\n assert str(source) == \" raise ValueError\"\n\n def test_except_line(self):\n source = getstatement(2, self.source)\n assert str(source) == \"except Something:\"\n\n def test_except_body(self):\n source = getstatement(3, self.source)\n assert str(source) == \" raise IndexError(1)\"\n\n def test_else(self):\n source = getstatement(5, self.source)\n assert str(source) == \" raise KeyError()\"\n\n\nclass TestTryFinally(object):\n source = \"\"\"\\\ntry:\n raise ValueError\nfinally:\n raise IndexError(1)\n\"\"\"\n\n def test_body(self):\n source = getstatement(1, self.source)\n assert str(source) == \" raise ValueError\"\n\n def test_finally(self):\n source = getstatement(3, self.source)\n assert str(source) == \" raise IndexError(1)\"\n\n\nclass TestIf(object):\n source = \"\"\"\\\nif 1:\n y = 3\nelif False:\n y = 5\nelse:\n y = 7\n\"\"\"\n\n def test_body(self):\n source = getstatement(1, self.source)\n assert str(source) == \" y = 3\"\n\n def test_elif_clause(self):\n source = getstatement(2, self.source)\n assert str(source) == \"elif False:\"\n\n def test_elif(self):\n source = getstatement(3, self.source)\n assert str(source) == \" y = 5\"\n\n def test_else(self):\n source = getstatement(5, self.source)\n assert str(source) == \" y = 7\"\n\n\ndef test_semicolon():\n s = \"\"\"\\\nhello ; pytest.skip()\n\"\"\"\n source = getstatement(0, s)\n assert str(source) == s.strip()\n\n\ndef test_def_online():\n s = \"\"\"\\\ndef func(): raise ValueError(42)\n\ndef something():\n pass\n\"\"\"\n source = getstatement(0, s)\n assert str(source) == \"def func(): raise ValueError(42)\"\n\n\ndef XXX_test_expression_multiline():\n source = \"\"\"\\\nsomething\n'''\n'''\"\"\"\n result = getstatement(1, source)\n assert str(result) == \"'''\\n'''\"\n\n\ndef test_getstartingblock_multiline():\n class A(object):\n def __init__(self, *args):\n frame = sys._getframe(1)\n self.source = _pytest._code.Frame(frame).statement\n\n # fmt: off\n x = A('x',\n 'y'\n ,\n 'z')\n # fmt: on\n values = [i for i in x.source.lines if i.strip()]\n assert len(values) == 4\n"},{"className":"TestAccesses","col":0,"comment":"null","endLoc":163,"id":6460,"nodeType":"Class","startLoc":138,"text":"class TestAccesses(object):\n source = Source(\n \"\"\"\\\n def f(x):\n pass\n def g(x):\n pass\n \"\"\"\n )\n\n def test_getrange(self):\n x = self.source[0:2]\n assert x.isparseable()\n assert len(x.lines) == 2\n assert str(x) == \"def f(x):\\n pass\"\n\n def test_getline(self):\n x = self.source[0]\n assert x == \"def f(x):\"\n\n def test_len(self):\n assert len(self.source) == 4\n\n def test_iter(self):\n values = [x for x in self.source]\n assert len(values) == 4"},{"col":4,"comment":"null","endLoc":152,"header":"def test_getrange(self)","id":6461,"name":"test_getrange","nodeType":"Function","startLoc":148,"text":"def test_getrange(self):\n x = self.source[0:2]\n assert x.isparseable()\n assert len(x.lines) == 2\n assert str(x) == \"def f(x):\\n pass\""},{"col":4,"comment":"null","endLoc":147,"header":"def test_traceback_entry_getsource(self)","id":6462,"name":"test_traceback_entry_getsource","nodeType":"Function","startLoc":143,"text":"def test_traceback_entry_getsource(self):\n tb = self.excinfo.traceback\n s = str(tb[-1].getsource())\n assert s.startswith(\"def f():\")\n assert s.endswith(\"raise ValueError\")"},{"col":4,"comment":"Return the collection node of a file.\n\n :param config: :py:class:`_pytest.config.Config` instance, see\n :py:meth:`parseconfig` and :py:meth:`parseconfigure` to create the\n configuration\n\n :param arg: a :py:class:`py.path.local` instance of the file\n\n ","endLoc":709,"header":"def getnode(self, config, arg)","id":6463,"name":"getnode","nodeType":"Function","startLoc":693,"text":"def getnode(self, config, arg):\n \"\"\"Return the collection node of a file.\n\n :param config: :py:class:`_pytest.config.Config` instance, see\n :py:meth:`parseconfig` and :py:meth:`parseconfigure` to create the\n configuration\n\n :param arg: a :py:class:`py.path.local` instance of the file\n\n \"\"\"\n session = Session(config)\n assert \"::\" not in str(arg)\n p = py.path.local(arg)\n config.hook.pytest_sessionstart(session=session)\n res = session.perform_collect([str(p)], genitems=False)[0]\n config.hook.pytest_sessionfinish(session=session, exitstatus=EXIT_OK)\n return res"},{"col":4,"comment":"null","endLoc":168,"header":"@failsonjython\n def test_traceback_entry_getsource_in_construct(self)","id":6464,"name":"test_traceback_entry_getsource_in_construct","nodeType":"Function","startLoc":149,"text":"@failsonjython\n def test_traceback_entry_getsource_in_construct(self):\n source = _pytest._code.Source(\n \"\"\"\\\n def xyz():\n try:\n raise ValueError\n except somenoname:\n pass\n xyz()\n \"\"\"\n )\n try:\n exec(source.compile())\n except NameError:\n tb = _pytest._code.ExceptionInfo.from_current().traceback\n print(tb[-1].getsource())\n s = str(tb[-1].getsource())\n assert s.startswith(\"def xyz():\\n try:\")\n assert s.strip().endswith(\"except somenoname:\")"},{"col":4,"comment":"null","endLoc":229,"header":"def test_raises_match(self)","id":6465,"name":"test_raises_match","nodeType":"Function","startLoc":214,"text":"def test_raises_match(self):\n msg = r\"with base \\d+\"\n with pytest.raises(ValueError, match=msg):\n int(\"asdf\")\n\n msg = \"with base 10\"\n with pytest.raises(ValueError, match=msg):\n int(\"asdf\")\n\n msg = \"with base 16\"\n expr = r\"Pattern '{}' not found in \\\"invalid literal for int\\(\\) with base 10: 'asdf'\\\"\".format(\n msg\n )\n with pytest.raises(AssertionError, match=expr):\n with pytest.raises(ValueError, match=msg):\n int(\"asdf\", base=10)"},{"col":4,"comment":"null","endLoc":165,"header":"def test_unittest_mock_and_fixture(self, testdir)","id":6466,"name":"test_unittest_mock_and_fixture","nodeType":"Function","startLoc":145,"text":"def test_unittest_mock_and_fixture(self, testdir):\n pytest.importorskip(\"unittest.mock\")\n testdir.makepyfile(\n \"\"\"\n import os.path\n import unittest.mock\n import pytest\n\n @pytest.fixture\n def inject_me():\n pass\n\n @unittest.mock.patch.object(os.path, \"abspath\",\n new=unittest.mock.MagicMock)\n def test_hello(inject_me):\n import os\n os.path.abspath(\"hello\")\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":"null","endLoc":156,"header":"def test_getline(self)","id":6467,"name":"test_getline","nodeType":"Function","startLoc":154,"text":"def test_getline(self):\n x = self.source[0]\n assert x == \"def f(x):\""},{"col":4,"comment":"null","endLoc":159,"header":"def test_len(self)","id":6468,"name":"test_len","nodeType":"Function","startLoc":158,"text":"def test_len(self):\n assert len(self.source) == 4"},{"col":4,"comment":"null","endLoc":163,"header":"def test_iter(self)","id":6469,"name":"test_iter","nodeType":"Function","startLoc":161,"text":"def test_iter(self):\n values = [x for x in self.source]\n assert len(values) == 4"},{"attributeType":"Source","col":4,"comment":"null","endLoc":139,"id":6470,"name":"source","nodeType":"Attribute","startLoc":139,"text":"source"},{"className":"TestSourceParsingAndCompiling","col":0,"comment":"null","endLoc":339,"id":6471,"nodeType":"Class","startLoc":166,"text":"class TestSourceParsingAndCompiling(object):\n source = Source(\n \"\"\"\\\n def f(x):\n assert (x ==\n 3 +\n 4)\n \"\"\"\n ).strip()\n\n def test_compile(self):\n co = _pytest._code.compile(\"x=3\")\n d = {}\n exec(co, d)\n assert d[\"x\"] == 3\n\n def test_compile_and_getsource_simple(self):\n co = _pytest._code.compile(\"x=3\")\n exec(co)\n source = _pytest._code.Source(co)\n assert str(source) == \"x=3\"\n\n def test_compile_and_getsource_through_same_function(self):\n def gensource(source):\n return _pytest._code.compile(source)\n\n co1 = gensource(\n \"\"\"\n def f():\n raise KeyError()\n \"\"\"\n )\n co2 = gensource(\n \"\"\"\n def f():\n raise ValueError()\n \"\"\"\n )\n source1 = inspect.getsource(co1)\n assert \"KeyError\" in source1\n source2 = inspect.getsource(co2)\n assert \"ValueError\" in source2\n\n def test_getstatement(self):\n # print str(self.source)\n ass = str(self.source[1:])\n for i in range(1, 4):\n # print \"trying start in line %r\" % self.source[i]\n s = self.source.getstatement(i)\n # x = s.deindent()\n assert str(s) == ass\n\n def test_getstatementrange_triple_quoted(self):\n # print str(self.source)\n source = Source(\n \"\"\"hello('''\n ''')\"\"\"\n )\n s = source.getstatement(0)\n assert s == str(source)\n s = source.getstatement(1)\n assert s == str(source)\n\n def test_getstatementrange_within_constructs(self):\n source = Source(\n \"\"\"\\\n try:\n try:\n raise ValueError\n except SomeThing:\n pass\n finally:\n 42\n \"\"\"\n )\n assert len(source) == 7\n # check all lineno's that could occur in a traceback\n # assert source.getstatementrange(0) == (0, 7)\n # assert source.getstatementrange(1) == (1, 5)\n assert source.getstatementrange(2) == (2, 3)\n assert source.getstatementrange(3) == (3, 4)\n assert source.getstatementrange(4) == (4, 5)\n # assert source.getstatementrange(5) == (0, 7)\n assert source.getstatementrange(6) == (6, 7)\n\n def test_getstatementrange_bug(self):\n source = Source(\n \"\"\"\\\n try:\n x = (\n y +\n z)\n except:\n pass\n \"\"\"\n )\n assert len(source) == 6\n assert source.getstatementrange(2) == (1, 4)\n\n def test_getstatementrange_bug2(self):\n source = Source(\n \"\"\"\\\n assert (\n 33\n ==\n [\n X(3,\n b=1, c=2\n ),\n ]\n )\n \"\"\"\n )\n assert len(source) == 9\n assert source.getstatementrange(5) == (0, 9)\n\n def test_getstatementrange_ast_issue58(self):\n source = Source(\n \"\"\"\\\n\n def test_some():\n for a in [a for a in\n CAUSE_ERROR]: pass\n\n x = 3\n \"\"\"\n )\n assert getstatement(2, source).lines == source.lines[2:3]\n assert getstatement(3, source).lines == source.lines[3:4]\n\n def test_getstatementrange_out_of_bounds_py3(self):\n source = Source(\"if xxx:\\n from .collections import something\")\n r = source.getstatementrange(1)\n assert r == (1, 2)\n\n def test_getstatementrange_with_syntaxerror_issue7(self):\n source = Source(\":\")\n pytest.raises(SyntaxError, lambda: source.getstatementrange(0))\n\n def test_compile_to_ast(self):\n source = Source(\"x = 4\")\n mod = source.compile(flag=ast.PyCF_ONLY_AST)\n assert isinstance(mod, ast.Module)\n compile(mod, \"\", \"exec\")\n\n def test_compile_and_getsource(self):\n co = self.source.compile()\n exec(co, globals())\n f(7)\n excinfo = pytest.raises(AssertionError, f, 6)\n frame = excinfo.traceback[-1].frame\n stmt = frame.code.fullsource.getstatement(frame.lineno)\n assert str(stmt).strip().startswith(\"assert\")\n\n @pytest.mark.parametrize(\"name\", [\"\", None, \"my\"])\n def test_compilefuncs_and_path_sanity(self, name):\n def check(comp, name):\n co = comp(self.source, name)\n if not name:\n expected = \"codegen %s:%d>\" % (mypath, mylineno + 2 + 2)\n else:\n expected = \"codegen %r %s:%d>\" % (name, mypath, mylineno + 2 + 2)\n fn = co.co_filename\n assert fn.endswith(expected)\n\n mycode = _pytest._code.Code(self.test_compilefuncs_and_path_sanity)\n mylineno = mycode.firstlineno\n mypath = mycode.path\n\n for comp in _pytest._code.compile, _pytest._code.Source.compile:\n check(comp, name)\n\n def test_offsetless_synerr(self):\n pytest.raises(SyntaxError, _pytest._code.compile, \"lambda a,a: 0\", mode=\"eval\")"},{"col":4,"comment":"null","endLoc":180,"header":"def test_compile(self)","id":6472,"name":"test_compile","nodeType":"Function","startLoc":176,"text":"def test_compile(self):\n co = _pytest._code.compile(\"x=3\")\n d = {}\n exec(co, d)\n assert d[\"x\"] == 3"},{"col":4,"comment":"null","endLoc":186,"header":"def test_compile_and_getsource_simple(self)","id":6473,"name":"test_compile_and_getsource_simple","nodeType":"Function","startLoc":182,"text":"def test_compile_and_getsource_simple(self):\n co = _pytest._code.compile(\"x=3\")\n exec(co)\n source = _pytest._code.Source(co)\n assert str(source) == \"x=3\""},{"col":4,"comment":"Return the collection node of a file.\n\n This is like :py:meth:`getnode` but uses :py:meth:`parseconfigure` to\n create the (configured) pytest Config instance.\n\n :param path: a :py:class:`py.path.local` instance of the file\n\n ","endLoc":726,"header":"def getpathnode(self, path)","id":6474,"name":"getpathnode","nodeType":"Function","startLoc":711,"text":"def getpathnode(self, path):\n \"\"\"Return the collection node of a file.\n\n This is like :py:meth:`getnode` but uses :py:meth:`parseconfigure` to\n create the (configured) pytest Config instance.\n\n :param path: a :py:class:`py.path.local` instance of the file\n\n \"\"\"\n config = self.parseconfigure(path)\n session = Session(config)\n x = session.fspath.bestrelpath(path)\n config.hook.pytest_sessionstart(session=session)\n res = session.perform_collect([x], genitems=False)[0]\n config.hook.pytest_sessionfinish(session=session, exitstatus=EXIT_OK)\n return res"},{"col":4,"comment":"null","endLoc":189,"header":"def test_unittest_mock_and_pypi_mock(self, testdir)","id":6475,"name":"test_unittest_mock_and_pypi_mock","nodeType":"Function","startLoc":167,"text":"def test_unittest_mock_and_pypi_mock(self, testdir):\n pytest.importorskip(\"unittest.mock\")\n pytest.importorskip(\"mock\", \"1.0.1\")\n testdir.makepyfile(\n \"\"\"\n import mock\n import unittest.mock\n class TestBoth(object):\n @unittest.mock.patch(\"os.path.abspath\")\n def test_hello(self, abspath):\n import os\n os.path.abspath(\"hello\")\n abspath.assert_any_call(\"hello\")\n\n @mock.patch(\"os.path.abspath\")\n def test_hello_mock(self, abspath):\n import os\n os.path.abspath(\"hello\")\n abspath.assert_any_call(\"hello\")\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)"},{"fileName":"util.py","filePath":"src/_pytest/assertion","id":6476,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"Utilities for assertion debugging\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pprint\n\nimport six\n\nimport _pytest._code\nfrom ..compat import Sequence\nfrom _pytest import outcomes\nfrom _pytest._io.saferepr import saferepr\n\n# The _reprcompare attribute on the util module is used by the new assertion\n# interpretation code and assertion rewriter to detect this plugin was\n# loaded and in turn call the hooks defined here as part of the\n# DebugInterpreter.\n_reprcompare = None\n\n\n# the re-encoding is needed for python2 repr\n# with non-ascii characters (see issue 877 and 1379)\ndef ecu(s):\n if isinstance(s, bytes):\n return s.decode(\"UTF-8\", \"replace\")\n else:\n return s\n\n\ndef format_explanation(explanation):\n \"\"\"This formats an explanation\n\n Normally all embedded newlines are escaped, however there are\n three exceptions: \\n{, \\n} and \\n~. The first two are intended\n cover nested explanations, see function and attribute explanations\n for examples (.visit_Call(), visit_Attribute()). The last one is\n for when one explanation needs to span multiple lines, e.g. when\n displaying diffs.\n \"\"\"\n explanation = ecu(explanation)\n lines = _split_explanation(explanation)\n result = _format_lines(lines)\n return u\"\\n\".join(result)\n\n\ndef _split_explanation(explanation):\n \"\"\"Return a list of individual lines in the explanation\n\n This will return a list of lines split on '\\n{', '\\n}' and '\\n~'.\n Any other newlines will be escaped and appear in the line as the\n literal '\\n' characters.\n \"\"\"\n raw_lines = (explanation or u\"\").split(\"\\n\")\n lines = [raw_lines[0]]\n for values in raw_lines[1:]:\n if values and values[0] in [\"{\", \"}\", \"~\", \">\"]:\n lines.append(values)\n else:\n lines[-1] += \"\\\\n\" + values\n return lines\n\n\ndef _format_lines(lines):\n \"\"\"Format the individual lines\n\n This will replace the '{', '}' and '~' characters of our mini\n formatting language with the proper 'where ...', 'and ...' and ' +\n ...' text, taking care of indentation along the way.\n\n Return a list of formatted lines.\n \"\"\"\n result = lines[:1]\n stack = [0]\n stackcnt = [0]\n for line in lines[1:]:\n if line.startswith(\"{\"):\n if stackcnt[-1]:\n s = u\"and \"\n else:\n s = u\"where \"\n stack.append(len(result))\n stackcnt[-1] += 1\n stackcnt.append(0)\n result.append(u\" +\" + u\" \" * (len(stack) - 1) + s + line[1:])\n elif line.startswith(\"}\"):\n stack.pop()\n stackcnt.pop()\n result[stack[-1]] += line[1:]\n else:\n assert line[0] in [\"~\", \">\"]\n stack[-1] += 1\n indent = len(stack) if line.startswith(\"~\") else len(stack) - 1\n result.append(u\" \" * indent + line[1:])\n assert len(stack) == 1\n return result\n\n\n# Provide basestring in python3\ntry:\n basestring = basestring\nexcept NameError:\n basestring = str\n\n\ndef issequence(x):\n return isinstance(x, Sequence) and not isinstance(x, basestring)\n\n\ndef istext(x):\n return isinstance(x, basestring)\n\n\ndef isdict(x):\n return isinstance(x, dict)\n\n\ndef isset(x):\n return isinstance(x, (set, frozenset))\n\n\ndef isdatacls(obj):\n return getattr(obj, \"__dataclass_fields__\", None) is not None\n\n\ndef isattrs(obj):\n return getattr(obj, \"__attrs_attrs__\", None) is not None\n\n\ndef isiterable(obj):\n try:\n iter(obj)\n return not istext(obj)\n except TypeError:\n return False\n\n\ndef assertrepr_compare(config, op, left, right):\n \"\"\"Return specialised explanations for some operators/operands\"\"\"\n width = 80 - 15 - len(op) - 2 # 15 chars indentation, 1 space around op\n left_repr = saferepr(left, maxsize=int(width // 2))\n right_repr = saferepr(right, maxsize=width - len(left_repr))\n\n summary = u\"%s %s %s\" % (ecu(left_repr), op, ecu(right_repr))\n\n verbose = config.getoption(\"verbose\")\n explanation = None\n try:\n if op == \"==\":\n if istext(left) and istext(right):\n explanation = _diff_text(left, right, verbose)\n else:\n if issequence(left) and issequence(right):\n explanation = _compare_eq_sequence(left, right, verbose)\n elif isset(left) and isset(right):\n explanation = _compare_eq_set(left, right, verbose)\n elif isdict(left) and isdict(right):\n explanation = _compare_eq_dict(left, right, verbose)\n elif type(left) == type(right) and (isdatacls(left) or isattrs(left)):\n type_fn = (isdatacls, isattrs)\n explanation = _compare_eq_cls(left, right, verbose, type_fn)\n elif verbose > 0:\n explanation = _compare_eq_verbose(left, right)\n if isiterable(left) and isiterable(right):\n expl = _compare_eq_iterable(left, right, verbose)\n if explanation is not None:\n explanation.extend(expl)\n else:\n explanation = expl\n elif op == \"not in\":\n if istext(left) and istext(right):\n explanation = _notin_text(left, right, verbose)\n except outcomes.Exit:\n raise\n except Exception:\n explanation = [\n u\"(pytest_assertion plugin: representation of details failed. \"\n u\"Probably an object has a faulty __repr__.)\",\n six.text_type(_pytest._code.ExceptionInfo.from_current()),\n ]\n\n if not explanation:\n return None\n\n return [summary] + explanation\n\n\ndef _diff_text(left, right, verbose=0):\n \"\"\"Return the explanation for the diff between text or bytes.\n\n Unless --verbose is used this will skip leading and trailing\n characters which are identical to keep the diff minimal.\n\n If the input are bytes they will be safely converted to text.\n \"\"\"\n from difflib import ndiff\n\n explanation = []\n\n def escape_for_readable_diff(binary_text):\n \"\"\"\n Ensures that the internal string is always valid unicode, converting any bytes safely to valid unicode.\n This is done using repr() which then needs post-processing to fix the encompassing quotes and un-escape\n newlines and carriage returns (#429).\n \"\"\"\n r = six.text_type(repr(binary_text)[1:-1])\n r = r.replace(r\"\\n\", \"\\n\")\n r = r.replace(r\"\\r\", \"\\r\")\n return r\n\n if isinstance(left, bytes):\n left = escape_for_readable_diff(left)\n if isinstance(right, bytes):\n right = escape_for_readable_diff(right)\n if verbose < 1:\n i = 0 # just in case left or right has zero length\n for i in range(min(len(left), len(right))):\n if left[i] != right[i]:\n break\n if i > 42:\n i -= 10 # Provide some context\n explanation = [\n u\"Skipping %s identical leading characters in diff, use -v to show\" % i\n ]\n left = left[i:]\n right = right[i:]\n if len(left) == len(right):\n for i in range(len(left)):\n if left[-i] != right[-i]:\n break\n if i > 42:\n i -= 10 # Provide some context\n explanation += [\n u\"Skipping {} identical trailing \"\n u\"characters in diff, use -v to show\".format(i)\n ]\n left = left[:-i]\n right = right[:-i]\n keepends = True\n if left.isspace() or right.isspace():\n left = repr(str(left))\n right = repr(str(right))\n explanation += [u\"Strings contain only whitespace, escaping them using repr()\"]\n explanation += [\n line.strip(\"\\n\")\n for line in ndiff(left.splitlines(keepends), right.splitlines(keepends))\n ]\n return explanation\n\n\ndef _compare_eq_verbose(left, right):\n keepends = True\n left_lines = repr(left).splitlines(keepends)\n right_lines = repr(right).splitlines(keepends)\n\n explanation = []\n explanation += [u\"-\" + line for line in left_lines]\n explanation += [u\"+\" + line for line in right_lines]\n\n return explanation\n\n\ndef _compare_eq_iterable(left, right, verbose=0):\n if not verbose:\n return [u\"Use -v to get the full diff\"]\n # dynamic import to speedup pytest\n import difflib\n\n try:\n left_formatting = pprint.pformat(left).splitlines()\n right_formatting = pprint.pformat(right).splitlines()\n explanation = [u\"Full diff:\"]\n except Exception:\n # hack: PrettyPrinter.pformat() in python 2 fails when formatting items that can't be sorted(), ie, calling\n # sorted() on a list would raise. See issue #718.\n # As a workaround, the full diff is generated by using the repr() string of each item of each container.\n left_formatting = sorted(repr(x) for x in left)\n right_formatting = sorted(repr(x) for x in right)\n explanation = [u\"Full diff (fallback to calling repr on each item):\"]\n explanation.extend(\n line.strip() for line in difflib.ndiff(left_formatting, right_formatting)\n )\n return explanation\n\n\ndef _compare_eq_sequence(left, right, verbose=0):\n explanation = []\n len_left = len(left)\n len_right = len(right)\n for i in range(min(len_left, len_right)):\n if left[i] != right[i]:\n explanation += [u\"At index %s diff: %r != %r\" % (i, left[i], right[i])]\n break\n len_diff = len_left - len_right\n\n if len_diff:\n if len_diff > 0:\n dir_with_more = \"Left\"\n extra = saferepr(left[len_right])\n else:\n len_diff = 0 - len_diff\n dir_with_more = \"Right\"\n extra = saferepr(right[len_left])\n\n if len_diff == 1:\n explanation += [u\"%s contains one more item: %s\" % (dir_with_more, extra)]\n else:\n explanation += [\n u\"%s contains %d more items, first extra item: %s\"\n % (dir_with_more, len_diff, extra)\n ]\n return explanation\n\n\ndef _compare_eq_set(left, right, verbose=0):\n explanation = []\n diff_left = left - right\n diff_right = right - left\n if diff_left:\n explanation.append(u\"Extra items in the left set:\")\n for item in diff_left:\n explanation.append(saferepr(item))\n if diff_right:\n explanation.append(u\"Extra items in the right set:\")\n for item in diff_right:\n explanation.append(saferepr(item))\n return explanation\n\n\ndef _compare_eq_dict(left, right, verbose=0):\n explanation = []\n set_left = set(left)\n set_right = set(right)\n common = set_left.intersection(set_right)\n same = {k: left[k] for k in common if left[k] == right[k]}\n if same and verbose < 2:\n explanation += [u\"Omitting %s identical items, use -vv to show\" % len(same)]\n elif same:\n explanation += [u\"Common items:\"]\n explanation += pprint.pformat(same).splitlines()\n diff = {k for k in common if left[k] != right[k]}\n if diff:\n explanation += [u\"Differing items:\"]\n for k in diff:\n explanation += [saferepr({k: left[k]}) + \" != \" + saferepr({k: right[k]})]\n extra_left = set_left - set_right\n len_extra_left = len(extra_left)\n if len_extra_left:\n explanation.append(\n u\"Left contains %d more item%s:\"\n % (len_extra_left, \"\" if len_extra_left == 1 else \"s\")\n )\n explanation.extend(\n pprint.pformat({k: left[k] for k in extra_left}).splitlines()\n )\n extra_right = set_right - set_left\n len_extra_right = len(extra_right)\n if len_extra_right:\n explanation.append(\n u\"Right contains %d more item%s:\"\n % (len_extra_right, \"\" if len_extra_right == 1 else \"s\")\n )\n explanation.extend(\n pprint.pformat({k: right[k] for k in extra_right}).splitlines()\n )\n return explanation\n\n\ndef _compare_eq_cls(left, right, verbose, type_fns):\n isdatacls, isattrs = type_fns\n if isdatacls(left):\n all_fields = left.__dataclass_fields__\n fields_to_check = [field for field, info in all_fields.items() if info.compare]\n elif isattrs(left):\n all_fields = left.__attrs_attrs__\n fields_to_check = [field.name for field in all_fields if field.cmp]\n\n same = []\n diff = []\n for field in fields_to_check:\n if getattr(left, field) == getattr(right, field):\n same.append(field)\n else:\n diff.append(field)\n\n explanation = []\n if same and verbose < 2:\n explanation.append(u\"Omitting %s identical items, use -vv to show\" % len(same))\n elif same:\n explanation += [u\"Matching attributes:\"]\n explanation += pprint.pformat(same).splitlines()\n if diff:\n explanation += [u\"Differing attributes:\"]\n for field in diff:\n explanation += [\n (u\"%s: %r != %r\") % (field, getattr(left, field), getattr(right, field))\n ]\n return explanation\n\n\ndef _notin_text(term, text, verbose=0):\n index = text.find(term)\n head = text[:index]\n tail = text[index + len(term) :]\n correct_text = head + tail\n diff = _diff_text(correct_text, text, verbose)\n newdiff = [u\"%s is contained here:\" % saferepr(term, maxsize=42)]\n for line in diff:\n if line.startswith(u\"Skipping\"):\n continue\n if line.startswith(u\"- \"):\n continue\n if line.startswith(u\"+ \"):\n newdiff.append(u\" \" + line[2:])\n else:\n newdiff.append(line)\n return newdiff\n"},{"col":0,"comment":"null","endLoc":108,"header":"def issequence(x)","id":6477,"name":"issequence","nodeType":"Function","startLoc":107,"text":"def issequence(x):\n return isinstance(x, Sequence) and not isinstance(x, basestring)"},{"col":0,"comment":"null","endLoc":112,"header":"def istext(x)","id":6478,"name":"istext","nodeType":"Function","startLoc":111,"text":"def istext(x):\n return isinstance(x, basestring)"},{"col":0,"comment":"null","endLoc":116,"header":"def isdict(x)","id":6479,"name":"isdict","nodeType":"Function","startLoc":115,"text":"def isdict(x):\n return isinstance(x, dict)"},{"col":0,"comment":"null","endLoc":120,"header":"def isset(x)","id":6480,"name":"isset","nodeType":"Function","startLoc":119,"text":"def isset(x):\n return isinstance(x, (set, frozenset))"},{"col":0,"comment":"null","endLoc":124,"header":"def isdatacls(obj)","id":6481,"name":"isdatacls","nodeType":"Function","startLoc":123,"text":"def isdatacls(obj):\n return getattr(obj, \"__dataclass_fields__\", None) is not None"},{"col":4,"comment":"null","endLoc":222,"header":"def test_mock(self, testdir)","id":6482,"name":"test_mock","nodeType":"Function","startLoc":191,"text":"def test_mock(self, testdir):\n pytest.importorskip(\"mock\", \"1.0.1\")\n testdir.makepyfile(\n \"\"\"\n import os\n import unittest\n import mock\n\n class T(unittest.TestCase):\n @mock.patch(\"os.path.abspath\")\n def test_hello(self, abspath):\n os.path.abspath(\"hello\")\n abspath.assert_any_call(\"hello\")\n def mock_basename(path):\n return \"mock_basename\"\n @mock.patch(\"os.path.abspath\")\n @mock.patch(\"os.path.normpath\")\n @mock.patch(\"os.path.basename\", new=mock_basename)\n def test_someting(normpath, abspath, tmpdir):\n abspath.return_value = \"this\"\n os.path.normpath(os.path.abspath(\"hello\"))\n normpath.assert_any_call(\"this\")\n assert os.path.basename(\"123\") == \"mock_basename\"\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=2)\n calls = reprec.getcalls(\"pytest_runtest_logreport\")\n funcnames = [\n call.report.location[2] for call in calls if call.report.when == \"call\"\n ]\n assert funcnames == [\"T.test_hello\", \"test_someting\"]"},{"col":0,"comment":"null","endLoc":128,"header":"def isattrs(obj)","id":6483,"name":"isattrs","nodeType":"Function","startLoc":127,"text":"def isattrs(obj):\n return getattr(obj, \"__attrs_attrs__\", None) is not None"},{"col":4,"comment":"null","endLoc":207,"header":"def test_compile_and_getsource_through_same_function(self)","id":6484,"name":"test_compile_and_getsource_through_same_function","nodeType":"Function","startLoc":188,"text":"def test_compile_and_getsource_through_same_function(self):\n def gensource(source):\n return _pytest._code.compile(source)\n\n co1 = gensource(\n \"\"\"\n def f():\n raise KeyError()\n \"\"\"\n )\n co2 = gensource(\n \"\"\"\n def f():\n raise ValueError()\n \"\"\"\n )\n source1 = inspect.getsource(co1)\n assert \"KeyError\" in source1\n source2 = inspect.getsource(co2)\n assert \"ValueError\" in source2"},{"col":0,"comment":"null","endLoc":136,"header":"def isiterable(obj)","id":6485,"name":"isiterable","nodeType":"Function","startLoc":131,"text":"def isiterable(obj):\n try:\n iter(obj)\n return not istext(obj)\n except TypeError:\n return False"},{"col":0,"comment":"Return specialised explanations for some operators/operands","endLoc":186,"header":"def assertrepr_compare(config, op, left, right)","id":6486,"name":"assertrepr_compare","nodeType":"Function","startLoc":139,"text":"def assertrepr_compare(config, op, left, right):\n \"\"\"Return specialised explanations for some operators/operands\"\"\"\n width = 80 - 15 - len(op) - 2 # 15 chars indentation, 1 space around op\n left_repr = saferepr(left, maxsize=int(width // 2))\n right_repr = saferepr(right, maxsize=width - len(left_repr))\n\n summary = u\"%s %s %s\" % (ecu(left_repr), op, ecu(right_repr))\n\n verbose = config.getoption(\"verbose\")\n explanation = None\n try:\n if op == \"==\":\n if istext(left) and istext(right):\n explanation = _diff_text(left, right, verbose)\n else:\n if issequence(left) and issequence(right):\n explanation = _compare_eq_sequence(left, right, verbose)\n elif isset(left) and isset(right):\n explanation = _compare_eq_set(left, right, verbose)\n elif isdict(left) and isdict(right):\n explanation = _compare_eq_dict(left, right, verbose)\n elif type(left) == type(right) and (isdatacls(left) or isattrs(left)):\n type_fn = (isdatacls, isattrs)\n explanation = _compare_eq_cls(left, right, verbose, type_fn)\n elif verbose > 0:\n explanation = _compare_eq_verbose(left, right)\n if isiterable(left) and isiterable(right):\n expl = _compare_eq_iterable(left, right, verbose)\n if explanation is not None:\n explanation.extend(expl)\n else:\n explanation = expl\n elif op == \"not in\":\n if istext(left) and istext(right):\n explanation = _notin_text(left, right, verbose)\n except outcomes.Exit:\n raise\n except Exception:\n explanation = [\n u\"(pytest_assertion plugin: representation of details failed. \"\n u\"Probably an object has a faulty __repr__.)\",\n six.text_type(_pytest._code.ExceptionInfo.from_current()),\n ]\n\n if not explanation:\n return None\n\n return [summary] + explanation"},{"col":4,"comment":"null","endLoc":246,"header":"def test_mock_sorting(self, testdir)","id":6488,"name":"test_mock_sorting","nodeType":"Function","startLoc":224,"text":"def test_mock_sorting(self, testdir):\n pytest.importorskip(\"mock\", \"1.0.1\")\n testdir.makepyfile(\n \"\"\"\n import os\n import mock\n\n @mock.patch(\"os.path.abspath\")\n def test_one(abspath):\n pass\n @mock.patch(\"os.path.abspath\")\n def test_two(abspath):\n pass\n @mock.patch(\"os.path.abspath\")\n def test_three(abspath):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n calls = reprec.getreports(\"pytest_runtest_logreport\")\n calls = [x for x in calls if x.when == \"call\"]\n names = [x.nodeid.split(\"::\")[-1] for x in calls]\n assert names == [\"test_one\", \"test_two\", \"test_three\"]"},{"col":4,"comment":"null","endLoc":264,"header":"def test_mock_double_patch_issue473(self, testdir)","id":6489,"name":"test_mock_double_patch_issue473","nodeType":"Function","startLoc":248,"text":"def test_mock_double_patch_issue473(self, testdir):\n pytest.importorskip(\"mock\", \"1.0.1\")\n testdir.makepyfile(\n \"\"\"\n from mock import patch\n from pytest import mark\n\n @patch('os.getcwd')\n @patch('os.path')\n @mark.slow\n class TestSimple(object):\n def test_simple_thing(self, mock_path, mock_getcwd):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"attributeType":"null","col":8,"comment":"null","endLoc":219,"id":6490,"name":"match_expr","nodeType":"Attribute","startLoc":219,"text":"self.match_expr"},{"attributeType":"tuple | (type)","col":8,"comment":"null","endLoc":218,"id":6491,"name":"expected_warning","nodeType":"Attribute","startLoc":218,"text":"self.expected_warning"},{"col":4,"comment":"Return a new pytest configured Config instance.\n\n This returns a new :py:class:`_pytest.config.Config` instance like\n :py:meth:`parseconfig`, but also calls the pytest_configure hook.\n\n ","endLoc":953,"header":"def parseconfigure(self, *args)","id":6492,"name":"parseconfigure","nodeType":"Function","startLoc":943,"text":"def parseconfigure(self, *args):\n \"\"\"Return a new pytest configured Config instance.\n\n This returns a new :py:class:`_pytest.config.Config` instance like\n :py:meth:`parseconfig`, but also calls the pytest_configure hook.\n\n \"\"\"\n config = self.parseconfig(*args)\n config._do_configure()\n self.request.addfinalizer(config._ensure_unconfigure)\n return config"},{"col":4,"comment":"Return a new pytest Config instance from given commandline args.\n\n This invokes the pytest bootstrapping code in _pytest.config to create\n a new :py:class:`_pytest.core.PluginManager` and call the\n pytest_cmdline_parse hook to create a new\n :py:class:`_pytest.config.Config` instance.\n\n If :py:attr:`plugins` has been populated they should be plugin modules\n to be registered with the PluginManager.\n\n ","endLoc":941,"header":"def parseconfig(self, *args)","id":6493,"name":"parseconfig","nodeType":"Function","startLoc":920,"text":"def parseconfig(self, *args):\n \"\"\"Return a new pytest Config instance from given commandline args.\n\n This invokes the pytest bootstrapping code in _pytest.config to create\n a new :py:class:`_pytest.core.PluginManager` and call the\n pytest_cmdline_parse hook to create a new\n :py:class:`_pytest.config.Config` instance.\n\n If :py:attr:`plugins` has been populated they should be plugin modules\n to be registered with the PluginManager.\n\n \"\"\"\n args = self._ensure_basetemp(args)\n\n import _pytest.config\n\n config = _pytest.config._prepareconfig(args, self.plugins)\n # we don't know what the test will do with this half-setup config\n # object and thus we make sure it gets unconfigured properly in any\n # case (otherwise capturing could still be active, for example)\n self.request.addfinalizer(config._ensure_unconfigure)\n return config"},{"col":4,"comment":"null","endLoc":918,"header":"def _ensure_basetemp(self, args)","id":6494,"name":"_ensure_basetemp","nodeType":"Function","startLoc":911,"text":"def _ensure_basetemp(self, args):\n args = list(args)\n for x in args:\n if safe_str(x).startswith(\"--basetemp\"):\n break\n else:\n args.append(\"--basetemp=%s\" % self.tmpdir.dirpath(\"basetemp\"))\n return args"},{"col":4,"comment":"null","endLoc":216,"header":"def test_getstatement(self)","id":6495,"name":"test_getstatement","nodeType":"Function","startLoc":209,"text":"def test_getstatement(self):\n # print str(self.source)\n ass = str(self.source[1:])\n for i in range(1, 4):\n # print \"trying start in line %r\" % self.source[i]\n s = self.source.getstatement(i)\n # x = s.deindent()\n assert str(s) == ass"},{"col":0,"comment":"Return a :class:`WarningsRecorder` instance that records all warnings emitted by test functions.\n\n See http://docs.python.org/library/warnings.html for information\n on warning categories.\n ","endLoc":31,"header":"@yield_fixture\ndef recwarn()","id":6496,"name":"recwarn","nodeType":"Function","startLoc":21,"text":"@yield_fixture\ndef recwarn():\n \"\"\"Return a :class:`WarningsRecorder` instance that records all warnings emitted by test functions.\n\n See http://docs.python.org/library/warnings.html for information\n on warning categories.\n \"\"\"\n wrec = WarningsRecorder()\n with wrec:\n warnings.simplefilter(\"default\")\n yield wrec"},{"col":0,"comment":"","endLoc":2,"header":"recwarn.py#","id":6497,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" recording warnings during test function execution. \"\"\""},{"col":4,"comment":"Generate all test items from a collection node.\n\n This recurses into the collection node and returns a list of all the\n test items contained within.\n\n ","endLoc":739,"header":"def genitems(self, colitems)","id":6498,"name":"genitems","nodeType":"Function","startLoc":728,"text":"def genitems(self, colitems):\n \"\"\"Generate all test items from a collection node.\n\n This recurses into the collection node and returns a list of all the\n test items contained within.\n\n \"\"\"\n session = colitems[0].session\n result = []\n for colitem in colitems:\n result.extend(session.genitems(colitem))\n return result"},{"className":"TestReRunTests","col":0,"comment":"null","endLoc":304,"id":6499,"nodeType":"Class","startLoc":267,"text":"class TestReRunTests(object):\n def test_rerun(self, testdir):\n testdir.makeconftest(\n \"\"\"\n from _pytest.runner import runtestprotocol\n def pytest_runtest_protocol(item, nextitem):\n runtestprotocol(item, log=False, nextitem=nextitem)\n runtestprotocol(item, log=True, nextitem=nextitem)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n count = 0\n req = None\n @pytest.fixture\n def fix(request):\n global count, req\n assert request != req\n req = request\n print(\"fix count %s\" % count)\n count += 1\n def test_fix(fix):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *fix count 0*\n *fix count 1*\n \"\"\"\n )\n result.stdout.fnmatch_lines(\n \"\"\"\n *2 passed*\n \"\"\"\n )"},{"col":4,"comment":"null","endLoc":304,"header":"def test_rerun(self, testdir)","id":6500,"name":"test_rerun","nodeType":"Function","startLoc":268,"text":"def test_rerun(self, testdir):\n testdir.makeconftest(\n \"\"\"\n from _pytest.runner import runtestprotocol\n def pytest_runtest_protocol(item, nextitem):\n runtestprotocol(item, log=False, nextitem=nextitem)\n runtestprotocol(item, log=True, nextitem=nextitem)\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n import pytest\n count = 0\n req = None\n @pytest.fixture\n def fix(request):\n global count, req\n assert request != req\n req = request\n print(\"fix count %s\" % count)\n count += 1\n def test_fix(fix):\n pass\n \"\"\"\n )\n result = testdir.runpytest(\"-s\")\n result.stdout.fnmatch_lines(\n \"\"\"\n *fix count 0*\n *fix count 1*\n \"\"\"\n )\n result.stdout.fnmatch_lines(\n \"\"\"\n *2 passed*\n \"\"\"\n )"},{"col":4,"comment":"Run the \"test_func\" Item.\n\n The calling test instance (class containing the test method) must\n provide a ``.getrunner()`` method which should return a runner which\n can run the test protocol for a single item, e.g.\n :py:func:`_pytest.runner.runtestprotocol`.\n\n ","endLoc":755,"header":"def runitem(self, source)","id":6501,"name":"runitem","nodeType":"Function","startLoc":741,"text":"def runitem(self, source):\n \"\"\"Run the \"test_func\" Item.\n\n The calling test instance (class containing the test method) must\n provide a ``.getrunner()`` method which should return a runner which\n can run the test protocol for a single item, e.g.\n :py:func:`_pytest.runner.runtestprotocol`.\n\n \"\"\"\n # used from runner functional tests\n item = self.getitem(source)\n # the test class where we are called from wants to provide the runner\n testclassinstance = self.request.instance\n runner = testclassinstance.getrunner()\n return runner(item)"},{"className":"TestNoselikeTestAttribute","col":0,"comment":"null","endLoc":394,"id":6502,"nodeType":"Class","startLoc":313,"text":"class TestNoselikeTestAttribute(object):\n def test_module_with_global_test(self, testdir):\n testdir.makepyfile(\n \"\"\"\n __test__ = False\n def test_hello():\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n assert not reprec.getfailedcollections()\n calls = reprec.getreports(\"pytest_runtest_logreport\")\n assert not calls\n\n def test_class_and_method(self, testdir):\n testdir.makepyfile(\n \"\"\"\n __test__ = True\n def test_func():\n pass\n test_func.__test__ = False\n\n class TestSome(object):\n __test__ = False\n def test_method(self):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n assert not reprec.getfailedcollections()\n calls = reprec.getreports(\"pytest_runtest_logreport\")\n assert not calls\n\n def test_unittest_class(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import unittest\n class TC(unittest.TestCase):\n def test_1(self):\n pass\n class TC2(unittest.TestCase):\n __test__ = False\n def test_2(self):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n assert not reprec.getfailedcollections()\n call = reprec.getcalls(\"pytest_collection_modifyitems\")[0]\n assert len(call.items) == 1\n assert call.items[0].cls.__name__ == \"TC\"\n\n def test_class_with_nasty_getattr(self, testdir):\n \"\"\"Make sure we handle classes with a custom nasty __getattr__ right.\n\n With a custom __getattr__ which e.g. returns a function (like with a\n RPC wrapper), we shouldn't assume this meant \"__test__ = True\".\n \"\"\"\n # https://github.com/pytest-dev/pytest/issues/1204\n testdir.makepyfile(\n \"\"\"\n class MetaModel(type):\n\n def __getattr__(cls, key):\n return lambda: None\n\n\n BaseModel = MetaModel('Model', (), {})\n\n\n class Model(BaseModel):\n\n __metaclass__ = MetaModel\n\n def test_blah(self):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n assert not reprec.getfailedcollections()\n call = reprec.getcalls(\"pytest_collection_modifyitems\")[0]\n assert not call.items"},{"col":4,"comment":"null","endLoc":325,"header":"def test_module_with_global_test(self, testdir)","id":6503,"name":"test_module_with_global_test","nodeType":"Function","startLoc":314,"text":"def test_module_with_global_test(self, testdir):\n testdir.makepyfile(\n \"\"\"\n __test__ = False\n def test_hello():\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n assert not reprec.getfailedcollections()\n calls = reprec.getreports(\"pytest_runtest_logreport\")\n assert not calls"},{"col":4,"comment":"Raising an exception with the wrong type and match= given.\n\n pytest should throw the unexpected exception - the pattern match is not\n really relevant if we got a different exception.\n ","endLoc":239,"header":"def test_raises_match_wrong_type(self)","id":6504,"name":"test_raises_match_wrong_type","nodeType":"Function","startLoc":231,"text":"def test_raises_match_wrong_type(self):\n \"\"\"Raising an exception with the wrong type and match= given.\n\n pytest should throw the unexpected exception - the pattern match is not\n really relevant if we got a different exception.\n \"\"\"\n with pytest.raises(ValueError):\n with pytest.raises(IndexError, match=\"nomatch\"):\n int(\"asdf\")"},{"col":4,"comment":"null","endLoc":344,"header":"def test_class_and_method(self, testdir)","id":6505,"name":"test_class_and_method","nodeType":"Function","startLoc":327,"text":"def test_class_and_method(self, testdir):\n testdir.makepyfile(\n \"\"\"\n __test__ = True\n def test_func():\n pass\n test_func.__test__ = False\n\n class TestSome(object):\n __test__ = False\n def test_method(self):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n assert not reprec.getfailedcollections()\n calls = reprec.getreports(\"pytest_runtest_logreport\")\n assert not calls"},{"col":4,"comment":"null","endLoc":363,"header":"def test_unittest_class(self, testdir)","id":6506,"name":"test_unittest_class","nodeType":"Function","startLoc":346,"text":"def test_unittest_class(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import unittest\n class TC(unittest.TestCase):\n def test_1(self):\n pass\n class TC2(unittest.TestCase):\n __test__ = False\n def test_2(self):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n assert not reprec.getfailedcollections()\n call = reprec.getcalls(\"pytest_collection_modifyitems\")[0]\n assert len(call.items) == 1\n assert call.items[0].cls.__name__ == \"TC\""},{"col":4,"comment":"Make sure we handle classes with a custom nasty __getattr__ right.\n\n With a custom __getattr__ which e.g. returns a function (like with a\n RPC wrapper), we shouldn't assume this meant \"__test__ = True\".\n ","endLoc":394,"header":"def test_class_with_nasty_getattr(self, testdir)","id":6507,"name":"test_class_with_nasty_getattr","nodeType":"Function","startLoc":365,"text":"def test_class_with_nasty_getattr(self, testdir):\n \"\"\"Make sure we handle classes with a custom nasty __getattr__ right.\n\n With a custom __getattr__ which e.g. returns a function (like with a\n RPC wrapper), we shouldn't assume this meant \"__test__ = True\".\n \"\"\"\n # https://github.com/pytest-dev/pytest/issues/1204\n testdir.makepyfile(\n \"\"\"\n class MetaModel(type):\n\n def __getattr__(cls, key):\n return lambda: None\n\n\n BaseModel = MetaModel('Model', (), {})\n\n\n class Model(BaseModel):\n\n __metaclass__ = MetaModel\n\n def test_blah(self):\n pass\n \"\"\"\n )\n reprec = testdir.inline_run()\n assert not reprec.getfailedcollections()\n call = reprec.getcalls(\"pytest_collection_modifyitems\")[0]\n assert not call.items"},{"className":"TestParameterize","col":0,"comment":"#351","endLoc":447,"id":6508,"nodeType":"Class","startLoc":397,"text":"class TestParameterize(object):\n \"\"\"#351\"\"\"\n\n def test_idfn_marker(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n def idfn(param):\n if param == 0:\n return 'spam'\n elif param == 1:\n return 'ham'\n else:\n return None\n\n @pytest.mark.parametrize('a,b', [(0, 2), (1, 2)], ids=idfn)\n def test_params(a, b):\n pass\n \"\"\"\n )\n res = testdir.runpytest(\"--collect-only\")\n res.stdout.fnmatch_lines([\"*spam-2*\", \"*ham-2*\"])\n\n def test_idfn_fixture(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n def idfn(param):\n if param == 0:\n return 'spam'\n elif param == 1:\n return 'ham'\n else:\n return None\n\n @pytest.fixture(params=[0, 1], ids=idfn)\n def a(request):\n return request.param\n\n @pytest.fixture(params=[1, 2], ids=idfn)\n def b(request):\n return request.param\n\n def test_params(a, b):\n pass\n \"\"\"\n )\n res = testdir.runpytest(\"--collect-only\")\n res.stdout.fnmatch_lines([\"*spam-2*\", \"*ham-2*\"])"},{"col":4,"comment":"Call saferepr on the expression.","endLoc":734,"header":"def display(self, expr)","id":6509,"name":"display","nodeType":"Function","startLoc":732,"text":"def display(self, expr):\n \"\"\"Call saferepr on the expression.\"\"\"\n return self.helper(\"_saferepr\", expr)"},{"col":4,"comment":"null","endLoc":419,"header":"def test_idfn_marker(self, testdir)","id":6510,"name":"test_idfn_marker","nodeType":"Function","startLoc":400,"text":"def test_idfn_marker(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n def idfn(param):\n if param == 0:\n return 'spam'\n elif param == 1:\n return 'ham'\n else:\n return None\n\n @pytest.mark.parametrize('a,b', [(0, 2), (1, 2)], ids=idfn)\n def test_params(a, b):\n pass\n \"\"\"\n )\n res = testdir.runpytest(\"--collect-only\")\n res.stdout.fnmatch_lines([\"*spam-2*\", \"*ham-2*\"])"},{"col":4,"comment":"null","endLoc":447,"header":"def test_idfn_fixture(self, testdir)","id":6511,"name":"test_idfn_fixture","nodeType":"Function","startLoc":421,"text":"def test_idfn_fixture(self, testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n\n def idfn(param):\n if param == 0:\n return 'spam'\n elif param == 1:\n return 'ham'\n else:\n return None\n\n @pytest.fixture(params=[0, 1], ids=idfn)\n def a(request):\n return request.param\n\n @pytest.fixture(params=[1, 2], ids=idfn)\n def b(request):\n return request.param\n\n def test_params(a, b):\n pass\n \"\"\"\n )\n res = testdir.runpytest(\"--collect-only\")\n res.stdout.fnmatch_lines([\"*spam-2*\", \"*ham-2*\"])"},{"col":0,"comment":"null","endLoc":87,"header":"def test_wrapped_getfslineno()","id":6512,"name":"test_wrapped_getfslineno","nodeType":"Function","startLoc":72,"text":"def test_wrapped_getfslineno():\n def func():\n pass\n\n def wrap(f):\n func.__wrapped__ = f\n func.patchings = [\"qwe\"]\n return func\n\n @wrap\n def wrapped_func(x, y, z):\n pass\n\n fs, lineno = python.getfslineno(wrapped_func)\n fs2, lineno2 = python.getfslineno(wrap)\n assert lineno > lineno2, \"getfslineno does not unwrap correctly\""},{"col":4,"comment":"null","endLoc":259,"header":"def test_raises_exception_looks_iterable(self)","id":6513,"name":"test_raises_exception_looks_iterable","nodeType":"Function","startLoc":241,"text":"def test_raises_exception_looks_iterable(self):\n from six import add_metaclass\n\n class Meta(type(object)):\n def __getitem__(self, item):\n return 1 / 0\n\n def __len__(self):\n return 1\n\n @add_metaclass(Meta)\n class ClassLooksIterableException(Exception):\n pass\n\n with pytest.raises(\n Failed,\n match=r\"DID NOT RAISE \",\n ):\n pytest.raises(ClassLooksIterableException, lambda: None)"},{"col":4,"comment":"null","endLoc":177,"header":"def test_traceback_cut(self)","id":6514,"name":"test_traceback_cut","nodeType":"Function","startLoc":170,"text":"def test_traceback_cut(self):\n co = _pytest._code.Code(f)\n path, firstlineno = co.path, co.firstlineno\n traceback = self.excinfo.traceback\n newtraceback = traceback.cut(path=path, firstlineno=firstlineno)\n assert len(newtraceback) == 1\n newtraceback = traceback.cut(path=path, lineno=firstlineno + 2)\n assert len(newtraceback) == 1"},{"col":0,"comment":"null","endLoc":310,"header":"def test_pytestconfig_is_session_scoped()","id":6515,"name":"test_pytestconfig_is_session_scoped","nodeType":"Function","startLoc":307,"text":"def test_pytestconfig_is_session_scoped():\n from _pytest.fixtures import pytestconfig\n\n assert pytestconfig._pytestfixturefunction.scope == \"session\""},{"id":6516,"name":"release-3.2.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.2.2\n=======================================\n\npytest 3.2.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Andreas Pelme\n* Antonio Hidalgo\n* Bruno Oliveira\n* Felipe Dau\n* Fernando Macedo\n* Jesús Espino\n* Joan Massich\n* Joe Talbott\n* Kirill Pinchuk\n* Ronny Pfannschmidt\n* Xuan Luong\n\n\nHappy testing,\nThe pytest Development Team\n"},{"fileName":"bench_argcomplete.py","filePath":"bench","id":6518,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n# 10000 iterations, just for relative comparison\n# 2.7.5 3.3.2\n# FilesCompleter 75.1109 69.2116\n# FastFilesCompleter 0.7383 1.0760\nimport timeit\n\nimports = [\n \"from argcomplete.completers import FilesCompleter as completer\",\n \"from _pytest._argcomplete import FastFilesCompleter as completer\",\n]\n\ncount = 1000 # only a few seconds\nsetup = \"%s\\nfc = completer()\"\nrun = 'fc(\"/d\")'\n\n\nif __name__ == \"__main__\":\n print(timeit.timeit(run, setup=setup % imports[0], number=count))\n print(timeit.timeit(run, setup=setup % imports[1], number=count))\n"},{"attributeType":"list","col":0,"comment":"null","endLoc":8,"id":6519,"name":"imports","nodeType":"Attribute","startLoc":8,"text":"imports"},{"col":0,"comment":"\n Test that the level names of captured log messages of a failing test are\n colored.\n ","endLoc":1143,"header":"def test_colored_captured_log(testdir)","id":6520,"name":"test_colored_captured_log","nodeType":"Function","startLoc":1120,"text":"def test_colored_captured_log(testdir):\n \"\"\"\n Test that the level names of captured log messages of a failing test are\n colored.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import logging\n\n logger = logging.getLogger(__name__)\n\n def test_foo():\n logger.info('text going to logger from call')\n assert False\n \"\"\"\n )\n result = testdir.runpytest(\"--log-level=INFO\", \"--color=yes\")\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n [\n \"*-- Captured log call --*\",\n \"\\x1b[32mINFO \\x1b[0m*text going to logger from call\",\n ]\n )"},{"col":0,"comment":"\n Make sure that caplog.text does not contain ANSI escape sequences.\n ","endLoc":1162,"header":"def test_colored_ansi_esc_caplogtext(testdir)","id":6521,"name":"test_colored_ansi_esc_caplogtext","nodeType":"Function","startLoc":1146,"text":"def test_colored_ansi_esc_caplogtext(testdir):\n \"\"\"\n Make sure that caplog.text does not contain ANSI escape sequences.\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n import logging\n\n logger = logging.getLogger(__name__)\n\n def test_foo(caplog):\n logger.info('text going to logger from call')\n assert '\\x1b' not in caplog.text\n \"\"\"\n )\n result = testdir.runpytest(\"--log-level=INFO\", \"--color=yes\")\n assert result.ret == 0"},{"attributeType":"int","col":0,"comment":"null","endLoc":13,"id":6522,"name":"count","nodeType":"Attribute","startLoc":13,"text":"count"},{"attributeType":"str","col":0,"comment":"null","endLoc":14,"id":6523,"name":"setup","nodeType":"Attribute","startLoc":14,"text":"setup"},{"attributeType":"str","col":0,"comment":"null","endLoc":15,"id":6524,"name":"run","nodeType":"Attribute","startLoc":15,"text":"run"},{"col":0,"comment":"","endLoc":6,"header":"bench_argcomplete.py#","id":6525,"name":"","nodeType":"Function","startLoc":6,"text":"imports = [\n \"from argcomplete.completers import FilesCompleter as completer\",\n \"from _pytest._argcomplete import FastFilesCompleter as completer\",\n]\n\ncount = 1000 # only a few seconds\n\nsetup = \"%s\\nfc = completer()\"\n\nrun = 'fc(\"/d\")'\n\nif __name__ == \"__main__\":\n print(timeit.timeit(run, setup=setup % imports[0], number=count))\n print(timeit.timeit(run, setup=setup % imports[1], number=count))"},{"col":55,"endLoc":259,"id":6526,"nodeType":"Lambda","startLoc":259,"text":"lambda: None"},{"col":4,"comment":"Test current behavior with regard to exceptions via __class__ (#4284).","endLoc":281,"header":"def test_raises_with_raising_dunder_class(self)","id":6527,"name":"test_raises_with_raising_dunder_class","nodeType":"Function","startLoc":261,"text":"def test_raises_with_raising_dunder_class(self):\n \"\"\"Test current behavior with regard to exceptions via __class__ (#4284).\"\"\"\n\n class CrappyClass(Exception):\n @property\n def __class__(self):\n assert False, \"via __class__\"\n\n if six.PY2:\n with pytest.raises(pytest.fail.Exception) as excinfo:\n with pytest.raises(CrappyClass()):\n pass\n assert \"DID NOT RAISE\" in excinfo.value.args[0]\n\n with pytest.raises(CrappyClass) as excinfo:\n raise CrappyClass()\n else:\n with pytest.raises(AssertionError) as excinfo:\n with pytest.raises(CrappyClass()):\n pass\n assert \"via __class__\" in excinfo.value.args[0]"},{"col":4,"comment":"null","endLoc":188,"header":"def test_traceback_cut_excludepath(self, testdir)","id":6528,"name":"test_traceback_cut_excludepath","nodeType":"Function","startLoc":179,"text":"def test_traceback_cut_excludepath(self, testdir):\n p = testdir.makepyfile(\"def f(): raise ValueError\")\n with pytest.raises(ValueError) as excinfo:\n p.pyimport().f()\n basedir = py.path.local(pytest.__file__).dirpath()\n newtraceback = excinfo.traceback.cut(excludepath=basedir)\n for x in newtraceback:\n if hasattr(x, \"path\"):\n assert not py.path.local(x.path).relto(basedir)\n assert newtraceback[-1].frame.code.path == p"},{"fileName":"tmpdir.py","filePath":"src/_pytest","id":6530,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\" support for providing temporary directories to test functions. \"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport re\nimport tempfile\nimport warnings\n\nimport attr\nimport py\nimport six\n\nimport pytest\nfrom .pathlib import ensure_reset_dir\nfrom .pathlib import LOCK_TIMEOUT\nfrom .pathlib import make_numbered_dir\nfrom .pathlib import make_numbered_dir_with_cleanup\nfrom .pathlib import Path\nfrom _pytest.monkeypatch import MonkeyPatch\n\n\n@attr.s\nclass TempPathFactory(object):\n \"\"\"Factory for temporary directories under the common base temp directory.\n\n The base directory can be configured using the ``--basetemp`` option.\"\"\"\n\n _given_basetemp = attr.ib(\n # using os.path.abspath() to get absolute path instead of resolve() as it\n # does not work the same in all platforms (see #4427)\n # Path.absolute() exists, but it is not public (see https://bugs.python.org/issue25012)\n converter=attr.converters.optional(\n lambda p: Path(os.path.abspath(six.text_type(p)))\n )\n )\n _trace = attr.ib()\n _basetemp = attr.ib(default=None)\n\n @classmethod\n def from_config(cls, config):\n \"\"\"\n :param config: a pytest configuration\n \"\"\"\n return cls(\n given_basetemp=config.option.basetemp, trace=config.trace.get(\"tmpdir\")\n )\n\n def mktemp(self, basename, numbered=True):\n \"\"\"makes a temporary directory managed by the factory\"\"\"\n if not numbered:\n p = self.getbasetemp().joinpath(basename)\n p.mkdir()\n else:\n p = make_numbered_dir(root=self.getbasetemp(), prefix=basename)\n self._trace(\"mktemp\", p)\n return p\n\n def getbasetemp(self):\n \"\"\" return base temporary directory. \"\"\"\n if self._basetemp is not None:\n return self._basetemp\n\n if self._given_basetemp is not None:\n basetemp = self._given_basetemp\n ensure_reset_dir(basetemp)\n basetemp = basetemp.resolve()\n else:\n from_env = os.environ.get(\"PYTEST_DEBUG_TEMPROOT\")\n temproot = Path(from_env or tempfile.gettempdir()).resolve()\n user = get_user() or \"unknown\"\n # use a sub-directory in the temproot to speed-up\n # make_numbered_dir() call\n rootdir = temproot.joinpath(\"pytest-of-{}\".format(user))\n rootdir.mkdir(exist_ok=True)\n basetemp = make_numbered_dir_with_cleanup(\n prefix=\"pytest-\", root=rootdir, keep=3, lock_timeout=LOCK_TIMEOUT\n )\n assert basetemp is not None, basetemp\n self._basetemp = t = basetemp\n self._trace(\"new basetemp\", t)\n return t\n\n\n@attr.s\nclass TempdirFactory(object):\n \"\"\"\n backward comptibility wrapper that implements\n :class:``py.path.local`` for :class:``TempPathFactory``\n \"\"\"\n\n _tmppath_factory = attr.ib()\n\n def ensuretemp(self, string, dir=1):\n \"\"\" (deprecated) return temporary directory path with\n the given string as the trailing part. It is usually\n better to use the 'tmpdir' function argument which\n provides an empty unique-per-test-invocation directory\n and is guaranteed to be empty.\n \"\"\"\n # py.log._apiwarn(\">1.1\", \"use tmpdir function argument\")\n from .deprecated import PYTEST_ENSURETEMP\n\n warnings.warn(PYTEST_ENSURETEMP, stacklevel=2)\n return self.getbasetemp().ensure(string, dir=dir)\n\n def mktemp(self, basename, numbered=True):\n \"\"\"Create a subdirectory of the base temporary directory and return it.\n If ``numbered``, ensure the directory is unique by adding a number\n prefix greater than any existing one.\n \"\"\"\n return py.path.local(self._tmppath_factory.mktemp(basename, numbered).resolve())\n\n def getbasetemp(self):\n \"\"\"backward compat wrapper for ``_tmppath_factory.getbasetemp``\"\"\"\n return py.path.local(self._tmppath_factory.getbasetemp().resolve())\n\n\ndef get_user():\n \"\"\"Return the current user name, or None if getuser() does not work\n in the current environment (see #1010).\n \"\"\"\n import getpass\n\n try:\n return getpass.getuser()\n except (ImportError, KeyError):\n return None\n\n\ndef pytest_configure(config):\n \"\"\"Create a TempdirFactory and attach it to the config object.\n\n This is to comply with existing plugins which expect the handler to be\n available at pytest_configure time, but ideally should be moved entirely\n to the tmpdir_factory session fixture.\n \"\"\"\n mp = MonkeyPatch()\n tmppath_handler = TempPathFactory.from_config(config)\n t = TempdirFactory(tmppath_handler)\n config._cleanup.append(mp.undo)\n mp.setattr(config, \"_tmp_path_factory\", tmppath_handler, raising=False)\n mp.setattr(config, \"_tmpdirhandler\", t, raising=False)\n mp.setattr(pytest, \"ensuretemp\", t.ensuretemp, raising=False)\n\n\n@pytest.fixture(scope=\"session\")\ndef tmpdir_factory(request):\n \"\"\"Return a :class:`_pytest.tmpdir.TempdirFactory` instance for the test session.\n \"\"\"\n return request.config._tmpdirhandler\n\n\n@pytest.fixture(scope=\"session\")\ndef tmp_path_factory(request):\n \"\"\"Return a :class:`_pytest.tmpdir.TempPathFactory` instance for the test session.\n \"\"\"\n return request.config._tmp_path_factory\n\n\ndef _mk_tmp(request, factory):\n name = request.node.name\n name = re.sub(r\"[\\W]\", \"_\", name)\n MAXVAL = 30\n name = name[:MAXVAL]\n return factory.mktemp(name, numbered=True)\n\n\n@pytest.fixture\ndef tmpdir(tmp_path):\n \"\"\"Return a temporary directory path object\n which is unique to each test function invocation,\n created as a sub directory of the base temporary\n directory. The returned object is a `py.path.local`_\n path object.\n\n .. _`py.path.local`: https://py.readthedocs.io/en/latest/path.html\n \"\"\"\n return py.path.local(tmp_path)\n\n\n@pytest.fixture\ndef tmp_path(request, tmp_path_factory):\n \"\"\"Return a temporary directory path object\n which is unique to each test function invocation,\n created as a sub directory of the base temporary\n directory. The returned object is a :class:`pathlib.Path`\n object.\n\n .. note::\n\n in python < 3.6 this is a pathlib2.Path\n \"\"\"\n\n return _mk_tmp(request, tmp_path_factory)\n"},{"col":4,"comment":"Return the test item for a test function.\n\n This writes the source to a python file and runs pytest's collection on\n the resulting module, returning the test item for the requested\n function name.\n\n :param source: the module source\n\n :param funcname: the name of the test function for which to return a\n test item\n\n ","endLoc":976,"header":"def getitem(self, source, funcname=\"test_func\")","id":6531,"name":"getitem","nodeType":"Function","startLoc":955,"text":"def getitem(self, source, funcname=\"test_func\"):\n \"\"\"Return the test item for a test function.\n\n This writes the source to a python file and runs pytest's collection on\n the resulting module, returning the test item for the requested\n function name.\n\n :param source: the module source\n\n :param funcname: the name of the test function for which to return a\n test item\n\n \"\"\"\n items = self.getitems(source)\n for item in items:\n if item.name == funcname:\n return item\n assert 0, \"%r item not found in module:\\n%s\\nitems: %s\" % (\n funcname,\n source,\n items,\n )"},{"col":4,"comment":"Return all test items collected from the module.\n\n This writes the source to a python file and runs pytest's collection on\n the resulting module, returning all test items contained within.\n\n ","endLoc":986,"header":"def getitems(self, source)","id":6532,"name":"getitems","nodeType":"Function","startLoc":978,"text":"def getitems(self, source):\n \"\"\"Return all test items collected from the module.\n\n This writes the source to a python file and runs pytest's collection on\n the resulting module, returning all test items contained within.\n\n \"\"\"\n modcol = self.getmodulecol(source)\n return self.genitems([modcol])"},{"col":4,"comment":"Return the module collection node for ``source``.\n\n This writes ``source`` to a file using :py:meth:`makepyfile` and then\n runs the pytest collection on it, returning the collection node for the\n test module.\n\n :param source: the source code of the module to collect\n\n :param configargs: any extra arguments to pass to\n :py:meth:`parseconfigure`\n\n :param withinit: whether to also write an ``__init__.py`` file to the\n same directory to ensure it is a package\n\n ","endLoc":1013,"header":"def getmodulecol(self, source, configargs=(), withinit=False)","id":6533,"name":"getmodulecol","nodeType":"Function","startLoc":988,"text":"def getmodulecol(self, source, configargs=(), withinit=False):\n \"\"\"Return the module collection node for ``source``.\n\n This writes ``source`` to a file using :py:meth:`makepyfile` and then\n runs the pytest collection on it, returning the collection node for the\n test module.\n\n :param source: the source code of the module to collect\n\n :param configargs: any extra arguments to pass to\n :py:meth:`parseconfigure`\n\n :param withinit: whether to also write an ``__init__.py`` file to the\n same directory to ensure it is a package\n\n \"\"\"\n if isinstance(source, Path):\n path = self.tmpdir.join(str(source))\n assert not withinit, \"not supported for paths\"\n else:\n kw = {self.request.function.__name__: Source(source).strip()}\n path = self.makepyfile(**kw)\n if withinit:\n self.makepyfile(__init__=\"#\")\n self.config = config = self.parseconfigure(path, *configargs)\n return self.getnode(config, path)"},{"col":4,"comment":"Run a test module in process using ``pytest.main()``.\n\n This run writes \"source\" into a temporary file and runs\n ``pytest.main()`` on it, returning a :py:class:`HookRecorder` instance\n for the result.\n\n :param source: the source code of the test module\n\n :param cmdlineargs: any extra command line arguments to use\n\n :return: :py:class:`HookRecorder` instance of the result\n\n ","endLoc":773,"header":"def inline_runsource(self, source, *cmdlineargs)","id":6534,"name":"inline_runsource","nodeType":"Function","startLoc":757,"text":"def inline_runsource(self, source, *cmdlineargs):\n \"\"\"Run a test module in process using ``pytest.main()``.\n\n This run writes \"source\" into a temporary file and runs\n ``pytest.main()`` on it, returning a :py:class:`HookRecorder` instance\n for the result.\n\n :param source: the source code of the test module\n\n :param cmdlineargs: any extra command line arguments to use\n\n :return: :py:class:`HookRecorder` instance of the result\n\n \"\"\"\n p = self.makepyfile(source)\n values = list(cmdlineargs) + [p]\n return self.inline_run(*values)"},{"id":6535,"name":"release-3.2.3.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.2.3\n=======================================\n\npytest 3.2.3 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n* Evan\n* Joe Hamman\n* Oliver Bestwalter\n* Ronny Pfannschmidt\n* Xuan Luong\n\n\nHappy testing,\nThe pytest Development Team\n"},{"id":6536,"name":"release-3.3.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.3.1\n=======================================\n\npytest 3.3.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n* Daniel Hahler\n* Eugene Prikazchikov\n* Florian Bruhin\n* Roland Puntaier\n* Ronny Pfannschmidt\n* Sebastian Rahlf\n* Tom Viner\n\n\nHappy testing,\nThe pytest Development Team\n"},{"id":6537,"name":"release-4.6.3.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-4.6.3\n=======================================\n\npytest 4.6.3 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Dirk Thomas\n\n\nHappy testing,\nThe pytest Development Team\n"},{"id":6538,"name":"release-3.7.0.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.7.0\n=======================================\n\nThe pytest team is proud to announce the 3.7.0 release!\n\npytest is a mature Python testing tool with more than a 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n http://doc.pytest.org/en/latest/changelog.html\n\nFor complete documentation, please visit:\n\n http://docs.pytest.org\n\nAs usual, you can upgrade from pypi via:\n\n pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Alan\n* Alan Brammer\n* Ammar Najjar\n* Anthony Sottile\n* Bruno Oliveira\n* Jeffrey Rackauckas\n* Kale Kundert\n* Ronny Pfannschmidt\n* Serhii Mozghovyi\n* Tadek Teleżyński\n* Wil Cooley\n* abrammer\n* avirlrma\n* turturica\n\n\nHappy testing,\nThe Pytest Development Team\n"},{"fileName":"setuponly.py","filePath":"src/_pytest","id":6539,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\n\nimport pytest\n\n\ndef pytest_addoption(parser):\n group = parser.getgroup(\"debugconfig\")\n group.addoption(\n \"--setuponly\",\n \"--setup-only\",\n action=\"store_true\",\n help=\"only setup fixtures, do not execute tests.\",\n )\n group.addoption(\n \"--setupshow\",\n \"--setup-show\",\n action=\"store_true\",\n help=\"show setup of fixtures while executing tests.\",\n )\n\n\n@pytest.hookimpl(hookwrapper=True)\ndef pytest_fixture_setup(fixturedef, request):\n yield\n config = request.config\n if config.option.setupshow:\n if hasattr(request, \"param\"):\n # Save the fixture parameter so ._show_fixture_action() can\n # display it now and during the teardown (in .finish()).\n if fixturedef.ids:\n if callable(fixturedef.ids):\n fixturedef.cached_param = fixturedef.ids(request.param)\n else:\n fixturedef.cached_param = fixturedef.ids[request.param_index]\n else:\n fixturedef.cached_param = request.param\n _show_fixture_action(fixturedef, \"SETUP\")\n\n\ndef pytest_fixture_post_finalizer(fixturedef):\n if hasattr(fixturedef, \"cached_result\"):\n config = fixturedef._fixturemanager.config\n if config.option.setupshow:\n _show_fixture_action(fixturedef, \"TEARDOWN\")\n if hasattr(fixturedef, \"cached_param\"):\n del fixturedef.cached_param\n\n\ndef _show_fixture_action(fixturedef, msg):\n config = fixturedef._fixturemanager.config\n capman = config.pluginmanager.getplugin(\"capturemanager\")\n if capman:\n capman.suspend_global_capture()\n out, err = capman.read_global_capture()\n\n tw = config.get_terminal_writer()\n tw.line()\n tw.write(\" \" * 2 * fixturedef.scopenum)\n tw.write(\n \"{step} {scope} {fixture}\".format(\n step=msg.ljust(8), # align the output to TEARDOWN\n scope=fixturedef.scope[0].upper(),\n fixture=fixturedef.argname,\n )\n )\n\n if msg == \"SETUP\":\n deps = sorted(arg for arg in fixturedef.argnames if arg != \"request\")\n if deps:\n tw.write(\" (fixtures used: {})\".format(\", \".join(deps)))\n\n if hasattr(fixturedef, \"cached_param\"):\n tw.write(\"[{}]\".format(fixturedef.cached_param))\n\n if capman:\n capman.resume_global_capture()\n sys.stdout.write(out)\n sys.stderr.write(err)\n\n\n@pytest.hookimpl(tryfirst=True)\ndef pytest_cmdline_main(config):\n if config.option.setuponly:\n config.option.setupshow = True\n"},{"col":0,"comment":"null","endLoc":24,"header":"def pytest_addoption(parser)","id":6540,"name":"pytest_addoption","nodeType":"Function","startLoc":11,"text":"def pytest_addoption(parser):\n group = parser.getgroup(\"debugconfig\")\n group.addoption(\n \"--setuponly\",\n \"--setup-only\",\n action=\"store_true\",\n help=\"only setup fixtures, do not execute tests.\",\n )\n group.addoption(\n \"--setupshow\",\n \"--setup-show\",\n action=\"store_true\",\n help=\"show setup of fixtures while executing tests.\",\n )"},{"col":4,"comment":"Run ``pytest.main()`` in-process, returning a HookRecorder.\n\n Runs the :py:func:`pytest.main` function to run all of pytest inside\n the test process itself. This means it can return a\n :py:class:`HookRecorder` instance which gives more detailed results\n from that run than can be done by matching stdout/stderr from\n :py:meth:`runpytest`.\n\n :param args: command line arguments to pass to :py:func:`pytest.main`\n\n :param plugins: (keyword-only) extra plugin instances the\n ``pytest.main()`` instance should use\n\n :return: a :py:class:`HookRecorder` instance\n ","endLoc":866,"header":"def inline_run(self, *args, **kwargs)","id":6541,"name":"inline_run","nodeType":"Function","startLoc":787,"text":"def inline_run(self, *args, **kwargs):\n \"\"\"Run ``pytest.main()`` in-process, returning a HookRecorder.\n\n Runs the :py:func:`pytest.main` function to run all of pytest inside\n the test process itself. This means it can return a\n :py:class:`HookRecorder` instance which gives more detailed results\n from that run than can be done by matching stdout/stderr from\n :py:meth:`runpytest`.\n\n :param args: command line arguments to pass to :py:func:`pytest.main`\n\n :param plugins: (keyword-only) extra plugin instances the\n ``pytest.main()`` instance should use\n\n :return: a :py:class:`HookRecorder` instance\n \"\"\"\n plugins = kwargs.pop(\"plugins\", [])\n no_reraise_ctrlc = kwargs.pop(\"no_reraise_ctrlc\", None)\n raise_on_kwargs(kwargs)\n\n finalizers = []\n try:\n # Do not load user config (during runs only).\n mp_run = MonkeyPatch()\n for k, v in self._env_run_update.items():\n mp_run.setenv(k, v)\n finalizers.append(mp_run.undo)\n\n # When running pytest inline any plugins active in the main test\n # process are already imported. So this disables the warning which\n # will trigger to say they can no longer be rewritten, which is\n # fine as they have already been rewritten.\n orig_warn = AssertionRewritingHook._warn_already_imported\n\n def revert_warn_already_imported():\n AssertionRewritingHook._warn_already_imported = orig_warn\n\n finalizers.append(revert_warn_already_imported)\n AssertionRewritingHook._warn_already_imported = lambda *a: None\n\n # Any sys.module or sys.path changes done while running pytest\n # inline should be reverted after the test run completes to avoid\n # clashing with later inline tests run within the same pytest test,\n # e.g. just because they use matching test module names.\n finalizers.append(self.__take_sys_modules_snapshot().restore)\n finalizers.append(SysPathsSnapshot().restore)\n\n # Important note:\n # - our tests should not leave any other references/registrations\n # laying around other than possibly loaded test modules\n # referenced from sys.modules, as nothing will clean those up\n # automatically\n\n rec = []\n\n class Collect(object):\n def pytest_configure(x, config):\n rec.append(self.make_hook_recorder(config.pluginmanager))\n\n plugins.append(Collect())\n ret = pytest.main(list(args), plugins=plugins)\n if len(rec) == 1:\n reprec = rec.pop()\n else:\n\n class reprec(object):\n pass\n\n reprec.ret = ret\n\n # typically we reraise keyboard interrupts from the child run\n # because it's our user requesting interruption of the testing\n if ret == EXIT_INTERRUPTED and not no_reraise_ctrlc:\n calls = reprec.getcalls(\"pytest_keyboard_interrupt\")\n if calls and calls[-1].excinfo.type == KeyboardInterrupt:\n raise KeyboardInterrupt()\n return reprec\n finally:\n for finalizer in finalizers:\n finalizer()"},{"col":0,"comment":"null","endLoc":84,"header":"def raise_on_kwargs(kwargs)","id":6542,"name":"raise_on_kwargs","nodeType":"Function","startLoc":79,"text":"def raise_on_kwargs(kwargs):\n __tracebackhide__ = True\n if kwargs: # pragma: no branch\n raise TypeError(\n \"Unexpected keyword arguments: {}\".format(\", \".join(sorted(kwargs)))\n )"},{"col":4,"comment":"null","endLoc":193,"header":"def test_traceback_filter(self)","id":6543,"name":"test_traceback_filter","nodeType":"Function","startLoc":190,"text":"def test_traceback_filter(self):\n traceback = self.excinfo.traceback\n ntraceback = traceback.filter()\n assert len(ntraceback) == len(traceback) - 1"},{"col":0,"comment":"null","endLoc":42,"header":"@pytest.hookimpl(hookwrapper=True)\ndef pytest_fixture_setup(fixturedef, request)","id":6544,"name":"pytest_fixture_setup","nodeType":"Function","startLoc":27,"text":"@pytest.hookimpl(hookwrapper=True)\ndef pytest_fixture_setup(fixturedef, request):\n yield\n config = request.config\n if config.option.setupshow:\n if hasattr(request, \"param\"):\n # Save the fixture parameter so ._show_fixture_action() can\n # display it now and during the teardown (in .finish()).\n if fixturedef.ids:\n if callable(fixturedef.ids):\n fixturedef.cached_param = fixturedef.ids(request.param)\n else:\n fixturedef.cached_param = fixturedef.ids[request.param_index]\n else:\n fixturedef.cached_param = request.param\n _show_fixture_action(fixturedef, \"SETUP\")"},{"col":60,"endLoc":825,"id":6545,"nodeType":"Lambda","startLoc":825,"text":"lambda *a: None"},{"col":4,"comment":"null","endLoc":231,"header":"@pytest.mark.parametrize(\n \"tracebackhide, matching\",\n [\n (lambda info: True, True),\n (lambda info","id":6546,"name":"test_traceback_filter_selective","nodeType":"Function","startLoc":195,"text":"@pytest.mark.parametrize(\n \"tracebackhide, matching\",\n [\n (lambda info: True, True),\n (lambda info: False, False),\n (operator.methodcaller(\"errisinstance\", ValueError), True),\n (operator.methodcaller(\"errisinstance\", IndexError), False),\n ],\n )\n def test_traceback_filter_selective(self, tracebackhide, matching):\n def f():\n #\n raise ValueError\n #\n\n def g():\n #\n __tracebackhide__ = tracebackhide\n f()\n #\n\n def h():\n #\n g()\n #\n\n excinfo = pytest.raises(ValueError, h)\n traceback = excinfo.traceback\n ntraceback = traceback.filter()\n print(\"old: {!r}\".format(traceback))\n print(\"new: {!r}\".format(ntraceback))\n\n if matching:\n assert len(ntraceback) == len(traceback) - 2\n else:\n # -1 because of the __tracebackhide__ in pytest.raises\n assert len(ntraceback) == len(traceback) - 1"},{"col":13,"endLoc":198,"id":6547,"nodeType":"Lambda","startLoc":198,"text":"lambda info: True"},{"col":13,"endLoc":199,"id":6548,"nodeType":"Lambda","startLoc":199,"text":"lambda info: False"},{"className":"TestUnicodeHandling","col":0,"comment":"Test various combinations of bytes and unicode with pytest.raises (#5478)\n\n https://github.com/pytest-dev/pytest/pull/5479#discussion_r298852433\n ","endLoc":325,"id":6549,"nodeType":"Class","startLoc":284,"text":"class TestUnicodeHandling:\n \"\"\"Test various combinations of bytes and unicode with pytest.raises (#5478)\n\n https://github.com/pytest-dev/pytest/pull/5479#discussion_r298852433\n \"\"\"\n\n success = dummy_context_manager\n py2_only = pytest.mark.skipif(\n not six.PY2, reason=\"bytes in raises only supported in Python 2\"\n )\n\n @pytest.mark.parametrize(\n \"message, match, expectation\",\n [\n (u\"\\u2603\", u\"\\u2603\", success()),\n (u\"\\u2603\", u\"\\u2603foo\", pytest.raises(AssertionError)),\n pytest.param(b\"hello\", b\"hello\", success(), marks=py2_only),\n pytest.param(\n b\"hello\", b\"world\", pytest.raises(AssertionError), marks=py2_only\n ),\n pytest.param(u\"hello\", b\"hello\", success(), marks=py2_only),\n pytest.param(\n u\"hello\", b\"world\", pytest.raises(AssertionError), marks=py2_only\n ),\n pytest.param(\n u\"😊\".encode(\"UTF-8\"),\n b\"world\",\n pytest.raises(AssertionError),\n marks=py2_only,\n ),\n pytest.param(\n u\"world\",\n u\"😊\".encode(\"UTF-8\"),\n pytest.raises(AssertionError),\n marks=py2_only,\n ),\n ],\n )\n def test_handling(self, message, match, expectation):\n with expectation:\n with pytest.raises(RuntimeError, match=match):\n raise RuntimeError(message)"},{"col":4,"comment":"null","endLoc":325,"header":"@pytest.mark.parametrize(\n \"message, match, expectation\",\n [\n (u\"\\u2603\", u\"\\u2603\", success()),\n (u\"\\u2603\", u\"\\u2603foo\", pytest.raises(AssertionError)),\n pytest.param(b\"hello\", b\"hello\", success(), marks=py2_only),\n pytest.param(\n b\"hello\", b\"world\", pytest.raises(AssertionError), marks=py2_only\n ),\n pytest.param(u\"hello\", b\"hello\", success(), marks=py2_only),\n pytest.param(\n u\"hello\", b\"world\", pytest.raises(AssertionError), marks=py2_only\n ),\n pytest.param(\n u\"😊\".encode(\"UTF-8\"),\n b\"world\",\n pytest.raises(AssertionError),\n marks=py2_only,\n ),\n pytest.param(\n u\"world\",\n u\"😊\".encode(\"UTF-8\"),\n pytest.raises(AssertionError),\n marks=py2_only,\n ),\n ],\n )\n def test_handling(self, message, match, expectation)","id":6550,"name":"test_handling","nodeType":"Function","startLoc":295,"text":"@pytest.mark.parametrize(\n \"message, match, expectation\",\n [\n (u\"\\u2603\", u\"\\u2603\", success()),\n (u\"\\u2603\", u\"\\u2603foo\", pytest.raises(AssertionError)),\n pytest.param(b\"hello\", b\"hello\", success(), marks=py2_only),\n pytest.param(\n b\"hello\", b\"world\", pytest.raises(AssertionError), marks=py2_only\n ),\n pytest.param(u\"hello\", b\"hello\", success(), marks=py2_only),\n pytest.param(\n u\"hello\", b\"world\", pytest.raises(AssertionError), marks=py2_only\n ),\n pytest.param(\n u\"😊\".encode(\"UTF-8\"),\n b\"world\",\n pytest.raises(AssertionError),\n marks=py2_only,\n ),\n pytest.param(\n u\"world\",\n u\"😊\".encode(\"UTF-8\"),\n pytest.raises(AssertionError),\n marks=py2_only,\n ),\n ],\n )\n def test_handling(self, message, match, expectation):\n with expectation:\n with pytest.raises(RuntimeError, match=match):\n raise RuntimeError(message)"},{"col":0,"comment":"null","endLoc":83,"header":"def _show_fixture_action(fixturedef, msg)","id":6551,"name":"_show_fixture_action","nodeType":"Function","startLoc":54,"text":"def _show_fixture_action(fixturedef, msg):\n config = fixturedef._fixturemanager.config\n capman = config.pluginmanager.getplugin(\"capturemanager\")\n if capman:\n capman.suspend_global_capture()\n out, err = capman.read_global_capture()\n\n tw = config.get_terminal_writer()\n tw.line()\n tw.write(\" \" * 2 * fixturedef.scopenum)\n tw.write(\n \"{step} {scope} {fixture}\".format(\n step=msg.ljust(8), # align the output to TEARDOWN\n scope=fixturedef.scope[0].upper(),\n fixture=fixturedef.argname,\n )\n )\n\n if msg == \"SETUP\":\n deps = sorted(arg for arg in fixturedef.argnames if arg != \"request\")\n if deps:\n tw.write(\" (fixtures used: {})\".format(\", \".join(deps)))\n\n if hasattr(fixturedef, \"cached_param\"):\n tw.write(\"[{}]\".format(fixturedef.cached_param))\n\n if capman:\n capman.resume_global_capture()\n sys.stdout.write(out)\n sys.stderr.write(err)"},{"col":4,"comment":"null","endLoc":227,"header":"def test_getstatementrange_triple_quoted(self)","id":6552,"name":"test_getstatementrange_triple_quoted","nodeType":"Function","startLoc":218,"text":"def test_getstatementrange_triple_quoted(self):\n # print str(self.source)\n source = Source(\n \"\"\"hello('''\n ''')\"\"\"\n )\n s = source.getstatement(0)\n assert s == str(source)\n s = source.getstatement(1)\n assert s == str(source)"},{"className":"TempPathFactory","col":0,"comment":"Factory for temporary directories under the common base temp directory.\n\n The base directory can be configured using the ``--basetemp`` option.","endLoc":84,"id":6554,"nodeType":"Class","startLoc":25,"text":"@attr.s\nclass TempPathFactory(object):\n \"\"\"Factory for temporary directories under the common base temp directory.\n\n The base directory can be configured using the ``--basetemp`` option.\"\"\"\n\n _given_basetemp = attr.ib(\n # using os.path.abspath() to get absolute path instead of resolve() as it\n # does not work the same in all platforms (see #4427)\n # Path.absolute() exists, but it is not public (see https://bugs.python.org/issue25012)\n converter=attr.converters.optional(\n lambda p: Path(os.path.abspath(six.text_type(p)))\n )\n )\n _trace = attr.ib()\n _basetemp = attr.ib(default=None)\n\n @classmethod\n def from_config(cls, config):\n \"\"\"\n :param config: a pytest configuration\n \"\"\"\n return cls(\n given_basetemp=config.option.basetemp, trace=config.trace.get(\"tmpdir\")\n )\n\n def mktemp(self, basename, numbered=True):\n \"\"\"makes a temporary directory managed by the factory\"\"\"\n if not numbered:\n p = self.getbasetemp().joinpath(basename)\n p.mkdir()\n else:\n p = make_numbered_dir(root=self.getbasetemp(), prefix=basename)\n self._trace(\"mktemp\", p)\n return p\n\n def getbasetemp(self):\n \"\"\" return base temporary directory. \"\"\"\n if self._basetemp is not None:\n return self._basetemp\n\n if self._given_basetemp is not None:\n basetemp = self._given_basetemp\n ensure_reset_dir(basetemp)\n basetemp = basetemp.resolve()\n else:\n from_env = os.environ.get(\"PYTEST_DEBUG_TEMPROOT\")\n temproot = Path(from_env or tempfile.gettempdir()).resolve()\n user = get_user() or \"unknown\"\n # use a sub-directory in the temproot to speed-up\n # make_numbered_dir() call\n rootdir = temproot.joinpath(\"pytest-of-{}\".format(user))\n rootdir.mkdir(exist_ok=True)\n basetemp = make_numbered_dir_with_cleanup(\n prefix=\"pytest-\", root=rootdir, keep=3, lock_timeout=LOCK_TIMEOUT\n )\n assert basetemp is not None, basetemp\n self._basetemp = t = basetemp\n self._trace(\"new basetemp\", t)\n return t"},{"col":4,"comment":"\n :param config: a pytest configuration\n ","endLoc":49,"header":"@classmethod\n def from_config(cls, config)","id":6556,"name":"from_config","nodeType":"Function","startLoc":42,"text":"@classmethod\n def from_config(cls, config):\n \"\"\"\n :param config: a pytest configuration\n \"\"\"\n return cls(\n given_basetemp=config.option.basetemp, trace=config.trace.get(\"tmpdir\")\n )"},{"fileName":"test_monkeypatch.py","filePath":"testing","id":6557,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport re\nimport sys\nimport textwrap\n\nimport six\n\nimport pytest\nfrom _pytest.monkeypatch import MonkeyPatch\n\n\n@pytest.fixture\ndef mp():\n cwd = os.getcwd()\n sys_path = list(sys.path)\n yield MonkeyPatch()\n sys.path[:] = sys_path\n os.chdir(cwd)\n\n\ndef test_setattr():\n class A(object):\n x = 1\n\n monkeypatch = MonkeyPatch()\n pytest.raises(AttributeError, monkeypatch.setattr, A, \"notexists\", 2)\n monkeypatch.setattr(A, \"y\", 2, raising=False)\n assert A.y == 2\n monkeypatch.undo()\n assert not hasattr(A, \"y\")\n\n monkeypatch = MonkeyPatch()\n monkeypatch.setattr(A, \"x\", 2)\n assert A.x == 2\n monkeypatch.setattr(A, \"x\", 3)\n assert A.x == 3\n monkeypatch.undo()\n assert A.x == 1\n\n A.x = 5\n monkeypatch.undo() # double-undo makes no modification\n assert A.x == 5\n\n\nclass TestSetattrWithImportPath(object):\n def test_string_expression(self, monkeypatch):\n monkeypatch.setattr(\"os.path.abspath\", lambda x: \"hello2\")\n assert os.path.abspath(\"123\") == \"hello2\"\n\n def test_string_expression_class(self, monkeypatch):\n monkeypatch.setattr(\"_pytest.config.Config\", 42)\n import _pytest\n\n assert _pytest.config.Config == 42\n\n def test_unicode_string(self, monkeypatch):\n monkeypatch.setattr(\"_pytest.config.Config\", 42)\n import _pytest\n\n assert _pytest.config.Config == 42\n monkeypatch.delattr(\"_pytest.config.Config\")\n\n def test_wrong_target(self, monkeypatch):\n pytest.raises(TypeError, lambda: monkeypatch.setattr(None, None))\n\n def test_unknown_import(self, monkeypatch):\n pytest.raises(ImportError, lambda: monkeypatch.setattr(\"unkn123.classx\", None))\n\n def test_unknown_attr(self, monkeypatch):\n pytest.raises(\n AttributeError, lambda: monkeypatch.setattr(\"os.path.qweqwe\", None)\n )\n\n def test_unknown_attr_non_raising(self, monkeypatch):\n # https://github.com/pytest-dev/pytest/issues/746\n monkeypatch.setattr(\"os.path.qweqwe\", 42, raising=False)\n assert os.path.qweqwe == 42\n\n def test_delattr(self, monkeypatch):\n monkeypatch.delattr(\"os.path.abspath\")\n assert not hasattr(os.path, \"abspath\")\n monkeypatch.undo()\n assert os.path.abspath\n\n\ndef test_delattr():\n class A(object):\n x = 1\n\n monkeypatch = MonkeyPatch()\n monkeypatch.delattr(A, \"x\")\n assert not hasattr(A, \"x\")\n monkeypatch.undo()\n assert A.x == 1\n\n monkeypatch = MonkeyPatch()\n monkeypatch.delattr(A, \"x\")\n pytest.raises(AttributeError, monkeypatch.delattr, A, \"y\")\n monkeypatch.delattr(A, \"y\", raising=False)\n monkeypatch.setattr(A, \"x\", 5, raising=False)\n assert A.x == 5\n monkeypatch.undo()\n assert A.x == 1\n\n\ndef test_setitem():\n d = {\"x\": 1}\n monkeypatch = MonkeyPatch()\n monkeypatch.setitem(d, \"x\", 2)\n monkeypatch.setitem(d, \"y\", 1700)\n monkeypatch.setitem(d, \"y\", 1700)\n assert d[\"x\"] == 2\n assert d[\"y\"] == 1700\n monkeypatch.setitem(d, \"x\", 3)\n assert d[\"x\"] == 3\n monkeypatch.undo()\n assert d[\"x\"] == 1\n assert \"y\" not in d\n d[\"x\"] = 5\n monkeypatch.undo()\n assert d[\"x\"] == 5\n\n\ndef test_setitem_deleted_meanwhile():\n d = {}\n monkeypatch = MonkeyPatch()\n monkeypatch.setitem(d, \"x\", 2)\n del d[\"x\"]\n monkeypatch.undo()\n assert not d\n\n\n@pytest.mark.parametrize(\"before\", [True, False])\ndef test_setenv_deleted_meanwhile(before):\n key = \"qwpeoip123\"\n if before:\n os.environ[key] = \"world\"\n monkeypatch = MonkeyPatch()\n monkeypatch.setenv(key, \"hello\")\n del os.environ[key]\n monkeypatch.undo()\n if before:\n assert os.environ[key] == \"world\"\n del os.environ[key]\n else:\n assert key not in os.environ\n\n\ndef test_delitem():\n d = {\"x\": 1}\n monkeypatch = MonkeyPatch()\n monkeypatch.delitem(d, \"x\")\n assert \"x\" not in d\n monkeypatch.delitem(d, \"y\", raising=False)\n pytest.raises(KeyError, monkeypatch.delitem, d, \"y\")\n assert not d\n monkeypatch.setitem(d, \"y\", 1700)\n assert d[\"y\"] == 1700\n d[\"hello\"] = \"world\"\n monkeypatch.setitem(d, \"x\", 1500)\n assert d[\"x\"] == 1500\n monkeypatch.undo()\n assert d == {\"hello\": \"world\", \"x\": 1}\n\n\ndef test_setenv():\n monkeypatch = MonkeyPatch()\n with pytest.warns(pytest.PytestWarning):\n monkeypatch.setenv(\"XYZ123\", 2)\n import os\n\n assert os.environ[\"XYZ123\"] == \"2\"\n monkeypatch.undo()\n assert \"XYZ123\" not in os.environ\n\n\ndef test_delenv():\n name = \"xyz1234\"\n assert name not in os.environ\n monkeypatch = MonkeyPatch()\n pytest.raises(KeyError, monkeypatch.delenv, name, raising=True)\n monkeypatch.delenv(name, raising=False)\n monkeypatch.undo()\n os.environ[name] = \"1\"\n try:\n monkeypatch = MonkeyPatch()\n monkeypatch.delenv(name)\n assert name not in os.environ\n monkeypatch.setenv(name, \"3\")\n assert os.environ[name] == \"3\"\n monkeypatch.undo()\n assert os.environ[name] == \"1\"\n finally:\n if name in os.environ:\n del os.environ[name]\n\n\nclass TestEnvironWarnings(object):\n \"\"\"\n os.environ keys and values should be native strings, otherwise it will cause problems with other modules (notably\n subprocess). On Python 2 os.environ accepts anything without complaining, while Python 3 does the right thing\n and raises an error.\n \"\"\"\n\n VAR_NAME = u\"PYTEST_INTERNAL_MY_VAR\"\n\n @pytest.mark.skipif(not six.PY2, reason=\"Python 2 only test\")\n def test_setenv_unicode_key(self, monkeypatch):\n with pytest.warns(\n pytest.PytestWarning,\n match=\"Environment variable name {!r} should be str\".format(self.VAR_NAME),\n ):\n monkeypatch.setenv(self.VAR_NAME, \"2\")\n\n @pytest.mark.skipif(not six.PY2, reason=\"Python 2 only test\")\n def test_delenv_unicode_key(self, monkeypatch):\n with pytest.warns(\n pytest.PytestWarning,\n match=\"Environment variable name {!r} should be str\".format(self.VAR_NAME),\n ):\n monkeypatch.delenv(self.VAR_NAME, raising=False)\n\n def test_setenv_non_str_warning(self, monkeypatch):\n value = 2\n msg = (\n \"Value of environment variable PYTEST_INTERNAL_MY_VAR type should be str, \"\n \"but got 2 (type: int); converted to str implicitly\"\n )\n with pytest.warns(pytest.PytestWarning, match=re.escape(msg)):\n monkeypatch.setenv(str(self.VAR_NAME), value)\n\n\ndef test_setenv_prepend():\n import os\n\n monkeypatch = MonkeyPatch()\n with pytest.warns(pytest.PytestWarning):\n monkeypatch.setenv(\"XYZ123\", 2, prepend=\"-\")\n assert os.environ[\"XYZ123\"] == \"2\"\n with pytest.warns(pytest.PytestWarning):\n monkeypatch.setenv(\"XYZ123\", 3, prepend=\"-\")\n assert os.environ[\"XYZ123\"] == \"3-2\"\n monkeypatch.undo()\n assert \"XYZ123\" not in os.environ\n\n\ndef test_monkeypatch_plugin(testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n def test_method(monkeypatch):\n assert monkeypatch.__class__.__name__ == \"MonkeyPatch\"\n \"\"\"\n )\n res = reprec.countoutcomes()\n assert tuple(res) == (1, 0, 0), res\n\n\ndef test_syspath_prepend(mp):\n old = list(sys.path)\n mp.syspath_prepend(\"world\")\n mp.syspath_prepend(\"hello\")\n assert sys.path[0] == \"hello\"\n assert sys.path[1] == \"world\"\n mp.undo()\n assert sys.path == old\n mp.undo()\n assert sys.path == old\n\n\ndef test_syspath_prepend_double_undo(mp):\n old_syspath = sys.path[:]\n try:\n mp.syspath_prepend(\"hello world\")\n mp.undo()\n sys.path.append(\"more hello world\")\n mp.undo()\n assert sys.path[-1] == \"more hello world\"\n finally:\n sys.path[:] = old_syspath\n\n\ndef test_chdir_with_path_local(mp, tmpdir):\n mp.chdir(tmpdir)\n assert os.getcwd() == tmpdir.strpath\n\n\ndef test_chdir_with_str(mp, tmpdir):\n mp.chdir(tmpdir.strpath)\n assert os.getcwd() == tmpdir.strpath\n\n\ndef test_chdir_undo(mp, tmpdir):\n cwd = os.getcwd()\n mp.chdir(tmpdir)\n mp.undo()\n assert os.getcwd() == cwd\n\n\ndef test_chdir_double_undo(mp, tmpdir):\n mp.chdir(tmpdir.strpath)\n mp.undo()\n tmpdir.chdir()\n mp.undo()\n assert os.getcwd() == tmpdir.strpath\n\n\ndef test_issue185_time_breaks(testdir):\n testdir.makepyfile(\n \"\"\"\n import time\n def test_m(monkeypatch):\n def f():\n raise Exception\n monkeypatch.setattr(time, \"time\", f)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n \"\"\"\n *1 passed*\n \"\"\"\n )\n\n\ndef test_importerror(testdir):\n p = testdir.mkpydir(\"package\")\n p.join(\"a.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import doesnotexist\n\n x = 1\n \"\"\"\n )\n )\n testdir.tmpdir.join(\"test_importerror.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_importerror(monkeypatch):\n monkeypatch.setattr('package.a.x', 2)\n \"\"\"\n )\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n \"\"\"\n *import error in package.a: No module named {0}doesnotexist{0}*\n \"\"\".format(\n \"'\" if sys.version_info > (3, 0) else \"\"\n )\n )\n\n\nclass SampleNew(object):\n @staticmethod\n def hello():\n return True\n\n\nclass SampleNewInherit(SampleNew):\n pass\n\n\nclass SampleOld(object):\n # oldstyle on python2\n @staticmethod\n def hello():\n return True\n\n\nclass SampleOldInherit(SampleOld):\n pass\n\n\n@pytest.mark.parametrize(\n \"Sample\",\n [SampleNew, SampleNewInherit, SampleOld, SampleOldInherit],\n ids=[\"new\", \"new-inherit\", \"old\", \"old-inherit\"],\n)\ndef test_issue156_undo_staticmethod(Sample):\n monkeypatch = MonkeyPatch()\n\n monkeypatch.setattr(Sample, \"hello\", None)\n assert Sample.hello is None\n\n monkeypatch.undo()\n assert Sample.hello()\n\n\ndef test_undo_class_descriptors_delattr():\n class SampleParent(object):\n @classmethod\n def hello(_cls):\n pass\n\n @staticmethod\n def world():\n pass\n\n class SampleChild(SampleParent):\n pass\n\n monkeypatch = MonkeyPatch()\n\n original_hello = SampleChild.hello\n original_world = SampleChild.world\n monkeypatch.delattr(SampleParent, \"hello\")\n monkeypatch.delattr(SampleParent, \"world\")\n assert getattr(SampleParent, \"hello\", None) is None\n assert getattr(SampleParent, \"world\", None) is None\n\n monkeypatch.undo()\n assert original_hello == SampleChild.hello\n assert original_world == SampleChild.world\n\n\ndef test_issue1338_name_resolving():\n pytest.importorskip(\"requests\")\n monkeypatch = MonkeyPatch()\n try:\n monkeypatch.delattr(\"requests.sessions.Session.request\")\n finally:\n monkeypatch.undo()\n\n\ndef test_context():\n monkeypatch = MonkeyPatch()\n\n import functools\n import inspect\n\n with monkeypatch.context() as m:\n m.setattr(functools, \"partial\", 3)\n assert not inspect.isclass(functools.partial)\n assert inspect.isclass(functools.partial)\n\n\ndef test_syspath_prepend_with_namespace_packages(testdir, monkeypatch):\n for dirname in \"hello\", \"world\":\n d = testdir.mkdir(dirname)\n ns = d.mkdir(\"ns_pkg\")\n ns.join(\"__init__.py\").write(\n \"__import__('pkg_resources').declare_namespace(__name__)\"\n )\n lib = ns.mkdir(dirname)\n lib.join(\"__init__.py\").write(\"def check(): return %r\" % dirname)\n\n monkeypatch.syspath_prepend(\"hello\")\n import ns_pkg.hello\n\n assert ns_pkg.hello.check() == \"hello\"\n\n with pytest.raises(ImportError):\n import ns_pkg.world\n\n # Prepending should call fixup_namespace_packages.\n monkeypatch.syspath_prepend(\"world\")\n import ns_pkg.world\n\n assert ns_pkg.world.check() == \"world\"\n\n # Should invalidate caches via importlib.invalidate_caches.\n tmpdir = testdir.tmpdir\n modules_tmpdir = tmpdir.mkdir(\"modules_tmpdir\")\n monkeypatch.syspath_prepend(str(modules_tmpdir))\n modules_tmpdir.join(\"main_app.py\").write(\"app = True\")\n from main_app import app # noqa: F401\n"},{"className":"TestSetattrWithImportPath","col":0,"comment":"null","endLoc":88,"id":6558,"nodeType":"Class","startLoc":50,"text":"class TestSetattrWithImportPath(object):\n def test_string_expression(self, monkeypatch):\n monkeypatch.setattr(\"os.path.abspath\", lambda x: \"hello2\")\n assert os.path.abspath(\"123\") == \"hello2\"\n\n def test_string_expression_class(self, monkeypatch):\n monkeypatch.setattr(\"_pytest.config.Config\", 42)\n import _pytest\n\n assert _pytest.config.Config == 42\n\n def test_unicode_string(self, monkeypatch):\n monkeypatch.setattr(\"_pytest.config.Config\", 42)\n import _pytest\n\n assert _pytest.config.Config == 42\n monkeypatch.delattr(\"_pytest.config.Config\")\n\n def test_wrong_target(self, monkeypatch):\n pytest.raises(TypeError, lambda: monkeypatch.setattr(None, None))\n\n def test_unknown_import(self, monkeypatch):\n pytest.raises(ImportError, lambda: monkeypatch.setattr(\"unkn123.classx\", None))\n\n def test_unknown_attr(self, monkeypatch):\n pytest.raises(\n AttributeError, lambda: monkeypatch.setattr(\"os.path.qweqwe\", None)\n )\n\n def test_unknown_attr_non_raising(self, monkeypatch):\n # https://github.com/pytest-dev/pytest/issues/746\n monkeypatch.setattr(\"os.path.qweqwe\", 42, raising=False)\n assert os.path.qweqwe == 42\n\n def test_delattr(self, monkeypatch):\n monkeypatch.delattr(\"os.path.abspath\")\n assert not hasattr(os.path, \"abspath\")\n monkeypatch.undo()\n assert os.path.abspath"},{"col":4,"comment":"Call a helper in this module.","endLoc":740,"header":"def helper(self, name, *args)","id":6559,"name":"helper","nodeType":"Function","startLoc":736,"text":"def helper(self, name, *args):\n \"\"\"Call a helper in this module.\"\"\"\n py_name = ast.Name(\"@pytest_ar\", ast.Load())\n attr = ast.Attribute(py_name, name, ast.Load())\n return ast_Call(attr, list(args), [])"},{"col":4,"comment":"null","endLoc":249,"header":"def test_getstatementrange_within_constructs(self)","id":6561,"name":"test_getstatementrange_within_constructs","nodeType":"Function","startLoc":229,"text":"def test_getstatementrange_within_constructs(self):\n source = Source(\n \"\"\"\\\n try:\n try:\n raise ValueError\n except SomeThing:\n pass\n finally:\n 42\n \"\"\"\n )\n assert len(source) == 7\n # check all lineno's that could occur in a traceback\n # assert source.getstatementrange(0) == (0, 7)\n # assert source.getstatementrange(1) == (1, 5)\n assert source.getstatementrange(2) == (2, 3)\n assert source.getstatementrange(3) == (3, 4)\n assert source.getstatementrange(4) == (4, 5)\n # assert source.getstatementrange(5) == (0, 7)\n assert source.getstatementrange(6) == (6, 7)"},{"col":4,"comment":"null","endLoc":53,"header":"def test_string_expression(self, monkeypatch)","id":6562,"name":"test_string_expression","nodeType":"Function","startLoc":51,"text":"def test_string_expression(self, monkeypatch):\n monkeypatch.setattr(\"os.path.abspath\", lambda x: \"hello2\")\n assert os.path.abspath(\"123\") == \"hello2\""},{"col":47,"endLoc":52,"id":6563,"nodeType":"Lambda","startLoc":52,"text":"lambda x: \"hello2\""},{"col":4,"comment":"Run ``pytest.main(['--collectonly'])`` in-process.\n\n Runs the :py:func:`pytest.main` function to run all of pytest inside\n the test process itself like :py:meth:`inline_run`, but returns a\n tuple of the collected items and a :py:class:`HookRecorder` instance.\n\n ","endLoc":785,"header":"def inline_genitems(self, *args)","id":6565,"name":"inline_genitems","nodeType":"Function","startLoc":775,"text":"def inline_genitems(self, *args):\n \"\"\"Run ``pytest.main(['--collectonly'])`` in-process.\n\n Runs the :py:func:`pytest.main` function to run all of pytest inside\n the test process itself like :py:meth:`inline_run`, but returns a\n tuple of the collected items and a :py:class:`HookRecorder` instance.\n\n \"\"\"\n rec = self.inline_run(\"--collect-only\", *args)\n items = [x.item for x in rec.getcalls(\"pytest_itemcollected\")]\n return items, rec"},{"col":4,"comment":"makes a temporary directory managed by the factory","endLoc":59,"header":"def mktemp(self, basename, numbered=True)","id":6566,"name":"mktemp","nodeType":"Function","startLoc":51,"text":"def mktemp(self, basename, numbered=True):\n \"\"\"makes a temporary directory managed by the factory\"\"\"\n if not numbered:\n p = self.getbasetemp().joinpath(basename)\n p.mkdir()\n else:\n p = make_numbered_dir(root=self.getbasetemp(), prefix=basename)\n self._trace(\"mktemp\", p)\n return p"},{"col":4,"comment":"null","endLoc":263,"header":"def test_getstatementrange_bug(self)","id":6567,"name":"test_getstatementrange_bug","nodeType":"Function","startLoc":251,"text":"def test_getstatementrange_bug(self):\n source = Source(\n \"\"\"\\\n try:\n x = (\n y +\n z)\n except:\n pass\n \"\"\"\n )\n assert len(source) == 6\n assert source.getstatementrange(2) == (1, 4)"},{"col":4,"comment":"null","endLoc":280,"header":"def test_getstatementrange_bug2(self)","id":6568,"name":"test_getstatementrange_bug2","nodeType":"Function","startLoc":265,"text":"def test_getstatementrange_bug2(self):\n source = Source(\n \"\"\"\\\n assert (\n 33\n ==\n [\n X(3,\n b=1, c=2\n ),\n ]\n )\n \"\"\"\n )\n assert len(source) == 9\n assert source.getstatementrange(5) == (0, 9)"},{"col":4,"comment":"Return result of running pytest in-process, providing a similar\n interface to what self.runpytest() provides.\n ","endLoc":901,"header":"def runpytest_inprocess(self, *args, **kwargs)","id":6569,"name":"runpytest_inprocess","nodeType":"Function","startLoc":868,"text":"def runpytest_inprocess(self, *args, **kwargs):\n \"\"\"Return result of running pytest in-process, providing a similar\n interface to what self.runpytest() provides.\n \"\"\"\n syspathinsert = kwargs.pop(\"syspathinsert\", False)\n\n if syspathinsert:\n self.syspathinsert()\n now = time.time()\n capture = MultiCapture(Capture=SysCapture)\n capture.start_capturing()\n try:\n try:\n reprec = self.inline_run(*args, **kwargs)\n except SystemExit as e:\n\n class reprec(object):\n ret = e.args[0]\n\n except Exception:\n traceback.print_exc()\n\n class reprec(object):\n ret = 3\n\n finally:\n out, err = capture.readouterr()\n capture.stop_capturing()\n sys.stdout.write(out)\n sys.stderr.write(err)\n\n res = RunResult(reprec.ret, out.split(\"\\n\"), err.split(\"\\n\"), time.time() - now)\n res.reprec = reprec\n return res"},{"col":4,"comment":"null","endLoc":294,"header":"def test_getstatementrange_ast_issue58(self)","id":6571,"name":"test_getstatementrange_ast_issue58","nodeType":"Function","startLoc":282,"text":"def test_getstatementrange_ast_issue58(self):\n source = Source(\n \"\"\"\\\n\n def test_some():\n for a in [a for a in\n CAUSE_ERROR]: pass\n\n x = 3\n \"\"\"\n )\n assert getstatement(2, source).lines == source.lines[2:3]\n assert getstatement(3, source).lines == source.lines[3:4]"},{"col":0,"comment":"null","endLoc":533,"header":"def getstatement(lineno, source)","id":6572,"name":"getstatement","nodeType":"Function","startLoc":528,"text":"def getstatement(lineno, source):\n from _pytest._code.source import getstatementrange_ast\n\n source = _pytest._code.Source(source, deindent=False)\n ast, start, end = getstatementrange_ast(lineno, source)\n return source[start:end]"},{"col":4,"comment":"null","endLoc":299,"header":"def test_getstatementrange_out_of_bounds_py3(self)","id":6573,"name":"test_getstatementrange_out_of_bounds_py3","nodeType":"Function","startLoc":296,"text":"def test_getstatementrange_out_of_bounds_py3(self):\n source = Source(\"if xxx:\\n from .collections import something\")\n r = source.getstatementrange(1)\n assert r == (1, 2)"},{"attributeType":"(argsAny, kwargsAny) -> _GeneratorContextManager","col":4,"comment":"null","endLoc":290,"id":6574,"name":"success","nodeType":"Attribute","startLoc":290,"text":"success"},{"attributeType":"null","col":4,"comment":"null","endLoc":291,"id":6575,"name":"py2_only","nodeType":"Attribute","startLoc":291,"text":"py2_only"},{"id":6576,"name":"FUNDING.yml","nodeType":"TextFile","path":".github","text":"# info:\n# * https://help.github.com/en/articles/displaying-a-sponsor-button-in-your-repository\n# * https://tidelift.com/subscription/how-to-connect-tidelift-with-github\ntidelift: pypi/pytest\n"},{"col":4,"comment":"null","endLoc":59,"header":"def test_string_expression_class(self, monkeypatch)","id":6577,"name":"test_string_expression_class","nodeType":"Function","startLoc":55,"text":"def test_string_expression_class(self, monkeypatch):\n monkeypatch.setattr(\"_pytest.config.Config\", 42)\n import _pytest\n\n assert _pytest.config.Config == 42"},{"col":4,"comment":"null","endLoc":66,"header":"def test_unicode_string(self, monkeypatch)","id":6578,"name":"test_unicode_string","nodeType":"Function","startLoc":61,"text":"def test_unicode_string(self, monkeypatch):\n monkeypatch.setattr(\"_pytest.config.Config\", 42)\n import _pytest\n\n assert _pytest.config.Config == 42\n monkeypatch.delattr(\"_pytest.config.Config\")"},{"col":4,"comment":"null","endLoc":69,"header":"def test_wrong_target(self, monkeypatch)","id":6579,"name":"test_wrong_target","nodeType":"Function","startLoc":68,"text":"def test_wrong_target(self, monkeypatch):\n pytest.raises(TypeError, lambda: monkeypatch.setattr(None, None))"},{"col":4,"comment":"null","endLoc":242,"header":"def test_traceback_recursion_index(self)","id":6580,"name":"test_traceback_recursion_index","nodeType":"Function","startLoc":233,"text":"def test_traceback_recursion_index(self):\n def f(n):\n if n < 10:\n n += 1\n f(n)\n\n excinfo = pytest.raises(RuntimeError, f, 8)\n traceback = excinfo.traceback\n recindex = traceback.recursionindex()\n assert recindex == 3"},{"col":33,"endLoc":69,"id":6582,"nodeType":"Lambda","startLoc":69,"text":"lambda: monkeypatch.setattr(None, None)"},{"col":4,"comment":"null","endLoc":253,"header":"def test_traceback_only_specific_recursion_errors(self, monkeypatch)","id":6583,"name":"test_traceback_only_specific_recursion_errors","nodeType":"Function","startLoc":244,"text":"def test_traceback_only_specific_recursion_errors(self, monkeypatch):\n def f(n):\n if n == 0:\n raise RuntimeError(\"hello\")\n f(n - 1)\n\n excinfo = pytest.raises(RuntimeError, f, 25)\n monkeypatch.delattr(excinfo.traceback.__class__, \"recursionindex\")\n repr = excinfo.getrepr()\n assert \"RuntimeError: hello\" in str(repr.reprcrash)"},{"col":4,"comment":"null","endLoc":303,"header":"def test_getstatementrange_with_syntaxerror_issue7(self)","id":6584,"name":"test_getstatementrange_with_syntaxerror_issue7","nodeType":"Function","startLoc":301,"text":"def test_getstatementrange_with_syntaxerror_issue7(self):\n source = Source(\":\")\n pytest.raises(SyntaxError, lambda: source.getstatementrange(0))"},{"col":4,"comment":"null","endLoc":72,"header":"def test_unknown_import(self, monkeypatch)","id":6585,"name":"test_unknown_import","nodeType":"Function","startLoc":71,"text":"def test_unknown_import(self, monkeypatch):\n pytest.raises(ImportError, lambda: monkeypatch.setattr(\"unkn123.classx\", None))"},{"col":35,"endLoc":303,"id":6586,"nodeType":"Lambda","startLoc":303,"text":"lambda: source.getstatementrange(0)"},{"col":4,"comment":"null","endLoc":309,"header":"def test_compile_to_ast(self)","id":6587,"name":"test_compile_to_ast","nodeType":"Function","startLoc":305,"text":"def test_compile_to_ast(self):\n source = Source(\"x = 4\")\n mod = source.compile(flag=ast.PyCF_ONLY_AST)\n assert isinstance(mod, ast.Module)\n compile(mod, \"\", \"exec\")"},{"col":35,"endLoc":72,"id":6588,"nodeType":"Lambda","startLoc":72,"text":"lambda: monkeypatch.setattr(\"unkn123.classx\", None)"},{"col":4,"comment":"null","endLoc":77,"header":"def test_unknown_attr(self, monkeypatch)","id":6589,"name":"test_unknown_attr","nodeType":"Function","startLoc":74,"text":"def test_unknown_attr(self, monkeypatch):\n pytest.raises(\n AttributeError, lambda: monkeypatch.setattr(\"os.path.qweqwe\", None)\n )"},{"col":4,"comment":"Run pytest inline or in a subprocess, depending on the command line\n option \"--runpytest\" and return a :py:class:`RunResult`.\n\n ","endLoc":909,"header":"def runpytest(self, *args, **kwargs)","id":6590,"name":"runpytest","nodeType":"Function","startLoc":903,"text":"def runpytest(self, *args, **kwargs):\n \"\"\"Run pytest inline or in a subprocess, depending on the command line\n option \"--runpytest\" and return a :py:class:`RunResult`.\n\n \"\"\"\n args = self._ensure_basetemp(args)\n return self._runpytest_method(*args, **kwargs)"},{"col":4,"comment":"null","endLoc":318,"header":"def test_compile_and_getsource(self)","id":6591,"name":"test_compile_and_getsource","nodeType":"Function","startLoc":311,"text":"def test_compile_and_getsource(self):\n co = self.source.compile()\n exec(co, globals())\n f(7)\n excinfo = pytest.raises(AssertionError, f, 6)\n frame = excinfo.traceback[-1].frame\n stmt = frame.code.fullsource.getstatement(frame.lineno)\n assert str(stmt).strip().startswith(\"assert\")"},{"col":28,"endLoc":76,"id":6592,"nodeType":"Lambda","startLoc":76,"text":"lambda: monkeypatch.setattr(\"os.path.qweqwe\", None)"},{"col":4,"comment":"null","endLoc":82,"header":"def test_unknown_attr_non_raising(self, monkeypatch)","id":6594,"name":"test_unknown_attr_non_raising","nodeType":"Function","startLoc":79,"text":"def test_unknown_attr_non_raising(self, monkeypatch):\n # https://github.com/pytest-dev/pytest/issues/746\n monkeypatch.setattr(\"os.path.qweqwe\", 42, raising=False)\n assert os.path.qweqwe == 42"},{"col":4,"comment":"null","endLoc":88,"header":"def test_delattr(self, monkeypatch)","id":6595,"name":"test_delattr","nodeType":"Function","startLoc":84,"text":"def test_delattr(self, monkeypatch):\n monkeypatch.delattr(\"os.path.abspath\")\n assert not hasattr(os.path, \"abspath\")\n monkeypatch.undo()\n assert os.path.abspath"},{"col":4,"comment":"Return the builtin called *name*.","endLoc":745,"header":"def builtin(self, name)","id":6597,"name":"builtin","nodeType":"Function","startLoc":742,"text":"def builtin(self, name):\n \"\"\"Return the builtin called *name*.\"\"\"\n builtin_name = ast.Name(\"@py_builtins\", ast.Load())\n return ast.Attribute(builtin_name, name, ast.Load())"},{"className":"TestEnvironWarnings","col":0,"comment":"\n os.environ keys and values should be native strings, otherwise it will cause problems with other modules (notably\n subprocess). On Python 2 os.environ accepts anything without complaining, while Python 3 does the right thing\n and raises an error.\n ","endLoc":235,"id":6599,"nodeType":"Class","startLoc":203,"text":"class TestEnvironWarnings(object):\n \"\"\"\n os.environ keys and values should be native strings, otherwise it will cause problems with other modules (notably\n subprocess). On Python 2 os.environ accepts anything without complaining, while Python 3 does the right thing\n and raises an error.\n \"\"\"\n\n VAR_NAME = u\"PYTEST_INTERNAL_MY_VAR\"\n\n @pytest.mark.skipif(not six.PY2, reason=\"Python 2 only test\")\n def test_setenv_unicode_key(self, monkeypatch):\n with pytest.warns(\n pytest.PytestWarning,\n match=\"Environment variable name {!r} should be str\".format(self.VAR_NAME),\n ):\n monkeypatch.setenv(self.VAR_NAME, \"2\")\n\n @pytest.mark.skipif(not six.PY2, reason=\"Python 2 only test\")\n def test_delenv_unicode_key(self, monkeypatch):\n with pytest.warns(\n pytest.PytestWarning,\n match=\"Environment variable name {!r} should be str\".format(self.VAR_NAME),\n ):\n monkeypatch.delenv(self.VAR_NAME, raising=False)\n\n def test_setenv_non_str_warning(self, monkeypatch):\n value = 2\n msg = (\n \"Value of environment variable PYTEST_INTERNAL_MY_VAR type should be str, \"\n \"but got 2 (type: int); converted to str implicitly\"\n )\n with pytest.warns(pytest.PytestWarning, match=re.escape(msg)):\n monkeypatch.setenv(str(self.VAR_NAME), value)"},{"col":4,"comment":"null","endLoc":218,"header":"@pytest.mark.skipif(not six.PY2, reason=\"Python 2 only test\")\n def test_setenv_unicode_key(self, monkeypatch)","id":6600,"name":"test_setenv_unicode_key","nodeType":"Function","startLoc":212,"text":"@pytest.mark.skipif(not six.PY2, reason=\"Python 2 only test\")\n def test_setenv_unicode_key(self, monkeypatch):\n with pytest.warns(\n pytest.PytestWarning,\n match=\"Environment variable name {!r} should be str\".format(self.VAR_NAME),\n ):\n monkeypatch.setenv(self.VAR_NAME, \"2\")"},{"col":4,"comment":"Return a new named %-formatting placeholder for expr.\n\n This creates a %-formatting placeholder for expr in the\n current formatting context, e.g. ``%(py0)s``. The placeholder\n and expr are placed in the current format context so that it\n can be used on the next call to .pop_format_context().\n\n ","endLoc":758,"header":"def explanation_param(self, expr)","id":6601,"name":"explanation_param","nodeType":"Function","startLoc":747,"text":"def explanation_param(self, expr):\n \"\"\"Return a new named %-formatting placeholder for expr.\n\n This creates a %-formatting placeholder for expr in the\n current formatting context, e.g. ``%(py0)s``. The placeholder\n and expr are placed in the current format context so that it\n can be used on the next call to .pop_format_context().\n\n \"\"\"\n specifier = \"py\" + str(next(self.variable_counter))\n self.explanation_specifiers[specifier] = expr\n return \"%(\" + specifier + \")s\""},{"col":0,"comment":"Return the explanation for the diff between text or bytes.\n\n Unless --verbose is used this will skip leading and trailing\n characters which are identical to keep the diff minimal.\n\n If the input are bytes they will be safely converted to text.\n ","endLoc":249,"header":"def _diff_text(left, right, verbose=0)","id":6602,"name":"_diff_text","nodeType":"Function","startLoc":189,"text":"def _diff_text(left, right, verbose=0):\n \"\"\"Return the explanation for the diff between text or bytes.\n\n Unless --verbose is used this will skip leading and trailing\n characters which are identical to keep the diff minimal.\n\n If the input are bytes they will be safely converted to text.\n \"\"\"\n from difflib import ndiff\n\n explanation = []\n\n def escape_for_readable_diff(binary_text):\n \"\"\"\n Ensures that the internal string is always valid unicode, converting any bytes safely to valid unicode.\n This is done using repr() which then needs post-processing to fix the encompassing quotes and un-escape\n newlines and carriage returns (#429).\n \"\"\"\n r = six.text_type(repr(binary_text)[1:-1])\n r = r.replace(r\"\\n\", \"\\n\")\n r = r.replace(r\"\\r\", \"\\r\")\n return r\n\n if isinstance(left, bytes):\n left = escape_for_readable_diff(left)\n if isinstance(right, bytes):\n right = escape_for_readable_diff(right)\n if verbose < 1:\n i = 0 # just in case left or right has zero length\n for i in range(min(len(left), len(right))):\n if left[i] != right[i]:\n break\n if i > 42:\n i -= 10 # Provide some context\n explanation = [\n u\"Skipping %s identical leading characters in diff, use -v to show\" % i\n ]\n left = left[i:]\n right = right[i:]\n if len(left) == len(right):\n for i in range(len(left)):\n if left[-i] != right[-i]:\n break\n if i > 42:\n i -= 10 # Provide some context\n explanation += [\n u\"Skipping {} identical trailing \"\n u\"characters in diff, use -v to show\".format(i)\n ]\n left = left[:-i]\n right = right[:-i]\n keepends = True\n if left.isspace() or right.isspace():\n left = repr(str(left))\n right = repr(str(right))\n explanation += [u\"Strings contain only whitespace, escaping them using repr()\"]\n explanation += [\n line.strip(\"\\n\")\n for line in ndiff(left.splitlines(keepends), right.splitlines(keepends))\n ]\n return explanation"},{"col":4,"comment":"Create a new formatting context.\n\n The format context is used for when an explanation wants to\n have a variable value formatted in the assertion message. In\n this case the value required can be added using\n .explanation_param(). Finally .pop_format_context() is used\n to format a string of %-formatted values as added by\n .explanation_param().\n\n ","endLoc":772,"header":"def push_format_context(self)","id":6603,"name":"push_format_context","nodeType":"Function","startLoc":760,"text":"def push_format_context(self):\n \"\"\"Create a new formatting context.\n\n The format context is used for when an explanation wants to\n have a variable value formatted in the assertion message. In\n this case the value required can be added using\n .explanation_param(). Finally .pop_format_context() is used\n to format a string of %-formatted values as added by\n .explanation_param().\n\n \"\"\"\n self.explanation_specifiers = {}\n self.stack.append(self.explanation_specifiers)"},{"fileName":"doctest.py","filePath":"src/_pytest","id":6604,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\" discover and run doctests in modules and test files.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport inspect\nimport platform\nimport sys\nimport traceback\nimport warnings\nfrom contextlib import contextmanager\n\nimport pytest\nfrom _pytest._code.code import ExceptionInfo\nfrom _pytest._code.code import ReprFileLocation\nfrom _pytest._code.code import TerminalRepr\nfrom _pytest.compat import safe_getattr\nfrom _pytest.fixtures import FixtureRequest\nfrom _pytest.outcomes import Skipped\nfrom _pytest.warning_types import PytestWarning\n\nDOCTEST_REPORT_CHOICE_NONE = \"none\"\nDOCTEST_REPORT_CHOICE_CDIFF = \"cdiff\"\nDOCTEST_REPORT_CHOICE_NDIFF = \"ndiff\"\nDOCTEST_REPORT_CHOICE_UDIFF = \"udiff\"\nDOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE = \"only_first_failure\"\n\nDOCTEST_REPORT_CHOICES = (\n DOCTEST_REPORT_CHOICE_NONE,\n DOCTEST_REPORT_CHOICE_CDIFF,\n DOCTEST_REPORT_CHOICE_NDIFF,\n DOCTEST_REPORT_CHOICE_UDIFF,\n DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE,\n)\n\n# Lazy definition of runner class\nRUNNER_CLASS = None\n\n\ndef pytest_addoption(parser):\n parser.addini(\n \"doctest_optionflags\",\n \"option flags for doctests\",\n type=\"args\",\n default=[\"ELLIPSIS\"],\n )\n parser.addini(\n \"doctest_encoding\", \"encoding used for doctest files\", default=\"utf-8\"\n )\n group = parser.getgroup(\"collect\")\n group.addoption(\n \"--doctest-modules\",\n action=\"store_true\",\n default=False,\n help=\"run doctests in all .py modules\",\n dest=\"doctestmodules\",\n )\n group.addoption(\n \"--doctest-report\",\n type=str.lower,\n default=\"udiff\",\n help=\"choose another output format for diffs on doctest failure\",\n choices=DOCTEST_REPORT_CHOICES,\n dest=\"doctestreport\",\n )\n group.addoption(\n \"--doctest-glob\",\n action=\"append\",\n default=[],\n metavar=\"pat\",\n help=\"doctests file matching pattern, default: test*.txt\",\n dest=\"doctestglob\",\n )\n group.addoption(\n \"--doctest-ignore-import-errors\",\n action=\"store_true\",\n default=False,\n help=\"ignore doctest ImportErrors\",\n dest=\"doctest_ignore_import_errors\",\n )\n group.addoption(\n \"--doctest-continue-on-failure\",\n action=\"store_true\",\n default=False,\n help=\"for a given doctest, continue to run after the first failure\",\n dest=\"doctest_continue_on_failure\",\n )\n\n\ndef pytest_collect_file(path, parent):\n config = parent.config\n if path.ext == \".py\":\n if config.option.doctestmodules and not _is_setup_py(config, path, parent):\n return DoctestModule(path, parent)\n elif _is_doctest(config, path, parent):\n return DoctestTextfile(path, parent)\n\n\ndef _is_setup_py(config, path, parent):\n if path.basename != \"setup.py\":\n return False\n contents = path.read()\n return \"setuptools\" in contents or \"distutils\" in contents\n\n\ndef _is_doctest(config, path, parent):\n if path.ext in (\".txt\", \".rst\") and parent.session.isinitpath(path):\n return True\n globs = config.getoption(\"doctestglob\") or [\"test*.txt\"]\n for glob in globs:\n if path.check(fnmatch=glob):\n return True\n return False\n\n\nclass ReprFailDoctest(TerminalRepr):\n def __init__(self, reprlocation_lines):\n # List of (reprlocation, lines) tuples\n self.reprlocation_lines = reprlocation_lines\n\n def toterminal(self, tw):\n for reprlocation, lines in self.reprlocation_lines:\n for line in lines:\n tw.line(line)\n reprlocation.toterminal(tw)\n\n\nclass MultipleDoctestFailures(Exception):\n def __init__(self, failures):\n super(MultipleDoctestFailures, self).__init__()\n self.failures = failures\n\n\ndef _init_runner_class():\n import doctest\n\n class PytestDoctestRunner(doctest.DebugRunner):\n \"\"\"\n Runner to collect failures. Note that the out variable in this case is\n a list instead of a stdout-like object\n \"\"\"\n\n def __init__(\n self, checker=None, verbose=None, optionflags=0, continue_on_failure=True\n ):\n doctest.DebugRunner.__init__(\n self, checker=checker, verbose=verbose, optionflags=optionflags\n )\n self.continue_on_failure = continue_on_failure\n\n def report_failure(self, out, test, example, got):\n failure = doctest.DocTestFailure(test, example, got)\n if self.continue_on_failure:\n out.append(failure)\n else:\n raise failure\n\n def report_unexpected_exception(self, out, test, example, exc_info):\n if isinstance(exc_info[1], Skipped):\n raise exc_info[1]\n failure = doctest.UnexpectedException(test, example, exc_info)\n if self.continue_on_failure:\n out.append(failure)\n else:\n raise failure\n\n return PytestDoctestRunner\n\n\ndef _get_runner(checker=None, verbose=None, optionflags=0, continue_on_failure=True):\n # We need this in order to do a lazy import on doctest\n global RUNNER_CLASS\n if RUNNER_CLASS is None:\n RUNNER_CLASS = _init_runner_class()\n return RUNNER_CLASS(\n checker=checker,\n verbose=verbose,\n optionflags=optionflags,\n continue_on_failure=continue_on_failure,\n )\n\n\nclass DoctestItem(pytest.Item):\n def __init__(self, name, parent, runner=None, dtest=None):\n super(DoctestItem, self).__init__(name, parent)\n self.runner = runner\n self.dtest = dtest\n self.obj = None\n self.fixture_request = None\n\n def setup(self):\n if self.dtest is not None:\n self.fixture_request = _setup_fixtures(self)\n globs = dict(getfixture=self.fixture_request.getfixturevalue)\n for name, value in self.fixture_request.getfixturevalue(\n \"doctest_namespace\"\n ).items():\n globs[name] = value\n self.dtest.globs.update(globs)\n\n def runtest(self):\n _check_all_skipped(self.dtest)\n self._disable_output_capturing_for_darwin()\n failures = []\n self.runner.run(self.dtest, out=failures)\n if failures:\n raise MultipleDoctestFailures(failures)\n\n def _disable_output_capturing_for_darwin(self):\n \"\"\"\n Disable output capturing. Otherwise, stdout is lost to doctest (#985)\n \"\"\"\n if platform.system() != \"Darwin\":\n return\n capman = self.config.pluginmanager.getplugin(\"capturemanager\")\n if capman:\n capman.suspend_global_capture(in_=True)\n out, err = capman.read_global_capture()\n sys.stdout.write(out)\n sys.stderr.write(err)\n\n def repr_failure(self, excinfo):\n import doctest\n\n failures = None\n if excinfo.errisinstance((doctest.DocTestFailure, doctest.UnexpectedException)):\n failures = [excinfo.value]\n elif excinfo.errisinstance(MultipleDoctestFailures):\n failures = excinfo.value.failures\n\n if failures is not None:\n reprlocation_lines = []\n for failure in failures:\n example = failure.example\n test = failure.test\n filename = test.filename\n if test.lineno is None:\n lineno = None\n else:\n lineno = test.lineno + example.lineno + 1\n message = type(failure).__name__\n reprlocation = ReprFileLocation(filename, lineno, message)\n checker = _get_checker()\n report_choice = _get_report_choice(\n self.config.getoption(\"doctestreport\")\n )\n if lineno is not None:\n lines = failure.test.docstring.splitlines(False)\n # add line numbers to the left of the error message\n lines = [\n \"%03d %s\" % (i + test.lineno + 1, x)\n for (i, x) in enumerate(lines)\n ]\n # trim docstring error lines to 10\n lines = lines[max(example.lineno - 9, 0) : example.lineno + 1]\n else:\n lines = [\n \"EXAMPLE LOCATION UNKNOWN, not showing all tests of that example\"\n ]\n indent = \">>>\"\n for line in example.source.splitlines():\n lines.append(\"??? %s %s\" % (indent, line))\n indent = \"...\"\n if isinstance(failure, doctest.DocTestFailure):\n lines += checker.output_difference(\n example, failure.got, report_choice\n ).split(\"\\n\")\n else:\n inner_excinfo = ExceptionInfo(failure.exc_info)\n lines += [\"UNEXPECTED EXCEPTION: %s\" % repr(inner_excinfo.value)]\n lines += traceback.format_exception(*failure.exc_info)\n reprlocation_lines.append((reprlocation, lines))\n return ReprFailDoctest(reprlocation_lines)\n else:\n return super(DoctestItem, self).repr_failure(excinfo)\n\n def reportinfo(self):\n return self.fspath, self.dtest.lineno, \"[doctest] %s\" % self.name\n\n\ndef _get_flag_lookup():\n import doctest\n\n return dict(\n DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1,\n DONT_ACCEPT_BLANKLINE=doctest.DONT_ACCEPT_BLANKLINE,\n NORMALIZE_WHITESPACE=doctest.NORMALIZE_WHITESPACE,\n ELLIPSIS=doctest.ELLIPSIS,\n IGNORE_EXCEPTION_DETAIL=doctest.IGNORE_EXCEPTION_DETAIL,\n COMPARISON_FLAGS=doctest.COMPARISON_FLAGS,\n ALLOW_UNICODE=_get_allow_unicode_flag(),\n ALLOW_BYTES=_get_allow_bytes_flag(),\n )\n\n\ndef get_optionflags(parent):\n optionflags_str = parent.config.getini(\"doctest_optionflags\")\n flag_lookup_table = _get_flag_lookup()\n flag_acc = 0\n for flag in optionflags_str:\n flag_acc |= flag_lookup_table[flag]\n return flag_acc\n\n\ndef _get_continue_on_failure(config):\n continue_on_failure = config.getvalue(\"doctest_continue_on_failure\")\n if continue_on_failure:\n # We need to turn off this if we use pdb since we should stop at\n # the first failure\n if config.getvalue(\"usepdb\"):\n continue_on_failure = False\n return continue_on_failure\n\n\nclass DoctestTextfile(pytest.Module):\n obj = None\n\n def collect(self):\n import doctest\n\n # inspired by doctest.testfile; ideally we would use it directly,\n # but it doesn't support passing a custom checker\n encoding = self.config.getini(\"doctest_encoding\")\n text = self.fspath.read_text(encoding)\n filename = str(self.fspath)\n name = self.fspath.basename\n globs = {\"__name__\": \"__main__\"}\n\n optionflags = get_optionflags(self)\n\n runner = _get_runner(\n verbose=0,\n optionflags=optionflags,\n checker=_get_checker(),\n continue_on_failure=_get_continue_on_failure(self.config),\n )\n _fix_spoof_python2(runner, encoding)\n\n parser = doctest.DocTestParser()\n test = parser.get_doctest(text, globs, name, filename, 0)\n if test.examples:\n yield DoctestItem(test.name, self, runner, test)\n\n\ndef _check_all_skipped(test):\n \"\"\"raises pytest.skip() if all examples in the given DocTest have the SKIP\n option set.\n \"\"\"\n import doctest\n\n all_skipped = all(x.options.get(doctest.SKIP, False) for x in test.examples)\n if all_skipped:\n pytest.skip(\"all tests skipped by +SKIP option\")\n\n\ndef _is_mocked(obj):\n \"\"\"\n returns if a object is possibly a mock object by checking the existence of a highly improbable attribute\n \"\"\"\n return (\n safe_getattr(obj, \"pytest_mock_example_attribute_that_shouldnt_exist\", None)\n is not None\n )\n\n\n@contextmanager\ndef _patch_unwrap_mock_aware():\n \"\"\"\n contextmanager which replaces ``inspect.unwrap`` with a version\n that's aware of mock objects and doesn't recurse on them\n \"\"\"\n real_unwrap = getattr(inspect, \"unwrap\", None)\n if real_unwrap is None:\n yield\n else:\n\n def _mock_aware_unwrap(obj, stop=None):\n try:\n if stop is None or stop is _is_mocked:\n return real_unwrap(obj, stop=_is_mocked)\n return real_unwrap(obj, stop=lambda obj: _is_mocked(obj) or stop(obj))\n except Exception as e:\n warnings.warn(\n \"Got %r when unwrapping %r. This is usually caused \"\n \"by a violation of Python's object protocol; see e.g. \"\n \"https://github.com/pytest-dev/pytest/issues/5080\" % (e, obj),\n PytestWarning,\n )\n raise\n\n inspect.unwrap = _mock_aware_unwrap\n try:\n yield\n finally:\n inspect.unwrap = real_unwrap\n\n\nclass DoctestModule(pytest.Module):\n def collect(self):\n import doctest\n\n class MockAwareDocTestFinder(doctest.DocTestFinder):\n \"\"\"\n a hackish doctest finder that overrides stdlib internals to fix a stdlib bug\n\n https://github.com/pytest-dev/pytest/issues/3456\n https://bugs.python.org/issue25532\n \"\"\"\n\n def _find(self, tests, obj, name, module, source_lines, globs, seen):\n if _is_mocked(obj):\n return\n with _patch_unwrap_mock_aware():\n\n doctest.DocTestFinder._find(\n self, tests, obj, name, module, source_lines, globs, seen\n )\n\n if self.fspath.basename == \"conftest.py\":\n module = self.config.pluginmanager._importconftest(self.fspath)\n else:\n try:\n module = self.fspath.pyimport()\n except ImportError:\n if self.config.getvalue(\"doctest_ignore_import_errors\"):\n pytest.skip(\"unable to import module %r\" % self.fspath)\n else:\n raise\n # uses internal doctest module parsing mechanism\n finder = MockAwareDocTestFinder()\n optionflags = get_optionflags(self)\n runner = _get_runner(\n verbose=0,\n optionflags=optionflags,\n checker=_get_checker(),\n continue_on_failure=_get_continue_on_failure(self.config),\n )\n\n for test in finder.find(module, module.__name__):\n if test.examples: # skip empty doctests\n yield DoctestItem(test.name, self, runner, test)\n\n\ndef _setup_fixtures(doctest_item):\n \"\"\"\n Used by DoctestTextfile and DoctestItem to setup fixture information.\n \"\"\"\n\n def func():\n pass\n\n doctest_item.funcargs = {}\n fm = doctest_item.session._fixturemanager\n doctest_item._fixtureinfo = fm.getfixtureinfo(\n node=doctest_item, func=func, cls=None, funcargs=False\n )\n fixture_request = FixtureRequest(doctest_item)\n fixture_request._fillfixtures()\n return fixture_request\n\n\ndef _get_checker():\n \"\"\"\n Returns a doctest.OutputChecker subclass that takes in account the\n ALLOW_UNICODE option to ignore u'' prefixes in strings and ALLOW_BYTES\n to strip b'' prefixes.\n Useful when the same doctest should run in Python 2 and Python 3.\n\n An inner class is used to avoid importing \"doctest\" at the module\n level.\n \"\"\"\n if hasattr(_get_checker, \"LiteralsOutputChecker\"):\n return _get_checker.LiteralsOutputChecker()\n\n import doctest\n import re\n\n class LiteralsOutputChecker(doctest.OutputChecker):\n \"\"\"\n Copied from doctest_nose_plugin.py from the nltk project:\n https://github.com/nltk/nltk\n\n Further extended to also support byte literals.\n \"\"\"\n\n _unicode_literal_re = re.compile(r\"(\\W|^)[uU]([rR]?[\\'\\\"])\", re.UNICODE)\n _bytes_literal_re = re.compile(r\"(\\W|^)[bB]([rR]?[\\'\\\"])\", re.UNICODE)\n\n def check_output(self, want, got, optionflags):\n res = doctest.OutputChecker.check_output(self, want, got, optionflags)\n if res:\n return True\n\n allow_unicode = optionflags & _get_allow_unicode_flag()\n allow_bytes = optionflags & _get_allow_bytes_flag()\n if not allow_unicode and not allow_bytes:\n return False\n\n else: # pragma: no cover\n\n def remove_prefixes(regex, txt):\n return re.sub(regex, r\"\\1\\2\", txt)\n\n if allow_unicode:\n want = remove_prefixes(self._unicode_literal_re, want)\n got = remove_prefixes(self._unicode_literal_re, got)\n if allow_bytes:\n want = remove_prefixes(self._bytes_literal_re, want)\n got = remove_prefixes(self._bytes_literal_re, got)\n res = doctest.OutputChecker.check_output(self, want, got, optionflags)\n return res\n\n _get_checker.LiteralsOutputChecker = LiteralsOutputChecker\n return _get_checker.LiteralsOutputChecker()\n\n\ndef _get_allow_unicode_flag():\n \"\"\"\n Registers and returns the ALLOW_UNICODE flag.\n \"\"\"\n import doctest\n\n return doctest.register_optionflag(\"ALLOW_UNICODE\")\n\n\ndef _get_allow_bytes_flag():\n \"\"\"\n Registers and returns the ALLOW_BYTES flag.\n \"\"\"\n import doctest\n\n return doctest.register_optionflag(\"ALLOW_BYTES\")\n\n\ndef _get_report_choice(key):\n \"\"\"\n This function returns the actual `doctest` module flag value, we want to do it as late as possible to avoid\n importing `doctest` and all its dependencies when parsing options, as it adds overhead and breaks tests.\n \"\"\"\n import doctest\n\n return {\n DOCTEST_REPORT_CHOICE_UDIFF: doctest.REPORT_UDIFF,\n DOCTEST_REPORT_CHOICE_CDIFF: doctest.REPORT_CDIFF,\n DOCTEST_REPORT_CHOICE_NDIFF: doctest.REPORT_NDIFF,\n DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE: doctest.REPORT_ONLY_FIRST_FAILURE,\n DOCTEST_REPORT_CHOICE_NONE: 0,\n }[key]\n\n\ndef _fix_spoof_python2(runner, encoding):\n \"\"\"\n Installs a \"SpoofOut\" into the given DebugRunner so it properly deals with unicode output. This\n should patch only doctests for text files because they don't have a way to declare their\n encoding. Doctests in docstrings from Python modules don't have the same problem given that\n Python already decoded the strings.\n\n This fixes the problem related in issue #2434.\n \"\"\"\n from _pytest.compat import _PY2\n\n if not _PY2:\n return\n\n from doctest import _SpoofOut\n\n class UnicodeSpoof(_SpoofOut):\n def getvalue(self):\n result = _SpoofOut.getvalue(self)\n if encoding and isinstance(result, bytes):\n result = result.decode(encoding)\n return result\n\n runner._fakeout = UnicodeSpoof()\n\n\n@pytest.fixture(scope=\"session\")\ndef doctest_namespace():\n \"\"\"\n Fixture that returns a :py:class:`dict` that will be injected into the namespace of doctests.\n \"\"\"\n return dict()\n"},{"col":4,"comment":"null","endLoc":274,"header":"def test_traceback_no_recursion_index(self)","id":6605,"name":"test_traceback_no_recursion_index","nodeType":"Function","startLoc":255,"text":"def test_traceback_no_recursion_index(self):\n def do_stuff():\n raise RuntimeError\n\n def reraise_me():\n import sys\n\n exc, val, tb = sys.exc_info()\n six.reraise(exc, val, tb)\n\n def f(n):\n try:\n do_stuff()\n except: # noqa\n reraise_me()\n\n excinfo = pytest.raises(RuntimeError, f, 8)\n traceback = excinfo.traceback\n recindex = traceback.recursionindex()\n assert recindex is None"},{"col":4,"comment":"Format the %-formatted string with current format context.\n\n The expl_expr should be an ast.Str instance constructed from\n the %-placeholders created by .explanation_param(). This will\n add the required code to format said string to .on_failure and\n return the ast.Name instance of the formatted string.\n\n ","endLoc":791,"header":"def pop_format_context(self, expl_expr)","id":6606,"name":"pop_format_context","nodeType":"Function","startLoc":774,"text":"def pop_format_context(self, expl_expr):\n \"\"\"Format the %-formatted string with current format context.\n\n The expl_expr should be an ast.Str instance constructed from\n the %-placeholders created by .explanation_param(). This will\n add the required code to format said string to .on_failure and\n return the ast.Name instance of the formatted string.\n\n \"\"\"\n current = self.stack.pop()\n if self.stack:\n self.explanation_specifiers = self.stack[-1]\n keys = [ast.Str(key) for key in current.keys()]\n format_dict = ast.Dict(keys, list(current.values()))\n form = ast.BinOp(expl_expr, ast.Mod(), format_dict)\n name = \"@py_format\" + str(next(self.variable_counter))\n self.on_failure.append(ast.Assign([ast.Name(name, ast.Store())], form))\n return ast.Name(name, ast.Load())"},{"className":"ReprFailDoctest","col":0,"comment":"null","endLoc":126,"id":6607,"nodeType":"Class","startLoc":117,"text":"class ReprFailDoctest(TerminalRepr):\n def __init__(self, reprlocation_lines):\n # List of (reprlocation, lines) tuples\n self.reprlocation_lines = reprlocation_lines\n\n def toterminal(self, tw):\n for reprlocation, lines in self.reprlocation_lines:\n for line in lines:\n tw.line(line)\n reprlocation.toterminal(tw)"},{"col":4,"comment":"null","endLoc":126,"header":"def toterminal(self, tw)","id":6608,"name":"toterminal","nodeType":"Function","startLoc":122,"text":"def toterminal(self, tw):\n for reprlocation, lines in self.reprlocation_lines:\n for line in lines:\n tw.line(line)\n reprlocation.toterminal(tw)"},{"col":4,"comment":"null","endLoc":226,"header":"@pytest.mark.skipif(not six.PY2, reason=\"Python 2 only test\")\n def test_delenv_unicode_key(self, monkeypatch)","id":6609,"name":"test_delenv_unicode_key","nodeType":"Function","startLoc":220,"text":"@pytest.mark.skipif(not six.PY2, reason=\"Python 2 only test\")\n def test_delenv_unicode_key(self, monkeypatch):\n with pytest.warns(\n pytest.PytestWarning,\n match=\"Environment variable name {!r} should be str\".format(self.VAR_NAME),\n ):\n monkeypatch.delenv(self.VAR_NAME, raising=False)"},{"fileName":"test_tmpdir.py","filePath":"testing","id":6610,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport errno\nimport os\nimport stat\nimport sys\n\nimport attr\nimport six\n\nimport pytest\nfrom _pytest import pathlib\nfrom _pytest.pathlib import Path\nfrom _pytest.warnings import SHOW_PYTEST_WARNINGS_ARG\n\n\ndef test_tmpdir_fixture(testdir):\n p = testdir.copy_example(\"tmpdir/tmpdir_fixture.py\")\n results = testdir.runpytest(p)\n results.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_ensuretemp(recwarn):\n d1 = pytest.ensuretemp(\"hello\")\n d2 = pytest.ensuretemp(\"hello\")\n assert d1 == d2\n assert d1.check(dir=1)\n\n\n@attr.s\nclass FakeConfig(object):\n basetemp = attr.ib()\n trace = attr.ib(default=None)\n\n @property\n def trace(self):\n return self\n\n def get(self, key):\n return lambda *k: None\n\n @property\n def option(self):\n return self\n\n\nclass TestTempdirHandler(object):\n def test_mktemp(self, tmp_path):\n\n from _pytest.tmpdir import TempdirFactory, TempPathFactory\n\n config = FakeConfig(tmp_path)\n t = TempdirFactory(TempPathFactory.from_config(config))\n tmp = t.mktemp(\"world\")\n assert tmp.relto(t.getbasetemp()) == \"world0\"\n tmp = t.mktemp(\"this\")\n assert tmp.relto(t.getbasetemp()).startswith(\"this\")\n tmp2 = t.mktemp(\"this\")\n assert tmp2.relto(t.getbasetemp()).startswith(\"this\")\n assert tmp2 != tmp\n\n def test_tmppath_relative_basetemp_absolute(self, tmp_path, monkeypatch):\n \"\"\"#4425\"\"\"\n from _pytest.tmpdir import TempPathFactory\n\n monkeypatch.chdir(tmp_path)\n config = FakeConfig(\"hello\")\n t = TempPathFactory.from_config(config)\n assert t.getbasetemp().resolve() == (tmp_path / \"hello\").resolve()\n\n\nclass TestConfigTmpdir(object):\n def test_getbasetemp_custom_removes_old(self, testdir):\n mytemp = testdir.tmpdir.join(\"xyz\")\n p = testdir.makepyfile(\n \"\"\"\n def test_1(tmpdir):\n pass\n \"\"\"\n )\n testdir.runpytest(p, \"--basetemp=%s\" % mytemp)\n mytemp.check()\n mytemp.ensure(\"hello\")\n\n testdir.runpytest(p, \"--basetemp=%s\" % mytemp)\n mytemp.check()\n assert not mytemp.join(\"hello\").check()\n\n\ndef test_basetemp(testdir):\n mytemp = testdir.tmpdir.mkdir(\"mytemp\")\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1():\n pytest.ensuretemp(\"hello\")\n \"\"\"\n )\n result = testdir.runpytest(p, \"--basetemp=%s\" % mytemp, SHOW_PYTEST_WARNINGS_ARG)\n assert result.ret == 0\n assert mytemp.join(\"hello\").check()\n\n\ndef test_tmpdir_always_is_realpath(testdir):\n # the reason why tmpdir should be a realpath is that\n # when you cd to it and do \"os.getcwd()\" you will anyway\n # get the realpath. Using the symlinked path can thus\n # easily result in path-inequality\n # XXX if that proves to be a problem, consider using\n # os.environ[\"PWD\"]\n realtemp = testdir.tmpdir.mkdir(\"myrealtemp\")\n linktemp = testdir.tmpdir.join(\"symlinktemp\")\n attempt_symlink_to(linktemp, str(realtemp))\n p = testdir.makepyfile(\n \"\"\"\n def test_1(tmpdir):\n import os\n assert os.path.realpath(str(tmpdir)) == str(tmpdir)\n \"\"\"\n )\n result = testdir.runpytest(\"-s\", p, \"--basetemp=%s/bt\" % linktemp)\n assert not result.ret\n\n\ndef test_tmp_path_always_is_realpath(testdir, monkeypatch):\n # for reasoning see: test_tmpdir_always_is_realpath test-case\n realtemp = testdir.tmpdir.mkdir(\"myrealtemp\")\n linktemp = testdir.tmpdir.join(\"symlinktemp\")\n attempt_symlink_to(linktemp, str(realtemp))\n monkeypatch.setenv(\"PYTEST_DEBUG_TEMPROOT\", str(linktemp))\n testdir.makepyfile(\n \"\"\"\n def test_1(tmp_path):\n assert tmp_path.resolve() == tmp_path\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n\ndef test_tmpdir_too_long_on_parametrization(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize(\"arg\", [\"1\"*1000])\n def test_some(arg, tmpdir):\n tmpdir.ensure(\"hello\")\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n\ndef test_tmpdir_factory(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope='session')\n def session_dir(tmpdir_factory):\n return tmpdir_factory.mktemp('data', numbered=False)\n def test_some(session_dir):\n assert session_dir.isdir()\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n\ndef test_tmpdir_fallback_tox_env(testdir, monkeypatch):\n \"\"\"Test that tmpdir works even if environment variables required by getpass\n module are missing (#1010).\n \"\"\"\n monkeypatch.delenv(\"USER\", raising=False)\n monkeypatch.delenv(\"USERNAME\", raising=False)\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_some(tmpdir):\n assert tmpdir.isdir()\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n\n@pytest.fixture\ndef break_getuser(monkeypatch):\n monkeypatch.setattr(\"os.getuid\", lambda: -1)\n # taken from python 2.7/3.4\n for envvar in (\"LOGNAME\", \"USER\", \"LNAME\", \"USERNAME\"):\n monkeypatch.delenv(envvar, raising=False)\n\n\n@pytest.mark.usefixtures(\"break_getuser\")\n@pytest.mark.skipif(sys.platform.startswith(\"win\"), reason=\"no os.getuid on windows\")\ndef test_tmpdir_fallback_uid_not_found(testdir):\n \"\"\"Test that tmpdir works even if the current process's user id does not\n correspond to a valid user.\n \"\"\"\n\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_some(tmpdir):\n assert tmpdir.isdir()\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)\n\n\n@pytest.mark.usefixtures(\"break_getuser\")\n@pytest.mark.skipif(sys.platform.startswith(\"win\"), reason=\"no os.getuid on windows\")\ndef test_get_user_uid_not_found():\n \"\"\"Test that get_user() function works even if the current process's\n user id does not correspond to a valid user (e.g. running pytest in a\n Docker container with 'docker run -u'.\n \"\"\"\n from _pytest.tmpdir import get_user\n\n assert get_user() is None\n\n\n@pytest.mark.skipif(not sys.platform.startswith(\"win\"), reason=\"win only\")\ndef test_get_user(monkeypatch):\n \"\"\"Test that get_user() function works even if environment variables\n required by getpass module are missing from the environment on Windows\n (#1010).\n \"\"\"\n from _pytest.tmpdir import get_user\n\n monkeypatch.delenv(\"USER\", raising=False)\n monkeypatch.delenv(\"USERNAME\", raising=False)\n assert get_user() is None\n\n\nclass TestNumberedDir(object):\n PREFIX = \"fun-\"\n\n def test_make(self, tmp_path):\n from _pytest.pathlib import make_numbered_dir\n\n for i in range(10):\n d = make_numbered_dir(root=tmp_path, prefix=self.PREFIX)\n assert d.name.startswith(self.PREFIX)\n assert d.name.endswith(str(i))\n\n symlink = tmp_path.joinpath(self.PREFIX + \"current\")\n if symlink.exists():\n # unix\n assert symlink.is_symlink()\n assert symlink.resolve() == d.resolve()\n\n def test_cleanup_lock_create(self, tmp_path):\n d = tmp_path.joinpath(\"test\")\n d.mkdir()\n from _pytest.pathlib import create_cleanup_lock\n\n lockfile = create_cleanup_lock(d)\n with pytest.raises(EnvironmentError, match=\"cannot create lockfile in .*\"):\n create_cleanup_lock(d)\n\n lockfile.unlink()\n\n def test_lock_register_cleanup_removal(self, tmp_path):\n from _pytest.pathlib import create_cleanup_lock, register_cleanup_lock_removal\n\n lock = create_cleanup_lock(tmp_path)\n\n registry = []\n register_cleanup_lock_removal(lock, register=registry.append)\n\n cleanup_func, = registry\n\n assert lock.is_file()\n\n cleanup_func(original_pid=\"intentionally_different\")\n\n assert lock.is_file()\n\n cleanup_func()\n\n assert not lock.exists()\n\n cleanup_func()\n\n assert not lock.exists()\n\n def _do_cleanup(self, tmp_path):\n self.test_make(tmp_path)\n from _pytest.pathlib import cleanup_numbered_dir\n\n cleanup_numbered_dir(\n root=tmp_path,\n prefix=self.PREFIX,\n keep=2,\n consider_lock_dead_if_created_before=0,\n )\n\n def test_cleanup_keep(self, tmp_path):\n self._do_cleanup(tmp_path)\n a, b = (x for x in tmp_path.iterdir() if not x.is_symlink())\n print(a, b)\n\n def test_cleanup_locked(self, tmp_path):\n\n from _pytest import pathlib\n\n p = pathlib.make_numbered_dir(root=tmp_path, prefix=self.PREFIX)\n\n pathlib.create_cleanup_lock(p)\n\n assert not pathlib.ensure_deletable(\n p, consider_lock_dead_if_created_before=p.stat().st_mtime - 1\n )\n assert pathlib.ensure_deletable(\n p, consider_lock_dead_if_created_before=p.stat().st_mtime + 1\n )\n\n def test_cleanup_ignores_symlink(self, tmp_path):\n the_symlink = tmp_path / (self.PREFIX + \"current\")\n attempt_symlink_to(the_symlink, tmp_path / (self.PREFIX + \"5\"))\n self._do_cleanup(tmp_path)\n\n def test_removal_accepts_lock(self, tmp_path):\n folder = pathlib.make_numbered_dir(root=tmp_path, prefix=self.PREFIX)\n pathlib.create_cleanup_lock(folder)\n pathlib.maybe_delete_a_numbered_dir(folder)\n assert folder.is_dir()\n\n\nclass TestRmRf:\n def test_rm_rf(self, tmp_path):\n from _pytest.pathlib import rm_rf\n\n adir = tmp_path / \"adir\"\n adir.mkdir()\n rm_rf(adir)\n\n assert not adir.exists()\n\n adir.mkdir()\n afile = adir / \"afile\"\n afile.write_bytes(b\"aa\")\n\n rm_rf(adir)\n assert not adir.exists()\n\n def test_rm_rf_with_read_only_file(self, tmp_path):\n \"\"\"Ensure rm_rf can remove directories with read-only files in them (#5524)\"\"\"\n from _pytest.pathlib import rm_rf\n\n fn = tmp_path / \"dir/foo.txt\"\n fn.parent.mkdir()\n\n fn.touch()\n\n self.chmod_r(fn)\n\n rm_rf(fn.parent)\n\n assert not fn.parent.is_dir()\n\n def chmod_r(self, path):\n mode = os.stat(str(path)).st_mode\n os.chmod(str(path), mode & ~stat.S_IWRITE)\n\n def test_rm_rf_with_read_only_directory(self, tmp_path):\n \"\"\"Ensure rm_rf can remove read-only directories (#5524)\"\"\"\n from _pytest.pathlib import rm_rf\n\n adir = tmp_path / \"dir\"\n adir.mkdir()\n\n (adir / \"foo.txt\").touch()\n self.chmod_r(adir)\n\n rm_rf(adir)\n\n assert not adir.is_dir()\n\n def test_on_rm_rf_error(self, tmp_path):\n from _pytest.pathlib import on_rm_rf_error\n\n adir = tmp_path / \"dir\"\n adir.mkdir()\n\n fn = adir / \"foo.txt\"\n fn.touch()\n self.chmod_r(fn)\n\n # unknown exception\n with pytest.warns(pytest.PytestWarning):\n exc_info = (None, RuntimeError(), None)\n on_rm_rf_error(os.unlink, str(fn), exc_info, start_path=tmp_path)\n assert fn.is_file()\n\n permission_error = OSError()\n permission_error.errno = errno.EACCES\n\n # unknown function\n with pytest.warns(pytest.PytestWarning):\n exc_info = (None, permission_error, None)\n on_rm_rf_error(None, str(fn), exc_info, start_path=tmp_path)\n assert fn.is_file()\n\n exc_info = (None, permission_error, None)\n on_rm_rf_error(os.unlink, str(fn), exc_info, start_path=tmp_path)\n assert not fn.is_file()\n\n\ndef attempt_symlink_to(path, to_path):\n \"\"\"Try to make a symlink from \"path\" to \"to_path\", skipping in case this platform\n does not support it or we don't have sufficient privileges (common on Windows).\"\"\"\n if sys.platform.startswith(\"win\") and six.PY2:\n pytest.skip(\"pathlib for some reason cannot make symlinks on Python 2\")\n try:\n Path(path).symlink_to(Path(to_path))\n except OSError:\n pytest.skip(\"could not create symbolic link\")\n\n\ndef test_tmpdir_equals_tmp_path(tmpdir, tmp_path):\n assert Path(tmpdir) == tmp_path\n\n\ndef test_basetemp_with_read_only_files(testdir):\n \"\"\"Integration test for #5524\"\"\"\n testdir.makepyfile(\n \"\"\"\n import os\n import stat\n\n def test(tmp_path):\n fn = tmp_path / 'foo.txt'\n fn.write_text(u'hello')\n mode = os.stat(str(fn)).st_mode\n os.chmod(str(fn), mode & ~stat.S_IREAD)\n \"\"\"\n )\n result = testdir.runpytest(\"--basetemp=tmp\")\n assert result.ret == 0\n # running a second time and ensure we don't crash\n result = testdir.runpytest(\"--basetemp=tmp\")\n assert result.ret == 0\n"},{"col":4,"comment":"null","endLoc":235,"header":"def test_setenv_non_str_warning(self, monkeypatch)","id":6611,"name":"test_setenv_non_str_warning","nodeType":"Function","startLoc":228,"text":"def test_setenv_non_str_warning(self, monkeypatch):\n value = 2\n msg = (\n \"Value of environment variable PYTEST_INTERNAL_MY_VAR type should be str, \"\n \"but got 2 (type: int); converted to str implicitly\"\n )\n with pytest.warns(pytest.PytestWarning, match=re.escape(msg)):\n monkeypatch.setenv(str(self.VAR_NAME), value)"},{"col":4,"comment":"null","endLoc":336,"header":"@pytest.mark.parametrize(\"name\", [\"\", None, \"my\"])\n def test_compilefuncs_and_path_sanity(self, name)","id":6612,"name":"test_compilefuncs_and_path_sanity","nodeType":"Function","startLoc":320,"text":"@pytest.mark.parametrize(\"name\", [\"\", None, \"my\"])\n def test_compilefuncs_and_path_sanity(self, name):\n def check(comp, name):\n co = comp(self.source, name)\n if not name:\n expected = \"codegen %s:%d>\" % (mypath, mylineno + 2 + 2)\n else:\n expected = \"codegen %r %s:%d>\" % (name, mypath, mylineno + 2 + 2)\n fn = co.co_filename\n assert fn.endswith(expected)\n\n mycode = _pytest._code.Code(self.test_compilefuncs_and_path_sanity)\n mylineno = mycode.firstlineno\n mypath = mycode.path\n\n for comp in _pytest._code.compile, _pytest._code.Source.compile:\n check(comp, name)"},{"col":4,"comment":"null","endLoc":339,"header":"def test_offsetless_synerr(self)","id":6614,"name":"test_offsetless_synerr","nodeType":"Function","startLoc":338,"text":"def test_offsetless_synerr(self):\n pytest.raises(SyntaxError, _pytest._code.compile, \"lambda a,a: 0\", mode=\"eval\")"},{"attributeType":"null","col":4,"comment":"null","endLoc":167,"id":6615,"name":"source","nodeType":"Attribute","startLoc":167,"text":"source"},{"className":"TestTry","col":0,"comment":"null","endLoc":654,"id":6616,"nodeType":"Class","startLoc":630,"text":"class TestTry(object):\n source = \"\"\"\\\ntry:\n raise ValueError\nexcept Something:\n raise IndexError(1)\nelse:\n raise KeyError()\n\"\"\"\n\n def test_body(self):\n source = getstatement(1, self.source)\n assert str(source) == \" raise ValueError\"\n\n def test_except_line(self):\n source = getstatement(2, self.source)\n assert str(source) == \"except Something:\"\n\n def test_except_body(self):\n source = getstatement(3, self.source)\n assert str(source) == \" raise IndexError(1)\"\n\n def test_else(self):\n source = getstatement(5, self.source)\n assert str(source) == \" raise KeyError()\""},{"col":4,"comment":"null","endLoc":642,"header":"def test_body(self)","id":6617,"name":"test_body","nodeType":"Function","startLoc":640,"text":"def test_body(self):\n source = getstatement(1, self.source)\n assert str(source) == \" raise ValueError\""},{"attributeType":"null","col":8,"comment":"null","endLoc":120,"id":6618,"name":"reprlocation_lines","nodeType":"Attribute","startLoc":120,"text":"self.reprlocation_lines"},{"className":"MultipleDoctestFailures","col":0,"comment":"null","endLoc":132,"id":6619,"nodeType":"Class","startLoc":129,"text":"class MultipleDoctestFailures(Exception):\n def __init__(self, failures):\n super(MultipleDoctestFailures, self).__init__()\n self.failures = failures"},{"className":"FakeConfig","col":0,"comment":"null","endLoc":47,"id":6620,"nodeType":"Class","startLoc":33,"text":"@attr.s\nclass FakeConfig(object):\n basetemp = attr.ib()\n trace = attr.ib(default=None)\n\n @property\n def trace(self):\n return self\n\n def get(self, key):\n return lambda *k: None\n\n @property\n def option(self):\n return self"},{"attributeType":"null","col":8,"comment":"null","endLoc":132,"id":6621,"name":"failures","nodeType":"Attribute","startLoc":132,"text":"self.failures"},{"col":4,"comment":"null","endLoc":40,"header":"@property\n def trace(self)","id":6622,"name":"trace","nodeType":"Function","startLoc":38,"text":"@property\n def trace(self):\n return self"},{"col":4,"comment":"null","endLoc":43,"header":"def get(self, key)","id":6623,"name":"get","nodeType":"Function","startLoc":42,"text":"def get(self, key):\n return lambda *k: None"},{"col":15,"endLoc":43,"id":6624,"nodeType":"Lambda","startLoc":43,"text":"lambda *k: None"},{"col":4,"comment":"null","endLoc":47,"header":"@property\n def option(self)","id":6625,"name":"option","nodeType":"Function","startLoc":45,"text":"@property\n def option(self):\n return self"},{"attributeType":"null","col":4,"comment":"null","endLoc":35,"id":6626,"name":"basetemp","nodeType":"Attribute","startLoc":35,"text":"basetemp"},{"attributeType":"null","col":4,"comment":"null","endLoc":36,"id":6628,"name":"trace","nodeType":"Attribute","startLoc":36,"text":"trace"},{"className":"TestTempdirHandler","col":0,"comment":"null","endLoc":72,"id":6630,"nodeType":"Class","startLoc":50,"text":"class TestTempdirHandler(object):\n def test_mktemp(self, tmp_path):\n\n from _pytest.tmpdir import TempdirFactory, TempPathFactory\n\n config = FakeConfig(tmp_path)\n t = TempdirFactory(TempPathFactory.from_config(config))\n tmp = t.mktemp(\"world\")\n assert tmp.relto(t.getbasetemp()) == \"world0\"\n tmp = t.mktemp(\"this\")\n assert tmp.relto(t.getbasetemp()).startswith(\"this\")\n tmp2 = t.mktemp(\"this\")\n assert tmp2.relto(t.getbasetemp()).startswith(\"this\")\n assert tmp2 != tmp\n\n def test_tmppath_relative_basetemp_absolute(self, tmp_path, monkeypatch):\n \"\"\"#4425\"\"\"\n from _pytest.tmpdir import TempPathFactory\n\n monkeypatch.chdir(tmp_path)\n config = FakeConfig(\"hello\")\n t = TempPathFactory.from_config(config)\n assert t.getbasetemp().resolve() == (tmp_path / \"hello\").resolve()"},{"col":4,"comment":"null","endLoc":63,"header":"def test_mktemp(self, tmp_path)","id":6631,"name":"test_mktemp","nodeType":"Function","startLoc":51,"text":"def test_mktemp(self, tmp_path):\n\n from _pytest.tmpdir import TempdirFactory, TempPathFactory\n\n config = FakeConfig(tmp_path)\n t = TempdirFactory(TempPathFactory.from_config(config))\n tmp = t.mktemp(\"world\")\n assert tmp.relto(t.getbasetemp()) == \"world0\"\n tmp = t.mktemp(\"this\")\n assert tmp.relto(t.getbasetemp()).startswith(\"this\")\n tmp2 = t.mktemp(\"this\")\n assert tmp2.relto(t.getbasetemp()).startswith(\"this\")\n assert tmp2 != tmp"},{"col":0,"comment":"null","endLoc":51,"header":"def pytest_fixture_post_finalizer(fixturedef)","id":6632,"name":"pytest_fixture_post_finalizer","nodeType":"Function","startLoc":45,"text":"def pytest_fixture_post_finalizer(fixturedef):\n if hasattr(fixturedef, \"cached_result\"):\n config = fixturedef._fixturemanager.config\n if config.option.setupshow:\n _show_fixture_action(fixturedef, \"TEARDOWN\")\n if hasattr(fixturedef, \"cached_param\"):\n del fixturedef.cached_param"},{"col":4,"comment":"null","endLoc":292,"header":"def test_traceback_messy_recursion(self)","id":6633,"name":"test_traceback_messy_recursion","nodeType":"Function","startLoc":276,"text":"def test_traceback_messy_recursion(self):\n # XXX: simplified locally testable version\n decorator = pytest.importorskip(\"decorator\").decorator\n\n def log(f, *k, **kw):\n print(\"{} {}\".format(k, kw))\n f(*k, **kw)\n\n log = decorator(log)\n\n def fail():\n raise ValueError(\"\")\n\n fail = log(log(fail))\n\n excinfo = pytest.raises(ValueError, fail)\n assert excinfo.traceback.recursionindex() is None"},{"col":0,"comment":"null","endLoc":89,"header":"@pytest.hookimpl(tryfirst=True)\ndef pytest_cmdline_main(config)","id":6634,"name":"pytest_cmdline_main","nodeType":"Function","startLoc":86,"text":"@pytest.hookimpl(tryfirst=True)\ndef pytest_cmdline_main(config):\n if config.option.setuponly:\n config.option.setupshow = True"},{"id":6635,"name":"release-3.4.1.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.4.1\n=======================================\n\npytest 3.4.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Aaron\n* Alan Velasco\n* Andy Freeland\n* Brian Maissy\n* Bruno Oliveira\n* Florian Bruhin\n* Jason R. Coombs\n* Marcin Bachry\n* Pedro Algarvio\n* Ronny Pfannschmidt\n\n\nHappy testing,\nThe pytest Development Team\n"},{"id":6636,"name":"release-4.6.5.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-4.6.5\n=======================================\n\npytest 4.6.5 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Thomas Grainger\n\n\nHappy testing,\nThe pytest Development Team\n"},{"col":4,"comment":"Create a subdirectory of the base temporary directory and return it.\n If ``numbered``, ensure the directory is unique by adding a number\n prefix greater than any existing one.\n ","endLoc":114,"header":"def mktemp(self, basename, numbered=True)","id":6637,"name":"mktemp","nodeType":"Function","startLoc":109,"text":"def mktemp(self, basename, numbered=True):\n \"\"\"Create a subdirectory of the base temporary directory and return it.\n If ``numbered``, ensure the directory is unique by adding a number\n prefix greater than any existing one.\n \"\"\"\n return py.path.local(self._tmppath_factory.mktemp(basename, numbered).resolve())"},{"fileName":"test_modimport.py","filePath":"testing","id":6638,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nimport subprocess\nimport sys\n\nimport py\n\nimport _pytest\nimport pytest\n\npytestmark = pytest.mark.slow\n\nMODSET = [\n x\n for x in py.path.local(_pytest.__file__).dirpath().visit(\"*.py\")\n if x.purebasename != \"__init__\"\n]\n\n\n@pytest.mark.parametrize(\"modfile\", MODSET, ids=lambda x: x.purebasename)\ndef test_fileimport(modfile):\n # this test ensures all internal packages can import\n # without needing the pytest namespace being set\n # this is critical for the initialization of xdist\n\n p = subprocess.Popen(\n [\n sys.executable,\n \"-c\",\n \"import sys, py; py.path.local(sys.argv[1]).pyimport()\",\n modfile.strpath,\n ],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n (out, err) = p.communicate()\n assert p.returncode == 0, \"importing %s failed (exitcode %d): out=%r, err=%r\" % (\n modfile,\n p.returncode,\n out,\n err,\n )\n"},{"col":4,"comment":"backward compat wrapper for ``_tmppath_factory.getbasetemp``","endLoc":118,"header":"def getbasetemp(self)","id":6639,"name":"getbasetemp","nodeType":"Function","startLoc":116,"text":"def getbasetemp(self):\n \"\"\"backward compat wrapper for ``_tmppath_factory.getbasetemp``\"\"\"\n return py.path.local(self._tmppath_factory.getbasetemp().resolve())"},{"col":4,"comment":"null","endLoc":315,"header":"def test_traceback_getcrashentry(self)","id":6640,"name":"test_traceback_getcrashentry","nodeType":"Function","startLoc":294,"text":"def test_traceback_getcrashentry(self):\n def i():\n __tracebackhide__ = True\n raise ValueError\n\n def h():\n i()\n\n def g():\n __tracebackhide__ = True\n h()\n\n def f():\n g()\n\n excinfo = pytest.raises(ValueError, f)\n tb = excinfo.traceback\n entry = tb.getcrashentry()\n co = _pytest._code.Code(h)\n assert entry.frame.code.path == co.path\n assert entry.lineno == co.firstlineno + 1\n assert entry.frame.code.name == \"h\""},{"col":0,"comment":"null","endLoc":41,"header":"@pytest.mark.parametrize(\"modfile\", MODSET, ids=lambda x: x.purebasename)\ndef test_fileimport(modfile)","id":6644,"name":"test_fileimport","nodeType":"Function","startLoc":19,"text":"@pytest.mark.parametrize(\"modfile\", MODSET, ids=lambda x: x.purebasename)\ndef test_fileimport(modfile):\n # this test ensures all internal packages can import\n # without needing the pytest namespace being set\n # this is critical for the initialization of xdist\n\n p = subprocess.Popen(\n [\n sys.executable,\n \"-c\",\n \"import sys, py; py.path.local(sys.argv[1]).pyimport()\",\n modfile.strpath,\n ],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n (out, err) = p.communicate()\n assert p.returncode == 0, \"importing %s failed (exitcode %d): out=%r, err=%r\" % (\n modfile,\n p.returncode,\n out,\n err,\n )"},{"col":48,"endLoc":19,"id":6645,"nodeType":"Lambda","startLoc":19,"text":"lambda x: x.purebasename"},{"col":4,"comment":"#4425","endLoc":72,"header":"def test_tmppath_relative_basetemp_absolute(self, tmp_path, monkeypatch)","id":6646,"name":"test_tmppath_relative_basetemp_absolute","nodeType":"Function","startLoc":65,"text":"def test_tmppath_relative_basetemp_absolute(self, tmp_path, monkeypatch):\n \"\"\"#4425\"\"\"\n from _pytest.tmpdir import TempPathFactory\n\n monkeypatch.chdir(tmp_path)\n config = FakeConfig(\"hello\")\n t = TempPathFactory.from_config(config)\n assert t.getbasetemp().resolve() == (tmp_path / \"hello\").resolve()"},{"col":4,"comment":"null","endLoc":332,"header":"def test_traceback_getcrashentry_empty(self)","id":6647,"name":"test_traceback_getcrashentry_empty","nodeType":"Function","startLoc":317,"text":"def test_traceback_getcrashentry_empty(self):\n def g():\n __tracebackhide__ = True\n raise ValueError\n\n def f():\n __tracebackhide__ = True\n g()\n\n excinfo = pytest.raises(ValueError, f)\n tb = excinfo.traceback\n entry = tb.getcrashentry()\n co = _pytest._code.Code(g)\n assert entry.frame.code.path == co.path\n assert entry.lineno == co.firstlineno + 2\n assert entry.frame.code.name == \"g\""},{"col":4,"comment":"null","endLoc":646,"header":"def test_except_line(self)","id":6649,"name":"test_except_line","nodeType":"Function","startLoc":644,"text":"def test_except_line(self):\n source = getstatement(2, self.source)\n assert str(source) == \"except Something:\""},{"attributeType":"null","col":12,"comment":"null","endLoc":128,"id":6650,"name":"excinfo","nodeType":"Attribute","startLoc":128,"text":"self.excinfo"},{"className":"TestFormattedExcinfo","col":0,"comment":"null","endLoc":1366,"id":6651,"nodeType":"Class","startLoc":440,"text":"class TestFormattedExcinfo(object):\n @pytest.fixture\n def importasmod(self, request, _sys_snapshot):\n def importasmod(source):\n source = textwrap.dedent(source)\n tmpdir = request.getfixturevalue(\"tmpdir\")\n modpath = tmpdir.join(\"mod.py\")\n tmpdir.ensure(\"__init__.py\")\n modpath.write(source)\n if invalidate_import_caches is not None:\n invalidate_import_caches()\n return modpath.pyimport()\n\n return importasmod\n\n def excinfo_from_exec(self, source):\n source = _pytest._code.Source(source).strip()\n try:\n exec(source.compile())\n except KeyboardInterrupt:\n raise\n except: # noqa\n return _pytest._code.ExceptionInfo.from_current()\n assert 0, \"did not raise\"\n\n def test_repr_source(self):\n pr = FormattedExcinfo()\n source = _pytest._code.Source(\n \"\"\"\\\n def f(x):\n pass\n \"\"\"\n ).strip()\n pr.flow_marker = \"|\"\n lines = pr.get_source(source, 0)\n assert len(lines) == 2\n assert lines[0] == \"| def f(x):\"\n assert lines[1] == \" pass\"\n\n def test_repr_source_excinfo(self):\n \"\"\" check if indentation is right \"\"\"\n pr = FormattedExcinfo()\n excinfo = self.excinfo_from_exec(\n \"\"\"\n def f():\n assert 0\n f()\n \"\"\"\n )\n pr = FormattedExcinfo()\n source = pr._getentrysource(excinfo.traceback[-1])\n lines = pr.get_source(source, 1, excinfo)\n assert lines == [\" def f():\", \"> assert 0\", \"E AssertionError\"]\n\n def test_repr_source_not_existing(self):\n pr = FormattedExcinfo()\n co = compile(\"raise ValueError()\", \"\", \"exec\")\n try:\n exec(co)\n except ValueError:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n repr = pr.repr_excinfo(excinfo)\n assert repr.reprtraceback.reprentries[1].lines[0] == \"> ???\"\n if sys.version_info[0] >= 3:\n assert repr.chain[0][0].reprentries[1].lines[0] == \"> ???\"\n\n def test_repr_many_line_source_not_existing(self):\n pr = FormattedExcinfo()\n co = compile(\n \"\"\"\na = 1\nraise ValueError()\n\"\"\",\n \"\",\n \"exec\",\n )\n try:\n exec(co)\n except ValueError:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n repr = pr.repr_excinfo(excinfo)\n assert repr.reprtraceback.reprentries[1].lines[0] == \"> ???\"\n if sys.version_info[0] >= 3:\n assert repr.chain[0][0].reprentries[1].lines[0] == \"> ???\"\n\n def test_repr_source_failing_fullsource(self):\n pr = FormattedExcinfo()\n\n class FakeCode(object):\n class raw(object):\n co_filename = \"?\"\n\n path = \"?\"\n firstlineno = 5\n\n def fullsource(self):\n return None\n\n fullsource = property(fullsource)\n\n class FakeFrame(object):\n code = FakeCode()\n f_locals = {}\n f_globals = {}\n\n class FakeTracebackEntry(_pytest._code.Traceback.Entry):\n def __init__(self, tb, excinfo=None):\n self.lineno = 5 + 3\n\n @property\n def frame(self):\n return FakeFrame()\n\n class Traceback(_pytest._code.Traceback):\n Entry = FakeTracebackEntry\n\n class FakeExcinfo(_pytest._code.ExceptionInfo):\n typename = \"Foo\"\n value = Exception()\n\n def __init__(self):\n pass\n\n def exconly(self, tryshort):\n return \"EXC\"\n\n def errisinstance(self, cls):\n return False\n\n excinfo = FakeExcinfo()\n\n class FakeRawTB(object):\n tb_next = None\n\n tb = FakeRawTB()\n excinfo.traceback = Traceback(tb)\n\n fail = IOError()\n repr = pr.repr_excinfo(excinfo)\n assert repr.reprtraceback.reprentries[0].lines[0] == \"> ???\"\n if sys.version_info[0] >= 3:\n assert repr.chain[0][0].reprentries[0].lines[0] == \"> ???\"\n\n fail = py.error.ENOENT # noqa\n repr = pr.repr_excinfo(excinfo)\n assert repr.reprtraceback.reprentries[0].lines[0] == \"> ???\"\n if sys.version_info[0] >= 3:\n assert repr.chain[0][0].reprentries[0].lines[0] == \"> ???\"\n\n def test_repr_local(self):\n p = FormattedExcinfo(showlocals=True)\n loc = {\"y\": 5, \"z\": 7, \"x\": 3, \"@x\": 2, \"__builtins__\": {}}\n reprlocals = p.repr_locals(loc)\n assert reprlocals.lines\n assert reprlocals.lines[0] == \"__builtins__ = \"\n assert reprlocals.lines[1] == \"x = 3\"\n assert reprlocals.lines[2] == \"y = 5\"\n assert reprlocals.lines[3] == \"z = 7\"\n\n def test_repr_local_with_error(self):\n class ObjWithErrorInRepr:\n def __repr__(self):\n raise NotImplementedError\n\n p = FormattedExcinfo(showlocals=True, truncate_locals=False)\n loc = {\"x\": ObjWithErrorInRepr(), \"__builtins__\": {}}\n reprlocals = p.repr_locals(loc)\n assert reprlocals.lines\n assert reprlocals.lines[0] == \"__builtins__ = \"\n assert '[NotImplementedError(\"\") raised in repr()]' in reprlocals.lines[1]\n\n def test_repr_local_with_exception_in_class_property(self):\n class ExceptionWithBrokenClass(Exception):\n @property\n def __class__(self):\n raise TypeError(\"boom!\")\n\n class ObjWithErrorInRepr:\n def __repr__(self):\n raise ExceptionWithBrokenClass()\n\n p = FormattedExcinfo(showlocals=True, truncate_locals=False)\n loc = {\"x\": ObjWithErrorInRepr(), \"__builtins__\": {}}\n reprlocals = p.repr_locals(loc)\n assert reprlocals.lines\n assert reprlocals.lines[0] == \"__builtins__ = \"\n assert '[ExceptionWithBrokenClass(\"\") raised in repr()]' in reprlocals.lines[1]\n\n def test_repr_local_truncated(self):\n loc = {\"l\": [i for i in range(10)]}\n p = FormattedExcinfo(showlocals=True)\n truncated_reprlocals = p.repr_locals(loc)\n assert truncated_reprlocals.lines\n assert truncated_reprlocals.lines[0] == \"l = [0, 1, 2, 3, 4, 5, ...]\"\n\n q = FormattedExcinfo(showlocals=True, truncate_locals=False)\n full_reprlocals = q.repr_locals(loc)\n assert full_reprlocals.lines\n assert full_reprlocals.lines[0] == \"l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\"\n\n def test_repr_tracebackentry_lines(self, importasmod):\n mod = importasmod(\n \"\"\"\n def func1():\n raise ValueError(\"hello\\\\nworld\")\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.func1)\n excinfo.traceback = excinfo.traceback.filter()\n p = FormattedExcinfo()\n reprtb = p.repr_traceback_entry(excinfo.traceback[-1])\n\n # test as intermittent entry\n lines = reprtb.lines\n assert lines[0] == \" def func1():\"\n assert lines[1] == '> raise ValueError(\"hello\\\\nworld\")'\n\n # test as last entry\n p = FormattedExcinfo(showlocals=True)\n repr_entry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)\n lines = repr_entry.lines\n assert lines[0] == \" def func1():\"\n assert lines[1] == '> raise ValueError(\"hello\\\\nworld\")'\n assert lines[2] == \"E ValueError: hello\"\n assert lines[3] == \"E world\"\n assert not lines[4:]\n\n loc = repr_entry.reprlocals is not None\n loc = repr_entry.reprfileloc\n assert loc.path == mod.__file__\n assert loc.lineno == 3\n # assert loc.message == \"ValueError: hello\"\n\n def test_repr_tracebackentry_lines2(self, importasmod):\n mod = importasmod(\n \"\"\"\n def func1(m, x, y, z):\n raise ValueError(\"hello\\\\nworld\")\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.func1, \"m\" * 90, 5, 13, \"z\" * 120)\n excinfo.traceback = excinfo.traceback.filter()\n entry = excinfo.traceback[-1]\n p = FormattedExcinfo(funcargs=True)\n reprfuncargs = p.repr_args(entry)\n assert reprfuncargs.args[0] == (\"m\", repr(\"m\" * 90))\n assert reprfuncargs.args[1] == (\"x\", \"5\")\n assert reprfuncargs.args[2] == (\"y\", \"13\")\n assert reprfuncargs.args[3] == (\"z\", repr(\"z\" * 120))\n\n p = FormattedExcinfo(funcargs=True)\n repr_entry = p.repr_traceback_entry(entry)\n assert repr_entry.reprfuncargs.args == reprfuncargs.args\n tw = TWMock()\n repr_entry.toterminal(tw)\n assert tw.lines[0] == \"m = \" + repr(\"m\" * 90)\n assert tw.lines[1] == \"x = 5, y = 13\"\n assert tw.lines[2] == \"z = \" + repr(\"z\" * 120)\n\n def test_repr_tracebackentry_lines_var_kw_args(self, importasmod):\n mod = importasmod(\n \"\"\"\n def func1(x, *y, **z):\n raise ValueError(\"hello\\\\nworld\")\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.func1, \"a\", \"b\", c=\"d\")\n excinfo.traceback = excinfo.traceback.filter()\n entry = excinfo.traceback[-1]\n p = FormattedExcinfo(funcargs=True)\n reprfuncargs = p.repr_args(entry)\n assert reprfuncargs.args[0] == (\"x\", repr(\"a\"))\n assert reprfuncargs.args[1] == (\"y\", repr((\"b\",)))\n assert reprfuncargs.args[2] == (\"z\", repr({\"c\": \"d\"}))\n\n p = FormattedExcinfo(funcargs=True)\n repr_entry = p.repr_traceback_entry(entry)\n assert repr_entry.reprfuncargs.args == reprfuncargs.args\n tw = TWMock()\n repr_entry.toterminal(tw)\n assert tw.lines[0] == \"x = 'a', y = ('b',), z = {'c': 'd'}\"\n\n def test_repr_tracebackentry_short(self, importasmod):\n mod = importasmod(\n \"\"\"\n def func1():\n raise ValueError(\"hello\")\n def entry():\n func1()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n p = FormattedExcinfo(style=\"short\")\n reprtb = p.repr_traceback_entry(excinfo.traceback[-2])\n lines = reprtb.lines\n basename = py.path.local(mod.__file__).basename\n assert lines[0] == \" func1()\"\n assert basename in str(reprtb.reprfileloc.path)\n assert reprtb.reprfileloc.lineno == 5\n\n # test last entry\n p = FormattedExcinfo(style=\"short\")\n reprtb = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)\n lines = reprtb.lines\n assert lines[0] == ' raise ValueError(\"hello\")'\n assert lines[1] == \"E ValueError: hello\"\n assert basename in str(reprtb.reprfileloc.path)\n assert reprtb.reprfileloc.lineno == 3\n\n def test_repr_tracebackentry_no(self, importasmod):\n mod = importasmod(\n \"\"\"\n def func1():\n raise ValueError(\"hello\")\n def entry():\n func1()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n p = FormattedExcinfo(style=\"no\")\n p.repr_traceback_entry(excinfo.traceback[-2])\n\n p = FormattedExcinfo(style=\"no\")\n reprentry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)\n lines = reprentry.lines\n assert lines[0] == \"E ValueError: hello\"\n assert not lines[1:]\n\n def test_repr_traceback_tbfilter(self, importasmod):\n mod = importasmod(\n \"\"\"\n def f(x):\n raise ValueError(x)\n def entry():\n f(0)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n p = FormattedExcinfo(tbfilter=True)\n reprtb = p.repr_traceback(excinfo)\n assert len(reprtb.reprentries) == 2\n p = FormattedExcinfo(tbfilter=False)\n reprtb = p.repr_traceback(excinfo)\n assert len(reprtb.reprentries) == 3\n\n def test_traceback_short_no_source(self, importasmod, monkeypatch):\n mod = importasmod(\n \"\"\"\n def func1():\n raise ValueError(\"hello\")\n def entry():\n func1()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n from _pytest._code.code import Code\n\n monkeypatch.setattr(Code, \"path\", \"bogus\")\n excinfo.traceback[0].frame.code.path = \"bogus\"\n p = FormattedExcinfo(style=\"short\")\n reprtb = p.repr_traceback_entry(excinfo.traceback[-2])\n lines = reprtb.lines\n last_p = FormattedExcinfo(style=\"short\")\n last_reprtb = last_p.repr_traceback_entry(excinfo.traceback[-1], excinfo)\n last_lines = last_reprtb.lines\n monkeypatch.undo()\n assert lines[0] == \" func1()\"\n\n assert last_lines[0] == ' raise ValueError(\"hello\")'\n assert last_lines[1] == \"E ValueError: hello\"\n\n def test_repr_traceback_and_excinfo(self, importasmod):\n mod = importasmod(\n \"\"\"\n def f(x):\n raise ValueError(x)\n def entry():\n f(0)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n\n for style in (\"long\", \"short\"):\n p = FormattedExcinfo(style=style)\n reprtb = p.repr_traceback(excinfo)\n assert len(reprtb.reprentries) == 2\n assert reprtb.style == style\n assert not reprtb.extraline\n repr = p.repr_excinfo(excinfo)\n assert repr.reprtraceback\n assert len(repr.reprtraceback.reprentries) == len(reprtb.reprentries)\n if sys.version_info[0] >= 3:\n assert repr.chain[0][0]\n assert len(repr.chain[0][0].reprentries) == len(reprtb.reprentries)\n assert repr.reprcrash.path.endswith(\"mod.py\")\n assert repr.reprcrash.message == \"ValueError: 0\"\n\n def test_repr_traceback_with_invalid_cwd(self, importasmod, monkeypatch):\n mod = importasmod(\n \"\"\"\n def f(x):\n raise ValueError(x)\n def entry():\n f(0)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n\n p = FormattedExcinfo()\n\n def raiseos():\n raise OSError(2)\n\n monkeypatch.setattr(os, \"getcwd\", raiseos)\n assert p._makepath(__file__) == __file__\n p.repr_traceback(excinfo)\n\n def test_repr_excinfo_addouterr(self, importasmod):\n mod = importasmod(\n \"\"\"\n def entry():\n raise ValueError()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n repr = excinfo.getrepr()\n repr.addsection(\"title\", \"content\")\n twmock = TWMock()\n repr.toterminal(twmock)\n assert twmock.lines[-1] == \"content\"\n assert twmock.lines[-2] == (\"-\", \"title\")\n\n def test_repr_excinfo_reprcrash(self, importasmod):\n mod = importasmod(\n \"\"\"\n def entry():\n raise ValueError()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n repr = excinfo.getrepr()\n assert repr.reprcrash.path.endswith(\"mod.py\")\n assert repr.reprcrash.lineno == 3\n assert repr.reprcrash.message == \"ValueError\"\n assert str(repr.reprcrash).endswith(\"mod.py:3: ValueError\")\n\n def test_repr_traceback_recursion(self, importasmod):\n mod = importasmod(\n \"\"\"\n def rec2(x):\n return rec1(x+1)\n def rec1(x):\n return rec2(x-1)\n def entry():\n rec1(42)\n \"\"\"\n )\n excinfo = pytest.raises(RuntimeError, mod.entry)\n\n for style in (\"short\", \"long\", \"no\"):\n p = FormattedExcinfo(style=\"short\")\n reprtb = p.repr_traceback(excinfo)\n assert reprtb.extraline == \"!!! Recursion detected (same locals & position)\"\n assert str(reprtb)\n\n def test_reprexcinfo_getrepr(self, importasmod):\n mod = importasmod(\n \"\"\"\n def f(x):\n raise ValueError(x)\n def entry():\n f(0)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n\n for style in (\"short\", \"long\", \"no\"):\n for showlocals in (True, False):\n repr = excinfo.getrepr(style=style, showlocals=showlocals)\n if sys.version_info[0] < 3:\n assert isinstance(repr, ReprExceptionInfo)\n assert repr.reprtraceback.style == style\n if sys.version_info[0] >= 3:\n assert isinstance(repr, ExceptionChainRepr)\n for repr in repr.chain:\n assert repr[0].style == style\n\n def test_reprexcinfo_unicode(self):\n from _pytest._code.code import TerminalRepr\n\n class MyRepr(TerminalRepr):\n def toterminal(self, tw):\n tw.line(u\"я\")\n\n x = six.text_type(MyRepr())\n assert x == u\"я\"\n\n def test_toterminal_long(self, importasmod):\n mod = importasmod(\n \"\"\"\n def g(x):\n raise ValueError(x)\n def f():\n g(3)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.f)\n excinfo.traceback = excinfo.traceback.filter()\n repr = excinfo.getrepr()\n tw = TWMock()\n repr.toterminal(tw)\n assert tw.lines[0] == \"\"\n tw.lines.pop(0)\n assert tw.lines[0] == \" def f():\"\n assert tw.lines[1] == \"> g(3)\"\n assert tw.lines[2] == \"\"\n line = tw.get_write_msg(3)\n assert line.endswith(\"mod.py\")\n assert tw.lines[4] == (\":5: \")\n assert tw.lines[5] == (\"_ \", None)\n assert tw.lines[6] == \"\"\n assert tw.lines[7] == \" def g(x):\"\n assert tw.lines[8] == \"> raise ValueError(x)\"\n assert tw.lines[9] == \"E ValueError: 3\"\n assert tw.lines[10] == \"\"\n line = tw.get_write_msg(11)\n assert line.endswith(\"mod.py\")\n assert tw.lines[12] == \":3: ValueError\"\n\n def test_toterminal_long_missing_source(self, importasmod, tmpdir):\n mod = importasmod(\n \"\"\"\n def g(x):\n raise ValueError(x)\n def f():\n g(3)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.f)\n tmpdir.join(\"mod.py\").remove()\n excinfo.traceback = excinfo.traceback.filter()\n repr = excinfo.getrepr()\n tw = TWMock()\n repr.toterminal(tw)\n assert tw.lines[0] == \"\"\n tw.lines.pop(0)\n assert tw.lines[0] == \"> ???\"\n assert tw.lines[1] == \"\"\n line = tw.get_write_msg(2)\n assert line.endswith(\"mod.py\")\n assert tw.lines[3] == \":5: \"\n assert tw.lines[4] == (\"_ \", None)\n assert tw.lines[5] == \"\"\n assert tw.lines[6] == \"> ???\"\n assert tw.lines[7] == \"E ValueError: 3\"\n assert tw.lines[8] == \"\"\n line = tw.get_write_msg(9)\n assert line.endswith(\"mod.py\")\n assert tw.lines[10] == \":3: ValueError\"\n\n def test_toterminal_long_incomplete_source(self, importasmod, tmpdir):\n mod = importasmod(\n \"\"\"\n def g(x):\n raise ValueError(x)\n def f():\n g(3)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.f)\n tmpdir.join(\"mod.py\").write(\"asdf\")\n excinfo.traceback = excinfo.traceback.filter()\n repr = excinfo.getrepr()\n tw = TWMock()\n repr.toterminal(tw)\n assert tw.lines[0] == \"\"\n tw.lines.pop(0)\n assert tw.lines[0] == \"> ???\"\n assert tw.lines[1] == \"\"\n line = tw.get_write_msg(2)\n assert line.endswith(\"mod.py\")\n assert tw.lines[3] == \":5: \"\n assert tw.lines[4] == (\"_ \", None)\n assert tw.lines[5] == \"\"\n assert tw.lines[6] == \"> ???\"\n assert tw.lines[7] == \"E ValueError: 3\"\n assert tw.lines[8] == \"\"\n line = tw.get_write_msg(9)\n assert line.endswith(\"mod.py\")\n assert tw.lines[10] == \":3: ValueError\"\n\n def test_toterminal_long_filenames(self, importasmod):\n mod = importasmod(\n \"\"\"\n def f():\n raise ValueError()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.f)\n tw = TWMock()\n path = py.path.local(mod.__file__)\n old = path.dirpath().chdir()\n try:\n repr = excinfo.getrepr(abspath=False)\n repr.toterminal(tw)\n x = py.path.local().bestrelpath(path)\n if len(x) < len(str(path)):\n msg = tw.get_write_msg(-2)\n assert msg == \"mod.py\"\n assert tw.lines[-1] == \":3: ValueError\"\n\n repr = excinfo.getrepr(abspath=True)\n repr.toterminal(tw)\n msg = tw.get_write_msg(-2)\n assert msg == path\n line = tw.lines[-1]\n assert line == \":3: ValueError\"\n finally:\n old.chdir()\n\n @pytest.mark.parametrize(\n \"reproptions\",\n [\n {\n \"style\": style,\n \"showlocals\": showlocals,\n \"funcargs\": funcargs,\n \"tbfilter\": tbfilter,\n }\n for style in (\"long\", \"short\", \"no\")\n for showlocals in (True, False)\n for tbfilter in (True, False)\n for funcargs in (True, False)\n ],\n )\n def test_format_excinfo(self, importasmod, reproptions):\n mod = importasmod(\n \"\"\"\n def g(x):\n raise ValueError(x)\n def f():\n g(3)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.f)\n tw = py.io.TerminalWriter(stringio=True)\n repr = excinfo.getrepr(**reproptions)\n repr.toterminal(tw)\n assert tw.stringio.getvalue()\n\n def test_traceback_repr_style(self, importasmod):\n mod = importasmod(\n \"\"\"\n def f():\n g()\n def g():\n h()\n def h():\n i()\n def i():\n raise ValueError()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.f)\n excinfo.traceback = excinfo.traceback.filter()\n excinfo.traceback[1].set_repr_style(\"short\")\n excinfo.traceback[2].set_repr_style(\"short\")\n r = excinfo.getrepr(style=\"long\")\n tw = TWMock()\n r.toterminal(tw)\n for line in tw.lines:\n print(line)\n assert tw.lines[0] == \"\"\n assert tw.lines[1] == \" def f():\"\n assert tw.lines[2] == \"> g()\"\n assert tw.lines[3] == \"\"\n msg = tw.get_write_msg(4)\n assert msg.endswith(\"mod.py\")\n assert tw.lines[5] == \":3: \"\n assert tw.lines[6] == (\"_ \", None)\n tw.get_write_msg(7)\n assert tw.lines[8].endswith(\"in g\")\n assert tw.lines[9] == \" h()\"\n tw.get_write_msg(10)\n assert tw.lines[11].endswith(\"in h\")\n assert tw.lines[12] == \" i()\"\n assert tw.lines[13] == (\"_ \", None)\n assert tw.lines[14] == \"\"\n assert tw.lines[15] == \" def i():\"\n assert tw.lines[16] == \"> raise ValueError()\"\n assert tw.lines[17] == \"E ValueError\"\n assert tw.lines[18] == \"\"\n msg = tw.get_write_msg(19)\n msg.endswith(\"mod.py\")\n assert tw.lines[20] == \":9: ValueError\"\n\n @pytest.mark.skipif(\"sys.version_info[0] < 3\")\n def test_exc_chain_repr(self, importasmod):\n mod = importasmod(\n \"\"\"\n class Err(Exception):\n pass\n def f():\n try:\n g()\n except Exception as e:\n raise Err() from e\n finally:\n h()\n def g():\n raise ValueError()\n\n def h():\n raise AttributeError()\n \"\"\"\n )\n excinfo = pytest.raises(AttributeError, mod.f)\n r = excinfo.getrepr(style=\"long\")\n tw = TWMock()\n r.toterminal(tw)\n for line in tw.lines:\n print(line)\n assert tw.lines[0] == \"\"\n assert tw.lines[1] == \" def f():\"\n assert tw.lines[2] == \" try:\"\n assert tw.lines[3] == \"> g()\"\n assert tw.lines[4] == \"\"\n line = tw.get_write_msg(5)\n assert line.endswith(\"mod.py\")\n assert tw.lines[6] == \":6: \"\n assert tw.lines[7] == (\"_ \", None)\n assert tw.lines[8] == \"\"\n assert tw.lines[9] == \" def g():\"\n assert tw.lines[10] == \"> raise ValueError()\"\n assert tw.lines[11] == \"E ValueError\"\n assert tw.lines[12] == \"\"\n line = tw.get_write_msg(13)\n assert line.endswith(\"mod.py\")\n assert tw.lines[14] == \":12: ValueError\"\n assert tw.lines[15] == \"\"\n assert (\n tw.lines[16]\n == \"The above exception was the direct cause of the following exception:\"\n )\n assert tw.lines[17] == \"\"\n assert tw.lines[18] == \" def f():\"\n assert tw.lines[19] == \" try:\"\n assert tw.lines[20] == \" g()\"\n assert tw.lines[21] == \" except Exception as e:\"\n assert tw.lines[22] == \"> raise Err() from e\"\n assert tw.lines[23] == \"E test_exc_chain_repr0.mod.Err\"\n assert tw.lines[24] == \"\"\n line = tw.get_write_msg(25)\n assert line.endswith(\"mod.py\")\n assert tw.lines[26] == \":8: Err\"\n assert tw.lines[27] == \"\"\n assert (\n tw.lines[28]\n == \"During handling of the above exception, another exception occurred:\"\n )\n assert tw.lines[29] == \"\"\n assert tw.lines[30] == \" def f():\"\n assert tw.lines[31] == \" try:\"\n assert tw.lines[32] == \" g()\"\n assert tw.lines[33] == \" except Exception as e:\"\n assert tw.lines[34] == \" raise Err() from e\"\n assert tw.lines[35] == \" finally:\"\n assert tw.lines[36] == \"> h()\"\n assert tw.lines[37] == \"\"\n line = tw.get_write_msg(38)\n assert line.endswith(\"mod.py\")\n assert tw.lines[39] == \":10: \"\n assert tw.lines[40] == (\"_ \", None)\n assert tw.lines[41] == \"\"\n assert tw.lines[42] == \" def h():\"\n assert tw.lines[43] == \"> raise AttributeError()\"\n assert tw.lines[44] == \"E AttributeError\"\n assert tw.lines[45] == \"\"\n line = tw.get_write_msg(46)\n assert line.endswith(\"mod.py\")\n assert tw.lines[47] == \":15: AttributeError\"\n\n @pytest.mark.skipif(\"sys.version_info[0] < 3\")\n @pytest.mark.parametrize(\"mode\", [\"from_none\", \"explicit_suppress\"])\n def test_exc_repr_chain_suppression(self, importasmod, mode):\n \"\"\"Check that exc repr does not show chained exceptions in Python 3.\n - When the exception is raised with \"from None\"\n - Explicitly suppressed with \"chain=False\" to ExceptionInfo.getrepr().\n \"\"\"\n raise_suffix = \" from None\" if mode == \"from_none\" else \"\"\n mod = importasmod(\n \"\"\"\n def f():\n try:\n g()\n except Exception:\n raise AttributeError(){raise_suffix}\n def g():\n raise ValueError()\n \"\"\".format(\n raise_suffix=raise_suffix\n )\n )\n excinfo = pytest.raises(AttributeError, mod.f)\n r = excinfo.getrepr(style=\"long\", chain=mode != \"explicit_suppress\")\n tw = TWMock()\n r.toterminal(tw)\n for line in tw.lines:\n print(line)\n assert tw.lines[0] == \"\"\n assert tw.lines[1] == \" def f():\"\n assert tw.lines[2] == \" try:\"\n assert tw.lines[3] == \" g()\"\n assert tw.lines[4] == \" except Exception:\"\n assert tw.lines[5] == \"> raise AttributeError(){}\".format(\n raise_suffix\n )\n assert tw.lines[6] == \"E AttributeError\"\n assert tw.lines[7] == \"\"\n line = tw.get_write_msg(8)\n assert line.endswith(\"mod.py\")\n assert tw.lines[9] == \":6: AttributeError\"\n assert len(tw.lines) == 10\n\n @pytest.mark.skipif(\"sys.version_info[0] < 3\")\n @pytest.mark.parametrize(\n \"reason, description\",\n [\n (\n \"cause\",\n \"The above exception was the direct cause of the following exception:\",\n ),\n (\n \"context\",\n \"During handling of the above exception, another exception occurred:\",\n ),\n ],\n )\n def test_exc_chain_repr_without_traceback(self, importasmod, reason, description):\n \"\"\"\n Handle representation of exception chains where one of the exceptions doesn't have a\n real traceback, such as those raised in a subprocess submitted by the multiprocessing\n module (#1984).\n \"\"\"\n from _pytest.pytester import LineMatcher\n\n exc_handling_code = \" from e\" if reason == \"cause\" else \"\"\n mod = importasmod(\n \"\"\"\n def f():\n try:\n g()\n except Exception as e:\n raise RuntimeError('runtime problem'){exc_handling_code}\n def g():\n raise ValueError('invalid value')\n \"\"\".format(\n exc_handling_code=exc_handling_code\n )\n )\n\n with pytest.raises(RuntimeError) as excinfo:\n mod.f()\n\n # emulate the issue described in #1984\n attr = \"__%s__\" % reason\n getattr(excinfo.value, attr).__traceback__ = None\n\n r = excinfo.getrepr()\n tw = py.io.TerminalWriter(stringio=True)\n tw.hasmarkup = False\n r.toterminal(tw)\n\n matcher = LineMatcher(tw.stringio.getvalue().splitlines())\n matcher.fnmatch_lines(\n [\n \"ValueError: invalid value\",\n description,\n \"* except Exception as e:\",\n \"> * raise RuntimeError('runtime problem')\" + exc_handling_code,\n \"E *RuntimeError: runtime problem\",\n ]\n )\n\n @pytest.mark.skipif(\"sys.version_info[0] < 3\")\n def test_exc_chain_repr_cycle(self, importasmod):\n mod = importasmod(\n \"\"\"\n class Err(Exception):\n pass\n def fail():\n return 0 / 0\n def reraise():\n try:\n fail()\n except ZeroDivisionError as e:\n raise Err() from e\n def unreraise():\n try:\n reraise()\n except Err as e:\n raise e.__cause__\n \"\"\"\n )\n excinfo = pytest.raises(ZeroDivisionError, mod.unreraise)\n r = excinfo.getrepr(style=\"short\")\n tw = TWMock()\n r.toterminal(tw)\n out = \"\\n\".join(line for line in tw.lines if isinstance(line, str))\n expected_out = textwrap.dedent(\n \"\"\"\\\n :13: in unreraise\n reraise()\n :10: in reraise\n raise Err() from e\n E test_exc_chain_repr_cycle0.mod.Err\n\n During handling of the above exception, another exception occurred:\n :15: in unreraise\n raise e.__cause__\n :8: in reraise\n fail()\n :5: in fail\n return 0 / 0\n E ZeroDivisionError: division by zero\"\"\"\n )\n assert out == expected_out"},{"col":4,"comment":"null","endLoc":453,"header":"@pytest.fixture\n def importasmod(self, request, _sys_snapshot)","id":6652,"name":"importasmod","nodeType":"Function","startLoc":441,"text":"@pytest.fixture\n def importasmod(self, request, _sys_snapshot):\n def importasmod(source):\n source = textwrap.dedent(source)\n tmpdir = request.getfixturevalue(\"tmpdir\")\n modpath = tmpdir.join(\"mod.py\")\n tmpdir.ensure(\"__init__.py\")\n modpath.write(source)\n if invalidate_import_caches is not None:\n invalidate_import_caches()\n return modpath.pyimport()\n\n return importasmod"},{"className":"TestConfigTmpdir","col":0,"comment":"null","endLoc":90,"id":6653,"nodeType":"Class","startLoc":75,"text":"class TestConfigTmpdir(object):\n def test_getbasetemp_custom_removes_old(self, testdir):\n mytemp = testdir.tmpdir.join(\"xyz\")\n p = testdir.makepyfile(\n \"\"\"\n def test_1(tmpdir):\n pass\n \"\"\"\n )\n testdir.runpytest(p, \"--basetemp=%s\" % mytemp)\n mytemp.check()\n mytemp.ensure(\"hello\")\n\n testdir.runpytest(p, \"--basetemp=%s\" % mytemp)\n mytemp.check()\n assert not mytemp.join(\"hello\").check()"},{"col":4,"comment":"null","endLoc":90,"header":"def test_getbasetemp_custom_removes_old(self, testdir)","id":6654,"name":"test_getbasetemp_custom_removes_old","nodeType":"Function","startLoc":76,"text":"def test_getbasetemp_custom_removes_old(self, testdir):\n mytemp = testdir.tmpdir.join(\"xyz\")\n p = testdir.makepyfile(\n \"\"\"\n def test_1(tmpdir):\n pass\n \"\"\"\n )\n testdir.runpytest(p, \"--basetemp=%s\" % mytemp)\n mytemp.check()\n mytemp.ensure(\"hello\")\n\n testdir.runpytest(p, \"--basetemp=%s\" % mytemp)\n mytemp.check()\n assert not mytemp.join(\"hello\").check()"},{"col":0,"comment":"null","endLoc":88,"header":"def pytest_addoption(parser)","id":6655,"name":"pytest_addoption","nodeType":"Function","startLoc":41,"text":"def pytest_addoption(parser):\n parser.addini(\n \"doctest_optionflags\",\n \"option flags for doctests\",\n type=\"args\",\n default=[\"ELLIPSIS\"],\n )\n parser.addini(\n \"doctest_encoding\", \"encoding used for doctest files\", default=\"utf-8\"\n )\n group = parser.getgroup(\"collect\")\n group.addoption(\n \"--doctest-modules\",\n action=\"store_true\",\n default=False,\n help=\"run doctests in all .py modules\",\n dest=\"doctestmodules\",\n )\n group.addoption(\n \"--doctest-report\",\n type=str.lower,\n default=\"udiff\",\n help=\"choose another output format for diffs on doctest failure\",\n choices=DOCTEST_REPORT_CHOICES,\n dest=\"doctestreport\",\n )\n group.addoption(\n \"--doctest-glob\",\n action=\"append\",\n default=[],\n metavar=\"pat\",\n help=\"doctests file matching pattern, default: test*.txt\",\n dest=\"doctestglob\",\n )\n group.addoption(\n \"--doctest-ignore-import-errors\",\n action=\"store_true\",\n default=False,\n help=\"ignore doctest ImportErrors\",\n dest=\"doctest_ignore_import_errors\",\n )\n group.addoption(\n \"--doctest-continue-on-failure\",\n action=\"store_true\",\n default=False,\n help=\"for a given doctest, continue to run after the first failure\",\n dest=\"doctest_continue_on_failure\",\n )"},{"className":"TestNumberedDir","col":0,"comment":"null","endLoc":332,"id":6656,"nodeType":"Class","startLoc":240,"text":"class TestNumberedDir(object):\n PREFIX = \"fun-\"\n\n def test_make(self, tmp_path):\n from _pytest.pathlib import make_numbered_dir\n\n for i in range(10):\n d = make_numbered_dir(root=tmp_path, prefix=self.PREFIX)\n assert d.name.startswith(self.PREFIX)\n assert d.name.endswith(str(i))\n\n symlink = tmp_path.joinpath(self.PREFIX + \"current\")\n if symlink.exists():\n # unix\n assert symlink.is_symlink()\n assert symlink.resolve() == d.resolve()\n\n def test_cleanup_lock_create(self, tmp_path):\n d = tmp_path.joinpath(\"test\")\n d.mkdir()\n from _pytest.pathlib import create_cleanup_lock\n\n lockfile = create_cleanup_lock(d)\n with pytest.raises(EnvironmentError, match=\"cannot create lockfile in .*\"):\n create_cleanup_lock(d)\n\n lockfile.unlink()\n\n def test_lock_register_cleanup_removal(self, tmp_path):\n from _pytest.pathlib import create_cleanup_lock, register_cleanup_lock_removal\n\n lock = create_cleanup_lock(tmp_path)\n\n registry = []\n register_cleanup_lock_removal(lock, register=registry.append)\n\n cleanup_func, = registry\n\n assert lock.is_file()\n\n cleanup_func(original_pid=\"intentionally_different\")\n\n assert lock.is_file()\n\n cleanup_func()\n\n assert not lock.exists()\n\n cleanup_func()\n\n assert not lock.exists()\n\n def _do_cleanup(self, tmp_path):\n self.test_make(tmp_path)\n from _pytest.pathlib import cleanup_numbered_dir\n\n cleanup_numbered_dir(\n root=tmp_path,\n prefix=self.PREFIX,\n keep=2,\n consider_lock_dead_if_created_before=0,\n )\n\n def test_cleanup_keep(self, tmp_path):\n self._do_cleanup(tmp_path)\n a, b = (x for x in tmp_path.iterdir() if not x.is_symlink())\n print(a, b)\n\n def test_cleanup_locked(self, tmp_path):\n\n from _pytest import pathlib\n\n p = pathlib.make_numbered_dir(root=tmp_path, prefix=self.PREFIX)\n\n pathlib.create_cleanup_lock(p)\n\n assert not pathlib.ensure_deletable(\n p, consider_lock_dead_if_created_before=p.stat().st_mtime - 1\n )\n assert pathlib.ensure_deletable(\n p, consider_lock_dead_if_created_before=p.stat().st_mtime + 1\n )\n\n def test_cleanup_ignores_symlink(self, tmp_path):\n the_symlink = tmp_path / (self.PREFIX + \"current\")\n attempt_symlink_to(the_symlink, tmp_path / (self.PREFIX + \"5\"))\n self._do_cleanup(tmp_path)\n\n def test_removal_accepts_lock(self, tmp_path):\n folder = pathlib.make_numbered_dir(root=tmp_path, prefix=self.PREFIX)\n pathlib.create_cleanup_lock(folder)\n pathlib.maybe_delete_a_numbered_dir(folder)\n assert folder.is_dir()"},{"col":4,"comment":"null","endLoc":255,"header":"def test_make(self, tmp_path)","id":6657,"name":"test_make","nodeType":"Function","startLoc":243,"text":"def test_make(self, tmp_path):\n from _pytest.pathlib import make_numbered_dir\n\n for i in range(10):\n d = make_numbered_dir(root=tmp_path, prefix=self.PREFIX)\n assert d.name.startswith(self.PREFIX)\n assert d.name.endswith(str(i))\n\n symlink = tmp_path.joinpath(self.PREFIX + \"current\")\n if symlink.exists():\n # unix\n assert symlink.is_symlink()\n assert symlink.resolve() == d.resolve()"},{"col":4,"comment":"null","endLoc":650,"header":"def test_except_body(self)","id":6658,"name":"test_except_body","nodeType":"Function","startLoc":648,"text":"def test_except_body(self):\n source = getstatement(3, self.source)\n assert str(source) == \" raise IndexError(1)\""},{"col":0,"comment":"null","endLoc":97,"header":"def pytest_collect_file(path, parent)","id":6659,"name":"pytest_collect_file","nodeType":"Function","startLoc":91,"text":"def pytest_collect_file(path, parent):\n config = parent.config\n if path.ext == \".py\":\n if config.option.doctestmodules and not _is_setup_py(config, path, parent):\n return DoctestModule(path, parent)\n elif _is_doctest(config, path, parent):\n return DoctestTextfile(path, parent)"},{"col":0,"comment":"null","endLoc":104,"header":"def _is_setup_py(config, path, parent)","id":6660,"name":"_is_setup_py","nodeType":"Function","startLoc":100,"text":"def _is_setup_py(config, path, parent):\n if path.basename != \"setup.py\":\n return False\n contents = path.read()\n return \"setuptools\" in contents or \"distutils\" in contents"},{"col":4,"comment":"null","endLoc":463,"header":"def excinfo_from_exec(self, source)","id":6662,"name":"excinfo_from_exec","nodeType":"Function","startLoc":455,"text":"def excinfo_from_exec(self, source):\n source = _pytest._code.Source(source).strip()\n try:\n exec(source.compile())\n except KeyboardInterrupt:\n raise\n except: # noqa\n return _pytest._code.ExceptionInfo.from_current()\n assert 0, \"did not raise\""},{"attributeType":"str","col":4,"comment":"null","endLoc":210,"id":6663,"name":"VAR_NAME","nodeType":"Attribute","startLoc":210,"text":"VAR_NAME"},{"className":"SampleNew","col":0,"comment":"null","endLoc":362,"id":6664,"nodeType":"Class","startLoc":359,"text":"class SampleNew(object):\n @staticmethod\n def hello():\n return True"},{"col":4,"comment":"null","endLoc":362,"header":"@staticmethod\n def hello()","id":6665,"name":"hello","nodeType":"Function","startLoc":360,"text":"@staticmethod\n def hello():\n return True"},{"className":"SampleNewInherit","col":0,"comment":"null","endLoc":366,"id":6666,"nodeType":"Class","startLoc":365,"text":"class SampleNewInherit(SampleNew):\n pass"},{"className":"SampleOld","col":0,"comment":"null","endLoc":373,"id":6667,"nodeType":"Class","startLoc":369,"text":"class SampleOld(object):\n # oldstyle on python2\n @staticmethod\n def hello():\n return True"},{"col":4,"comment":"null","endLoc":373,"header":"@staticmethod\n def hello()","id":6668,"name":"hello","nodeType":"Function","startLoc":371,"text":"@staticmethod\n def hello():\n return True"},{"className":"SampleOldInherit","col":0,"comment":"null","endLoc":377,"id":6669,"nodeType":"Class","startLoc":376,"text":"class SampleOldInherit(SampleOld):\n pass"},{"col":0,"comment":"null","endLoc":23,"header":"@pytest.fixture\ndef mp()","id":6670,"name":"mp","nodeType":"Function","startLoc":17,"text":"@pytest.fixture\ndef mp():\n cwd = os.getcwd()\n sys_path = list(sys.path)\n yield MonkeyPatch()\n sys.path[:] = sys_path\n os.chdir(cwd)"},{"col":4,"comment":"null","endLoc":477,"header":"def test_repr_source(self)","id":6671,"name":"test_repr_source","nodeType":"Function","startLoc":465,"text":"def test_repr_source(self):\n pr = FormattedExcinfo()\n source = _pytest._code.Source(\n \"\"\"\\\n def f(x):\n pass\n \"\"\"\n ).strip()\n pr.flow_marker = \"|\"\n lines = pr.get_source(source, 0)\n assert len(lines) == 2\n assert lines[0] == \"| def f(x):\"\n assert lines[1] == \" pass\""},{"col":4,"comment":"null","endLoc":654,"header":"def test_else(self)","id":6672,"name":"test_else","nodeType":"Function","startLoc":652,"text":"def test_else(self):\n source = getstatement(5, self.source)\n assert str(source) == \" raise KeyError()\""},{"col":0,"comment":"null","endLoc":114,"header":"def _is_doctest(config, path, parent)","id":6673,"name":"_is_doctest","nodeType":"Function","startLoc":107,"text":"def _is_doctest(config, path, parent):\n if path.ext in (\".txt\", \".rst\") and parent.session.isinitpath(path):\n return True\n globs = config.getoption(\"doctestglob\") or [\"test*.txt\"]\n for glob in globs:\n if path.check(fnmatch=glob):\n return True\n return False"},{"attributeType":"str","col":4,"comment":"null","endLoc":631,"id":6674,"name":"source","nodeType":"Attribute","startLoc":631,"text":"source"},{"col":0,"comment":"\n Fixture that returns a :py:class:`dict` that will be injected into the namespace of doctests.\n ","endLoc":583,"header":"@pytest.fixture(scope=\"session\")\ndef doctest_namespace()","id":6675,"name":"doctest_namespace","nodeType":"Function","startLoc":578,"text":"@pytest.fixture(scope=\"session\")\ndef doctest_namespace():\n \"\"\"\n Fixture that returns a :py:class:`dict` that will be injected into the namespace of doctests.\n \"\"\"\n return dict()"},{"className":"TestTryFinally","col":0,"comment":"null","endLoc":671,"id":6676,"nodeType":"Class","startLoc":657,"text":"class TestTryFinally(object):\n source = \"\"\"\\\ntry:\n raise ValueError\nfinally:\n raise IndexError(1)\n\"\"\"\n\n def test_body(self):\n source = getstatement(1, self.source)\n assert str(source) == \" raise ValueError\"\n\n def test_finally(self):\n source = getstatement(3, self.source)\n assert str(source) == \" raise IndexError(1)\""},{"col":4,"comment":"null","endLoc":667,"header":"def test_body(self)","id":6677,"name":"test_body","nodeType":"Function","startLoc":665,"text":"def test_body(self):\n source = getstatement(1, self.source)\n assert str(source) == \" raise ValueError\""},{"col":0,"comment":"null","endLoc":47,"header":"def test_setattr()","id":6678,"name":"test_setattr","nodeType":"Function","startLoc":26,"text":"def test_setattr():\n class A(object):\n x = 1\n\n monkeypatch = MonkeyPatch()\n pytest.raises(AttributeError, monkeypatch.setattr, A, \"notexists\", 2)\n monkeypatch.setattr(A, \"y\", 2, raising=False)\n assert A.y == 2\n monkeypatch.undo()\n assert not hasattr(A, \"y\")\n\n monkeypatch = MonkeyPatch()\n monkeypatch.setattr(A, \"x\", 2)\n assert A.x == 2\n monkeypatch.setattr(A, \"x\", 3)\n assert A.x == 3\n monkeypatch.undo()\n assert A.x == 1\n\n A.x = 5\n monkeypatch.undo() # double-undo makes no modification\n assert A.x == 5"},{"col":4,"comment":" check if indentation is right ","endLoc":492,"header":"def test_repr_source_excinfo(self)","id":6679,"name":"test_repr_source_excinfo","nodeType":"Function","startLoc":479,"text":"def test_repr_source_excinfo(self):\n \"\"\" check if indentation is right \"\"\"\n pr = FormattedExcinfo()\n excinfo = self.excinfo_from_exec(\n \"\"\"\n def f():\n assert 0\n f()\n \"\"\"\n )\n pr = FormattedExcinfo()\n source = pr._getentrysource(excinfo.traceback[-1])\n lines = pr.get_source(source, 1, excinfo)\n assert lines == [\" def f():\", \"> assert 0\", \"E AssertionError\"]"},{"col":4,"comment":"null","endLoc":671,"header":"def test_finally(self)","id":6680,"name":"test_finally","nodeType":"Function","startLoc":669,"text":"def test_finally(self):\n source = getstatement(3, self.source)\n assert str(source) == \" raise IndexError(1)\""},{"attributeType":"str","col":4,"comment":"null","endLoc":658,"id":6681,"name":"source","nodeType":"Attribute","startLoc":658,"text":"source"},{"col":0,"comment":"null","endLoc":108,"header":"def test_delattr()","id":6682,"name":"test_delattr","nodeType":"Function","startLoc":91,"text":"def test_delattr():\n class A(object):\n x = 1\n\n monkeypatch = MonkeyPatch()\n monkeypatch.delattr(A, \"x\")\n assert not hasattr(A, \"x\")\n monkeypatch.undo()\n assert A.x == 1\n\n monkeypatch = MonkeyPatch()\n monkeypatch.delattr(A, \"x\")\n pytest.raises(AttributeError, monkeypatch.delattr, A, \"y\")\n monkeypatch.delattr(A, \"y\", raising=False)\n monkeypatch.setattr(A, \"x\", 5, raising=False)\n assert A.x == 5\n monkeypatch.undo()\n assert A.x == 1"},{"className":"TestIf","col":0,"comment":"null","endLoc":698,"id":6683,"nodeType":"Class","startLoc":674,"text":"class TestIf(object):\n source = \"\"\"\\\nif 1:\n y = 3\nelif False:\n y = 5\nelse:\n y = 7\n\"\"\"\n\n def test_body(self):\n source = getstatement(1, self.source)\n assert str(source) == \" y = 3\"\n\n def test_elif_clause(self):\n source = getstatement(2, self.source)\n assert str(source) == \"elif False:\"\n\n def test_elif(self):\n source = getstatement(3, self.source)\n assert str(source) == \" y = 5\"\n\n def test_else(self):\n source = getstatement(5, self.source)\n assert str(source) == \" y = 7\""},{"col":4,"comment":"null","endLoc":686,"header":"def test_body(self)","id":6684,"name":"test_body","nodeType":"Function","startLoc":684,"text":"def test_body(self):\n source = getstatement(1, self.source)\n assert str(source) == \" y = 3\""},{"col":4,"comment":"Run pytest as a subprocess with given arguments.\n\n Any plugins added to the :py:attr:`plugins` list will be added using the\n ``-p`` command line option. Additionally ``--basetemp`` is used to put\n any temporary files and directories in a numbered directory prefixed\n with \"runpytest-\" to not conflict with the normal numbered pytest\n location for temporary files and directories.\n\n :param args: the sequence of arguments to pass to the pytest subprocess\n :param timeout: the period in seconds after which to timeout and raise\n :py:class:`Testdir.TimeoutExpired`\n\n Returns a :py:class:`RunResult`.\n ","endLoc":1210,"header":"def runpytest_subprocess(self, *args, **kwargs)","id":6685,"name":"runpytest_subprocess","nodeType":"Function","startLoc":1183,"text":"def runpytest_subprocess(self, *args, **kwargs):\n \"\"\"Run pytest as a subprocess with given arguments.\n\n Any plugins added to the :py:attr:`plugins` list will be added using the\n ``-p`` command line option. Additionally ``--basetemp`` is used to put\n any temporary files and directories in a numbered directory prefixed\n with \"runpytest-\" to not conflict with the normal numbered pytest\n location for temporary files and directories.\n\n :param args: the sequence of arguments to pass to the pytest subprocess\n :param timeout: the period in seconds after which to timeout and raise\n :py:class:`Testdir.TimeoutExpired`\n\n Returns a :py:class:`RunResult`.\n \"\"\"\n __tracebackhide__ = True\n timeout = kwargs.pop(\"timeout\", None)\n raise_on_kwargs(kwargs)\n\n p = py.path.local.make_numbered_dir(\n prefix=\"runpytest-\", keep=None, rootdir=self.tmpdir\n )\n args = (\"--basetemp=%s\" % p,) + args\n plugins = [x for x in self.plugins if isinstance(x, str)]\n if plugins:\n args = (\"-p\", plugins[0]) + args\n args = self._getpytestargs() + args\n return self.run(*args, timeout=timeout)"},{"col":4,"comment":"null","endLoc":1169,"header":"def _getpytestargs(self)","id":6687,"name":"_getpytestargs","nodeType":"Function","startLoc":1168,"text":"def _getpytestargs(self):\n return sys.executable, \"-mpytest\""},{"col":4,"comment":"Run a command with arguments.\n\n Run a process using subprocess.Popen saving the stdout and stderr.\n\n :param args: the sequence of arguments to pass to `subprocess.Popen()`\n :param timeout: the period in seconds after which to timeout and raise\n :py:class:`Testdir.TimeoutExpired`\n :param stdin: optional standard input. Bytes are being send, closing\n the pipe, otherwise it is passed through to ``popen``.\n Defaults to ``CLOSE_STDIN``, which translates to using a pipe\n (``subprocess.PIPE``) that gets closed.\n\n Returns a :py:class:`RunResult`.\n\n ","endLoc":1159,"header":"def run(self, *cmdargs, **kwargs)","id":6688,"name":"run","nodeType":"Function","startLoc":1070,"text":"def run(self, *cmdargs, **kwargs):\n \"\"\"Run a command with arguments.\n\n Run a process using subprocess.Popen saving the stdout and stderr.\n\n :param args: the sequence of arguments to pass to `subprocess.Popen()`\n :param timeout: the period in seconds after which to timeout and raise\n :py:class:`Testdir.TimeoutExpired`\n :param stdin: optional standard input. Bytes are being send, closing\n the pipe, otherwise it is passed through to ``popen``.\n Defaults to ``CLOSE_STDIN``, which translates to using a pipe\n (``subprocess.PIPE``) that gets closed.\n\n Returns a :py:class:`RunResult`.\n\n \"\"\"\n __tracebackhide__ = True\n\n timeout = kwargs.pop(\"timeout\", None)\n stdin = kwargs.pop(\"stdin\", Testdir.CLOSE_STDIN)\n raise_on_kwargs(kwargs)\n\n cmdargs = [\n str(arg) if isinstance(arg, py.path.local) else arg for arg in cmdargs\n ]\n p1 = self.tmpdir.join(\"stdout\")\n p2 = self.tmpdir.join(\"stderr\")\n print(\"running:\", *cmdargs)\n print(\" in:\", py.path.local())\n f1 = codecs.open(str(p1), \"w\", encoding=\"utf8\")\n f2 = codecs.open(str(p2), \"w\", encoding=\"utf8\")\n try:\n now = time.time()\n popen = self.popen(\n cmdargs,\n stdin=stdin,\n stdout=f1,\n stderr=f2,\n close_fds=(sys.platform != \"win32\"),\n )\n if isinstance(stdin, bytes):\n popen.stdin.close()\n\n def handle_timeout():\n __tracebackhide__ = True\n\n timeout_message = (\n \"{seconds} second timeout expired running:\"\n \" {command}\".format(seconds=timeout, command=cmdargs)\n )\n\n popen.kill()\n popen.wait()\n raise self.TimeoutExpired(timeout_message)\n\n if timeout is None:\n ret = popen.wait()\n elif not six.PY2:\n try:\n ret = popen.wait(timeout)\n except subprocess.TimeoutExpired:\n handle_timeout()\n else:\n end = time.time() + timeout\n\n resolution = min(0.1, timeout / 10)\n\n while True:\n ret = popen.poll()\n if ret is not None:\n break\n\n if time.time() > end:\n handle_timeout()\n\n time.sleep(resolution)\n finally:\n f1.close()\n f2.close()\n f1 = codecs.open(str(p1), \"r\", encoding=\"utf8\")\n f2 = codecs.open(str(p2), \"r\", encoding=\"utf8\")\n try:\n out = f1.read().splitlines()\n err = f2.read().splitlines()\n finally:\n f1.close()\n f2.close()\n self._dump_lines(out, sys.stdout)\n self._dump_lines(err, sys.stderr)\n return RunResult(ret, out, err, time.time() - now)"},{"col":4,"comment":"null","endLoc":690,"header":"def test_elif_clause(self)","id":6689,"name":"test_elif_clause","nodeType":"Function","startLoc":688,"text":"def test_elif_clause(self):\n source = getstatement(2, self.source)\n assert str(source) == \"elif False:\""},{"col":4,"comment":" return base temporary directory. ","endLoc":84,"header":"def getbasetemp(self)","id":6690,"name":"getbasetemp","nodeType":"Function","startLoc":61,"text":"def getbasetemp(self):\n \"\"\" return base temporary directory. \"\"\"\n if self._basetemp is not None:\n return self._basetemp\n\n if self._given_basetemp is not None:\n basetemp = self._given_basetemp\n ensure_reset_dir(basetemp)\n basetemp = basetemp.resolve()\n else:\n from_env = os.environ.get(\"PYTEST_DEBUG_TEMPROOT\")\n temproot = Path(from_env or tempfile.gettempdir()).resolve()\n user = get_user() or \"unknown\"\n # use a sub-directory in the temproot to speed-up\n # make_numbered_dir() call\n rootdir = temproot.joinpath(\"pytest-of-{}\".format(user))\n rootdir.mkdir(exist_ok=True)\n basetemp = make_numbered_dir_with_cleanup(\n prefix=\"pytest-\", root=rootdir, keep=3, lock_timeout=LOCK_TIMEOUT\n )\n assert basetemp is not None, basetemp\n self._basetemp = t = basetemp\n self._trace(\"new basetemp\", t)\n return t"},{"col":0,"comment":"Return the current user name, or None if getuser() does not work\n in the current environment (see #1010).\n ","endLoc":130,"header":"def get_user()","id":6692,"name":"get_user","nodeType":"Function","startLoc":121,"text":"def get_user():\n \"\"\"Return the current user name, or None if getuser() does not work\n in the current environment (see #1010).\n \"\"\"\n import getpass\n\n try:\n return getpass.getuser()\n except (ImportError, KeyError):\n return None"},{"col":0,"comment":"null","endLoc":126,"header":"def test_setitem()","id":6694,"name":"test_setitem","nodeType":"Function","startLoc":111,"text":"def test_setitem():\n d = {\"x\": 1}\n monkeypatch = MonkeyPatch()\n monkeypatch.setitem(d, \"x\", 2)\n monkeypatch.setitem(d, \"y\", 1700)\n monkeypatch.setitem(d, \"y\", 1700)\n assert d[\"x\"] == 2\n assert d[\"y\"] == 1700\n monkeypatch.setitem(d, \"x\", 3)\n assert d[\"x\"] == 3\n monkeypatch.undo()\n assert d[\"x\"] == 1\n assert \"y\" not in d\n d[\"x\"] = 5\n monkeypatch.undo()\n assert d[\"x\"] == 5"},{"attributeType":"null","col":4,"comment":"null","endLoc":31,"id":6695,"name":"_given_basetemp","nodeType":"Attribute","startLoc":31,"text":"_given_basetemp"},{"attributeType":"null","col":4,"comment":"null","endLoc":39,"id":6696,"name":"_trace","nodeType":"Attribute","startLoc":39,"text":"_trace"},{"attributeType":"null","col":4,"comment":"null","endLoc":40,"id":6697,"name":"_basetemp","nodeType":"Attribute","startLoc":40,"text":"_basetemp"},{"attributeType":"null","col":8,"comment":"null","endLoc":82,"id":6698,"name":"_basetemp","nodeType":"Attribute","startLoc":82,"text":"self._basetemp"},{"className":"TempdirFactory","col":0,"comment":"\n backward comptibility wrapper that implements\n :class:``py.path.local`` for :class:``TempPathFactory``\n ","endLoc":118,"id":6699,"nodeType":"Class","startLoc":87,"text":"@attr.s\nclass TempdirFactory(object):\n \"\"\"\n backward comptibility wrapper that implements\n :class:``py.path.local`` for :class:``TempPathFactory``\n \"\"\"\n\n _tmppath_factory = attr.ib()\n\n def ensuretemp(self, string, dir=1):\n \"\"\" (deprecated) return temporary directory path with\n the given string as the trailing part. It is usually\n better to use the 'tmpdir' function argument which\n provides an empty unique-per-test-invocation directory\n and is guaranteed to be empty.\n \"\"\"\n # py.log._apiwarn(\">1.1\", \"use tmpdir function argument\")\n from .deprecated import PYTEST_ENSURETEMP\n\n warnings.warn(PYTEST_ENSURETEMP, stacklevel=2)\n return self.getbasetemp().ensure(string, dir=dir)\n\n def mktemp(self, basename, numbered=True):\n \"\"\"Create a subdirectory of the base temporary directory and return it.\n If ``numbered``, ensure the directory is unique by adding a number\n prefix greater than any existing one.\n \"\"\"\n return py.path.local(self._tmppath_factory.mktemp(basename, numbered).resolve())\n\n def getbasetemp(self):\n \"\"\"backward compat wrapper for ``_tmppath_factory.getbasetemp``\"\"\"\n return py.path.local(self._tmppath_factory.getbasetemp().resolve())"},{"col":4,"comment":" (deprecated) return temporary directory path with\n the given string as the trailing part. It is usually\n better to use the 'tmpdir' function argument which\n provides an empty unique-per-test-invocation directory\n and is guaranteed to be empty.\n ","endLoc":107,"header":"def ensuretemp(self, string, dir=1)","id":6700,"name":"ensuretemp","nodeType":"Function","startLoc":96,"text":"def ensuretemp(self, string, dir=1):\n \"\"\" (deprecated) return temporary directory path with\n the given string as the trailing part. It is usually\n better to use the 'tmpdir' function argument which\n provides an empty unique-per-test-invocation directory\n and is guaranteed to be empty.\n \"\"\"\n # py.log._apiwarn(\">1.1\", \"use tmpdir function argument\")\n from .deprecated import PYTEST_ENSURETEMP\n\n warnings.warn(PYTEST_ENSURETEMP, stacklevel=2)\n return self.getbasetemp().ensure(string, dir=dir)"},{"col":4,"comment":"null","endLoc":694,"header":"def test_elif(self)","id":6701,"name":"test_elif","nodeType":"Function","startLoc":692,"text":"def test_elif(self):\n source = getstatement(3, self.source)\n assert str(source) == \" y = 5\""},{"col":0,"comment":"null","endLoc":135,"header":"def test_setitem_deleted_meanwhile()","id":6702,"name":"test_setitem_deleted_meanwhile","nodeType":"Function","startLoc":129,"text":"def test_setitem_deleted_meanwhile():\n d = {}\n monkeypatch = MonkeyPatch()\n monkeypatch.setitem(d, \"x\", 2)\n del d[\"x\"]\n monkeypatch.undo()\n assert not d"},{"attributeType":"null","col":4,"comment":"null","endLoc":94,"id":6703,"name":"_tmppath_factory","nodeType":"Attribute","startLoc":94,"text":"_tmppath_factory"},{"col":0,"comment":"Create a TempdirFactory and attach it to the config object.\n\n This is to comply with existing plugins which expect the handler to be\n available at pytest_configure time, but ideally should be moved entirely\n to the tmpdir_factory session fixture.\n ","endLoc":146,"header":"def pytest_configure(config)","id":6704,"name":"pytest_configure","nodeType":"Function","startLoc":133,"text":"def pytest_configure(config):\n \"\"\"Create a TempdirFactory and attach it to the config object.\n\n This is to comply with existing plugins which expect the handler to be\n available at pytest_configure time, but ideally should be moved entirely\n to the tmpdir_factory session fixture.\n \"\"\"\n mp = MonkeyPatch()\n tmppath_handler = TempPathFactory.from_config(config)\n t = TempdirFactory(tmppath_handler)\n config._cleanup.append(mp.undo)\n mp.setattr(config, \"_tmp_path_factory\", tmppath_handler, raising=False)\n mp.setattr(config, \"_tmpdirhandler\", t, raising=False)\n mp.setattr(pytest, \"ensuretemp\", t.ensuretemp, raising=False)"},{"col":4,"comment":"null","endLoc":698,"header":"def test_else(self)","id":6705,"name":"test_else","nodeType":"Function","startLoc":696,"text":"def test_else(self):\n source = getstatement(5, self.source)\n assert str(source) == \" y = 7\""},{"col":0,"comment":"null","endLoc":151,"header":"@pytest.mark.parametrize(\"before\", [True, False])\ndef test_setenv_deleted_meanwhile(before)","id":6706,"name":"test_setenv_deleted_meanwhile","nodeType":"Function","startLoc":138,"text":"@pytest.mark.parametrize(\"before\", [True, False])\ndef test_setenv_deleted_meanwhile(before):\n key = \"qwpeoip123\"\n if before:\n os.environ[key] = \"world\"\n monkeypatch = MonkeyPatch()\n monkeypatch.setenv(key, \"hello\")\n del os.environ[key]\n monkeypatch.undo()\n if before:\n assert os.environ[key] == \"world\"\n del os.environ[key]\n else:\n assert key not in os.environ"},{"attributeType":"str","col":4,"comment":"null","endLoc":675,"id":6707,"name":"source","nodeType":"Attribute","startLoc":675,"text":"source"},{"col":0,"comment":"null","endLoc":34,"header":"def test_source_str_function()","id":6708,"name":"test_source_str_function","nodeType":"Function","startLoc":22,"text":"def test_source_str_function():\n x = Source(\"3\")\n assert str(x) == \"3\"\n\n x = Source(\" 3\")\n assert str(x) == \"3\"\n\n x = Source(\n \"\"\"\n 3\n \"\"\"\n )\n assert str(x) == \"\\n3\""},{"col":0,"comment":"Return a :class:`_pytest.tmpdir.TempdirFactory` instance for the test session.\n ","endLoc":153,"header":"@pytest.fixture(scope=\"session\")\ndef tmpdir_factory(request)","id":6710,"name":"tmpdir_factory","nodeType":"Function","startLoc":149,"text":"@pytest.fixture(scope=\"session\")\ndef tmpdir_factory(request):\n \"\"\"Return a :class:`_pytest.tmpdir.TempdirFactory` instance for the test session.\n \"\"\"\n return request.config._tmpdirhandler"},{"col":4,"comment":"null","endLoc":504,"header":"def test_repr_source_not_existing(self)","id":6711,"name":"test_repr_source_not_existing","nodeType":"Function","startLoc":494,"text":"def test_repr_source_not_existing(self):\n pr = FormattedExcinfo()\n co = compile(\"raise ValueError()\", \"\", \"exec\")\n try:\n exec(co)\n except ValueError:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n repr = pr.repr_excinfo(excinfo)\n assert repr.reprtraceback.reprentries[1].lines[0] == \"> ???\"\n if sys.version_info[0] >= 3:\n assert repr.chain[0][0].reprentries[1].lines[0] == \"> ???\""},{"col":0,"comment":"null","endLoc":168,"header":"def test_delitem()","id":6712,"name":"test_delitem","nodeType":"Function","startLoc":154,"text":"def test_delitem():\n d = {\"x\": 1}\n monkeypatch = MonkeyPatch()\n monkeypatch.delitem(d, \"x\")\n assert \"x\" not in d\n monkeypatch.delitem(d, \"y\", raising=False)\n pytest.raises(KeyError, monkeypatch.delitem, d, \"y\")\n assert not d\n monkeypatch.setitem(d, \"y\", 1700)\n assert d[\"y\"] == 1700\n d[\"hello\"] = \"world\"\n monkeypatch.setitem(d, \"x\", 1500)\n assert d[\"x\"] == 1500\n monkeypatch.undo()\n assert d == {\"hello\": \"world\", \"x\": 1}"},{"col":0,"comment":"Return a :class:`_pytest.tmpdir.TempPathFactory` instance for the test session.\n ","endLoc":160,"header":"@pytest.fixture(scope=\"session\")\ndef tmp_path_factory(request)","id":6713,"name":"tmp_path_factory","nodeType":"Function","startLoc":156,"text":"@pytest.fixture(scope=\"session\")\ndef tmp_path_factory(request):\n \"\"\"Return a :class:`_pytest.tmpdir.TempPathFactory` instance for the test session.\n \"\"\"\n return request.config._tmp_path_factory"},{"col":0,"comment":"null","endLoc":168,"header":"def _mk_tmp(request, factory)","id":6715,"name":"_mk_tmp","nodeType":"Function","startLoc":163,"text":"def _mk_tmp(request, factory):\n name = request.node.name\n name = re.sub(r\"[\\W]\", \"_\", name)\n MAXVAL = 30\n name = name[:MAXVAL]\n return factory.mktemp(name, numbered=True)"},{"col":4,"comment":"null","endLoc":523,"header":"def test_repr_many_line_source_not_existing(self)","id":6716,"name":"test_repr_many_line_source_not_existing","nodeType":"Function","startLoc":506,"text":"def test_repr_many_line_source_not_existing(self):\n pr = FormattedExcinfo()\n co = compile(\n \"\"\"\na = 1\nraise ValueError()\n\"\"\",\n \"\",\n \"exec\",\n )\n try:\n exec(co)\n except ValueError:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n repr = pr.repr_excinfo(excinfo)\n assert repr.reprtraceback.reprentries[1].lines[0] == \"> ???\"\n if sys.version_info[0] >= 3:\n assert repr.chain[0][0].reprentries[1].lines[0] == \"> ???\""},{"col":4,"comment":"null","endLoc":587,"header":"def test_repr_source_failing_fullsource(self)","id":6717,"name":"test_repr_source_failing_fullsource","nodeType":"Function","startLoc":525,"text":"def test_repr_source_failing_fullsource(self):\n pr = FormattedExcinfo()\n\n class FakeCode(object):\n class raw(object):\n co_filename = \"?\"\n\n path = \"?\"\n firstlineno = 5\n\n def fullsource(self):\n return None\n\n fullsource = property(fullsource)\n\n class FakeFrame(object):\n code = FakeCode()\n f_locals = {}\n f_globals = {}\n\n class FakeTracebackEntry(_pytest._code.Traceback.Entry):\n def __init__(self, tb, excinfo=None):\n self.lineno = 5 + 3\n\n @property\n def frame(self):\n return FakeFrame()\n\n class Traceback(_pytest._code.Traceback):\n Entry = FakeTracebackEntry\n\n class FakeExcinfo(_pytest._code.ExceptionInfo):\n typename = \"Foo\"\n value = Exception()\n\n def __init__(self):\n pass\n\n def exconly(self, tryshort):\n return \"EXC\"\n\n def errisinstance(self, cls):\n return False\n\n excinfo = FakeExcinfo()\n\n class FakeRawTB(object):\n tb_next = None\n\n tb = FakeRawTB()\n excinfo.traceback = Traceback(tb)\n\n fail = IOError()\n repr = pr.repr_excinfo(excinfo)\n assert repr.reprtraceback.reprentries[0].lines[0] == \"> ???\"\n if sys.version_info[0] >= 3:\n assert repr.chain[0][0].reprentries[0].lines[0] == \"> ???\"\n\n fail = py.error.ENOENT # noqa\n repr = pr.repr_excinfo(excinfo)\n assert repr.reprtraceback.reprentries[0].lines[0] == \"> ???\"\n if sys.version_info[0] >= 3:\n assert repr.chain[0][0].reprentries[0].lines[0] == \"> ???\""},{"col":0,"comment":"Return a temporary directory path object\n which is unique to each test function invocation,\n created as a sub directory of the base temporary\n directory. The returned object is a `py.path.local`_\n path object.\n\n .. _`py.path.local`: https://py.readthedocs.io/en/latest/path.html\n ","endLoc":181,"header":"@pytest.fixture\ndef tmpdir(tmp_path)","id":6718,"name":"tmpdir","nodeType":"Function","startLoc":171,"text":"@pytest.fixture\ndef tmpdir(tmp_path):\n \"\"\"Return a temporary directory path object\n which is unique to each test function invocation,\n created as a sub directory of the base temporary\n directory. The returned object is a `py.path.local`_\n path object.\n\n .. _`py.path.local`: https://py.readthedocs.io/en/latest/path.html\n \"\"\"\n return py.path.local(tmp_path)"},{"col":0,"comment":"Return a temporary directory path object\n which is unique to each test function invocation,\n created as a sub directory of the base temporary\n directory. The returned object is a :class:`pathlib.Path`\n object.\n\n .. note::\n\n in python < 3.6 this is a pathlib2.Path\n ","endLoc":197,"header":"@pytest.fixture\ndef tmp_path(request, tmp_path_factory)","id":6719,"name":"tmp_path","nodeType":"Function","startLoc":184,"text":"@pytest.fixture\ndef tmp_path(request, tmp_path_factory):\n \"\"\"Return a temporary directory path object\n which is unique to each test function invocation,\n created as a sub directory of the base temporary\n directory. The returned object is a :class:`pathlib.Path`\n object.\n\n .. note::\n\n in python < 3.6 this is a pathlib2.Path\n \"\"\"\n\n return _mk_tmp(request, tmp_path_factory)"},{"col":0,"comment":"","endLoc":2,"header":"tmpdir.py#","id":6720,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" support for providing temporary directories to test functions. \"\"\""},{"id":6721,"name":"release-3.8.2.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.8.2\n=======================================\n\npytest 3.8.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Ankit Goel\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Denis Otkidach\n* Harry Percival\n* Jeffrey Rackauckas\n* Jose Carlos Menezes\n* Ronny Pfannschmidt\n* Zac-HD\n* iwanb\n\n\nHappy testing,\nThe pytest Development Team\n"},{"col":0,"comment":"null","endLoc":179,"header":"def test_setenv()","id":6722,"name":"test_setenv","nodeType":"Function","startLoc":171,"text":"def test_setenv():\n monkeypatch = MonkeyPatch()\n with pytest.warns(pytest.PytestWarning):\n monkeypatch.setenv(\"XYZ123\", 2)\n import os\n\n assert os.environ[\"XYZ123\"] == \"2\"\n monkeypatch.undo()\n assert \"XYZ123\" not in os.environ"},{"col":0,"comment":"null","endLoc":200,"header":"def test_delenv()","id":6723,"name":"test_delenv","nodeType":"Function","startLoc":182,"text":"def test_delenv():\n name = \"xyz1234\"\n assert name not in os.environ\n monkeypatch = MonkeyPatch()\n pytest.raises(KeyError, monkeypatch.delenv, name, raising=True)\n monkeypatch.delenv(name, raising=False)\n monkeypatch.undo()\n os.environ[name] = \"1\"\n try:\n monkeypatch = MonkeyPatch()\n monkeypatch.delenv(name)\n assert name not in os.environ\n monkeypatch.setenv(name, \"3\")\n assert os.environ[name] == \"3\"\n monkeypatch.undo()\n assert os.environ[name] == \"1\"\n finally:\n if name in os.environ:\n del os.environ[name]"},{"col":4,"comment":"Handle expressions we don't have custom code for.","endLoc":797,"header":"def generic_visit(self, node)","id":6724,"name":"generic_visit","nodeType":"Function","startLoc":793,"text":"def generic_visit(self, node):\n \"\"\"Handle expressions we don't have custom code for.\"\"\"\n assert isinstance(node, ast.expr)\n res = self.assign(node)\n return res, self.explanation_param(self.display(res))"},{"col":0,"comment":"null","endLoc":249,"header":"def test_setenv_prepend()","id":6725,"name":"test_setenv_prepend","nodeType":"Function","startLoc":238,"text":"def test_setenv_prepend():\n import os\n\n monkeypatch = MonkeyPatch()\n with pytest.warns(pytest.PytestWarning):\n monkeypatch.setenv(\"XYZ123\", 2, prepend=\"-\")\n assert os.environ[\"XYZ123\"] == \"2\"\n with pytest.warns(pytest.PytestWarning):\n monkeypatch.setenv(\"XYZ123\", 3, prepend=\"-\")\n assert os.environ[\"XYZ123\"] == \"3-2\"\n monkeypatch.undo()\n assert \"XYZ123\" not in os.environ"},{"col":0,"comment":"null","endLoc":260,"header":"def test_monkeypatch_plugin(testdir)","id":6726,"name":"test_monkeypatch_plugin","nodeType":"Function","startLoc":252,"text":"def test_monkeypatch_plugin(testdir):\n reprec = testdir.inline_runsource(\n \"\"\"\n def test_method(monkeypatch):\n assert monkeypatch.__class__.__name__ == \"MonkeyPatch\"\n \"\"\"\n )\n res = reprec.countoutcomes()\n assert tuple(res) == (1, 0, 0), res"},{"col":0,"comment":"null","endLoc":42,"header":"def test_unicode()","id":6727,"name":"test_unicode","nodeType":"Function","startLoc":37,"text":"def test_unicode():\n x = Source(u\"4\")\n assert str(x) == \"4\"\n co = _pytest._code.compile(u'u\"å\"', mode=\"eval\")\n val = eval(co)\n assert isinstance(val, six.text_type)"},{"col":4,"comment":"Return the AST statements to replace the ast.Assert instance.\n\n This rewrites the test of an assertion to provide\n intermediate values and replace it with an if statement which\n raises an assertion error with a detailed explanation in case\n the expression is false.\n\n ","endLoc":864,"header":"def visit_Assert(self, assert_)","id":6728,"name":"visit_Assert","nodeType":"Function","startLoc":799,"text":"def visit_Assert(self, assert_):\n \"\"\"Return the AST statements to replace the ast.Assert instance.\n\n This rewrites the test of an assertion to provide\n intermediate values and replace it with an if statement which\n raises an assertion error with a detailed explanation in case\n the expression is false.\n\n \"\"\"\n if isinstance(assert_.test, ast.Tuple) and len(assert_.test.elts) >= 1:\n from _pytest.warning_types import PytestAssertRewriteWarning\n import warnings\n\n warnings.warn_explicit(\n PytestAssertRewriteWarning(\n \"assertion is always true, perhaps remove parentheses?\"\n ),\n category=None,\n filename=str(self.module_path),\n lineno=assert_.lineno,\n )\n\n self.statements = []\n self.variables = []\n self.variable_counter = itertools.count()\n self.stack = []\n self.on_failure = []\n self.push_format_context()\n # Rewrite assert into a bunch of statements.\n top_condition, explanation = self.visit(assert_.test)\n # If in a test module, check if directly asserting None, in order to warn [Issue #3191]\n if self.module_path is not None:\n self.statements.append(\n self.warn_about_none_ast(\n top_condition, module_path=self.module_path, lineno=assert_.lineno\n )\n )\n # Create failure message.\n body = self.on_failure\n negation = ast.UnaryOp(ast.Not(), top_condition)\n self.statements.append(ast.If(negation, body, []))\n if assert_.msg:\n assertmsg = self.helper(\"_format_assertmsg\", assert_.msg)\n explanation = \"\\n>assert \" + explanation\n else:\n assertmsg = ast.Str(\"\")\n explanation = \"assert \" + explanation\n template = ast.BinOp(assertmsg, ast.Add(), ast.Str(explanation))\n msg = self.pop_format_context(template)\n fmt = self.helper(\"_format_explanation\", msg)\n err_name = ast.Name(\"AssertionError\", ast.Load())\n exc = ast_Call(err_name, [fmt], [])\n if sys.version_info[0] >= 3:\n raise_ = ast.Raise(exc, None)\n else:\n raise_ = ast.Raise(exc, None, None)\n body.append(raise_)\n # Clear temporary variables by setting them to None.\n if self.variables:\n variables = [ast.Name(name, ast.Store()) for name in self.variables]\n clear = ast.Assign(variables, _NameConstant(None))\n self.statements.append(clear)\n # Fix line numbers.\n for stmt in self.statements:\n set_location(stmt, assert_.lineno, assert_.col_offset)\n return self.statements"},{"col":0,"comment":"null","endLoc":47,"header":"def test_source_from_function()","id":6729,"name":"test_source_from_function","nodeType":"Function","startLoc":45,"text":"def test_source_from_function():\n source = _pytest._code.Source(test_source_str_function)\n assert str(source).startswith(\"def test_source_str_function():\")"},{"col":0,"comment":"null","endLoc":272,"header":"def test_syspath_prepend(mp)","id":6730,"name":"test_syspath_prepend","nodeType":"Function","startLoc":263,"text":"def test_syspath_prepend(mp):\n old = list(sys.path)\n mp.syspath_prepend(\"world\")\n mp.syspath_prepend(\"hello\")\n assert sys.path[0] == \"hello\"\n assert sys.path[1] == \"world\"\n mp.undo()\n assert sys.path == old\n mp.undo()\n assert sys.path == old"},{"id":6731,"name":"CHANGELOG.rst","nodeType":"TextFile","path":"","text":"=================\nChangelog history\n=================\n\nVersions follow `Semantic Versioning `_ (``..``).\n\nBackward incompatible (breaking) changes will only be introduced in major versions\nwith advance notice in the **Deprecations** section of releases.\n\n\n..\n You should *NOT* be adding new change log entries to this file, this\n file is managed by towncrier. You *may* edit previous change logs to\n fix problems like typo corrections or such.\n To add a new change log entry, please see\n https://pip.pypa.io/en/latest/development/#adding-a-news-entry\n we named the news folder changelog\n\n.. towncrier release notes start\n\npytest 4.6.5 (2019-08-05)\n=========================\n\nBug Fixes\n---------\n\n- `#4344 `_: Fix RuntimeError/StopIteration when trying to collect package with \"__init__.py\" only.\n\n\n- `#5478 `_: Fix encode error when using unicode strings in exceptions with ``pytest.raises``.\n\n\n- `#5524 `_: Fix issue where ``tmp_path`` and ``tmpdir`` would not remove directories containing files marked as read-only,\n which could lead to pytest crashing when executed a second time with the ``--basetemp`` option.\n\n\n- `#5547 `_: ``--step-wise`` now handles ``xfail(strict=True)`` markers properly.\n\n\n- `#5650 `_: Improved output when parsing an ini configuration file fails.\n\n\npytest 4.6.4 (2019-06-28)\n=========================\n\nBug Fixes\n---------\n\n- `#5404 `_: Emit a warning when attempting to unwrap a broken object raises an exception,\n for easier debugging (`#5080 `__).\n\n\n- `#5444 `_: Fix ``--stepwise`` mode when the first file passed on the command-line fails to collect.\n\n\n- `#5482 `_: Fix bug introduced in 4.6.0 causing collection errors when passing\n more than 2 positional arguments to ``pytest.mark.parametrize``.\n\n\n- `#5505 `_: Fix crash when discovery fails while using ``-p no:terminal``.\n\n\npytest 4.6.3 (2019-06-11)\n=========================\n\nBug Fixes\n---------\n\n- `#5383 `_: ``-q`` has again an impact on the style of the collected items\n (``--collect-only``) when ``--log-cli-level`` is used.\n\n\n- `#5389 `_: Fix regressions of `#5063 `__ for ``importlib_metadata.PathDistribution`` which have their ``files`` attribute being ``None``.\n\n\n- `#5390 `_: Fix regression where the ``obj`` attribute of ``TestCase`` items was no longer bound to methods.\n\n\npytest 4.6.2 (2019-06-03)\n=========================\n\nBug Fixes\n---------\n\n- `#5370 `_: Revert unrolling of ``all()`` to fix ``NameError`` on nested comprehensions.\n\n\n- `#5371 `_: Revert unrolling of ``all()`` to fix incorrect handling of generators with ``if``.\n\n\n- `#5372 `_: Revert unrolling of ``all()`` to fix incorrect assertion when using ``all()`` in an expression.\n\n\npytest 4.6.1 (2019-06-02)\n=========================\n\nBug Fixes\n---------\n\n- `#5354 `_: Fix ``pytest.mark.parametrize`` when the argvalues is an iterator.\n\n\n- `#5358 `_: Fix assertion rewriting of ``all()`` calls to deal with non-generators.\n\n\npytest 4.6.0 (2019-05-31)\n=========================\n\nImportant\n---------\n\nThe ``4.6.X`` series will be the last series to support **Python 2 and Python 3.4**.\n\nFor more details, see our `Python 2.7 and 3.4 support plan `__.\n\n\nFeatures\n--------\n\n- `#4559 `_: Added the ``junit_log_passing_tests`` ini value which can be used to enable or disable logging of passing test output in the Junit XML file.\n\n\n- `#4956 `_: pytester's ``testdir.spawn`` uses ``tmpdir`` as HOME/USERPROFILE directory.\n\n\n- `#5062 `_: Unroll calls to ``all`` to full for-loops with assertion rewriting for better failure messages, especially when using Generator Expressions.\n\n\n- `#5063 `_: Switch from ``pkg_resources`` to ``importlib-metadata`` for entrypoint detection for improved performance and import time.\n\n\n- `#5091 `_: The output for ini options in ``--help`` has been improved.\n\n\n- `#5269 `_: ``pytest.importorskip`` includes the ``ImportError`` now in the default ``reason``.\n\n\n- `#5311 `_: Captured logs that are output for each failing test are formatted using the\n ColoredLevelFormatter.\n\n\n- `#5312 `_: Improved formatting of multiline log messages in Python 3.\n\n\n\nBug Fixes\n---------\n\n- `#2064 `_: The debugging plugin imports the wrapped ``Pdb`` class (``--pdbcls``) on-demand now.\n\n\n- `#4908 `_: The ``pytest_enter_pdb`` hook gets called with post-mortem (``--pdb``).\n\n\n- `#5036 `_: Fix issue where fixtures dependent on other parametrized fixtures would be erroneously parametrized.\n\n\n- `#5256 `_: Handle internal error due to a lone surrogate unicode character not being representable in Jython.\n\n\n- `#5257 `_: Ensure that ``sys.stdout.mode`` does not include ``'b'`` as it is a text stream.\n\n\n- `#5278 `_: Pytest's internal python plugin can be disabled using ``-p no:python`` again.\n\n\n- `#5286 `_: Fix issue with ``disable_test_id_escaping_and_forfeit_all_rights_to_community_support`` option not working when using a list of test IDs in parametrized tests.\n\n\n- `#5330 `_: Show the test module being collected when emitting ``PytestCollectionWarning`` messages for\n test classes with ``__init__`` and ``__new__`` methods to make it easier to pin down the problem.\n\n\n- `#5333 `_: Fix regression in 4.5.0 with ``--lf`` not re-running all tests with known failures from non-selected tests.\n\n\n\nImproved Documentation\n----------------------\n\n- `#5250 `_: Expand docs on use of ``setenv`` and ``delenv`` with ``monkeypatch``.\n\n\npytest 4.5.0 (2019-05-11)\n=========================\n\nFeatures\n--------\n\n- `#4826 `_: A warning is now emitted when unknown marks are used as a decorator.\n This is often due to a typo, which can lead to silently broken tests.\n\n\n- `#4907 `_: Show XFail reason as part of JUnitXML message field.\n\n\n- `#5013 `_: Messages from crash reports are displayed within test summaries now, truncated to the terminal width.\n\n\n- `#5023 `_: New flag ``--strict-markers`` that triggers an error when unknown markers (e.g. those not registered using the `markers option`_ in the configuration file) are used in the test suite.\n\n The existing ``--strict`` option has the same behavior currently, but can be augmented in the future for additional checks.\n\n .. _`markers option`: https://docs.pytest.org/en/latest/reference.html#confval-markers\n\n\n- `#5026 `_: Assertion failure messages for sequences and dicts contain the number of different items now.\n\n\n- `#5034 `_: Improve reporting with ``--lf`` and ``--ff`` (run-last-failure).\n\n\n- `#5035 `_: The ``--cache-show`` option/action accepts an optional glob to show only matching cache entries.\n\n\n- `#5059 `_: Standard input (stdin) can be given to pytester's ``Testdir.run()`` and ``Testdir.popen()``.\n\n\n- `#5068 `_: The ``-r`` option learnt about ``A`` to display all reports (including passed ones) in the short test summary.\n\n\n- `#5108 `_: The short test summary is displayed after passes with output (``-rP``).\n\n\n- `#5172 `_: The ``--last-failed`` (``--lf``) option got smarter and will now skip entire files if all tests\n of that test file have passed in previous runs, greatly speeding up collection.\n\n\n- `#5177 `_: Introduce new specific warning ``PytestWarning`` subclasses to make it easier to filter warnings based on the class, rather than on the message. The new subclasses are:\n\n\n * ``PytestAssertRewriteWarning``\n\n * ``PytestCacheWarning``\n\n * ``PytestCollectionWarning``\n\n * ``PytestConfigWarning``\n\n * ``PytestUnhandledCoroutineWarning``\n\n * ``PytestUnknownMarkWarning``\n\n\n- `#5202 `_: New ``record_testsuite_property`` session-scoped fixture allows users to log ```` tags at the ``testsuite``\n level with the ``junitxml`` plugin.\n\n The generated XML is compatible with the latest xunit standard, contrary to\n the properties recorded by ``record_property`` and ``record_xml_attribute``.\n\n\n- `#5214 `_: The default logging format has been changed to improve readability. Here is an\n example of a previous logging message::\n\n test_log_cli_enabled_disabled.py 3 CRITICAL critical message logged by test\n\n This has now become::\n\n CRITICAL root:test_log_cli_enabled_disabled.py:3 critical message logged by test\n\n The formatting can be changed through the `log_format `__ configuration option.\n\n\n- `#5220 `_: ``--fixtures`` now also shows fixture scope for scopes other than ``\"function\"``.\n\n\n\nBug Fixes\n---------\n\n- `#5113 `_: Deselected items from plugins using ``pytest_collect_modifyitems`` as a hookwrapper are correctly reported now.\n\n\n- `#5144 `_: With usage errors ``exitstatus`` is set to ``EXIT_USAGEERROR`` in the ``pytest_sessionfinish`` hook now as expected.\n\n\n- `#5235 `_: ``outcome.exit`` is not used with ``EOF`` in the pdb wrapper anymore, but only with ``quit``.\n\n\n\nImproved Documentation\n----------------------\n\n- `#4935 `_: Expand docs on registering marks and the effect of ``--strict``.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#4942 `_: ``logging.raiseExceptions`` is not set to ``False`` anymore.\n\n\n- `#5013 `_: pytest now depends on `wcwidth `__ to properly track unicode character sizes for more precise terminal output.\n\n\n- `#5059 `_: pytester's ``Testdir.popen()`` uses ``stdout`` and ``stderr`` via keyword arguments with defaults now (``subprocess.PIPE``).\n\n\n- `#5069 `_: The code for the short test summary in the terminal was moved to the terminal plugin.\n\n\n- `#5082 `_: Improved validation of kwargs for various methods in the pytester plugin.\n\n\n- `#5202 `_: ``record_property`` now emits a ``PytestWarning`` when used with ``junit_family=xunit2``: the fixture generates\n ``property`` tags as children of ``testcase``, which is not permitted according to the most\n `recent schema `__.\n\n\n- `#5239 `_: Pin ``pluggy`` to ``< 1.0`` so we don't update to ``1.0`` automatically when\n it gets released: there are planned breaking changes, and we want to ensure\n pytest properly supports ``pluggy 1.0``.\n\n\npytest 4.4.2 (2019-05-08)\n=========================\n\nBug Fixes\n---------\n\n- `#5089 `_: Fix crash caused by error in ``__repr__`` function with both ``showlocals`` and verbose output enabled.\n\n\n- `#5139 `_: Eliminate core dependency on 'terminal' plugin.\n\n\n- `#5229 `_: Require ``pluggy>=0.11.0`` which reverts a dependency to ``importlib-metadata`` added in ``0.10.0``.\n The ``importlib-metadata`` package cannot be imported when installed as an egg and causes issues when relying on ``setup.py`` to install test dependencies.\n\n\n\nImproved Documentation\n----------------------\n\n- `#5171 `_: Doc: ``pytest_ignore_collect``, ``pytest_collect_directory``, ``pytest_collect_file`` and ``pytest_pycollect_makemodule`` hooks's 'path' parameter documented type is now ``py.path.local``\n\n\n- `#5188 `_: Improve help for ``--runxfail`` flag.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#5182 `_: Removed internal and unused ``_pytest.deprecated.MARK_INFO_ATTRIBUTE``.\n\n\npytest 4.4.1 (2019-04-15)\n=========================\n\nBug Fixes\n---------\n\n- `#5031 `_: Environment variables are properly restored when using pytester's ``testdir`` fixture.\n\n\n- `#5039 `_: Fix regression with ``--pdbcls``, which stopped working with local modules in 4.0.0.\n\n\n- `#5092 `_: Produce a warning when unknown keywords are passed to ``pytest.param(...)``.\n\n\n- `#5098 `_: Invalidate import caches with ``monkeypatch.syspath_prepend``, which is required with namespace packages being used.\n\n\npytest 4.4.0 (2019-03-29)\n=========================\n\nFeatures\n--------\n\n- `#2224 `_: ``async`` test functions are skipped and a warning is emitted when a suitable\n async plugin is not installed (such as ``pytest-asyncio`` or ``pytest-trio``).\n\n Previously ``async`` functions would not execute at all but still be marked as \"passed\".\n\n\n- `#2482 `_: Include new ``disable_test_id_escaping_and_forfeit_all_rights_to_community_support`` option to disable ascii-escaping in parametrized values. This may cause a series of problems and as the name makes clear, use at your own risk.\n\n\n- `#4718 `_: The ``-p`` option can now be used to early-load plugins also by entry-point name, instead of just\n by module name.\n\n This makes it possible to early load external plugins like ``pytest-cov`` in the command-line::\n\n pytest -p pytest_cov\n\n\n- `#4855 `_: The ``--pdbcls`` option handles classes via module attributes now (e.g.\n ``pdb:pdb.Pdb`` with `pdb++`_), and its validation was improved.\n\n .. _pdb++: https://pypi.org/project/pdbpp/\n\n\n- `#4875 `_: The `testpaths `__ configuration option is now displayed next\n to the ``rootdir`` and ``inifile`` lines in the pytest header if the option is in effect, i.e., directories or file names were\n not explicitly passed in the command line.\n\n Also, ``inifile`` is only displayed if there's a configuration file, instead of an empty ``inifile:`` string.\n\n\n- `#4911 `_: Doctests can be skipped now dynamically using ``pytest.skip()``.\n\n\n- `#4920 `_: Internal refactorings have been made in order to make the implementation of the\n `pytest-subtests `__ plugin\n possible, which adds unittest sub-test support and a new ``subtests`` fixture as discussed in\n `#1367 `__.\n\n For details on the internal refactorings, please see the details on the related PR.\n\n\n- `#4931 `_: pytester's ``LineMatcher`` asserts that the passed lines are a sequence.\n\n\n- `#4936 `_: Handle ``-p plug`` after ``-p no:plug``.\n\n This can be used to override a blocked plugin (e.g. in \"addopts\") from the\n command line etc.\n\n\n- `#4951 `_: Output capturing is handled correctly when only capturing via fixtures (capsys, capfs) with ``pdb.set_trace()``.\n\n\n- `#4956 `_: ``pytester`` sets ``$HOME`` and ``$USERPROFILE`` to the temporary directory during test runs.\n\n This ensures to not load configuration files from the real user's home directory.\n\n\n- `#4980 `_: Namespace packages are handled better with ``monkeypatch.syspath_prepend`` and ``testdir.syspathinsert`` (via ``pkg_resources.fixup_namespace_packages``).\n\n\n- `#4993 `_: The stepwise plugin reports status information now.\n\n\n- `#5008 `_: If a ``setup.cfg`` file contains ``[tool:pytest]`` and also the no longer supported ``[pytest]`` section, pytest will use ``[tool:pytest]`` ignoring ``[pytest]``. Previously it would unconditionally error out.\n\n This makes it simpler for plugins to support old pytest versions.\n\n\n\nBug Fixes\n---------\n\n- `#1895 `_: Fix bug where fixtures requested dynamically via ``request.getfixturevalue()`` might be teardown\n before the requesting fixture.\n\n\n- `#4851 `_: pytester unsets ``PYTEST_ADDOPTS`` now to not use outer options with ``testdir.runpytest()``.\n\n\n- `#4903 `_: Use the correct modified time for years after 2038 in rewritten ``.pyc`` files.\n\n\n- `#4928 `_: Fix line offsets with ``ScopeMismatch`` errors.\n\n\n- `#4957 `_: ``-p no:plugin`` is handled correctly for default (internal) plugins now, e.g. with ``-p no:capture``.\n\n Previously they were loaded (imported) always, making e.g. the ``capfd`` fixture available.\n\n\n- `#4968 `_: The pdb ``quit`` command is handled properly when used after the ``debug`` command with `pdb++`_.\n\n .. _pdb++: https://pypi.org/project/pdbpp/\n\n\n- `#4975 `_: Fix the interpretation of ``-qq`` option where it was being considered as ``-v`` instead.\n\n\n- `#4978 `_: ``outcomes.Exit`` is not swallowed in ``assertrepr_compare`` anymore.\n\n\n- `#4988 `_: Close logging's file handler explicitly when the session finishes.\n\n\n- `#5003 `_: Fix line offset with mark collection error (off by one).\n\n\n\nImproved Documentation\n----------------------\n\n- `#4974 `_: Update docs for ``pytest_cmdline_parse`` hook to note availability liminations\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#4718 `_: ``pluggy>=0.9`` is now required.\n\n\n- `#4815 `_: ``funcsigs>=1.0`` is now required for Python 2.7.\n\n\n- `#4829 `_: Some left-over internal code related to ``yield`` tests has been removed.\n\n\n- `#4890 `_: Remove internally unused ``anypython`` fixture from the pytester plugin.\n\n\n- `#4912 `_: Remove deprecated Sphinx directive, ``add_description_unit()``,\n pin sphinx-removed-in to >= 0.2.0 to support Sphinx 2.0.\n\n\n- `#4913 `_: Fix pytest tests invocation with custom ``PYTHONPATH``.\n\n\n- `#4965 `_: New ``pytest_report_to_serializable`` and ``pytest_report_from_serializable`` **experimental** hooks.\n\n These hooks will be used by ``pytest-xdist``, ``pytest-subtests``, and the replacement for\n resultlog to serialize and customize reports.\n\n They are experimental, meaning that their details might change or even be removed\n completely in future patch releases without warning.\n\n Feedback is welcome from plugin authors and users alike.\n\n\n- `#4987 `_: ``Collector.repr_failure`` respects the ``--tb`` option, but only defaults to ``short`` now (with ``auto``).\n\n\npytest 4.3.1 (2019-03-11)\n=========================\n\nBug Fixes\n---------\n\n- `#4810 `_: Logging messages inside ``pytest_runtest_logreport()`` are now properly captured and displayed.\n\n\n- `#4861 `_: Improve validation of contents written to captured output so it behaves the same as when capture is disabled.\n\n\n- `#4898 `_: Fix ``AttributeError: FixtureRequest has no 'confg' attribute`` bug in ``testdir.copy_example``.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#4768 `_: Avoid pkg_resources import at the top-level.\n\n\npytest 4.3.0 (2019-02-16)\n=========================\n\nDeprecations\n------------\n\n- `#4724 `_: ``pytest.warns()`` now emits a warning when it receives unknown keyword arguments.\n\n This will be changed into an error in the future.\n\n\n\nFeatures\n--------\n\n- `#2753 `_: Usage errors from argparse are mapped to pytest's ``UsageError``.\n\n\n- `#3711 `_: Add the ``--ignore-glob`` parameter to exclude test-modules with Unix shell-style wildcards.\n Add the ``collect_ignore_glob`` for ``conftest.py`` to exclude test-modules with Unix shell-style wildcards.\n\n\n- `#4698 `_: The warning about Python 2.7 and 3.4 not being supported in pytest 5.0 has been removed.\n\n In the end it was considered to be more\n of a nuisance than actual utility and users of those Python versions shouldn't have problems as ``pip`` will not\n install pytest 5.0 on those interpreters.\n\n\n- `#4707 `_: With the help of new ``set_log_path()`` method there is a way to set ``log_file`` paths from hooks.\n\n\n\nBug Fixes\n---------\n\n- `#4651 `_: ``--help`` and ``--version`` are handled with ``UsageError``.\n\n\n- `#4782 `_: Fix ``AssertionError`` with collection of broken symlinks with packages.\n\n\npytest 4.2.1 (2019-02-12)\n=========================\n\nBug Fixes\n---------\n\n- `#2895 `_: The ``pytest_report_collectionfinish`` hook now is also called with ``--collect-only``.\n\n\n- `#3899 `_: Do not raise ``UsageError`` when an imported package has a ``pytest_plugins.py`` child module.\n\n\n- `#4347 `_: Fix output capturing when using pdb++ with recursive debugging.\n\n\n- `#4592 `_: Fix handling of ``collect_ignore`` via parent ``conftest.py``.\n\n\n- `#4700 `_: Fix regression where ``setUpClass`` would always be called in subclasses even if all tests\n were skipped by a ``unittest.skip()`` decorator applied in the subclass.\n\n\n- `#4739 `_: Fix ``parametrize(... ids=)`` when the function returns non-strings.\n\n\n- `#4745 `_: Fix/improve collection of args when passing in ``__init__.py`` and a test file.\n\n\n- `#4770 `_: ``more_itertools`` is now constrained to <6.0.0 when required for Python 2.7 compatibility.\n\n\n- `#526 `_: Fix \"ValueError: Plugin already registered\" exceptions when running in build directories that symlink to actual source.\n\n\n\nImproved Documentation\n----------------------\n\n- `#3899 `_: Add note to ``plugins.rst`` that ``pytest_plugins`` should not be used as a name for a user module containing plugins.\n\n\n- `#4324 `_: Document how to use ``raises`` and ``does_not_raise`` to write parametrized tests with conditional raises.\n\n\n- `#4709 `_: Document how to customize test failure messages when using\n ``pytest.warns``.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#4741 `_: Some verbosity related attributes of the TerminalReporter plugin are now\n read only properties.\n\n\npytest 4.2.0 (2019-01-30)\n=========================\n\nFeatures\n--------\n\n- `#3094 `_: `Classic xunit-style `__ functions and methods\n now obey the scope of *autouse* fixtures.\n\n This fixes a number of surprising issues like ``setup_method`` being called before session-scoped\n autouse fixtures (see `#517 `__ for an example).\n\n\n- `#4627 `_: Display a message at the end of the test session when running under Python 2.7 and 3.4 that pytest 5.0 will no longer\n support those Python versions.\n\n\n- `#4660 `_: The number of *selected* tests now are also displayed when the ``-k`` or ``-m`` flags are used.\n\n\n- `#4688 `_: ``pytest_report_teststatus`` hook now can also receive a ``config`` parameter.\n\n\n- `#4691 `_: ``pytest_terminal_summary`` hook now can also receive a ``config`` parameter.\n\n\n\nBug Fixes\n---------\n\n- `#3547 `_: ``--junitxml`` can emit XML compatible with Jenkins xUnit.\n ``junit_family`` INI option accepts ``legacy|xunit1``, which produces old style output, and ``xunit2`` that conforms more strictly to https://github.com/jenkinsci/xunit-plugin/blob/xunit-2.3.2/src/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd\n\n\n- `#4280 `_: Improve quitting from pdb, especially with ``--trace``.\n\n Using ``q[quit]`` after ``pdb.set_trace()`` will quit pytest also.\n\n\n- `#4402 `_: Warning summary now groups warnings by message instead of by test id.\n\n This makes the output more compact and better conveys the general idea of how much code is\n actually generating warnings, instead of how many tests call that code.\n\n\n- `#4536 `_: ``monkeypatch.delattr`` handles class descriptors like ``staticmethod``/``classmethod``.\n\n\n- `#4649 `_: Restore marks being considered keywords for keyword expressions.\n\n\n- `#4653 `_: ``tmp_path`` fixture and other related ones provides resolved path (a.k.a real path)\n\n\n- `#4667 `_: ``pytest_terminal_summary`` uses result from ``pytest_report_teststatus`` hook, rather than hardcoded strings.\n\n\n- `#4669 `_: Correctly handle ``unittest.SkipTest`` exception containing non-ascii characters on Python 2.\n\n\n- `#4680 `_: Ensure the ``tmpdir`` and the ``tmp_path`` fixtures are the same folder.\n\n\n- `#4681 `_: Ensure ``tmp_path`` is always a real path.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#4643 `_: Use ``a.item()`` instead of the deprecated ``np.asscalar(a)`` in ``pytest.approx``.\n\n ``np.asscalar`` has been `deprecated `__ in ``numpy 1.16.``.\n\n\n- `#4657 `_: Copy saferepr from pylib\n\n\n- `#4668 `_: The verbose word for expected failures in the teststatus report changes from ``xfail`` to ``XFAIL`` to be consistent with other test outcomes.\n\n\npytest 4.1.1 (2019-01-12)\n=========================\n\nBug Fixes\n---------\n\n- `#2256 `_: Show full repr with ``assert a==b`` and ``-vv``.\n\n\n- `#3456 `_: Extend Doctest-modules to ignore mock objects.\n\n\n- `#4617 `_: Fixed ``pytest.warns`` bug when context manager is reused (e.g. multiple parametrization).\n\n\n- `#4631 `_: Don't rewrite assertion when ``__getattr__`` is broken\n\n\n\nImproved Documentation\n----------------------\n\n- `#3375 `_: Document that using ``setup.cfg`` may crash other tools or cause hard to track down problems because it uses a different parser than ``pytest.ini`` or ``tox.ini`` files.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#4602 `_: Uninstall ``hypothesis`` in regen tox env.\n\n\npytest 4.1.0 (2019-01-05)\n=========================\n\nRemovals\n--------\n\n- `#2169 `_: ``pytest.mark.parametrize``: in previous versions, errors raised by id functions were suppressed and changed into warnings. Now the exceptions are propagated, along with a pytest message informing the node, parameter value and index where the exception occurred.\n\n\n- `#3078 `_: Remove legacy internal warnings system: ``config.warn``, ``Node.warn``. The ``pytest_logwarning`` now issues a warning when implemented.\n\n See our `docs `__ on information on how to update your code.\n\n\n- `#3079 `_: Removed support for yield tests - they are fundamentally broken because they don't support fixtures properly since collection and test execution were separated.\n\n See our `docs `__ on information on how to update your code.\n\n\n- `#3082 `_: Removed support for applying marks directly to values in ``@pytest.mark.parametrize``. Use ``pytest.param`` instead.\n\n See our `docs `__ on information on how to update your code.\n\n\n- `#3083 `_: Removed ``Metafunc.addcall``. This was the predecessor mechanism to ``@pytest.mark.parametrize``.\n\n See our `docs `__ on information on how to update your code.\n\n\n- `#3085 `_: Removed support for passing strings to ``pytest.main``. Now, always pass a list of strings instead.\n\n See our `docs `__ on information on how to update your code.\n\n\n- `#3086 `_: ``[pytest]`` section in **setup.cfg** files is no longer supported, use ``[tool:pytest]`` instead. ``setup.cfg`` files\n are meant for use with ``distutils``, and a section named ``pytest`` has notoriously been a source of conflicts and bugs.\n\n Note that for **pytest.ini** and **tox.ini** files the section remains ``[pytest]``.\n\n\n- `#3616 `_: Removed the deprecated compat properties for ``node.Class/Function/Module`` - use ``pytest.Class/Function/Module`` now.\n\n See our `docs `__ on information on how to update your code.\n\n\n- `#4421 `_: Removed the implementation of the ``pytest_namespace`` hook.\n\n See our `docs `__ on information on how to update your code.\n\n\n- `#4489 `_: Removed ``request.cached_setup``. This was the predecessor mechanism to modern fixtures.\n\n See our `docs `__ on information on how to update your code.\n\n\n- `#4535 `_: Removed the deprecated ``PyCollector.makeitem`` method. This method was made public by mistake a long time ago.\n\n\n- `#4543 `_: Removed support to define fixtures using the ``pytest_funcarg__`` prefix. Use the ``@pytest.fixture`` decorator instead.\n\n See our `docs `__ on information on how to update your code.\n\n\n- `#4545 `_: Calling fixtures directly is now always an error instead of a warning.\n\n See our `docs `__ on information on how to update your code.\n\n\n- `#4546 `_: Remove ``Node.get_marker(name)`` the return value was not usable for more than a existence check.\n\n Use ``Node.get_closest_marker(name)`` as a replacement.\n\n\n- `#4547 `_: The deprecated ``record_xml_property`` fixture has been removed, use the more generic ``record_property`` instead.\n\n See our `docs `__ for more information.\n\n\n- `#4548 `_: An error is now raised if the ``pytest_plugins`` variable is defined in a non-top-level ``conftest.py`` file (i.e., not residing in the ``rootdir``).\n\n See our `docs `__ for more information.\n\n\n- `#891 `_: Remove ``testfunction.markername`` attributes - use ``Node.iter_markers(name=None)`` to iterate them.\n\n\n\nDeprecations\n------------\n\n- `#3050 `_: Deprecated the ``pytest.config`` global.\n\n See https://docs.pytest.org/en/latest/deprecations.html#pytest-config-global for rationale.\n\n\n- `#3974 `_: Passing the ``message`` parameter of ``pytest.raises`` now issues a ``DeprecationWarning``.\n\n It is a common mistake to think this parameter will match the exception message, while in fact\n it only serves to provide a custom message in case the ``pytest.raises`` check fails. To avoid this\n mistake and because it is believed to be little used, pytest is deprecating it without providing\n an alternative for the moment.\n\n If you have concerns about this, please comment on `issue #3974 `__.\n\n\n- `#4435 `_: Deprecated ``raises(..., 'code(as_a_string)')`` and ``warns(..., 'code(as_a_string)')``.\n\n See https://docs.pytest.org/en/latest/deprecations.html#raises-warns-exec for rationale and examples.\n\n\n\nFeatures\n--------\n\n- `#3191 `_: A warning is now issued when assertions are made for ``None``.\n\n This is a common source of confusion among new users, which write:\n\n .. code-block:: python\n\n assert mocked_object.assert_called_with(3, 4, 5, key=\"value\")\n\n When they should write:\n\n .. code-block:: python\n\n mocked_object.assert_called_with(3, 4, 5, key=\"value\")\n\n Because the ``assert_called_with`` method of mock objects already executes an assertion.\n\n This warning will not be issued when ``None`` is explicitly checked. An assertion like:\n\n .. code-block:: python\n\n assert variable is None\n\n will not issue the warning.\n\n\n- `#3632 `_: Richer equality comparison introspection on ``AssertionError`` for objects created using `attrs `__ or `dataclasses `_ (Python 3.7+, `backported to 3.6 `__).\n\n\n- `#4278 `_: ``CACHEDIR.TAG`` files are now created inside cache directories.\n\n Those files are part of the `Cache Directory Tagging Standard `__, and can\n be used by backup or synchronization programs to identify pytest's cache directory as such.\n\n\n- `#4292 `_: ``pytest.outcomes.Exit`` is derived from ``SystemExit`` instead of ``KeyboardInterrupt``. This allows us to better handle ``pdb`` exiting.\n\n\n- `#4371 `_: Updated the ``--collect-only`` option to display test descriptions when ran using ``--verbose``.\n\n\n- `#4386 `_: Restructured ``ExceptionInfo`` object construction and ensure incomplete instances have a ``repr``/``str``.\n\n\n- `#4416 `_: pdb: added support for keyword arguments with ``pdb.set_trace``.\n\n It handles ``header`` similar to Python 3.7 does it, and forwards any\n other keyword arguments to the ``Pdb`` constructor.\n\n This allows for ``__import__(\"pdb\").set_trace(skip=[\"foo.*\"])``.\n\n\n- `#4483 `_: Added ini parameter ``junit_duration_report`` to optionally report test call durations, excluding setup and teardown times.\n\n The JUnit XML specification and the default pytest behavior is to include setup and teardown times in the test duration\n report. You can include just the call durations instead (excluding setup and teardown) by adding this to your ``pytest.ini`` file:\n\n .. code-block:: ini\n\n [pytest]\n junit_duration_report = call\n\n\n- `#4532 `_: ``-ra`` now will show errors and failures last, instead of as the first items in the summary.\n\n This makes it easier to obtain a list of errors and failures to run tests selectively.\n\n\n- `#4599 `_: ``pytest.importorskip`` now supports a ``reason`` parameter, which will be shown when the\n requested module cannot be imported.\n\n\n\nBug Fixes\n---------\n\n- `#3532 `_: ``-p`` now accepts its argument without a space between the value, for example ``-pmyplugin``.\n\n\n- `#4327 `_: ``approx`` again works with more generic containers, more precisely instances of ``Iterable`` and ``Sized`` instead of more restrictive ``Sequence``.\n\n\n- `#4397 `_: Ensure that node ids are printable.\n\n\n- `#4435 `_: Fixed ``raises(..., 'code(string)')`` frame filename.\n\n\n- `#4458 `_: Display actual test ids in ``--collect-only``.\n\n\n\nImproved Documentation\n----------------------\n\n- `#4557 `_: Markers example documentation page updated to support latest pytest version.\n\n\n- `#4558 `_: Update cache documentation example to correctly show cache hit and miss.\n\n\n- `#4580 `_: Improved detailed summary report documentation.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#4447 `_: Changed the deprecation type of ``--result-log`` to ``PytestDeprecationWarning``.\n\n It was decided to remove this feature at the next major revision.\n\n\npytest 4.0.2 (2018-12-13)\n=========================\n\nBug Fixes\n---------\n\n- `#4265 `_: Validate arguments from the ``PYTEST_ADDOPTS`` environment variable and the ``addopts`` ini option separately.\n\n\n- `#4435 `_: Fix ``raises(..., 'code(string)')`` frame filename.\n\n\n- `#4500 `_: When a fixture yields and a log call is made after the test runs, and, if the test is interrupted, capture attributes are ``None``.\n\n\n- `#4538 `_: Raise ``TypeError`` for ``with raises(..., match=)``.\n\n\n\nImproved Documentation\n----------------------\n\n- `#1495 `_: Document common doctest fixture directory tree structure pitfalls\n\n\npytest 4.0.1 (2018-11-23)\n=========================\n\nBug Fixes\n---------\n\n- `#3952 `_: Display warnings before \"short test summary info\" again, but still later warnings in the end.\n\n\n- `#4386 `_: Handle uninitialized exceptioninfo in repr/str.\n\n\n- `#4393 `_: Do not create ``.gitignore``/``README.md`` files in existing cache directories.\n\n\n- `#4400 `_: Rearrange warning handling for the yield test errors so the opt-out in 4.0.x correctly works.\n\n\n- `#4405 `_: Fix collection of testpaths with ``--pyargs``.\n\n\n- `#4412 `_: Fix assertion rewriting involving ``Starred`` + side-effects.\n\n\n- `#4425 `_: Ensure we resolve the absolute path when the given ``--basetemp`` is a relative path.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#4315 `_: Use ``pkg_resources.parse_version`` instead of ``LooseVersion`` in minversion check.\n\n\n- `#4440 `_: Adjust the stack level of some internal pytest warnings.\n\n\npytest 4.0.0 (2018-11-13)\n=========================\n\nRemovals\n--------\n\n- `#3737 `_: **RemovedInPytest4Warnings are now errors by default.**\n\n Following our plan to remove deprecated features with as little disruption as\n possible, all warnings of type ``RemovedInPytest4Warnings`` now generate errors\n instead of warning messages.\n\n **The affected features will be effectively removed in pytest 4.1**, so please consult the\n `Deprecations and Removals `__\n section in the docs for directions on how to update existing code.\n\n In the pytest ``4.0.X`` series, it is possible to change the errors back into warnings as a stop\n gap measure by adding this to your ``pytest.ini`` file:\n\n .. code-block:: ini\n\n [pytest]\n filterwarnings =\n ignore::pytest.RemovedInPytest4Warning\n\n But this will stop working when pytest ``4.1`` is released.\n\n **If you have concerns** about the removal of a specific feature, please add a\n comment to `#4348 `__.\n\n\n- `#4358 `_: Remove the ``::()`` notation to denote a test class instance in node ids.\n\n Previously, node ids that contain test instances would use ``::()`` to denote the instance like this::\n\n test_foo.py::Test::()::test_bar\n\n The extra ``::()`` was puzzling to most users and has been removed, so that the test id becomes now::\n\n test_foo.py::Test::test_bar\n\n This change could not accompany a deprecation period as is usual when user-facing functionality changes because\n it was not really possible to detect when the functionality was being used explicitly.\n\n The extra ``::()`` might have been removed in some places internally already,\n which then led to confusion in places where it was expected, e.g. with\n ``--deselect`` (`#4127 `_).\n\n Test class instances are also not listed with ``--collect-only`` anymore.\n\n\n\nFeatures\n--------\n\n- `#4270 `_: The ``cache_dir`` option uses ``$TOX_ENV_DIR`` as prefix (if set in the environment).\n\n This uses a different cache per tox environment by default.\n\n\n\nBug Fixes\n---------\n\n- `#3554 `_: Fix ``CallInfo.__repr__`` for when the call is not finished yet.\n\n\npytest 3.10.1 (2018-11-11)\n==========================\n\nBug Fixes\n---------\n\n- `#4287 `_: Fix nested usage of debugging plugin (pdb), e.g. with pytester's ``testdir.runpytest``.\n\n\n- `#4304 `_: Block the ``stepwise`` plugin if ``cacheprovider`` is also blocked, as one depends on the other.\n\n\n- `#4306 `_: Parse ``minversion`` as an actual version and not as dot-separated strings.\n\n\n- `#4310 `_: Fix duplicate collection due to multiple args matching the same packages.\n\n\n- `#4321 `_: Fix ``item.nodeid`` with resolved symlinks.\n\n\n- `#4325 `_: Fix collection of direct symlinked files, where the target does not match ``python_files``.\n\n\n- `#4329 `_: Fix TypeError in report_collect with _collect_report_last_write.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#4305 `_: Replace byte/unicode helpers in test_capture with python level syntax.\n\n\npytest 3.10.0 (2018-11-03)\n==========================\n\nFeatures\n--------\n\n- `#2619 `_: Resume capturing output after ``continue`` with ``__import__(\"pdb\").set_trace()``.\n\n This also adds a new ``pytest_leave_pdb`` hook, and passes in ``pdb`` to the\n existing ``pytest_enter_pdb`` hook.\n\n\n- `#4147 `_: Add ``--sw``, ``--stepwise`` as an alternative to ``--lf -x`` for stopping at the first failure, but starting the next test invocation from that test. See `the documentation `__ for more info.\n\n\n- `#4188 `_: Make ``--color`` emit colorful dots when not running in verbose mode. Earlier, it would only colorize the test-by-test output if ``--verbose`` was also passed.\n\n\n- `#4225 `_: Improve performance with collection reporting in non-quiet mode with terminals.\n\n The \"collecting …\" message is only printed/updated every 0.5s.\n\n\n\nBug Fixes\n---------\n\n- `#2701 `_: Fix false ``RemovedInPytest4Warning: usage of Session... is deprecated, please use pytest`` warnings.\n\n\n- `#4046 `_: Fix problems with running tests in package ``__init__.py`` files.\n\n\n- `#4260 `_: Swallow warnings during anonymous compilation of source.\n\n\n- `#4262 `_: Fix access denied error when deleting stale directories created by ``tmpdir`` / ``tmp_path``.\n\n\n- `#611 `_: Naming a fixture ``request`` will now raise a warning: the ``request`` fixture is internal and\n should not be overwritten as it will lead to internal errors.\n\n- `#4266 `_: Handle (ignore) exceptions raised during collection, e.g. with Django's LazySettings proxy class.\n\n\n\nImproved Documentation\n----------------------\n\n- `#4255 `_: Added missing documentation about the fact that module names passed to filter warnings are not regex-escaped.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#4272 `_: Display cachedir also in non-verbose mode if non-default.\n\n\n- `#4277 `_: pdb: improve message about output capturing with ``set_trace``.\n\n Do not display \"IO-capturing turned off/on\" when ``-s`` is used to avoid\n confusion.\n\n\n- `#4279 `_: Improve message and stack level of warnings issued by ``monkeypatch.setenv`` when the value of the environment variable is not a ``str``.\n\n\npytest 3.9.3 (2018-10-27)\n=========================\n\nBug Fixes\n---------\n\n- `#4174 `_: Fix \"ValueError: Plugin already registered\" with conftest plugins via symlink.\n\n\n- `#4181 `_: Handle race condition between creation and deletion of temporary folders.\n\n\n- `#4221 `_: Fix bug where the warning summary at the end of the test session was not showing the test where the warning was originated.\n\n\n- `#4243 `_: Fix regression when ``stacklevel`` for warnings was passed as positional argument on python2.\n\n\n\nImproved Documentation\n----------------------\n\n- `#3851 `_: Add reference to ``empty_parameter_set_mark`` ini option in documentation of ``@pytest.mark.parametrize``\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#4028 `_: Revert patching of ``sys.breakpointhook`` since it appears to do nothing.\n\n\n- `#4233 `_: Apply an import sorter (``reorder-python-imports``) to the codebase.\n\n\n- `#4248 `_: Remove use of unnecessary compat shim, six.binary_type\n\n\npytest 3.9.2 (2018-10-22)\n=========================\n\nBug Fixes\n---------\n\n- `#2909 `_: Improve error message when a recursive dependency between fixtures is detected.\n\n\n- `#3340 `_: Fix logging messages not shown in hooks ``pytest_sessionstart()`` and ``pytest_sessionfinish()``.\n\n\n- `#3533 `_: Fix unescaped XML raw objects in JUnit report for skipped tests\n\n\n- `#3691 `_: Python 2: safely format warning message about passing unicode strings to ``warnings.warn``, which may cause\n surprising ``MemoryError`` exception when monkey patching ``warnings.warn`` itself.\n\n\n- `#4026 `_: Improve error message when it is not possible to determine a function's signature.\n\n\n- `#4177 `_: Pin ``setuptools>=40.0`` to support ``py_modules`` in ``setup.cfg``\n\n\n- `#4179 `_: Restore the tmpdir behaviour of symlinking the current test run.\n\n\n- `#4192 `_: Fix filename reported by ``warnings.warn`` when using ``recwarn`` under python2.\n\n\npytest 3.9.1 (2018-10-16)\n=========================\n\nFeatures\n--------\n\n- `#4159 `_: For test-suites containing test classes, the information about the subclassed\n module is now output only if a higher verbosity level is specified (at least\n \"-vv\").\n\n\npytest 3.9.0 (2018-10-15 - not published due to a release automation bug)\n=========================================================================\n\nDeprecations\n------------\n\n- `#3616 `_: The following accesses have been documented as deprecated for years, but are now actually emitting deprecation warnings.\n\n * Access of ``Module``, ``Function``, ``Class``, ``Instance``, ``File`` and ``Item`` through ``Node`` instances. Now\n users will this warning::\n\n usage of Function.Module is deprecated, please use pytest.Module instead\n\n Users should just ``import pytest`` and access those objects using the ``pytest`` module.\n\n * ``request.cached_setup``, this was the precursor of the setup/teardown mechanism available to fixtures. You can\n consult `funcarg comparison section in the docs `_.\n\n * Using objects named ``\"Class\"`` as a way to customize the type of nodes that are collected in ``Collector``\n subclasses has been deprecated. Users instead should use ``pytest_collect_make_item`` to customize node types during\n collection.\n\n This issue should affect only advanced plugins who create new collection types, so if you see this warning\n message please contact the authors so they can change the code.\n\n * The warning that produces the message below has changed to ``RemovedInPytest4Warning``::\n\n getfuncargvalue is deprecated, use getfixturevalue\n\n\n- `#3988 `_: Add a Deprecation warning for pytest.ensuretemp as it was deprecated since a while.\n\n\n\nFeatures\n--------\n\n- `#2293 `_: Improve usage errors messages by hiding internal details which can be distracting and noisy.\n\n This has the side effect that some error conditions that previously raised generic errors (such as\n ``ValueError`` for unregistered marks) are now raising ``Failed`` exceptions.\n\n\n- `#3332 `_: Improve the error displayed when a ``conftest.py`` file could not be imported.\n\n In order to implement this, a new ``chain`` parameter was added to ``ExceptionInfo.getrepr``\n to show or hide chained tracebacks in Python 3 (defaults to ``True``).\n\n\n- `#3849 `_: Add ``empty_parameter_set_mark=fail_at_collect`` ini option for raising an exception when parametrize collects an empty set.\n\n\n- `#3964 `_: Log messages generated in the collection phase are shown when\n live-logging is enabled and/or when they are logged to a file.\n\n\n- `#3985 `_: Introduce ``tmp_path`` as a fixture providing a Path object.\n\n\n- `#4013 `_: Deprecation warnings are now shown even if you customize the warnings filters yourself. In the previous version\n any customization would override pytest's filters and deprecation warnings would fall back to being hidden by default.\n\n\n- `#4073 `_: Allow specification of timeout for ``Testdir.runpytest_subprocess()`` and ``Testdir.run()``.\n\n\n- `#4098 `_: Add returncode argument to pytest.exit() to exit pytest with a specific return code.\n\n\n- `#4102 `_: Reimplement ``pytest.deprecated_call`` using ``pytest.warns`` so it supports the ``match='...'`` keyword argument.\n\n This has the side effect that ``pytest.deprecated_call`` now raises ``pytest.fail.Exception`` instead\n of ``AssertionError``.\n\n\n- `#4149 `_: Require setuptools>=30.3 and move most of the metadata to ``setup.cfg``.\n\n\n\nBug Fixes\n---------\n\n- `#2535 `_: Improve error message when test functions of ``unittest.TestCase`` subclasses use a parametrized fixture.\n\n\n- `#3057 `_: ``request.fixturenames`` now correctly returns the name of fixtures created by ``request.getfixturevalue()``.\n\n\n- `#3946 `_: Warning filters passed as command line options using ``-W`` now take precedence over filters defined in ``ini``\n configuration files.\n\n\n- `#4066 `_: Fix source reindenting by using ``textwrap.dedent`` directly.\n\n\n- `#4102 `_: ``pytest.warn`` will capture previously-warned warnings in Python 2. Previously they were never raised.\n\n\n- `#4108 `_: Resolve symbolic links for args.\n\n This fixes running ``pytest tests/test_foo.py::test_bar``, where ``tests``\n is a symlink to ``project/app/tests``:\n previously ``project/app/conftest.py`` would be ignored for fixtures then.\n\n\n- `#4132 `_: Fix duplicate printing of internal errors when using ``--pdb``.\n\n\n- `#4135 `_: pathlib based tmpdir cleanup now correctly handles symlinks in the folder.\n\n\n- `#4152 `_: Display the filename when encountering ``SyntaxWarning``.\n\n\n\nImproved Documentation\n----------------------\n\n- `#3713 `_: Update usefixtures documentation to clarify that it can't be used with fixture functions.\n\n\n- `#4058 `_: Update fixture documentation to specify that a fixture can be invoked twice in the scope it's defined for.\n\n\n- `#4064 `_: According to unittest.rst, setUpModule and tearDownModule were not implemented, but it turns out they are. So updated the documentation for unittest.\n\n\n- `#4151 `_: Add tempir testing example to CONTRIBUTING.rst guide\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#2293 `_: The internal ``MarkerError`` exception has been removed.\n\n\n- `#3988 `_: Port the implementation of tmpdir to pathlib.\n\n\n- `#4063 `_: Exclude 0.00 second entries from ``--duration`` output unless ``-vv`` is passed on the command-line.\n\n\n- `#4093 `_: Fixed formatting of string literals in internal tests.\n\n\npytest 3.8.2 (2018-10-02)\n=========================\n\nDeprecations and Removals\n-------------------------\n\n- `#4036 `_: The ``item`` parameter of ``pytest_warning_captured`` hook is now documented as deprecated. We realized only after\n the ``3.8`` release that this parameter is incompatible with ``pytest-xdist``.\n\n Our policy is to not deprecate features during bugfix releases, but in this case we believe it makes sense as we are\n only documenting it as deprecated, without issuing warnings which might potentially break test suites. This will get\n the word out that hook implementers should not use this parameter at all.\n\n In a future release ``item`` will always be ``None`` and will emit a proper warning when a hook implementation\n makes use of it.\n\n\n\nBug Fixes\n---------\n\n- `#3539 `_: Fix reload on assertion rewritten modules.\n\n\n- `#4034 `_: The ``.user_properties`` attribute of ``TestReport`` objects is a list\n of (name, value) tuples, but could sometimes be instantiated as a tuple\n of tuples. It is now always a list.\n\n\n- `#4039 `_: No longer issue warnings about using ``pytest_plugins`` in non-top-level directories when using ``--pyargs``: the\n current ``--pyargs`` mechanism is not reliable and might give false negatives.\n\n\n- `#4040 `_: Exclude empty reports for passed tests when ``-rP`` option is used.\n\n\n- `#4051 `_: Improve error message when an invalid Python expression is passed to the ``-m`` option.\n\n\n- `#4056 `_: ``MonkeyPatch.setenv`` and ``MonkeyPatch.delenv`` issue a warning if the environment variable name is not ``str`` on Python 2.\n\n In Python 2, adding ``unicode`` keys to ``os.environ`` causes problems with ``subprocess`` (and possible other modules),\n making this a subtle bug specially susceptible when used with ``from __future__ import unicode_literals``.\n\n\n\nImproved Documentation\n----------------------\n\n- `#3928 `_: Add possible values for fixture scope to docs.\n\n\npytest 3.8.1 (2018-09-22)\n=========================\n\nBug Fixes\n---------\n\n- `#3286 `_: ``.pytest_cache`` directory is now automatically ignored by Git. Users who would like to contribute a solution for other SCMs please consult/comment on this issue.\n\n\n- `#3749 `_: Fix the following error during collection of tests inside packages::\n\n TypeError: object of type 'Package' has no len()\n\n\n- `#3941 `_: Fix bug where indirect parametrization would consider the scope of all fixtures used by the test function to determine the parametrization scope, and not only the scope of the fixtures being parametrized.\n\n\n- `#3973 `_: Fix crash of the assertion rewriter if a test changed the current working directory without restoring it afterwards.\n\n\n- `#3998 `_: Fix issue that prevented some caplog properties (for example ``record_tuples``) from being available when entering the debugger with ``--pdb``.\n\n\n- `#3999 `_: Fix ``UnicodeDecodeError`` in python2.x when a class returns a non-ascii binary ``__repr__`` in an assertion which also contains non-ascii text.\n\n\n\nImproved Documentation\n----------------------\n\n- `#3996 `_: New `Deprecations and Removals `_ page shows all currently\n deprecated features, the rationale to do so, and alternatives to update your code. It also list features removed\n from pytest in past major releases to help those with ancient pytest versions to upgrade.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#3955 `_: Improve pre-commit detection for changelog filenames\n\n\n- `#3975 `_: Remove legacy code around im_func as that was python2 only\n\n\npytest 3.8.0 (2018-09-05)\n=========================\n\nDeprecations and Removals\n-------------------------\n\n- `#2452 `_: ``Config.warn`` and ``Node.warn`` have been\n deprecated, see ``_ for rationale and\n examples.\n\n- `#3936 `_: ``@pytest.mark.filterwarnings`` second parameter is no longer regex-escaped,\n making it possible to actually use regular expressions to check the warning message.\n\n **Note**: regex-escaping the match string was an implementation oversight that might break test suites which depend\n on the old behavior.\n\n\n\nFeatures\n--------\n\n- `#2452 `_: Internal pytest warnings are now issued using the standard ``warnings`` module, making it possible to use\n the standard warnings filters to manage those warnings. This introduces ``PytestWarning``,\n ``PytestDeprecationWarning`` and ``RemovedInPytest4Warning`` warning types as part of the public API.\n\n Consult `the documentation `__ for more info.\n\n\n- `#2908 `_: ``DeprecationWarning`` and ``PendingDeprecationWarning`` are now shown by default if no other warning filter is\n configured. This makes pytest more compliant with\n `PEP-0506 `_. See\n `the docs `_ for\n more info.\n\n\n- `#3251 `_: Warnings are now captured and displayed during test collection.\n\n\n- `#3784 `_: ``PYTEST_DISABLE_PLUGIN_AUTOLOAD`` environment variable disables plugin auto-loading when set.\n\n\n- `#3829 `_: Added the ``count`` option to ``console_output_style`` to enable displaying the progress as a count instead of a percentage.\n\n\n- `#3837 `_: Added support for 'xfailed' and 'xpassed' outcomes to the ``pytester.RunResult.assert_outcomes`` signature.\n\n\n\nBug Fixes\n---------\n\n- `#3911 `_: Terminal writer now takes into account unicode character width when writing out progress.\n\n\n- `#3913 `_: Pytest now returns with correct exit code (EXIT_USAGEERROR, 4) when called with unknown arguments.\n\n\n- `#3918 `_: Improve performance of assertion rewriting.\n\n\n\nImproved Documentation\n----------------------\n\n- `#3566 `_: Added a blurb in usage.rst for the usage of -r flag which is used to show an extra test summary info.\n\n\n- `#3907 `_: Corrected type of the exceptions collection passed to ``xfail``: ``raises`` argument accepts a ``tuple`` instead of ``list``.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#3853 `_: Removed ``\"run all (no recorded failures)\"`` message printed with ``--failed-first`` and ``--last-failed`` when there are no failed tests.\n\n\npytest 3.7.4 (2018-08-29)\n=========================\n\nBug Fixes\n---------\n\n- `#3506 `_: Fix possible infinite recursion when writing ``.pyc`` files.\n\n\n- `#3853 `_: Cache plugin now obeys the ``-q`` flag when ``--last-failed`` and ``--failed-first`` flags are used.\n\n\n- `#3883 `_: Fix bad console output when using ``console_output_style=classic``.\n\n\n- `#3888 `_: Fix macOS specific code using ``capturemanager`` plugin in doctests.\n\n\n\nImproved Documentation\n----------------------\n\n- `#3902 `_: Fix pytest.org links\n\n\npytest 3.7.3 (2018-08-26)\n=========================\n\nBug Fixes\n---------\n\n- `#3033 `_: Fixtures during teardown can again use ``capsys`` and ``capfd`` to inspect output captured during tests.\n\n\n- `#3773 `_: Fix collection of tests from ``__init__.py`` files if they match the ``python_files`` configuration option.\n\n\n- `#3796 `_: Fix issue where teardown of fixtures of consecutive sub-packages were executed once, at the end of the outer\n package.\n\n\n- `#3816 `_: Fix bug where ``--show-capture=no`` option would still show logs printed during fixture teardown.\n\n\n- `#3819 `_: Fix ``stdout/stderr`` not getting captured when real-time cli logging is active.\n\n\n- `#3843 `_: Fix collection error when specifying test functions directly in the command line using ``test.py::test`` syntax together with ``--doctest-modules``.\n\n\n- `#3848 `_: Fix bugs where unicode arguments could not be passed to ``testdir.runpytest`` on Python 2.\n\n\n- `#3854 `_: Fix double collection of tests within packages when the filename starts with a capital letter.\n\n\n\nImproved Documentation\n----------------------\n\n- `#3824 `_: Added example for multiple glob pattern matches in ``python_files``.\n\n\n- `#3833 `_: Added missing docs for ``pytester.Testdir``.\n\n\n- `#3870 `_: Correct documentation for setuptools integration.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#3826 `_: Replace broken type annotations with type comments.\n\n\n- `#3845 `_: Remove a reference to issue `#568 `_ from the documentation, which has since been\n fixed.\n\n\npytest 3.7.2 (2018-08-16)\n=========================\n\nBug Fixes\n---------\n\n- `#3671 `_: Fix ``filterwarnings`` not being registered as a builtin mark.\n\n\n- `#3768 `_, `#3789 `_: Fix test collection from packages mixed with normal directories.\n\n\n- `#3771 `_: Fix infinite recursion during collection if a ``pytest_ignore_collect`` hook returns ``False`` instead of ``None``.\n\n\n- `#3774 `_: Fix bug where decorated fixtures would lose functionality (for example ``@mock.patch``).\n\n\n- `#3775 `_: Fix bug where importing modules or other objects with prefix ``pytest_`` prefix would raise a ``PluginValidationError``.\n\n\n- `#3788 `_: Fix ``AttributeError`` during teardown of ``TestCase`` subclasses which raise an exception during ``__init__``.\n\n\n- `#3804 `_: Fix traceback reporting for exceptions with ``__cause__`` cycles.\n\n\n\nImproved Documentation\n----------------------\n\n- `#3746 `_: Add documentation for ``metafunc.config`` that had been mistakenly hidden.\n\n\npytest 3.7.1 (2018-08-02)\n=========================\n\nBug Fixes\n---------\n\n- `#3473 `_: Raise immediately if ``approx()`` is given an expected value of a type it doesn't understand (e.g. strings, nested dicts, etc.).\n\n\n- `#3712 `_: Correctly represent the dimensions of a numpy array when calling ``repr()`` on ``approx()``.\n\n- `#3742 `_: Fix incompatibility with third party plugins during collection, which produced the error ``object has no attribute '_collectfile'``.\n\n- `#3745 `_: Display the absolute path if ``cache_dir`` is not relative to the ``rootdir`` instead of failing.\n\n\n- `#3747 `_: Fix compatibility problem with plugins and the warning code issued by fixture functions when they are called directly.\n\n\n- `#3748 `_: Fix infinite recursion in ``pytest.approx`` with arrays in ``numpy<1.13``.\n\n\n- `#3757 `_: Pin pathlib2 to ``>=2.2.0`` as we require ``__fspath__`` support.\n\n\n- `#3763 `_: Fix ``TypeError`` when the assertion message is ``bytes`` in python 3.\n\n\npytest 3.7.0 (2018-07-30)\n=========================\n\nDeprecations and Removals\n-------------------------\n\n- `#2639 `_: ``pytest_namespace`` has been `deprecated `_.\n\n\n- `#3661 `_: Calling a fixture function directly, as opposed to request them in a test function, now issues a ``RemovedInPytest4Warning``. See `the documentation for rationale and examples `_.\n\n\n\nFeatures\n--------\n\n- `#2283 `_: New ``package`` fixture scope: fixtures are finalized when the last test of a *package* finishes. This feature is considered **experimental**, so use it sparingly.\n\n\n- `#3576 `_: ``Node.add_marker`` now supports an ``append=True/False`` parameter to determine whether the mark comes last (default) or first.\n\n\n- `#3579 `_: Fixture ``caplog`` now has a ``messages`` property, providing convenient access to the format-interpolated log messages without the extra data provided by the formatter/handler.\n\n\n- `#3610 `_: New ``--trace`` option to enter the debugger at the start of a test.\n\n\n- `#3623 `_: Introduce ``pytester.copy_example`` as helper to do acceptance tests against examples from the project.\n\n\n\nBug Fixes\n---------\n\n- `#2220 `_: Fix a bug where fixtures overridden by direct parameters (for example parametrization) were being instantiated even if they were not being used by a test.\n\n\n- `#3695 `_: Fix ``ApproxNumpy`` initialisation argument mixup, ``abs`` and ``rel`` tolerances were flipped causing strange comparison results.\n Add tests to check ``abs`` and ``rel`` tolerances for ``np.array`` and test for expecting ``nan`` with ``np.array()``\n\n\n- `#980 `_: Fix truncated locals output in verbose mode.\n\n\n\nImproved Documentation\n----------------------\n\n- `#3295 `_: Correct the usage documentation of ``--last-failed-no-failures`` by adding the missing ``--last-failed`` argument in the presented examples, because they are misleading and lead to think that the missing argument is not needed.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#3519 `_: Now a ``README.md`` file is created in ``.pytest_cache`` to make it clear why the directory exists.\n\n\npytest 3.6.4 (2018-07-28)\n=========================\n\nBug Fixes\n---------\n\n- Invoke pytest using ``-mpytest`` so ``sys.path`` does not get polluted by packages installed in ``site-packages``. (`#742 `_)\n\n\nImproved Documentation\n----------------------\n\n- Use ``smtp_connection`` instead of ``smtp`` in fixtures documentation to avoid possible confusion. (`#3592 `_)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Remove obsolete ``__future__`` imports. (`#2319 `_)\n\n- Add CITATION to provide information on how to formally cite pytest. (`#3402 `_)\n\n- Replace broken type annotations with type comments. (`#3635 `_)\n\n- Pin ``pluggy`` to ``<0.8``. (`#3727 `_)\n\n\npytest 3.6.3 (2018-07-04)\n=========================\n\nBug Fixes\n---------\n\n- Fix ``ImportWarning`` triggered by explicit relative imports in\n assertion-rewritten package modules. (`#3061\n `_)\n\n- Fix error in ``pytest.approx`` when dealing with 0-dimension numpy\n arrays. (`#3593 `_)\n\n- No longer raise ``ValueError`` when using the ``get_marker`` API. (`#3605\n `_)\n\n- Fix problem where log messages with non-ascii characters would not\n appear in the output log file.\n (`#3630 `_)\n\n- No longer raise ``AttributeError`` when legacy marks can't be stored in\n functions. (`#3631 `_)\n\n\nImproved Documentation\n----------------------\n\n- The description above the example for ``@pytest.mark.skipif`` now better\n matches the code. (`#3611\n `_)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Internal refactoring: removed unused ``CallSpec2tox ._globalid_args``\n attribute and ``metafunc`` parameter from ``CallSpec2.copy()``. (`#3598\n `_)\n\n- Silence usage of ``reduce`` warning in Python 2 (`#3609\n `_)\n\n- Fix usage of ``attr.ib`` deprecated ``convert`` parameter. (`#3653\n `_)\n\n\npytest 3.6.2 (2018-06-20)\n=========================\n\nBug Fixes\n---------\n\n- Fix regression in ``Node.add_marker`` by extracting the mark object of a\n ``MarkDecorator``. (`#3555\n `_)\n\n- Warnings without ``location`` were reported as ``None``. This is corrected to\n now report ````. (`#3563\n `_)\n\n- Continue to call finalizers in the stack when a finalizer in a former scope\n raises an exception. (`#3569\n `_)\n\n- Fix encoding error with ``print`` statements in doctests (`#3583\n `_)\n\n\nImproved Documentation\n----------------------\n\n- Add documentation for the ``--strict`` flag. (`#3549\n `_)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Update old quotation style to parens in fixture.rst documentation. (`#3525\n `_)\n\n- Improve display of hint about ``--fulltrace`` with ``KeyboardInterrupt``.\n (`#3545 `_)\n\n- pytest's testsuite is no longer runnable through ``python setup.py test`` --\n instead invoke ``pytest`` or ``tox`` directly. (`#3552\n `_)\n\n- Fix typo in documentation (`#3567\n `_)\n\n\npytest 3.6.1 (2018-06-05)\n=========================\n\nBug Fixes\n---------\n\n- Fixed a bug where stdout and stderr were logged twice by junitxml when a test\n was marked xfail. (`#3491\n `_)\n\n- Fix ``usefixtures`` mark applyed to unittest tests by correctly instantiating\n ``FixtureInfo``. (`#3498\n `_)\n\n- Fix assertion rewriter compatibility with libraries that monkey patch\n ``file`` objects. (`#3503\n `_)\n\n\nImproved Documentation\n----------------------\n\n- Added a section on how to use fixtures as factories to the fixture\n documentation. (`#3461 `_)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Enable caching for pip/pre-commit in order to reduce build time on\n travis/appveyor. (`#3502\n `_)\n\n- Switch pytest to the src/ layout as we already suggested it for good practice\n - now we implement it as well. (`#3513\n `_)\n\n- Fix if in tests to support 3.7.0b5, where a docstring handling in AST got\n reverted. (`#3530 `_)\n\n- Remove some python2.5 compatibility code. (`#3529\n `_)\n\n\npytest 3.6.0 (2018-05-23)\n=========================\n\nFeatures\n--------\n\n- Revamp the internals of the ``pytest.mark`` implementation with correct per\n node handling which fixes a number of long standing bugs caused by the old\n design. This introduces new ``Node.iter_markers(name)`` and\n ``Node.get_closest_marker(name)`` APIs. Users are **strongly encouraged** to\n read the `reasons for the revamp in the docs\n `_,\n or jump over to details about `updating existing code to use the new APIs\n `_. (`#3317\n `_)\n\n- Now when ``@pytest.fixture`` is applied more than once to the same function a\n ``ValueError`` is raised. This buggy behavior would cause surprising problems\n and if was working for a test suite it was mostly by accident. (`#2334\n `_)\n\n- Support for Python 3.7's builtin ``breakpoint()`` method, see `Using the\n builtin breakpoint function\n `_ for\n details. (`#3180 `_)\n\n- ``monkeypatch`` now supports a ``context()`` function which acts as a context\n manager which undoes all patching done within the ``with`` block. (`#3290\n `_)\n\n- The ``--pdb`` option now causes KeyboardInterrupt to enter the debugger,\n instead of stopping the test session. On python 2.7, hitting CTRL+C again\n exits the debugger. On python 3.2 and higher, use CTRL+D. (`#3299\n `_)\n\n- pytest no longer changes the log level of the root logger when the\n ``log-level`` parameter has greater numeric value than that of the level of\n the root logger, which makes it play better with custom logging configuration\n in user code. (`#3307 `_)\n\n\nBug Fixes\n---------\n\n- A rare race-condition which might result in corrupted ``.pyc`` files on\n Windows has been hopefully solved. (`#3008\n `_)\n\n- Also use iter_marker for discovering the marks applying for marker\n expressions from the cli to avoid the bad data from the legacy mark storage.\n (`#3441 `_)\n\n- When showing diffs of failed assertions where the contents contain only\n whitespace, escape them using ``repr()`` first to make it easy to spot the\n differences. (`#3443 `_)\n\n\nImproved Documentation\n----------------------\n\n- Change documentation copyright year to a range which auto-updates itself each\n time it is published. (`#3303\n `_)\n\n\nTrivial/Internal Changes\n------------------------\n\n- ``pytest`` now depends on the `python-atomicwrites\n `_ library. (`#3008\n `_)\n\n- Update all pypi.python.org URLs to pypi.org. (`#3431\n `_)\n\n- Detect `pytest_` prefixed hooks using the internal plugin manager since\n ``pluggy`` is deprecating the ``implprefix`` argument to ``PluginManager``.\n (`#3487 `_)\n\n- Import ``Mapping`` and ``Sequence`` from ``_pytest.compat`` instead of\n directly from ``collections`` in ``python_api.py::approx``. Add ``Mapping``\n to ``_pytest.compat``, import it from ``collections`` on python 2, but from\n ``collections.abc`` on Python 3 to avoid a ``DeprecationWarning`` on Python\n 3.7 or newer. (`#3497 `_)\n\n\npytest 3.5.1 (2018-04-23)\n=========================\n\n\nBug Fixes\n---------\n\n- Reset ``sys.last_type``, ``sys.last_value`` and ``sys.last_traceback`` before\n each test executes. Those attributes are added by pytest during the test run\n to aid debugging, but were never reset so they would create a leaking\n reference to the last failing test's frame which in turn could never be\n reclaimed by the garbage collector. (`#2798\n `_)\n\n- ``pytest.raises`` now raises ``TypeError`` when receiving an unknown keyword\n argument. (`#3348 `_)\n\n- ``pytest.raises`` now works with exception classes that look like iterables.\n (`#3372 `_)\n\n\nImproved Documentation\n----------------------\n\n- Fix typo in ``caplog`` fixture documentation, which incorrectly identified\n certain attributes as methods. (`#3406\n `_)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Added a more indicative error message when parametrizing a function whose\n argument takes a default value. (`#3221\n `_)\n\n- Remove internal ``_pytest.terminal.flatten`` function in favor of\n ``more_itertools.collapse``. (`#3330\n `_)\n\n- Import some modules from ``collections.abc`` instead of ``collections`` as\n the former modules trigger ``DeprecationWarning`` in Python 3.7. (`#3339\n `_)\n\n- record_property is no longer experimental, removing the warnings was\n forgotten. (`#3360 `_)\n\n- Mention in documentation and CLI help that fixtures with leading ``_`` are\n printed by ``pytest --fixtures`` only if the ``-v`` option is added. (`#3398\n `_)\n\n\npytest 3.5.0 (2018-03-21)\n=========================\n\nDeprecations and Removals\n-------------------------\n\n- ``record_xml_property`` fixture is now deprecated in favor of the more\n generic ``record_property``. (`#2770\n `_)\n\n- Defining ``pytest_plugins`` is now deprecated in non-top-level conftest.py\n files, because they \"leak\" to the entire directory tree. `See the docs `_ for the rationale behind this decision (`#3084\n `_)\n\n\nFeatures\n--------\n\n- New ``--show-capture`` command-line option that allows to specify how to\n display captured output when tests fail: ``no``, ``stdout``, ``stderr``,\n ``log`` or ``all`` (the default). (`#1478\n `_)\n\n- New ``--rootdir`` command-line option to override the rules for discovering\n the root directory. See `customize\n `_ in the documentation for\n details. (`#1642 `_)\n\n- Fixtures are now instantiated based on their scopes, with higher-scoped\n fixtures (such as ``session``) being instantiated first than lower-scoped\n fixtures (such as ``function``). The relative order of fixtures of the same\n scope is kept unchanged, based in their declaration order and their\n dependencies. (`#2405 `_)\n\n- ``record_xml_property`` renamed to ``record_property`` and is now compatible\n with xdist, markers and any reporter. ``record_xml_property`` name is now\n deprecated. (`#2770 `_)\n\n- New ``--nf``, ``--new-first`` options: run new tests first followed by the\n rest of the tests, in both cases tests are also sorted by the file modified\n time, with more recent files coming first. (`#3034\n `_)\n\n- New ``--last-failed-no-failures`` command-line option that allows to specify\n the behavior of the cache plugin's ```--last-failed`` feature when no tests\n failed in the last run (or no cache was found): ``none`` or ``all`` (the\n default). (`#3139 `_)\n\n- New ``--doctest-continue-on-failure`` command-line option to enable doctests\n to show multiple failures for each snippet, instead of stopping at the first\n failure. (`#3149 `_)\n\n- Captured log messages are added to the ```` tag in the generated\n junit xml file if the ``junit_logging`` ini option is set to ``system-out``.\n If the value of this ini option is ``system-err``, the logs are written to\n ````. The default value for ``junit_logging`` is ``no``, meaning\n captured logs are not written to the output file. (`#3156\n `_)\n\n- Allow the logging plugin to handle ``pytest_runtest_logstart`` and\n ``pytest_runtest_logfinish`` hooks when live logs are enabled. (`#3189\n `_)\n\n- Passing ``--log-cli-level`` in the command-line now automatically activates\n live logging. (`#3190 `_)\n\n- Add command line option ``--deselect`` to allow deselection of individual\n tests at collection time. (`#3198\n `_)\n\n- Captured logs are printed before entering pdb. (`#3204\n `_)\n\n- Deselected item count is now shown before tests are run, e.g. ``collected X\n items / Y deselected``. (`#3213\n `_)\n\n- The builtin module ``platform`` is now available for use in expressions in\n ``pytest.mark``. (`#3236\n `_)\n\n- The *short test summary info* section now is displayed after tracebacks and\n warnings in the terminal. (`#3255\n `_)\n\n- New ``--verbosity`` flag to set verbosity level explicitly. (`#3296\n `_)\n\n- ``pytest.approx`` now accepts comparing a numpy array with a scalar. (`#3312\n `_)\n\n\nBug Fixes\n---------\n\n- Suppress ``IOError`` when closing the temporary file used for capturing\n streams in Python 2.7. (`#2370\n `_)\n\n- Fixed ``clear()`` method on ``caplog`` fixture which cleared ``records``, but\n not the ``text`` property. (`#3297\n `_)\n\n- During test collection, when stdin is not allowed to be read, the\n ``DontReadFromStdin`` object still allow itself to be iterable and resolved\n to an iterator without crashing. (`#3314\n `_)\n\n\nImproved Documentation\n----------------------\n\n- Added a `reference `_ page\n to the docs. (`#1713 `_)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Change minimum requirement of ``attrs`` to ``17.4.0``. (`#3228\n `_)\n\n- Renamed example directories so all tests pass when ran from the base\n directory. (`#3245 `_)\n\n- Internal ``mark.py`` module has been turned into a package. (`#3250\n `_)\n\n- ``pytest`` now depends on the `more-itertools\n `_ package. (`#3265\n `_)\n\n- Added warning when ``[pytest]`` section is used in a ``.cfg`` file passed\n with ``-c`` (`#3268 `_)\n\n- ``nodeids`` can now be passed explicitly to ``FSCollector`` and ``Node``\n constructors. (`#3291 `_)\n\n- Internal refactoring of ``FormattedExcinfo`` to use ``attrs`` facilities and\n remove old support code for legacy Python versions. (`#3292\n `_)\n\n- Refactoring to unify how verbosity is handled internally. (`#3296\n `_)\n\n- Internal refactoring to better integrate with argparse. (`#3304\n `_)\n\n- Fix a python example when calling a fixture in doc/en/usage.rst (`#3308\n `_)\n\n\npytest 3.4.2 (2018-03-04)\n=========================\n\nBug Fixes\n---------\n\n- Removed progress information when capture option is ``no``. (`#3203\n `_)\n\n- Refactor check of bindir from ``exists`` to ``isdir``. (`#3241\n `_)\n\n- Fix ``TypeError`` issue when using ``approx`` with a ``Decimal`` value.\n (`#3247 `_)\n\n- Fix reference cycle generated when using the ``request`` fixture. (`#3249\n `_)\n\n- ``[tool:pytest]`` sections in ``*.cfg`` files passed by the ``-c`` option are\n now properly recognized. (`#3260\n `_)\n\n\nImproved Documentation\n----------------------\n\n- Add logging plugin to plugins list. (`#3209\n `_)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Fix minor typo in fixture.rst (`#3259\n `_)\n\n\npytest 3.4.1 (2018-02-20)\n=========================\n\nBug Fixes\n---------\n\n- Move import of ``doctest.UnexpectedException`` to top-level to avoid possible\n errors when using ``--pdb``. (`#1810\n `_)\n\n- Added printing of captured stdout/stderr before entering pdb, and improved a\n test which was giving false negatives about output capturing. (`#3052\n `_)\n\n- Fix ordering of tests using parametrized fixtures which can lead to fixtures\n being created more than necessary. (`#3161\n `_)\n\n- Fix bug where logging happening at hooks outside of \"test run\" hooks would\n cause an internal error. (`#3184\n `_)\n\n- Detect arguments injected by ``unittest.mock.patch`` decorator correctly when\n pypi ``mock.patch`` is installed and imported. (`#3206\n `_)\n\n- Errors shown when a ``pytest.raises()`` with ``match=`` fails are now cleaner\n on what happened: When no exception was raised, the \"matching '...'\" part got\n removed as it falsely implies that an exception was raised but it didn't\n match. When a wrong exception was raised, it's now thrown (like\n ``pytest.raised()`` without ``match=`` would) instead of complaining about\n the unmatched text. (`#3222\n `_)\n\n- Fixed output capture handling in doctests on macOS. (`#985\n `_)\n\n\nImproved Documentation\n----------------------\n\n- Add Sphinx parameter docs for ``match`` and ``message`` args to\n ``pytest.raises``. (`#3202\n `_)\n\n\nTrivial/Internal Changes\n------------------------\n\n- pytest has changed the publication procedure and is now being published to\n PyPI directly from Travis. (`#3060\n `_)\n\n- Rename ``ParameterSet._for_parameterize()`` to ``_for_parametrize()`` in\n order to comply with the naming convention. (`#3166\n `_)\n\n- Skip failing pdb/doctest test on mac. (`#985\n `_)\n\n\npytest 3.4.0 (2018-01-30)\n=========================\n\nDeprecations and Removals\n-------------------------\n\n- All pytest classes now subclass ``object`` for better Python 2/3 compatibility.\n This should not affect user code except in very rare edge cases. (`#2147\n `_)\n\n\nFeatures\n--------\n\n- Introduce ``empty_parameter_set_mark`` ini option to select which mark to\n apply when ``@pytest.mark.parametrize`` is given an empty set of parameters.\n Valid options are ``skip`` (default) and ``xfail``. Note that it is planned\n to change the default to ``xfail`` in future releases as this is considered\n less error prone. (`#2527\n `_)\n\n- **Incompatible change**: after community feedback the `logging\n `_ functionality has\n undergone some changes. Please consult the `logging documentation\n `_\n for details. (`#3013 `_)\n\n- Console output falls back to \"classic\" mode when capturing is disabled (``-s``),\n otherwise the output gets garbled to the point of being useless. (`#3038\n `_)\n\n- New `pytest_runtest_logfinish\n `_\n hook which is called when a test item has finished executing, analogous to\n `pytest_runtest_logstart\n `_.\n (`#3101 `_)\n\n- Improve performance when collecting tests using many fixtures. (`#3107\n `_)\n\n- New ``caplog.get_records(when)`` method which provides access to the captured\n records for the ``\"setup\"``, ``\"call\"`` and ``\"teardown\"``\n testing stages. (`#3117 `_)\n\n- New fixture ``record_xml_attribute`` that allows modifying and inserting\n attributes on the ```` xml node in JUnit reports. (`#3130\n `_)\n\n- The default cache directory has been renamed from ``.cache`` to\n ``.pytest_cache`` after community feedback that the name ``.cache`` did not\n make it clear that it was used by pytest. (`#3138\n `_)\n\n- Colorize the levelname column in the live-log output. (`#3142\n `_)\n\n\nBug Fixes\n---------\n\n- Fix hanging pexpect test on MacOS by using flush() instead of wait().\n (`#2022 `_)\n\n- Fix restoring Python state after in-process pytest runs with the\n ``pytester`` plugin; this may break tests using multiple inprocess\n pytest runs if later ones depend on earlier ones leaking global interpreter\n changes. (`#3016 `_)\n\n- Fix skipping plugin reporting hook when test aborted before plugin setup\n hook. (`#3074 `_)\n\n- Fix progress percentage reported when tests fail during teardown. (`#3088\n `_)\n\n- **Incompatible change**: ``-o/--override`` option no longer eats all the\n remaining options, which can lead to surprising behavior: for example,\n ``pytest -o foo=1 /path/to/test.py`` would fail because ``/path/to/test.py``\n would be considered as part of the ``-o`` command-line argument. One\n consequence of this is that now multiple configuration overrides need\n multiple ``-o`` flags: ``pytest -o foo=1 -o bar=2``. (`#3103\n `_)\n\n\nImproved Documentation\n----------------------\n\n- Document hooks (defined with ``historic=True``) which cannot be used with\n ``hookwrapper=True``. (`#2423\n `_)\n\n- Clarify that warning capturing doesn't change the warning filter by default.\n (`#2457 `_)\n\n- Clarify a possible confusion when using pytest_fixture_setup with fixture\n functions that return None. (`#2698\n `_)\n\n- Fix the wording of a sentence on doctest flags used in pytest. (`#3076\n `_)\n\n- Prefer ``https://*.readthedocs.io`` over ``http://*.rtfd.org`` for links in\n the documentation. (`#3092\n `_)\n\n- Improve readability (wording, grammar) of Getting Started guide (`#3131\n `_)\n\n- Added note that calling pytest.main multiple times from the same process is\n not recommended because of import caching. (`#3143\n `_)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Show a simple and easy error when keyword expressions trigger a syntax error\n (for example, ``\"-k foo and import\"`` will show an error that you can not use\n the ``import`` keyword in expressions). (`#2953\n `_)\n\n- Change parametrized automatic test id generation to use the ``__name__``\n attribute of functions instead of the fallback argument name plus counter.\n (`#2976 `_)\n\n- Replace py.std with stdlib imports. (`#3067\n `_)\n\n- Corrected 'you' to 'your' in logging docs. (`#3129\n `_)\n\n\npytest 3.3.2 (2017-12-25)\n=========================\n\nBug Fixes\n---------\n\n- pytester: ignore files used to obtain current user metadata in the fd leak\n detector. (`#2784 `_)\n\n- Fix **memory leak** where objects returned by fixtures were never destructed\n by the garbage collector. (`#2981\n `_)\n\n- Fix conversion of pyargs to filename to not convert symlinks on Python 2. (`#2985\n `_)\n\n- ``PYTEST_DONT_REWRITE`` is now checked for plugins too rather than only for\n test modules. (`#2995 `_)\n\n\nImproved Documentation\n----------------------\n\n- Add clarifying note about behavior of multiple parametrized arguments (`#3001\n `_)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Code cleanup. (`#3015 `_,\n `#3021 `_)\n\n- Clean up code by replacing imports and references of ``_ast`` to ``ast``.\n (`#3018 `_)\n\n\npytest 3.3.1 (2017-12-05)\n=========================\n\nBug Fixes\n---------\n\n- Fix issue about ``-p no:`` having no effect. (`#2920\n `_)\n\n- Fix regression with warnings that contained non-strings in their arguments in\n Python 2. (`#2956 `_)\n\n- Always escape null bytes when setting ``PYTEST_CURRENT_TEST``. (`#2957\n `_)\n\n- Fix ``ZeroDivisionError`` when using the ``testmon`` plugin when no tests\n were actually collected. (`#2971\n `_)\n\n- Bring back ``TerminalReporter.writer`` as an alias to\n ``TerminalReporter._tw``. This alias was removed by accident in the ``3.3.0``\n release. (`#2984 `_)\n\n- The ``pytest-capturelog`` plugin is now also blacklisted, avoiding errors when\n running pytest with it still installed. (`#3004\n `_)\n\n\nImproved Documentation\n----------------------\n\n- Fix broken link to plugin ``pytest-localserver``. (`#2963\n `_)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Update github \"bugs\" link in ``CONTRIBUTING.rst`` (`#2949\n `_)\n\n\npytest 3.3.0 (2017-11-23)\n=========================\n\nDeprecations and Removals\n-------------------------\n\n- pytest no longer supports Python **2.6** and **3.3**. Those Python versions\n are EOL for some time now and incur maintenance and compatibility costs on\n the pytest core team, and following up with the rest of the community we\n decided that they will no longer be supported starting on this version. Users\n which still require those versions should pin pytest to ``<3.3``. (`#2812\n `_)\n\n- Remove internal ``_preloadplugins()`` function. This removal is part of the\n ``pytest_namespace()`` hook deprecation. (`#2636\n `_)\n\n- Internally change ``CallSpec2`` to have a list of marks instead of a broken\n mapping of keywords. This removes the keywords attribute of the internal\n ``CallSpec2`` class. (`#2672\n `_)\n\n- Remove ParameterSet.deprecated_arg_dict - its not a public api and the lack\n of the underscore was a naming error. (`#2675\n `_)\n\n- Remove the internal multi-typed attribute ``Node._evalskip`` and replace it\n with the boolean ``Node._skipped_by_mark``. (`#2767\n `_)\n\n- The ``params`` list passed to ``pytest.fixture`` is now for\n all effects considered immutable and frozen at the moment of the ``pytest.fixture``\n call. Previously the list could be changed before the first invocation of the fixture\n allowing for a form of dynamic parametrization (for example, updated from command-line options),\n but this was an unwanted implementation detail which complicated the internals and prevented\n some internal cleanup. See issue `#2959 `_\n for details and a recommended workaround.\n\nFeatures\n--------\n\n- ``pytest_fixture_post_finalizer`` hook can now receive a ``request``\n argument. (`#2124 `_)\n\n- Replace the old introspection code in compat.py that determines the available\n arguments of fixtures with inspect.signature on Python 3 and\n funcsigs.signature on Python 2. This should respect ``__signature__``\n declarations on functions. (`#2267\n `_)\n\n- Report tests with global ``pytestmark`` variable only once. (`#2549\n `_)\n\n- Now pytest displays the total progress percentage while running tests. The\n previous output style can be set by configuring the ``console_output_style``\n setting to ``classic``. (`#2657 `_)\n\n- Match ``warns`` signature to ``raises`` by adding ``match`` keyword. (`#2708\n `_)\n\n- pytest now captures and displays output from the standard ``logging`` module.\n The user can control the logging level to be captured by specifying options\n in ``pytest.ini``, the command line and also during individual tests using\n markers. Also, a ``caplog`` fixture is available that enables users to test\n the captured log during specific tests (similar to ``capsys`` for example).\n For more information, please see the `logging docs\n `_. This feature was\n introduced by merging the popular `pytest-catchlog\n `_ plugin, thanks to `Thomas Hisch\n `_. Be advised that during the merging the\n backward compatibility interface with the defunct ``pytest-capturelog`` has\n been dropped. (`#2794 `_)\n\n- Add ``allow_module_level`` kwarg to ``pytest.skip()``, enabling to skip the\n whole module. (`#2808 `_)\n\n- Allow setting ``file_or_dir``, ``-c``, and ``-o`` in PYTEST_ADDOPTS. (`#2824\n `_)\n\n- Return stdout/stderr capture results as a ``namedtuple``, so ``out`` and\n ``err`` can be accessed by attribute. (`#2879\n `_)\n\n- Add ``capfdbinary``, a version of ``capfd`` which returns bytes from\n ``readouterr()``. (`#2923\n `_)\n\n- Add ``capsysbinary`` a version of ``capsys`` which returns bytes from\n ``readouterr()``. (`#2934\n `_)\n\n- Implement feature to skip ``setup.py`` files when run with\n ``--doctest-modules``. (`#502\n `_)\n\n\nBug Fixes\n---------\n\n- Resume output capturing after ``capsys/capfd.disabled()`` context manager.\n (`#1993 `_)\n\n- ``pytest_fixture_setup`` and ``pytest_fixture_post_finalizer`` hooks are now\n called for all ``conftest.py`` files. (`#2124\n `_)\n\n- If an exception happens while loading a plugin, pytest no longer hides the\n original traceback. In Python 2 it will show the original traceback with a new\n message that explains in which plugin. In Python 3 it will show 2 canonized\n exceptions, the original exception while loading the plugin in addition to an\n exception that pytest throws about loading a plugin. (`#2491\n `_)\n\n- ``capsys`` and ``capfd`` can now be used by other fixtures. (`#2709\n `_)\n\n- Internal ``pytester`` plugin properly encodes ``bytes`` arguments to\n ``utf-8``. (`#2738 `_)\n\n- ``testdir`` now uses use the same method used by ``tmpdir`` to create its\n temporary directory. This changes the final structure of the ``testdir``\n directory slightly, but should not affect usage in normal scenarios and\n avoids a number of potential problems. (`#2751\n `_)\n\n- pytest no longer complains about warnings with unicode messages being\n non-ascii compatible even for ascii-compatible messages. As a result of this,\n warnings with unicode messages are converted first to an ascii representation\n for safety. (`#2809 `_)\n\n- Change return value of pytest command when ``--maxfail`` is reached from\n ``2`` (interrupted) to ``1`` (failed). (`#2845\n `_)\n\n- Fix issue in assertion rewriting which could lead it to rewrite modules which\n should not be rewritten. (`#2939\n `_)\n\n- Handle marks without description in ``pytest.ini``. (`#2942\n `_)\n\n\nTrivial/Internal Changes\n------------------------\n\n- pytest now depends on `attrs `__ for internal\n structures to ease code maintainability. (`#2641\n `_)\n\n- Refactored internal Python 2/3 compatibility code to use ``six``. (`#2642\n `_)\n\n- Stop vendoring ``pluggy`` - we're missing out on its latest changes for not\n much benefit (`#2719 `_)\n\n- Internal refactor: simplify ascii string escaping by using the\n backslashreplace error handler in newer Python 3 versions. (`#2734\n `_)\n\n- Remove unnecessary mark evaluator in unittest plugin (`#2767\n `_)\n\n- Calls to ``Metafunc.addcall`` now emit a deprecation warning. This function\n is scheduled to be removed in ``pytest-4.0``. (`#2876\n `_)\n\n- Internal move of the parameterset extraction to a more maintainable place.\n (`#2877 `_)\n\n- Internal refactoring to simplify scope node lookup. (`#2910\n `_)\n\n- Configure ``pytest`` to prevent pip from installing pytest in unsupported\n Python versions. (`#2922\n `_)\n\n\npytest 3.2.5 (2017-11-15)\n=========================\n\nBug Fixes\n---------\n\n- Remove ``py<1.5`` restriction from ``pytest`` as this can cause version\n conflicts in some installations. (`#2926\n `_)\n\n\npytest 3.2.4 (2017-11-13)\n=========================\n\nBug Fixes\n---------\n\n- Fix the bug where running with ``--pyargs`` will result in items with\n empty ``parent.nodeid`` if run from a different root directory. (`#2775\n `_)\n\n- Fix issue with ``@pytest.parametrize`` if argnames was specified as keyword arguments.\n (`#2819 `_)\n\n- Strip whitespace from marker names when reading them from INI config. (`#2856\n `_)\n\n- Show full context of doctest source in the pytest output, if the line number of\n failed example in the docstring is < 9. (`#2882\n `_)\n\n- Match fixture paths against actual path segments in order to avoid matching folders which share a prefix.\n (`#2836 `_)\n\nImproved Documentation\n----------------------\n\n- Introduce a dedicated section about conftest.py. (`#1505\n `_)\n\n- Explicitly mention ``xpass`` in the documentation of ``xfail``. (`#1997\n `_)\n\n- Append example for pytest.param in the example/parametrize document. (`#2658\n `_)\n\n- Clarify language of proposal for fixtures parameters (`#2893\n `_)\n\n- List python 3.6 in the documented supported versions in the getting started\n document. (`#2903 `_)\n\n- Clarify the documentation of available fixture scopes. (`#538\n `_)\n\n- Add documentation about the ``python -m pytest`` invocation adding the\n current directory to sys.path. (`#911\n `_)\n\n\npytest 3.2.3 (2017-10-03)\n=========================\n\nBug Fixes\n---------\n\n- Fix crash in tab completion when no prefix is given. (`#2748\n `_)\n\n- The equality checking function (``__eq__``) of ``MarkDecorator`` returns\n ``False`` if one object is not an instance of ``MarkDecorator``. (`#2758\n `_)\n\n- When running ``pytest --fixtures-per-test``: don't crash if an item has no\n _fixtureinfo attribute (e.g. doctests) (`#2788\n `_)\n\n\nImproved Documentation\n----------------------\n\n- In help text of ``-k`` option, add example of using ``not`` to not select\n certain tests whose names match the provided expression. (`#1442\n `_)\n\n- Add note in ``parametrize.rst`` about calling ``metafunc.parametrize``\n multiple times. (`#1548 `_)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Set ``xfail_strict=True`` in pytest's own test suite to catch expected\n failures as soon as they start to pass. (`#2722\n `_)\n\n- Fix typo in example of passing a callable to markers (in example/markers.rst)\n (`#2765 `_)\n\n\npytest 3.2.2 (2017-09-06)\n=========================\n\nBug Fixes\n---------\n\n- Calling the deprecated ``request.getfuncargvalue()`` now shows the source of\n the call. (`#2681 `_)\n\n- Allow tests declared as ``@staticmethod`` to use fixtures. (`#2699\n `_)\n\n- Fixed edge-case during collection: attributes which raised ``pytest.fail``\n when accessed would abort the entire collection. (`#2707\n `_)\n\n- Fix ``ReprFuncArgs`` with mixed unicode and UTF-8 args. (`#2731\n `_)\n\n\nImproved Documentation\n----------------------\n\n- In examples on working with custom markers, add examples demonstrating the\n usage of ``pytest.mark.MARKER_NAME.with_args`` in comparison with\n ``pytest.mark.MARKER_NAME.__call__`` (`#2604\n `_)\n\n- In one of the simple examples, use ``pytest_collection_modifyitems()`` to skip\n tests based on a command-line option, allowing its sharing while preventing a\n user error when acessing ``pytest.config`` before the argument parsing.\n (`#2653 `_)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Fixed minor error in 'Good Practices/Manual Integration' code snippet.\n (`#2691 `_)\n\n- Fixed typo in goodpractices.rst. (`#2721\n `_)\n\n- Improve user guidance regarding ``--resultlog`` deprecation. (`#2739\n `_)\n\n\npytest 3.2.1 (2017-08-08)\n=========================\n\nBug Fixes\n---------\n\n- Fixed small terminal glitch when collecting a single test item. (`#2579\n `_)\n\n- Correctly consider ``/`` as the file separator to automatically mark plugin\n files for rewrite on Windows. (`#2591 `_)\n\n- Properly escape test names when setting ``PYTEST_CURRENT_TEST`` environment\n variable. (`#2644 `_)\n\n- Fix error on Windows and Python 3.6+ when ``sys.stdout`` has been replaced\n with a stream-like object which does not implement the full ``io`` module\n buffer protocol. In particular this affects ``pytest-xdist`` users on the\n aforementioned platform. (`#2666 `_)\n\n\nImproved Documentation\n----------------------\n\n- Explicitly document which pytest features work with ``unittest``. (`#2626\n `_)\n\n\npytest 3.2.0 (2017-07-30)\n=========================\n\nDeprecations and Removals\n-------------------------\n\n- ``pytest.approx`` no longer supports ``>``, ``>=``, ``<`` and ``<=``\n operators to avoid surprising/inconsistent behavior. See `the approx docs\n `_ for more\n information. (`#2003 `_)\n\n- All old-style specific behavior in current classes in the pytest's API is\n considered deprecated at this point and will be removed in a future release.\n This affects Python 2 users only and in rare situations. (`#2147\n `_)\n\n- A deprecation warning is now raised when using marks for parameters\n in ``pytest.mark.parametrize``. Use ``pytest.param`` to apply marks to\n parameters instead. (`#2427 `_)\n\n\nFeatures\n--------\n\n- Add support for numpy arrays (and dicts) to approx. (`#1994\n `_)\n\n- Now test function objects have a ``pytestmark`` attribute containing a list\n of marks applied directly to the test function, as opposed to marks inherited\n from parent classes or modules. (`#2516 `_)\n\n- Collection ignores local virtualenvs by default; ``--collect-in-virtualenv``\n overrides this behavior. (`#2518 `_)\n\n- Allow class methods decorated as ``@staticmethod`` to be candidates for\n collection as a test function. (Only for Python 2.7 and above. Python 2.6\n will still ignore static methods.) (`#2528 `_)\n\n- Introduce ``mark.with_args`` in order to allow passing functions/classes as\n sole argument to marks. (`#2540 `_)\n\n- New ``cache_dir`` ini option: sets the directory where the contents of the\n cache plugin are stored. Directory may be relative or absolute path: if relative path, then\n directory is created relative to ``rootdir``, otherwise it is used as is.\n Additionally path may contain environment variables which are expanded during\n runtime. (`#2543 `_)\n\n- Introduce the ``PYTEST_CURRENT_TEST`` environment variable that is set with\n the ``nodeid`` and stage (``setup``, ``call`` and ``teardown``) of the test\n being currently executed. See the `documentation\n `_ for more info. (`#2583 `_)\n\n- Introduced ``@pytest.mark.filterwarnings`` mark which allows overwriting the\n warnings filter on a per test, class or module level. See the `docs\n `_ for more information. (`#2598 `_)\n\n- ``--last-failed`` now remembers forever when a test has failed and only\n forgets it if it passes again. This makes it easy to fix a test suite by\n selectively running files and fixing tests incrementally. (`#2621\n `_)\n\n- New ``pytest_report_collectionfinish`` hook which allows plugins to add\n messages to the terminal reporting after collection has been finished\n successfully. (`#2622 `_)\n\n- Added support for `PEP-415's `_\n ``Exception.__suppress_context__``. Now if a ``raise exception from None`` is\n caught by pytest, pytest will no longer chain the context in the test report.\n The behavior now matches Python's traceback behavior. (`#2631\n `_)\n\n- Exceptions raised by ``pytest.fail``, ``pytest.skip`` and ``pytest.xfail``\n now subclass BaseException, making them harder to be caught unintentionally\n by normal code. (`#580 `_)\n\n\nBug Fixes\n---------\n\n- Set ``stdin`` to a closed ``PIPE`` in ``pytester.py.Testdir.popen()`` for\n avoid unwanted interactive ``pdb`` (`#2023 `_)\n\n- Add missing ``encoding`` attribute to ``sys.std*`` streams when using\n ``capsys`` capture mode. (`#2375 `_)\n\n- Fix terminal color changing to black on Windows if ``colorama`` is imported\n in a ``conftest.py`` file. (`#2510 `_)\n\n- Fix line number when reporting summary of skipped tests. (`#2548\n `_)\n\n- capture: ensure that EncodedFile.name is a string. (`#2555\n `_)\n\n- The options ``--fixtures`` and ``--fixtures-per-test`` will now keep\n indentation within docstrings. (`#2574 `_)\n\n- doctests line numbers are now reported correctly, fixing `pytest-sugar#122\n `_. (`#2610\n `_)\n\n- Fix non-determinism in order of fixture collection. Adds new dependency\n (ordereddict) for Python 2.6. (`#920 `_)\n\n\nImproved Documentation\n----------------------\n\n- Clarify ``pytest_configure`` hook call order. (`#2539\n `_)\n\n- Extend documentation for testing plugin code with the ``pytester`` plugin.\n (`#971 `_)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Update help message for ``--strict`` to make it clear it only deals with\n unregistered markers, not warnings. (`#2444 `_)\n\n- Internal code move: move code for pytest.approx/pytest.raises to own files in\n order to cut down the size of python.py (`#2489 `_)\n\n- Renamed the utility function ``_pytest.compat._escape_strings`` to\n ``_ascii_escaped`` to better communicate the function's purpose. (`#2533\n `_)\n\n- Improve error message for CollectError with skip/skipif. (`#2546\n `_)\n\n- Emit warning about ``yield`` tests being deprecated only once per generator.\n (`#2562 `_)\n\n- Ensure final collected line doesn't include artifacts of previous write.\n (`#2571 `_)\n\n- Fixed all flake8 errors and warnings. (`#2581 `_)\n\n- Added ``fix-lint`` tox environment to run automatic pep8 fixes on the code.\n (`#2582 `_)\n\n- Turn warnings into errors in pytest's own test suite in order to catch\n regressions due to deprecations more promptly. (`#2588\n `_)\n\n- Show multiple issue links in CHANGELOG entries. (`#2620\n `_)\n\n\npytest 3.1.3 (2017-07-03)\n=========================\n\nBug Fixes\n---------\n\n- Fix decode error in Python 2 for doctests in docstrings. (`#2434\n `_)\n\n- Exceptions raised during teardown by finalizers are now suppressed until all\n finalizers are called, with the initial exception reraised. (`#2440\n `_)\n\n- Fix incorrect \"collected items\" report when specifying tests on the command-\n line. (`#2464 `_)\n\n- ``deprecated_call`` in context-manager form now captures deprecation warnings\n even if the same warning has already been raised. Also, ``deprecated_call``\n will always produce the same error message (previously it would produce\n different messages in context-manager vs. function-call mode). (`#2469\n `_)\n\n- Fix issue where paths collected by pytest could have triple leading ``/``\n characters. (`#2475 `_)\n\n- Fix internal error when trying to detect the start of a recursive traceback.\n (`#2486 `_)\n\n\nImproved Documentation\n----------------------\n\n- Explicitly state for which hooks the calls stop after the first non-None\n result. (`#2493 `_)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Create invoke tasks for updating the vendored packages. (`#2474\n `_)\n\n- Update copyright dates in LICENSE, README.rst and in the documentation.\n (`#2499 `_)\n\n\npytest 3.1.2 (2017-06-08)\n=========================\n\nBug Fixes\n---------\n\n- Required options added via ``pytest_addoption`` will no longer prevent using\n --help without passing them. (#1999)\n\n- Respect ``python_files`` in assertion rewriting. (#2121)\n\n- Fix recursion error detection when frames in the traceback contain objects\n that can't be compared (like ``numpy`` arrays). (#2459)\n\n- ``UnicodeWarning`` is issued from the internal pytest warnings plugin only\n when the message contains non-ascii unicode (Python 2 only). (#2463)\n\n- Added a workaround for Python 3.6 ``WindowsConsoleIO`` breaking due to Pytests's\n ``FDCapture``. Other code using console handles might still be affected by the\n very same issue and might require further workarounds/fixes, i.e. ``colorama``.\n (#2467)\n\n\nImproved Documentation\n----------------------\n\n- Fix internal API links to ``pluggy`` objects. (#2331)\n\n- Make it clear that ``pytest.xfail`` stops test execution at the calling point\n and improve overall flow of the ``skipping`` docs. (#810)\n\n\npytest 3.1.1 (2017-05-30)\n=========================\n\nBug Fixes\n---------\n\n- pytest warning capture no longer overrides existing warning filters. The\n previous behaviour would override all filters and caused regressions in test\n suites which configure warning filters to match their needs. Note that as a\n side-effect of this is that ``DeprecationWarning`` and\n ``PendingDeprecationWarning`` are no longer shown by default. (#2430)\n\n- Fix issue with non-ascii contents in doctest text files. (#2434)\n\n- Fix encoding errors for unicode warnings in Python 2. (#2436)\n\n- ``pytest.deprecated_call`` now captures ``PendingDeprecationWarning`` in\n context manager form. (#2441)\n\n\nImproved Documentation\n----------------------\n\n- Addition of towncrier for changelog management. (#2390)\n\n\n3.1.0 (2017-05-22)\n==================\n\n\nNew Features\n------------\n\n* The ``pytest-warnings`` plugin has been integrated into the core and now ``pytest`` automatically\n captures and displays warnings at the end of the test session.\n\n .. warning::\n\n This feature may disrupt test suites which apply and treat warnings themselves, and can be\n disabled in your ``pytest.ini``:\n\n .. code-block:: ini\n\n [pytest]\n addopts = -p no:warnings\n\n See the `warnings documentation page `_ for more\n information.\n\n Thanks `@nicoddemus`_ for the PR.\n\n* Added ``junit_suite_name`` ini option to specify root ```` name for JUnit XML reports (`#533`_).\n\n* Added an ini option ``doctest_encoding`` to specify which encoding to use for doctest files.\n Thanks `@wheerd`_ for the PR (`#2101`_).\n\n* ``pytest.warns`` now checks for subclass relationship rather than\n class equality. Thanks `@lesteve`_ for the PR (`#2166`_)\n\n* ``pytest.raises`` now asserts that the error message matches a text or regex\n with the ``match`` keyword argument. Thanks `@Kriechi`_ for the PR.\n\n* ``pytest.param`` can be used to declare test parameter sets with marks and test ids.\n Thanks `@RonnyPfannschmidt`_ for the PR.\n\n\nChanges\n-------\n\n* remove all internal uses of pytest_namespace hooks,\n this is to prepare the removal of preloadconfig in pytest 4.0\n Thanks to `@RonnyPfannschmidt`_ for the PR.\n\n* pytest now warns when a callable ids raises in a parametrized test. Thanks `@fogo`_ for the PR.\n\n* It is now possible to skip test classes from being collected by setting a\n ``__test__`` attribute to ``False`` in the class body (`#2007`_). Thanks\n to `@syre`_ for the report and `@lwm`_ for the PR.\n\n* Change junitxml.py to produce reports that comply with Junitxml schema.\n If the same test fails with failure in call and then errors in teardown\n we split testcase element into two, one containing the error and the other\n the failure. (`#2228`_) Thanks to `@kkoukiou`_ for the PR.\n\n* Testcase reports with a ``url`` attribute will now properly write this to junitxml.\n Thanks `@fushi`_ for the PR (`#1874`_).\n\n* Remove common items from dict comparison output when verbosity=1. Also update\n the truncation message to make it clearer that pytest truncates all\n assertion messages if verbosity < 2 (`#1512`_).\n Thanks `@mattduck`_ for the PR\n\n* ``--pdbcls`` no longer implies ``--pdb``. This makes it possible to use\n ``addopts=--pdbcls=module.SomeClass`` on ``pytest.ini``. Thanks `@davidszotten`_ for\n the PR (`#1952`_).\n\n* fix `#2013`_: turn RecordedWarning into ``namedtuple``,\n to give it a comprehensible repr while preventing unwarranted modification.\n\n* fix `#2208`_: ensure an iteration limit for _pytest.compat.get_real_func.\n Thanks `@RonnyPfannschmidt`_ for the report and PR.\n\n* Hooks are now verified after collection is complete, rather than right after loading installed plugins. This\n makes it easy to write hooks for plugins which will be loaded during collection, for example using the\n ``pytest_plugins`` special variable (`#1821`_).\n Thanks `@nicoddemus`_ for the PR.\n\n* Modify ``pytest_make_parametrize_id()`` hook to accept ``argname`` as an\n additional parameter.\n Thanks `@unsignedint`_ for the PR.\n\n* Add ``venv`` to the default ``norecursedirs`` setting.\n Thanks `@The-Compiler`_ for the PR.\n\n* ``PluginManager.import_plugin`` now accepts unicode plugin names in Python 2.\n Thanks `@reutsharabani`_ for the PR.\n\n* fix `#2308`_: When using both ``--lf`` and ``--ff``, only the last failed tests are run.\n Thanks `@ojii`_ for the PR.\n\n* Replace minor/patch level version numbers in the documentation with placeholders.\n This significantly reduces change-noise as different contributors regnerate\n the documentation on different platforms.\n Thanks `@RonnyPfannschmidt`_ for the PR.\n\n* fix `#2391`_: consider pytest_plugins on all plugin modules\n Thanks `@RonnyPfannschmidt`_ for the PR.\n\n\nBug Fixes\n---------\n\n* Fix ``AttributeError`` on ``sys.stdout.buffer`` / ``sys.stderr.buffer``\n while using ``capsys`` fixture in python 3. (`#1407`_).\n Thanks to `@asottile`_.\n\n* Change capture.py's ``DontReadFromInput`` class to throw ``io.UnsupportedOperation`` errors rather\n than ValueErrors in the ``fileno`` method (`#2276`_).\n Thanks `@metasyn`_ and `@vlad-dragos`_ for the PR.\n\n* Fix exception formatting while importing modules when the exception message\n contains non-ascii characters (`#2336`_).\n Thanks `@fabioz`_ for the report and `@nicoddemus`_ for the PR.\n\n* Added documentation related to issue (`#1937`_)\n Thanks `@skylarjhdownes`_ for the PR.\n\n* Allow collecting files with any file extension as Python modules (`#2369`_).\n Thanks `@Kodiologist`_ for the PR.\n\n* Show the correct error message when collect \"parametrize\" func with wrong args (`#2383`_).\n Thanks `@The-Compiler`_ for the report and `@robin0371`_ for the PR.\n\n\n.. _@davidszotten: https://github.com/davidszotten\n.. _@fabioz: https://github.com/fabioz\n.. _@fogo: https://github.com/fogo\n.. _@fushi: https://github.com/fushi\n.. _@Kodiologist: https://github.com/Kodiologist\n.. _@Kriechi: https://github.com/Kriechi\n.. _@mandeep: https://github.com/mandeep\n.. _@mattduck: https://github.com/mattduck\n.. _@metasyn: https://github.com/metasyn\n.. _@MichalTHEDUDE: https://github.com/MichalTHEDUDE\n.. _@ojii: https://github.com/ojii\n.. _@reutsharabani: https://github.com/reutsharabani\n.. _@robin0371: https://github.com/robin0371\n.. _@skylarjhdownes: https://github.com/skylarjhdownes\n.. _@unsignedint: https://github.com/unsignedint\n.. _@wheerd: https://github.com/wheerd\n\n\n.. _#1407: https://github.com/pytest-dev/pytest/issues/1407\n.. _#1512: https://github.com/pytest-dev/pytest/issues/1512\n.. _#1821: https://github.com/pytest-dev/pytest/issues/1821\n.. _#1874: https://github.com/pytest-dev/pytest/pull/1874\n.. _#1937: https://github.com/pytest-dev/pytest/issues/1937\n.. _#1952: https://github.com/pytest-dev/pytest/pull/1952\n.. _#2007: https://github.com/pytest-dev/pytest/issues/2007\n.. _#2013: https://github.com/pytest-dev/pytest/issues/2013\n.. _#2101: https://github.com/pytest-dev/pytest/pull/2101\n.. _#2166: https://github.com/pytest-dev/pytest/pull/2166\n.. _#2208: https://github.com/pytest-dev/pytest/issues/2208\n.. _#2228: https://github.com/pytest-dev/pytest/issues/2228\n.. _#2276: https://github.com/pytest-dev/pytest/issues/2276\n.. _#2308: https://github.com/pytest-dev/pytest/issues/2308\n.. _#2336: https://github.com/pytest-dev/pytest/issues/2336\n.. _#2369: https://github.com/pytest-dev/pytest/issues/2369\n.. _#2383: https://github.com/pytest-dev/pytest/issues/2383\n.. _#2391: https://github.com/pytest-dev/pytest/issues/2391\n.. _#533: https://github.com/pytest-dev/pytest/issues/533\n\n\n\n3.0.7 (2017-03-14)\n==================\n\n\n* Fix issue in assertion rewriting breaking due to modules silently discarding\n other modules when importing fails\n Notably, importing the ``anydbm`` module is fixed. (`#2248`_).\n Thanks `@pfhayes`_ for the PR.\n\n* junitxml: Fix problematic case where system-out tag occurred twice per testcase\n element in the XML report. Thanks `@kkoukiou`_ for the PR.\n\n* Fix regression, pytest now skips unittest correctly if run with ``--pdb``\n (`#2137`_). Thanks to `@gst`_ for the report and `@mbyt`_ for the PR.\n\n* Ignore exceptions raised from descriptors (e.g. properties) during Python test collection (`#2234`_).\n Thanks to `@bluetech`_.\n\n* ``--override-ini`` now correctly overrides some fundamental options like ``python_files`` (`#2238`_).\n Thanks `@sirex`_ for the report and `@nicoddemus`_ for the PR.\n\n* Replace ``raise StopIteration`` usages in the code by simple ``returns`` to finish generators, in accordance to `PEP-479`_ (`#2160`_).\n Thanks `@tgoodlet`_ for the report and `@nicoddemus`_ for the PR.\n\n* Fix internal errors when an unprintable ``AssertionError`` is raised inside a test.\n Thanks `@omerhadari`_ for the PR.\n\n* Skipping plugin now also works with test items generated by custom collectors (`#2231`_).\n Thanks to `@vidartf`_.\n\n* Fix trailing whitespace in console output if no .ini file presented (`#2281`_). Thanks `@fbjorn`_ for the PR.\n\n* Conditionless ``xfail`` markers no longer rely on the underlying test item\n being an instance of ``PyobjMixin``, and can therefore apply to tests not\n collected by the built-in python test collector. Thanks `@barneygale`_ for the\n PR.\n\n\n.. _@pfhayes: https://github.com/pfhayes\n.. _@bluetech: https://github.com/bluetech\n.. _@gst: https://github.com/gst\n.. _@sirex: https://github.com/sirex\n.. _@vidartf: https://github.com/vidartf\n.. _@kkoukiou: https://github.com/KKoukiou\n.. _@omerhadari: https://github.com/omerhadari\n.. _@fbjorn: https://github.com/fbjorn\n\n.. _#2248: https://github.com/pytest-dev/pytest/issues/2248\n.. _#2137: https://github.com/pytest-dev/pytest/issues/2137\n.. _#2160: https://github.com/pytest-dev/pytest/issues/2160\n.. _#2231: https://github.com/pytest-dev/pytest/issues/2231\n.. _#2234: https://github.com/pytest-dev/pytest/issues/2234\n.. _#2238: https://github.com/pytest-dev/pytest/issues/2238\n.. _#2281: https://github.com/pytest-dev/pytest/issues/2281\n\n.. _PEP-479: https://www.python.org/dev/peps/pep-0479/\n\n\n3.0.6 (2017-01-22)\n==================\n\n* pytest no longer generates ``PendingDeprecationWarning`` from its own operations, which was introduced by mistake in version ``3.0.5`` (`#2118`_).\n Thanks to `@nicoddemus`_ for the report and `@RonnyPfannschmidt`_ for the PR.\n\n\n* pytest no longer recognizes coroutine functions as yield tests (`#2129`_).\n Thanks to `@malinoff`_ for the PR.\n\n* Plugins loaded by the ``PYTEST_PLUGINS`` environment variable are now automatically\n considered for assertion rewriting (`#2185`_).\n Thanks `@nicoddemus`_ for the PR.\n\n* Improve error message when pytest.warns fails (`#2150`_). The type(s) of the\n expected warnings and the list of caught warnings is added to the\n error message. Thanks `@lesteve`_ for the PR.\n\n* Fix ``pytester`` internal plugin to work correctly with latest versions of\n ``zope.interface`` (`#1989`_). Thanks `@nicoddemus`_ for the PR.\n\n* Assert statements of the ``pytester`` plugin again benefit from assertion rewriting (`#1920`_).\n Thanks `@RonnyPfannschmidt`_ for the report and `@nicoddemus`_ for the PR.\n\n* Specifying tests with colons like ``test_foo.py::test_bar`` for tests in\n subdirectories with ini configuration files now uses the correct ini file\n (`#2148`_). Thanks `@pelme`_.\n\n* Fail ``testdir.runpytest().assert_outcomes()`` explicitly if the pytest\n terminal output it relies on is missing. Thanks to `@eli-b`_ for the PR.\n\n\n.. _@barneygale: https://github.com/barneygale\n.. _@lesteve: https://github.com/lesteve\n.. _@malinoff: https://github.com/malinoff\n.. _@pelme: https://github.com/pelme\n.. _@eli-b: https://github.com/eli-b\n\n.. _#2118: https://github.com/pytest-dev/pytest/issues/2118\n\n.. _#1989: https://github.com/pytest-dev/pytest/issues/1989\n.. _#1920: https://github.com/pytest-dev/pytest/issues/1920\n.. _#2129: https://github.com/pytest-dev/pytest/issues/2129\n.. _#2148: https://github.com/pytest-dev/pytest/issues/2148\n.. _#2150: https://github.com/pytest-dev/pytest/issues/2150\n.. _#2185: https://github.com/pytest-dev/pytest/issues/2185\n\n\n3.0.5 (2016-12-05)\n==================\n\n* Add warning when not passing ``option=value`` correctly to ``-o/--override-ini`` (`#2105`_).\n Also improved the help documentation. Thanks to `@mbukatov`_ for the report and\n `@lwm`_ for the PR.\n\n* Now ``--confcutdir`` and ``--junit-xml`` are properly validated if they are directories\n and filenames, respectively (`#2089`_ and `#2078`_). Thanks to `@lwm`_ for the PR.\n\n* Add hint to error message hinting possible missing ``__init__.py`` (`#478`_). Thanks `@DuncanBetts`_.\n\n* More accurately describe when fixture finalization occurs in documentation (`#687`_). Thanks `@DuncanBetts`_.\n\n* Provide ``:ref:`` targets for ``recwarn.rst`` so we can use intersphinx referencing.\n Thanks to `@dupuy`_ for the report and `@lwm`_ for the PR.\n\n* In Python 2, use a simple ``+-`` ASCII string in the string representation of ``pytest.approx`` (for example ``\"4 +- 4.0e-06\"``)\n because it is brittle to handle that in different contexts and representations internally in pytest\n which can result in bugs such as `#2111`_. In Python 3, the representation still uses ``±`` (for example ``4 ± 4.0e-06``).\n Thanks `@kerrick-lyft`_ for the report and `@nicoddemus`_ for the PR.\n\n* Using ``item.Function``, ``item.Module``, etc., is now issuing deprecation warnings, prefer\n ``pytest.Function``, ``pytest.Module``, etc., instead (`#2034`_).\n Thanks `@nmundar`_ for the PR.\n\n* Fix error message using ``approx`` with complex numbers (`#2082`_).\n Thanks `@adler-j`_ for the report and `@nicoddemus`_ for the PR.\n\n* Fixed false-positives warnings from assertion rewrite hook for modules imported more than\n once by the ``pytest_plugins`` mechanism.\n Thanks `@nicoddemus`_ for the PR.\n\n* Remove an internal cache which could cause hooks from ``conftest.py`` files in\n sub-directories to be called in other directories incorrectly (`#2016`_).\n Thanks `@d-b-w`_ for the report and `@nicoddemus`_ for the PR.\n\n* Remove internal code meant to support earlier Python 3 versions that produced the side effect\n of leaving ``None`` in ``sys.modules`` when expressions were evaluated by pytest (for example passing a condition\n as a string to ``pytest.mark.skipif``)(`#2103`_).\n Thanks `@jaraco`_ for the report and `@nicoddemus`_ for the PR.\n\n* Cope gracefully with a .pyc file with no matching .py file (`#2038`_). Thanks\n `@nedbat`_.\n\n.. _@syre: https://github.com/syre\n.. _@adler-j: https://github.com/adler-j\n.. _@d-b-w: https://bitbucket.org/d-b-w/\n.. _@DuncanBetts: https://github.com/DuncanBetts\n.. _@dupuy: https://bitbucket.org/dupuy/\n.. _@kerrick-lyft: https://github.com/kerrick-lyft\n.. _@lwm: https://github.com/lwm\n.. _@mbukatov: https://github.com/mbukatov\n.. _@nedbat: https://github.com/nedbat\n.. _@nmundar: https://github.com/nmundar\n\n.. _#2016: https://github.com/pytest-dev/pytest/issues/2016\n.. _#2034: https://github.com/pytest-dev/pytest/issues/2034\n.. _#2038: https://github.com/pytest-dev/pytest/issues/2038\n.. _#2078: https://github.com/pytest-dev/pytest/issues/2078\n.. _#2082: https://github.com/pytest-dev/pytest/issues/2082\n.. _#2089: https://github.com/pytest-dev/pytest/issues/2089\n.. _#2103: https://github.com/pytest-dev/pytest/issues/2103\n.. _#2105: https://github.com/pytest-dev/pytest/issues/2105\n.. _#2111: https://github.com/pytest-dev/pytest/issues/2111\n.. _#478: https://github.com/pytest-dev/pytest/issues/478\n.. _#687: https://github.com/pytest-dev/pytest/issues/687\n\n\n3.0.4 (2016-11-09)\n==================\n\n* Import errors when collecting test modules now display the full traceback (`#1976`_).\n Thanks `@cwitty`_ for the report and `@nicoddemus`_ for the PR.\n\n* Fix confusing command-line help message for custom options with two or more ``metavar`` properties (`#2004`_).\n Thanks `@okulynyak`_ and `@davehunt`_ for the report and `@nicoddemus`_ for the PR.\n\n* When loading plugins, import errors which contain non-ascii messages are now properly handled in Python 2 (`#1998`_).\n Thanks `@nicoddemus`_ for the PR.\n\n* Fixed cyclic reference when ``pytest.raises`` is used in context-manager form (`#1965`_). Also as a\n result of this fix, ``sys.exc_info()`` is left empty in both context-manager and function call usages.\n Previously, ``sys.exc_info`` would contain the exception caught by the context manager,\n even when the expected exception occurred.\n Thanks `@MSeifert04`_ for the report and the PR.\n\n* Fixed false-positives warnings from assertion rewrite hook for modules that were rewritten but\n were later marked explicitly by ``pytest.register_assert_rewrite``\n or implicitly as a plugin (`#2005`_).\n Thanks `@RonnyPfannschmidt`_ for the report and `@nicoddemus`_ for the PR.\n\n* Report teardown output on test failure (`#442`_).\n Thanks `@matclab`_ for the PR.\n\n* Fix teardown error message in generated xUnit XML.\n Thanks `@gdyuldin`_ for the PR.\n\n* Properly handle exceptions in ``multiprocessing`` tasks (`#1984`_).\n Thanks `@adborden`_ for the report and `@nicoddemus`_ for the PR.\n\n* Clean up unittest TestCase objects after tests are complete (`#1649`_).\n Thanks `@d_b_w`_ for the report and PR.\n\n\n.. _@adborden: https://github.com/adborden\n.. _@cwitty: https://github.com/cwitty\n.. _@d_b_w: https://github.com/d_b_w\n.. _@gdyuldin: https://github.com/gdyuldin\n.. _@matclab: https://github.com/matclab\n.. _@MSeifert04: https://github.com/MSeifert04\n.. _@okulynyak: https://github.com/okulynyak\n\n.. _#442: https://github.com/pytest-dev/pytest/issues/442\n.. _#1965: https://github.com/pytest-dev/pytest/issues/1965\n.. _#1976: https://github.com/pytest-dev/pytest/issues/1976\n.. _#1984: https://github.com/pytest-dev/pytest/issues/1984\n.. _#1998: https://github.com/pytest-dev/pytest/issues/1998\n.. _#2004: https://github.com/pytest-dev/pytest/issues/2004\n.. _#2005: https://github.com/pytest-dev/pytest/issues/2005\n.. _#1649: https://github.com/pytest-dev/pytest/issues/1649\n\n\n3.0.3 (2016-09-28)\n==================\n\n* The ``ids`` argument to ``parametrize`` again accepts ``unicode`` strings\n in Python 2 (`#1905`_).\n Thanks `@philpep`_ for the report and `@nicoddemus`_ for the PR.\n\n* Assertions are now being rewritten for plugins in development mode\n (``pip install -e``) (`#1934`_).\n Thanks `@nicoddemus`_ for the PR.\n\n* Fix pkg_resources import error in Jython projects (`#1853`_).\n Thanks `@raquel-ucl`_ for the PR.\n\n* Got rid of ``AttributeError: 'Module' object has no attribute '_obj'`` exception\n in Python 3 (`#1944`_).\n Thanks `@axil`_ for the PR.\n\n* Explain a bad scope value passed to ``@fixture`` declarations or\n a ``MetaFunc.parametrize()`` call. Thanks `@tgoodlet`_ for the PR.\n\n* This version includes ``pluggy-0.4.0``, which correctly handles\n ``VersionConflict`` errors in plugins (`#704`_).\n Thanks `@nicoddemus`_ for the PR.\n\n\n.. _@philpep: https://github.com/philpep\n.. _@raquel-ucl: https://github.com/raquel-ucl\n.. _@axil: https://github.com/axil\n.. _@tgoodlet: https://github.com/tgoodlet\n.. _@vlad-dragos: https://github.com/vlad-dragos\n\n.. _#1853: https://github.com/pytest-dev/pytest/issues/1853\n.. _#1905: https://github.com/pytest-dev/pytest/issues/1905\n.. _#1934: https://github.com/pytest-dev/pytest/issues/1934\n.. _#1944: https://github.com/pytest-dev/pytest/issues/1944\n.. _#704: https://github.com/pytest-dev/pytest/issues/704\n\n\n\n\n3.0.2 (2016-09-01)\n==================\n\n* Improve error message when passing non-string ids to ``pytest.mark.parametrize`` (`#1857`_).\n Thanks `@okken`_ for the report and `@nicoddemus`_ for the PR.\n\n* Add ``buffer`` attribute to stdin stub class ``pytest.capture.DontReadFromInput``\n Thanks `@joguSD`_ for the PR.\n\n* Fix ``UnicodeEncodeError`` when string comparison with unicode has failed. (`#1864`_)\n Thanks `@AiOO`_ for the PR.\n\n* ``pytest_plugins`` is now handled correctly if defined as a string (as opposed as\n a sequence of strings) when modules are considered for assertion rewriting.\n Due to this bug, much more modules were being rewritten than necessary\n if a test suite uses ``pytest_plugins`` to load internal plugins (`#1888`_).\n Thanks `@jaraco`_ for the report and `@nicoddemus`_ for the PR (`#1891`_).\n\n* Do not call tearDown and cleanups when running tests from\n ``unittest.TestCase`` subclasses with ``--pdb``\n enabled. This allows proper post mortem debugging for all applications\n which have significant logic in their tearDown machinery (`#1890`_). Thanks\n `@mbyt`_ for the PR.\n\n* Fix use of deprecated ``getfuncargvalue`` method in the internal doctest plugin.\n Thanks `@ViviCoder`_ for the report (`#1898`_).\n\n.. _@joguSD: https://github.com/joguSD\n.. _@AiOO: https://github.com/AiOO\n.. _@mbyt: https://github.com/mbyt\n.. _@ViviCoder: https://github.com/ViviCoder\n\n.. _#1857: https://github.com/pytest-dev/pytest/issues/1857\n.. _#1864: https://github.com/pytest-dev/pytest/issues/1864\n.. _#1888: https://github.com/pytest-dev/pytest/issues/1888\n.. _#1891: https://github.com/pytest-dev/pytest/pull/1891\n.. _#1890: https://github.com/pytest-dev/pytest/issues/1890\n.. _#1898: https://github.com/pytest-dev/pytest/issues/1898\n\n\n3.0.1 (2016-08-23)\n==================\n\n* Fix regression when ``importorskip`` is used at module level (`#1822`_).\n Thanks `@jaraco`_ and `@The-Compiler`_ for the report and `@nicoddemus`_ for the PR.\n\n* Fix parametrization scope when session fixtures are used in conjunction\n with normal parameters in the same call (`#1832`_).\n Thanks `@The-Compiler`_ for the report, `@Kingdread`_ and `@nicoddemus`_ for the PR.\n\n* Fix internal error when parametrizing tests or fixtures using an empty ``ids`` argument (`#1849`_).\n Thanks `@OPpuolitaival`_ for the report and `@nicoddemus`_ for the PR.\n\n* Fix loader error when running ``pytest`` embedded in a zipfile.\n Thanks `@mbachry`_ for the PR.\n\n\n.. _@Kingdread: https://github.com/Kingdread\n.. _@mbachry: https://github.com/mbachry\n.. _@OPpuolitaival: https://github.com/OPpuolitaival\n\n.. _#1822: https://github.com/pytest-dev/pytest/issues/1822\n.. _#1832: https://github.com/pytest-dev/pytest/issues/1832\n.. _#1849: https://github.com/pytest-dev/pytest/issues/1849\n\n\n3.0.0 (2016-08-18)\n==================\n\n**Incompatible changes**\n\n\nA number of incompatible changes were made in this release, with the intent of removing features deprecated for a long\ntime or change existing behaviors in order to make them less surprising/more useful.\n\n* Reinterpretation mode has now been removed. Only plain and rewrite\n mode are available, consequently the ``--assert=reinterp`` option is\n no longer available. This also means files imported from plugins or\n ``conftest.py`` will not benefit from improved assertions by\n default, you should use ``pytest.register_assert_rewrite()`` to\n explicitly turn on assertion rewriting for those files. Thanks\n `@flub`_ for the PR.\n\n* The following deprecated commandline options were removed:\n\n * ``--genscript``: no longer supported;\n * ``--no-assert``: use ``--assert=plain`` instead;\n * ``--nomagic``: use ``--assert=plain`` instead;\n * ``--report``: use ``-r`` instead;\n\n Thanks to `@RedBeardCode`_ for the PR (`#1664`_).\n\n* ImportErrors in plugins now are a fatal error instead of issuing a\n pytest warning (`#1479`_). Thanks to `@The-Compiler`_ for the PR.\n\n* Removed support code for Python 3 versions < 3.3 (`#1627`_).\n\n* Removed all ``py.test-X*`` entry points. The versioned, suffixed entry points\n were never documented and a leftover from a pre-virtualenv era. These entry\n points also created broken entry points in wheels, so removing them also\n removes a source of confusion for users (`#1632`_).\n Thanks `@obestwalter`_ for the PR.\n\n* ``pytest.skip()`` now raises an error when used to decorate a test function,\n as opposed to its original intent (to imperatively skip a test inside a test function). Previously\n this usage would cause the entire module to be skipped (`#607`_).\n Thanks `@omarkohl`_ for the complete PR (`#1519`_).\n\n* Exit tests if a collection error occurs. A poll indicated most users will hit CTRL-C\n anyway as soon as they see collection errors, so pytest might as well make that the default behavior (`#1421`_).\n A ``--continue-on-collection-errors`` option has been added to restore the previous behaviour.\n Thanks `@olegpidsadnyi`_ and `@omarkohl`_ for the complete PR (`#1628`_).\n\n* Renamed the pytest ``pdb`` module (plugin) into ``debugging`` to avoid clashes with the builtin ``pdb`` module.\n\n* Raise a helpful failure message when requesting a parametrized fixture at runtime,\n e.g. with ``request.getfixturevalue``. Previously these parameters were simply\n never defined, so a fixture decorated like ``@pytest.fixture(params=[0, 1, 2])``\n only ran once (`#460`_).\n Thanks to `@nikratio`_ for the bug report, `@RedBeardCode`_ and `@tomviner`_ for the PR.\n\n* ``_pytest.monkeypatch.monkeypatch`` class has been renamed to ``_pytest.monkeypatch.MonkeyPatch``\n so it doesn't conflict with the ``monkeypatch`` fixture.\n\n* ``--exitfirst / -x`` can now be overridden by a following ``--maxfail=N``\n and is just a synonym for ``--maxfail=1``.\n\n\n**New Features**\n\n* Support nose-style ``__test__`` attribute on methods of classes,\n including unittest-style Classes. If set to ``False``, the test will not be\n collected.\n\n* New ``doctest_namespace`` fixture for injecting names into the\n namespace in which doctests run.\n Thanks `@milliams`_ for the complete PR (`#1428`_).\n\n* New ``--doctest-report`` option available to change the output format of diffs\n when running (failing) doctests (implements `#1749`_).\n Thanks `@hartym`_ for the PR.\n\n* New ``name`` argument to ``pytest.fixture`` decorator which allows a custom name\n for a fixture (to solve the funcarg-shadowing-fixture problem).\n Thanks `@novas0x2a`_ for the complete PR (`#1444`_).\n\n* New ``approx()`` function for easily comparing floating-point numbers in\n tests.\n Thanks `@kalekundert`_ for the complete PR (`#1441`_).\n\n* Ability to add global properties in the final xunit output file by accessing\n the internal ``junitxml`` plugin (experimental).\n Thanks `@tareqalayan`_ for the complete PR `#1454`_).\n\n* New ``ExceptionInfo.match()`` method to match a regular expression on the\n string representation of an exception (`#372`_).\n Thanks `@omarkohl`_ for the complete PR (`#1502`_).\n\n* ``__tracebackhide__`` can now also be set to a callable which then can decide\n whether to filter the traceback based on the ``ExceptionInfo`` object passed\n to it. Thanks `@The-Compiler`_ for the complete PR (`#1526`_).\n\n* New ``pytest_make_parametrize_id(config, val)`` hook which can be used by plugins to provide\n friendly strings for custom types.\n Thanks `@palaviv`_ for the PR.\n\n* ``capsys`` and ``capfd`` now have a ``disabled()`` context-manager method, which\n can be used to temporarily disable capture within a test.\n Thanks `@nicoddemus`_ for the PR.\n\n* New cli flag ``--fixtures-per-test``: shows which fixtures are being used\n for each selected test item. Features doc strings of fixtures by default.\n Can also show where fixtures are defined if combined with ``-v``.\n Thanks `@hackebrot`_ for the PR.\n\n* Introduce ``pytest`` command as recommended entry point. Note that ``py.test``\n still works and is not scheduled for removal. Closes proposal\n `#1629`_. Thanks `@obestwalter`_ and `@davehunt`_ for the complete PR\n (`#1633`_).\n\n* New cli flags:\n\n + ``--setup-plan``: performs normal collection and reports\n the potential setup and teardown and does not execute any fixtures and tests;\n + ``--setup-only``: performs normal collection, executes setup and teardown of\n fixtures and reports them;\n + ``--setup-show``: performs normal test execution and additionally shows\n setup and teardown of fixtures;\n + ``--keep-duplicates``: py.test now ignores duplicated paths given in the command\n line. To retain the previous behavior where the same test could be run multiple\n times by specifying it in the command-line multiple times, pass the ``--keep-duplicates``\n argument (`#1609`_);\n\n Thanks `@d6e`_, `@kvas-it`_, `@sallner`_, `@ioggstream`_ and `@omarkohl`_ for the PRs.\n\n* New CLI flag ``--override-ini``/``-o``: overrides values from the ini file.\n For example: ``\"-o xfail_strict=True\"``'.\n Thanks `@blueyed`_ and `@fengxx`_ for the PR.\n\n* New hooks:\n\n + ``pytest_fixture_setup(fixturedef, request)``: executes fixture setup;\n + ``pytest_fixture_post_finalizer(fixturedef)``: called after the fixture's\n finalizer and has access to the fixture's result cache.\n\n Thanks `@d6e`_, `@sallner`_.\n\n* Issue warnings for asserts whose test is a tuple literal. Such asserts will\n never fail because tuples are always truthy and are usually a mistake\n (see `#1562`_). Thanks `@kvas-it`_, for the PR.\n\n* Allow passing a custom debugger class (e.g. ``--pdbcls=IPython.core.debugger:Pdb``).\n Thanks to `@anntzer`_ for the PR.\n\n\n**Changes**\n\n* Plugins now benefit from assertion rewriting. Thanks\n `@sober7`_, `@nicoddemus`_ and `@flub`_ for the PR.\n\n* Change ``report.outcome`` for ``xpassed`` tests to ``\"passed\"`` in non-strict\n mode and ``\"failed\"`` in strict mode. Thanks to `@hackebrot`_ for the PR\n (`#1795`_) and `@gprasad84`_ for report (`#1546`_).\n\n* Tests marked with ``xfail(strict=False)`` (the default) now appear in\n JUnitXML reports as passing tests instead of skipped.\n Thanks to `@hackebrot`_ for the PR (`#1795`_).\n\n* Highlight path of the file location in the error report to make it easier to copy/paste.\n Thanks `@suzaku`_ for the PR (`#1778`_).\n\n* Fixtures marked with ``@pytest.fixture`` can now use ``yield`` statements exactly like\n those marked with the ``@pytest.yield_fixture`` decorator. This change renders\n ``@pytest.yield_fixture`` deprecated and makes ``@pytest.fixture`` with ``yield`` statements\n the preferred way to write teardown code (`#1461`_).\n Thanks `@csaftoiu`_ for bringing this to attention and `@nicoddemus`_ for the PR.\n\n* Explicitly passed parametrize ids do not get escaped to ascii (`#1351`_).\n Thanks `@ceridwen`_ for the PR.\n\n* Fixtures are now sorted in the error message displayed when an unknown\n fixture is declared in a test function.\n Thanks `@nicoddemus`_ for the PR.\n\n* ``pytest_terminal_summary`` hook now receives the ``exitstatus``\n of the test session as argument. Thanks `@blueyed`_ for the PR (`#1809`_).\n\n* Parametrize ids can accept ``None`` as specific test id, in which case the\n automatically generated id for that argument will be used.\n Thanks `@palaviv`_ for the complete PR (`#1468`_).\n\n* The parameter to xunit-style setup/teardown methods (``setup_method``,\n ``setup_module``, etc.) is now optional and may be omitted.\n Thanks `@okken`_ for bringing this to attention and `@nicoddemus`_ for the PR.\n\n* Improved automatic id generation selection in case of duplicate ids in\n parametrize.\n Thanks `@palaviv`_ for the complete PR (`#1474`_).\n\n* Now pytest warnings summary is shown up by default. Added a new flag\n ``--disable-pytest-warnings`` to explicitly disable the warnings summary (`#1668`_).\n\n* Make ImportError during collection more explicit by reminding\n the user to check the name of the test module/package(s) (`#1426`_).\n Thanks `@omarkohl`_ for the complete PR (`#1520`_).\n\n* Add ``build/`` and ``dist/`` to the default ``--norecursedirs`` list. Thanks\n `@mikofski`_ for the report and `@tomviner`_ for the PR (`#1544`_).\n\n* ``pytest.raises`` in the context manager form accepts a custom\n ``message`` to raise when no exception occurred.\n Thanks `@palaviv`_ for the complete PR (`#1616`_).\n\n* ``conftest.py`` files now benefit from assertion rewriting; previously it\n was only available for test modules. Thanks `@flub`_, `@sober7`_ and\n `@nicoddemus`_ for the PR (`#1619`_).\n\n* Text documents without any doctests no longer appear as \"skipped\".\n Thanks `@graingert`_ for reporting and providing a full PR (`#1580`_).\n\n* Ensure that a module within a namespace package can be found when it\n is specified on the command line together with the ``--pyargs``\n option. Thanks to `@taschini`_ for the PR (`#1597`_).\n\n* Always include full assertion explanation during assertion rewriting. The previous behaviour was hiding\n sub-expressions that happened to be ``False``, assuming this was redundant information.\n Thanks `@bagerard`_ for reporting (`#1503`_). Thanks to `@davehunt`_ and\n `@tomviner`_ for the PR.\n\n* ``OptionGroup.addoption()`` now checks if option names were already\n added before, to make it easier to track down issues like `#1618`_.\n Before, you only got exceptions later from ``argparse`` library,\n giving no clue about the actual reason for double-added options.\n\n* ``yield``-based tests are considered deprecated and will be removed in pytest-4.0.\n Thanks `@nicoddemus`_ for the PR.\n\n* ``[pytest]`` sections in ``setup.cfg`` files should now be named ``[tool:pytest]``\n to avoid conflicts with other distutils commands (see `#567`_). ``[pytest]`` sections in\n ``pytest.ini`` or ``tox.ini`` files are supported and unchanged.\n Thanks `@nicoddemus`_ for the PR.\n\n* Using ``pytest_funcarg__`` prefix to declare fixtures is considered deprecated and will be\n removed in pytest-4.0 (`#1684`_).\n Thanks `@nicoddemus`_ for the PR.\n\n* Passing a command-line string to ``pytest.main()`` is considered deprecated and scheduled\n for removal in pytest-4.0. It is recommended to pass a list of arguments instead (`#1723`_).\n\n* Rename ``getfuncargvalue`` to ``getfixturevalue``. ``getfuncargvalue`` is\n still present but is now considered deprecated. Thanks to `@RedBeardCode`_ and `@tomviner`_\n for the PR (`#1626`_).\n\n* ``optparse`` type usage now triggers DeprecationWarnings (`#1740`_).\n\n\n* ``optparse`` backward compatibility supports float/complex types (`#457`_).\n\n* Refined logic for determining the ``rootdir``, considering only valid\n paths which fixes a number of issues: `#1594`_, `#1435`_ and `#1471`_.\n Updated the documentation according to current behavior. Thanks to\n `@blueyed`_, `@davehunt`_ and `@matthiasha`_ for the PR.\n\n* Always include full assertion explanation. The previous behaviour was hiding\n sub-expressions that happened to be False, assuming this was redundant information.\n Thanks `@bagerard`_ for reporting (`#1503`_). Thanks to `@davehunt`_ and\n `@tomviner`_ for PR.\n\n* Better message in case of not using parametrized variable (see `#1539`_).\n Thanks to `@tramwaj29`_ for the PR.\n\n* Updated docstrings with a more uniform style.\n\n* Add stderr write for ``pytest.exit(msg)`` during startup. Previously the message was never shown.\n Thanks `@BeyondEvil`_ for reporting `#1210`_. Thanks to `@JonathonSonesen`_ and\n `@tomviner`_ for the PR.\n\n* No longer display the incorrect test deselection reason (`#1372`_).\n Thanks `@ronnypfannschmidt`_ for the PR.\n\n* The ``--resultlog`` command line option has been deprecated: it is little used\n and there are more modern and better alternatives (see `#830`_).\n Thanks `@nicoddemus`_ for the PR.\n\n* Improve error message with fixture lookup errors: add an 'E' to the first\n line and '>' to the rest. Fixes `#717`_. Thanks `@blueyed`_ for reporting and\n a PR, `@eolo999`_ for the initial PR and `@tomviner`_ for his guidance during\n EuroPython2016 sprint.\n\n\n**Bug Fixes**\n\n* Parametrize now correctly handles duplicated test ids.\n\n* Fix internal error issue when the ``method`` argument is missing for\n ``teardown_method()`` (`#1605`_).\n\n* Fix exception visualization in case the current working directory (CWD) gets\n deleted during testing (`#1235`_). Thanks `@bukzor`_ for reporting. PR by\n `@marscher`_.\n\n* Improve test output for logical expression with brackets (`#925`_).\n Thanks `@DRMacIver`_ for reporting and `@RedBeardCode`_ for the PR.\n\n* Create correct diff for strings ending with newlines (`#1553`_).\n Thanks `@Vogtinator`_ for reporting and `@RedBeardCode`_ and\n `@tomviner`_ for the PR.\n\n* ``ConftestImportFailure`` now shows the traceback making it easier to\n identify bugs in ``conftest.py`` files (`#1516`_). Thanks `@txomon`_ for\n the PR.\n\n* Text documents without any doctests no longer appear as \"skipped\".\n Thanks `@graingert`_ for reporting and providing a full PR (`#1580`_).\n\n* Fixed collection of classes with custom ``__new__`` method.\n Fixes `#1579`_. Thanks to `@Stranger6667`_ for the PR.\n\n* Fixed scope overriding inside metafunc.parametrize (`#634`_).\n Thanks to `@Stranger6667`_ for the PR.\n\n* Fixed the total tests tally in junit xml output (`#1798`_).\n Thanks to `@cryporchild`_ for the PR.\n\n* Fixed off-by-one error with lines from ``request.node.warn``.\n Thanks to `@blueyed`_ for the PR.\n\n\n.. _#1210: https://github.com/pytest-dev/pytest/issues/1210\n.. _#1235: https://github.com/pytest-dev/pytest/issues/1235\n.. _#1351: https://github.com/pytest-dev/pytest/issues/1351\n.. _#1372: https://github.com/pytest-dev/pytest/issues/1372\n.. _#1421: https://github.com/pytest-dev/pytest/issues/1421\n.. _#1426: https://github.com/pytest-dev/pytest/issues/1426\n.. _#1428: https://github.com/pytest-dev/pytest/pull/1428\n.. _#1435: https://github.com/pytest-dev/pytest/issues/1435\n.. _#1441: https://github.com/pytest-dev/pytest/pull/1441\n.. _#1444: https://github.com/pytest-dev/pytest/pull/1444\n.. _#1454: https://github.com/pytest-dev/pytest/pull/1454\n.. _#1461: https://github.com/pytest-dev/pytest/pull/1461\n.. _#1468: https://github.com/pytest-dev/pytest/pull/1468\n.. _#1471: https://github.com/pytest-dev/pytest/issues/1471\n.. _#1474: https://github.com/pytest-dev/pytest/pull/1474\n.. _#1479: https://github.com/pytest-dev/pytest/issues/1479\n.. _#1502: https://github.com/pytest-dev/pytest/pull/1502\n.. _#1503: https://github.com/pytest-dev/pytest/issues/1503\n.. _#1516: https://github.com/pytest-dev/pytest/pull/1516\n.. _#1519: https://github.com/pytest-dev/pytest/pull/1519\n.. _#1520: https://github.com/pytest-dev/pytest/pull/1520\n.. _#1526: https://github.com/pytest-dev/pytest/pull/1526\n.. _#1539: https://github.com/pytest-dev/pytest/issues/1539\n.. _#1544: https://github.com/pytest-dev/pytest/issues/1544\n.. _#1546: https://github.com/pytest-dev/pytest/issues/1546\n.. _#1553: https://github.com/pytest-dev/pytest/issues/1553\n.. _#1562: https://github.com/pytest-dev/pytest/issues/1562\n.. _#1579: https://github.com/pytest-dev/pytest/issues/1579\n.. _#1580: https://github.com/pytest-dev/pytest/pull/1580\n.. _#1594: https://github.com/pytest-dev/pytest/issues/1594\n.. _#1597: https://github.com/pytest-dev/pytest/pull/1597\n.. _#1605: https://github.com/pytest-dev/pytest/issues/1605\n.. _#1616: https://github.com/pytest-dev/pytest/pull/1616\n.. _#1618: https://github.com/pytest-dev/pytest/issues/1618\n.. _#1619: https://github.com/pytest-dev/pytest/issues/1619\n.. _#1626: https://github.com/pytest-dev/pytest/pull/1626\n.. _#1627: https://github.com/pytest-dev/pytest/pull/1627\n.. _#1628: https://github.com/pytest-dev/pytest/pull/1628\n.. _#1629: https://github.com/pytest-dev/pytest/issues/1629\n.. _#1632: https://github.com/pytest-dev/pytest/issues/1632\n.. _#1633: https://github.com/pytest-dev/pytest/pull/1633\n.. _#1664: https://github.com/pytest-dev/pytest/pull/1664\n.. _#1668: https://github.com/pytest-dev/pytest/issues/1668\n.. _#1684: https://github.com/pytest-dev/pytest/pull/1684\n.. _#1723: https://github.com/pytest-dev/pytest/pull/1723\n.. _#1740: https://github.com/pytest-dev/pytest/issues/1740\n.. _#1749: https://github.com/pytest-dev/pytest/issues/1749\n.. _#1778: https://github.com/pytest-dev/pytest/pull/1778\n.. _#1795: https://github.com/pytest-dev/pytest/pull/1795\n.. _#1798: https://github.com/pytest-dev/pytest/pull/1798\n.. _#1809: https://github.com/pytest-dev/pytest/pull/1809\n.. _#372: https://github.com/pytest-dev/pytest/issues/372\n.. _#457: https://github.com/pytest-dev/pytest/issues/457\n.. _#460: https://github.com/pytest-dev/pytest/pull/460\n.. _#567: https://github.com/pytest-dev/pytest/pull/567\n.. _#607: https://github.com/pytest-dev/pytest/issues/607\n.. _#634: https://github.com/pytest-dev/pytest/issues/634\n.. _#717: https://github.com/pytest-dev/pytest/issues/717\n.. _#830: https://github.com/pytest-dev/pytest/issues/830\n.. _#925: https://github.com/pytest-dev/pytest/issues/925\n\n\n.. _@anntzer: https://github.com/anntzer\n.. _@bagerard: https://github.com/bagerard\n.. _@BeyondEvil: https://github.com/BeyondEvil\n.. _@blueyed: https://github.com/blueyed\n.. _@ceridwen: https://github.com/ceridwen\n.. _@cryporchild: https://github.com/cryporchild\n.. _@csaftoiu: https://github.com/csaftoiu\n.. _@d6e: https://github.com/d6e\n.. _@davehunt: https://github.com/davehunt\n.. _@DRMacIver: https://github.com/DRMacIver\n.. _@eolo999: https://github.com/eolo999\n.. _@fengxx: https://github.com/fengxx\n.. _@flub: https://github.com/flub\n.. _@gprasad84: https://github.com/gprasad84\n.. _@graingert: https://github.com/graingert\n.. _@hartym: https://github.com/hartym\n.. _@JonathonSonesen: https://github.com/JonathonSonesen\n.. _@kalekundert: https://github.com/kalekundert\n.. _@kvas-it: https://github.com/kvas-it\n.. _@marscher: https://github.com/marscher\n.. _@mikofski: https://github.com/mikofski\n.. _@milliams: https://github.com/milliams\n.. _@nikratio: https://github.com/nikratio\n.. _@novas0x2a: https://github.com/novas0x2a\n.. _@obestwalter: https://github.com/obestwalter\n.. _@okken: https://github.com/okken\n.. _@olegpidsadnyi: https://github.com/olegpidsadnyi\n.. _@omarkohl: https://github.com/omarkohl\n.. _@palaviv: https://github.com/palaviv\n.. _@RedBeardCode: https://github.com/RedBeardCode\n.. _@sallner: https://github.com/sallner\n.. _@sober7: https://github.com/sober7\n.. _@Stranger6667: https://github.com/Stranger6667\n.. _@suzaku: https://github.com/suzaku\n.. _@tareqalayan: https://github.com/tareqalayan\n.. _@taschini: https://github.com/taschini\n.. _@tramwaj29: https://github.com/tramwaj29\n.. _@txomon: https://github.com/txomon\n.. _@Vogtinator: https://github.com/Vogtinator\n.. _@matthiasha: https://github.com/matthiasha\n\n\n2.9.2 (2016-05-31)\n==================\n\n**Bug Fixes**\n\n* fix `#510`_: skip tests where one parameterize dimension was empty\n thanks Alex Stapleton for the Report and `@RonnyPfannschmidt`_ for the PR\n\n* Fix Xfail does not work with condition keyword argument.\n Thanks `@astraw38`_ for reporting the issue (`#1496`_) and `@tomviner`_\n for PR the (`#1524`_).\n\n* Fix win32 path issue when putting custom config file with absolute path\n in ``pytest.main(\"-c your_absolute_path\")``.\n\n* Fix maximum recursion depth detection when raised error class is not aware\n of unicode/encoded bytes.\n Thanks `@prusse-martin`_ for the PR (`#1506`_).\n\n* Fix ``pytest.mark.skip`` mark when used in strict mode.\n Thanks `@pquentin`_ for the PR and `@RonnyPfannschmidt`_ for\n showing how to fix the bug.\n\n* Minor improvements and fixes to the documentation.\n Thanks `@omarkohl`_ for the PR.\n\n* Fix ``--fixtures`` to show all fixture definitions as opposed to just\n one per fixture name.\n Thanks to `@hackebrot`_ for the PR.\n\n.. _#510: https://github.com/pytest-dev/pytest/issues/510\n.. _#1506: https://github.com/pytest-dev/pytest/pull/1506\n.. _#1496: https://github.com/pytest-dev/pytest/issues/1496\n.. _#1524: https://github.com/pytest-dev/pytest/pull/1524\n\n.. _@prusse-martin: https://github.com/prusse-martin\n.. _@astraw38: https://github.com/astraw38\n\n\n2.9.1 (2016-03-17)\n==================\n\n**Bug Fixes**\n\n* Improve error message when a plugin fails to load.\n Thanks `@nicoddemus`_ for the PR.\n\n* Fix (`#1178 `_):\n ``pytest.fail`` with non-ascii characters raises an internal pytest error.\n Thanks `@nicoddemus`_ for the PR.\n\n* Fix (`#469`_): junit parses report.nodeid incorrectly, when params IDs\n contain ``::``. Thanks `@tomviner`_ for the PR (`#1431`_).\n\n* Fix (`#578 `_): SyntaxErrors\n containing non-ascii lines at the point of failure generated an internal\n py.test error.\n Thanks `@asottile`_ for the report and `@nicoddemus`_ for the PR.\n\n* Fix (`#1437`_): When passing in a bytestring regex pattern to parameterize\n attempt to decode it as utf-8 ignoring errors.\n\n* Fix (`#649`_): parametrized test nodes cannot be specified to run on the command line.\n\n* Fix (`#138`_): better reporting for python 3.3+ chained exceptions\n\n.. _#1437: https://github.com/pytest-dev/pytest/issues/1437\n.. _#469: https://github.com/pytest-dev/pytest/issues/469\n.. _#1431: https://github.com/pytest-dev/pytest/pull/1431\n.. _#649: https://github.com/pytest-dev/pytest/issues/649\n.. _#138: https://github.com/pytest-dev/pytest/issues/138\n\n.. _@asottile: https://github.com/asottile\n\n\n2.9.0 (2016-02-29)\n==================\n\n**New Features**\n\n* New ``pytest.mark.skip`` mark, which unconditionally skips marked tests.\n Thanks `@MichaelAquilina`_ for the complete PR (`#1040`_).\n\n* ``--doctest-glob`` may now be passed multiple times in the command-line.\n Thanks `@jab`_ and `@nicoddemus`_ for the PR.\n\n* New ``-rp`` and ``-rP`` reporting options give the summary and full output\n of passing tests, respectively. Thanks to `@codewarrior0`_ for the PR.\n\n* ``pytest.mark.xfail`` now has a ``strict`` option, which makes ``XPASS``\n tests to fail the test suite (defaulting to ``False``). There's also a\n ``xfail_strict`` ini option that can be used to configure it project-wise.\n Thanks `@rabbbit`_ for the request and `@nicoddemus`_ for the PR (`#1355`_).\n\n* ``Parser.addini`` now supports options of type ``bool``.\n Thanks `@nicoddemus`_ for the PR.\n\n* New ``ALLOW_BYTES`` doctest option. This strips ``b`` prefixes from byte strings\n in doctest output (similar to ``ALLOW_UNICODE``).\n Thanks `@jaraco`_ for the request and `@nicoddemus`_ for the PR (`#1287`_).\n\n* Give a hint on ``KeyboardInterrupt`` to use the ``--fulltrace`` option to show the errors.\n Fixes `#1366`_.\n Thanks to `@hpk42`_ for the report and `@RonnyPfannschmidt`_ for the PR.\n\n* Catch ``IndexError`` exceptions when getting exception source location.\n Fixes a pytest internal error for dynamically generated code (fixtures and tests)\n where source lines are fake by intention.\n\n**Changes**\n\n* **Important**: `py.code `_ has been\n merged into the ``pytest`` repository as ``pytest._code``. This decision\n was made because ``py.code`` had very few uses outside ``pytest`` and the\n fact that it was in a different repository made it difficult to fix bugs on\n its code in a timely manner. The team hopes with this to be able to better\n refactor out and improve that code.\n This change shouldn't affect users, but it is useful to let users aware\n if they encounter any strange behavior.\n\n Keep in mind that the code for ``pytest._code`` is **private** and\n **experimental**, so you definitely should not import it explicitly!\n\n Please note that the original ``py.code`` is still available in\n `pylib `_.\n\n* ``pytest_enter_pdb`` now optionally receives the pytest config object.\n Thanks `@nicoddemus`_ for the PR.\n\n* Removed code and documentation for Python 2.5 or lower versions,\n including removal of the obsolete ``_pytest.assertion.oldinterpret`` module.\n Thanks `@nicoddemus`_ for the PR (`#1226`_).\n\n* Comparisons now always show up in full when ``CI`` or ``BUILD_NUMBER`` is\n found in the environment, even when ``-vv`` isn't used.\n Thanks `@The-Compiler`_ for the PR.\n\n* ``--lf`` and ``--ff`` now support long names: ``--last-failed`` and\n ``--failed-first`` respectively.\n Thanks `@MichaelAquilina`_ for the PR.\n\n* Added expected exceptions to ``pytest.raises`` fail message.\n\n* Collection only displays progress (\"collecting X items\") when in a terminal.\n This avoids cluttering the output when using ``--color=yes`` to obtain\n colors in CI integrations systems (`#1397`_).\n\n**Bug Fixes**\n\n* The ``-s`` and ``-c`` options should now work under ``xdist``;\n ``Config.fromdictargs`` now represents its input much more faithfully.\n Thanks to `@bukzor`_ for the complete PR (`#680`_).\n\n* Fix (`#1290`_): support Python 3.5's ``@`` operator in assertion rewriting.\n Thanks `@Shinkenjoe`_ for report with test case and `@tomviner`_ for the PR.\n\n* Fix formatting utf-8 explanation messages (`#1379`_).\n Thanks `@biern`_ for the PR.\n\n* Fix `traceback style docs`_ to describe all of the available options\n (auto/long/short/line/native/no), with ``auto`` being the default since v2.6.\n Thanks `@hackebrot`_ for the PR.\n\n* Fix (`#1422`_): junit record_xml_property doesn't allow multiple records\n with same name.\n\n.. _`traceback style docs`: https://pytest.org/latest/usage.html#modifying-python-traceback-printing\n\n.. _#1609: https://github.com/pytest-dev/pytest/issues/1609\n.. _#1422: https://github.com/pytest-dev/pytest/issues/1422\n.. _#1379: https://github.com/pytest-dev/pytest/issues/1379\n.. _#1366: https://github.com/pytest-dev/pytest/issues/1366\n.. _#1040: https://github.com/pytest-dev/pytest/pull/1040\n.. _#680: https://github.com/pytest-dev/pytest/issues/680\n.. _#1287: https://github.com/pytest-dev/pytest/pull/1287\n.. _#1226: https://github.com/pytest-dev/pytest/pull/1226\n.. _#1290: https://github.com/pytest-dev/pytest/pull/1290\n.. _#1355: https://github.com/pytest-dev/pytest/pull/1355\n.. _#1397: https://github.com/pytest-dev/pytest/issues/1397\n.. _@biern: https://github.com/biern\n.. _@MichaelAquilina: https://github.com/MichaelAquilina\n.. _@bukzor: https://github.com/bukzor\n.. _@hpk42: https://github.com/hpk42\n.. _@nicoddemus: https://github.com/nicoddemus\n.. _@jab: https://github.com/jab\n.. _@codewarrior0: https://github.com/codewarrior0\n.. _@jaraco: https://github.com/jaraco\n.. _@The-Compiler: https://github.com/The-Compiler\n.. _@Shinkenjoe: https://github.com/Shinkenjoe\n.. _@tomviner: https://github.com/tomviner\n.. _@RonnyPfannschmidt: https://github.com/RonnyPfannschmidt\n.. _@rabbbit: https://github.com/rabbbit\n.. _@hackebrot: https://github.com/hackebrot\n.. _@pquentin: https://github.com/pquentin\n.. _@ioggstream: https://github.com/ioggstream\n\n2.8.7 (2016-01-24)\n==================\n\n- fix #1338: use predictable object resolution for monkeypatch\n\n2.8.6 (2016-01-21)\n==================\n\n- fix #1259: allow for double nodeids in junitxml,\n this was a regression failing plugins combinations\n like pytest-pep8 + pytest-flakes\n\n- Workaround for exception that occurs in pyreadline when using\n ``--pdb`` with standard I/O capture enabled.\n Thanks Erik M. Bray for the PR.\n\n- fix #900: Better error message in case the target of a ``monkeypatch`` call\n raises an ``ImportError``.\n\n- fix #1292: monkeypatch calls (setattr, setenv, etc.) are now O(1).\n Thanks David R. MacIver for the report and Bruno Oliveira for the PR.\n\n- fix #1223: captured stdout and stderr are now properly displayed before\n entering pdb when ``--pdb`` is used instead of being thrown away.\n Thanks Cal Leeming for the PR.\n\n- fix #1305: pytest warnings emitted during ``pytest_terminal_summary`` are now\n properly displayed.\n Thanks Ionel Maries Cristian for the report and Bruno Oliveira for the PR.\n\n- fix #628: fixed internal UnicodeDecodeError when doctests contain unicode.\n Thanks Jason R. Coombs for the report and Bruno Oliveira for the PR.\n\n- fix #1334: Add captured stdout to jUnit XML report on setup error.\n Thanks Georgy Dyuldin for the PR.\n\n\n2.8.5 (2015-12-11)\n==================\n\n- fix #1243: fixed issue where class attributes injected during collection could break pytest.\n PR by Alexei Kozlenok, thanks Ronny Pfannschmidt and Bruno Oliveira for the review and help.\n\n- fix #1074: precompute junitxml chunks instead of storing the whole tree in objects\n Thanks Bruno Oliveira for the report and Ronny Pfannschmidt for the PR\n\n- fix #1238: fix ``pytest.deprecated_call()`` receiving multiple arguments\n (Regression introduced in 2.8.4). Thanks Alex Gaynor for the report and\n Bruno Oliveira for the PR.\n\n\n2.8.4 (2015-12-06)\n==================\n\n- fix #1190: ``deprecated_call()`` now works when the deprecated\n function has been already called by another test in the same\n module. Thanks Mikhail Chernykh for the report and Bruno Oliveira for the\n PR.\n\n- fix #1198: ``--pastebin`` option now works on Python 3. Thanks\n Mehdy Khoshnoody for the PR.\n\n- fix #1219: ``--pastebin`` now works correctly when captured output contains\n non-ascii characters. Thanks Bruno Oliveira for the PR.\n\n- fix #1204: another error when collecting with a nasty __getattr__().\n Thanks Florian Bruhin for the PR.\n\n- fix the summary printed when no tests did run.\n Thanks Florian Bruhin for the PR.\n- fix #1185 - ensure MANIFEST.in exactly matches what should go to a sdist\n\n- a number of documentation modernizations wrt good practices.\n Thanks Bruno Oliveira for the PR.\n\n2.8.3 (2015-11-18)\n==================\n\n- fix #1169: add __name__ attribute to testcases in TestCaseFunction to\n support the @unittest.skip decorator on functions and methods.\n Thanks Lee Kamentsky for the PR.\n\n- fix #1035: collecting tests if test module level obj has __getattr__().\n Thanks Suor for the report and Bruno Oliveira / Tom Viner for the PR.\n\n- fix #331: don't collect tests if their failure cannot be reported correctly\n e.g. they are a callable instance of a class.\n\n- fix #1133: fixed internal error when filtering tracebacks where one entry\n belongs to a file which is no longer available.\n Thanks Bruno Oliveira for the PR.\n\n- enhancement made to highlight in red the name of the failing tests so\n they stand out in the output.\n Thanks Gabriel Reis for the PR.\n\n- add more talks to the documentation\n- extend documentation on the --ignore cli option\n- use pytest-runner for setuptools integration\n- minor fixes for interaction with OS X El Capitan\n system integrity protection (thanks Florian)\n\n\n2.8.2 (2015-10-07)\n==================\n\n- fix #1085: proper handling of encoding errors when passing encoded byte\n strings to pytest.parametrize in Python 2.\n Thanks Themanwithoutaplan for the report and Bruno Oliveira for the PR.\n\n- fix #1087: handling SystemError when passing empty byte strings to\n pytest.parametrize in Python 3.\n Thanks Paul Kehrer for the report and Bruno Oliveira for the PR.\n\n- fix #995: fixed internal error when filtering tracebacks where one entry\n was generated by an exec() statement.\n Thanks Daniel Hahler, Ashley C Straw, Philippe Gauthier and Pavel Savchenko\n for contributing and Bruno Oliveira for the PR.\n\n- fix #1100 and #1057: errors when using autouse fixtures and doctest modules.\n Thanks Sergey B Kirpichev and Vital Kudzelka for contributing and Bruno\n Oliveira for the PR.\n\n2.8.1 (2015-09-29)\n==================\n\n- fix #1034: Add missing nodeid on pytest_logwarning call in\n addhook. Thanks Simon Gomizelj for the PR.\n\n- 'deprecated_call' is now only satisfied with a DeprecationWarning or\n PendingDeprecationWarning. Before 2.8.0, it accepted any warning, and 2.8.0\n made it accept only DeprecationWarning (but not PendingDeprecationWarning).\n Thanks Alex Gaynor for the issue and Eric Hunsberger for the PR.\n\n- fix issue #1073: avoid calling __getattr__ on potential plugin objects.\n This fixes an incompatibility with pytest-django. Thanks Andreas Pelme,\n Bruno Oliveira and Ronny Pfannschmidt for contributing and Holger Krekel\n for the fix.\n\n- Fix issue #704: handle versionconflict during plugin loading more\n gracefully. Thanks Bruno Oliveira for the PR.\n\n- Fix issue #1064: \"\"--junitxml\" regression when used with the\n \"pytest-xdist\" plugin, with test reports being assigned to the wrong tests.\n Thanks Daniel Grunwald for the report and Bruno Oliveira for the PR.\n\n- (experimental) adapt more SEMVER style versioning and change meaning of\n master branch in git repo: \"master\" branch now keeps the bugfixes, changes\n aimed for micro releases. \"features\" branch will only be released\n with minor or major pytest releases.\n\n- Fix issue #766 by removing documentation references to distutils.\n Thanks Russel Winder.\n\n- Fix issue #1030: now byte-strings are escaped to produce item node ids\n to make them always serializable.\n Thanks Andy Freeland for the report and Bruno Oliveira for the PR.\n\n- Python 2: if unicode parametrized values are convertible to ascii, their\n ascii representation is used for the node id.\n\n- Fix issue #411: Add __eq__ method to assertion comparison example.\n Thanks Ben Webb.\n- Fix issue #653: deprecated_call can be used as context manager.\n\n- fix issue 877: properly handle assertion explanations with non-ascii repr\n Thanks Mathieu Agopian for the report and Ronny Pfannschmidt for the PR.\n\n- fix issue 1029: transform errors when writing cache values into pytest-warnings\n\n2.8.0 (2015-09-18)\n==================\n\n- new ``--lf`` and ``-ff`` options to run only the last failing tests or\n \"failing tests first\" from the last run. This functionality is provided\n through porting the formerly external pytest-cache plugin into pytest core.\n BACKWARD INCOMPAT: if you used pytest-cache's functionality to persist\n data between test runs be aware that we don't serialize sets anymore.\n Thanks Ronny Pfannschmidt for most of the merging work.\n\n- \"-r\" option now accepts \"a\" to include all possible reports, similar\n to passing \"fEsxXw\" explicitly (isse960).\n Thanks Abhijeet Kasurde for the PR.\n\n- avoid python3.5 deprecation warnings by introducing version\n specific inspection helpers, thanks Michael Droettboom.\n\n- fix issue562: @nose.tools.istest now fully respected.\n\n- fix issue934: when string comparison fails and a diff is too large to display\n without passing -vv, still show a few lines of the diff.\n Thanks Florian Bruhin for the report and Bruno Oliveira for the PR.\n\n- fix issue736: Fix a bug where fixture params would be discarded when combined\n with parametrization markers.\n Thanks to Markus Unterwaditzer for the PR.\n\n- fix issue710: introduce ALLOW_UNICODE doctest option: when enabled, the\n ``u`` prefix is stripped from unicode strings in expected doctest output. This\n allows doctests which use unicode to run in Python 2 and 3 unchanged.\n Thanks Jason R. Coombs for the report and Bruno Oliveira for the PR.\n\n- parametrize now also generates meaningful test IDs for enum, regex and class\n objects (as opposed to class instances).\n Thanks to Florian Bruhin for the PR.\n\n- Add 'warns' to assert that warnings are thrown (like 'raises').\n Thanks to Eric Hunsberger for the PR.\n\n- Fix issue683: Do not apply an already applied mark. Thanks ojake for the PR.\n\n- Deal with capturing failures better so fewer exceptions get lost to\n /dev/null. Thanks David Szotten for the PR.\n\n- fix issue730: deprecate and warn about the --genscript option.\n Thanks Ronny Pfannschmidt for the report and Christian Pommranz for the PR.\n\n- fix issue751: multiple parametrize with ids bug if it parametrizes class with\n two or more test methods. Thanks Sergey Chipiga for reporting and Jan\n Bednarik for PR.\n\n- fix issue82: avoid loading conftest files from setup.cfg/pytest.ini/tox.ini\n files and upwards by default (--confcutdir can still be set to override this).\n Thanks Bruno Oliveira for the PR.\n\n- fix issue768: docstrings found in python modules were not setting up session\n fixtures. Thanks Jason R. Coombs for reporting and Bruno Oliveira for the PR.\n\n- added ``tmpdir_factory``, a session-scoped fixture that can be used to create\n directories under the base temporary directory. Previously this object was\n installed as a ``_tmpdirhandler`` attribute of the ``config`` object, but now it\n is part of the official API and using ``config._tmpdirhandler`` is\n deprecated.\n Thanks Bruno Oliveira for the PR.\n\n- fix issue808: pytest's internal assertion rewrite hook now implements the\n optional PEP302 get_data API so tests can access data files next to them.\n Thanks xmo-odoo for request and example and Bruno Oliveira for\n the PR.\n\n- rootdir and inifile are now displayed during usage errors to help\n users diagnose problems such as unexpected ini files which add\n unknown options being picked up by pytest. Thanks to Pavel Savchenko for\n bringing the problem to attention in #821 and Bruno Oliveira for the PR.\n\n- Summary bar now is colored yellow for warning\n situations such as: all tests either were skipped or xpass/xfailed,\n or no tests were run at all (this is a partial fix for issue500).\n\n- fix issue812: pytest now exits with status code 5 in situations where no\n tests were run at all, such as the directory given in the command line does\n not contain any tests or as result of a command line option filters\n all out all tests (-k for example).\n Thanks Eric Siegerman (issue812) and Bruno Oliveira for the PR.\n\n- Summary bar now is colored yellow for warning\n situations such as: all tests either were skipped or xpass/xfailed,\n or no tests were run at all (related to issue500).\n Thanks Eric Siegerman.\n\n- New ``testpaths`` ini option: list of directories to search for tests\n when executing pytest from the root directory. This can be used\n to speed up test collection when a project has well specified directories\n for tests, being usually more practical than configuring norecursedirs for\n all directories that do not contain tests.\n Thanks to Adrian for idea (#694) and Bruno Oliveira for the PR.\n\n- fix issue713: JUnit XML reports for doctest failures.\n Thanks Punyashloka Biswal.\n\n- fix issue970: internal pytest warnings now appear as \"pytest-warnings\" in\n the terminal instead of \"warnings\", so it is clear for users that those\n warnings are from pytest and not from the builtin \"warnings\" module.\n Thanks Bruno Oliveira.\n\n- Include setup and teardown in junitxml test durations.\n Thanks Janne Vanhala.\n\n- fix issue735: assertion failures on debug versions of Python 3.4+\n\n- new option ``--import-mode`` to allow to change test module importing\n behaviour to append to sys.path instead of prepending. This better allows\n to run test modules against installed versions of a package even if the\n package under test has the same import root. In this example::\n\n testing/__init__.py\n testing/test_pkg_under_test.py\n pkg_under_test/\n\n the tests will run against the installed version\n of pkg_under_test when ``--import-mode=append`` is used whereas\n by default they would always pick up the local version. Thanks Holger Krekel.\n\n- pytester: add method ``TmpTestdir.delete_loaded_modules()``, and call it\n from ``inline_run()`` to allow temporary modules to be reloaded.\n Thanks Eduardo Schettino.\n\n- internally refactor pluginmanager API and code so that there\n is a clear distinction between a pytest-agnostic rather simple\n pluginmanager and the PytestPluginManager which adds a lot of\n behaviour, among it handling of the local conftest files.\n In terms of documented methods this is a backward compatible\n change but it might still break 3rd party plugins which relied on\n details like especially the pluginmanager.add_shutdown() API.\n Thanks Holger Krekel.\n\n- pluginmanagement: introduce ``pytest.hookimpl`` and\n ``pytest.hookspec`` decorators for setting impl/spec\n specific parameters. This substitutes the previous\n now deprecated use of ``pytest.mark`` which is meant to\n contain markers for test functions only.\n\n- write/refine docs for \"writing plugins\" which now have their\n own page and are separate from the \"using/installing plugins`` page.\n\n- fix issue732: properly unregister plugins from any hook calling\n sites allowing to have temporary plugins during test execution.\n\n- deprecate and warn about ``__multicall__`` argument in hook\n implementations. Use the ``hookwrapper`` mechanism instead already\n introduced with pytest-2.7.\n\n- speed up pytest's own test suite considerably by using inprocess\n tests by default (testrun can be modified with --runpytest=subprocess\n to create subprocesses in many places instead). The main\n APIs to run pytest in a test is \"runpytest()\" or \"runpytest_subprocess\"\n and \"runpytest_inprocess\" if you need a particular way of running\n the test. In all cases you get back a RunResult but the inprocess\n one will also have a \"reprec\" attribute with the recorded events/reports.\n\n- fix monkeypatch.setattr(\"x.y\", raising=False) to actually not raise\n if \"y\" is not a pre-existing attribute. Thanks Florian Bruhin.\n\n- fix issue741: make running output from testdir.run copy/pasteable\n Thanks Bruno Oliveira.\n\n- add a new ``--noconftest`` argument which ignores all ``conftest.py`` files.\n\n- add ``file`` and ``line`` attributes to JUnit-XML output.\n\n- fix issue890: changed extension of all documentation files from ``txt`` to\n ``rst``. Thanks to Abhijeet for the PR.\n\n- fix issue714: add ability to apply indirect=True parameter on particular argnames.\n Thanks Elizaveta239.\n\n- fix issue890: changed extension of all documentation files from ``txt`` to\n ``rst``. Thanks to Abhijeet for the PR.\n\n- fix issue957: \"# doctest: SKIP\" option will now register doctests as SKIPPED\n rather than PASSED.\n Thanks Thomas Grainger for the report and Bruno Oliveira for the PR.\n\n- issue951: add new record_xml_property fixture, that supports logging\n additional information on xml output. Thanks David Diaz for the PR.\n\n- issue949: paths after normal options (for example ``-s``, ``-v``, etc) are now\n properly used to discover ``rootdir`` and ``ini`` files.\n Thanks Peter Lauri for the report and Bruno Oliveira for the PR.\n\n2.7.3 (2015-09-15)\n==================\n\n- Allow 'dev', 'rc', or other non-integer version strings in ``importorskip``.\n Thanks to Eric Hunsberger for the PR.\n\n- fix issue856: consider --color parameter in all outputs (for example\n --fixtures). Thanks Barney Gale for the report and Bruno Oliveira for the PR.\n\n- fix issue855: passing str objects as ``plugins`` argument to pytest.main\n is now interpreted as a module name to be imported and registered as a\n plugin, instead of silently having no effect.\n Thanks xmo-odoo for the report and Bruno Oliveira for the PR.\n\n- fix issue744: fix for ast.Call changes in Python 3.5+. Thanks\n Guido van Rossum, Matthias Bussonnier, Stefan Zimmermann and\n Thomas Kluyver.\n\n- fix issue842: applying markers in classes no longer propagate this markers\n to superclasses which also have markers.\n Thanks xmo-odoo for the report and Bruno Oliveira for the PR.\n\n- preserve warning functions after call to pytest.deprecated_call. Thanks\n Pieter Mulder for PR.\n\n- fix issue854: autouse yield_fixtures defined as class members of\n unittest.TestCase subclasses now work as expected.\n Thannks xmo-odoo for the report and Bruno Oliveira for the PR.\n\n- fix issue833: --fixtures now shows all fixtures of collected test files, instead of just the\n fixtures declared on the first one.\n Thanks Florian Bruhin for reporting and Bruno Oliveira for the PR.\n\n- fix issue863: skipped tests now report the correct reason when a skip/xfail\n condition is met when using multiple markers.\n Thanks Raphael Pierzina for reporting and Bruno Oliveira for the PR.\n\n- optimized tmpdir fixture initialization, which should make test sessions\n faster (specially when using pytest-xdist). The only visible effect\n is that now pytest uses a subdirectory in the $TEMP directory for all\n directories created by this fixture (defaults to $TEMP/pytest-$USER).\n Thanks Bruno Oliveira for the PR.\n\n2.7.2 (2015-06-23)\n==================\n\n- fix issue767: pytest.raises value attribute does not contain the exception\n instance on Python 2.6. Thanks Eric Siegerman for providing the test\n case and Bruno Oliveira for PR.\n\n- Automatically create directory for junitxml and results log.\n Thanks Aron Curzon.\n\n- fix issue713: JUnit XML reports for doctest failures.\n Thanks Punyashloka Biswal.\n\n- fix issue735: assertion failures on debug versions of Python 3.4+\n Thanks Benjamin Peterson.\n\n- fix issue114: skipif marker reports to internal skipping plugin;\n Thanks Floris Bruynooghe for reporting and Bruno Oliveira for the PR.\n\n- fix issue748: unittest.SkipTest reports to internal pytest unittest plugin.\n Thanks Thomas De Schampheleire for reporting and Bruno Oliveira for the PR.\n\n- fix issue718: failed to create representation of sets containing unsortable\n elements in python 2. Thanks Edison Gustavo Muenz.\n\n- fix issue756, fix issue752 (and similar issues): depend on py-1.4.29\n which has a refined algorithm for traceback generation.\n\n\n2.7.1 (2015-05-19)\n==================\n\n- fix issue731: do not get confused by the braces which may be present\n and unbalanced in an object's repr while collapsing False\n explanations. Thanks Carl Meyer for the report and test case.\n\n- fix issue553: properly handling inspect.getsourcelines failures in\n FixtureLookupError which would lead to an internal error,\n obfuscating the original problem. Thanks talljosh for initial\n diagnose/patch and Bruno Oliveira for final patch.\n\n- fix issue660: properly report scope-mismatch-access errors\n independently from ordering of fixture arguments. Also\n avoid the pytest internal traceback which does not provide\n information to the user. Thanks Holger Krekel.\n\n- streamlined and documented release process. Also all versions\n (in setup.py and documentation generation) are now read\n from _pytest/__init__.py. Thanks Holger Krekel.\n\n- fixed docs to remove the notion that yield-fixtures are experimental.\n They are here to stay :) Thanks Bruno Oliveira.\n\n- Support building wheels by using environment markers for the\n requirements. Thanks Ionel Maries Cristian.\n\n- fixed regression to 2.6.4 which surfaced e.g. in lost stdout capture printing\n when tests raised SystemExit. Thanks Holger Krekel.\n\n- reintroduced _pytest fixture of the pytester plugin which is used\n at least by pytest-xdist.\n\n2.7.0 (2015-03-26)\n==================\n\n- fix issue435: make reload() work when assert rewriting is active.\n Thanks Daniel Hahler.\n\n- fix issue616: conftest.py files and their contained fixutres are now\n properly considered for visibility, independently from the exact\n current working directory and test arguments that are used.\n Many thanks to Eric Siegerman and his PR235 which contains\n systematic tests for conftest visibility and now passes.\n This change also introduces the concept of a ``rootdir`` which\n is printed as a new pytest header and documented in the pytest\n customize web page.\n\n- change reporting of \"diverted\" tests, i.e. tests that are collected\n in one file but actually come from another (e.g. when tests in a test class\n come from a base class in a different file). We now show the nodeid\n and indicate via a postfix the other file.\n\n- add ability to set command line options by environment variable PYTEST_ADDOPTS.\n\n- added documentation on the new pytest-dev teams on bitbucket and\n github. See https://pytest.org/latest/contributing.html .\n Thanks to Anatoly for pushing and initial work on this.\n\n- fix issue650: new option ``--docttest-ignore-import-errors`` which\n will turn import errors in doctests into skips. Thanks Charles Cloud\n for the complete PR.\n\n- fix issue655: work around different ways that cause python2/3\n to leak sys.exc_info into fixtures/tests causing failures in 3rd party code\n\n- fix issue615: assertion rewriting did not correctly escape % signs\n when formatting boolean operations, which tripped over mixing\n booleans with modulo operators. Thanks to Tom Viner for the report,\n triaging and fix.\n\n- implement issue351: add ability to specify parametrize ids as a callable\n to generate custom test ids. Thanks Brianna Laugher for the idea and\n implementation.\n\n- introduce and document new hookwrapper mechanism useful for plugins\n which want to wrap the execution of certain hooks for their purposes.\n This supersedes the undocumented ``__multicall__`` protocol which\n pytest itself and some external plugins use. Note that pytest-2.8\n is scheduled to drop supporting the old ``__multicall__``\n and only support the hookwrapper protocol.\n\n- majorly speed up invocation of plugin hooks\n\n- use hookwrapper mechanism in builtin pytest plugins.\n\n- add a doctest ini option for doctest flags, thanks Holger Peters.\n\n- add note to docs that if you want to mark a parameter and the\n parameter is a callable, you also need to pass in a reason to disambiguate\n it from the \"decorator\" case. Thanks Tom Viner.\n\n- \"python_classes\" and \"python_functions\" options now support glob-patterns\n for test discovery, as discussed in issue600. Thanks Ldiary Translations.\n\n- allow to override parametrized fixtures with non-parametrized ones and vice versa (bubenkoff).\n\n- fix issue463: raise specific error for 'parameterize' misspelling (pfctdayelise).\n\n- On failure, the ``sys.last_value``, ``sys.last_type`` and\n ``sys.last_traceback`` are set, so that a user can inspect the error\n via postmortem debugging (almarklein).\n\n2.6.4 (2014-10-24)\n==================\n\n- Improve assertion failure reporting on iterables, by using ndiff and\n pprint.\n\n- removed outdated japanese docs from source tree.\n\n- docs for \"pytest_addhooks\" hook. Thanks Bruno Oliveira.\n\n- updated plugin index docs. Thanks Bruno Oliveira.\n\n- fix issue557: with \"-k\" we only allow the old style \"-\" for negation\n at the beginning of strings and even that is deprecated. Use \"not\" instead.\n This should allow to pick parametrized tests where \"-\" appeared in the parameter.\n\n- fix issue604: Escape % character in the assertion message.\n\n- fix issue620: add explanation in the --genscript target about what\n the binary blob means. Thanks Dinu Gherman.\n\n- fix issue614: fixed pastebin support.\n\n\n- fix issue620: add explanation in the --genscript target about what\n the binary blob means. Thanks Dinu Gherman.\n\n- fix issue614: fixed pastebin support.\n\n2.6.3 (2014-09-24)\n==================\n\n- fix issue575: xunit-xml was reporting collection errors as failures\n instead of errors, thanks Oleg Sinyavskiy.\n\n- fix issue582: fix setuptools example, thanks Laszlo Papp and Ronny\n Pfannschmidt.\n\n- Fix infinite recursion bug when pickling capture.EncodedFile, thanks\n Uwe Schmitt.\n\n- fix issue589: fix bad interaction with numpy and others when showing\n exceptions. Check for precise \"maximum recursion depth exceed\" exception\n instead of presuming any RuntimeError is that one (implemented in py\n dep). Thanks Charles Cloud for analysing the issue.\n\n- fix conftest related fixture visibility issue: when running with a\n CWD outside of a test package pytest would get fixture discovery wrong.\n Thanks to Wolfgang Schnerring for figuring out a reproducible example.\n\n- Introduce pytest_enter_pdb hook (needed e.g. by pytest_timeout to cancel the\n timeout when interactively entering pdb). Thanks Wolfgang Schnerring.\n\n- check xfail/skip also with non-python function test items. Thanks\n Floris Bruynooghe.\n\n2.6.2 (2014-09-05)\n==================\n\n- Added function pytest.freeze_includes(), which makes it easy to embed\n pytest into executables using tools like cx_freeze.\n See docs for examples and rationale. Thanks Bruno Oliveira.\n\n- Improve assertion rewriting cache invalidation precision.\n\n- fixed issue561: adapt autouse fixture example for python3.\n\n- fixed issue453: assertion rewriting issue with __repr__ containing\n \"\\n{\", \"\\n}\" and \"\\n~\".\n\n- fix issue560: correctly display code if an \"else:\" or \"finally:\" is\n followed by statements on the same line.\n\n- Fix example in monkeypatch documentation, thanks t-8ch.\n\n- fix issue572: correct tmpdir doc example for python3.\n\n- Do not mark as universal wheel because Python 2.6 is different from\n other builds due to the extra argparse dependency. Fixes issue566.\n Thanks sontek.\n\n- Implement issue549: user-provided assertion messages now no longer\n replace the py.test introspection message but are shown in addition\n to them.\n\n2.6.1 (2014-08-07)\n==================\n\n- No longer show line numbers in the --verbose output, the output is now\n purely the nodeid. The line number is still shown in failure reports.\n Thanks Floris Bruynooghe.\n\n- fix issue437 where assertion rewriting could cause pytest-xdist slaves\n to collect different tests. Thanks Bruno Oliveira.\n\n- fix issue555: add \"errors\" attribute to capture-streams to satisfy\n some distutils and possibly other code accessing sys.stdout.errors.\n\n- fix issue547 capsys/capfd also work when output capturing (\"-s\") is disabled.\n\n- address issue170: allow pytest.mark.xfail(...) to specify expected exceptions via\n an optional \"raises=EXC\" argument where EXC can be a single exception\n or a tuple of exception classes. Thanks David Mohr for the complete\n PR.\n\n- fix integration of pytest with unittest.mock.patch decorator when\n it uses the \"new\" argument. Thanks Nicolas Delaby for test and PR.\n\n- fix issue with detecting conftest files if the arguments contain\n \"::\" node id specifications (copy pasted from \"-v\" output)\n\n- fix issue544 by only removing \"@NUM\" at the end of \"::\" separated parts\n and if the part has a \".py\" extension\n\n- don't use py.std import helper, rather import things directly.\n Thanks Bruno Oliveira.\n\n2.6\n===\n\n- Cache exceptions from fixtures according to their scope (issue 467).\n\n- fix issue537: Avoid importing old assertion reinterpretation code by default.\n\n- fix issue364: shorten and enhance tracebacks representation by default.\n The new \"--tb=auto\" option (default) will only display long tracebacks\n for the first and last entry. You can get the old behaviour of printing\n all entries as long entries with \"--tb=long\". Also short entries by\n default are now printed very similarly to \"--tb=native\" ones.\n\n- fix issue514: teach assertion reinterpretation about private class attributes\n\n- change -v output to include full node IDs of tests. Users can copy\n a node ID from a test run, including line number, and use it as a\n positional argument in order to run only a single test.\n\n- fix issue 475: fail early and comprehensible if calling\n pytest.raises with wrong exception type.\n\n- fix issue516: tell in getting-started about current dependencies.\n\n- cleanup setup.py a bit and specify supported versions. Thanks Jurko\n Gospodnetic for the PR.\n\n- change XPASS colour to yellow rather then red when tests are run\n with -v.\n\n- fix issue473: work around mock putting an unbound method into a class\n dict when double-patching.\n\n- fix issue498: if a fixture finalizer fails, make sure that\n the fixture is still invalidated.\n\n- fix issue453: the result of the pytest_assertrepr_compare hook now gets\n it's newlines escaped so that format_exception does not blow up.\n\n- internal new warning system: pytest will now produce warnings when\n it detects oddities in your test collection or execution.\n Warnings are ultimately sent to a new pytest_logwarning hook which is\n currently only implemented by the terminal plugin which displays\n warnings in the summary line and shows more details when -rw (report on\n warnings) is specified.\n\n- change skips into warnings for test classes with an __init__ and\n callables in test modules which look like a test but are not functions.\n\n- fix issue436: improved finding of initial conftest files from command\n line arguments by using the result of parse_known_args rather than\n the previous flaky heuristics. Thanks Marc Abramowitz for tests\n and initial fixing approaches in this area.\n\n- fix issue #479: properly handle nose/unittest(2) SkipTest exceptions\n during collection/loading of test modules. Thanks to Marc Schlaich\n for the complete PR.\n\n- fix issue490: include pytest_load_initial_conftests in documentation\n and improve docstring.\n\n- fix issue472: clarify that ``pytest.config.getvalue()`` cannot work\n if it's triggered ahead of command line parsing.\n\n- merge PR123: improved integration with mock.patch decorator on tests.\n\n- fix issue412: messing with stdout/stderr FD-level streams is now\n captured without crashes.\n\n- fix issue483: trial/py33 works now properly. Thanks Daniel Grana for PR.\n\n- improve example for pytest integration with \"python setup.py test\"\n which now has a generic \"-a\" or \"--pytest-args\" option where you\n can pass additional options as a quoted string. Thanks Trevor Bekolay.\n\n- simplified internal capturing mechanism and made it more robust\n against tests or setups changing FD1/FD2, also better integrated\n now with pytest.pdb() in single tests.\n\n- improvements to pytest's own test-suite leakage detection, courtesy of PRs\n from Marc Abramowitz\n\n- fix issue492: avoid leak in test_writeorg. Thanks Marc Abramowitz.\n\n- fix issue493: don't run tests in doc directory with ``python setup.py test``\n (use tox -e doctesting for that)\n\n- fix issue486: better reporting and handling of early conftest loading failures\n\n- some cleanup and simplification of internal conftest handling.\n\n- work a bit harder to break reference cycles when catching exceptions.\n Thanks Jurko Gospodnetic.\n\n- fix issue443: fix skip examples to use proper comparison. Thanks Alex\n Groenholm.\n\n- support nose-style ``__test__`` attribute on modules, classes and\n functions, including unittest-style Classes. If set to False, the\n test will not be collected.\n\n- fix issue512: show \"\" for arguments which might not be set\n in monkeypatch plugin. Improves output in documentation.\n\n\n2.5.2 (2014-01-29)\n==================\n\n- fix issue409 -- better interoperate with cx_freeze by not\n trying to import from collections.abc which causes problems\n for py27/cx_freeze. Thanks Wolfgang L. for reporting and tracking it down.\n\n- fixed docs and code to use \"pytest\" instead of \"py.test\" almost everywhere.\n Thanks Jurko Gospodnetic for the complete PR.\n\n- fix issue425: mention at end of \"py.test -h\" that --markers\n and --fixtures work according to specified test path (or current dir)\n\n- fix issue413: exceptions with unicode attributes are now printed\n correctly also on python2 and with pytest-xdist runs. (the fix\n requires py-1.4.20)\n\n- copy, cleanup and integrate py.io capture\n from pylib 1.4.20.dev2 (rev 13d9af95547e)\n\n- address issue416: clarify docs as to conftest.py loading semantics\n\n- fix issue429: comparing byte strings with non-ascii chars in assert\n expressions now work better. Thanks Floris Bruynooghe.\n\n- make capfd/capsys.capture private, its unused and shouldn't be exposed\n\n\n2.5.1 (2013-12-17)\n==================\n\n- merge new documentation styling PR from Tobias Bieniek.\n\n- fix issue403: allow parametrize of multiple same-name functions within\n a collection node. Thanks Andreas Kloeckner and Alex Gaynor for reporting\n and analysis.\n\n- Allow parameterized fixtures to specify the ID of the parameters by\n adding an ids argument to pytest.fixture() and pytest.yield_fixture().\n Thanks Floris Bruynooghe.\n\n- fix issue404 by always using the binary xml escape in the junitxml\n plugin. Thanks Ronny Pfannschmidt.\n\n- fix issue407: fix addoption docstring to point to argparse instead of\n optparse. Thanks Daniel D. Wright.\n\n\n\n2.5.0 (2013-12-12)\n==================\n\n- dropped python2.5 from automated release testing of pytest itself\n which means it's probably going to break soon (but still works\n with this release we believe).\n\n- simplified and fixed implementation for calling finalizers when\n parametrized fixtures or function arguments are involved. finalization\n is now performed lazily at setup time instead of in the \"teardown phase\".\n While this might sound odd at first, it helps to ensure that we are\n correctly handling setup/teardown even in complex code. User-level code\n should not be affected unless it's implementing the pytest_runtest_teardown\n hook and expecting certain fixture instances are torn down within (very\n unlikely and would have been unreliable anyway).\n\n- PR90: add --color=yes|no|auto option to force terminal coloring\n mode (\"auto\" is default). Thanks Marc Abramowitz.\n\n- fix issue319 - correctly show unicode in assertion errors. Many\n thanks to Floris Bruynooghe for the complete PR. Also means\n we depend on py>=1.4.19 now.\n\n- fix issue396 - correctly sort and finalize class-scoped parametrized\n tests independently from number of methods on the class.\n\n- refix issue323 in a better way -- parametrization should now never\n cause Runtime Recursion errors because the underlying algorithm\n for re-ordering tests per-scope/per-fixture is not recursive\n anymore (it was tail-call recursive before which could lead\n to problems for more than >966 non-function scoped parameters).\n\n- fix issue290 - there is preliminary support now for parametrizing\n with repeated same values (sometimes useful to test if calling\n a second time works as with the first time).\n\n- close issue240 - document precisely how pytest module importing\n works, discuss the two common test directory layouts, and how it\n interacts with PEP420-namespace packages.\n\n- fix issue246 fix finalizer order to be LIFO on independent fixtures\n depending on a parametrized higher-than-function scoped fixture.\n (was quite some effort so please bear with the complexity of this sentence :)\n Thanks Ralph Schmitt for the precise failure example.\n\n- fix issue244 by implementing special index for parameters to only use\n indices for paramentrized test ids\n\n- fix issue287 by running all finalizers but saving the exception\n from the first failing finalizer and re-raising it so teardown will\n still have failed. We reraise the first failing exception because\n it might be the cause for other finalizers to fail.\n\n- fix ordering when mock.patch or other standard decorator-wrappings\n are used with test methods. This fixues issue346 and should\n help with random \"xdist\" collection failures. Thanks to\n Ronny Pfannschmidt and Donald Stufft for helping to isolate it.\n\n- fix issue357 - special case \"-k\" expressions to allow for\n filtering with simple strings that are not valid python expressions.\n Examples: \"-k 1.3\" matches all tests parametrized with 1.3.\n \"-k None\" filters all tests that have \"None\" in their name\n and conversely \"-k 'not None'\".\n Previously these examples would raise syntax errors.\n\n- fix issue384 by removing the trial support code\n since the unittest compat enhancements allow\n trial to handle it on its own\n\n- don't hide an ImportError when importing a plugin produces one.\n fixes issue375.\n\n- fix issue275 - allow usefixtures and autouse fixtures\n for running doctest text files.\n\n- fix issue380 by making --resultlog only rely on longrepr instead\n of the \"reprcrash\" attribute which only exists sometimes.\n\n- address issue122: allow @pytest.fixture(params=iterator) by exploding\n into a list early on.\n\n- fix pexpect-3.0 compatibility for pytest's own tests.\n (fixes issue386)\n\n- allow nested parametrize-value markers, thanks James Lan for the PR.\n\n- fix unicode handling with new monkeypatch.setattr(import_path, value)\n API. Thanks Rob Dennis. Fixes issue371.\n\n- fix unicode handling with junitxml, fixes issue368.\n\n- In assertion rewriting mode on Python 2, fix the detection of coding\n cookies. See issue #330.\n\n- make \"--runxfail\" turn imperative pytest.xfail calls into no ops\n (it already did neutralize pytest.mark.xfail markers)\n\n- refine pytest / pkg_resources interactions: The AssertionRewritingHook\n PEP302 compliant loader now registers itself with setuptools/pkg_resources\n properly so that the pkg_resources.resource_stream method works properly.\n Fixes issue366. Thanks for the investigations and full PR to Jason R. Coombs.\n\n- pytestconfig fixture is now session-scoped as it is the same object during the\n whole test run. Fixes issue370.\n\n- avoid one surprising case of marker malfunction/confusion::\n\n @pytest.mark.some(lambda arg: ...)\n def test_function():\n\n would not work correctly because pytest assumes @pytest.mark.some\n gets a function to be decorated already. We now at least detect if this\n arg is a lambda and thus the example will work. Thanks Alex Gaynor\n for bringing it up.\n\n- xfail a test on pypy that checks wrong encoding/ascii (pypy does\n not error out). fixes issue385.\n\n- internally make varnames() deal with classes's __init__,\n although it's not needed by pytest itself atm. Also\n fix caching. Fixes issue376.\n\n- fix issue221 - handle importing of namespace-package with no\n __init__.py properly.\n\n- refactor internal FixtureRequest handling to avoid monkeypatching.\n One of the positive user-facing effects is that the \"request\" object\n can now be used in closures.\n\n- fixed version comparison in pytest.importskip(modname, minverstring)\n\n- fix issue377 by clarifying in the nose-compat docs that pytest\n does not duplicate the unittest-API into the \"plain\" namespace.\n\n- fix verbose reporting for @mock'd test functions\n\n2.4.2 (2013-10-04)\n==================\n\n- on Windows require colorama and a newer py lib so that py.io.TerminalWriter()\n now uses colorama instead of its own ctypes hacks. (fixes issue365)\n thanks Paul Moore for bringing it up.\n\n- fix \"-k\" matching of tests where \"repr\" and \"attr\" and other names would\n cause wrong matches because of an internal implementation quirk\n (don't ask) which is now properly implemented. fixes issue345.\n\n- avoid tmpdir fixture to create too long filenames especially\n when parametrization is used (issue354)\n\n- fix pytest-pep8 and pytest-flakes / pytest interactions\n (collection names in mark plugin was assuming an item always\n has a function which is not true for those plugins etc.)\n Thanks Andi Zeidler.\n\n- introduce node.get_marker/node.add_marker API for plugins\n like pytest-pep8 and pytest-flakes to avoid the messy\n details of the node.keywords pseudo-dicts. Adapted\n docs.\n\n- remove attempt to \"dup\" stdout at startup as it's icky.\n the normal capturing should catch enough possibilities\n of tests messing up standard FDs.\n\n- add pluginmanager.do_configure(config) as a link to\n config.do_configure() for plugin-compatibility\n\n2.4.1 (2013-10-02)\n==================\n\n- When using parser.addoption() unicode arguments to the\n \"type\" keyword should also be converted to the respective types.\n thanks Floris Bruynooghe, @dnozay. (fixes issue360 and issue362)\n\n- fix dotted filename completion when using argcomplete\n thanks Anthon van der Neuth. (fixes issue361)\n\n- fix regression when a 1-tuple (\"arg\",) is used for specifying\n parametrization (the values of the parametrization were passed\n nested in a tuple). Thanks Donald Stufft.\n\n- merge doc typo fixes, thanks Andy Dirnberger\n\n2.4\n===\n\nknown incompatibilities:\n\n- if calling --genscript from python2.7 or above, you only get a\n standalone script which works on python2.7 or above. Use Python2.6\n to also get a python2.5 compatible version.\n\n- all xunit-style teardown methods (nose-style, pytest-style,\n unittest-style) will not be called if the corresponding setup method failed,\n see issue322 below.\n\n- the pytest_plugin_unregister hook wasn't ever properly called\n and there is no known implementation of the hook - so it got removed.\n\n- pytest.fixture-decorated functions cannot be generators (i.e. use\n yield) anymore. This change might be reversed in 2.4.1 if it causes\n unforeseen real-life issues. However, you can always write and return\n an inner function/generator and change the fixture consumer to iterate\n over the returned generator. This change was done in lieu of the new\n ``pytest.yield_fixture`` decorator, see below.\n\nnew features:\n\n- experimentally introduce a new ``pytest.yield_fixture`` decorator\n which accepts exactly the same parameters as pytest.fixture but\n mandates a ``yield`` statement instead of a ``return statement`` from\n fixture functions. This allows direct integration with \"with-style\"\n context managers in fixture functions and generally avoids registering\n of finalization callbacks in favour of treating the \"after-yield\" as\n teardown code. Thanks Andreas Pelme, Vladimir Keleshev, Floris\n Bruynooghe, Ronny Pfannschmidt and many others for discussions.\n\n- allow boolean expression directly with skipif/xfail\n if a \"reason\" is also specified. Rework skipping documentation\n to recommend \"condition as booleans\" because it prevents surprises\n when importing markers between modules. Specifying conditions\n as strings will remain fully supported.\n\n- reporting: color the last line red or green depending if\n failures/errors occurred or everything passed. thanks Christian\n Theunert.\n\n- make \"import pdb ; pdb.set_trace()\" work natively wrt capturing (no\n \"-s\" needed anymore), making ``pytest.set_trace()`` a mere shortcut.\n\n- fix issue181: --pdb now also works on collect errors (and\n on internal errors) . This was implemented by a slight internal\n refactoring and the introduction of a new hook\n ``pytest_exception_interact`` hook (see next item).\n\n- fix issue341: introduce new experimental hook for IDEs/terminals to\n intercept debugging: ``pytest_exception_interact(node, call, report)``.\n\n- new monkeypatch.setattr() variant to provide a shorter\n invocation for patching out classes/functions from modules:\n\n monkeypatch.setattr(\"requests.get\", myfunc)\n\n will replace the \"get\" function of the \"requests\" module with ``myfunc``.\n\n- fix issue322: tearDownClass is not run if setUpClass failed. Thanks\n Mathieu Agopian for the initial fix. Also make all of pytest/nose\n finalizer mimic the same generic behaviour: if a setupX exists and\n fails, don't run teardownX. This internally introduces a new method\n \"node.addfinalizer()\" helper which can only be called during the setup\n phase of a node.\n\n- simplify pytest.mark.parametrize() signature: allow to pass a\n CSV-separated string to specify argnames. For example:\n ``pytest.mark.parametrize(\"input,expected\", [(1,2), (2,3)])``\n works as well as the previous:\n ``pytest.mark.parametrize((\"input\", \"expected\"), ...)``.\n\n- add support for setUpModule/tearDownModule detection, thanks Brian Okken.\n\n- integrate tab-completion on options through use of \"argcomplete\".\n Thanks Anthon van der Neut for the PR.\n\n- change option names to be hyphen-separated long options but keep the\n old spelling backward compatible. py.test -h will only show the\n hyphenated version, for example \"--collect-only\" but \"--collectonly\"\n will remain valid as well (for backward-compat reasons). Many thanks to\n Anthon van der Neut for the implementation and to Hynek Schlawack for\n pushing us.\n\n- fix issue 308 - allow to mark/xfail/skip individual parameter sets\n when parametrizing. Thanks Brianna Laugher.\n\n- call new experimental pytest_load_initial_conftests hook to allow\n 3rd party plugins to do something before a conftest is loaded.\n\nBug fixes:\n\n- fix issue358 - capturing options are now parsed more properly\n by using a new parser.parse_known_args method.\n\n- pytest now uses argparse instead of optparse (thanks Anthon) which\n means that \"argparse\" is added as a dependency if installing into python2.6\n environments or below.\n\n- fix issue333: fix a case of bad unittest/pytest hook interaction.\n\n- PR27: correctly handle nose.SkipTest during collection. Thanks\n Antonio Cuni, Ronny Pfannschmidt.\n\n- fix issue355: junitxml puts name=\"pytest\" attribute to testsuite tag.\n\n- fix issue336: autouse fixture in plugins should work again.\n\n- fix issue279: improve object comparisons on assertion failure\n for standard datatypes and recognise collections.abc. Thanks to\n Brianna Laugher and Mathieu Agopian.\n\n- fix issue317: assertion rewriter support for the is_package method\n\n- fix issue335: document py.code.ExceptionInfo() object returned\n from pytest.raises(), thanks Mathieu Agopian.\n\n- remove implicit distribute_setup support from setup.py.\n\n- fix issue305: ignore any problems when writing pyc files.\n\n- SO-17664702: call fixture finalizers even if the fixture function\n partially failed (finalizers would not always be called before)\n\n- fix issue320 - fix class scope for fixtures when mixed with\n module-level functions. Thanks Anatloy Bubenkoff.\n\n- you can specify \"-q\" or \"-qq\" to get different levels of \"quieter\"\n reporting (thanks Katarzyna Jachim)\n\n- fix issue300 - Fix order of conftest loading when starting py.test\n in a subdirectory.\n\n- fix issue323 - sorting of many module-scoped arg parametrizations\n\n- make sessionfinish hooks execute with the same cwd-context as at\n session start (helps fix plugin behaviour which write output files\n with relative path such as pytest-cov)\n\n- fix issue316 - properly reference collection hooks in docs\n\n- fix issue 306 - cleanup of -k/-m options to only match markers/test\n names/keywords respectively. Thanks Wouter van Ackooy.\n\n- improved doctest counting for doctests in python modules --\n files without any doctest items will not show up anymore\n and doctest examples are counted as separate test items.\n thanks Danilo Bellini.\n\n- fix issue245 by depending on the released py-1.4.14\n which fixes py.io.dupfile to work with files with no\n mode. Thanks Jason R. Coombs.\n\n- fix junitxml generation when test output contains control characters,\n addressing issue267, thanks Jaap Broekhuizen\n\n- fix issue338: honor --tb style for setup/teardown errors as well. Thanks Maho.\n\n- fix issue307 - use yaml.safe_load in example, thanks Mark Eichin.\n\n- better parametrize error messages, thanks Brianna Laugher\n\n- pytest_terminal_summary(terminalreporter) hooks can now use\n \".section(title)\" and \".line(msg)\" methods to print extra\n information at the end of a test run.\n\n2.3.5 (2013-04-30)\n==================\n\n- fix issue169: respect --tb=style with setup/teardown errors as well.\n\n- never consider a fixture function for test function collection\n\n- allow re-running of test items / helps to fix pytest-reruntests plugin\n and also help to keep less fixture/resource references alive\n\n- put captured stdout/stderr into junitxml output even for passing tests\n (thanks Adam Goucher)\n\n- Issue 265 - integrate nose setup/teardown with setupstate\n so it doesn't try to teardown if it did not setup\n\n- issue 271 - don't write junitxml on slave nodes\n\n- Issue 274 - don't try to show full doctest example\n when doctest does not know the example location\n\n- issue 280 - disable assertion rewriting on buggy CPython 2.6.0\n\n- inject \"getfixture()\" helper to retrieve fixtures from doctests,\n thanks Andreas Zeidler\n\n- issue 259 - when assertion rewriting, be consistent with the default\n source encoding of ASCII on Python 2\n\n- issue 251 - report a skip instead of ignoring classes with init\n\n- issue250 unicode/str mixes in parametrization names and values now works\n\n- issue257, assertion-triggered compilation of source ending in a\n comment line doesn't blow up in python2.5 (fixed through py>=1.4.13.dev6)\n\n- fix --genscript option to generate standalone scripts that also\n work with python3.3 (importer ordering)\n\n- issue171 - in assertion rewriting, show the repr of some\n global variables\n\n- fix option help for \"-k\"\n\n- move long description of distribution into README.rst\n\n- improve docstring for metafunc.parametrize()\n\n- fix bug where using capsys with pytest.set_trace() in a test\n function would break when looking at capsys.readouterr()\n\n- allow to specify prefixes starting with \"_\" when\n customizing python_functions test discovery. (thanks Graham Horler)\n\n- improve PYTEST_DEBUG tracing output by putting\n extra data on a new lines with additional indent\n\n- ensure OutcomeExceptions like skip/fail have initialized exception attributes\n\n- issue 260 - don't use nose special setup on plain unittest cases\n\n- fix issue134 - print the collect errors that prevent running specified test items\n\n- fix issue266 - accept unicode in MarkEvaluator expressions\n\n2.3.4 (2012-11-20)\n==================\n\n- yielded test functions will now have autouse-fixtures active but\n cannot accept fixtures as funcargs - it's anyway recommended to\n rather use the post-2.0 parametrize features instead of yield, see:\n http://pytest.org/latest/example/parametrize.html\n- fix autouse-issue where autouse-fixtures would not be discovered\n if defined in an a/conftest.py file and tests in a/tests/test_some.py\n- fix issue226 - LIFO ordering for fixture teardowns\n- fix issue224 - invocations with >256 char arguments now work\n- fix issue91 - add/discuss package/directory level setups in example\n- allow to dynamically define markers via\n item.keywords[...]=assignment integrating with \"-m\" option\n- make \"-k\" accept an expressions the same as with \"-m\" so that one\n can write: -k \"name1 or name2\" etc. This is a slight incompatibility\n if you used special syntax like \"TestClass.test_method\" which you now\n need to write as -k \"TestClass and test_method\" to match a certain\n method in a certain test class.\n\n2.3.3 (2012-11-06)\n==================\n\n- fix issue214 - parse modules that contain special objects like e. g.\n flask's request object which blows up on getattr access if no request\n is active. thanks Thomas Waldmann.\n\n- fix issue213 - allow to parametrize with values like numpy arrays that\n do not support an __eq__ operator\n\n- fix issue215 - split test_python.org into multiple files\n\n- fix issue148 - @unittest.skip on classes is now recognized and avoids\n calling setUpClass/tearDownClass, thanks Pavel Repin\n\n- fix issue209 - reintroduce python2.4 support by depending on newer\n pylib which re-introduced statement-finding for pre-AST interpreters\n\n- nose support: only call setup if it's a callable, thanks Andrew\n Taumoefolau\n\n- fix issue219 - add py2.4-3.3 classifiers to TROVE list\n\n- in tracebacks *,** arg values are now shown next to normal arguments\n (thanks Manuel Jacob)\n\n- fix issue217 - support mock.patch with pytest's fixtures - note that\n you need either mock-1.0.1 or the python3.3 builtin unittest.mock.\n\n- fix issue127 - improve documentation for pytest_addoption() and\n add a ``config.getoption(name)`` helper function for consistency.\n\n2.3.2 (2012-10-25)\n==================\n\n- fix issue208 and fix issue29 use new py version to avoid long pauses\n when printing tracebacks in long modules\n\n- fix issue205 - conftests in subdirs customizing\n pytest_pycollect_makemodule and pytest_pycollect_makeitem\n now work properly\n\n- fix teardown-ordering for parametrized setups\n\n- fix issue127 - better documentation for pytest_addoption\n and related objects.\n\n- fix unittest behaviour: TestCase.runtest only called if there are\n test methods defined\n\n- improve trial support: don't collect its empty\n unittest.TestCase.runTest() method\n\n- \"python setup.py test\" now works with pytest itself\n\n- fix/improve internal/packaging related bits:\n\n - exception message check of test_nose.py now passes on python33 as well\n\n - issue206 - fix test_assertrewrite.py to work when a global\n PYTHONDONTWRITEBYTECODE=1 is present\n\n - add tox.ini to pytest distribution so that ignore-dirs and others config\n bits are properly distributed for maintainers who run pytest-own tests\n\n2.3.1 (2012-10-20)\n==================\n\n- fix issue202 - fix regression: using \"self\" from fixture functions now\n works as expected (it's the same \"self\" instance that a test method\n which uses the fixture sees)\n\n- skip pexpect using tests (test_pdb.py mostly) on freebsd* systems\n due to pexpect not supporting it properly (hanging)\n\n- link to web pages from --markers output which provides help for\n pytest.mark.* usage.\n\n2.3.0 (2012-10-19)\n==================\n\n- fix issue202 - better automatic names for parametrized test functions\n- fix issue139 - introduce @pytest.fixture which allows direct scoping\n and parametrization of funcarg factories.\n- fix issue198 - conftest fixtures were not found on windows32 in some\n circumstances with nested directory structures due to path manipulation issues\n- fix issue193 skip test functions with were parametrized with empty\n parameter sets\n- fix python3.3 compat, mostly reporting bits that previously depended\n on dict ordering\n- introduce re-ordering of tests by resource and parametrization setup\n which takes precedence to the usual file-ordering\n- fix issue185 monkeypatching time.time does not cause pytest to fail\n- fix issue172 duplicate call of pytest.fixture decoratored setup_module\n functions\n- fix junitxml=path construction so that if tests change the\n current working directory and the path is a relative path\n it is constructed correctly from the original current working dir.\n- fix \"python setup.py test\" example to cause a proper \"errno\" return\n- fix issue165 - fix broken doc links and mention stackoverflow for FAQ\n- catch unicode-issues when writing failure representations\n to terminal to prevent the whole session from crashing\n- fix xfail/skip confusion: a skip-mark or an imperative pytest.skip\n will now take precedence before xfail-markers because we\n can't determine xfail/xpass status in case of a skip. see also:\n http://stackoverflow.com/questions/11105828/in-py-test-when-i-explicitly-skip-a-test-that-is-marked-as-xfail-how-can-i-get\n\n- always report installed 3rd party plugins in the header of a test run\n\n- fix issue160: a failing setup of an xfail-marked tests should\n be reported as xfail (not xpass)\n\n- fix issue128: show captured output when capsys/capfd are used\n\n- fix issue179: properly show the dependency chain of factories\n\n- pluginmanager.register(...) now raises ValueError if the\n plugin has been already registered or the name is taken\n\n- fix issue159: improve http://pytest.org/latest/faq.html\n especially with respect to the \"magic\" history, also mention\n pytest-django, trial and unittest integration.\n\n- make request.keywords and node.keywords writable. All descendant\n collection nodes will see keyword values. Keywords are dictionaries\n containing markers and other info.\n\n- fix issue 178: xml binary escapes are now wrapped in py.xml.raw\n\n- fix issue 176: correctly catch the builtin AssertionError\n even when we replaced AssertionError with a subclass on the\n python level\n\n- factory discovery no longer fails with magic global callables\n that provide no sane __code__ object (mock.call for example)\n\n- fix issue 182: testdir.inprocess_run now considers passed plugins\n\n- fix issue 188: ensure sys.exc_info is clear on python2\n before calling into a test\n\n- fix issue 191: add unittest TestCase runTest method support\n- fix issue 156: monkeypatch correctly handles class level descriptors\n\n- reporting refinements:\n\n - pytest_report_header now receives a \"startdir\" so that\n you can use startdir.bestrelpath(yourpath) to show\n nice relative path\n\n - allow plugins to implement both pytest_report_header and\n pytest_sessionstart (sessionstart is invoked first).\n\n - don't show deselected reason line if there is none\n\n - py.test -vv will show all of assert comparisons instead of truncating\n\n2.2.4 (2012-05-22)\n==================\n\n- fix error message for rewritten assertions involving the % operator\n- fix issue 126: correctly match all invalid xml characters for junitxml\n binary escape\n- fix issue with unittest: now @unittest.expectedFailure markers should\n be processed correctly (you can also use @pytest.mark markers)\n- document integration with the extended distribute/setuptools test commands\n- fix issue 140: properly get the real functions\n of bound classmethods for setup/teardown_class\n- fix issue #141: switch from the deceased paste.pocoo.org to bpaste.net\n- fix issue #143: call unconfigure/sessionfinish always when\n configure/sessionstart where called\n- fix issue #144: better mangle test ids to junitxml classnames\n- upgrade distribute_setup.py to 0.6.27\n\n2.2.3 (2012-02-05)\n==================\n\n- fix uploaded package to only include necessary files\n\n2.2.2 (2012-02-05)\n==================\n\n- fix issue101: wrong args to unittest.TestCase test function now\n produce better output\n- fix issue102: report more useful errors and hints for when a\n test directory was renamed and some pyc/__pycache__ remain\n- fix issue106: allow parametrize to be applied multiple times\n e.g. from module, class and at function level.\n- fix issue107: actually perform session scope finalization\n- don't check in parametrize if indirect parameters are funcarg names\n- add chdir method to monkeypatch funcarg\n- fix crash resulting from calling monkeypatch undo a second time\n- fix issue115: make --collectonly robust against early failure\n (missing files/directories)\n- \"-qq --collectonly\" now shows only files and the number of tests in them\n- \"-q --collectonly\" now shows test ids\n- allow adding of attributes to test reports such that it also works\n with distributed testing (no upgrade of pytest-xdist needed)\n\n2.2.1 (2011-12-16)\n==================\n\n- fix issue99 (in pytest and py) internallerrors with resultlog now\n produce better output - fixed by normalizing pytest_internalerror\n input arguments.\n- fix issue97 / traceback issues (in pytest and py) improve traceback output\n in conjunction with jinja2 and cython which hack tracebacks\n- fix issue93 (in pytest and pytest-xdist) avoid \"delayed teardowns\":\n the final test in a test node will now run its teardown directly\n instead of waiting for the end of the session. Thanks Dave Hunt for\n the good reporting and feedback. The pytest_runtest_protocol as well\n as the pytest_runtest_teardown hooks now have \"nextitem\" available\n which will be None indicating the end of the test run.\n- fix collection crash due to unknown-source collected items, thanks\n to Ralf Schmitt (fixed by depending on a more recent pylib)\n\n2.2.0 (2011-11-18)\n==================\n\n- fix issue90: introduce eager tearing down of test items so that\n teardown function are called earlier.\n- add an all-powerful metafunc.parametrize function which allows to\n parametrize test function arguments in multiple steps and therefore\n from independent plugins and places.\n- add a @pytest.mark.parametrize helper which allows to easily\n call a test function with different argument values\n- Add examples to the \"parametrize\" example page, including a quick port\n of Test scenarios and the new parametrize function and decorator.\n- introduce registration for \"pytest.mark.*\" helpers via ini-files\n or through plugin hooks. Also introduce a \"--strict\" option which\n will treat unregistered markers as errors\n allowing to avoid typos and maintain a well described set of markers\n for your test suite. See exaples at http://pytest.org/latest/mark.html\n and its links.\n- issue50: introduce \"-m marker\" option to select tests based on markers\n (this is a stricter and more predictable version of '-k' in that \"-m\"\n only matches complete markers and has more obvious rules for and/or\n semantics.\n- new feature to help optimizing the speed of your tests:\n --durations=N option for displaying N slowest test calls\n and setup/teardown methods.\n- fix issue87: --pastebin now works with python3\n- fix issue89: --pdb with unexpected exceptions in doctest work more sensibly\n- fix and cleanup pytest's own test suite to not leak FDs\n- fix issue83: link to generated funcarg list\n- fix issue74: pyarg module names are now checked against imp.find_module false positives\n- fix compatibility with twisted/trial-11.1.0 use cases\n- simplify Node.listchain\n- simplify junitxml output code by relying on py.xml\n- add support for skip properties on unittest classes and functions\n\n2.1.3 (2011-10-18)\n==================\n\n- fix issue79: assertion rewriting failed on some comparisons in boolops\n- correctly handle zero length arguments (a la pytest '')\n- fix issue67 / junitxml now contains correct test durations, thanks ronny\n- fix issue75 / skipping test failure on jython\n- fix issue77 / Allow assertrepr_compare hook to apply to a subset of tests\n\n2.1.2 (2011-09-24)\n==================\n\n- fix assertion rewriting on files with windows newlines on some Python versions\n- refine test discovery by package/module name (--pyargs), thanks Florian Mayer\n- fix issue69 / assertion rewriting fixed on some boolean operations\n- fix issue68 / packages now work with assertion rewriting\n- fix issue66: use different assertion rewriting caches when the -O option is passed\n- don't try assertion rewriting on Jython, use reinterp\n\n2.1.1\n=====\n\n- fix issue64 / pytest.set_trace now works within pytest_generate_tests hooks\n- fix issue60 / fix error conditions involving the creation of __pycache__\n- fix issue63 / assertion rewriting on inserts involving strings containing '%'\n- fix assertion rewriting on calls with a ** arg\n- don't cache rewritten modules if bytecode generation is disabled\n- fix assertion rewriting in read-only directories\n- fix issue59: provide system-out/err tags for junitxml output\n- fix issue61: assertion rewriting on boolean operations with 3 or more operands\n- you can now build a man page with \"cd doc ; make man\"\n\n2.1.0 (2011-07-09)\n==================\n\n- fix issue53 call nosestyle setup functions with correct ordering\n- fix issue58 and issue59: new assertion code fixes\n- merge Benjamin's assertionrewrite branch: now assertions\n for test modules on python 2.6 and above are done by rewriting\n the AST and saving the pyc file before the test module is imported.\n see doc/assert.txt for more info.\n- fix issue43: improve doctests with better traceback reporting on\n unexpected exceptions\n- fix issue47: timing output in junitxml for test cases is now correct\n- fix issue48: typo in MarkInfo repr leading to exception\n- fix issue49: avoid confusing error when initizaliation partially fails\n- fix issue44: env/username expansion for junitxml file path\n- show releaselevel information in test runs for pypy\n- reworked doc pages for better navigation and PDF generation\n- report KeyboardInterrupt even if interrupted during session startup\n- fix issue 35 - provide PDF doc version and download link from index page\n\n2.0.3 (2011-05-11)\n==================\n\n- fix issue38: nicer tracebacks on calls to hooks, particularly early\n configure/sessionstart ones\n\n- fix missing skip reason/meta information in junitxml files, reported\n via http://lists.idyll.org/pipermail/testing-in-python/2011-March/003928.html\n\n- fix issue34: avoid collection failure with \"test\" prefixed classes\n deriving from object.\n\n- don't require zlib (and other libs) for genscript plugin without\n --genscript actually being used.\n\n- speed up skips (by not doing a full traceback representation\n internally)\n\n- fix issue37: avoid invalid characters in junitxml's output\n\n2.0.2 (2011-03-09)\n==================\n\n- tackle issue32 - speed up test runs of very quick test functions\n by reducing the relative overhead\n\n- fix issue30 - extended xfail/skipif handling and improved reporting.\n If you have a syntax error in your skip/xfail\n expressions you now get nice error reports.\n\n Also you can now access module globals from xfail/skipif\n expressions so that this for example works now::\n\n import pytest\n import mymodule\n @pytest.mark.skipif(\"mymodule.__version__[0] == \"1\")\n def test_function():\n pass\n\n This will not run the test function if the module's version string\n does not start with a \"1\". Note that specifying a string instead\n of a boolean expressions allows py.test to report meaningful information\n when summarizing a test run as to what conditions lead to skipping\n (or xfail-ing) tests.\n\n- fix issue28 - setup_method and pytest_generate_tests work together\n The setup_method fixture method now gets called also for\n test function invocations generated from the pytest_generate_tests\n hook.\n\n- fix issue27 - collectonly and keyword-selection (-k) now work together\n Also, if you do \"py.test --collectonly -q\" you now get a flat list\n of test ids that you can use to paste to the py.test commandline\n in order to execute a particular test.\n\n- fix issue25 avoid reported problems with --pdb and python3.2/encodings output\n\n- fix issue23 - tmpdir argument now works on Python3.2 and WindowsXP\n Starting with Python3.2 os.symlink may be supported. By requiring\n a newer py lib version the py.path.local() implementation acknowledges\n this.\n\n- fixed typos in the docs (thanks Victor Garcia, Brianna Laugher) and particular\n thanks to Laura Creighton who also reviewed parts of the documentation.\n\n- fix slightly wrong output of verbose progress reporting for classes\n (thanks Amaury)\n\n- more precise (avoiding of) deprecation warnings for node.Class|Function accesses\n\n- avoid std unittest assertion helper code in tracebacks (thanks Ronny)\n\n2.0.1 (2011-02-07)\n==================\n\n- refine and unify initial capturing so that it works nicely\n even if the logging module is used on an early-loaded conftest.py\n file or plugin.\n- allow to omit \"()\" in test ids to allow for uniform test ids\n as produced by Alfredo's nice pytest.vim plugin.\n- fix issue12 - show plugin versions with \"--version\" and\n \"--traceconfig\" and also document how to add extra information\n to reporting test header\n- fix issue17 (import-* reporting issue on python3) by\n requiring py>1.4.0 (1.4.1 is going to include it)\n- fix issue10 (numpy arrays truth checking) by refining\n assertion interpretation in py lib\n- fix issue15: make nose compatibility tests compatible\n with python3 (now that nose-1.0 supports python3)\n- remove somewhat surprising \"same-conftest\" detection because\n it ignores conftest.py when they appear in several subdirs.\n- improve assertions (\"not in\"), thanks Floris Bruynooghe\n- improve behaviour/warnings when running on top of \"python -OO\"\n (assertions and docstrings are turned off, leading to potential\n false positives)\n- introduce a pytest_cmdline_processargs(args) hook\n to allow dynamic computation of command line arguments.\n This fixes a regression because py.test prior to 2.0\n allowed to set command line options from conftest.py\n files which so far pytest-2.0 only allowed from ini-files now.\n- fix issue7: assert failures in doctest modules.\n unexpected failures in doctests will not generally\n show nicer, i.e. within the doctest failing context.\n- fix issue9: setup/teardown functions for an xfail-marked\n test will report as xfail if they fail but report as normally\n passing (not xpassing) if they succeed. This only is true\n for \"direct\" setup/teardown invocations because teardown_class/\n teardown_module cannot closely relate to a single test.\n- fix issue14: no logging errors at process exit\n- refinements to \"collecting\" output on non-ttys\n- refine internal plugin registration and --traceconfig output\n- introduce a mechanism to prevent/unregister plugins from the\n command line, see http://pytest.org/plugins.html#cmdunregister\n- activate resultlog plugin by default\n- fix regression wrt yielded tests which due to the\n collection-before-running semantics were not\n setup as with pytest 1.3.4. Note, however, that\n the recommended and much cleaner way to do test\n parametraization remains the \"pytest_generate_tests\"\n mechanism, see the docs.\n\n2.0.0 (2010-11-25)\n==================\n\n- pytest-2.0 is now its own package and depends on pylib-2.0\n- new ability: python -m pytest / python -m pytest.main ability\n- new python invocation: pytest.main(args, plugins) to load\n some custom plugins early.\n- try harder to run unittest test suites in a more compatible manner\n by deferring setup/teardown semantics to the unittest package.\n also work harder to run twisted/trial and Django tests which\n should now basically work by default.\n- introduce a new way to set config options via ini-style files,\n by default setup.cfg and tox.ini files are searched. The old\n ways (certain environment variables, dynamic conftest.py reading\n is removed).\n- add a new \"-q\" option which decreases verbosity and prints a more\n nose/unittest-style \"dot\" output.\n- fix issue135 - marks now work with unittest test cases as well\n- fix issue126 - introduce py.test.set_trace() to trace execution via\n PDB during the running of tests even if capturing is ongoing.\n- fix issue123 - new \"python -m py.test\" invocation for py.test\n (requires Python 2.5 or above)\n- fix issue124 - make reporting more resilient against tests opening\n files on filedescriptor 1 (stdout).\n- fix issue109 - sibling conftest.py files will not be loaded.\n (and Directory collectors cannot be customized anymore from a Directory's\n conftest.py - this needs to happen at least one level up).\n- introduce (customizable) assertion failure representations and enhance\n output on assertion failures for comparisons and other cases (Floris Bruynooghe)\n- nose-plugin: pass through type-signature failures in setup/teardown\n functions instead of not calling them (Ed Singleton)\n- remove py.test.collect.Directory (follows from a major refactoring\n and simplification of the collection process)\n- majorly reduce py.test core code, shift function/python testing to own plugin\n- fix issue88 (finding custom test nodes from command line arg)\n- refine 'tmpdir' creation, will now create basenames better associated\n with test names (thanks Ronny)\n- \"xpass\" (unexpected pass) tests don't cause exitcode!=0\n- fix issue131 / issue60 - importing doctests in __init__ files used as namespace packages\n- fix issue93 stdout/stderr is captured while importing conftest.py\n- fix bug: unittest collected functions now also can have \"pytestmark\"\n applied at class/module level\n- add ability to use \"class\" level for cached_setup helper\n- fix strangeness: mark.* objects are now immutable, create new instances\n\n1.3.4 (2010-09-14)\n==================\n\n- fix issue111: improve install documentation for windows\n- fix issue119: fix custom collectability of __init__.py as a module\n- fix issue116: --doctestmodules work with __init__.py files as well\n- fix issue115: unify internal exception passthrough/catching/GeneratorExit\n- fix issue118: new --tb=native for presenting cpython-standard exceptions\n\n1.3.3 (2010-07-30)\n==================\n\n- fix issue113: assertion representation problem with triple-quoted strings\n (and possibly other cases)\n- make conftest loading detect that a conftest file with the same\n content was already loaded, avoids surprises in nested directory structures\n which can be produced e.g. by Hudson. It probably removes the need to use\n --confcutdir in most cases.\n- fix terminal coloring for win32\n (thanks Michael Foord for reporting)\n- fix weirdness: make terminal width detection work on stdout instead of stdin\n (thanks Armin Ronacher for reporting)\n- remove trailing whitespace in all py/text distribution files\n\n1.3.2 (2010-07-08)\n==================\n\n**New features**\n\n- fix issue103: introduce py.test.raises as context manager, examples::\n\n with py.test.raises(ZeroDivisionError):\n x = 0\n 1 / x\n\n with py.test.raises(RuntimeError) as excinfo:\n call_something()\n\n # you may do extra checks on excinfo.value|type|traceback here\n\n (thanks Ronny Pfannschmidt)\n\n- Funcarg factories can now dynamically apply a marker to a\n test invocation. This is for example useful if a factory\n provides parameters to a test which are expected-to-fail::\n\n def pytest_funcarg__arg(request):\n request.applymarker(py.test.mark.xfail(reason=\"flaky config\"))\n ...\n\n def test_function(arg):\n ...\n\n- improved error reporting on collection and import errors. This makes\n use of a more general mechanism, namely that for custom test item/collect\n nodes ``node.repr_failure(excinfo)`` is now uniformly called so that you can\n override it to return a string error representation of your choice\n which is going to be reported as a (red) string.\n\n- introduce '--junitprefix=STR' option to prepend a prefix\n to all reports in the junitxml file.\n\n**Bug fixes**\n\n- make tests and the ``pytest_recwarn`` plugin in particular fully compatible\n to Python2.7 (if you use the ``recwarn`` funcarg warnings will be enabled so that\n you can properly check for their existence in a cross-python manner).\n- refine --pdb: ignore xfailed tests, unify its TB-reporting and\n don't display failures again at the end.\n- fix assertion interpretation with the ** operator (thanks Benjamin Peterson)\n- fix issue105 assignment on the same line as a failing assertion (thanks Benjamin Peterson)\n- fix issue104 proper escaping for test names in junitxml plugin (thanks anonymous)\n- fix issue57 -f|--looponfail to work with xpassing tests (thanks Ronny)\n- fix issue92 collectonly reporter and --pastebin (thanks Benjamin Peterson)\n- fix py.code.compile(source) to generate unique filenames\n- fix assertion re-interp problems on PyPy, by defering code\n compilation to the (overridable) Frame.eval class. (thanks Amaury Forgeot)\n- fix py.path.local.pyimport() to work with directories\n- streamline py.path.local.mkdtemp implementation and usage\n- don't print empty lines when showing junitxml-filename\n- add optional boolean ignore_errors parameter to py.path.local.remove\n- fix terminal writing on win32/python2.4\n- py.process.cmdexec() now tries harder to return properly encoded unicode objects\n on all python versions\n- install plain py.test/py.which scripts also for Jython, this helps to\n get canonical script paths in virtualenv situations\n- make path.bestrelpath(path) return \".\", note that when calling\n X.bestrelpath the assumption is that X is a directory.\n- make initial conftest discovery ignore \"--\" prefixed arguments\n- fix resultlog plugin when used in a multicpu/multihost xdist situation\n (thanks Jakub Gustak)\n- perform distributed testing related reporting in the xdist-plugin\n rather than having dist-related code in the generic py.test\n distribution\n- fix homedir detection on Windows\n- ship distribute_setup.py version 0.6.13\n\n1.3.1 (2010-05-25)\n==================\n\n**New features**\n\n- issue91: introduce new py.test.xfail(reason) helper\n to imperatively mark a test as expected to fail. Can\n be used from within setup and test functions. This is\n useful especially for parametrized tests when certain\n configurations are expected-to-fail. In this case the\n declarative approach with the @py.test.mark.xfail cannot\n be used as it would mark all configurations as xfail.\n\n- issue102: introduce new --maxfail=NUM option to stop\n test runs after NUM failures. This is a generalization\n of the '-x' or '--exitfirst' option which is now equivalent\n to '--maxfail=1'. Both '-x' and '--maxfail' will\n now also print a line near the end indicating the Interruption.\n\n- issue89: allow py.test.mark decorators to be used on classes\n (class decorators were introduced with python2.6) and\n also allow to have multiple markers applied at class/module level\n by specifying a list.\n\n- improve and refine letter reporting in the progress bar:\n . pass\n f failed test\n s skipped tests (reminder: use for dependency/platform mismatch only)\n x xfailed test (test that was expected to fail)\n X xpassed test (test that was expected to fail but passed)\n\n You can use any combination of 'fsxX' with the '-r' extended\n reporting option. The xfail/xpass results will show up as\n skipped tests in the junitxml output - which also fixes\n issue99.\n\n- make py.test.cmdline.main() return the exitstatus instead of raising\n SystemExit and also allow it to be called multiple times. This of\n course requires that your application and tests are properly teared\n down and don't have global state.\n\n**Bug Fixes**\n\n- improved traceback presentation:\n - improved and unified reporting for \"--tb=short\" option\n - Errors during test module imports are much shorter, (using --tb=short style)\n - raises shows shorter more relevant tracebacks\n - --fulltrace now more systematically makes traces longer / inhibits cutting\n\n- improve support for raises and other dynamically compiled code by\n manipulating python's linecache.cache instead of the previous\n rather hacky way of creating custom code objects. This makes\n it seemlessly work on Jython and PyPy where it previously didn't.\n\n- fix issue96: make capturing more resilient against Control-C\n interruptions (involved somewhat substantial refactoring\n to the underlying capturing functionality to avoid race\n conditions).\n\n- fix chaining of conditional skipif/xfail decorators - so it works now\n as expected to use multiple @py.test.mark.skipif(condition) decorators,\n including specific reporting which of the conditions lead to skipping.\n\n- fix issue95: late-import zlib so that it's not required\n for general py.test startup.\n\n- fix issue94: make reporting more robust against bogus source code\n (and internally be more careful when presenting unexpected byte sequences)\n\n\n1.3.0 (2010-05-05)\n==================\n\n- deprecate --report option in favour of a new shorter and easier to\n remember -r option: it takes a string argument consisting of any\n combination of 'xfsX' characters. They relate to the single chars\n you see during the dotted progress printing and will print an extra line\n per test at the end of the test run. This extra line indicates the exact\n position or test ID that you directly paste to the py.test cmdline in order\n to re-run a particular test.\n\n- allow external plugins to register new hooks via the new\n pytest_addhooks(pluginmanager) hook. The new release of\n the pytest-xdist plugin for distributed and looponfailing\n testing requires this feature.\n\n- add a new pytest_ignore_collect(path, config) hook to allow projects and\n plugins to define exclusion behaviour for their directory structure -\n for example you may define in a conftest.py this method::\n\n def pytest_ignore_collect(path):\n return path.check(link=1)\n\n to prevent even a collection try of any tests in symlinked dirs.\n\n- new pytest_pycollect_makemodule(path, parent) hook for\n allowing customization of the Module collection object for a\n matching test module.\n\n- extend and refine xfail mechanism:\n ``@py.test.mark.xfail(run=False)`` do not run the decorated test\n ``@py.test.mark.xfail(reason=\"...\")`` prints the reason string in xfail summaries\n specifying ``--runxfail`` on command line virtually ignores xfail markers\n\n- expose (previously internal) commonly useful methods:\n py.io.get_terminal_with() -> return terminal width\n py.io.ansi_print(...) -> print colored/bold text on linux/win32\n py.io.saferepr(obj) -> return limited representation string\n\n- expose test outcome related exceptions as py.test.skip.Exception,\n py.test.raises.Exception etc., useful mostly for plugins\n doing special outcome interpretation/tweaking\n\n- (issue85) fix junitxml plugin to handle tests with non-ascii output\n\n- fix/refine python3 compatibility (thanks Benjamin Peterson)\n\n- fixes for making the jython/win32 combination work, note however:\n jython2.5.1/win32 does not provide a command line launcher, see\n http://bugs.jython.org/issue1491 . See pylib install documentation\n for how to work around.\n\n- fixes for handling of unicode exception values and unprintable objects\n\n- (issue87) fix unboundlocal error in assertionold code\n\n- (issue86) improve documentation for looponfailing\n\n- refine IO capturing: stdin-redirect pseudo-file now has a NOP close() method\n\n- ship distribute_setup.py version 0.6.10\n\n- added links to the new capturelog and coverage plugins\n\n\n1.2.0 (2010-01-18)\n==================\n\n- refined usage and options for \"py.cleanup\"::\n\n py.cleanup # remove \"*.pyc\" and \"*$py.class\" (jython) files\n py.cleanup -e .swp -e .cache # also remove files with these extensions\n py.cleanup -s # remove \"build\" and \"dist\" directory next to setup.py files\n py.cleanup -d # also remove empty directories\n py.cleanup -a # synonym for \"-s -d -e 'pip-log.txt'\"\n py.cleanup -n # dry run, only show what would be removed\n\n- add a new option \"py.test --funcargs\" which shows available funcargs\n and their help strings (docstrings on their respective factory function)\n for a given test path\n\n- display a short and concise traceback if a funcarg lookup fails\n\n- early-load \"conftest.py\" files in non-dot first-level sub directories.\n allows to conveniently keep and access test-related options in a ``test``\n subdir and still add command line options.\n\n- fix issue67: new super-short traceback-printing option: \"--tb=line\" will print a single line for each failing (python) test indicating its filename, lineno and the failure value\n\n- fix issue78: always call python-level teardown functions even if the\n according setup failed. This includes refinements for calling setup_module/class functions\n which will now only be called once instead of the previous behaviour where they'd be called\n multiple times if they raise an exception (including a Skipped exception). Any exception\n will be re-corded and associated with all tests in the according module/class scope.\n\n- fix issue63: assume <40 columns to be a bogus terminal width, default to 80\n\n- fix pdb debugging to be in the correct frame on raises-related errors\n\n- update apipkg.py to fix an issue where recursive imports might\n unnecessarily break importing\n\n- fix plugin links\n\n1.1.1 (2009-11-24)\n==================\n\n- moved dist/looponfailing from py.test core into a new\n separately released pytest-xdist plugin.\n\n- new junitxml plugin: --junitxml=path will generate a junit style xml file\n which is processable e.g. by the Hudson CI system.\n\n- new option: --genscript=path will generate a standalone py.test script\n which will not need any libraries installed. thanks to Ralf Schmitt.\n\n- new option: --ignore will prevent specified path from collection.\n Can be specified multiple times.\n\n- new option: --confcutdir=dir will make py.test only consider conftest\n files that are relative to the specified dir.\n\n- new funcarg: \"pytestconfig\" is the pytest config object for access\n to command line args and can now be easily used in a test.\n\n- install ``py.test`` and ``py.which`` with a ``-$VERSION`` suffix to\n disambiguate between Python3, python2.X, Jython and PyPy installed versions.\n\n- new \"pytestconfig\" funcarg allows access to test config object\n\n- new \"pytest_report_header\" hook can return additional lines\n to be displayed at the header of a test run.\n\n- (experimental) allow \"py.test path::name1::name2::...\" for pointing\n to a test within a test collection directly. This might eventually\n evolve as a full substitute to \"-k\" specifications.\n\n- streamlined plugin loading: order is now as documented in\n customize.html: setuptools, ENV, commandline, conftest.\n also setuptools entry point names are turned to canonical namees (\"pytest_*\")\n\n- automatically skip tests that need 'capfd' but have no os.dup\n\n- allow pytest_generate_tests to be defined in classes as well\n\n- deprecate usage of 'disabled' attribute in favour of pytestmark\n- deprecate definition of Directory, Module, Class and Function nodes\n in conftest.py files. Use pytest collect hooks instead.\n\n- collection/item node specific runtest/collect hooks are only called exactly\n on matching conftest.py files, i.e. ones which are exactly below\n the filesystem path of an item\n\n- change: the first pytest_collect_directory hook to return something\n will now prevent further hooks to be called.\n\n- change: figleaf plugin now requires --figleaf to run. Also\n change its long command line options to be a bit shorter (see py.test -h).\n\n- change: pytest doctest plugin is now enabled by default and has a\n new option --doctest-glob to set a pattern for file matches.\n\n- change: remove internal py._* helper vars, only keep py._pydir\n\n- robustify capturing to survive if custom pytest_runtest_setup\n code failed and prevented the capturing setup code from running.\n\n- make py.test.* helpers provided by default plugins visible early -\n works transparently both for pydoc and for interactive sessions\n which will regularly see e.g. py.test.mark and py.test.importorskip.\n\n- simplify internal plugin manager machinery\n- simplify internal collection tree by introducing a RootCollector node\n\n- fix assert reinterpreation that sees a call containing \"keyword=...\"\n\n- fix issue66: invoke pytest_sessionstart and pytest_sessionfinish\n hooks on slaves during dist-testing, report module/session teardown\n hooks correctly.\n\n- fix issue65: properly handle dist-testing if no\n execnet/py lib installed remotely.\n\n- skip some install-tests if no execnet is available\n\n- fix docs, fix internal bin/ script generation\n\n\n1.1.0 (2009-11-05)\n==================\n\n- introduce automatic plugin registration via 'pytest11'\n entrypoints via setuptools' pkg_resources.iter_entry_points\n\n- fix py.test dist-testing to work with execnet >= 1.0.0b4\n\n- re-introduce py.test.cmdline.main() for better backward compatibility\n\n- svn paths: fix a bug with path.check(versioned=True) for svn paths,\n allow '%' in svn paths, make svnwc.update() default to interactive mode\n like in 1.0.x and add svnwc.update(interactive=False) to inhibit interaction.\n\n- refine distributed tarball to contain test and no pyc files\n\n- try harder to have deprecation warnings for py.compat.* accesses\n report a correct location\n\n1.0.3\n=====\n\n* adjust and improve docs\n\n* remove py.rest tool and internal namespace - it was\n never really advertised and can still be used with\n the old release if needed. If there is interest\n it could be revived into its own tool i guess.\n\n* fix issue48 and issue59: raise an Error if the module\n from an imported test file does not seem to come from\n the filepath - avoids \"same-name\" confusion that has\n been reported repeatedly\n\n* merged Ronny's nose-compatibility hacks: now\n nose-style setup_module() and setup() functions are\n supported\n\n* introduce generalized py.test.mark function marking\n\n* reshuffle / refine command line grouping\n\n* deprecate parser.addgroup in favour of getgroup which creates option group\n\n* add --report command line option that allows to control showing of skipped/xfailed sections\n\n* generalized skipping: a new way to mark python functions with skipif or xfail\n at function, class and modules level based on platform or sys-module attributes.\n\n* extend py.test.mark decorator to allow for positional args\n\n* introduce and test \"py.cleanup -d\" to remove empty directories\n\n* fix issue #59 - robustify unittest test collection\n\n* make bpython/help interaction work by adding an __all__ attribute\n to ApiModule, cleanup initpkg\n\n* use MIT license for pylib, add some contributors\n\n* remove py.execnet code and substitute all usages with 'execnet' proper\n\n* fix issue50 - cached_setup now caches more to expectations\n for test functions with multiple arguments.\n\n* merge Jarko's fixes, issue #45 and #46\n\n* add the ability to specify a path for py.lookup to search in\n\n* fix a funcarg cached_setup bug probably only occurring\n in distributed testing and \"module\" scope with teardown.\n\n* many fixes and changes for making the code base python3 compatible,\n many thanks to Benjamin Peterson for helping with this.\n\n* consolidate builtins implementation to be compatible with >=2.3,\n add helpers to ease keeping 2 and 3k compatible code\n\n* deprecate py.compat.doctest|subprocess|textwrap|optparse\n\n* deprecate py.magic.autopath, remove py/magic directory\n\n* move pytest assertion handling to py/code and a pytest_assertion\n plugin, add \"--no-assert\" option, deprecate py.magic namespaces\n in favour of (less) py.code ones.\n\n* consolidate and cleanup py/code classes and files\n\n* cleanup py/misc, move tests to bin-for-dist\n\n* introduce delattr/delitem/delenv methods to py.test's monkeypatch funcarg\n\n* consolidate py.log implementation, remove old approach.\n\n* introduce py.io.TextIO and py.io.BytesIO for distinguishing between\n text/unicode and byte-streams (uses underlying standard lib io.*\n if available)\n\n* make py.unittest_convert helper script available which converts \"unittest.py\"\n style files into the simpler assert/direct-test-classes py.test/nosetests\n style. The script was written by Laura Creighton.\n\n* simplified internal localpath implementation\n\n1.0.2 (2009-08-27)\n==================\n\n* fixing packaging issues, triggered by fedora redhat packaging,\n also added doc, examples and contrib dirs to the tarball.\n\n* added a documentation link to the new django plugin.\n\n1.0.1 (2009-08-19)\n==================\n\n* added a 'pytest_nose' plugin which handles nose.SkipTest,\n nose-style function/method/generator setup/teardown and\n tries to report functions correctly.\n\n* capturing of unicode writes or encoded strings to sys.stdout/err\n work better, also terminalwriting was adapted and somewhat\n unified between windows and linux.\n\n* improved documentation layout and content a lot\n\n* added a \"--help-config\" option to show conftest.py / ENV-var names for\n all longopt cmdline options, and some special conftest.py variables.\n renamed 'conf_capture' conftest setting to 'option_capture' accordingly.\n\n* fix issue #27: better reporting on non-collectable items given on commandline\n (e.g. pyc files)\n\n* fix issue #33: added --version flag (thanks Benjamin Peterson)\n\n* fix issue #32: adding support for \"incomplete\" paths to wcpath.status()\n\n* \"Test\" prefixed classes are *not* collected by default anymore if they\n have an __init__ method\n\n* monkeypatch setenv() now accepts a \"prepend\" parameter\n\n* improved reporting of collection error tracebacks\n\n* simplified multicall mechanism and plugin architecture,\n renamed some internal methods and argnames\n\n1.0.0 (2009-08-04)\n==================\n\n* more terse reporting try to show filesystem path relatively to current dir\n* improve xfail output a bit\n\n1.0.0b9 (2009-07-31)\n====================\n\n* cleanly handle and report final teardown of test setup\n\n* fix svn-1.6 compat issue with py.path.svnwc().versioned()\n (thanks Wouter Vanden Hove)\n\n* setup/teardown or collection problems now show as ERRORs\n or with big \"E\"'s in the progress lines. they are reported\n and counted separately.\n\n* dist-testing: properly handle test items that get locally\n collected but cannot be collected on the remote side - often\n due to platform/dependency reasons\n\n* simplified py.test.mark API - see keyword plugin documentation\n\n* integrate better with logging: capturing now by default captures\n test functions and their immediate setup/teardown in a single stream\n\n* capsys and capfd funcargs now have a readouterr() and a close() method\n (underlyingly py.io.StdCapture/FD objects are used which grew a\n readouterr() method as well to return snapshots of captured out/err)\n\n* make assert-reinterpretation work better with comparisons not\n returning bools (reported with numpy from thanks maciej fijalkowski)\n\n* reworked per-test output capturing into the pytest_iocapture.py plugin\n and thus removed capturing code from config object\n\n* item.repr_failure(excinfo) instead of item.repr_failure(excinfo, outerr)\n\n\n1.0.0b8 (2009-07-22)\n====================\n\n* pytest_unittest-plugin is now enabled by default\n\n* introduced pytest_keyboardinterrupt hook and\n refined pytest_sessionfinish hooked, added tests.\n\n* workaround a buggy logging module interaction (\"closing already closed\n files\"). Thanks to Sridhar Ratnakumar for triggering.\n\n* if plugins use \"py.test.importorskip\" for importing\n a dependency only a warning will be issued instead\n of exiting the testing process.\n\n* many improvements to docs:\n - refined funcargs doc , use the term \"factory\" instead of \"provider\"\n - added a new talk/tutorial doc page\n - better download page\n - better plugin docstrings\n - added new plugins page and automatic doc generation script\n\n* fixed teardown problem related to partially failing funcarg setups\n (thanks MrTopf for reporting), \"pytest_runtest_teardown\" is now\n always invoked even if the \"pytest_runtest_setup\" failed.\n\n* tweaked doctest output for docstrings in py modules,\n thanks Radomir.\n\n1.0.0b7\n=======\n\n* renamed py.test.xfail back to py.test.mark.xfail to avoid\n two ways to decorate for xfail\n\n* re-added py.test.mark decorator for setting keywords on functions\n (it was actually documented so removing it was not nice)\n\n* remove scope-argument from request.addfinalizer() because\n request.cached_setup has the scope arg. TOOWTDI.\n\n* perform setup finalization before reporting failures\n\n* apply modified patches from Andreas Kloeckner to allow\n test functions to have no func_code (#22) and to make\n \"-k\" and function keywords work (#20)\n\n* apply patch from Daniel Peolzleithner (issue #23)\n\n* resolve issue #18, multiprocessing.Manager() and\n redirection clash\n\n* make __name__ == \"__channelexec__\" for remote_exec code\n\n1.0.0b3 (2009-06-19)\n====================\n\n* plugin classes are removed: one now defines\n hooks directly in conftest.py or global pytest_*.py\n files.\n\n* added new pytest_namespace(config) hook that allows\n to inject helpers directly to the py.test.* namespace.\n\n* documented and refined many hooks\n\n* added new style of generative tests via\n pytest_generate_tests hook that integrates\n well with function arguments.\n\n\n1.0.0b1\n=======\n\n* introduced new \"funcarg\" setup method,\n see doc/test/funcarg.txt\n\n* introduced plugin architecture and many\n new py.test plugins, see\n doc/test/plugins.txt\n\n* teardown_method is now guaranteed to get\n called after a test method has run.\n\n* new method: py.test.importorskip(mod,minversion)\n will either import or call py.test.skip()\n\n* completely revised internal py.test architecture\n\n* new py.process.ForkedFunc object allowing to\n fork execution of a function to a sub process\n and getting a result back.\n\nXXX lots of things missing here XXX\n\n0.9.2\n=====\n\n* refined installation and metadata, created new setup.py,\n now based on setuptools/ez_setup (thanks to Ralf Schmitt\n for his support).\n\n* improved the way of making py.* scripts available in\n windows environments, they are now added to the\n Scripts directory as \".cmd\" files.\n\n* py.path.svnwc.status() now is more complete and\n uses xml output from the 'svn' command if available\n (Guido Wesdorp)\n\n* fix for py.path.svn* to work with svn 1.5\n (Chris Lamb)\n\n* fix path.relto(otherpath) method on windows to\n use normcase for checking if a path is relative.\n\n* py.test's traceback is better parseable from editors\n (follows the filenames:LINENO: MSG convention)\n (thanks to Osmo Salomaa)\n\n* fix to javascript-generation, \"py.test --runbrowser\"\n should work more reliably now\n\n* removed previously accidentally added\n py.test.broken and py.test.notimplemented helpers.\n\n* there now is a py.__version__ attribute\n\n0.9.1\n=====\n\nThis is a fairly complete list of v0.9.1, which can\nserve as a reference for developers.\n\n* allowing + signs in py.path.svn urls [39106]\n* fixed support for Failed exceptions without excinfo in py.test [39340]\n* added support for killing processes for Windows (as well as platforms that\n support os.kill) in py.misc.killproc [39655]\n* added setup/teardown for generative tests to py.test [40702]\n* added detection of FAILED TO LOAD MODULE to py.test [40703, 40738, 40739]\n* fixed problem with calling .remove() on wcpaths of non-versioned files in\n py.path [44248]\n* fixed some import and inheritance issues in py.test [41480, 44648, 44655]\n* fail to run greenlet tests when pypy is available, but without stackless\n [45294]\n* small fixes in rsession tests [45295]\n* fixed issue with 2.5 type representations in py.test [45483, 45484]\n* made that internal reporting issues displaying is done atomically in py.test\n [45518]\n* made that non-existing files are ignored by the py.lookup script [45519]\n* improved exception name creation in py.test [45535]\n* made that less threads are used in execnet [merge in 45539]\n* removed lock required for atomic reporting issue displaying in py.test\n [45545]\n* removed globals from execnet [45541, 45547]\n* refactored cleanup mechanics, made that setDaemon is set to 1 to make atexit\n get called in 2.5 (py.execnet) [45548]\n* fixed bug in joining threads in py.execnet's servemain [45549]\n* refactored py.test.rsession tests to not rely on exact output format anymore\n [45646]\n* using repr() on test outcome [45647]\n* added 'Reason' classes for py.test.skip() [45648, 45649]\n* killed some unnecessary sanity check in py.test.collect [45655]\n* avoid using os.tmpfile() in py.io.fdcapture because on Windows it's only\n usable by Administrators [45901]\n* added support for locking and non-recursive commits to py.path.svnwc [45994]\n* locking files in py.execnet to prevent CPython from segfaulting [46010]\n* added export() method to py.path.svnurl\n* fixed -d -x in py.test [47277]\n* fixed argument concatenation problem in py.path.svnwc [49423]\n* restore py.test behaviour that it exits with code 1 when there are failures\n [49974]\n* don't fail on html files that don't have an accompanying .txt file [50606]\n* fixed 'utestconvert.py < input' [50645]\n* small fix for code indentation in py.code.source [50755]\n* fix _docgen.py documentation building [51285]\n* improved checks for source representation of code blocks in py.test [51292]\n* added support for passing authentication to py.path.svn* objects [52000,\n 52001]\n* removed sorted() call for py.apigen tests in favour of [].sort() to support\n Python 2.3 [52481]\n"},{"col":0,"comment":"null","endLoc":284,"header":"def test_syspath_prepend_double_undo(mp)","id":6732,"name":"test_syspath_prepend_double_undo","nodeType":"Function","startLoc":275,"text":"def test_syspath_prepend_double_undo(mp):\n old_syspath = sys.path[:]\n try:\n mp.syspath_prepend(\"hello world\")\n mp.undo()\n sys.path.append(\"more hello world\")\n mp.undo()\n assert sys.path[-1] == \"more hello world\"\n finally:\n sys.path[:] = old_syspath"},{"col":0,"comment":"null","endLoc":289,"header":"def test_chdir_with_path_local(mp, tmpdir)","id":6733,"name":"test_chdir_with_path_local","nodeType":"Function","startLoc":287,"text":"def test_chdir_with_path_local(mp, tmpdir):\n mp.chdir(tmpdir)\n assert os.getcwd() == tmpdir.strpath"},{"col":4,"comment":"null","endLoc":266,"header":"def test_cleanup_lock_create(self, tmp_path)","id":6734,"name":"test_cleanup_lock_create","nodeType":"Function","startLoc":257,"text":"def test_cleanup_lock_create(self, tmp_path):\n d = tmp_path.joinpath(\"test\")\n d.mkdir()\n from _pytest.pathlib import create_cleanup_lock\n\n lockfile = create_cleanup_lock(d)\n with pytest.raises(EnvironmentError, match=\"cannot create lockfile in .*\"):\n create_cleanup_lock(d)\n\n lockfile.unlink()"},{"fileName":"test_foo.py","filePath":"testing/example_scripts/collect/collect_init_tests/tests","id":6735,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ndef test_foo():\n pass\n"},{"col":0,"comment":"null","endLoc":3,"header":"def test_foo()","id":6736,"name":"test_foo","nodeType":"Function","startLoc":2,"text":"def test_foo():\n pass"},{"col":0,"comment":"null","endLoc":294,"header":"def test_chdir_with_str(mp, tmpdir)","id":6737,"name":"test_chdir_with_str","nodeType":"Function","startLoc":292,"text":"def test_chdir_with_str(mp, tmpdir):\n mp.chdir(tmpdir.strpath)\n assert os.getcwd() == tmpdir.strpath"},{"col":0,"comment":"null","endLoc":301,"header":"def test_chdir_undo(mp, tmpdir)","id":6738,"name":"test_chdir_undo","nodeType":"Function","startLoc":297,"text":"def test_chdir_undo(mp, tmpdir):\n cwd = os.getcwd()\n mp.chdir(tmpdir)\n mp.undo()\n assert os.getcwd() == cwd"},{"col":4,"comment":"null","endLoc":290,"header":"def test_lock_register_cleanup_removal(self, tmp_path)","id":6739,"name":"test_lock_register_cleanup_removal","nodeType":"Function","startLoc":268,"text":"def test_lock_register_cleanup_removal(self, tmp_path):\n from _pytest.pathlib import create_cleanup_lock, register_cleanup_lock_removal\n\n lock = create_cleanup_lock(tmp_path)\n\n registry = []\n register_cleanup_lock_removal(lock, register=registry.append)\n\n cleanup_func, = registry\n\n assert lock.is_file()\n\n cleanup_func(original_pid=\"intentionally_different\")\n\n assert lock.is_file()\n\n cleanup_func()\n\n assert not lock.exists()\n\n cleanup_func()\n\n assert not lock.exists()"},{"col":0,"comment":"null","endLoc":56,"header":"def test_source_from_method()","id":6743,"name":"test_source_from_method","nodeType":"Function","startLoc":50,"text":"def test_source_from_method():\n class TestClass(object):\n def test_method(self):\n pass\n\n source = _pytest._code.Source(TestClass().test_method)\n assert source.lines == [\"def test_method(self):\", \" pass\"]"},{"fileName":"test_foo.py","filePath":"testing/example_scripts/config/collect_pytest_prefix","id":6744,"nodeType":"File","text":"# -*- coding: utf-8 -*-\ndef test_foo():\n pass\n"},{"col":0,"comment":"null","endLoc":3,"header":"def test_foo()","id":6745,"name":"test_foo","nodeType":"Function","startLoc":2,"text":"def test_foo():\n pass"},{"col":0,"comment":"null","endLoc":62,"header":"def test_source_from_lines()","id":6746,"name":"test_source_from_lines","nodeType":"Function","startLoc":59,"text":"def test_source_from_lines():\n lines = [\"a \\n\", \"b\\n\", \"c\"]\n source = _pytest._code.Source(lines)\n assert source.lines == [\"a \", \"b\", \"c\"]"},{"col":0,"comment":"null","endLoc":72,"header":"def test_source_from_inner_function()","id":6747,"name":"test_source_from_inner_function","nodeType":"Function","startLoc":65,"text":"def test_source_from_inner_function():\n def f():\n pass\n\n source = _pytest._code.Source(f, deindent=False)\n assert str(source).startswith(\" def f():\")\n source = _pytest._code.Source(f)\n assert str(source).startswith(\"def f():\")"},{"col":4,"comment":"null","endLoc":301,"header":"def _do_cleanup(self, tmp_path)","id":6749,"name":"_do_cleanup","nodeType":"Function","startLoc":292,"text":"def _do_cleanup(self, tmp_path):\n self.test_make(tmp_path)\n from _pytest.pathlib import cleanup_numbered_dir\n\n cleanup_numbered_dir(\n root=tmp_path,\n prefix=self.PREFIX,\n keep=2,\n consider_lock_dead_if_created_before=0,\n )"},{"col":4,"comment":"null","endLoc":306,"header":"def test_cleanup_keep(self, tmp_path)","id":6750,"name":"test_cleanup_keep","nodeType":"Function","startLoc":303,"text":"def test_cleanup_keep(self, tmp_path):\n self._do_cleanup(tmp_path)\n a, b = (x for x in tmp_path.iterdir() if not x.is_symlink())\n print(a, b)"},{"col":0,"comment":"null","endLoc":309,"header":"def test_chdir_double_undo(mp, tmpdir)","id":6751,"name":"test_chdir_double_undo","nodeType":"Function","startLoc":304,"text":"def test_chdir_double_undo(mp, tmpdir):\n mp.chdir(tmpdir.strpath)\n mp.undo()\n tmpdir.chdir()\n mp.undo()\n assert os.getcwd() == tmpdir.strpath"},{"col":4,"comment":"null","endLoc":321,"header":"def test_cleanup_locked(self, tmp_path)","id":6752,"name":"test_cleanup_locked","nodeType":"Function","startLoc":308,"text":"def test_cleanup_locked(self, tmp_path):\n\n from _pytest import pathlib\n\n p = pathlib.make_numbered_dir(root=tmp_path, prefix=self.PREFIX)\n\n pathlib.create_cleanup_lock(p)\n\n assert not pathlib.ensure_deletable(\n p, consider_lock_dead_if_created_before=p.stat().st_mtime - 1\n )\n assert pathlib.ensure_deletable(\n p, consider_lock_dead_if_created_before=p.stat().st_mtime + 1\n )"},{"col":4,"comment":"\n Returns an AST issuing a warning if the value of node is `None`.\n This is used to warn the user when asserting a function that asserts\n internally already.\n See issue #3191 for more details.\n ","endLoc":891,"header":"def warn_about_none_ast(self, node, module_path, lineno)","id":6753,"name":"warn_about_none_ast","nodeType":"Function","startLoc":866,"text":"def warn_about_none_ast(self, node, module_path, lineno):\n \"\"\"\n Returns an AST issuing a warning if the value of node is `None`.\n This is used to warn the user when asserting a function that asserts\n internally already.\n See issue #3191 for more details.\n \"\"\"\n\n # Using parse because it is different between py2 and py3.\n AST_NONE = ast.parse(\"None\").body[0].value\n val_is_none = ast.Compare(node, [ast.Is()], [AST_NONE])\n send_warning = ast.parse(\n \"\"\"\nfrom _pytest.warning_types import PytestAssertRewriteWarning\nfrom warnings import warn_explicit\nwarn_explicit(\n PytestAssertRewriteWarning('asserting the value None, please use \"assert is None\"'),\n category=None,\n filename={filename!r},\n lineno={lineno},\n)\n \"\"\".format(\n filename=module_path.strpath, lineno=lineno\n )\n ).body\n return ast.If(val_is_none, send_warning, [])"},{"col":0,"comment":"null","endLoc":327,"header":"def test_issue185_time_breaks(testdir)","id":6755,"name":"test_issue185_time_breaks","nodeType":"Function","startLoc":312,"text":"def test_issue185_time_breaks(testdir):\n testdir.makepyfile(\n \"\"\"\n import time\n def test_m(monkeypatch):\n def f():\n raise Exception\n monkeypatch.setattr(time, \"time\", f)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n \"\"\"\n *1 passed*\n \"\"\"\n )"},{"col":4,"comment":"null","endLoc":326,"header":"def test_cleanup_ignores_symlink(self, tmp_path)","id":6756,"name":"test_cleanup_ignores_symlink","nodeType":"Function","startLoc":323,"text":"def test_cleanup_ignores_symlink(self, tmp_path):\n the_symlink = tmp_path / (self.PREFIX + \"current\")\n attempt_symlink_to(the_symlink, tmp_path / (self.PREFIX + \"5\"))\n self._do_cleanup(tmp_path)"},{"col":0,"comment":"Try to make a symlink from \"path\" to \"to_path\", skipping in case this platform\n does not support it or we don't have sufficient privileges (common on Windows).","endLoc":423,"header":"def attempt_symlink_to(path, to_path)","id":6757,"name":"attempt_symlink_to","nodeType":"Function","startLoc":415,"text":"def attempt_symlink_to(path, to_path):\n \"\"\"Try to make a symlink from \"path\" to \"to_path\", skipping in case this platform\n does not support it or we don't have sufficient privileges (common on Windows).\"\"\"\n if sys.platform.startswith(\"win\") and six.PY2:\n pytest.skip(\"pathlib for some reason cannot make symlinks on Python 2\")\n try:\n Path(path).symlink_to(Path(to_path))\n except OSError:\n pytest.skip(\"could not create symbolic link\")"},{"col":0,"comment":"null","endLoc":356,"header":"def test_importerror(testdir)","id":6758,"name":"test_importerror","nodeType":"Function","startLoc":330,"text":"def test_importerror(testdir):\n p = testdir.mkpydir(\"package\")\n p.join(\"a.py\").write(\n textwrap.dedent(\n \"\"\"\\\n import doesnotexist\n\n x = 1\n \"\"\"\n )\n )\n testdir.tmpdir.join(\"test_importerror.py\").write(\n textwrap.dedent(\n \"\"\"\\\n def test_importerror(monkeypatch):\n monkeypatch.setattr('package.a.x', 2)\n \"\"\"\n )\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n \"\"\"\n *import error in package.a: No module named {0}doesnotexist{0}*\n \"\"\".format(\n \"'\" if sys.version_info > (3, 0) else \"\"\n )\n )"},{"attributeType":"str","col":0,"comment":"null","endLoc":23,"id":6759,"name":"DOCTEST_REPORT_CHOICE_NONE","nodeType":"Attribute","startLoc":23,"text":"DOCTEST_REPORT_CHOICE_NONE"},{"attributeType":"str","col":0,"comment":"null","endLoc":24,"id":6760,"name":"DOCTEST_REPORT_CHOICE_CDIFF","nodeType":"Attribute","startLoc":24,"text":"DOCTEST_REPORT_CHOICE_CDIFF"},{"attributeType":"str","col":0,"comment":"null","endLoc":25,"id":6761,"name":"DOCTEST_REPORT_CHOICE_NDIFF","nodeType":"Attribute","startLoc":25,"text":"DOCTEST_REPORT_CHOICE_NDIFF"},{"attributeType":"str","col":0,"comment":"null","endLoc":26,"id":6762,"name":"DOCTEST_REPORT_CHOICE_UDIFF","nodeType":"Attribute","startLoc":26,"text":"DOCTEST_REPORT_CHOICE_UDIFF"},{"attributeType":"str","col":0,"comment":"null","endLoc":27,"id":6763,"name":"DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE","nodeType":"Attribute","startLoc":27,"text":"DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE"},{"attributeType":"(str, str, str, str, str)","col":0,"comment":"null","endLoc":29,"id":6764,"name":"DOCTEST_REPORT_CHOICES","nodeType":"Attribute","startLoc":29,"text":"DOCTEST_REPORT_CHOICES"},{"attributeType":"None","col":0,"comment":"null","endLoc":38,"id":6765,"name":"RUNNER_CLASS","nodeType":"Attribute","startLoc":38,"text":"RUNNER_CLASS"},{"col":0,"comment":"","endLoc":2,"header":"doctest.py#","id":6766,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\" discover and run doctests in modules and test files.\"\"\"\n\nDOCTEST_REPORT_CHOICE_NONE = \"none\"\n\nDOCTEST_REPORT_CHOICE_CDIFF = \"cdiff\"\n\nDOCTEST_REPORT_CHOICE_NDIFF = \"ndiff\"\n\nDOCTEST_REPORT_CHOICE_UDIFF = \"udiff\"\n\nDOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE = \"only_first_failure\"\n\nDOCTEST_REPORT_CHOICES = (\n DOCTEST_REPORT_CHOICE_NONE,\n DOCTEST_REPORT_CHOICE_CDIFF,\n DOCTEST_REPORT_CHOICE_NDIFF,\n DOCTEST_REPORT_CHOICE_UDIFF,\n DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE,\n)\n\nRUNNER_CLASS = None"},{"col":0,"comment":"null","endLoc":392,"header":"@pytest.mark.parametrize(\n \"Sample\",\n [SampleNew, SampleNewInherit, SampleOld, SampleOldInherit],\n ids=[\"new\", \"new-inherit\", \"old\", \"old-inherit\"],\n)\ndef test_issue156_undo_staticmethod(Sample)","id":6767,"name":"test_issue156_undo_staticmethod","nodeType":"Function","startLoc":380,"text":"@pytest.mark.parametrize(\n \"Sample\",\n [SampleNew, SampleNewInherit, SampleOld, SampleOldInherit],\n ids=[\"new\", \"new-inherit\", \"old\", \"old-inherit\"],\n)\ndef test_issue156_undo_staticmethod(Sample):\n monkeypatch = MonkeyPatch()\n\n monkeypatch.setattr(Sample, \"hello\", None)\n assert Sample.hello is None\n\n monkeypatch.undo()\n assert Sample.hello()"},{"id":6768,"name":"release-3.6.4.rst","nodeType":"TextFile","path":"doc/en/announce","text":"pytest-3.6.4\n=======================================\n\npytest 3.6.4 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bernhard M. Wiedemann\n* Bruno Oliveira\n* Drew\n* E Hershey\n* Hugo Martins\n* Vlad Shcherbina\n\n\nHappy testing,\nThe pytest Development Team\n"},{"id":6769,"name":"CITATION","nodeType":"TextFile","path":"","text":"NOTE: Change \"x.y\" by the version you use. If you are unsure about which version\nyou are using run: `pip show pytest`.\n\nText:\n\n[pytest] pytest x.y, 2004\nKrekel et al., https://github.com/pytest-dev/pytest\n\nBibTeX:\n\n@misc{pytestx.y,\n title = {pytest x.y},\n author = {Krekel, Holger and Oliveira, Bruno and Pfannschmidt, Ronny and Bruynooghe, Floris and Laugher, Brianna and Bruhin, Florian},\n year = {2004},\n url = {https://github.com/pytest-dev/pytest},\n}\n"},{"fileName":"test_assertion.py","filePath":"testing","id":6770,"nodeType":"File","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nimport textwrap\n\nimport attr\nimport six\n\nimport _pytest.assertion as plugin\nimport pytest\nfrom _pytest import outcomes\nfrom _pytest.assertion import truncate\nfrom _pytest.assertion import util\n\nPY3 = sys.version_info >= (3, 0)\n\n\ndef mock_config():\n class Config(object):\n verbose = False\n\n def getoption(self, name):\n if name == \"verbose\":\n return self.verbose\n raise KeyError(\"Not mocked out: %s\" % name)\n\n return Config()\n\n\nclass TestImportHookInstallation(object):\n @pytest.mark.parametrize(\"initial_conftest\", [True, False])\n @pytest.mark.parametrize(\"mode\", [\"plain\", \"rewrite\"])\n def test_conftest_assertion_rewrite(self, testdir, initial_conftest, mode):\n \"\"\"Test that conftest files are using assertion rewrite on import.\n (#1619)\n \"\"\"\n testdir.tmpdir.join(\"foo/tests\").ensure(dir=1)\n conftest_path = \"conftest.py\" if initial_conftest else \"foo/conftest.py\"\n contents = {\n conftest_path: \"\"\"\n import pytest\n @pytest.fixture\n def check_first():\n def check(values, value):\n assert values.pop(0) == value\n return check\n \"\"\",\n \"foo/tests/test_foo.py\": \"\"\"\n def test(check_first):\n check_first([10, 30], 30)\n \"\"\",\n }\n testdir.makepyfile(**contents)\n result = testdir.runpytest_subprocess(\"--assert=%s\" % mode)\n if mode == \"plain\":\n expected = \"E AssertionError\"\n elif mode == \"rewrite\":\n expected = \"*assert 10 == 30*\"\n else:\n assert 0\n result.stdout.fnmatch_lines([expected])\n\n def test_rewrite_assertions_pytester_plugin(self, testdir):\n \"\"\"\n Assertions in the pytester plugin must also benefit from assertion\n rewriting (#1920).\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n pytest_plugins = ['pytester']\n def test_dummy_failure(testdir): # how meta!\n testdir.makepyfile('def test(): assert 0')\n r = testdir.inline_run()\n r.assertoutcome(passed=1)\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*assert 1 == 0*\"])\n\n @pytest.mark.parametrize(\"mode\", [\"plain\", \"rewrite\"])\n def test_pytest_plugins_rewrite(self, testdir, mode):\n contents = {\n \"conftest.py\": \"\"\"\n pytest_plugins = ['ham']\n \"\"\",\n \"ham.py\": \"\"\"\n import pytest\n @pytest.fixture\n def check_first():\n def check(values, value):\n assert values.pop(0) == value\n return check\n \"\"\",\n \"test_foo.py\": \"\"\"\n def test_foo(check_first):\n check_first([10, 30], 30)\n \"\"\",\n }\n testdir.makepyfile(**contents)\n result = testdir.runpytest_subprocess(\"--assert=%s\" % mode)\n if mode == \"plain\":\n expected = \"E AssertionError\"\n elif mode == \"rewrite\":\n expected = \"*assert 10 == 30*\"\n else:\n assert 0\n result.stdout.fnmatch_lines([expected])\n\n @pytest.mark.parametrize(\"mode\", [\"str\", \"list\"])\n def test_pytest_plugins_rewrite_module_names(self, testdir, mode):\n \"\"\"Test that pluginmanager correct marks pytest_plugins variables\n for assertion rewriting if they are defined as plain strings or\n list of strings (#1888).\n \"\"\"\n plugins = '\"ham\"' if mode == \"str\" else '[\"ham\"]'\n contents = {\n \"conftest.py\": \"\"\"\n pytest_plugins = {plugins}\n \"\"\".format(\n plugins=plugins\n ),\n \"ham.py\": \"\"\"\n import pytest\n \"\"\",\n \"test_foo.py\": \"\"\"\n def test_foo(pytestconfig):\n assert 'ham' in pytestconfig.pluginmanager.rewrite_hook._must_rewrite\n \"\"\",\n }\n testdir.makepyfile(**contents)\n result = testdir.runpytest_subprocess(\"--assert=rewrite\")\n assert result.ret == 0\n\n def test_pytest_plugins_rewrite_module_names_correctly(self, testdir):\n \"\"\"Test that we match files correctly when they are marked for rewriting (#2939).\"\"\"\n contents = {\n \"conftest.py\": \"\"\"\\\n pytest_plugins = \"ham\"\n \"\"\",\n \"ham.py\": \"\",\n \"hamster.py\": \"\",\n \"test_foo.py\": \"\"\"\\\n def test_foo(pytestconfig):\n assert pytestconfig.pluginmanager.rewrite_hook.find_module('ham') is not None\n assert pytestconfig.pluginmanager.rewrite_hook.find_module('hamster') is None\n \"\"\",\n }\n testdir.makepyfile(**contents)\n result = testdir.runpytest_subprocess(\"--assert=rewrite\")\n assert result.ret == 0\n\n @pytest.mark.parametrize(\"mode\", [\"plain\", \"rewrite\"])\n def test_installed_plugin_rewrite(self, testdir, mode, monkeypatch):\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n # Make sure the hook is installed early enough so that plugins\n # installed via setuptools are rewritten.\n testdir.tmpdir.join(\"hampkg\").ensure(dir=1)\n contents = {\n \"hampkg/__init__.py\": \"\"\"\\\n import pytest\n\n @pytest.fixture\n def check_first2():\n def check(values, value):\n assert values.pop(0) == value\n return check\n \"\"\",\n \"spamplugin.py\": \"\"\"\\\n import pytest\n from hampkg import check_first2\n\n @pytest.fixture\n def check_first():\n def check(values, value):\n assert values.pop(0) == value\n return check\n \"\"\",\n \"mainwrapper.py\": \"\"\"\\\n import pytest, importlib_metadata\n\n class DummyEntryPoint(object):\n name = 'spam'\n module_name = 'spam.py'\n group = 'pytest11'\n\n def load(self):\n import spamplugin\n return spamplugin\n\n class DummyDistInfo(object):\n version = '1.0'\n files = ('spamplugin.py', 'hampkg/__init__.py')\n entry_points = (DummyEntryPoint(),)\n metadata = {'name': 'foo'}\n\n def distributions():\n return (DummyDistInfo(),)\n\n importlib_metadata.distributions = distributions\n pytest.main()\n \"\"\",\n \"test_foo.py\": \"\"\"\\\n def test(check_first):\n check_first([10, 30], 30)\n\n def test2(check_first2):\n check_first([10, 30], 30)\n \"\"\",\n }\n testdir.makepyfile(**contents)\n result = testdir.run(\n sys.executable, \"mainwrapper.py\", \"-s\", \"--assert=%s\" % mode\n )\n if mode == \"plain\":\n expected = \"E AssertionError\"\n elif mode == \"rewrite\":\n expected = \"*assert 10 == 30*\"\n else:\n assert 0\n result.stdout.fnmatch_lines([expected])\n\n def test_rewrite_ast(self, testdir):\n testdir.tmpdir.join(\"pkg\").ensure(dir=1)\n contents = {\n \"pkg/__init__.py\": \"\"\"\n import pytest\n pytest.register_assert_rewrite('pkg.helper')\n \"\"\",\n \"pkg/helper.py\": \"\"\"\n def tool():\n a, b = 2, 3\n assert a == b\n \"\"\",\n \"pkg/plugin.py\": \"\"\"\n import pytest, pkg.helper\n @pytest.fixture\n def tool():\n return pkg.helper.tool\n \"\"\",\n \"pkg/other.py\": \"\"\"\n values = [3, 2]\n def tool():\n assert values.pop() == 3\n \"\"\",\n \"conftest.py\": \"\"\"\n pytest_plugins = ['pkg.plugin']\n \"\"\",\n \"test_pkg.py\": \"\"\"\n import pkg.other\n def test_tool(tool):\n tool()\n def test_other():\n pkg.other.tool()\n \"\"\",\n }\n testdir.makepyfile(**contents)\n result = testdir.runpytest_subprocess(\"--assert=rewrite\")\n result.stdout.fnmatch_lines(\n [\n \">*assert a == b*\",\n \"E*assert 2 == 3*\",\n \">*assert values.pop() == 3*\",\n \"E*AssertionError\",\n ]\n )\n\n def test_register_assert_rewrite_checks_types(self):\n with pytest.raises(TypeError):\n pytest.register_assert_rewrite([\"pytest_tests_internal_non_existing\"])\n pytest.register_assert_rewrite(\n \"pytest_tests_internal_non_existing\", \"pytest_tests_internal_non_existing2\"\n )\n\n\nclass TestBinReprIntegration(object):\n def test_pytest_assertrepr_compare_called(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n values = []\n def pytest_assertrepr_compare(op, left, right):\n values.append((op, left, right))\n\n @pytest.fixture\n def list(request):\n return values\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n assert 0 == 1\n def test_check(list):\n assert list == [(\"==\", 0, 1)]\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines([\"*test_hello*FAIL*\", \"*test_check*PASS*\"])\n\n\ndef callequal(left, right, verbose=False):\n config = mock_config()\n config.verbose = verbose\n return plugin.pytest_assertrepr_compare(config, \"==\", left, right)\n\n\nclass TestAssert_reprcompare(object):\n def test_different_types(self):\n assert callequal([0, 1], \"foo\") is None\n\n def test_summary(self):\n summary = callequal([0, 1], [0, 2])[0]\n assert len(summary) < 65\n\n def test_text_diff(self):\n diff = callequal(\"spam\", \"eggs\")[1:]\n assert \"- spam\" in diff\n assert \"+ eggs\" in diff\n\n def test_text_skipping(self):\n lines = callequal(\"a\" * 50 + \"spam\", \"a\" * 50 + \"eggs\")\n assert \"Skipping\" in lines[1]\n for line in lines:\n assert \"a\" * 50 not in line\n\n def test_text_skipping_verbose(self):\n lines = callequal(\"a\" * 50 + \"spam\", \"a\" * 50 + \"eggs\", verbose=True)\n assert \"- \" + \"a\" * 50 + \"spam\" in lines\n assert \"+ \" + \"a\" * 50 + \"eggs\" in lines\n\n def test_multiline_text_diff(self):\n left = \"foo\\nspam\\nbar\"\n right = \"foo\\neggs\\nbar\"\n diff = callequal(left, right)\n assert \"- spam\" in diff\n assert \"+ eggs\" in diff\n\n def test_list(self):\n expl = callequal([0, 1], [0, 2])\n assert len(expl) > 1\n\n @pytest.mark.parametrize(\n [\"left\", \"right\", \"expected\"],\n [\n (\n [0, 1],\n [0, 2],\n \"\"\"\n Full diff:\n - [0, 1]\n ? ^\n + [0, 2]\n ? ^\n \"\"\",\n ),\n (\n {0: 1},\n {0: 2},\n \"\"\"\n Full diff:\n - {0: 1}\n ? ^\n + {0: 2}\n ? ^\n \"\"\",\n ),\n (\n {0, 1},\n {0, 2},\n \"\"\"\n Full diff:\n - set([0, 1])\n ? ^\n + set([0, 2])\n ? ^\n \"\"\"\n if not PY3\n else \"\"\"\n Full diff:\n - {0, 1}\n ? ^\n + {0, 2}\n ? ^\n \"\"\",\n ),\n ],\n )\n def test_iterable_full_diff(self, left, right, expected):\n \"\"\"Test the full diff assertion failure explanation.\n\n When verbose is False, then just a -v notice to get the diff is rendered,\n when verbose is True, then ndiff of the pprint is returned.\n \"\"\"\n expl = callequal(left, right, verbose=False)\n assert expl[-1] == \"Use -v to get the full diff\"\n expl = \"\\n\".join(callequal(left, right, verbose=True))\n assert expl.endswith(textwrap.dedent(expected).strip())\n\n def test_list_different_lengths(self):\n expl = callequal([0, 1], [0, 1, 2])\n assert len(expl) > 1\n expl = callequal([0, 1, 2], [0, 1])\n assert len(expl) > 1\n\n def test_dict(self):\n expl = callequal({\"a\": 0}, {\"a\": 1})\n assert len(expl) > 1\n\n def test_dict_omitting(self):\n lines = callequal({\"a\": 0, \"b\": 1}, {\"a\": 1, \"b\": 1})\n assert lines[1].startswith(\"Omitting 1 identical item\")\n assert \"Common items\" not in lines\n for line in lines[1:]:\n assert \"b\" not in line\n\n def test_dict_omitting_with_verbosity_1(self):\n \"\"\" Ensure differing items are visible for verbosity=1 (#1512) \"\"\"\n lines = callequal({\"a\": 0, \"b\": 1}, {\"a\": 1, \"b\": 1}, verbose=1)\n assert lines[1].startswith(\"Omitting 1 identical item\")\n assert lines[2].startswith(\"Differing items\")\n assert lines[3] == \"{'a': 0} != {'a': 1}\"\n assert \"Common items\" not in lines\n\n def test_dict_omitting_with_verbosity_2(self):\n lines = callequal({\"a\": 0, \"b\": 1}, {\"a\": 1, \"b\": 1}, verbose=2)\n assert lines[1].startswith(\"Common items:\")\n assert \"Omitting\" not in lines[1]\n assert lines[2] == \"{'b': 1}\"\n\n def test_dict_different_items(self):\n lines = callequal({\"a\": 0}, {\"b\": 1, \"c\": 2}, verbose=2)\n assert lines == [\n \"{'a': 0} == {'b': 1, 'c': 2}\",\n \"Left contains 1 more item:\",\n \"{'a': 0}\",\n \"Right contains 2 more items:\",\n \"{'b': 1, 'c': 2}\",\n \"Full diff:\",\n \"- {'a': 0}\",\n \"+ {'b': 1, 'c': 2}\",\n ]\n lines = callequal({\"b\": 1, \"c\": 2}, {\"a\": 0}, verbose=2)\n assert lines == [\n \"{'b': 1, 'c': 2} == {'a': 0}\",\n \"Left contains 2 more items:\",\n \"{'b': 1, 'c': 2}\",\n \"Right contains 1 more item:\",\n \"{'a': 0}\",\n \"Full diff:\",\n \"- {'b': 1, 'c': 2}\",\n \"+ {'a': 0}\",\n ]\n\n def test_sequence_different_items(self):\n lines = callequal((1, 2), (3, 4, 5), verbose=2)\n assert lines == [\n \"(1, 2) == (3, 4, 5)\",\n \"At index 0 diff: 1 != 3\",\n \"Right contains one more item: 5\",\n \"Full diff:\",\n \"- (1, 2)\",\n \"+ (3, 4, 5)\",\n ]\n lines = callequal((1, 2, 3), (4,), verbose=2)\n assert lines == [\n \"(1, 2, 3) == (4,)\",\n \"At index 0 diff: 1 != 4\",\n \"Left contains 2 more items, first extra item: 2\",\n \"Full diff:\",\n \"- (1, 2, 3)\",\n \"+ (4,)\",\n ]\n\n def test_set(self):\n expl = callequal({0, 1}, {0, 2})\n assert len(expl) > 1\n\n def test_frozenzet(self):\n expl = callequal(frozenset([0, 1]), {0, 2})\n assert len(expl) > 1\n\n def test_Sequence(self):\n if sys.version_info >= (3, 3):\n import collections.abc as collections_abc\n else:\n import collections as collections_abc\n if not hasattr(collections_abc, \"MutableSequence\"):\n pytest.skip(\"cannot import MutableSequence\")\n MutableSequence = collections_abc.MutableSequence\n\n class TestSequence(MutableSequence): # works with a Sequence subclass\n def __init__(self, iterable):\n self.elements = list(iterable)\n\n def __getitem__(self, item):\n return self.elements[item]\n\n def __len__(self):\n return len(self.elements)\n\n def __setitem__(self, item, value):\n pass\n\n def __delitem__(self, item):\n pass\n\n def insert(self, item, index):\n pass\n\n expl = callequal(TestSequence([0, 1]), list([0, 2]))\n assert len(expl) > 1\n\n def test_list_tuples(self):\n expl = callequal([], [(1, 2)])\n assert len(expl) > 1\n expl = callequal([(1, 2)], [])\n assert len(expl) > 1\n\n def test_repr_verbose(self):\n class Nums:\n def __init__(self, nums):\n self.nums = nums\n\n def __repr__(self):\n return str(self.nums)\n\n list_x = list(range(5000))\n list_y = list(range(5000))\n list_y[len(list_y) // 2] = 3\n nums_x = Nums(list_x)\n nums_y = Nums(list_y)\n\n assert callequal(nums_x, nums_y) is None\n\n expl = callequal(nums_x, nums_y, verbose=1)\n assert \"-\" + repr(nums_x) in expl\n assert \"+\" + repr(nums_y) in expl\n\n expl = callequal(nums_x, nums_y, verbose=2)\n assert \"-\" + repr(nums_x) in expl\n assert \"+\" + repr(nums_y) in expl\n\n def test_list_bad_repr(self):\n class A(object):\n def __repr__(self):\n raise ValueError(42)\n\n expl = callequal([], [A()])\n assert \"ValueError\" in \"\".join(expl)\n expl = callequal({}, {\"1\": A()})\n assert \"faulty\" in \"\".join(expl)\n\n def test_one_repr_empty(self):\n \"\"\"\n the faulty empty string repr did trigger\n an unbound local error in _diff_text\n \"\"\"\n\n class A(str):\n def __repr__(self):\n return \"\"\n\n expl = callequal(A(), \"\")\n assert not expl\n\n def test_repr_no_exc(self):\n expl = \" \".join(callequal(\"foo\", \"bar\"))\n assert \"raised in repr()\" not in expl\n\n def test_unicode(self):\n left = u\"£€\"\n right = u\"£\"\n expl = callequal(left, right)\n assert expl[0] == u\"'£€' == '£'\"\n assert expl[1] == u\"- £€\"\n assert expl[2] == u\"+ £\"\n\n def test_nonascii_text(self):\n \"\"\"\n :issue: 877\n non ascii python2 str caused a UnicodeDecodeError\n \"\"\"\n\n class A(str):\n def __repr__(self):\n return \"\\xff\"\n\n expl = callequal(A(), \"1\")\n if PY3:\n assert expl == [\"ÿ == '1'\", \"+ 1\"]\n else:\n assert expl == [u\"\\ufffd == '1'\", u\"+ 1\"]\n\n def test_format_nonascii_explanation(self):\n assert util.format_explanation(\"λ\")\n\n def test_mojibake(self):\n # issue 429\n left = b\"e\"\n right = b\"\\xc3\\xa9\"\n expl = callequal(left, right)\n for line in expl:\n assert isinstance(line, six.text_type)\n msg = u\"\\n\".join(expl)\n assert msg\n\n\nclass TestAssert_reprcompare_dataclass(object):\n @pytest.mark.skipif(sys.version_info < (3, 7), reason=\"Dataclasses in Python3.7+\")\n def test_dataclasses(self, testdir):\n p = testdir.copy_example(\"dataclasses/test_compare_dataclasses.py\")\n result = testdir.runpytest(p)\n result.assert_outcomes(failed=1, passed=0)\n result.stdout.fnmatch_lines(\n [\n \"*Omitting 1 identical items, use -vv to show*\",\n \"*Differing attributes:*\",\n \"*field_b: 'b' != 'c'*\",\n ]\n )\n\n @pytest.mark.skipif(sys.version_info < (3, 7), reason=\"Dataclasses in Python3.7+\")\n def test_dataclasses_verbose(self, testdir):\n p = testdir.copy_example(\"dataclasses/test_compare_dataclasses_verbose.py\")\n result = testdir.runpytest(p, \"-vv\")\n result.assert_outcomes(failed=1, passed=0)\n result.stdout.fnmatch_lines(\n [\n \"*Matching attributes:*\",\n \"*['field_a']*\",\n \"*Differing attributes:*\",\n \"*field_b: 'b' != 'c'*\",\n ]\n )\n\n @pytest.mark.skipif(sys.version_info < (3, 7), reason=\"Dataclasses in Python3.7+\")\n def test_dataclasses_with_attribute_comparison_off(self, testdir):\n p = testdir.copy_example(\n \"dataclasses/test_compare_dataclasses_field_comparison_off.py\"\n )\n result = testdir.runpytest(p, \"-vv\")\n result.assert_outcomes(failed=0, passed=1)\n\n @pytest.mark.skipif(sys.version_info < (3, 7), reason=\"Dataclasses in Python3.7+\")\n def test_comparing_two_different_data_classes(self, testdir):\n p = testdir.copy_example(\n \"dataclasses/test_compare_two_different_dataclasses.py\"\n )\n result = testdir.runpytest(p, \"-vv\")\n result.assert_outcomes(failed=0, passed=1)\n\n\nclass TestAssert_reprcompare_attrsclass(object):\n def test_attrs(self):\n @attr.s\n class SimpleDataObject(object):\n field_a = attr.ib()\n field_b = attr.ib()\n\n left = SimpleDataObject(1, \"b\")\n right = SimpleDataObject(1, \"c\")\n\n lines = callequal(left, right)\n assert lines[1].startswith(\"Omitting 1 identical item\")\n assert \"Matching attributes\" not in lines\n for line in lines[1:]:\n assert \"field_a\" not in line\n\n def test_attrs_verbose(self):\n @attr.s\n class SimpleDataObject(object):\n field_a = attr.ib()\n field_b = attr.ib()\n\n left = SimpleDataObject(1, \"b\")\n right = SimpleDataObject(1, \"c\")\n\n lines = callequal(left, right, verbose=2)\n assert lines[1].startswith(\"Matching attributes:\")\n assert \"Omitting\" not in lines[1]\n assert lines[2] == \"['field_a']\"\n\n def test_attrs_with_attribute_comparison_off(self):\n @attr.s\n class SimpleDataObject(object):\n field_a = attr.ib()\n field_b = attr.ib(cmp=False)\n\n left = SimpleDataObject(1, \"b\")\n right = SimpleDataObject(1, \"b\")\n\n lines = callequal(left, right, verbose=2)\n assert lines[1].startswith(\"Matching attributes:\")\n assert \"Omitting\" not in lines[1]\n assert lines[2] == \"['field_a']\"\n for line in lines[2:]:\n assert \"field_b\" not in line\n\n def test_comparing_two_different_attrs_classes(self):\n @attr.s\n class SimpleDataObjectOne(object):\n field_a = attr.ib()\n field_b = attr.ib()\n\n @attr.s\n class SimpleDataObjectTwo(object):\n field_a = attr.ib()\n field_b = attr.ib()\n\n left = SimpleDataObjectOne(1, \"b\")\n right = SimpleDataObjectTwo(1, \"c\")\n\n lines = callequal(left, right)\n assert lines is None\n\n\nclass TestFormatExplanation(object):\n def test_special_chars_full(self, testdir):\n # Issue 453, for the bug this would raise IndexError\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert '\\\\n}' == ''\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines([\"*AssertionError*\"])\n\n def test_fmt_simple(self):\n expl = \"assert foo\"\n assert util.format_explanation(expl) == \"assert foo\"\n\n def test_fmt_where(self):\n expl = \"\\n\".join([\"assert 1\", \"{1 = foo\", \"} == 2\"])\n res = \"\\n\".join([\"assert 1 == 2\", \" + where 1 = foo\"])\n assert util.format_explanation(expl) == res\n\n def test_fmt_and(self):\n expl = \"\\n\".join([\"assert 1\", \"{1 = foo\", \"} == 2\", \"{2 = bar\", \"}\"])\n res = \"\\n\".join([\"assert 1 == 2\", \" + where 1 = foo\", \" + and 2 = bar\"])\n assert util.format_explanation(expl) == res\n\n def test_fmt_where_nested(self):\n expl = \"\\n\".join([\"assert 1\", \"{1 = foo\", \"{foo = bar\", \"}\", \"} == 2\"])\n res = \"\\n\".join([\"assert 1 == 2\", \" + where 1 = foo\", \" + where foo = bar\"])\n assert util.format_explanation(expl) == res\n\n def test_fmt_newline(self):\n expl = \"\\n\".join(['assert \"foo\" == \"bar\"', \"~- foo\", \"~+ bar\"])\n res = \"\\n\".join(['assert \"foo\" == \"bar\"', \" - foo\", \" + bar\"])\n assert util.format_explanation(expl) == res\n\n def test_fmt_newline_escaped(self):\n expl = \"\\n\".join([\"assert foo == bar\", \"baz\"])\n res = \"assert foo == bar\\\\nbaz\"\n assert util.format_explanation(expl) == res\n\n def test_fmt_newline_before_where(self):\n expl = \"\\n\".join(\n [\n \"the assertion message here\",\n \">assert 1\",\n \"{1 = foo\",\n \"} == 2\",\n \"{2 = bar\",\n \"}\",\n ]\n )\n res = \"\\n\".join(\n [\n \"the assertion message here\",\n \"assert 1 == 2\",\n \" + where 1 = foo\",\n \" + and 2 = bar\",\n ]\n )\n assert util.format_explanation(expl) == res\n\n def test_fmt_multi_newline_before_where(self):\n expl = \"\\n\".join(\n [\n \"the assertion\",\n \"~message here\",\n \">assert 1\",\n \"{1 = foo\",\n \"} == 2\",\n \"{2 = bar\",\n \"}\",\n ]\n )\n res = \"\\n\".join(\n [\n \"the assertion\",\n \" message here\",\n \"assert 1 == 2\",\n \" + where 1 = foo\",\n \" + and 2 = bar\",\n ]\n )\n assert util.format_explanation(expl) == res\n\n\nclass TestTruncateExplanation(object):\n\n \"\"\" Confirm assertion output is truncated as expected \"\"\"\n\n # The number of lines in the truncation explanation message. Used\n # to calculate that results have the expected length.\n LINES_IN_TRUNCATION_MSG = 2\n\n def test_doesnt_truncate_when_input_is_empty_list(self):\n expl = []\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)\n assert result == expl\n\n def test_doesnt_truncate_at_when_input_is_5_lines_and_LT_max_chars(self):\n expl = [\"a\" * 100 for x in range(5)]\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)\n assert result == expl\n\n def test_truncates_at_8_lines_when_given_list_of_empty_strings(self):\n expl = [\"\" for x in range(50)]\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)\n assert result != expl\n assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG\n assert \"Full output truncated\" in result[-1]\n assert \"43 lines hidden\" in result[-1]\n last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]\n assert last_line_before_trunc_msg.endswith(\"...\")\n\n def test_truncates_at_8_lines_when_first_8_lines_are_LT_max_chars(self):\n expl = [\"a\" for x in range(100)]\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)\n assert result != expl\n assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG\n assert \"Full output truncated\" in result[-1]\n assert \"93 lines hidden\" in result[-1]\n last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]\n assert last_line_before_trunc_msg.endswith(\"...\")\n\n def test_truncates_at_8_lines_when_first_8_lines_are_EQ_max_chars(self):\n expl = [\"a\" * 80 for x in range(16)]\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)\n assert result != expl\n assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG\n assert \"Full output truncated\" in result[-1]\n assert \"9 lines hidden\" in result[-1]\n last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]\n assert last_line_before_trunc_msg.endswith(\"...\")\n\n def test_truncates_at_4_lines_when_first_4_lines_are_GT_max_chars(self):\n expl = [\"a\" * 250 for x in range(10)]\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=999)\n assert result != expl\n assert len(result) == 4 + self.LINES_IN_TRUNCATION_MSG\n assert \"Full output truncated\" in result[-1]\n assert \"7 lines hidden\" in result[-1]\n last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]\n assert last_line_before_trunc_msg.endswith(\"...\")\n\n def test_truncates_at_1_line_when_first_line_is_GT_max_chars(self):\n expl = [\"a\" * 250 for x in range(1000)]\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)\n assert result != expl\n assert len(result) == 1 + self.LINES_IN_TRUNCATION_MSG\n assert \"Full output truncated\" in result[-1]\n assert \"1000 lines hidden\" in result[-1]\n last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]\n assert last_line_before_trunc_msg.endswith(\"...\")\n\n def test_full_output_truncated(self, monkeypatch, testdir):\n \"\"\" Test against full runpytest() output. \"\"\"\n\n line_count = 7\n line_len = 100\n expected_truncated_lines = 2\n testdir.makepyfile(\n r\"\"\"\n def test_many_lines():\n a = list([str(i)[0] * %d for i in range(%d)])\n b = a[::2]\n a = '\\n'.join(map(str, a))\n b = '\\n'.join(map(str, b))\n assert a == b\n \"\"\"\n % (line_len, line_count)\n )\n monkeypatch.delenv(\"CI\", raising=False)\n\n result = testdir.runpytest()\n # without -vv, truncate the message showing a few diff lines only\n result.stdout.fnmatch_lines(\n [\n \"*- 1*\",\n \"*- 3*\",\n \"*- 5*\",\n \"*truncated (%d lines hidden)*use*-vv*\" % expected_truncated_lines,\n ]\n )\n\n result = testdir.runpytest(\"-vv\")\n result.stdout.fnmatch_lines([\"* 6*\"])\n\n monkeypatch.setenv(\"CI\", \"1\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 6*\"])\n\n\ndef test_python25_compile_issue257(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_rewritten():\n assert 1 == 2\n # some comment\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n \"\"\"\n *E*assert 1 == 2*\n *1 failed*\n \"\"\"\n )\n\n\ndef test_rewritten(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_rewritten():\n assert \"@py_builtins\" in globals()\n \"\"\"\n )\n assert testdir.runpytest().ret == 0\n\n\ndef test_reprcompare_notin():\n config = mock_config()\n detail = plugin.pytest_assertrepr_compare(config, \"not in\", \"foo\", \"aaafoobbb\")[1:]\n assert detail == [\"'foo' is contained here:\", \" aaafoobbb\", \"? +++\"]\n\n\ndef test_reprcompare_whitespaces():\n config = mock_config()\n detail = plugin.pytest_assertrepr_compare(config, \"==\", \"\\r\\n\", \"\\n\")\n assert detail == [\n r\"'\\r\\n' == '\\n'\",\n r\"Strings contain only whitespace, escaping them using repr()\",\n r\"- '\\r\\n'\",\n r\"? --\",\n r\"+ '\\n'\",\n ]\n\n\ndef test_pytest_assertrepr_compare_integration(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n x = set(range(100))\n y = x.copy()\n y.remove(50)\n assert x == y\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"*def test_hello():*\", \"*assert x == y*\", \"*E*Extra items*left*\", \"*E*50*\"]\n )\n\n\ndef test_sequence_comparison_uses_repr(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n x = set(\"hello x\")\n y = set(\"hello y\")\n assert x == y\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*def test_hello():*\",\n \"*assert x == y*\",\n \"*E*Extra items*left*\",\n \"*E*'x'*\",\n \"*E*Extra items*right*\",\n \"*E*'y'*\",\n ]\n )\n\n\ndef test_assertrepr_loaded_per_dir(testdir):\n testdir.makepyfile(test_base=[\"def test_base(): assert 1 == 2\"])\n a = testdir.mkdir(\"a\")\n a_test = a.join(\"test_a.py\")\n a_test.write(\"def test_a(): assert 1 == 2\")\n a_conftest = a.join(\"conftest.py\")\n a_conftest.write('def pytest_assertrepr_compare(): return [\"summary a\"]')\n b = testdir.mkdir(\"b\")\n b_test = b.join(\"test_b.py\")\n b_test.write(\"def test_b(): assert 1 == 2\")\n b_conftest = b.join(\"conftest.py\")\n b_conftest.write('def pytest_assertrepr_compare(): return [\"summary b\"]')\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*def test_base():*\",\n \"*E*assert 1 == 2*\",\n \"*def test_a():*\",\n \"*E*assert summary a*\",\n \"*def test_b():*\",\n \"*E*assert summary b*\",\n ]\n )\n\n\ndef test_assertion_options(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n x = 3\n assert x == 4\n \"\"\"\n )\n result = testdir.runpytest()\n assert \"3 == 4\" in result.stdout.str()\n result = testdir.runpytest_subprocess(\"--assert=plain\")\n assert \"3 == 4\" not in result.stdout.str()\n\n\ndef test_triple_quoted_string_issue113(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n assert \"\" == '''\n '''\"\"\"\n )\n result = testdir.runpytest(\"--fulltrace\")\n result.stdout.fnmatch_lines([\"*1 failed*\"])\n assert \"SyntaxError\" not in result.stdout.str()\n\n\ndef test_traceback_failure(testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def g():\n return 2\n def f(x):\n assert x == g()\n def test_onefails():\n f(3)\n \"\"\"\n )\n result = testdir.runpytest(p1, \"--tb=long\")\n result.stdout.fnmatch_lines(\n [\n \"*test_traceback_failure.py F*\",\n \"====* FAILURES *====\",\n \"____*____\",\n \"\",\n \" def test_onefails():\",\n \"> f(3)\",\n \"\",\n \"*test_*.py:6: \",\n \"_ _ _ *\",\n # \"\",\n \" def f(x):\",\n \"> assert x == g()\",\n \"E assert 3 == 2\",\n \"E + where 2 = g()\",\n \"\",\n \"*test_traceback_failure.py:4: AssertionError\",\n ]\n )\n\n result = testdir.runpytest(p1) # \"auto\"\n result.stdout.fnmatch_lines(\n [\n \"*test_traceback_failure.py F*\",\n \"====* FAILURES *====\",\n \"____*____\",\n \"\",\n \" def test_onefails():\",\n \"> f(3)\",\n \"\",\n \"*test_*.py:6: \",\n \"\",\n \" def f(x):\",\n \"> assert x == g()\",\n \"E assert 3 == 2\",\n \"E + where 2 = g()\",\n \"\",\n \"*test_traceback_failure.py:4: AssertionError\",\n ]\n )\n\n\n@pytest.mark.skipif(\n sys.version_info[:2] <= (3, 3),\n reason=\"Python 3.4+ shows chained exceptions on multiprocess\",\n)\ndef test_exception_handling_no_traceback(testdir):\n \"\"\"\n Handle chain exceptions in tasks submitted by the multiprocess module (#1984).\n \"\"\"\n p1 = testdir.makepyfile(\n \"\"\"\n from multiprocessing import Pool\n\n def process_task(n):\n assert n == 10\n\n def multitask_job():\n tasks = [1]\n with Pool(processes=1) as pool:\n pool.map(process_task, tasks)\n\n def test_multitask_job():\n multitask_job()\n \"\"\"\n )\n result = testdir.runpytest(p1, \"--tb=long\")\n result.stdout.fnmatch_lines(\n [\n \"====* FAILURES *====\",\n \"*multiprocessing.pool.RemoteTraceback:*\",\n \"Traceback (most recent call last):\",\n \"*assert n == 10\",\n \"The above exception was the direct cause of the following exception:\",\n \"> * multitask_job()\",\n ]\n )\n\n\n@pytest.mark.skipif(\n \"'__pypy__' in sys.builtin_module_names or sys.platform.startswith('java')\"\n)\ndef test_warn_missing(testdir):\n testdir.makepyfile(\"\")\n result = testdir.run(sys.executable, \"-OO\", \"-m\", \"pytest\", \"-h\")\n result.stderr.fnmatch_lines([\"*WARNING*assert statements are not executed*\"])\n result = testdir.run(sys.executable, \"-OO\", \"-m\", \"pytest\")\n result.stderr.fnmatch_lines([\"*WARNING*assert statements are not executed*\"])\n\n\ndef test_recursion_source_decode(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_something():\n pass\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n python_files = *.py\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines(\n \"\"\"\n \n \"\"\"\n )\n\n\ndef test_AssertionError_message(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n x,y = 1,2\n assert 0, (x,y)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n \"\"\"\n *def test_hello*\n *assert 0, (x,y)*\n *AssertionError: (1, 2)*\n \"\"\"\n )\n\n\n@pytest.mark.skipif(PY3, reason=\"This bug does not exist on PY3\")\ndef test_set_with_unsortable_elements():\n # issue #718\n class UnsortableKey(object):\n def __init__(self, name):\n self.name = name\n\n def __lt__(self, other):\n raise RuntimeError()\n\n def __repr__(self):\n return \"repr({})\".format(self.name)\n\n def __eq__(self, other):\n return self.name == other.name\n\n def __hash__(self):\n return hash(self.name)\n\n left_set = {UnsortableKey(str(i)) for i in range(1, 3)}\n right_set = {UnsortableKey(str(i)) for i in range(2, 4)}\n expl = callequal(left_set, right_set, verbose=True)\n # skip first line because it contains the \"construction\" of the set, which does not have a guaranteed order\n expl = expl[1:]\n dedent = textwrap.dedent(\n \"\"\"\n Extra items in the left set:\n repr(1)\n Extra items in the right set:\n repr(3)\n Full diff (fallback to calling repr on each item):\n - repr(1)\n repr(2)\n + repr(3)\n \"\"\"\n ).strip()\n assert \"\\n\".join(expl) == dedent\n\n\ndef test_diff_newline_at_end(monkeypatch, testdir):\n testdir.makepyfile(\n r\"\"\"\n def test_diff():\n assert 'asdf' == 'asdf\\n'\n \"\"\"\n )\n\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n r\"\"\"\n *assert 'asdf' == 'asdf\\n'\n * - asdf\n * + asdf\n * ? +\n \"\"\"\n )\n\n\n@pytest.mark.filterwarnings(\"default\")\ndef test_assert_tuple_warning(testdir):\n msg = \"assertion is always true\"\n testdir.makepyfile(\n \"\"\"\n def test_tuple():\n assert(False, 'you shall not pass')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*test_assert_tuple_warning.py:2:*{}*\".format(msg)])\n\n # tuples with size != 2 should not trigger the warning\n testdir.makepyfile(\n \"\"\"\n def test_tuple():\n assert ()\n \"\"\"\n )\n result = testdir.runpytest()\n assert msg not in result.stdout.str()\n\n\ndef test_assert_indirect_tuple_no_warning(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_tuple():\n tpl = ('foo', 'bar')\n assert tpl\n \"\"\"\n )\n result = testdir.runpytest(\"-rw\")\n output = \"\\n\".join(result.stdout.lines)\n assert \"WR1\" not in output\n\n\ndef test_assert_with_unicode(monkeypatch, testdir):\n testdir.makepyfile(\n u\"\"\"\n # -*- coding: utf-8 -*-\n def test_unicode():\n assert u'유니코드' == u'Unicode'\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*AssertionError*\"])\n\n\ndef test_raise_unprintable_assertion_error(testdir):\n testdir.makepyfile(\n r\"\"\"\n def test_raise_assertion_error():\n raise AssertionError('\\xff')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [r\"> raise AssertionError('\\xff')\", \"E AssertionError: *\"]\n )\n\n\ndef test_raise_assertion_error_raisin_repr(testdir):\n testdir.makepyfile(\n u\"\"\"\n class RaisingRepr(object):\n def __repr__(self):\n raise Exception()\n def test_raising_repr():\n raise AssertionError(RaisingRepr())\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"E AssertionError: \"]\n )\n\n\ndef test_issue_1944(testdir):\n testdir.makepyfile(\n \"\"\"\n def f():\n return\n\n assert f() == 10\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 error*\"])\n assert (\n \"AttributeError: 'Module' object has no attribute '_obj'\"\n not in result.stdout.str()\n )\n\n\ndef test_exit_from_assertrepr_compare(monkeypatch):\n def raise_exit(obj):\n outcomes.exit(\"Quitting debugger\")\n\n monkeypatch.setattr(util, \"istext\", raise_exit)\n\n with pytest.raises(outcomes.Exit, match=\"Quitting debugger\"):\n callequal(1, 1)\n"},{"className":"TestImportHookInstallation","col":0,"comment":"null","endLoc":275,"id":6771,"nodeType":"Class","startLoc":33,"text":"class TestImportHookInstallation(object):\n @pytest.mark.parametrize(\"initial_conftest\", [True, False])\n @pytest.mark.parametrize(\"mode\", [\"plain\", \"rewrite\"])\n def test_conftest_assertion_rewrite(self, testdir, initial_conftest, mode):\n \"\"\"Test that conftest files are using assertion rewrite on import.\n (#1619)\n \"\"\"\n testdir.tmpdir.join(\"foo/tests\").ensure(dir=1)\n conftest_path = \"conftest.py\" if initial_conftest else \"foo/conftest.py\"\n contents = {\n conftest_path: \"\"\"\n import pytest\n @pytest.fixture\n def check_first():\n def check(values, value):\n assert values.pop(0) == value\n return check\n \"\"\",\n \"foo/tests/test_foo.py\": \"\"\"\n def test(check_first):\n check_first([10, 30], 30)\n \"\"\",\n }\n testdir.makepyfile(**contents)\n result = testdir.runpytest_subprocess(\"--assert=%s\" % mode)\n if mode == \"plain\":\n expected = \"E AssertionError\"\n elif mode == \"rewrite\":\n expected = \"*assert 10 == 30*\"\n else:\n assert 0\n result.stdout.fnmatch_lines([expected])\n\n def test_rewrite_assertions_pytester_plugin(self, testdir):\n \"\"\"\n Assertions in the pytester plugin must also benefit from assertion\n rewriting (#1920).\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n pytest_plugins = ['pytester']\n def test_dummy_failure(testdir): # how meta!\n testdir.makepyfile('def test(): assert 0')\n r = testdir.inline_run()\n r.assertoutcome(passed=1)\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*assert 1 == 0*\"])\n\n @pytest.mark.parametrize(\"mode\", [\"plain\", \"rewrite\"])\n def test_pytest_plugins_rewrite(self, testdir, mode):\n contents = {\n \"conftest.py\": \"\"\"\n pytest_plugins = ['ham']\n \"\"\",\n \"ham.py\": \"\"\"\n import pytest\n @pytest.fixture\n def check_first():\n def check(values, value):\n assert values.pop(0) == value\n return check\n \"\"\",\n \"test_foo.py\": \"\"\"\n def test_foo(check_first):\n check_first([10, 30], 30)\n \"\"\",\n }\n testdir.makepyfile(**contents)\n result = testdir.runpytest_subprocess(\"--assert=%s\" % mode)\n if mode == \"plain\":\n expected = \"E AssertionError\"\n elif mode == \"rewrite\":\n expected = \"*assert 10 == 30*\"\n else:\n assert 0\n result.stdout.fnmatch_lines([expected])\n\n @pytest.mark.parametrize(\"mode\", [\"str\", \"list\"])\n def test_pytest_plugins_rewrite_module_names(self, testdir, mode):\n \"\"\"Test that pluginmanager correct marks pytest_plugins variables\n for assertion rewriting if they are defined as plain strings or\n list of strings (#1888).\n \"\"\"\n plugins = '\"ham\"' if mode == \"str\" else '[\"ham\"]'\n contents = {\n \"conftest.py\": \"\"\"\n pytest_plugins = {plugins}\n \"\"\".format(\n plugins=plugins\n ),\n \"ham.py\": \"\"\"\n import pytest\n \"\"\",\n \"test_foo.py\": \"\"\"\n def test_foo(pytestconfig):\n assert 'ham' in pytestconfig.pluginmanager.rewrite_hook._must_rewrite\n \"\"\",\n }\n testdir.makepyfile(**contents)\n result = testdir.runpytest_subprocess(\"--assert=rewrite\")\n assert result.ret == 0\n\n def test_pytest_plugins_rewrite_module_names_correctly(self, testdir):\n \"\"\"Test that we match files correctly when they are marked for rewriting (#2939).\"\"\"\n contents = {\n \"conftest.py\": \"\"\"\\\n pytest_plugins = \"ham\"\n \"\"\",\n \"ham.py\": \"\",\n \"hamster.py\": \"\",\n \"test_foo.py\": \"\"\"\\\n def test_foo(pytestconfig):\n assert pytestconfig.pluginmanager.rewrite_hook.find_module('ham') is not None\n assert pytestconfig.pluginmanager.rewrite_hook.find_module('hamster') is None\n \"\"\",\n }\n testdir.makepyfile(**contents)\n result = testdir.runpytest_subprocess(\"--assert=rewrite\")\n assert result.ret == 0\n\n @pytest.mark.parametrize(\"mode\", [\"plain\", \"rewrite\"])\n def test_installed_plugin_rewrite(self, testdir, mode, monkeypatch):\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n # Make sure the hook is installed early enough so that plugins\n # installed via setuptools are rewritten.\n testdir.tmpdir.join(\"hampkg\").ensure(dir=1)\n contents = {\n \"hampkg/__init__.py\": \"\"\"\\\n import pytest\n\n @pytest.fixture\n def check_first2():\n def check(values, value):\n assert values.pop(0) == value\n return check\n \"\"\",\n \"spamplugin.py\": \"\"\"\\\n import pytest\n from hampkg import check_first2\n\n @pytest.fixture\n def check_first():\n def check(values, value):\n assert values.pop(0) == value\n return check\n \"\"\",\n \"mainwrapper.py\": \"\"\"\\\n import pytest, importlib_metadata\n\n class DummyEntryPoint(object):\n name = 'spam'\n module_name = 'spam.py'\n group = 'pytest11'\n\n def load(self):\n import spamplugin\n return spamplugin\n\n class DummyDistInfo(object):\n version = '1.0'\n files = ('spamplugin.py', 'hampkg/__init__.py')\n entry_points = (DummyEntryPoint(),)\n metadata = {'name': 'foo'}\n\n def distributions():\n return (DummyDistInfo(),)\n\n importlib_metadata.distributions = distributions\n pytest.main()\n \"\"\",\n \"test_foo.py\": \"\"\"\\\n def test(check_first):\n check_first([10, 30], 30)\n\n def test2(check_first2):\n check_first([10, 30], 30)\n \"\"\",\n }\n testdir.makepyfile(**contents)\n result = testdir.run(\n sys.executable, \"mainwrapper.py\", \"-s\", \"--assert=%s\" % mode\n )\n if mode == \"plain\":\n expected = \"E AssertionError\"\n elif mode == \"rewrite\":\n expected = \"*assert 10 == 30*\"\n else:\n assert 0\n result.stdout.fnmatch_lines([expected])\n\n def test_rewrite_ast(self, testdir):\n testdir.tmpdir.join(\"pkg\").ensure(dir=1)\n contents = {\n \"pkg/__init__.py\": \"\"\"\n import pytest\n pytest.register_assert_rewrite('pkg.helper')\n \"\"\",\n \"pkg/helper.py\": \"\"\"\n def tool():\n a, b = 2, 3\n assert a == b\n \"\"\",\n \"pkg/plugin.py\": \"\"\"\n import pytest, pkg.helper\n @pytest.fixture\n def tool():\n return pkg.helper.tool\n \"\"\",\n \"pkg/other.py\": \"\"\"\n values = [3, 2]\n def tool():\n assert values.pop() == 3\n \"\"\",\n \"conftest.py\": \"\"\"\n pytest_plugins = ['pkg.plugin']\n \"\"\",\n \"test_pkg.py\": \"\"\"\n import pkg.other\n def test_tool(tool):\n tool()\n def test_other():\n pkg.other.tool()\n \"\"\",\n }\n testdir.makepyfile(**contents)\n result = testdir.runpytest_subprocess(\"--assert=rewrite\")\n result.stdout.fnmatch_lines(\n [\n \">*assert a == b*\",\n \"E*assert 2 == 3*\",\n \">*assert values.pop() == 3*\",\n \"E*AssertionError\",\n ]\n )\n\n def test_register_assert_rewrite_checks_types(self):\n with pytest.raises(TypeError):\n pytest.register_assert_rewrite([\"pytest_tests_internal_non_existing\"])\n pytest.register_assert_rewrite(\n \"pytest_tests_internal_non_existing\", \"pytest_tests_internal_non_existing2\"\n )"},{"col":0,"comment":"null","endLoc":419,"header":"def test_undo_class_descriptors_delattr()","id":6772,"name":"test_undo_class_descriptors_delattr","nodeType":"Function","startLoc":395,"text":"def test_undo_class_descriptors_delattr():\n class SampleParent(object):\n @classmethod\n def hello(_cls):\n pass\n\n @staticmethod\n def world():\n pass\n\n class SampleChild(SampleParent):\n pass\n\n monkeypatch = MonkeyPatch()\n\n original_hello = SampleChild.hello\n original_world = SampleChild.world\n monkeypatch.delattr(SampleParent, \"hello\")\n monkeypatch.delattr(SampleParent, \"world\")\n assert getattr(SampleParent, \"hello\", None) is None\n assert getattr(SampleParent, \"world\", None) is None\n\n monkeypatch.undo()\n assert original_hello == SampleChild.hello\n assert original_world == SampleChild.world"},{"col":4,"comment":"Test that conftest files are using assertion rewrite on import.\n (#1619)\n ","endLoc":64,"header":"@pytest.mark.parametrize(\"initial_conftest\", [True, False])\n @pytest.mark.parametrize(\"mode\", [\"plain\", \"rewrite\"])\n def test_conftest_assertion_rewrite(self, testdir, initial_conftest, mode)","id":6773,"name":"test_conftest_assertion_rewrite","nodeType":"Function","startLoc":34,"text":"@pytest.mark.parametrize(\"initial_conftest\", [True, False])\n @pytest.mark.parametrize(\"mode\", [\"plain\", \"rewrite\"])\n def test_conftest_assertion_rewrite(self, testdir, initial_conftest, mode):\n \"\"\"Test that conftest files are using assertion rewrite on import.\n (#1619)\n \"\"\"\n testdir.tmpdir.join(\"foo/tests\").ensure(dir=1)\n conftest_path = \"conftest.py\" if initial_conftest else \"foo/conftest.py\"\n contents = {\n conftest_path: \"\"\"\n import pytest\n @pytest.fixture\n def check_first():\n def check(values, value):\n assert values.pop(0) == value\n return check\n \"\"\",\n \"foo/tests/test_foo.py\": \"\"\"\n def test(check_first):\n check_first([10, 30], 30)\n \"\"\",\n }\n testdir.makepyfile(**contents)\n result = testdir.runpytest_subprocess(\"--assert=%s\" % mode)\n if mode == \"plain\":\n expected = \"E AssertionError\"\n elif mode == \"rewrite\":\n expected = \"*assert 10 == 30*\"\n else:\n assert 0\n result.stdout.fnmatch_lines([expected])"},{"col":0,"comment":"null","endLoc":428,"header":"def test_issue1338_name_resolving()","id":6774,"name":"test_issue1338_name_resolving","nodeType":"Function","startLoc":422,"text":"def test_issue1338_name_resolving():\n pytest.importorskip(\"requests\")\n monkeypatch = MonkeyPatch()\n try:\n monkeypatch.delattr(\"requests.sessions.Session.request\")\n finally:\n monkeypatch.undo()"},{"col":0,"comment":"null","endLoc":440,"header":"def test_context()","id":6775,"name":"test_context","nodeType":"Function","startLoc":431,"text":"def test_context():\n monkeypatch = MonkeyPatch()\n\n import functools\n import inspect\n\n with monkeypatch.context() as m:\n m.setattr(functools, \"partial\", 3)\n assert not inspect.isclass(functools.partial)\n assert inspect.isclass(functools.partial)"},{"col":0,"comment":"null","endLoc":94,"header":"def test_source_putaround_simple()","id":6777,"name":"test_source_putaround_simple","nodeType":"Function","startLoc":75,"text":"def test_source_putaround_simple():\n source = Source(\"raise ValueError\")\n source = source.putaround(\n \"try:\",\n \"\"\"\\\n except ValueError:\n x = 42\n else:\n x = 23\"\"\",\n )\n assert (\n str(source)\n == \"\"\"\\\ntry:\n raise ValueError\nexcept ValueError:\n x = 42\nelse:\n x = 23\"\"\"\n )"},{"col":4,"comment":"null","endLoc":597,"header":"def test_repr_local(self)","id":6778,"name":"test_repr_local","nodeType":"Function","startLoc":589,"text":"def test_repr_local(self):\n p = FormattedExcinfo(showlocals=True)\n loc = {\"y\": 5, \"z\": 7, \"x\": 3, \"@x\": 2, \"__builtins__\": {}}\n reprlocals = p.repr_locals(loc)\n assert reprlocals.lines\n assert reprlocals.lines[0] == \"__builtins__ = \"\n assert reprlocals.lines[1] == \"x = 3\"\n assert reprlocals.lines[2] == \"y = 5\"\n assert reprlocals.lines[3] == \"z = 7\""},{"col":4,"comment":"null","endLoc":609,"header":"def test_repr_local_with_error(self)","id":6779,"name":"test_repr_local_with_error","nodeType":"Function","startLoc":599,"text":"def test_repr_local_with_error(self):\n class ObjWithErrorInRepr:\n def __repr__(self):\n raise NotImplementedError\n\n p = FormattedExcinfo(showlocals=True, truncate_locals=False)\n loc = {\"x\": ObjWithErrorInRepr(), \"__builtins__\": {}}\n reprlocals = p.repr_locals(loc)\n assert reprlocals.lines\n assert reprlocals.lines[0] == \"__builtins__ = \"\n assert '[NotImplementedError(\"\") raised in repr()]' in reprlocals.lines[1]"},{"col":0,"comment":"null","endLoc":105,"header":"def test_source_putaround()","id":6780,"name":"test_source_putaround","nodeType":"Function","startLoc":97,"text":"def test_source_putaround():\n source = Source()\n source = source.putaround(\n \"\"\"\n if 1:\n x=1\n \"\"\"\n )\n assert str(source).strip() == \"if 1:\\n x=1\""},{"col":4,"comment":"null","endLoc":626,"header":"def test_repr_local_with_exception_in_class_property(self)","id":6781,"name":"test_repr_local_with_exception_in_class_property","nodeType":"Function","startLoc":611,"text":"def test_repr_local_with_exception_in_class_property(self):\n class ExceptionWithBrokenClass(Exception):\n @property\n def __class__(self):\n raise TypeError(\"boom!\")\n\n class ObjWithErrorInRepr:\n def __repr__(self):\n raise ExceptionWithBrokenClass()\n\n p = FormattedExcinfo(showlocals=True, truncate_locals=False)\n loc = {\"x\": ObjWithErrorInRepr(), \"__builtins__\": {}}\n reprlocals = p.repr_locals(loc)\n assert reprlocals.lines\n assert reprlocals.lines[0] == \"__builtins__ = \"\n assert '[ExceptionWithBrokenClass(\"\") raised in repr()]' in reprlocals.lines[1]"},{"col":0,"comment":"null","endLoc":112,"header":"def test_source_strips()","id":6782,"name":"test_source_strips","nodeType":"Function","startLoc":108,"text":"def test_source_strips():\n source = Source(\"\")\n assert source == Source()\n assert str(source) == \"\"\n assert source.strip() == source"},{"col":0,"comment":"null","endLoc":119,"header":"def test_source_strip_multiline()","id":6784,"name":"test_source_strip_multiline","nodeType":"Function","startLoc":115,"text":"def test_source_strip_multiline():\n source = Source()\n source.lines = [\"\", \" hello\", \" \"]\n source2 = source.strip()\n assert source2.lines == [\" hello\"]"},{"col":0,"comment":"null","endLoc":126,"header":"def test_syntaxerror_rerepresentation()","id":6785,"name":"test_syntaxerror_rerepresentation","nodeType":"Function","startLoc":122,"text":"def test_syntaxerror_rerepresentation():\n ex = pytest.raises(SyntaxError, _pytest._code.compile, \"xyz xyz\")\n assert ex.value.lineno == 1\n assert ex.value.offset in (4, 5, 7) # XXX pypy/jython versus cpython?\n assert ex.value.text.strip(), \"x x\""},{"col":4,"comment":"null","endLoc":638,"header":"def test_repr_local_truncated(self)","id":6786,"name":"test_repr_local_truncated","nodeType":"Function","startLoc":628,"text":"def test_repr_local_truncated(self):\n loc = {\"l\": [i for i in range(10)]}\n p = FormattedExcinfo(showlocals=True)\n truncated_reprlocals = p.repr_locals(loc)\n assert truncated_reprlocals.lines\n assert truncated_reprlocals.lines[0] == \"l = [0, 1, 2, 3, 4, 5, ...]\"\n\n q = FormattedExcinfo(showlocals=True, truncate_locals=False)\n full_reprlocals = q.repr_locals(loc)\n assert full_reprlocals.lines\n assert full_reprlocals.lines[0] == \"l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\""},{"col":0,"comment":"null","endLoc":135,"header":"def test_isparseable()","id":6787,"name":"test_isparseable","nodeType":"Function","startLoc":129,"text":"def test_isparseable():\n assert Source(\"hello\").isparseable()\n assert Source(\"if 1:\\n pass\").isparseable()\n assert Source(\" \\nif 1:\\n pass\").isparseable()\n assert not Source(\"if 1:\\n\").isparseable()\n assert not Source(\" \\nif 1:\\npass\").isparseable()\n assert not Source(chr(0)).isparseable()"},{"col":4,"comment":"\n Assertions in the pytester plugin must also benefit from assertion\n rewriting (#1920).\n ","endLoc":81,"header":"def test_rewrite_assertions_pytester_plugin(self, testdir)","id":6789,"name":"test_rewrite_assertions_pytester_plugin","nodeType":"Function","startLoc":66,"text":"def test_rewrite_assertions_pytester_plugin(self, testdir):\n \"\"\"\n Assertions in the pytester plugin must also benefit from assertion\n rewriting (#1920).\n \"\"\"\n testdir.makepyfile(\n \"\"\"\n pytest_plugins = ['pytester']\n def test_dummy_failure(testdir): # how meta!\n testdir.makepyfile('def test(): assert 0')\n r = testdir.inline_run()\n r.assertoutcome(passed=1)\n \"\"\"\n )\n result = testdir.runpytest_subprocess()\n result.stdout.fnmatch_lines([\"*assert 1 == 0*\"])"},{"col":4,"comment":"null","endLoc":110,"header":"@pytest.mark.parametrize(\"mode\", [\"plain\", \"rewrite\"])\n def test_pytest_plugins_rewrite(self, testdir, mode)","id":6790,"name":"test_pytest_plugins_rewrite","nodeType":"Function","startLoc":83,"text":"@pytest.mark.parametrize(\"mode\", [\"plain\", \"rewrite\"])\n def test_pytest_plugins_rewrite(self, testdir, mode):\n contents = {\n \"conftest.py\": \"\"\"\n pytest_plugins = ['ham']\n \"\"\",\n \"ham.py\": \"\"\"\n import pytest\n @pytest.fixture\n def check_first():\n def check(values, value):\n assert values.pop(0) == value\n return check\n \"\"\",\n \"test_foo.py\": \"\"\"\n def test_foo(check_first):\n check_first([10, 30], 30)\n \"\"\",\n }\n testdir.makepyfile(**contents)\n result = testdir.runpytest_subprocess(\"--assert=%s\" % mode)\n if mode == \"plain\":\n expected = \"E AssertionError\"\n elif mode == \"rewrite\":\n expected = \"*assert 10 == 30*\"\n else:\n assert 0\n result.stdout.fnmatch_lines([expected])"},{"col":4,"comment":"null","endLoc":671,"header":"def test_repr_tracebackentry_lines(self, importasmod)","id":6791,"name":"test_repr_tracebackentry_lines","nodeType":"Function","startLoc":640,"text":"def test_repr_tracebackentry_lines(self, importasmod):\n mod = importasmod(\n \"\"\"\n def func1():\n raise ValueError(\"hello\\\\nworld\")\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.func1)\n excinfo.traceback = excinfo.traceback.filter()\n p = FormattedExcinfo()\n reprtb = p.repr_traceback_entry(excinfo.traceback[-1])\n\n # test as intermittent entry\n lines = reprtb.lines\n assert lines[0] == \" def func1():\"\n assert lines[1] == '> raise ValueError(\"hello\\\\nworld\")'\n\n # test as last entry\n p = FormattedExcinfo(showlocals=True)\n repr_entry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)\n lines = repr_entry.lines\n assert lines[0] == \" def func1():\"\n assert lines[1] == '> raise ValueError(\"hello\\\\nworld\")'\n assert lines[2] == \"E ValueError: hello\"\n assert lines[3] == \"E world\"\n assert not lines[4:]\n\n loc = repr_entry.reprlocals is not None\n loc = repr_entry.reprfileloc\n assert loc.path == mod.__file__\n assert loc.lineno == 3\n # assert loc.message == \"ValueError: hello\""},{"col":4,"comment":"Test that pluginmanager correct marks pytest_plugins variables\n for assertion rewriting if they are defined as plain strings or\n list of strings (#1888).\n ","endLoc":135,"header":"@pytest.mark.parametrize(\"mode\", [\"str\", \"list\"])\n def test_pytest_plugins_rewrite_module_names(self, testdir, mode)","id":6792,"name":"test_pytest_plugins_rewrite_module_names","nodeType":"Function","startLoc":112,"text":"@pytest.mark.parametrize(\"mode\", [\"str\", \"list\"])\n def test_pytest_plugins_rewrite_module_names(self, testdir, mode):\n \"\"\"Test that pluginmanager correct marks pytest_plugins variables\n for assertion rewriting if they are defined as plain strings or\n list of strings (#1888).\n \"\"\"\n plugins = '\"ham\"' if mode == \"str\" else '[\"ham\"]'\n contents = {\n \"conftest.py\": \"\"\"\n pytest_plugins = {plugins}\n \"\"\".format(\n plugins=plugins\n ),\n \"ham.py\": \"\"\"\n import pytest\n \"\"\",\n \"test_foo.py\": \"\"\"\n def test_foo(pytestconfig):\n assert 'ham' in pytestconfig.pluginmanager.rewrite_hook._must_rewrite\n \"\"\",\n }\n testdir.makepyfile(**contents)\n result = testdir.runpytest_subprocess(\"--assert=rewrite\")\n assert result.ret == 0"},{"col":4,"comment":"Test that we match files correctly when they are marked for rewriting (#2939).","endLoc":153,"header":"def test_pytest_plugins_rewrite_module_names_correctly(self, testdir)","id":6794,"name":"test_pytest_plugins_rewrite_module_names_correctly","nodeType":"Function","startLoc":137,"text":"def test_pytest_plugins_rewrite_module_names_correctly(self, testdir):\n \"\"\"Test that we match files correctly when they are marked for rewriting (#2939).\"\"\"\n contents = {\n \"conftest.py\": \"\"\"\\\n pytest_plugins = \"ham\"\n \"\"\",\n \"ham.py\": \"\",\n \"hamster.py\": \"\",\n \"test_foo.py\": \"\"\"\\\n def test_foo(pytestconfig):\n assert pytestconfig.pluginmanager.rewrite_hook.find_module('ham') is not None\n assert pytestconfig.pluginmanager.rewrite_hook.find_module('hamster') is None\n \"\"\",\n }\n testdir.makepyfile(**contents)\n result = testdir.runpytest_subprocess(\"--assert=rewrite\")\n assert result.ret == 0"},{"col":4,"comment":"null","endLoc":332,"header":"def test_removal_accepts_lock(self, tmp_path)","id":6795,"name":"test_removal_accepts_lock","nodeType":"Function","startLoc":328,"text":"def test_removal_accepts_lock(self, tmp_path):\n folder = pathlib.make_numbered_dir(root=tmp_path, prefix=self.PREFIX)\n pathlib.create_cleanup_lock(folder)\n pathlib.maybe_delete_a_numbered_dir(folder)\n assert folder.is_dir()"},{"col":4,"comment":"null","endLoc":223,"header":"@pytest.mark.parametrize(\"mode\", [\"plain\", \"rewrite\"])\n def test_installed_plugin_rewrite(self, testdir, mode, monkeypatch)","id":6796,"name":"test_installed_plugin_rewrite","nodeType":"Function","startLoc":155,"text":"@pytest.mark.parametrize(\"mode\", [\"plain\", \"rewrite\"])\n def test_installed_plugin_rewrite(self, testdir, mode, monkeypatch):\n monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n # Make sure the hook is installed early enough so that plugins\n # installed via setuptools are rewritten.\n testdir.tmpdir.join(\"hampkg\").ensure(dir=1)\n contents = {\n \"hampkg/__init__.py\": \"\"\"\\\n import pytest\n\n @pytest.fixture\n def check_first2():\n def check(values, value):\n assert values.pop(0) == value\n return check\n \"\"\",\n \"spamplugin.py\": \"\"\"\\\n import pytest\n from hampkg import check_first2\n\n @pytest.fixture\n def check_first():\n def check(values, value):\n assert values.pop(0) == value\n return check\n \"\"\",\n \"mainwrapper.py\": \"\"\"\\\n import pytest, importlib_metadata\n\n class DummyEntryPoint(object):\n name = 'spam'\n module_name = 'spam.py'\n group = 'pytest11'\n\n def load(self):\n import spamplugin\n return spamplugin\n\n class DummyDistInfo(object):\n version = '1.0'\n files = ('spamplugin.py', 'hampkg/__init__.py')\n entry_points = (DummyEntryPoint(),)\n metadata = {'name': 'foo'}\n\n def distributions():\n return (DummyDistInfo(),)\n\n importlib_metadata.distributions = distributions\n pytest.main()\n \"\"\",\n \"test_foo.py\": \"\"\"\\\n def test(check_first):\n check_first([10, 30], 30)\n\n def test2(check_first2):\n check_first([10, 30], 30)\n \"\"\",\n }\n testdir.makepyfile(**contents)\n result = testdir.run(\n sys.executable, \"mainwrapper.py\", \"-s\", \"--assert=%s\" % mode\n )\n if mode == \"plain\":\n expected = \"E AssertionError\"\n elif mode == \"rewrite\":\n expected = \"*assert 10 == 30*\"\n else:\n assert 0\n result.stdout.fnmatch_lines([expected])"},{"col":0,"comment":"null","endLoc":472,"header":"def test_syspath_prepend_with_namespace_packages(testdir, monkeypatch)","id":6797,"name":"test_syspath_prepend_with_namespace_packages","nodeType":"Function","startLoc":443,"text":"def test_syspath_prepend_with_namespace_packages(testdir, monkeypatch):\n for dirname in \"hello\", \"world\":\n d = testdir.mkdir(dirname)\n ns = d.mkdir(\"ns_pkg\")\n ns.join(\"__init__.py\").write(\n \"__import__('pkg_resources').declare_namespace(__name__)\"\n )\n lib = ns.mkdir(dirname)\n lib.join(\"__init__.py\").write(\"def check(): return %r\" % dirname)\n\n monkeypatch.syspath_prepend(\"hello\")\n import ns_pkg.hello\n\n assert ns_pkg.hello.check() == \"hello\"\n\n with pytest.raises(ImportError):\n import ns_pkg.world\n\n # Prepending should call fixup_namespace_packages.\n monkeypatch.syspath_prepend(\"world\")\n import ns_pkg.world\n\n assert ns_pkg.world.check() == \"world\"\n\n # Should invalidate caches via importlib.invalidate_caches.\n tmpdir = testdir.tmpdir\n modules_tmpdir = tmpdir.mkdir(\"modules_tmpdir\")\n monkeypatch.syspath_prepend(str(modules_tmpdir))\n modules_tmpdir.join(\"main_app.py\").write(\"app = True\")\n from main_app import app # noqa: F401"},{"attributeType":"str","col":4,"comment":"null","endLoc":241,"id":6798,"name":"PREFIX","nodeType":"Attribute","startLoc":241,"text":"PREFIX"},{"className":"TestRmRf","col":0,"comment":"null","endLoc":412,"id":6799,"nodeType":"Class","startLoc":335,"text":"class TestRmRf:\n def test_rm_rf(self, tmp_path):\n from _pytest.pathlib import rm_rf\n\n adir = tmp_path / \"adir\"\n adir.mkdir()\n rm_rf(adir)\n\n assert not adir.exists()\n\n adir.mkdir()\n afile = adir / \"afile\"\n afile.write_bytes(b\"aa\")\n\n rm_rf(adir)\n assert not adir.exists()\n\n def test_rm_rf_with_read_only_file(self, tmp_path):\n \"\"\"Ensure rm_rf can remove directories with read-only files in them (#5524)\"\"\"\n from _pytest.pathlib import rm_rf\n\n fn = tmp_path / \"dir/foo.txt\"\n fn.parent.mkdir()\n\n fn.touch()\n\n self.chmod_r(fn)\n\n rm_rf(fn.parent)\n\n assert not fn.parent.is_dir()\n\n def chmod_r(self, path):\n mode = os.stat(str(path)).st_mode\n os.chmod(str(path), mode & ~stat.S_IWRITE)\n\n def test_rm_rf_with_read_only_directory(self, tmp_path):\n \"\"\"Ensure rm_rf can remove read-only directories (#5524)\"\"\"\n from _pytest.pathlib import rm_rf\n\n adir = tmp_path / \"dir\"\n adir.mkdir()\n\n (adir / \"foo.txt\").touch()\n self.chmod_r(adir)\n\n rm_rf(adir)\n\n assert not adir.is_dir()\n\n def test_on_rm_rf_error(self, tmp_path):\n from _pytest.pathlib import on_rm_rf_error\n\n adir = tmp_path / \"dir\"\n adir.mkdir()\n\n fn = adir / \"foo.txt\"\n fn.touch()\n self.chmod_r(fn)\n\n # unknown exception\n with pytest.warns(pytest.PytestWarning):\n exc_info = (None, RuntimeError(), None)\n on_rm_rf_error(os.unlink, str(fn), exc_info, start_path=tmp_path)\n assert fn.is_file()\n\n permission_error = OSError()\n permission_error.errno = errno.EACCES\n\n # unknown function\n with pytest.warns(pytest.PytestWarning):\n exc_info = (None, permission_error, None)\n on_rm_rf_error(None, str(fn), exc_info, start_path=tmp_path)\n assert fn.is_file()\n\n exc_info = (None, permission_error, None)\n on_rm_rf_error(os.unlink, str(fn), exc_info, start_path=tmp_path)\n assert not fn.is_file()"},{"col":4,"comment":"null","endLoc":350,"header":"def test_rm_rf(self, tmp_path)","id":6800,"name":"test_rm_rf","nodeType":"Function","startLoc":336,"text":"def test_rm_rf(self, tmp_path):\n from _pytest.pathlib import rm_rf\n\n adir = tmp_path / \"adir\"\n adir.mkdir()\n rm_rf(adir)\n\n assert not adir.exists()\n\n adir.mkdir()\n afile = adir / \"afile\"\n afile.write_bytes(b\"aa\")\n\n rm_rf(adir)\n assert not adir.exists()"},{"col":0,"comment":"null","endLoc":351,"header":"def test_getstartingblock_singleline()","id":6801,"name":"test_getstartingblock_singleline","nodeType":"Function","startLoc":342,"text":"def test_getstartingblock_singleline():\n class A(object):\n def __init__(self, *args):\n frame = sys._getframe(1)\n self.source = _pytest._code.Frame(frame).statement\n\n x = A(\"x\", \"y\")\n\n values = [i for i in x.source.lines if i.strip()]\n assert len(values) == 1"},{"col":4,"comment":"null","endLoc":575,"header":"def _NameConstant(c)","id":6803,"name":"_NameConstant","nodeType":"Function","startLoc":574,"text":"def _NameConstant(c):\n return ast.Name(str(c), ast.Load())"},{"col":0,"comment":"null","endLoc":366,"header":"def test_getline_finally()","id":6804,"name":"test_getline_finally","nodeType":"Function","startLoc":354,"text":"def test_getline_finally():\n def c():\n pass\n\n with pytest.raises(TypeError) as excinfo:\n teardown = None\n try:\n c(1)\n finally:\n if teardown:\n teardown()\n source = excinfo.traceback[-1].statement\n assert str(source).strip() == \"c(1)\""},{"col":4,"comment":"Ensure rm_rf can remove directories with read-only files in them (#5524)","endLoc":365,"header":"def test_rm_rf_with_read_only_file(self, tmp_path)","id":6806,"name":"test_rm_rf_with_read_only_file","nodeType":"Function","startLoc":352,"text":"def test_rm_rf_with_read_only_file(self, tmp_path):\n \"\"\"Ensure rm_rf can remove directories with read-only files in them (#5524)\"\"\"\n from _pytest.pathlib import rm_rf\n\n fn = tmp_path / \"dir/foo.txt\"\n fn.parent.mkdir()\n\n fn.touch()\n\n self.chmod_r(fn)\n\n rm_rf(fn.parent)\n\n assert not fn.parent.is_dir()"},{"col":0,"comment":"null","endLoc":379,"header":"def test_getfuncsource_dynamic()","id":6807,"name":"test_getfuncsource_dynamic","nodeType":"Function","startLoc":369,"text":"def test_getfuncsource_dynamic():\n source = \"\"\"\n def f():\n raise ValueError\n\n def g(): pass\n \"\"\"\n co = _pytest._code.compile(source)\n exec(co, globals())\n assert str(_pytest._code.Source(f)).strip() == \"def f():\\n raise ValueError\"\n assert str(_pytest._code.Source(g)).strip() == \"def g(): pass\""},{"col":4,"comment":"null","endLoc":697,"header":"def test_repr_tracebackentry_lines2(self, importasmod)","id":6808,"name":"test_repr_tracebackentry_lines2","nodeType":"Function","startLoc":673,"text":"def test_repr_tracebackentry_lines2(self, importasmod):\n mod = importasmod(\n \"\"\"\n def func1(m, x, y, z):\n raise ValueError(\"hello\\\\nworld\")\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.func1, \"m\" * 90, 5, 13, \"z\" * 120)\n excinfo.traceback = excinfo.traceback.filter()\n entry = excinfo.traceback[-1]\n p = FormattedExcinfo(funcargs=True)\n reprfuncargs = p.repr_args(entry)\n assert reprfuncargs.args[0] == (\"m\", repr(\"m\" * 90))\n assert reprfuncargs.args[1] == (\"x\", \"5\")\n assert reprfuncargs.args[2] == (\"y\", \"13\")\n assert reprfuncargs.args[3] == (\"z\", repr(\"z\" * 120))\n\n p = FormattedExcinfo(funcargs=True)\n repr_entry = p.repr_traceback_entry(entry)\n assert repr_entry.reprfuncargs.args == reprfuncargs.args\n tw = TWMock()\n repr_entry.toterminal(tw)\n assert tw.lines[0] == \"m = \" + repr(\"m\" * 90)\n assert tw.lines[1] == \"x = 5, y = 13\"\n assert tw.lines[2] == \"z = \" + repr(\"z\" * 120)"},{"col":4,"comment":"null","endLoc":268,"header":"def test_rewrite_ast(self, testdir)","id":6809,"name":"test_rewrite_ast","nodeType":"Function","startLoc":225,"text":"def test_rewrite_ast(self, testdir):\n testdir.tmpdir.join(\"pkg\").ensure(dir=1)\n contents = {\n \"pkg/__init__.py\": \"\"\"\n import pytest\n pytest.register_assert_rewrite('pkg.helper')\n \"\"\",\n \"pkg/helper.py\": \"\"\"\n def tool():\n a, b = 2, 3\n assert a == b\n \"\"\",\n \"pkg/plugin.py\": \"\"\"\n import pytest, pkg.helper\n @pytest.fixture\n def tool():\n return pkg.helper.tool\n \"\"\",\n \"pkg/other.py\": \"\"\"\n values = [3, 2]\n def tool():\n assert values.pop() == 3\n \"\"\",\n \"conftest.py\": \"\"\"\n pytest_plugins = ['pkg.plugin']\n \"\"\",\n \"test_pkg.py\": \"\"\"\n import pkg.other\n def test_tool(tool):\n tool()\n def test_other():\n pkg.other.tool()\n \"\"\",\n }\n testdir.makepyfile(**contents)\n result = testdir.runpytest_subprocess(\"--assert=rewrite\")\n result.stdout.fnmatch_lines(\n [\n \">*assert a == b*\",\n \"E*assert 2 == 3*\",\n \">*assert values.pop() == 3*\",\n \"E*AssertionError\",\n ]\n )"},{"col":0,"comment":"Set node location information recursively.","endLoc":590,"header":"def set_location(node, lineno, col_offset)","id":6810,"name":"set_location","nodeType":"Function","startLoc":578,"text":"def set_location(node, lineno, col_offset):\n \"\"\"Set node location information recursively.\"\"\"\n\n def _fix(node, lineno, col_offset):\n if \"lineno\" in node._attributes:\n node.lineno = lineno\n if \"col_offset\" in node._attributes:\n node.col_offset = col_offset\n for child in ast.iter_child_nodes(node):\n _fix(child, lineno, col_offset)\n\n _fix(node, lineno, col_offset)\n return node"},{"col":0,"comment":"null","endLoc":394,"header":"def test_getfuncsource_with_multine_string()","id":6811,"name":"test_getfuncsource_with_multine_string","nodeType":"Function","startLoc":382,"text":"def test_getfuncsource_with_multine_string():\n def f():\n c = \"\"\"while True:\n pass\n\"\"\"\n\n expected = '''\\\n def f():\n c = \"\"\"while True:\n pass\n\"\"\"\n'''\n assert str(_pytest._code.Source(f)) == expected.rstrip()"},{"col":4,"comment":"null","endLoc":275,"header":"def test_register_assert_rewrite_checks_types(self)","id":6813,"name":"test_register_assert_rewrite_checks_types","nodeType":"Function","startLoc":270,"text":"def test_register_assert_rewrite_checks_types(self):\n with pytest.raises(TypeError):\n pytest.register_assert_rewrite([\"pytest_tests_internal_non_existing\"])\n pytest.register_assert_rewrite(\n \"pytest_tests_internal_non_existing\", \"pytest_tests_internal_non_existing2\"\n )"},{"className":"TestBinReprIntegration","col":0,"comment":"null","endLoc":301,"id":6814,"nodeType":"Class","startLoc":278,"text":"class TestBinReprIntegration(object):\n def test_pytest_assertrepr_compare_called(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n values = []\n def pytest_assertrepr_compare(op, left, right):\n values.append((op, left, right))\n\n @pytest.fixture\n def list(request):\n return values\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n assert 0 == 1\n def test_check(list):\n assert list == [(\"==\", 0, 1)]\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines([\"*test_hello*FAIL*\", \"*test_check*PASS*\"])"},{"col":4,"comment":"null","endLoc":301,"header":"def test_pytest_assertrepr_compare_called(self, testdir)","id":6815,"name":"test_pytest_assertrepr_compare_called","nodeType":"Function","startLoc":279,"text":"def test_pytest_assertrepr_compare_called(self, testdir):\n testdir.makeconftest(\n \"\"\"\n import pytest\n values = []\n def pytest_assertrepr_compare(op, left, right):\n values.append((op, left, right))\n\n @pytest.fixture\n def list(request):\n return values\n \"\"\"\n )\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n assert 0 == 1\n def test_check(list):\n assert list == [(\"==\", 0, 1)]\n \"\"\"\n )\n result = testdir.runpytest(\"-v\")\n result.stdout.fnmatch_lines([\"*test_hello*FAIL*\", \"*test_check*PASS*\"])"},{"col":0,"comment":"null","endLoc":408,"header":"def test_deindent()","id":6816,"name":"test_deindent","nodeType":"Function","startLoc":397,"text":"def test_deindent():\n from _pytest._code.source import deindent as deindent\n\n assert deindent([\"\\tfoo\", \"\\tbar\"]) == [\"foo\", \"bar\"]\n\n source = \"\"\"\\\n def f():\n def g():\n pass\n \"\"\"\n lines = deindent(source.splitlines())\n assert lines == [\"def f():\", \" def g():\", \" pass\"]"},{"className":"TestAssert_reprcompare","col":0,"comment":"null","endLoc":608,"id":6817,"nodeType":"Class","startLoc":310,"text":"class TestAssert_reprcompare(object):\n def test_different_types(self):\n assert callequal([0, 1], \"foo\") is None\n\n def test_summary(self):\n summary = callequal([0, 1], [0, 2])[0]\n assert len(summary) < 65\n\n def test_text_diff(self):\n diff = callequal(\"spam\", \"eggs\")[1:]\n assert \"- spam\" in diff\n assert \"+ eggs\" in diff\n\n def test_text_skipping(self):\n lines = callequal(\"a\" * 50 + \"spam\", \"a\" * 50 + \"eggs\")\n assert \"Skipping\" in lines[1]\n for line in lines:\n assert \"a\" * 50 not in line\n\n def test_text_skipping_verbose(self):\n lines = callequal(\"a\" * 50 + \"spam\", \"a\" * 50 + \"eggs\", verbose=True)\n assert \"- \" + \"a\" * 50 + \"spam\" in lines\n assert \"+ \" + \"a\" * 50 + \"eggs\" in lines\n\n def test_multiline_text_diff(self):\n left = \"foo\\nspam\\nbar\"\n right = \"foo\\neggs\\nbar\"\n diff = callequal(left, right)\n assert \"- spam\" in diff\n assert \"+ eggs\" in diff\n\n def test_list(self):\n expl = callequal([0, 1], [0, 2])\n assert len(expl) > 1\n\n @pytest.mark.parametrize(\n [\"left\", \"right\", \"expected\"],\n [\n (\n [0, 1],\n [0, 2],\n \"\"\"\n Full diff:\n - [0, 1]\n ? ^\n + [0, 2]\n ? ^\n \"\"\",\n ),\n (\n {0: 1},\n {0: 2},\n \"\"\"\n Full diff:\n - {0: 1}\n ? ^\n + {0: 2}\n ? ^\n \"\"\",\n ),\n (\n {0, 1},\n {0, 2},\n \"\"\"\n Full diff:\n - set([0, 1])\n ? ^\n + set([0, 2])\n ? ^\n \"\"\"\n if not PY3\n else \"\"\"\n Full diff:\n - {0, 1}\n ? ^\n + {0, 2}\n ? ^\n \"\"\",\n ),\n ],\n )\n def test_iterable_full_diff(self, left, right, expected):\n \"\"\"Test the full diff assertion failure explanation.\n\n When verbose is False, then just a -v notice to get the diff is rendered,\n when verbose is True, then ndiff of the pprint is returned.\n \"\"\"\n expl = callequal(left, right, verbose=False)\n assert expl[-1] == \"Use -v to get the full diff\"\n expl = \"\\n\".join(callequal(left, right, verbose=True))\n assert expl.endswith(textwrap.dedent(expected).strip())\n\n def test_list_different_lengths(self):\n expl = callequal([0, 1], [0, 1, 2])\n assert len(expl) > 1\n expl = callequal([0, 1, 2], [0, 1])\n assert len(expl) > 1\n\n def test_dict(self):\n expl = callequal({\"a\": 0}, {\"a\": 1})\n assert len(expl) > 1\n\n def test_dict_omitting(self):\n lines = callequal({\"a\": 0, \"b\": 1}, {\"a\": 1, \"b\": 1})\n assert lines[1].startswith(\"Omitting 1 identical item\")\n assert \"Common items\" not in lines\n for line in lines[1:]:\n assert \"b\" not in line\n\n def test_dict_omitting_with_verbosity_1(self):\n \"\"\" Ensure differing items are visible for verbosity=1 (#1512) \"\"\"\n lines = callequal({\"a\": 0, \"b\": 1}, {\"a\": 1, \"b\": 1}, verbose=1)\n assert lines[1].startswith(\"Omitting 1 identical item\")\n assert lines[2].startswith(\"Differing items\")\n assert lines[3] == \"{'a': 0} != {'a': 1}\"\n assert \"Common items\" not in lines\n\n def test_dict_omitting_with_verbosity_2(self):\n lines = callequal({\"a\": 0, \"b\": 1}, {\"a\": 1, \"b\": 1}, verbose=2)\n assert lines[1].startswith(\"Common items:\")\n assert \"Omitting\" not in lines[1]\n assert lines[2] == \"{'b': 1}\"\n\n def test_dict_different_items(self):\n lines = callequal({\"a\": 0}, {\"b\": 1, \"c\": 2}, verbose=2)\n assert lines == [\n \"{'a': 0} == {'b': 1, 'c': 2}\",\n \"Left contains 1 more item:\",\n \"{'a': 0}\",\n \"Right contains 2 more items:\",\n \"{'b': 1, 'c': 2}\",\n \"Full diff:\",\n \"- {'a': 0}\",\n \"+ {'b': 1, 'c': 2}\",\n ]\n lines = callequal({\"b\": 1, \"c\": 2}, {\"a\": 0}, verbose=2)\n assert lines == [\n \"{'b': 1, 'c': 2} == {'a': 0}\",\n \"Left contains 2 more items:\",\n \"{'b': 1, 'c': 2}\",\n \"Right contains 1 more item:\",\n \"{'a': 0}\",\n \"Full diff:\",\n \"- {'b': 1, 'c': 2}\",\n \"+ {'a': 0}\",\n ]\n\n def test_sequence_different_items(self):\n lines = callequal((1, 2), (3, 4, 5), verbose=2)\n assert lines == [\n \"(1, 2) == (3, 4, 5)\",\n \"At index 0 diff: 1 != 3\",\n \"Right contains one more item: 5\",\n \"Full diff:\",\n \"- (1, 2)\",\n \"+ (3, 4, 5)\",\n ]\n lines = callequal((1, 2, 3), (4,), verbose=2)\n assert lines == [\n \"(1, 2, 3) == (4,)\",\n \"At index 0 diff: 1 != 4\",\n \"Left contains 2 more items, first extra item: 2\",\n \"Full diff:\",\n \"- (1, 2, 3)\",\n \"+ (4,)\",\n ]\n\n def test_set(self):\n expl = callequal({0, 1}, {0, 2})\n assert len(expl) > 1\n\n def test_frozenzet(self):\n expl = callequal(frozenset([0, 1]), {0, 2})\n assert len(expl) > 1\n\n def test_Sequence(self):\n if sys.version_info >= (3, 3):\n import collections.abc as collections_abc\n else:\n import collections as collections_abc\n if not hasattr(collections_abc, \"MutableSequence\"):\n pytest.skip(\"cannot import MutableSequence\")\n MutableSequence = collections_abc.MutableSequence\n\n class TestSequence(MutableSequence): # works with a Sequence subclass\n def __init__(self, iterable):\n self.elements = list(iterable)\n\n def __getitem__(self, item):\n return self.elements[item]\n\n def __len__(self):\n return len(self.elements)\n\n def __setitem__(self, item, value):\n pass\n\n def __delitem__(self, item):\n pass\n\n def insert(self, item, index):\n pass\n\n expl = callequal(TestSequence([0, 1]), list([0, 2]))\n assert len(expl) > 1\n\n def test_list_tuples(self):\n expl = callequal([], [(1, 2)])\n assert len(expl) > 1\n expl = callequal([(1, 2)], [])\n assert len(expl) > 1\n\n def test_repr_verbose(self):\n class Nums:\n def __init__(self, nums):\n self.nums = nums\n\n def __repr__(self):\n return str(self.nums)\n\n list_x = list(range(5000))\n list_y = list(range(5000))\n list_y[len(list_y) // 2] = 3\n nums_x = Nums(list_x)\n nums_y = Nums(list_y)\n\n assert callequal(nums_x, nums_y) is None\n\n expl = callequal(nums_x, nums_y, verbose=1)\n assert \"-\" + repr(nums_x) in expl\n assert \"+\" + repr(nums_y) in expl\n\n expl = callequal(nums_x, nums_y, verbose=2)\n assert \"-\" + repr(nums_x) in expl\n assert \"+\" + repr(nums_y) in expl\n\n def test_list_bad_repr(self):\n class A(object):\n def __repr__(self):\n raise ValueError(42)\n\n expl = callequal([], [A()])\n assert \"ValueError\" in \"\".join(expl)\n expl = callequal({}, {\"1\": A()})\n assert \"faulty\" in \"\".join(expl)\n\n def test_one_repr_empty(self):\n \"\"\"\n the faulty empty string repr did trigger\n an unbound local error in _diff_text\n \"\"\"\n\n class A(str):\n def __repr__(self):\n return \"\"\n\n expl = callequal(A(), \"\")\n assert not expl\n\n def test_repr_no_exc(self):\n expl = \" \".join(callequal(\"foo\", \"bar\"))\n assert \"raised in repr()\" not in expl\n\n def test_unicode(self):\n left = u\"£€\"\n right = u\"£\"\n expl = callequal(left, right)\n assert expl[0] == u\"'£€' == '£'\"\n assert expl[1] == u\"- £€\"\n assert expl[2] == u\"+ £\"\n\n def test_nonascii_text(self):\n \"\"\"\n :issue: 877\n non ascii python2 str caused a UnicodeDecodeError\n \"\"\"\n\n class A(str):\n def __repr__(self):\n return \"\\xff\"\n\n expl = callequal(A(), \"1\")\n if PY3:\n assert expl == [\"ÿ == '1'\", \"+ 1\"]\n else:\n assert expl == [u\"\\ufffd == '1'\", u\"+ 1\"]\n\n def test_format_nonascii_explanation(self):\n assert util.format_explanation(\"λ\")\n\n def test_mojibake(self):\n # issue 429\n left = b\"e\"\n right = b\"\\xc3\\xa9\"\n expl = callequal(left, right)\n for line in expl:\n assert isinstance(line, six.text_type)\n msg = u\"\\n\".join(expl)\n assert msg"},{"col":4,"comment":"null","endLoc":312,"header":"def test_different_types(self)","id":6818,"name":"test_different_types","nodeType":"Function","startLoc":311,"text":"def test_different_types(self):\n assert callequal([0, 1], \"foo\") is None"},{"col":0,"comment":"null","endLoc":307,"header":"def callequal(left, right, verbose=False)","id":6819,"name":"callequal","nodeType":"Function","startLoc":304,"text":"def callequal(left, right, verbose=False):\n config = mock_config()\n config.verbose = verbose\n return plugin.pytest_assertrepr_compare(config, \"==\", left, right)"},{"col":4,"comment":"null","endLoc":369,"header":"def chmod_r(self, path)","id":6820,"name":"chmod_r","nodeType":"Function","startLoc":367,"text":"def chmod_r(self, path):\n mode = os.stat(str(path)).st_mode\n os.chmod(str(path), mode & ~stat.S_IWRITE)"},{"col":0,"comment":"null","endLoc":30,"header":"def mock_config()","id":6822,"name":"mock_config","nodeType":"Function","startLoc":21,"text":"def mock_config():\n class Config(object):\n verbose = False\n\n def getoption(self, name):\n if name == \"verbose\":\n return self.verbose\n raise KeyError(\"Not mocked out: %s\" % name)\n\n return Config()"},{"fileName":"cacheprovider.py","filePath":"src/_pytest","id":6824,"nodeType":"File","text":"# -*- coding: utf-8 -*-\n\"\"\"\nmerged implementation of the cache provider\n\nthe name cache was not chosen to ensure pluggy automatically\nignores the external pytest-cache\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport json\nimport os\nfrom collections import OrderedDict\n\nimport attr\nimport py\nimport six\n\nimport pytest\nfrom .compat import _PY2 as PY2\nfrom .pathlib import Path\nfrom .pathlib import resolve_from_str\nfrom .pathlib import rm_rf\n\nREADME_CONTENT = u\"\"\"\\\n# pytest cache directory #\n\nThis directory contains data from the pytest's cache plugin,\nwhich provides the `--lf` and `--ff` options, as well as the `cache` fixture.\n\n**Do not** commit this to version control.\n\nSee [the docs](https://docs.pytest.org/en/latest/cache.html) for more information.\n\"\"\"\n\nCACHEDIR_TAG_CONTENT = b\"\"\"\\\nSignature: 8a477f597d28d172789f06886806bc55\n# This file is a cache directory tag created by pytest.\n# For information about cache directory tags, see:\n#\thttp://www.bford.info/cachedir/spec.html\n\"\"\"\n\n\n@attr.s\nclass Cache(object):\n _cachedir = attr.ib(repr=False)\n _config = attr.ib(repr=False)\n\n @classmethod\n def for_config(cls, config):\n cachedir = cls.cache_dir_from_config(config)\n if config.getoption(\"cacheclear\") and cachedir.exists():\n rm_rf(cachedir)\n cachedir.mkdir()\n return cls(cachedir, config)\n\n @staticmethod\n def cache_dir_from_config(config):\n return resolve_from_str(config.getini(\"cache_dir\"), config.rootdir)\n\n def warn(self, fmt, **args):\n from _pytest.warnings import _issue_warning_captured\n from _pytest.warning_types import PytestCacheWarning\n\n _issue_warning_captured(\n PytestCacheWarning(fmt.format(**args) if args else fmt),\n self._config.hook,\n stacklevel=3,\n )\n\n def makedir(self, name):\n \"\"\" return a directory path object with the given name. If the\n directory does not yet exist, it will be created. You can use it\n to manage files likes e. g. store/retrieve database\n dumps across test sessions.\n\n :param name: must be a string not containing a ``/`` separator.\n Make sure the name contains your plugin or application\n identifiers to prevent clashes with other cache users.\n \"\"\"\n name = Path(name)\n if len(name.parts) > 1:\n raise ValueError(\"name is not allowed to contain path separators\")\n res = self._cachedir.joinpath(\"d\", name)\n res.mkdir(exist_ok=True, parents=True)\n return py.path.local(res)\n\n def _getvaluepath(self, key):\n return self._cachedir.joinpath(\"v\", Path(key))\n\n def get(self, key, default):\n \"\"\" return cached value for the given key. If no value\n was yet cached or the value cannot be read, the specified\n default is returned.\n\n :param key: must be a ``/`` separated value. Usually the first\n name is the name of your plugin or your application.\n :param default: must be provided in case of a cache-miss or\n invalid cache values.\n\n \"\"\"\n path = self._getvaluepath(key)\n try:\n with path.open(\"r\") as f:\n return json.load(f)\n except (ValueError, IOError, OSError):\n return default\n\n def set(self, key, value):\n \"\"\" save value for the given key.\n\n :param key: must be a ``/`` separated value. Usually the first\n name is the name of your plugin or your application.\n :param value: must be of any combination of basic\n python types, including nested types\n like e. g. lists of dictionaries.\n \"\"\"\n path = self._getvaluepath(key)\n try:\n if path.parent.is_dir():\n cache_dir_exists_already = True\n else:\n cache_dir_exists_already = self._cachedir.exists()\n path.parent.mkdir(exist_ok=True, parents=True)\n except (IOError, OSError):\n self.warn(\"could not create cache path {path}\", path=path)\n return\n if not cache_dir_exists_already:\n self._ensure_supporting_files()\n try:\n f = path.open(\"wb\" if PY2 else \"w\")\n except (IOError, OSError):\n self.warn(\"cache could not write path {path}\", path=path)\n else:\n with f:\n json.dump(value, f, indent=2, sort_keys=True)\n\n def _ensure_supporting_files(self):\n \"\"\"Create supporting files in the cache dir that are not really part of the cache.\"\"\"\n readme_path = self._cachedir / \"README.md\"\n readme_path.write_text(README_CONTENT)\n\n gitignore_path = self._cachedir.joinpath(\".gitignore\")\n msg = u\"# Created by pytest automatically.\\n*\"\n gitignore_path.write_text(msg, encoding=\"UTF-8\")\n\n cachedir_tag_path = self._cachedir.joinpath(\"CACHEDIR.TAG\")\n cachedir_tag_path.write_bytes(CACHEDIR_TAG_CONTENT)\n\n\nclass LFPlugin(object):\n \"\"\" Plugin which implements the --lf (run last-failing) option \"\"\"\n\n def __init__(self, config):\n self.config = config\n active_keys = \"lf\", \"failedfirst\"\n self.active = any(config.getoption(key) for key in active_keys)\n self.lastfailed = config.cache.get(\"cache/lastfailed\", {})\n self._previously_failed_count = None\n self._report_status = None\n self._skipped_files = 0 # count skipped files during collection due to --lf\n\n def last_failed_paths(self):\n \"\"\"Returns a set with all Paths()s of the previously failed nodeids (cached).\n \"\"\"\n try:\n return self._last_failed_paths\n except AttributeError:\n rootpath = Path(self.config.rootdir)\n result = {rootpath / nodeid.split(\"::\")[0] for nodeid in self.lastfailed}\n result = {x for x in result if x.exists()}\n self._last_failed_paths = result\n return result\n\n def pytest_ignore_collect(self, path):\n \"\"\"\n Ignore this file path if we are in --lf mode and it is not in the list of\n previously failed files.\n \"\"\"\n if self.active and self.config.getoption(\"lf\") and path.isfile():\n last_failed_paths = self.last_failed_paths()\n if last_failed_paths:\n skip_it = Path(path) not in self.last_failed_paths()\n if skip_it:\n self._skipped_files += 1\n return skip_it\n\n def pytest_report_collectionfinish(self):\n if self.active and self.config.getoption(\"verbose\") >= 0:\n return \"run-last-failure: %s\" % self._report_status\n\n def pytest_runtest_logreport(self, report):\n if (report.when == \"call\" and report.passed) or report.skipped:\n self.lastfailed.pop(report.nodeid, None)\n elif report.failed:\n self.lastfailed[report.nodeid] = True\n\n def pytest_collectreport(self, report):\n passed = report.outcome in (\"passed\", \"skipped\")\n if passed:\n if report.nodeid in self.lastfailed:\n self.lastfailed.pop(report.nodeid)\n self.lastfailed.update((item.nodeid, True) for item in report.result)\n else:\n self.lastfailed[report.nodeid] = True\n\n def pytest_collection_modifyitems(self, session, config, items):\n if not self.active:\n return\n\n if self.lastfailed:\n previously_failed = []\n previously_passed = []\n for item in items:\n if item.nodeid in self.lastfailed:\n previously_failed.append(item)\n else:\n previously_passed.append(item)\n self._previously_failed_count = len(previously_failed)\n\n if not previously_failed:\n # Running a subset of all tests with recorded failures\n # only outside of it.\n self._report_status = \"%d known failures not in selected tests\" % (\n len(self.lastfailed),\n )\n else:\n if self.config.getoption(\"lf\"):\n items[:] = previously_failed\n config.hook.pytest_deselected(items=previously_passed)\n else: # --failedfirst\n items[:] = previously_failed + previously_passed\n\n noun = \"failure\" if self._previously_failed_count == 1 else \"failures\"\n suffix = \" first\" if self.config.getoption(\"failedfirst\") else \"\"\n self._report_status = \"rerun previous {count} {noun}{suffix}\".format(\n count=self._previously_failed_count, suffix=suffix, noun=noun\n )\n\n if self._skipped_files > 0:\n files_noun = \"file\" if self._skipped_files == 1 else \"files\"\n self._report_status += \" (skipped {files} {files_noun})\".format(\n files=self._skipped_files, files_noun=files_noun\n )\n else:\n self._report_status = \"no previously failed tests, \"\n if self.config.getoption(\"last_failed_no_failures\") == \"none\":\n self._report_status += \"deselecting all items.\"\n config.hook.pytest_deselected(items=items)\n items[:] = []\n else:\n self._report_status += \"not deselecting items.\"\n\n def pytest_sessionfinish(self, session):\n config = self.config\n if config.getoption(\"cacheshow\") or hasattr(config, \"slaveinput\"):\n return\n\n saved_lastfailed = config.cache.get(\"cache/lastfailed\", {})\n if saved_lastfailed != self.lastfailed:\n config.cache.set(\"cache/lastfailed\", self.lastfailed)\n\n\nclass NFPlugin(object):\n \"\"\" Plugin which implements the --nf (run new-first) option \"\"\"\n\n def __init__(self, config):\n self.config = config\n self.active = config.option.newfirst\n self.cached_nodeids = config.cache.get(\"cache/nodeids\", [])\n\n def pytest_collection_modifyitems(self, session, config, items):\n if self.active:\n new_items = OrderedDict()\n other_items = OrderedDict()\n for item in items:\n if item.nodeid not in self.cached_nodeids:\n new_items[item.nodeid] = item\n else:\n other_items[item.nodeid] = item\n\n items[:] = self._get_increasing_order(\n six.itervalues(new_items)\n ) + self._get_increasing_order(six.itervalues(other_items))\n self.cached_nodeids = [x.nodeid for x in items if isinstance(x, pytest.Item)]\n\n def _get_increasing_order(self, items):\n return sorted(items, key=lambda item: item.fspath.mtime(), reverse=True)\n\n def pytest_sessionfinish(self, session):\n config = self.config\n if config.getoption(\"cacheshow\") or hasattr(config, \"slaveinput\"):\n return\n\n config.cache.set(\"cache/nodeids\", self.cached_nodeids)\n\n\ndef pytest_addoption(parser):\n group = parser.getgroup(\"general\")\n group.addoption(\n \"--lf\",\n \"--last-failed\",\n action=\"store_true\",\n dest=\"lf\",\n help=\"rerun only the tests that failed \"\n \"at the last run (or all if none failed)\",\n )\n group.addoption(\n \"--ff\",\n \"--failed-first\",\n action=\"store_true\",\n dest=\"failedfirst\",\n help=\"run all tests but run the last failures first. \"\n \"This may re-order tests and thus lead to \"\n \"repeated fixture setup/teardown\",\n )\n group.addoption(\n \"--nf\",\n \"--new-first\",\n action=\"store_true\",\n dest=\"newfirst\",\n help=\"run tests from new files first, then the rest of the tests \"\n \"sorted by file mtime\",\n )\n group.addoption(\n \"--cache-show\",\n action=\"append\",\n nargs=\"?\",\n dest=\"cacheshow\",\n help=(\n \"show cache contents, don't perform collection or tests. \"\n \"Optional argument: glob (default: '*').\"\n ),\n )\n group.addoption(\n \"--cache-clear\",\n action=\"store_true\",\n dest=\"cacheclear\",\n help=\"remove all cache contents at start of test run.\",\n )\n cache_dir_default = \".pytest_cache\"\n if \"TOX_ENV_DIR\" in os.environ:\n cache_dir_default = os.path.join(os.environ[\"TOX_ENV_DIR\"], cache_dir_default)\n parser.addini(\"cache_dir\", default=cache_dir_default, help=\"cache directory path.\")\n group.addoption(\n \"--lfnf\",\n \"--last-failed-no-failures\",\n action=\"store\",\n dest=\"last_failed_no_failures\",\n choices=(\"all\", \"none\"),\n default=\"all\",\n help=\"which tests to run with no previously (known) failures.\",\n )\n\n\ndef pytest_cmdline_main(config):\n if config.option.cacheshow:\n from _pytest.main import wrap_session\n\n return wrap_session(config, cacheshow)\n\n\n@pytest.hookimpl(tryfirst=True)\ndef pytest_configure(config):\n config.cache = Cache.for_config(config)\n config.pluginmanager.register(LFPlugin(config), \"lfplugin\")\n config.pluginmanager.register(NFPlugin(config), \"nfplugin\")\n\n\n@pytest.fixture\ndef cache(request):\n \"\"\"\n Return a cache object that can persist state between testing sessions.\n\n cache.get(key, default)\n cache.set(key, value)\n\n Keys must be a ``/`` separated value, where the first part is usually the\n name of your plugin or application to avoid clashes with other cache users.\n\n Values can be any object handled by the json stdlib module.\n \"\"\"\n return request.config.cache\n\n\ndef pytest_report_header(config):\n \"\"\"Display cachedir with --cache-show and if non-default.\"\"\"\n if config.option.verbose > 0 or config.getini(\"cache_dir\") != \".pytest_cache\":\n cachedir = config.cache._cachedir\n # TODO: evaluate generating upward relative paths\n # starting with .., ../.. if sensible\n\n try:\n displaypath = cachedir.relative_to(config.rootdir)\n except ValueError:\n displaypath = cachedir\n return \"cachedir: {}\".format(displaypath)\n\n\ndef cacheshow(config, session):\n from pprint import pformat\n\n tw = py.io.TerminalWriter()\n tw.line(\"cachedir: \" + str(config.cache._cachedir))\n if not config.cache._cachedir.is_dir():\n tw.line(\"cache is empty\")\n return 0\n\n glob = config.option.cacheshow[0]\n if glob is None:\n glob = \"*\"\n\n dummy = object()\n basedir = config.cache._cachedir\n vdir = basedir / \"v\"\n tw.sep(\"-\", \"cache values for %r\" % glob)\n for valpath in sorted(x for x in vdir.rglob(glob) if x.is_file()):\n key = valpath.relative_to(vdir)\n val = config.cache.get(key, dummy)\n if val is dummy:\n tw.line(\"%s contains unreadable content, will be ignored\" % key)\n else:\n tw.line(\"%s contains:\" % key)\n for line in pformat(val).splitlines():\n tw.line(\" \" + line)\n\n ddir = basedir / \"d\"\n if ddir.is_dir():\n contents = sorted(ddir.rglob(glob))\n tw.sep(\"-\", \"cache directories for %r\" % glob)\n for p in contents:\n # if p.check(dir=1):\n # print(\"%s/\" % p.relto(basedir))\n if p.is_file():\n key = p.relative_to(basedir)\n tw.line(\"{} is a file of length {:d}\".format(key, p.stat().st_size))\n return 0\n"},{"col":4,"comment":"Ensure rm_rf can remove read-only directories (#5524)","endLoc":383,"header":"def test_rm_rf_with_read_only_directory(self, tmp_path)","id":6825,"name":"test_rm_rf_with_read_only_directory","nodeType":"Function","startLoc":371,"text":"def test_rm_rf_with_read_only_directory(self, tmp_path):\n \"\"\"Ensure rm_rf can remove read-only directories (#5524)\"\"\"\n from _pytest.pathlib import rm_rf\n\n adir = tmp_path / \"dir\"\n adir.mkdir()\n\n (adir / \"foo.txt\").touch()\n self.chmod_r(adir)\n\n rm_rf(adir)\n\n assert not adir.is_dir()"},{"col":4,"comment":"null","endLoc":316,"header":"def test_summary(self)","id":6826,"name":"test_summary","nodeType":"Function","startLoc":314,"text":"def test_summary(self):\n summary = callequal([0, 1], [0, 2])[0]\n assert len(summary) < 65"},{"col":4,"comment":"null","endLoc":720,"header":"def test_repr_tracebackentry_lines_var_kw_args(self, importasmod)","id":6827,"name":"test_repr_tracebackentry_lines_var_kw_args","nodeType":"Function","startLoc":699,"text":"def test_repr_tracebackentry_lines_var_kw_args(self, importasmod):\n mod = importasmod(\n \"\"\"\n def func1(x, *y, **z):\n raise ValueError(\"hello\\\\nworld\")\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.func1, \"a\", \"b\", c=\"d\")\n excinfo.traceback = excinfo.traceback.filter()\n entry = excinfo.traceback[-1]\n p = FormattedExcinfo(funcargs=True)\n reprfuncargs = p.repr_args(entry)\n assert reprfuncargs.args[0] == (\"x\", repr(\"a\"))\n assert reprfuncargs.args[1] == (\"y\", repr((\"b\",)))\n assert reprfuncargs.args[2] == (\"z\", repr({\"c\": \"d\"}))\n\n p = FormattedExcinfo(funcargs=True)\n repr_entry = p.repr_traceback_entry(entry)\n assert repr_entry.reprfuncargs.args == reprfuncargs.args\n tw = TWMock()\n repr_entry.toterminal(tw)\n assert tw.lines[0] == \"x = 'a', y = ('b',), z = {'c': 'd'}\""},{"col":4,"comment":"null","endLoc":321,"header":"def test_text_diff(self)","id":6828,"name":"test_text_diff","nodeType":"Function","startLoc":318,"text":"def test_text_diff(self):\n diff = callequal(\"spam\", \"eggs\")[1:]\n assert \"- spam\" in diff\n assert \"+ eggs\" in diff"},{"col":4,"comment":"null","endLoc":327,"header":"def test_text_skipping(self)","id":6829,"name":"test_text_skipping","nodeType":"Function","startLoc":323,"text":"def test_text_skipping(self):\n lines = callequal(\"a\" * 50 + \"spam\", \"a\" * 50 + \"eggs\")\n assert \"Skipping\" in lines[1]\n for line in lines:\n assert \"a\" * 50 not in line"},{"col":4,"comment":"null","endLoc":332,"header":"def test_text_skipping_verbose(self)","id":6830,"name":"test_text_skipping_verbose","nodeType":"Function","startLoc":329,"text":"def test_text_skipping_verbose(self):\n lines = callequal(\"a\" * 50 + \"spam\", \"a\" * 50 + \"eggs\", verbose=True)\n assert \"- \" + \"a\" * 50 + \"spam\" in lines\n assert \"+ \" + \"a\" * 50 + \"eggs\" in lines"},{"col":4,"comment":"null","endLoc":339,"header":"def test_multiline_text_diff(self)","id":6831,"name":"test_multiline_text_diff","nodeType":"Function","startLoc":334,"text":"def test_multiline_text_diff(self):\n left = \"foo\\nspam\\nbar\"\n right = \"foo\\neggs\\nbar\"\n diff = callequal(left, right)\n assert \"- spam\" in diff\n assert \"+ eggs\" in diff"},{"col":4,"comment":"null","endLoc":343,"header":"def test_list(self)","id":6832,"name":"test_list","nodeType":"Function","startLoc":341,"text":"def test_list(self):\n expl = callequal([0, 1], [0, 2])\n assert len(expl) > 1"},{"col":4,"comment":"Test the full diff assertion failure explanation.\n\n When verbose is False, then just a -v notice to get the diff is rendered,\n when verbose is True, then ndiff of the pprint is returned.\n ","endLoc":400,"header":"@pytest.mark.parametrize(\n [\"left\", \"right\", \"expected\"],\n [\n (\n [0, 1],\n [0, 2],\n \"\"\"\n Full diff:\n - [0, 1]\n ? ^\n + [0, 2]\n ? ^\n \"\"\",\n ),\n (\n {0","id":6833,"name":"test_iterable_full_diff","nodeType":"Function","startLoc":345,"text":"@pytest.mark.parametrize(\n [\"left\", \"right\", \"expected\"],\n [\n (\n [0, 1],\n [0, 2],\n \"\"\"\n Full diff:\n - [0, 1]\n ? ^\n + [0, 2]\n ? ^\n \"\"\",\n ),\n (\n {0: 1},\n {0: 2},\n \"\"\"\n Full diff:\n - {0: 1}\n ? ^\n + {0: 2}\n ? ^\n \"\"\",\n ),\n (\n {0, 1},\n {0, 2},\n \"\"\"\n Full diff:\n - set([0, 1])\n ? ^\n + set([0, 2])\n ? ^\n \"\"\"\n if not PY3\n else \"\"\"\n Full diff:\n - {0, 1}\n ? ^\n + {0, 2}\n ? ^\n \"\"\",\n ),\n ],\n )\n def test_iterable_full_diff(self, left, right, expected):\n \"\"\"Test the full diff assertion failure explanation.\n\n When verbose is False, then just a -v notice to get the diff is rendered,\n when verbose is True, then ndiff of the pprint is returned.\n \"\"\"\n expl = callequal(left, right, verbose=False)\n assert expl[-1] == \"Use -v to get the full diff\"\n expl = \"\\n\".join(callequal(left, right, verbose=True))\n assert expl.endswith(textwrap.dedent(expected).strip())"},{"className":"Cache","col":0,"comment":"null","endLoc":149,"id":6834,"nodeType":"Class","startLoc":45,"text":"@attr.s\nclass Cache(object):\n _cachedir = attr.ib(repr=False)\n _config = attr.ib(repr=False)\n\n @classmethod\n def for_config(cls, config):\n cachedir = cls.cache_dir_from_config(config)\n if config.getoption(\"cacheclear\") and cachedir.exists():\n rm_rf(cachedir)\n cachedir.mkdir()\n return cls(cachedir, config)\n\n @staticmethod\n def cache_dir_from_config(config):\n return resolve_from_str(config.getini(\"cache_dir\"), config.rootdir)\n\n def warn(self, fmt, **args):\n from _pytest.warnings import _issue_warning_captured\n from _pytest.warning_types import PytestCacheWarning\n\n _issue_warning_captured(\n PytestCacheWarning(fmt.format(**args) if args else fmt),\n self._config.hook,\n stacklevel=3,\n )\n\n def makedir(self, name):\n \"\"\" return a directory path object with the given name. If the\n directory does not yet exist, it will be created. You can use it\n to manage files likes e. g. store/retrieve database\n dumps across test sessions.\n\n :param name: must be a string not containing a ``/`` separator.\n Make sure the name contains your plugin or application\n identifiers to prevent clashes with other cache users.\n \"\"\"\n name = Path(name)\n if len(name.parts) > 1:\n raise ValueError(\"name is not allowed to contain path separators\")\n res = self._cachedir.joinpath(\"d\", name)\n res.mkdir(exist_ok=True, parents=True)\n return py.path.local(res)\n\n def _getvaluepath(self, key):\n return self._cachedir.joinpath(\"v\", Path(key))\n\n def get(self, key, default):\n \"\"\" return cached value for the given key. If no value\n was yet cached or the value cannot be read, the specified\n default is returned.\n\n :param key: must be a ``/`` separated value. Usually the first\n name is the name of your plugin or your application.\n :param default: must be provided in case of a cache-miss or\n invalid cache values.\n\n \"\"\"\n path = self._getvaluepath(key)\n try:\n with path.open(\"r\") as f:\n return json.load(f)\n except (ValueError, IOError, OSError):\n return default\n\n def set(self, key, value):\n \"\"\" save value for the given key.\n\n :param key: must be a ``/`` separated value. Usually the first\n name is the name of your plugin or your application.\n :param value: must be of any combination of basic\n python types, including nested types\n like e. g. lists of dictionaries.\n \"\"\"\n path = self._getvaluepath(key)\n try:\n if path.parent.is_dir():\n cache_dir_exists_already = True\n else:\n cache_dir_exists_already = self._cachedir.exists()\n path.parent.mkdir(exist_ok=True, parents=True)\n except (IOError, OSError):\n self.warn(\"could not create cache path {path}\", path=path)\n return\n if not cache_dir_exists_already:\n self._ensure_supporting_files()\n try:\n f = path.open(\"wb\" if PY2 else \"w\")\n except (IOError, OSError):\n self.warn(\"cache could not write path {path}\", path=path)\n else:\n with f:\n json.dump(value, f, indent=2, sort_keys=True)\n\n def _ensure_supporting_files(self):\n \"\"\"Create supporting files in the cache dir that are not really part of the cache.\"\"\"\n readme_path = self._cachedir / \"README.md\"\n readme_path.write_text(README_CONTENT)\n\n gitignore_path = self._cachedir.joinpath(\".gitignore\")\n msg = u\"# Created by pytest automatically.\\n*\"\n gitignore_path.write_text(msg, encoding=\"UTF-8\")\n\n cachedir_tag_path = self._cachedir.joinpath(\"CACHEDIR.TAG\")\n cachedir_tag_path.write_bytes(CACHEDIR_TAG_CONTENT)"},{"col":4,"comment":"null","endLoc":70,"header":"def warn(self, fmt, **args)","id":6835,"name":"warn","nodeType":"Function","startLoc":62,"text":"def warn(self, fmt, **args):\n from _pytest.warnings import _issue_warning_captured\n from _pytest.warning_types import PytestCacheWarning\n\n _issue_warning_captured(\n PytestCacheWarning(fmt.format(**args) if args else fmt),\n self._config.hook,\n stacklevel=3,\n )"},{"col":4,"comment":"null","endLoc":901,"header":"def visit_Name(self, name)","id":6837,"name":"visit_Name","nodeType":"Function","startLoc":893,"text":"def visit_Name(self, name):\n # Display the repr of the name if it's a local variable or\n # _should_repr_global_name() thinks it's acceptable.\n locs = ast_Call(self.builtin(\"locals\"), [], [])\n inlocs = ast.Compare(ast.Str(name.id), [ast.In()], [locs])\n dorepr = self.helper(\"_should_repr_global_name\", name)\n test = ast.BoolOp(ast.Or(), [inlocs, dorepr])\n expr = ast.IfExp(test, self.display(name), ast.Str(name.id))\n return name, self.explanation_param(expr)"},{"col":4,"comment":"null","endLoc":412,"header":"def test_on_rm_rf_error(self, tmp_path)","id":6838,"name":"test_on_rm_rf_error","nodeType":"Function","startLoc":385,"text":"def test_on_rm_rf_error(self, tmp_path):\n from _pytest.pathlib import on_rm_rf_error\n\n adir = tmp_path / \"dir\"\n adir.mkdir()\n\n fn = adir / \"foo.txt\"\n fn.touch()\n self.chmod_r(fn)\n\n # unknown exception\n with pytest.warns(pytest.PytestWarning):\n exc_info = (None, RuntimeError(), None)\n on_rm_rf_error(os.unlink, str(fn), exc_info, start_path=tmp_path)\n assert fn.is_file()\n\n permission_error = OSError()\n permission_error.errno = errno.EACCES\n\n # unknown function\n with pytest.warns(pytest.PytestWarning):\n exc_info = (None, permission_error, None)\n on_rm_rf_error(None, str(fn), exc_info, start_path=tmp_path)\n assert fn.is_file()\n\n exc_info = (None, permission_error, None)\n on_rm_rf_error(os.unlink, str(fn), exc_info, start_path=tmp_path)\n assert not fn.is_file()"},{"col":0,"comment":"null","endLoc":424,"header":"def test_source_of_class_at_eof_without_newline(tmpdir, _sys_snapshot)","id":6839,"name":"test_source_of_class_at_eof_without_newline","nodeType":"Function","startLoc":411,"text":"def test_source_of_class_at_eof_without_newline(tmpdir, _sys_snapshot):\n # this test fails because the implicit inspect.getsource(A) below\n # does not return the \"x = 1\" last line.\n source = _pytest._code.Source(\n \"\"\"\n class A(object):\n def method(self):\n x = 1\n \"\"\"\n )\n path = tmpdir.join(\"a.py\")\n path.write(source)\n s2 = _pytest._code.Source(tmpdir.join(\"a.py\").pyimport().A)\n assert str(source).strip() == str(s2).strip()"},{"col":4,"comment":" return a directory path object with the given name. If the\n directory does not yet exist, it will be created. You can use it\n to manage files likes e. g. store/retrieve database\n dumps across test sessions.\n\n :param name: must be a string not containing a ``/`` separator.\n Make sure the name contains your plugin or application\n identifiers to prevent clashes with other cache users.\n ","endLoc":87,"header":"def makedir(self, name)","id":6840,"name":"makedir","nodeType":"Function","startLoc":72,"text":"def makedir(self, name):\n \"\"\" return a directory path object with the given name. If the\n directory does not yet exist, it will be created. You can use it\n to manage files likes e. g. store/retrieve database\n dumps across test sessions.\n\n :param name: must be a string not containing a ``/`` separator.\n Make sure the name contains your plugin or application\n identifiers to prevent clashes with other cache users.\n \"\"\"\n name = Path(name)\n if len(name.parts) > 1:\n raise ValueError(\"name is not allowed to contain path separators\")\n res = self._cachedir.joinpath(\"d\", name)\n res.mkdir(exist_ok=True, parents=True)\n return py.path.local(res)"},{"col":4,"comment":"null","endLoc":747,"header":"def test_repr_tracebackentry_short(self, importasmod)","id":6841,"name":"test_repr_tracebackentry_short","nodeType":"Function","startLoc":722,"text":"def test_repr_tracebackentry_short(self, importasmod):\n mod = importasmod(\n \"\"\"\n def func1():\n raise ValueError(\"hello\")\n def entry():\n func1()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n p = FormattedExcinfo(style=\"short\")\n reprtb = p.repr_traceback_entry(excinfo.traceback[-2])\n lines = reprtb.lines\n basename = py.path.local(mod.__file__).basename\n assert lines[0] == \" func1()\"\n assert basename in str(reprtb.reprfileloc.path)\n assert reprtb.reprfileloc.lineno == 5\n\n # test last entry\n p = FormattedExcinfo(style=\"short\")\n reprtb = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)\n lines = reprtb.lines\n assert lines[0] == ' raise ValueError(\"hello\")'\n assert lines[1] == \"E ValueError: hello\"\n assert basename in str(reprtb.reprfileloc.path)\n assert reprtb.reprfileloc.lineno == 3"},{"col":4,"comment":"null","endLoc":90,"header":"def _getvaluepath(self, key)","id":6842,"name":"_getvaluepath","nodeType":"Function","startLoc":89,"text":"def _getvaluepath(self, key):\n return self._cachedir.joinpath(\"v\", Path(key))"},{"col":4,"comment":" return cached value for the given key. If no value\n was yet cached or the value cannot be read, the specified\n default is returned.\n\n :param key: must be a ``/`` separated value. Usually the first\n name is the name of your plugin or your application.\n :param default: must be provided in case of a cache-miss or\n invalid cache values.\n\n ","endLoc":108,"header":"def get(self, key, default)","id":6843,"name":"get","nodeType":"Function","startLoc":92,"text":"def get(self, key, default):\n \"\"\" return cached value for the given key. If no value\n was yet cached or the value cannot be read, the specified\n default is returned.\n\n :param key: must be a ``/`` separated value. Usually the first\n name is the name of your plugin or your application.\n :param default: must be provided in case of a cache-miss or\n invalid cache values.\n\n \"\"\"\n path = self._getvaluepath(key)\n try:\n with path.open(\"r\") as f:\n return json.load(f)\n except (ValueError, IOError, OSError):\n return default"},{"col":4,"comment":" save value for the given key.\n\n :param key: must be a ``/`` separated value. Usually the first\n name is the name of your plugin or your application.\n :param value: must be of any combination of basic\n python types, including nested types\n like e. g. lists of dictionaries.\n ","endLoc":137,"header":"def set(self, key, value)","id":6845,"name":"set","nodeType":"Function","startLoc":110,"text":"def set(self, key, value):\n \"\"\" save value for the given key.\n\n :param key: must be a ``/`` separated value. Usually the first\n name is the name of your plugin or your application.\n :param value: must be of any combination of basic\n python types, including nested types\n like e. g. lists of dictionaries.\n \"\"\"\n path = self._getvaluepath(key)\n try:\n if path.parent.is_dir():\n cache_dir_exists_already = True\n else:\n cache_dir_exists_already = self._cachedir.exists()\n path.parent.mkdir(exist_ok=True, parents=True)\n except (IOError, OSError):\n self.warn(\"could not create cache path {path}\", path=path)\n return\n if not cache_dir_exists_already:\n self._ensure_supporting_files()\n try:\n f = path.open(\"wb\" if PY2 else \"w\")\n except (IOError, OSError):\n self.warn(\"cache could not write path {path}\", path=path)\n else:\n with f:\n json.dump(value, f, indent=2, sort_keys=True)"},{"col":4,"comment":"null","endLoc":766,"header":"def test_repr_tracebackentry_no(self, importasmod)","id":6846,"name":"test_repr_tracebackentry_no","nodeType":"Function","startLoc":749,"text":"def test_repr_tracebackentry_no(self, importasmod):\n mod = importasmod(\n \"\"\"\n def func1():\n raise ValueError(\"hello\")\n def entry():\n func1()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n p = FormattedExcinfo(style=\"no\")\n p.repr_traceback_entry(excinfo.traceback[-2])\n\n p = FormattedExcinfo(style=\"no\")\n reprentry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)\n lines = reprentry.lines\n assert lines[0] == \"E ValueError: hello\"\n assert not lines[1:]"},{"col":4,"comment":"Create supporting files in the cache dir that are not really part of the cache.","endLoc":149,"header":"def _ensure_supporting_files(self)","id":6847,"name":"_ensure_supporting_files","nodeType":"Function","startLoc":139,"text":"def _ensure_supporting_files(self):\n \"\"\"Create supporting files in the cache dir that are not really part of the cache.\"\"\"\n readme_path = self._cachedir / \"README.md\"\n readme_path.write_text(README_CONTENT)\n\n gitignore_path = self._cachedir.joinpath(\".gitignore\")\n msg = u\"# Created by pytest automatically.\\n*\"\n gitignore_path.write_text(msg, encoding=\"UTF-8\")\n\n cachedir_tag_path = self._cachedir.joinpath(\"CACHEDIR.TAG\")\n cachedir_tag_path.write_bytes(CACHEDIR_TAG_CONTENT)"},{"attributeType":"null","col":4,"comment":"null","endLoc":47,"id":6849,"name":"_cachedir","nodeType":"Attribute","startLoc":47,"text":"_cachedir"},{"attributeType":"null","col":4,"comment":"null","endLoc":48,"id":6850,"name":"_config","nodeType":"Attribute","startLoc":48,"text":"_config"},{"className":"LFPlugin","col":0,"comment":" Plugin which implements the --lf (run last-failing) option ","endLoc":262,"id":6851,"nodeType":"Class","startLoc":152,"text":"class LFPlugin(object):\n \"\"\" Plugin which implements the --lf (run last-failing) option \"\"\"\n\n def __init__(self, config):\n self.config = config\n active_keys = \"lf\", \"failedfirst\"\n self.active = any(config.getoption(key) for key in active_keys)\n self.lastfailed = config.cache.get(\"cache/lastfailed\", {})\n self._previously_failed_count = None\n self._report_status = None\n self._skipped_files = 0 # count skipped files during collection due to --lf\n\n def last_failed_paths(self):\n \"\"\"Returns a set with all Paths()s of the previously failed nodeids (cached).\n \"\"\"\n try:\n return self._last_failed_paths\n except AttributeError:\n rootpath = Path(self.config.rootdir)\n result = {rootpath / nodeid.split(\"::\")[0] for nodeid in self.lastfailed}\n result = {x for x in result if x.exists()}\n self._last_failed_paths = result\n return result\n\n def pytest_ignore_collect(self, path):\n \"\"\"\n Ignore this file path if we are in --lf mode and it is not in the list of\n previously failed files.\n \"\"\"\n if self.active and self.config.getoption(\"lf\") and path.isfile():\n last_failed_paths = self.last_failed_paths()\n if last_failed_paths:\n skip_it = Path(path) not in self.last_failed_paths()\n if skip_it:\n self._skipped_files += 1\n return skip_it\n\n def pytest_report_collectionfinish(self):\n if self.active and self.config.getoption(\"verbose\") >= 0:\n return \"run-last-failure: %s\" % self._report_status\n\n def pytest_runtest_logreport(self, report):\n if (report.when == \"call\" and report.passed) or report.skipped:\n self.lastfailed.pop(report.nodeid, None)\n elif report.failed:\n self.lastfailed[report.nodeid] = True\n\n def pytest_collectreport(self, report):\n passed = report.outcome in (\"passed\", \"skipped\")\n if passed:\n if report.nodeid in self.lastfailed:\n self.lastfailed.pop(report.nodeid)\n self.lastfailed.update((item.nodeid, True) for item in report.result)\n else:\n self.lastfailed[report.nodeid] = True\n\n def pytest_collection_modifyitems(self, session, config, items):\n if not self.active:\n return\n\n if self.lastfailed:\n previously_failed = []\n previously_passed = []\n for item in items:\n if item.nodeid in self.lastfailed:\n previously_failed.append(item)\n else:\n previously_passed.append(item)\n self._previously_failed_count = len(previously_failed)\n\n if not previously_failed:\n # Running a subset of all tests with recorded failures\n # only outside of it.\n self._report_status = \"%d known failures not in selected tests\" % (\n len(self.lastfailed),\n )\n else:\n if self.config.getoption(\"lf\"):\n items[:] = previously_failed\n config.hook.pytest_deselected(items=previously_passed)\n else: # --failedfirst\n items[:] = previously_failed + previously_passed\n\n noun = \"failure\" if self._previously_failed_count == 1 else \"failures\"\n suffix = \" first\" if self.config.getoption(\"failedfirst\") else \"\"\n self._report_status = \"rerun previous {count} {noun}{suffix}\".format(\n count=self._previously_failed_count, suffix=suffix, noun=noun\n )\n\n if self._skipped_files > 0:\n files_noun = \"file\" if self._skipped_files == 1 else \"files\"\n self._report_status += \" (skipped {files} {files_noun})\".format(\n files=self._skipped_files, files_noun=files_noun\n )\n else:\n self._report_status = \"no previously failed tests, \"\n if self.config.getoption(\"last_failed_no_failures\") == \"none\":\n self._report_status += \"deselecting all items.\"\n config.hook.pytest_deselected(items=items)\n items[:] = []\n else:\n self._report_status += \"not deselecting items.\"\n\n def pytest_sessionfinish(self, session):\n config = self.config\n if config.getoption(\"cacheshow\") or hasattr(config, \"slaveinput\"):\n return\n\n saved_lastfailed = config.cache.get(\"cache/lastfailed\", {})\n if saved_lastfailed != self.lastfailed:\n config.cache.set(\"cache/lastfailed\", self.lastfailed)"},{"col":4,"comment":"null","endLoc":162,"header":"def __init__(self, config)","id":6852,"name":"__init__","nodeType":"Function","startLoc":155,"text":"def __init__(self, config):\n self.config = config\n active_keys = \"lf\", \"failedfirst\"\n self.active = any(config.getoption(key) for key in active_keys)\n self.lastfailed = config.cache.get(\"cache/lastfailed\", {})\n self._previously_failed_count = None\n self._report_status = None\n self._skipped_files = 0 # count skipped files during collection due to --lf"},{"col":4,"comment":"Returns a set with all Paths()s of the previously failed nodeids (cached).\n ","endLoc":174,"header":"def last_failed_paths(self)","id":6853,"name":"last_failed_paths","nodeType":"Function","startLoc":164,"text":"def last_failed_paths(self):\n \"\"\"Returns a set with all Paths()s of the previously failed nodeids (cached).\n \"\"\"\n try:\n return self._last_failed_paths\n except AttributeError:\n rootpath = Path(self.config.rootdir)\n result = {rootpath / nodeid.split(\"::\")[0] for nodeid in self.lastfailed}\n result = {x for x in result if x.exists()}\n self._last_failed_paths = result\n return result"},{"col":4,"comment":"null","endLoc":430,"header":"def x()","id":6855,"name":"x","nodeType":"Function","startLoc":429,"text":"def x():\n pass"},{"col":0,"comment":"null","endLoc":439,"header":"def test_getsource_fallback()","id":6856,"name":"test_getsource_fallback","nodeType":"Function","startLoc":433,"text":"def test_getsource_fallback():\n from _pytest._code.source import getsource\n\n expected = \"\"\"def x():\n pass\"\"\"\n src = getsource(x)\n assert src == expected"},{"col":0,"comment":"null","endLoc":448,"header":"def test_idem_compile_and_getsource()","id":6858,"name":"test_idem_compile_and_getsource","nodeType":"Function","startLoc":442,"text":"def test_idem_compile_and_getsource():\n from _pytest._code.source import getsource\n\n expected = \"def x(): pass\"\n co = _pytest._code.compile(expected)\n src = getsource(co)\n assert src == expected"},{"col":4,"comment":"null","endLoc":406,"header":"def test_list_different_lengths(self)","id":6859,"name":"test_list_different_lengths","nodeType":"Function","startLoc":402,"text":"def test_list_different_lengths(self):\n expl = callequal([0, 1], [0, 1, 2])\n assert len(expl) > 1\n expl = callequal([0, 1, 2], [0, 1])\n assert len(expl) > 1"},{"col":0,"comment":"null","endLoc":456,"header":"def test_findsource_fallback()","id":6860,"name":"test_findsource_fallback","nodeType":"Function","startLoc":451,"text":"def test_findsource_fallback():\n from _pytest._code.source import findsource\n\n src, lineno = findsource(x)\n assert \"test_findsource_simple\" in str(src)\n assert src[lineno] == \" def x():\""},{"col":0,"comment":"null","endLoc":313,"header":"def _compare_eq_sequence(left, right, verbose=0)","id":6862,"name":"_compare_eq_sequence","nodeType":"Function","startLoc":287,"text":"def _compare_eq_sequence(left, right, verbose=0):\n explanation = []\n len_left = len(left)\n len_right = len(right)\n for i in range(min(len_left, len_right)):\n if left[i] != right[i]:\n explanation += [u\"At index %s diff: %r != %r\" % (i, left[i], right[i])]\n break\n len_diff = len_left - len_right\n\n if len_diff:\n if len_diff > 0:\n dir_with_more = \"Left\"\n extra = saferepr(left[len_right])\n else:\n len_diff = 0 - len_diff\n dir_with_more = \"Right\"\n extra = saferepr(right[len_left])\n\n if len_diff == 1:\n explanation += [u\"%s contains one more item: %s\" % (dir_with_more, extra)]\n else:\n explanation += [\n u\"%s contains %d more items, first extra item: %s\"\n % (dir_with_more, len_diff, extra)\n ]\n return explanation"},{"col":4,"comment":"null","endLoc":936,"header":"def visit_BoolOp(self, boolop)","id":6863,"name":"visit_BoolOp","nodeType":"Function","startLoc":903,"text":"def visit_BoolOp(self, boolop):\n res_var = self.variable()\n expl_list = self.assign(ast.List([], ast.Load()))\n app = ast.Attribute(expl_list, \"append\", ast.Load())\n is_or = int(isinstance(boolop.op, ast.Or))\n body = save = self.statements\n fail_save = self.on_failure\n levels = len(boolop.values) - 1\n self.push_format_context()\n # Process each operand, short-circuting if needed.\n for i, v in enumerate(boolop.values):\n if i:\n fail_inner = []\n # cond is set in a prior loop iteration below\n self.on_failure.append(ast.If(cond, fail_inner, [])) # noqa\n self.on_failure = fail_inner\n self.push_format_context()\n res, expl = self.visit(v)\n body.append(ast.Assign([ast.Name(res_var, ast.Store())], res))\n expl_format = self.pop_format_context(ast.Str(expl))\n call = ast_Call(app, [expl_format], [])\n self.on_failure.append(ast.Expr(call))\n if i < levels:\n cond = res\n if is_or:\n cond = ast.UnaryOp(ast.Not(), cond)\n inner = []\n self.statements.append(ast.If(cond, inner, []))\n self.statements = body = inner\n self.statements = save\n self.on_failure = fail_save\n expl_template = self.helper(\"_format_boolop\", expl_list, ast.Num(is_or))\n expl = self.pop_format_context(expl_template)\n return ast.Name(res_var, ast.Load()), self.explanation_param(expl)"},{"col":4,"comment":"null","endLoc":410,"header":"def test_dict(self)","id":6864,"name":"test_dict","nodeType":"Function","startLoc":408,"text":"def test_dict(self):\n expl = callequal({\"a\": 0}, {\"a\": 1})\n assert len(expl) > 1"},{"col":4,"comment":"null","endLoc":417,"header":"def test_dict_omitting(self)","id":6865,"name":"test_dict_omitting","nodeType":"Function","startLoc":412,"text":"def test_dict_omitting(self):\n lines = callequal({\"a\": 0, \"b\": 1}, {\"a\": 1, \"b\": 1})\n assert lines[1].startswith(\"Omitting 1 identical item\")\n assert \"Common items\" not in lines\n for line in lines[1:]:\n assert \"b\" not in line"},{"col":4,"comment":" Ensure differing items are visible for verbosity=1 (#1512) ","endLoc":425,"header":"def test_dict_omitting_with_verbosity_1(self)","id":6866,"name":"test_dict_omitting_with_verbosity_1","nodeType":"Function","startLoc":419,"text":"def test_dict_omitting_with_verbosity_1(self):\n \"\"\" Ensure differing items are visible for verbosity=1 (#1512) \"\"\"\n lines = callequal({\"a\": 0, \"b\": 1}, {\"a\": 1, \"b\": 1}, verbose=1)\n assert lines[1].startswith(\"Omitting 1 identical item\")\n assert lines[2].startswith(\"Differing items\")\n assert lines[3] == \"{'a': 0} != {'a': 1}\"\n assert \"Common items\" not in lines"},{"col":4,"comment":"null","endLoc":431,"header":"def test_dict_omitting_with_verbosity_2(self)","id":6867,"name":"test_dict_omitting_with_verbosity_2","nodeType":"Function","startLoc":427,"text":"def test_dict_omitting_with_verbosity_2(self):\n lines = callequal({\"a\": 0, \"b\": 1}, {\"a\": 1, \"b\": 1}, verbose=2)\n assert lines[1].startswith(\"Common items:\")\n assert \"Omitting\" not in lines[1]\n assert lines[2] == \"{'b': 1}\""},{"col":4,"comment":"null","endLoc":783,"header":"def test_repr_traceback_tbfilter(self, importasmod)","id":6868,"name":"test_repr_traceback_tbfilter","nodeType":"Function","startLoc":768,"text":"def test_repr_traceback_tbfilter(self, importasmod):\n mod = importasmod(\n \"\"\"\n def f(x):\n raise ValueError(x)\n def entry():\n f(0)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n p = FormattedExcinfo(tbfilter=True)\n reprtb = p.repr_traceback(excinfo)\n assert len(reprtb.reprentries) == 2\n p = FormattedExcinfo(tbfilter=False)\n reprtb = p.repr_traceback(excinfo)\n assert len(reprtb.reprentries) == 3"},{"col":4,"comment":"null","endLoc":455,"header":"def test_dict_different_items(self)","id":6869,"name":"test_dict_different_items","nodeType":"Function","startLoc":433,"text":"def test_dict_different_items(self):\n lines = callequal({\"a\": 0}, {\"b\": 1, \"c\": 2}, verbose=2)\n assert lines == [\n \"{'a': 0} == {'b': 1, 'c': 2}\",\n \"Left contains 1 more item:\",\n \"{'a': 0}\",\n \"Right contains 2 more items:\",\n \"{'b': 1, 'c': 2}\",\n \"Full diff:\",\n \"- {'a': 0}\",\n \"+ {'b': 1, 'c': 2}\",\n ]\n lines = callequal({\"b\": 1, \"c\": 2}, {\"a\": 0}, verbose=2)\n assert lines == [\n \"{'b': 1, 'c': 2} == {'a': 0}\",\n \"Left contains 2 more items:\",\n \"{'b': 1, 'c': 2}\",\n \"Right contains 1 more item:\",\n \"{'a': 0}\",\n \"Full diff:\",\n \"- {'b': 1, 'c': 2}\",\n \"+ {'a': 0}\",\n ]"},{"col":4,"comment":"null","endLoc":475,"header":"def test_sequence_different_items(self)","id":6870,"name":"test_sequence_different_items","nodeType":"Function","startLoc":457,"text":"def test_sequence_different_items(self):\n lines = callequal((1, 2), (3, 4, 5), verbose=2)\n assert lines == [\n \"(1, 2) == (3, 4, 5)\",\n \"At index 0 diff: 1 != 3\",\n \"Right contains one more item: 5\",\n \"Full diff:\",\n \"- (1, 2)\",\n \"+ (3, 4, 5)\",\n ]\n lines = callequal((1, 2, 3), (4,), verbose=2)\n assert lines == [\n \"(1, 2, 3) == (4,)\",\n \"At index 0 diff: 1 != 4\",\n \"Left contains 2 more items, first extra item: 2\",\n \"Full diff:\",\n \"- (1, 2, 3)\",\n \"+ (4,)\",\n ]"},{"col":4,"comment":"null","endLoc":479,"header":"def test_set(self)","id":6871,"name":"test_set","nodeType":"Function","startLoc":477,"text":"def test_set(self):\n expl = callequal({0, 1}, {0, 2})\n assert len(expl) > 1"},{"col":4,"comment":"null","endLoc":483,"header":"def test_frozenzet(self)","id":6872,"name":"test_frozenzet","nodeType":"Function","startLoc":481,"text":"def test_frozenzet(self):\n expl = callequal(frozenset([0, 1]), {0, 2})\n assert len(expl) > 1"},{"col":0,"comment":"null","endLoc":328,"header":"def _compare_eq_set(left, right, verbose=0)","id":6874,"name":"_compare_eq_set","nodeType":"Function","startLoc":316,"text":"def _compare_eq_set(left, right, verbose=0):\n explanation = []\n diff_left = left - right\n diff_right = right - left\n if diff_left:\n explanation.append(u\"Extra items in the left set:\")\n for item in diff_left:\n explanation.append(saferepr(item))\n if diff_right:\n explanation.append(u\"Extra items in the right set:\")\n for item in diff_right:\n explanation.append(saferepr(item))\n return explanation"},{"col":0,"comment":"null","endLoc":23,"header":"def test_tmpdir_fixture(testdir)","id":6875,"name":"test_tmpdir_fixture","nodeType":"Function","startLoc":20,"text":"def test_tmpdir_fixture(testdir):\n p = testdir.copy_example(\"tmpdir/tmpdir_fixture.py\")\n results = testdir.runpytest(p)\n results.stdout.fnmatch_lines([\"*1 passed*\"])"},{"col":0,"comment":"null","endLoc":30,"header":"def test_ensuretemp(recwarn)","id":6876,"name":"test_ensuretemp","nodeType":"Function","startLoc":26,"text":"def test_ensuretemp(recwarn):\n d1 = pytest.ensuretemp(\"hello\")\n d2 = pytest.ensuretemp(\"hello\")\n assert d1 == d2\n assert d1.check(dir=1)"},{"col":0,"comment":"null","endLoc":476,"header":"def test_findsource()","id":6877,"name":"test_findsource","nodeType":"Function","startLoc":459,"text":"def test_findsource():\n from _pytest._code.source import findsource\n\n co = _pytest._code.compile(\n \"\"\"if 1:\n def x():\n pass\n\"\"\"\n )\n\n src, lineno = findsource(co)\n assert \"if 1:\" in str(src)\n\n d = {}\n eval(co, d)\n src, lineno = findsource(d[\"x\"])\n assert \"if 1:\" in str(src)\n assert src[lineno] == \" def x():\""},{"col":4,"comment":"null","endLoc":809,"header":"def test_traceback_short_no_source(self, importasmod, monkeypatch)","id":6878,"name":"test_traceback_short_no_source","nodeType":"Function","startLoc":785,"text":"def test_traceback_short_no_source(self, importasmod, monkeypatch):\n mod = importasmod(\n \"\"\"\n def func1():\n raise ValueError(\"hello\")\n def entry():\n func1()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n from _pytest._code.code import Code\n\n monkeypatch.setattr(Code, \"path\", \"bogus\")\n excinfo.traceback[0].frame.code.path = \"bogus\"\n p = FormattedExcinfo(style=\"short\")\n reprtb = p.repr_traceback_entry(excinfo.traceback[-2])\n lines = reprtb.lines\n last_p = FormattedExcinfo(style=\"short\")\n last_reprtb = last_p.repr_traceback_entry(excinfo.traceback[-1], excinfo)\n last_lines = last_reprtb.lines\n monkeypatch.undo()\n assert lines[0] == \" func1()\"\n\n assert last_lines[0] == ' raise ValueError(\"hello\")'\n assert last_lines[1] == \"E ValueError: hello\""},{"col":0,"comment":"null","endLoc":367,"header":"def _compare_eq_dict(left, right, verbose=0)","id":6879,"name":"_compare_eq_dict","nodeType":"Function","startLoc":331,"text":"def _compare_eq_dict(left, right, verbose=0):\n explanation = []\n set_left = set(left)\n set_right = set(right)\n common = set_left.intersection(set_right)\n same = {k: left[k] for k in common if left[k] == right[k]}\n if same and verbose < 2:\n explanation += [u\"Omitting %s identical items, use -vv to show\" % len(same)]\n elif same:\n explanation += [u\"Common items:\"]\n explanation += pprint.pformat(same).splitlines()\n diff = {k for k in common if left[k] != right[k]}\n if diff:\n explanation += [u\"Differing items:\"]\n for k in diff:\n explanation += [saferepr({k: left[k]}) + \" != \" + saferepr({k: right[k]})]\n extra_left = set_left - set_right\n len_extra_left = len(extra_left)\n if len_extra_left:\n explanation.append(\n u\"Left contains %d more item%s:\"\n % (len_extra_left, \"\" if len_extra_left == 1 else \"s\")\n )\n explanation.extend(\n pprint.pformat({k: left[k] for k in extra_left}).splitlines()\n )\n extra_right = set_right - set_left\n len_extra_right = len(extra_right)\n if len_extra_right:\n explanation.append(\n u\"Right contains %d more item%s:\"\n % (len_extra_right, \"\" if len_extra_right == 1 else \"s\")\n )\n explanation.extend(\n pprint.pformat({k: right[k] for k in extra_right}).splitlines()\n )\n return explanation"},{"col":4,"comment":"null","endLoc":835,"header":"def test_repr_traceback_and_excinfo(self, importasmod)","id":6880,"name":"test_repr_traceback_and_excinfo","nodeType":"Function","startLoc":811,"text":"def test_repr_traceback_and_excinfo(self, importasmod):\n mod = importasmod(\n \"\"\"\n def f(x):\n raise ValueError(x)\n def entry():\n f(0)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n\n for style in (\"long\", \"short\"):\n p = FormattedExcinfo(style=style)\n reprtb = p.repr_traceback(excinfo)\n assert len(reprtb.reprentries) == 2\n assert reprtb.style == style\n assert not reprtb.extraline\n repr = p.repr_excinfo(excinfo)\n assert repr.reprtraceback\n assert len(repr.reprtraceback.reprentries) == len(reprtb.reprentries)\n if sys.version_info[0] >= 3:\n assert repr.chain[0][0]\n assert len(repr.chain[0][0].reprentries) == len(reprtb.reprentries)\n assert repr.reprcrash.path.endswith(\"mod.py\")\n assert repr.reprcrash.message == \"ValueError: 0\""},{"col":4,"comment":"null","endLoc":514,"header":"def test_Sequence(self)","id":6881,"name":"test_Sequence","nodeType":"Function","startLoc":485,"text":"def test_Sequence(self):\n if sys.version_info >= (3, 3):\n import collections.abc as collections_abc\n else:\n import collections as collections_abc\n if not hasattr(collections_abc, \"MutableSequence\"):\n pytest.skip(\"cannot import MutableSequence\")\n MutableSequence = collections_abc.MutableSequence\n\n class TestSequence(MutableSequence): # works with a Sequence subclass\n def __init__(self, iterable):\n self.elements = list(iterable)\n\n def __getitem__(self, item):\n return self.elements[item]\n\n def __len__(self):\n return len(self.elements)\n\n def __setitem__(self, item, value):\n pass\n\n def __delitem__(self, item):\n pass\n\n def insert(self, item, index):\n pass\n\n expl = callequal(TestSequence([0, 1]), list([0, 2]))\n assert len(expl) > 1"},{"col":4,"comment":"null","endLoc":855,"header":"def test_repr_traceback_with_invalid_cwd(self, importasmod, monkeypatch)","id":6882,"name":"test_repr_traceback_with_invalid_cwd","nodeType":"Function","startLoc":837,"text":"def test_repr_traceback_with_invalid_cwd(self, importasmod, monkeypatch):\n mod = importasmod(\n \"\"\"\n def f(x):\n raise ValueError(x)\n def entry():\n f(0)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n\n p = FormattedExcinfo()\n\n def raiseos():\n raise OSError(2)\n\n monkeypatch.setattr(os, \"getcwd\", raiseos)\n assert p._makepath(__file__) == __file__\n p.repr_traceback(excinfo)"},{"col":0,"comment":"null","endLoc":505,"header":"def test_getfslineno()","id":6883,"name":"test_getfslineno","nodeType":"Function","startLoc":479,"text":"def test_getfslineno():\n from _pytest._code import getfslineno\n\n def f(x):\n pass\n\n fspath, lineno = getfslineno(f)\n\n assert fspath.basename == \"test_source.py\"\n assert lineno == _pytest._code.getrawcode(f).co_firstlineno - 1 # see findsource\n\n class A(object):\n pass\n\n fspath, lineno = getfslineno(A)\n\n _, A_lineno = inspect.findsource(A)\n assert fspath.basename == \"test_source.py\"\n assert lineno == A_lineno\n\n assert getfslineno(3) == (\"\", -1)\n\n class B(object):\n pass\n\n B.__name__ = \"B2\"\n assert getfslineno(B)[1] == -1"},{"col":4,"comment":"null","endLoc":870,"header":"def test_repr_excinfo_addouterr(self, importasmod)","id":6884,"name":"test_repr_excinfo_addouterr","nodeType":"Function","startLoc":857,"text":"def test_repr_excinfo_addouterr(self, importasmod):\n mod = importasmod(\n \"\"\"\n def entry():\n raise ValueError()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n repr = excinfo.getrepr()\n repr.addsection(\"title\", \"content\")\n twmock = TWMock()\n repr.toterminal(twmock)\n assert twmock.lines[-1] == \"content\"\n assert twmock.lines[-2] == (\"-\", \"title\")"},{"col":4,"comment":"\n Ignore this file path if we are in --lf mode and it is not in the list of\n previously failed files.\n ","endLoc":187,"header":"def pytest_ignore_collect(self, path)","id":6885,"name":"pytest_ignore_collect","nodeType":"Function","startLoc":176,"text":"def pytest_ignore_collect(self, path):\n \"\"\"\n Ignore this file path if we are in --lf mode and it is not in the list of\n previously failed files.\n \"\"\"\n if self.active and self.config.getoption(\"lf\") and path.isfile():\n last_failed_paths = self.last_failed_paths()\n if last_failed_paths:\n skip_it = Path(path) not in self.last_failed_paths()\n if skip_it:\n self._skipped_files += 1\n return skip_it"},{"col":0,"comment":"null","endLoc":104,"header":"def test_basetemp(testdir)","id":6886,"name":"test_basetemp","nodeType":"Function","startLoc":93,"text":"def test_basetemp(testdir):\n mytemp = testdir.tmpdir.mkdir(\"mytemp\")\n p = testdir.makepyfile(\n \"\"\"\n import pytest\n def test_1():\n pytest.ensuretemp(\"hello\")\n \"\"\"\n )\n result = testdir.runpytest(p, \"--basetemp=%s\" % mytemp, SHOW_PYTEST_WARNINGS_ARG)\n assert result.ret == 0\n assert mytemp.join(\"hello\").check()"},{"col":0,"comment":"null","endLoc":525,"header":"def test_code_of_object_instance_with_call()","id":6887,"name":"test_code_of_object_instance_with_call","nodeType":"Function","startLoc":508,"text":"def test_code_of_object_instance_with_call():\n class A(object):\n pass\n\n pytest.raises(TypeError, lambda: _pytest._code.Source(A()))\n\n class WithCall(object):\n def __call__(self):\n pass\n\n code = _pytest._code.Code(WithCall())\n assert \"pass\" in str(code.source())\n\n class Hello(object):\n def __call__(self):\n pass\n\n pytest.raises(TypeError, lambda: _pytest._code.Code(Hello))"},{"col":4,"comment":"null","endLoc":884,"header":"def test_repr_excinfo_reprcrash(self, importasmod)","id":6888,"name":"test_repr_excinfo_reprcrash","nodeType":"Function","startLoc":872,"text":"def test_repr_excinfo_reprcrash(self, importasmod):\n mod = importasmod(\n \"\"\"\n def entry():\n raise ValueError()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n repr = excinfo.getrepr()\n assert repr.reprcrash.path.endswith(\"mod.py\")\n assert repr.reprcrash.lineno == 3\n assert repr.reprcrash.message == \"ValueError\"\n assert str(repr.reprcrash).endswith(\"mod.py:3: ValueError\")"},{"col":0,"comment":"null","endLoc":125,"header":"def test_tmpdir_always_is_realpath(testdir)","id":6889,"name":"test_tmpdir_always_is_realpath","nodeType":"Function","startLoc":107,"text":"def test_tmpdir_always_is_realpath(testdir):\n # the reason why tmpdir should be a realpath is that\n # when you cd to it and do \"os.getcwd()\" you will anyway\n # get the realpath. Using the symlinked path can thus\n # easily result in path-inequality\n # XXX if that proves to be a problem, consider using\n # os.environ[\"PWD\"]\n realtemp = testdir.tmpdir.mkdir(\"myrealtemp\")\n linktemp = testdir.tmpdir.join(\"symlinktemp\")\n attempt_symlink_to(linktemp, str(realtemp))\n p = testdir.makepyfile(\n \"\"\"\n def test_1(tmpdir):\n import os\n assert os.path.realpath(str(tmpdir)) == str(tmpdir)\n \"\"\"\n )\n result = testdir.runpytest(\"-s\", p, \"--basetemp=%s/bt\" % linktemp)\n assert not result.ret"},{"col":29,"endLoc":512,"id":6890,"nodeType":"Lambda","startLoc":512,"text":"lambda: _pytest._code.Source(A())"},{"col":0,"comment":"null","endLoc":141,"header":"def test_tmp_path_always_is_realpath(testdir, monkeypatch)","id":6891,"name":"test_tmp_path_always_is_realpath","nodeType":"Function","startLoc":128,"text":"def test_tmp_path_always_is_realpath(testdir, monkeypatch):\n # for reasoning see: test_tmpdir_always_is_realpath test-case\n realtemp = testdir.tmpdir.mkdir(\"myrealtemp\")\n linktemp = testdir.tmpdir.join(\"symlinktemp\")\n attempt_symlink_to(linktemp, str(realtemp))\n monkeypatch.setenv(\"PYTEST_DEBUG_TEMPROOT\", str(linktemp))\n testdir.makepyfile(\n \"\"\"\n def test_1(tmp_path):\n assert tmp_path.resolve() == tmp_path\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":29,"endLoc":525,"id":6892,"nodeType":"Lambda","startLoc":525,"text":"lambda: _pytest._code.Code(Hello)"},{"col":0,"comment":"null","endLoc":538,"header":"def test_oneline()","id":6893,"name":"test_oneline","nodeType":"Function","startLoc":536,"text":"def test_oneline():\n source = getstatement(0, \"raise ValueError\")\n assert str(source) == \"raise ValueError\""},{"col":0,"comment":"null","endLoc":552,"header":"def test_comment_and_no_newline_at_end()","id":6894,"name":"test_comment_and_no_newline_at_end","nodeType":"Function","startLoc":541,"text":"def test_comment_and_no_newline_at_end():\n from _pytest._code.source import getstatementrange_ast\n\n source = Source(\n [\n \"def test_basic_complex():\",\n \" assert 1 == 2\",\n \"# vim: filetype=pyopencl:fdm=marker\",\n ]\n )\n ast, start, end = getstatementrange_ast(1, source)\n assert end == 2"},{"col":0,"comment":"null","endLoc":557,"header":"def test_oneline_and_comment()","id":6895,"name":"test_oneline_and_comment","nodeType":"Function","startLoc":555,"text":"def test_oneline_and_comment():\n source = getstatement(0, \"raise ValueError\\n#hello\")\n assert str(source) == \"raise ValueError\""},{"col":0,"comment":"null","endLoc":583,"header":"def test_comments()","id":6896,"name":"test_comments","nodeType":"Function","startLoc":560,"text":"def test_comments():\n source = '''def test():\n \"comment 1\"\n x = 1\n # comment 2\n # comment 3\n\n assert False\n\n\"\"\"\ncomment 4\n\"\"\"\n'''\n for line in range(2, 6):\n assert str(getstatement(line, source)) == \" x = 1\"\n if sys.version_info >= (3, 8) or hasattr(sys, \"pypy_version_info\"):\n tqs_start = 8\n else:\n tqs_start = 10\n assert str(getstatement(10, source)) == '\"\"\"'\n for line in range(6, tqs_start):\n assert str(getstatement(line, source)) == \" assert False\"\n for line in range(tqs_start, 10):\n assert str(getstatement(line, source)) == '\"\"\"\\ncomment 4\\n\"\"\"'"},{"col":0,"comment":"null","endLoc":154,"header":"def test_tmpdir_too_long_on_parametrization(testdir)","id":6897,"name":"test_tmpdir_too_long_on_parametrization","nodeType":"Function","startLoc":144,"text":"def test_tmpdir_too_long_on_parametrization(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.mark.parametrize(\"arg\", [\"1\"*1000])\n def test_some(arg, tmpdir):\n tmpdir.ensure(\"hello\")\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":0,"comment":"null","endLoc":169,"header":"def test_tmpdir_factory(testdir)","id":6898,"name":"test_tmpdir_factory","nodeType":"Function","startLoc":157,"text":"def test_tmpdir_factory(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n @pytest.fixture(scope='session')\n def session_dir(tmpdir_factory):\n return tmpdir_factory.mktemp('data', numbered=False)\n def test_some(session_dir):\n assert session_dir.isdir()\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":0,"comment":"Test that tmpdir works even if environment variables required by getpass\n module are missing (#1010).\n ","endLoc":186,"header":"def test_tmpdir_fallback_tox_env(testdir, monkeypatch)","id":6899,"name":"test_tmpdir_fallback_tox_env","nodeType":"Function","startLoc":172,"text":"def test_tmpdir_fallback_tox_env(testdir, monkeypatch):\n \"\"\"Test that tmpdir works even if environment variables required by getpass\n module are missing (#1010).\n \"\"\"\n monkeypatch.delenv(\"USER\", raising=False)\n monkeypatch.delenv(\"USERNAME\", raising=False)\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_some(tmpdir):\n assert tmpdir.isdir()\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":0,"comment":"null","endLoc":194,"header":"@pytest.fixture\ndef break_getuser(monkeypatch)","id":6900,"name":"break_getuser","nodeType":"Function","startLoc":189,"text":"@pytest.fixture\ndef break_getuser(monkeypatch):\n monkeypatch.setattr(\"os.getuid\", lambda: -1)\n # taken from python 2.7/3.4\n for envvar in (\"LOGNAME\", \"USER\", \"LNAME\", \"USERNAME\"):\n monkeypatch.delenv(envvar, raising=False)"},{"col":37,"endLoc":191,"id":6901,"nodeType":"Lambda","startLoc":191,"text":"lambda: -1"},{"col":4,"comment":"null","endLoc":903,"header":"def test_repr_traceback_recursion(self, importasmod)","id":6902,"name":"test_repr_traceback_recursion","nodeType":"Function","startLoc":886,"text":"def test_repr_traceback_recursion(self, importasmod):\n mod = importasmod(\n \"\"\"\n def rec2(x):\n return rec1(x+1)\n def rec1(x):\n return rec2(x-1)\n def entry():\n rec1(42)\n \"\"\"\n )\n excinfo = pytest.raises(RuntimeError, mod.entry)\n\n for style in (\"short\", \"long\", \"no\"):\n p = FormattedExcinfo(style=\"short\")\n reprtb = p.repr_traceback(excinfo)\n assert reprtb.extraline == \"!!! Recursion detected (same locals & position)\"\n assert str(reprtb)"},{"col":4,"comment":"null","endLoc":191,"header":"def pytest_report_collectionfinish(self)","id":6903,"name":"pytest_report_collectionfinish","nodeType":"Function","startLoc":189,"text":"def pytest_report_collectionfinish(self):\n if self.active and self.config.getoption(\"verbose\") >= 0:\n return \"run-last-failure: %s\" % self._report_status"},{"col":0,"comment":"Test that tmpdir works even if the current process's user id does not\n correspond to a valid user.\n ","endLoc":212,"header":"@pytest.mark.usefixtures(\"break_getuser\")\n@pytest.mark.skipif(sys.platform.startswith(\"win\"), reason=\"no os.getuid on windows\")\ndef test_tmpdir_fallback_uid_not_found(testdir)","id":6904,"name":"test_tmpdir_fallback_uid_not_found","nodeType":"Function","startLoc":197,"text":"@pytest.mark.usefixtures(\"break_getuser\")\n@pytest.mark.skipif(sys.platform.startswith(\"win\"), reason=\"no os.getuid on windows\")\ndef test_tmpdir_fallback_uid_not_found(testdir):\n \"\"\"Test that tmpdir works even if the current process's user id does not\n correspond to a valid user.\n \"\"\"\n\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_some(tmpdir):\n assert tmpdir.isdir()\n \"\"\"\n )\n reprec = testdir.inline_run()\n reprec.assertoutcome(passed=1)"},{"col":4,"comment":"null","endLoc":197,"header":"def pytest_runtest_logreport(self, report)","id":6905,"name":"pytest_runtest_logreport","nodeType":"Function","startLoc":193,"text":"def pytest_runtest_logreport(self, report):\n if (report.when == \"call\" and report.passed) or report.skipped:\n self.lastfailed.pop(report.nodeid, None)\n elif report.failed:\n self.lastfailed[report.nodeid] = True"},{"col":0,"comment":"Test that get_user() function works even if the current process's\n user id does not correspond to a valid user (e.g. running pytest in a\n Docker container with 'docker run -u'.\n ","endLoc":224,"header":"@pytest.mark.usefixtures(\"break_getuser\")\n@pytest.mark.skipif(sys.platform.startswith(\"win\"), reason=\"no os.getuid on windows\")\ndef test_get_user_uid_not_found()","id":6906,"name":"test_get_user_uid_not_found","nodeType":"Function","startLoc":215,"text":"@pytest.mark.usefixtures(\"break_getuser\")\n@pytest.mark.skipif(sys.platform.startswith(\"win\"), reason=\"no os.getuid on windows\")\ndef test_get_user_uid_not_found():\n \"\"\"Test that get_user() function works even if the current process's\n user id does not correspond to a valid user (e.g. running pytest in a\n Docker container with 'docker run -u'.\n \"\"\"\n from _pytest.tmpdir import get_user\n\n assert get_user() is None"},{"col":0,"comment":"Test that get_user() function works even if environment variables\n required by getpass module are missing from the environment on Windows\n (#1010).\n ","endLoc":237,"header":"@pytest.mark.skipif(not sys.platform.startswith(\"win\"), reason=\"win only\")\ndef test_get_user(monkeypatch)","id":6907,"name":"test_get_user","nodeType":"Function","startLoc":227,"text":"@pytest.mark.skipif(not sys.platform.startswith(\"win\"), reason=\"win only\")\ndef test_get_user(monkeypatch):\n \"\"\"Test that get_user() function works even if environment variables\n required by getpass module are missing from the environment on Windows\n (#1010).\n \"\"\"\n from _pytest.tmpdir import get_user\n\n monkeypatch.delenv(\"USER\", raising=False)\n monkeypatch.delenv(\"USERNAME\", raising=False)\n assert get_user() is None"},{"col":0,"comment":"null","endLoc":427,"header":"def test_tmpdir_equals_tmp_path(tmpdir, tmp_path)","id":6908,"name":"test_tmpdir_equals_tmp_path","nodeType":"Function","startLoc":426,"text":"def test_tmpdir_equals_tmp_path(tmpdir, tmp_path):\n assert Path(tmpdir) == tmp_path"},{"col":4,"comment":"null","endLoc":206,"header":"def pytest_collectreport(self, report)","id":6909,"name":"pytest_collectreport","nodeType":"Function","startLoc":199,"text":"def pytest_collectreport(self, report):\n passed = report.outcome in (\"passed\", \"skipped\")\n if passed:\n if report.nodeid in self.lastfailed:\n self.lastfailed.pop(report.nodeid)\n self.lastfailed.update((item.nodeid, True) for item in report.result)\n else:\n self.lastfailed[report.nodeid] = True"},{"col":0,"comment":"Integration test for #5524","endLoc":448,"header":"def test_basetemp_with_read_only_files(testdir)","id":6910,"name":"test_basetemp_with_read_only_files","nodeType":"Function","startLoc":430,"text":"def test_basetemp_with_read_only_files(testdir):\n \"\"\"Integration test for #5524\"\"\"\n testdir.makepyfile(\n \"\"\"\n import os\n import stat\n\n def test(tmp_path):\n fn = tmp_path / 'foo.txt'\n fn.write_text(u'hello')\n mode = os.stat(str(fn)).st_mode\n os.chmod(str(fn), mode & ~stat.S_IREAD)\n \"\"\"\n )\n result = testdir.runpytest(\"--basetemp=tmp\")\n assert result.ret == 0\n # running a second time and ensure we don't crash\n result = testdir.runpytest(\"--basetemp=tmp\")\n assert result.ret == 0"},{"col":4,"comment":"null","endLoc":253,"header":"def pytest_collection_modifyitems(self, session, config, items)","id":6911,"name":"pytest_collection_modifyitems","nodeType":"Function","startLoc":208,"text":"def pytest_collection_modifyitems(self, session, config, items):\n if not self.active:\n return\n\n if self.lastfailed:\n previously_failed = []\n previously_passed = []\n for item in items:\n if item.nodeid in self.lastfailed:\n previously_failed.append(item)\n else:\n previously_passed.append(item)\n self._previously_failed_count = len(previously_failed)\n\n if not previously_failed:\n # Running a subset of all tests with recorded failures\n # only outside of it.\n self._report_status = \"%d known failures not in selected tests\" % (\n len(self.lastfailed),\n )\n else:\n if self.config.getoption(\"lf\"):\n items[:] = previously_failed\n config.hook.pytest_deselected(items=previously_passed)\n else: # --failedfirst\n items[:] = previously_failed + previously_passed\n\n noun = \"failure\" if self._previously_failed_count == 1 else \"failures\"\n suffix = \" first\" if self.config.getoption(\"failedfirst\") else \"\"\n self._report_status = \"rerun previous {count} {noun}{suffix}\".format(\n count=self._previously_failed_count, suffix=suffix, noun=noun\n )\n\n if self._skipped_files > 0:\n files_noun = \"file\" if self._skipped_files == 1 else \"files\"\n self._report_status += \" (skipped {files} {files_noun})\".format(\n files=self._skipped_files, files_noun=files_noun\n )\n else:\n self._report_status = \"no previously failed tests, \"\n if self.config.getoption(\"last_failed_no_failures\") == \"none\":\n self._report_status += \"deselecting all items.\"\n config.hook.pytest_deselected(items=items)\n items[:] = []\n else:\n self._report_status += \"not deselecting items.\""},{"col":4,"comment":"null","endLoc":925,"header":"def test_reprexcinfo_getrepr(self, importasmod)","id":6912,"name":"test_reprexcinfo_getrepr","nodeType":"Function","startLoc":905,"text":"def test_reprexcinfo_getrepr(self, importasmod):\n mod = importasmod(\n \"\"\"\n def f(x):\n raise ValueError(x)\n def entry():\n f(0)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.entry)\n\n for style in (\"short\", \"long\", \"no\"):\n for showlocals in (True, False):\n repr = excinfo.getrepr(style=style, showlocals=showlocals)\n if sys.version_info[0] < 3:\n assert isinstance(repr, ReprExceptionInfo)\n assert repr.reprtraceback.style == style\n if sys.version_info[0] >= 3:\n assert isinstance(repr, ExceptionChainRepr)\n for repr in repr.chain:\n assert repr[0].style == style"},{"col":4,"comment":"null","endLoc":935,"header":"def test_reprexcinfo_unicode(self)","id":6913,"name":"test_reprexcinfo_unicode","nodeType":"Function","startLoc":927,"text":"def test_reprexcinfo_unicode(self):\n from _pytest._code.code import TerminalRepr\n\n class MyRepr(TerminalRepr):\n def toterminal(self, tw):\n tw.line(u\"я\")\n\n x = six.text_type(MyRepr())\n assert x == u\"я\""},{"col":4,"comment":"null","endLoc":967,"header":"def test_toterminal_long(self, importasmod)","id":6914,"name":"test_toterminal_long","nodeType":"Function","startLoc":937,"text":"def test_toterminal_long(self, importasmod):\n mod = importasmod(\n \"\"\"\n def g(x):\n raise ValueError(x)\n def f():\n g(3)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.f)\n excinfo.traceback = excinfo.traceback.filter()\n repr = excinfo.getrepr()\n tw = TWMock()\n repr.toterminal(tw)\n assert tw.lines[0] == \"\"\n tw.lines.pop(0)\n assert tw.lines[0] == \" def f():\"\n assert tw.lines[1] == \"> g(3)\"\n assert tw.lines[2] == \"\"\n line = tw.get_write_msg(3)\n assert line.endswith(\"mod.py\")\n assert tw.lines[4] == (\":5: \")\n assert tw.lines[5] == (\"_ \", None)\n assert tw.lines[6] == \"\"\n assert tw.lines[7] == \" def g(x):\"\n assert tw.lines[8] == \"> raise ValueError(x)\"\n assert tw.lines[9] == \"E ValueError: 3\"\n assert tw.lines[10] == \"\"\n line = tw.get_write_msg(11)\n assert line.endswith(\"mod.py\")\n assert tw.lines[12] == \":3: ValueError\""},{"col":0,"comment":"null","endLoc":595,"header":"def test_comment_in_statement()","id":6915,"name":"test_comment_in_statement","nodeType":"Function","startLoc":586,"text":"def test_comment_in_statement():\n source = \"\"\"test(foo=1,\n # comment 1\n bar=2)\n\"\"\"\n for line in range(1, 3):\n assert (\n str(getstatement(line, source))\n == \"test(foo=1,\\n # comment 1\\n bar=2)\"\n )"},{"col":4,"comment":"null","endLoc":262,"header":"def pytest_sessionfinish(self, session)","id":6916,"name":"pytest_sessionfinish","nodeType":"Function","startLoc":255,"text":"def pytest_sessionfinish(self, session):\n config = self.config\n if config.getoption(\"cacheshow\") or hasattr(config, \"slaveinput\"):\n return\n\n saved_lastfailed = config.cache.get(\"cache/lastfailed\", {})\n if saved_lastfailed != self.lastfailed:\n config.cache.set(\"cache/lastfailed\", self.lastfailed)"},{"attributeType":"int","col":8,"comment":"null","endLoc":162,"id":6917,"name":"_skipped_files","nodeType":"Attribute","startLoc":162,"text":"self._skipped_files"},{"attributeType":"None","col":8,"comment":"null","endLoc":160,"id":6918,"name":"_previously_failed_count","nodeType":"Attribute","startLoc":160,"text":"self._previously_failed_count"},{"attributeType":"bool","col":8,"comment":"null","endLoc":158,"id":6919,"name":"active","nodeType":"Attribute","startLoc":158,"text":"self.active"},{"attributeType":"null","col":8,"comment":"null","endLoc":159,"id":6920,"name":"lastfailed","nodeType":"Attribute","startLoc":159,"text":"self.lastfailed"},{"attributeType":"None","col":8,"comment":"null","endLoc":161,"id":6921,"name":"_report_status","nodeType":"Attribute","startLoc":161,"text":"self._report_status"},{"attributeType":"{getoption, cache}","col":8,"comment":"null","endLoc":156,"id":6922,"name":"config","nodeType":"Attribute","startLoc":156,"text":"self.config"},{"attributeType":"set","col":12,"comment":"null","endLoc":173,"id":6923,"name":"_last_failed_paths","nodeType":"Attribute","startLoc":173,"text":"self._last_failed_paths"},{"className":"NFPlugin","col":0,"comment":" Plugin which implements the --nf (run new-first) option ","endLoc":296,"id":6924,"nodeType":"Class","startLoc":265,"text":"class NFPlugin(object):\n \"\"\" Plugin which implements the --nf (run new-first) option \"\"\"\n\n def __init__(self, config):\n self.config = config\n self.active = config.option.newfirst\n self.cached_nodeids = config.cache.get(\"cache/nodeids\", [])\n\n def pytest_collection_modifyitems(self, session, config, items):\n if self.active:\n new_items = OrderedDict()\n other_items = OrderedDict()\n for item in items:\n if item.nodeid not in self.cached_nodeids:\n new_items[item.nodeid] = item\n else:\n other_items[item.nodeid] = item\n\n items[:] = self._get_increasing_order(\n six.itervalues(new_items)\n ) + self._get_increasing_order(six.itervalues(other_items))\n self.cached_nodeids = [x.nodeid for x in items if isinstance(x, pytest.Item)]\n\n def _get_increasing_order(self, items):\n return sorted(items, key=lambda item: item.fspath.mtime(), reverse=True)\n\n def pytest_sessionfinish(self, session):\n config = self.config\n if config.getoption(\"cacheshow\") or hasattr(config, \"slaveinput\"):\n return\n\n config.cache.set(\"cache/nodeids\", self.cached_nodeids)"},{"col":4,"comment":"null","endLoc":271,"header":"def __init__(self, config)","id":6925,"name":"__init__","nodeType":"Function","startLoc":268,"text":"def __init__(self, config):\n self.config = config\n self.active = config.option.newfirst\n self.cached_nodeids = config.cache.get(\"cache/nodeids\", [])"},{"col":4,"comment":"null","endLoc":286,"header":"def pytest_collection_modifyitems(self, session, config, items)","id":6926,"name":"pytest_collection_modifyitems","nodeType":"Function","startLoc":273,"text":"def pytest_collection_modifyitems(self, session, config, items):\n if self.active:\n new_items = OrderedDict()\n other_items = OrderedDict()\n for item in items:\n if item.nodeid not in self.cached_nodeids:\n new_items[item.nodeid] = item\n else:\n other_items[item.nodeid] = item\n\n items[:] = self._get_increasing_order(\n six.itervalues(new_items)\n ) + self._get_increasing_order(six.itervalues(other_items))\n self.cached_nodeids = [x.nodeid for x in items if isinstance(x, pytest.Item)]"},{"col":0,"comment":"null","endLoc":600,"header":"def test_single_line_else()","id":6927,"name":"test_single_line_else","nodeType":"Function","startLoc":598,"text":"def test_single_line_else():\n source = getstatement(1, \"if False: 2\\nelse: 3\")\n assert str(source) == \"else: 3\""},{"col":0,"comment":"null","endLoc":605,"header":"def test_single_line_finally()","id":6929,"name":"test_single_line_finally","nodeType":"Function","startLoc":603,"text":"def test_single_line_finally():\n source = getstatement(1, \"try: 1\\nfinally: 3\")\n assert str(source) == \"finally: 3\""},{"col":0,"comment":"null","endLoc":614,"header":"def test_issue55()","id":6930,"name":"test_issue55","nodeType":"Function","startLoc":608,"text":"def test_issue55():\n source = (\n \"def round_trip(dinp):\\n assert 1 == dinp\\n\"\n 'def test_rt():\\n round_trip(\"\"\"\\n\"\"\")\\n'\n )\n s = getstatement(3, source)\n assert str(s) == ' round_trip(\"\"\"\\n\"\"\")'"},{"col":4,"comment":"null","endLoc":520,"header":"def test_list_tuples(self)","id":6931,"name":"test_list_tuples","nodeType":"Function","startLoc":516,"text":"def test_list_tuples(self):\n expl = callequal([], [(1, 2)])\n assert len(expl) > 1\n expl = callequal([(1, 2)], [])\n assert len(expl) > 1"},{"col":4,"comment":"null","endLoc":544,"header":"def test_repr_verbose(self)","id":6932,"name":"test_repr_verbose","nodeType":"Function","startLoc":522,"text":"def test_repr_verbose(self):\n class Nums:\n def __init__(self, nums):\n self.nums = nums\n\n def __repr__(self):\n return str(self.nums)\n\n list_x = list(range(5000))\n list_y = list(range(5000))\n list_y[len(list_y) // 2] = 3\n nums_x = Nums(list_x)\n nums_y = Nums(list_y)\n\n assert callequal(nums_x, nums_y) is None\n\n expl = callequal(nums_x, nums_y, verbose=1)\n assert \"-\" + repr(nums_x) in expl\n assert \"+\" + repr(nums_y) in expl\n\n expl = callequal(nums_x, nums_y, verbose=2)\n assert \"-\" + repr(nums_x) in expl\n assert \"+\" + repr(nums_y) in expl"},{"col":0,"comment":"null","endLoc":627,"header":"def test_multiline()","id":6933,"name":"test_multiline","nodeType":"Function","startLoc":617,"text":"def test_multiline():\n source = getstatement(\n 0,\n \"\"\"\\\nraise ValueError(\n 23\n)\nx = 3\n\"\"\",\n )\n assert str(source) == \"raise ValueError(\\n 23\\n)\""},{"col":4,"comment":"null","endLoc":998,"header":"def test_toterminal_long_missing_source(self, importasmod, tmpdir)","id":6934,"name":"test_toterminal_long_missing_source","nodeType":"Function","startLoc":969,"text":"def test_toterminal_long_missing_source(self, importasmod, tmpdir):\n mod = importasmod(\n \"\"\"\n def g(x):\n raise ValueError(x)\n def f():\n g(3)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.f)\n tmpdir.join(\"mod.py\").remove()\n excinfo.traceback = excinfo.traceback.filter()\n repr = excinfo.getrepr()\n tw = TWMock()\n repr.toterminal(tw)\n assert tw.lines[0] == \"\"\n tw.lines.pop(0)\n assert tw.lines[0] == \"> ???\"\n assert tw.lines[1] == \"\"\n line = tw.get_write_msg(2)\n assert line.endswith(\"mod.py\")\n assert tw.lines[3] == \":5: \"\n assert tw.lines[4] == (\"_ \", None)\n assert tw.lines[5] == \"\"\n assert tw.lines[6] == \"> ???\"\n assert tw.lines[7] == \"E ValueError: 3\"\n assert tw.lines[8] == \"\"\n line = tw.get_write_msg(9)\n assert line.endswith(\"mod.py\")\n assert tw.lines[10] == \":3: ValueError\""},{"col":0,"comment":"null","endLoc":706,"header":"def test_semicolon()","id":6935,"name":"test_semicolon","nodeType":"Function","startLoc":701,"text":"def test_semicolon():\n s = \"\"\"\\\nhello ; pytest.skip()\n\"\"\"\n source = getstatement(0, s)\n assert str(source) == s.strip()"},{"col":0,"comment":"null","endLoc":717,"header":"def test_def_online()","id":6936,"name":"test_def_online","nodeType":"Function","startLoc":709,"text":"def test_def_online():\n s = \"\"\"\\\ndef func(): raise ValueError(42)\n\ndef something():\n pass\n\"\"\"\n source = getstatement(0, s)\n assert str(source) == \"def func(): raise ValueError(42)\""},{"col":4,"comment":"null","endLoc":1029,"header":"def test_toterminal_long_incomplete_source(self, importasmod, tmpdir)","id":6937,"name":"test_toterminal_long_incomplete_source","nodeType":"Function","startLoc":1000,"text":"def test_toterminal_long_incomplete_source(self, importasmod, tmpdir):\n mod = importasmod(\n \"\"\"\n def g(x):\n raise ValueError(x)\n def f():\n g(3)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.f)\n tmpdir.join(\"mod.py\").write(\"asdf\")\n excinfo.traceback = excinfo.traceback.filter()\n repr = excinfo.getrepr()\n tw = TWMock()\n repr.toterminal(tw)\n assert tw.lines[0] == \"\"\n tw.lines.pop(0)\n assert tw.lines[0] == \"> ???\"\n assert tw.lines[1] == \"\"\n line = tw.get_write_msg(2)\n assert line.endswith(\"mod.py\")\n assert tw.lines[3] == \":5: \"\n assert tw.lines[4] == (\"_ \", None)\n assert tw.lines[5] == \"\"\n assert tw.lines[6] == \"> ???\"\n assert tw.lines[7] == \"E ValueError: 3\"\n assert tw.lines[8] == \"\"\n line = tw.get_write_msg(9)\n assert line.endswith(\"mod.py\")\n assert tw.lines[10] == \":3: ValueError\""},{"col":0,"comment":"null","endLoc":726,"header":"def XXX_test_expression_multiline()","id":6938,"name":"XXX_test_expression_multiline","nodeType":"Function","startLoc":720,"text":"def XXX_test_expression_multiline():\n source = \"\"\"\\\nsomething\n'''\n'''\"\"\"\n result = getstatement(1, source)\n assert str(result) == \"'''\\n'''\""},{"col":0,"comment":"null","endLoc":742,"header":"def test_getstartingblock_multiline()","id":6939,"name":"test_getstartingblock_multiline","nodeType":"Function","startLoc":729,"text":"def test_getstartingblock_multiline():\n class A(object):\n def __init__(self, *args):\n frame = sys._getframe(1)\n self.source = _pytest._code.Frame(frame).statement\n\n # fmt: off\n x = A('x',\n 'y'\n ,\n 'z')\n # fmt: on\n values = [i for i in x.source.lines if i.strip()]\n assert len(values) == 4"},{"col":4,"comment":"null","endLoc":1058,"header":"def test_toterminal_long_filenames(self, importasmod)","id":6940,"name":"test_toterminal_long_filenames","nodeType":"Function","startLoc":1031,"text":"def test_toterminal_long_filenames(self, importasmod):\n mod = importasmod(\n \"\"\"\n def f():\n raise ValueError()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.f)\n tw = TWMock()\n path = py.path.local(mod.__file__)\n old = path.dirpath().chdir()\n try:\n repr = excinfo.getrepr(abspath=False)\n repr.toterminal(tw)\n x = py.path.local().bestrelpath(path)\n if len(x) < len(str(path)):\n msg = tw.get_write_msg(-2)\n assert msg == \"mod.py\"\n assert tw.lines[-1] == \":3: ValueError\"\n\n repr = excinfo.getrepr(abspath=True)\n repr.toterminal(tw)\n msg = tw.get_write_msg(-2)\n assert msg == path\n line = tw.lines[-1]\n assert line == \":3: ValueError\"\n finally:\n old.chdir()"},{"attributeType":"null","col":0,"comment":"null","endLoc":19,"id":6942,"name":"failsonjython","nodeType":"Attribute","startLoc":19,"text":"failsonjython"},{"col":0,"comment":"","endLoc":5,"header":"test_source.py#","id":6943,"name":"","nodeType":"Function","startLoc":5,"text":"failsonjython = pytest.mark.xfail(\"sys.platform.startswith('java')\")\n\nif True:\n\n def x():\n pass"},{"col":4,"comment":"null","endLoc":1088,"header":"@pytest.mark.parametrize(\n \"reproptions\",\n [\n {\n \"style\": style,\n \"showlocals\": showlocals,\n \"funcargs\": funcargs,\n \"tbfilter\": tbfilter,\n }\n for style in (\"long\", \"short\", \"no\")\n for showlocals in (True, False)\n for tbfilter in (True, False)\n for funcargs in (True, False)\n ],\n )\n def test_format_excinfo(self, importasmod, reproptions)","id":6945,"name":"test_format_excinfo","nodeType":"Function","startLoc":1060,"text":"@pytest.mark.parametrize(\n \"reproptions\",\n [\n {\n \"style\": style,\n \"showlocals\": showlocals,\n \"funcargs\": funcargs,\n \"tbfilter\": tbfilter,\n }\n for style in (\"long\", \"short\", \"no\")\n for showlocals in (True, False)\n for tbfilter in (True, False)\n for funcargs in (True, False)\n ],\n )\n def test_format_excinfo(self, importasmod, reproptions):\n mod = importasmod(\n \"\"\"\n def g(x):\n raise ValueError(x)\n def f():\n g(3)\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.f)\n tw = py.io.TerminalWriter(stringio=True)\n repr = excinfo.getrepr(**reproptions)\n repr.toterminal(tw)\n assert tw.stringio.getvalue()"},{"col":4,"comment":"null","endLoc":1134,"header":"def test_traceback_repr_style(self, importasmod)","id":6946,"name":"test_traceback_repr_style","nodeType":"Function","startLoc":1090,"text":"def test_traceback_repr_style(self, importasmod):\n mod = importasmod(\n \"\"\"\n def f():\n g()\n def g():\n h()\n def h():\n i()\n def i():\n raise ValueError()\n \"\"\"\n )\n excinfo = pytest.raises(ValueError, mod.f)\n excinfo.traceback = excinfo.traceback.filter()\n excinfo.traceback[1].set_repr_style(\"short\")\n excinfo.traceback[2].set_repr_style(\"short\")\n r = excinfo.getrepr(style=\"long\")\n tw = TWMock()\n r.toterminal(tw)\n for line in tw.lines:\n print(line)\n assert tw.lines[0] == \"\"\n assert tw.lines[1] == \" def f():\"\n assert tw.lines[2] == \"> g()\"\n assert tw.lines[3] == \"\"\n msg = tw.get_write_msg(4)\n assert msg.endswith(\"mod.py\")\n assert tw.lines[5] == \":3: \"\n assert tw.lines[6] == (\"_ \", None)\n tw.get_write_msg(7)\n assert tw.lines[8].endswith(\"in g\")\n assert tw.lines[9] == \" h()\"\n tw.get_write_msg(10)\n assert tw.lines[11].endswith(\"in h\")\n assert tw.lines[12] == \" i()\"\n assert tw.lines[13] == (\"_ \", None)\n assert tw.lines[14] == \"\"\n assert tw.lines[15] == \" def i():\"\n assert tw.lines[16] == \"> raise ValueError()\"\n assert tw.lines[17] == \"E ValueError\"\n assert tw.lines[18] == \"\"\n msg = tw.get_write_msg(19)\n msg.endswith(\"mod.py\")\n assert tw.lines[20] == \":9: ValueError\""},{"col":0,"comment":"null","endLoc":399,"header":"def _compare_eq_cls(left, right, verbose, type_fns)","id":6947,"name":"_compare_eq_cls","nodeType":"Function","startLoc":370,"text":"def _compare_eq_cls(left, right, verbose, type_fns):\n isdatacls, isattrs = type_fns\n if isdatacls(left):\n all_fields = left.__dataclass_fields__\n fields_to_check = [field for field, info in all_fields.items() if info.compare]\n elif isattrs(left):\n all_fields = left.__attrs_attrs__\n fields_to_check = [field.name for field in all_fields if field.cmp]\n\n same = []\n diff = []\n for field in fields_to_check:\n if getattr(left, field) == getattr(right, field):\n same.append(field)\n else:\n diff.append(field)\n\n explanation = []\n if same and verbose < 2:\n explanation.append(u\"Omitting %s identical items, use -vv to show\" % len(same))\n elif same:\n explanation += [u\"Matching attributes:\"]\n explanation += pprint.pformat(same).splitlines()\n if diff:\n explanation += [u\"Differing attributes:\"]\n for field in diff:\n explanation += [\n (u\"%s: %r != %r\") % (field, getattr(left, field), getattr(right, field))\n ]\n return explanation"},{"attributeType":"null","col":0,"comment":"null","endLoc":10,"id":6948,"name":"pytestmark","nodeType":"Attribute","startLoc":10,"text":"pytestmark"},{"attributeType":"list","col":0,"comment":"null","endLoc":12,"id":6949,"name":"MODSET","nodeType":"Attribute","startLoc":12,"text":"MODSET"},{"attributeType":"null","col":8,"comment":"null","endLoc":14,"id":6950,"name":"x","nodeType":"Attribute","startLoc":14,"text":"x"},{"col":0,"comment":"","endLoc":2,"header":"test_modimport.py#","id":6951,"name":"","nodeType":"Function","startLoc":2,"text":"pytestmark = pytest.mark.slow\n\nMODSET = [\n x\n for x in py.path.local(_pytest.__file__).dirpath().visit(\"*.py\")\n if x.purebasename != \"__init__\"\n]"},{"col":4,"comment":"null","endLoc":942,"header":"def visit_UnaryOp(self, unary)","id":6953,"name":"visit_UnaryOp","nodeType":"Function","startLoc":938,"text":"def visit_UnaryOp(self, unary):\n pattern = unary_map[unary.op.__class__]\n operand_res, operand_expl = self.visit(unary.operand)\n res = self.assign(ast.UnaryOp(unary.op, operand_res))\n return res, pattern % (operand_expl,)"},{"col":4,"comment":"null","endLoc":950,"header":"def visit_BinOp(self, binop)","id":6954,"name":"visit_BinOp","nodeType":"Function","startLoc":944,"text":"def visit_BinOp(self, binop):\n symbol = binop_map[binop.op.__class__]\n left_expr, left_expl = self.visit(binop.left)\n right_expr, right_expl = self.visit(binop.right)\n explanation = \"(%s %s %s)\" % (left_expl, symbol, right_expl)\n res = self.assign(ast.BinOp(left_expr, binop.op, right_expr))\n return res, explanation"},{"col":4,"comment":"\n visit `ast.Call` nodes on Python3.5 and after\n ","endLoc":977,"header":"def visit_Call_35(self, call)","id":6955,"name":"visit_Call_35","nodeType":"Function","startLoc":952,"text":"def visit_Call_35(self, call):\n \"\"\"\n visit `ast.Call` nodes on Python3.5 and after\n \"\"\"\n new_func, func_expl = self.visit(call.func)\n arg_expls = []\n new_args = []\n new_kwargs = []\n for arg in call.args:\n res, expl = self.visit(arg)\n arg_expls.append(expl)\n new_args.append(res)\n for keyword in call.keywords:\n res, expl = self.visit(keyword.value)\n new_kwargs.append(ast.keyword(keyword.arg, res))\n if keyword.arg:\n arg_expls.append(keyword.arg + \"=\" + expl)\n else: # **args have `arg` keywords with an .arg of None\n arg_expls.append(\"**\" + expl)\n\n expl = \"%s(%s)\" % (func_expl, \", \".join(arg_expls))\n new_call = ast.Call(new_func, new_args, new_kwargs)\n res = self.assign(new_call)\n res_expl = self.explanation_param(self.display(res))\n outer_expl = \"%s\\n{%s = %s\\n}\" % (res_expl, res_expl, expl)\n return res, outer_expl"},{"col":4,"comment":"null","endLoc":289,"header":"def _get_increasing_order(self, items)","id":6956,"name":"_get_increasing_order","nodeType":"Function","startLoc":288,"text":"def _get_increasing_order(self, items):\n return sorted(items, key=lambda item: item.fspath.mtime(), reverse=True)"},{"col":33,"endLoc":289,"id":6957,"nodeType":"Lambda","startLoc":289,"text":"lambda item: item.fspath.mtime()"},{"col":4,"comment":"null","endLoc":296,"header":"def pytest_sessionfinish(self, session)","id":6958,"name":"pytest_sessionfinish","nodeType":"Function","startLoc":291,"text":"def pytest_sessionfinish(self, session):\n config = self.config\n if config.getoption(\"cacheshow\") or hasattr(config, \"slaveinput\"):\n return\n\n config.cache.set(\"cache/nodeids\", self.cached_nodeids)"},{"col":4,"comment":"Invoke subprocess.Popen.\n\n This calls subprocess.Popen making sure the current working directory\n is in the PYTHONPATH.\n\n You probably want to use :py:meth:`run` instead.\n\n ","endLoc":1068,"header":"def popen(\n self,\n cmdargs,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n stdin=CLOSE_STDIN,\n **kw\n )","id":6959,"name":"popen","nodeType":"Function","startLoc":1032,"text":"def popen(\n self,\n cmdargs,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n stdin=CLOSE_STDIN,\n **kw\n ):\n \"\"\"Invoke subprocess.Popen.\n\n This calls subprocess.Popen making sure the current working directory\n is in the PYTHONPATH.\n\n You probably want to use :py:meth:`run` instead.\n\n \"\"\"\n env = os.environ.copy()\n env[\"PYTHONPATH\"] = os.pathsep.join(\n filter(None, [os.getcwd(), env.get(\"PYTHONPATH\", \"\")])\n )\n env.update(self._env_run_update)\n kw[\"env\"] = env\n\n if stdin is Testdir.CLOSE_STDIN:\n kw[\"stdin\"] = subprocess.PIPE\n elif isinstance(stdin, bytes):\n kw[\"stdin\"] = subprocess.PIPE\n else:\n kw[\"stdin\"] = stdin\n\n popen = subprocess.Popen(cmdargs, stdout=stdout, stderr=stderr, **kw)\n if stdin is Testdir.CLOSE_STDIN:\n popen.stdin.close()\n elif isinstance(stdin, bytes):\n popen.stdin.write(stdin)\n\n return popen"},{"attributeType":"null","col":8,"comment":"null","endLoc":270,"id":6962,"name":"active","nodeType":"Attribute","startLoc":270,"text":"self.active"},{"attributeType":"null","col":8,"comment":"null","endLoc":271,"id":6963,"name":"cached_nodeids","nodeType":"Attribute","startLoc":271,"text":"self.cached_nodeids"},{"col":4,"comment":"null","endLoc":554,"header":"def test_list_bad_repr(self)","id":6964,"name":"test_list_bad_repr","nodeType":"Function","startLoc":546,"text":"def test_list_bad_repr(self):\n class A(object):\n def __repr__(self):\n raise ValueError(42)\n\n expl = callequal([], [A()])\n assert \"ValueError\" in \"\".join(expl)\n expl = callequal({}, {\"1\": A()})\n assert \"faulty\" in \"\".join(expl)"},{"attributeType":"{option, cache}","col":8,"comment":"null","endLoc":269,"id":6965,"name":"config","nodeType":"Attribute","startLoc":269,"text":"self.config"},{"col":0,"comment":"null","endLoc":354,"header":"def pytest_addoption(parser)","id":6966,"name":"pytest_addoption","nodeType":"Function","startLoc":299,"text":"def pytest_addoption(parser):\n group = parser.getgroup(\"general\")\n group.addoption(\n \"--lf\",\n \"--last-failed\",\n action=\"store_true\",\n dest=\"lf\",\n help=\"rerun only the tests that failed \"\n \"at the last run (or all if none failed)\",\n )\n group.addoption(\n \"--ff\",\n \"--failed-first\",\n action=\"store_true\",\n dest=\"failedfirst\",\n help=\"run all tests but run the last failures first. \"\n \"This may re-order tests and thus lead to \"\n \"repeated fixture setup/teardown\",\n )\n group.addoption(\n \"--nf\",\n \"--new-first\",\n action=\"store_true\",\n dest=\"newfirst\",\n help=\"run tests from new files first, then the rest of the tests \"\n \"sorted by file mtime\",\n )\n group.addoption(\n \"--cache-show\",\n action=\"append\",\n nargs=\"?\",\n dest=\"cacheshow\",\n help=(\n \"show cache contents, don't perform collection or tests. \"\n \"Optional argument: glob (default: '*').\"\n ),\n )\n group.addoption(\n \"--cache-clear\",\n action=\"store_true\",\n dest=\"cacheclear\",\n help=\"remove all cache contents at start of test run.\",\n )\n cache_dir_default = \".pytest_cache\"\n if \"TOX_ENV_DIR\" in os.environ:\n cache_dir_default = os.path.join(os.environ[\"TOX_ENV_DIR\"], cache_dir_default)\n parser.addini(\"cache_dir\", default=cache_dir_default, help=\"cache directory path.\")\n group.addoption(\n \"--lfnf\",\n \"--last-failed-no-failures\",\n action=\"store\",\n dest=\"last_failed_no_failures\",\n choices=(\"all\", \"none\"),\n default=\"all\",\n help=\"which tests to run with no previously (known) failures.\",\n )"},{"col":0,"comment":"null","endLoc":361,"header":"def pytest_cmdline_main(config)","id":6968,"name":"pytest_cmdline_main","nodeType":"Function","startLoc":357,"text":"def pytest_cmdline_main(config):\n if config.option.cacheshow:\n from _pytest.main import wrap_session\n\n return wrap_session(config, cacheshow)"},{"col":4,"comment":"\n the faulty empty string repr did trigger\n an unbound local error in _diff_text\n ","endLoc":567,"header":"def test_one_repr_empty(self)","id":6969,"name":"test_one_repr_empty","nodeType":"Function","startLoc":556,"text":"def test_one_repr_empty(self):\n \"\"\"\n the faulty empty string repr did trigger\n an unbound local error in _diff_text\n \"\"\"\n\n class A(str):\n def __repr__(self):\n return \"\"\n\n expl = callequal(A(), \"\")\n assert not expl"},{"col":0,"comment":"null","endLoc":368,"header":"@pytest.hookimpl(tryfirst=True)\ndef pytest_configure(config)","id":6970,"name":"pytest_configure","nodeType":"Function","startLoc":364,"text":"@pytest.hookimpl(tryfirst=True)\ndef pytest_configure(config):\n config.cache = Cache.for_config(config)\n config.pluginmanager.register(LFPlugin(config), \"lfplugin\")\n config.pluginmanager.register(NFPlugin(config), \"nfplugin\")"},{"col":0,"comment":"null","endLoc":261,"header":"def _compare_eq_verbose(left, right)","id":6972,"name":"_compare_eq_verbose","nodeType":"Function","startLoc":252,"text":"def _compare_eq_verbose(left, right):\n keepends = True\n left_lines = repr(left).splitlines(keepends)\n right_lines = repr(right).splitlines(keepends)\n\n explanation = []\n explanation += [u\"-\" + line for line in left_lines]\n explanation += [u\"+\" + line for line in right_lines]\n\n return explanation"},{"col":4,"comment":"null","endLoc":571,"header":"def test_repr_no_exc(self)","id":6973,"name":"test_repr_no_exc","nodeType":"Function","startLoc":569,"text":"def test_repr_no_exc(self):\n expl = \" \".join(callequal(\"foo\", \"bar\"))\n assert \"raised in repr()\" not in expl"},{"col":4,"comment":"null","endLoc":579,"header":"def test_unicode(self)","id":6974,"name":"test_unicode","nodeType":"Function","startLoc":573,"text":"def test_unicode(self):\n left = u\"£€\"\n right = u\"£\"\n expl = callequal(left, right)\n assert expl[0] == u\"'£€' == '£'\"\n assert expl[1] == u\"- £€\"\n assert expl[2] == u\"+ £\""},{"col":4,"comment":"\n :issue: 877\n non ascii python2 str caused a UnicodeDecodeError\n ","endLoc":595,"header":"def test_nonascii_text(self)","id":6975,"name":"test_nonascii_text","nodeType":"Function","startLoc":581,"text":"def test_nonascii_text(self):\n \"\"\"\n :issue: 877\n non ascii python2 str caused a UnicodeDecodeError\n \"\"\"\n\n class A(str):\n def __repr__(self):\n return \"\\xff\"\n\n expl = callequal(A(), \"1\")\n if PY3:\n assert expl == [\"ÿ == '1'\", \"+ 1\"]\n else:\n assert expl == [u\"\\ufffd == '1'\", u\"+ 1\"]"},{"col":0,"comment":"null","endLoc":284,"header":"def _compare_eq_iterable(left, right, verbose=0)","id":6976,"name":"_compare_eq_iterable","nodeType":"Function","startLoc":264,"text":"def _compare_eq_iterable(left, right, verbose=0):\n if not verbose:\n return [u\"Use -v to get the full diff\"]\n # dynamic import to speedup pytest\n import difflib\n\n try:\n left_formatting = pprint.pformat(left).splitlines()\n right_formatting = pprint.pformat(right).splitlines()\n explanation = [u\"Full diff:\"]\n except Exception:\n # hack: PrettyPrinter.pformat() in python 2 fails when formatting items that can't be sorted(), ie, calling\n # sorted() on a list would raise. See issue #718.\n # As a workaround, the full diff is generated by using the repr() string of each item of each container.\n left_formatting = sorted(repr(x) for x in left)\n right_formatting = sorted(repr(x) for x in right)\n explanation = [u\"Full diff (fallback to calling repr on each item):\"]\n explanation.extend(\n line.strip() for line in difflib.ndiff(left_formatting, right_formatting)\n )\n return explanation"},{"col":4,"comment":"null","endLoc":1220,"header":"@pytest.mark.skipif(\"sys.version_info[0] < 3\")\n def test_exc_chain_repr(self, importasmod)","id":6977,"name":"test_exc_chain_repr","nodeType":"Function","startLoc":1136,"text":"@pytest.mark.skipif(\"sys.version_info[0] < 3\")\n def test_exc_chain_repr(self, importasmod):\n mod = importasmod(\n \"\"\"\n class Err(Exception):\n pass\n def f():\n try:\n g()\n except Exception as e:\n raise Err() from e\n finally:\n h()\n def g():\n raise ValueError()\n\n def h():\n raise AttributeError()\n \"\"\"\n )\n excinfo = pytest.raises(AttributeError, mod.f)\n r = excinfo.getrepr(style=\"long\")\n tw = TWMock()\n r.toterminal(tw)\n for line in tw.lines:\n print(line)\n assert tw.lines[0] == \"\"\n assert tw.lines[1] == \" def f():\"\n assert tw.lines[2] == \" try:\"\n assert tw.lines[3] == \"> g()\"\n assert tw.lines[4] == \"\"\n line = tw.get_write_msg(5)\n assert line.endswith(\"mod.py\")\n assert tw.lines[6] == \":6: \"\n assert tw.lines[7] == (\"_ \", None)\n assert tw.lines[8] == \"\"\n assert tw.lines[9] == \" def g():\"\n assert tw.lines[10] == \"> raise ValueError()\"\n assert tw.lines[11] == \"E ValueError\"\n assert tw.lines[12] == \"\"\n line = tw.get_write_msg(13)\n assert line.endswith(\"mod.py\")\n assert tw.lines[14] == \":12: ValueError\"\n assert tw.lines[15] == \"\"\n assert (\n tw.lines[16]\n == \"The above exception was the direct cause of the following exception:\"\n )\n assert tw.lines[17] == \"\"\n assert tw.lines[18] == \" def f():\"\n assert tw.lines[19] == \" try:\"\n assert tw.lines[20] == \" g()\"\n assert tw.lines[21] == \" except Exception as e:\"\n assert tw.lines[22] == \"> raise Err() from e\"\n assert tw.lines[23] == \"E test_exc_chain_repr0.mod.Err\"\n assert tw.lines[24] == \"\"\n line = tw.get_write_msg(25)\n assert line.endswith(\"mod.py\")\n assert tw.lines[26] == \":8: Err\"\n assert tw.lines[27] == \"\"\n assert (\n tw.lines[28]\n == \"During handling of the above exception, another exception occurred:\"\n )\n assert tw.lines[29] == \"\"\n assert tw.lines[30] == \" def f():\"\n assert tw.lines[31] == \" try:\"\n assert tw.lines[32] == \" g()\"\n assert tw.lines[33] == \" except Exception as e:\"\n assert tw.lines[34] == \" raise Err() from e\"\n assert tw.lines[35] == \" finally:\"\n assert tw.lines[36] == \"> h()\"\n assert tw.lines[37] == \"\"\n line = tw.get_write_msg(38)\n assert line.endswith(\"mod.py\")\n assert tw.lines[39] == \":10: \"\n assert tw.lines[40] == (\"_ \", None)\n assert tw.lines[41] == \"\"\n assert tw.lines[42] == \" def h():\"\n assert tw.lines[43] == \"> raise AttributeError()\"\n assert tw.lines[44] == \"E AttributeError\"\n assert tw.lines[45] == \"\"\n line = tw.get_write_msg(46)\n assert line.endswith(\"mod.py\")\n assert tw.lines[47] == \":15: AttributeError\""},{"col":4,"comment":"null","endLoc":598,"header":"def test_format_nonascii_explanation(self)","id":6978,"name":"test_format_nonascii_explanation","nodeType":"Function","startLoc":597,"text":"def test_format_nonascii_explanation(self):\n assert util.format_explanation(\"λ\")"},{"col":4,"comment":"null","endLoc":608,"header":"def test_mojibake(self)","id":6979,"name":"test_mojibake","nodeType":"Function","startLoc":600,"text":"def test_mojibake(self):\n # issue 429\n left = b\"e\"\n right = b\"\\xc3\\xa9\"\n expl = callequal(left, right)\n for line in expl:\n assert isinstance(line, six.text_type)\n msg = u\"\\n\".join(expl)\n assert msg"},{"className":"TestAssert_reprcompare_dataclass","col":0,"comment":"null","endLoc":653,"id":6980,"nodeType":"Class","startLoc":611,"text":"class TestAssert_reprcompare_dataclass(object):\n @pytest.mark.skipif(sys.version_info < (3, 7), reason=\"Dataclasses in Python3.7+\")\n def test_dataclasses(self, testdir):\n p = testdir.copy_example(\"dataclasses/test_compare_dataclasses.py\")\n result = testdir.runpytest(p)\n result.assert_outcomes(failed=1, passed=0)\n result.stdout.fnmatch_lines(\n [\n \"*Omitting 1 identical items, use -vv to show*\",\n \"*Differing attributes:*\",\n \"*field_b: 'b' != 'c'*\",\n ]\n )\n\n @pytest.mark.skipif(sys.version_info < (3, 7), reason=\"Dataclasses in Python3.7+\")\n def test_dataclasses_verbose(self, testdir):\n p = testdir.copy_example(\"dataclasses/test_compare_dataclasses_verbose.py\")\n result = testdir.runpytest(p, \"-vv\")\n result.assert_outcomes(failed=1, passed=0)\n result.stdout.fnmatch_lines(\n [\n \"*Matching attributes:*\",\n \"*['field_a']*\",\n \"*Differing attributes:*\",\n \"*field_b: 'b' != 'c'*\",\n ]\n )\n\n @pytest.mark.skipif(sys.version_info < (3, 7), reason=\"Dataclasses in Python3.7+\")\n def test_dataclasses_with_attribute_comparison_off(self, testdir):\n p = testdir.copy_example(\n \"dataclasses/test_compare_dataclasses_field_comparison_off.py\"\n )\n result = testdir.runpytest(p, \"-vv\")\n result.assert_outcomes(failed=0, passed=1)\n\n @pytest.mark.skipif(sys.version_info < (3, 7), reason=\"Dataclasses in Python3.7+\")\n def test_comparing_two_different_data_classes(self, testdir):\n p = testdir.copy_example(\n \"dataclasses/test_compare_two_different_dataclasses.py\"\n )\n result = testdir.runpytest(p, \"-vv\")\n result.assert_outcomes(failed=0, passed=1)"},{"col":4,"comment":"null","endLoc":623,"header":"@pytest.mark.skipif(sys.version_info < (3, 7), reason=\"Dataclasses in Python3.7+\")\n def test_dataclasses(self, testdir)","id":6981,"name":"test_dataclasses","nodeType":"Function","startLoc":612,"text":"@pytest.mark.skipif(sys.version_info < (3, 7), reason=\"Dataclasses in Python3.7+\")\n def test_dataclasses(self, testdir):\n p = testdir.copy_example(\"dataclasses/test_compare_dataclasses.py\")\n result = testdir.runpytest(p)\n result.assert_outcomes(failed=1, passed=0)\n result.stdout.fnmatch_lines(\n [\n \"*Omitting 1 identical items, use -vv to show*\",\n \"*Differing attributes:*\",\n \"*field_b: 'b' != 'c'*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":637,"header":"@pytest.mark.skipif(sys.version_info < (3, 7), reason=\"Dataclasses in Python3.7+\")\n def test_dataclasses_verbose(self, testdir)","id":6984,"name":"test_dataclasses_verbose","nodeType":"Function","startLoc":625,"text":"@pytest.mark.skipif(sys.version_info < (3, 7), reason=\"Dataclasses in Python3.7+\")\n def test_dataclasses_verbose(self, testdir):\n p = testdir.copy_example(\"dataclasses/test_compare_dataclasses_verbose.py\")\n result = testdir.runpytest(p, \"-vv\")\n result.assert_outcomes(failed=1, passed=0)\n result.stdout.fnmatch_lines(\n [\n \"*Matching attributes:*\",\n \"*['field_a']*\",\n \"*Differing attributes:*\",\n \"*field_b: 'b' != 'c'*\",\n ]\n )"},{"col":4,"comment":"null","endLoc":645,"header":"@pytest.mark.skipif(sys.version_info < (3, 7), reason=\"Dataclasses in Python3.7+\")\n def test_dataclasses_with_attribute_comparison_off(self, testdir)","id":6985,"name":"test_dataclasses_with_attribute_comparison_off","nodeType":"Function","startLoc":639,"text":"@pytest.mark.skipif(sys.version_info < (3, 7), reason=\"Dataclasses in Python3.7+\")\n def test_dataclasses_with_attribute_comparison_off(self, testdir):\n p = testdir.copy_example(\n \"dataclasses/test_compare_dataclasses_field_comparison_off.py\"\n )\n result = testdir.runpytest(p, \"-vv\")\n result.assert_outcomes(failed=0, passed=1)"},{"col":4,"comment":"null","endLoc":983,"header":"def visit_Starred(self, starred)","id":6986,"name":"visit_Starred","nodeType":"Function","startLoc":979,"text":"def visit_Starred(self, starred):\n # From Python 3.5, a Starred node can appear in a function call\n res, expl = self.visit(starred.value)\n new_starred = ast.Starred(res, starred.ctx)\n return new_starred, \"*\" + expl"},{"col":4,"comment":"null","endLoc":653,"header":"@pytest.mark.skipif(sys.version_info < (3, 7), reason=\"Dataclasses in Python3.7+\")\n def test_comparing_two_different_data_classes(self, testdir)","id":6987,"name":"test_comparing_two_different_data_classes","nodeType":"Function","startLoc":647,"text":"@pytest.mark.skipif(sys.version_info < (3, 7), reason=\"Dataclasses in Python3.7+\")\n def test_comparing_two_different_data_classes(self, testdir):\n p = testdir.copy_example(\n \"dataclasses/test_compare_two_different_dataclasses.py\"\n )\n result = testdir.runpytest(p, \"-vv\")\n result.assert_outcomes(failed=0, passed=1)"},{"className":"TestAssert_reprcompare_attrsclass","col":0,"comment":"null","endLoc":717,"id":6988,"nodeType":"Class","startLoc":656,"text":"class TestAssert_reprcompare_attrsclass(object):\n def test_attrs(self):\n @attr.s\n class SimpleDataObject(object):\n field_a = attr.ib()\n field_b = attr.ib()\n\n left = SimpleDataObject(1, \"b\")\n right = SimpleDataObject(1, \"c\")\n\n lines = callequal(left, right)\n assert lines[1].startswith(\"Omitting 1 identical item\")\n assert \"Matching attributes\" not in lines\n for line in lines[1:]:\n assert \"field_a\" not in line\n\n def test_attrs_verbose(self):\n @attr.s\n class SimpleDataObject(object):\n field_a = attr.ib()\n field_b = attr.ib()\n\n left = SimpleDataObject(1, \"b\")\n right = SimpleDataObject(1, \"c\")\n\n lines = callequal(left, right, verbose=2)\n assert lines[1].startswith(\"Matching attributes:\")\n assert \"Omitting\" not in lines[1]\n assert lines[2] == \"['field_a']\"\n\n def test_attrs_with_attribute_comparison_off(self):\n @attr.s\n class SimpleDataObject(object):\n field_a = attr.ib()\n field_b = attr.ib(cmp=False)\n\n left = SimpleDataObject(1, \"b\")\n right = SimpleDataObject(1, \"b\")\n\n lines = callequal(left, right, verbose=2)\n assert lines[1].startswith(\"Matching attributes:\")\n assert \"Omitting\" not in lines[1]\n assert lines[2] == \"['field_a']\"\n for line in lines[2:]:\n assert \"field_b\" not in line\n\n def test_comparing_two_different_attrs_classes(self):\n @attr.s\n class SimpleDataObjectOne(object):\n field_a = attr.ib()\n field_b = attr.ib()\n\n @attr.s\n class SimpleDataObjectTwo(object):\n field_a = attr.ib()\n field_b = attr.ib()\n\n left = SimpleDataObjectOne(1, \"b\")\n right = SimpleDataObjectTwo(1, \"c\")\n\n lines = callequal(left, right)\n assert lines is None"},{"col":4,"comment":"null","endLoc":670,"header":"def test_attrs(self)","id":6989,"name":"test_attrs","nodeType":"Function","startLoc":657,"text":"def test_attrs(self):\n @attr.s\n class SimpleDataObject(object):\n field_a = attr.ib()\n field_b = attr.ib()\n\n left = SimpleDataObject(1, \"b\")\n right = SimpleDataObject(1, \"c\")\n\n lines = callequal(left, right)\n assert lines[1].startswith(\"Omitting 1 identical item\")\n assert \"Matching attributes\" not in lines\n for line in lines[1:]:\n assert \"field_a\" not in line"},{"col":0,"comment":"\n Return a cache object that can persist state between testing sessions.\n\n cache.get(key, default)\n cache.set(key, value)\n\n Keys must be a ``/`` separated value, where the first part is usually the\n name of your plugin or application to avoid clashes with other cache users.\n\n Values can be any object handled by the json stdlib module.\n ","endLoc":384,"header":"@pytest.fixture\ndef cache(request)","id":6990,"name":"cache","nodeType":"Function","startLoc":371,"text":"@pytest.fixture\ndef cache(request):\n \"\"\"\n Return a cache object that can persist state between testing sessions.\n\n cache.get(key, default)\n cache.set(key, value)\n\n Keys must be a ``/`` separated value, where the first part is usually the\n name of your plugin or application to avoid clashes with other cache users.\n\n Values can be any object handled by the json stdlib module.\n \"\"\"\n return request.config.cache"},{"col":4,"comment":"\n visit `ast.Call nodes on 3.4 and below`\n ","endLoc":1013,"header":"def visit_Call_legacy(self, call)","id":6992,"name":"visit_Call_legacy","nodeType":"Function","startLoc":985,"text":"def visit_Call_legacy(self, call):\n \"\"\"\n visit `ast.Call nodes on 3.4 and below`\n \"\"\"\n new_func, func_expl = self.visit(call.func)\n arg_expls = []\n new_args = []\n new_kwargs = []\n new_star = new_kwarg = None\n for arg in call.args:\n res, expl = self.visit(arg)\n new_args.append(res)\n arg_expls.append(expl)\n for keyword in call.keywords:\n res, expl = self.visit(keyword.value)\n new_kwargs.append(ast.keyword(keyword.arg, res))\n arg_expls.append(keyword.arg + \"=\" + expl)\n if call.starargs:\n new_star, expl = self.visit(call.starargs)\n arg_expls.append(\"*\" + expl)\n if call.kwargs:\n new_kwarg, expl = self.visit(call.kwargs)\n arg_expls.append(\"**\" + expl)\n expl = \"%s(%s)\" % (func_expl, \", \".join(arg_expls))\n new_call = ast.Call(new_func, new_args, new_kwargs, new_star, new_kwarg)\n res = self.assign(new_call)\n res_expl = self.explanation_param(self.display(res))\n outer_expl = \"%s\\n{%s = %s\\n}\" % (res_expl, res_expl, expl)\n return res, outer_expl"},{"col":0,"comment":"Display cachedir with --cache-show and if non-default.","endLoc":398,"header":"def pytest_report_header(config)","id":6993,"name":"pytest_report_header","nodeType":"Function","startLoc":387,"text":"def pytest_report_header(config):\n \"\"\"Display cachedir with --cache-show and if non-default.\"\"\"\n if config.option.verbose > 0 or config.getini(\"cache_dir\") != \".pytest_cache\":\n cachedir = config.cache._cachedir\n # TODO: evaluate generating upward relative paths\n # starting with .., ../.. if sensible\n\n try:\n displaypath = cachedir.relative_to(config.rootdir)\n except ValueError:\n displaypath = cachedir\n return \"cachedir: {}\".format(displaypath)"},{"col":4,"comment":"Check that exc repr does not show chained exceptions in Python 3.\n - When the exception is raised with \"from None\"\n - Explicitly suppressed with \"chain=False\" to ExceptionInfo.getrepr().\n ","endLoc":1262,"header":"@pytest.mark.skipif(\"sys.version_info[0] < 3\")\n @pytest.mark.parametrize(\"mode\", [\"from_none\", \"explicit_suppress\"])\n def test_exc_repr_chain_suppression(self, importasmod, mode)","id":6994,"name":"test_exc_repr_chain_suppression","nodeType":"Function","startLoc":1222,"text":"@pytest.mark.skipif(\"sys.version_info[0] < 3\")\n @pytest.mark.parametrize(\"mode\", [\"from_none\", \"explicit_suppress\"])\n def test_exc_repr_chain_suppression(self, importasmod, mode):\n \"\"\"Check that exc repr does not show chained exceptions in Python 3.\n - When the exception is raised with \"from None\"\n - Explicitly suppressed with \"chain=False\" to ExceptionInfo.getrepr().\n \"\"\"\n raise_suffix = \" from None\" if mode == \"from_none\" else \"\"\n mod = importasmod(\n \"\"\"\n def f():\n try:\n g()\n except Exception:\n raise AttributeError(){raise_suffix}\n def g():\n raise ValueError()\n \"\"\".format(\n raise_suffix=raise_suffix\n )\n )\n excinfo = pytest.raises(AttributeError, mod.f)\n r = excinfo.getrepr(style=\"long\", chain=mode != \"explicit_suppress\")\n tw = TWMock()\n r.toterminal(tw)\n for line in tw.lines:\n print(line)\n assert tw.lines[0] == \"\"\n assert tw.lines[1] == \" def f():\"\n assert tw.lines[2] == \" try:\"\n assert tw.lines[3] == \" g()\"\n assert tw.lines[4] == \" except Exception:\"\n assert tw.lines[5] == \"> raise AttributeError(){}\".format(\n raise_suffix\n )\n assert tw.lines[6] == \"E AttributeError\"\n assert tw.lines[7] == \"\"\n line = tw.get_write_msg(8)\n assert line.endswith(\"mod.py\")\n assert tw.lines[9] == \":6: AttributeError\"\n assert len(tw.lines) == 10"},{"col":0,"comment":"null","endLoc":438,"header":"def cacheshow(config, session)","id":6995,"name":"cacheshow","nodeType":"Function","startLoc":401,"text":"def cacheshow(config, session):\n from pprint import pformat\n\n tw = py.io.TerminalWriter()\n tw.line(\"cachedir: \" + str(config.cache._cachedir))\n if not config.cache._cachedir.is_dir():\n tw.line(\"cache is empty\")\n return 0\n\n glob = config.option.cacheshow[0]\n if glob is None:\n glob = \"*\"\n\n dummy = object()\n basedir = config.cache._cachedir\n vdir = basedir / \"v\"\n tw.sep(\"-\", \"cache values for %r\" % glob)\n for valpath in sorted(x for x in vdir.rglob(glob) if x.is_file()):\n key = valpath.relative_to(vdir)\n val = config.cache.get(key, dummy)\n if val is dummy:\n tw.line(\"%s contains unreadable content, will be ignored\" % key)\n else:\n tw.line(\"%s contains:\" % key)\n for line in pformat(val).splitlines():\n tw.line(\" \" + line)\n\n ddir = basedir / \"d\"\n if ddir.is_dir():\n contents = sorted(ddir.rglob(glob))\n tw.sep(\"-\", \"cache directories for %r\" % glob)\n for p in contents:\n # if p.check(dir=1):\n # print(\"%s/\" % p.relto(basedir))\n if p.is_file():\n key = p.relative_to(basedir)\n tw.line(\"{} is a file of length {:d}\".format(key, p.stat().st_size))\n return 0"},{"col":4,"comment":"null","endLoc":684,"header":"def test_attrs_verbose(self)","id":6996,"name":"test_attrs_verbose","nodeType":"Function","startLoc":672,"text":"def test_attrs_verbose(self):\n @attr.s\n class SimpleDataObject(object):\n field_a = attr.ib()\n field_b = attr.ib()\n\n left = SimpleDataObject(1, \"b\")\n right = SimpleDataObject(1, \"c\")\n\n lines = callequal(left, right, verbose=2)\n assert lines[1].startswith(\"Matching attributes:\")\n assert \"Omitting\" not in lines[1]\n assert lines[2] == \"['field_a']\""},{"col":4,"comment":"\n Handle representation of exception chains where one of the exceptions doesn't have a\n real traceback, such as those raised in a subprocess submitted by the multiprocessing\n module (#1984).\n ","endLoc":1322,"header":"@pytest.mark.skipif(\"sys.version_info[0] < 3\")\n @pytest.mark.parametrize(\n \"reason, description\",\n [\n (\n \"cause\",\n \"The above exception was the direct cause of the following exception","id":6998,"name":"test_exc_chain_repr_without_traceback","nodeType":"Function","startLoc":1264,"text":"@pytest.mark.skipif(\"sys.version_info[0] < 3\")\n @pytest.mark.parametrize(\n \"reason, description\",\n [\n (\n \"cause\",\n \"The above exception was the direct cause of the following exception:\",\n ),\n (\n \"context\",\n \"During handling of the above exception, another exception occurred:\",\n ),\n ],\n )\n def test_exc_chain_repr_without_traceback(self, importasmod, reason, description):\n \"\"\"\n Handle representation of exception chains where one of the exceptions doesn't have a\n real traceback, such as those raised in a subprocess submitted by the multiprocessing\n module (#1984).\n \"\"\"\n from _pytest.pytester import LineMatcher\n\n exc_handling_code = \" from e\" if reason == \"cause\" else \"\"\n mod = importasmod(\n \"\"\"\n def f():\n try:\n g()\n except Exception as e:\n raise RuntimeError('runtime problem'){exc_handling_code}\n def g():\n raise ValueError('invalid value')\n \"\"\".format(\n exc_handling_code=exc_handling_code\n )\n )\n\n with pytest.raises(RuntimeError) as excinfo:\n mod.f()\n\n # emulate the issue described in #1984\n attr = \"__%s__\" % reason\n getattr(excinfo.value, attr).__traceback__ = None\n\n r = excinfo.getrepr()\n tw = py.io.TerminalWriter(stringio=True)\n tw.hasmarkup = False\n r.toterminal(tw)\n\n matcher = LineMatcher(tw.stringio.getvalue().splitlines())\n matcher.fnmatch_lines(\n [\n \"ValueError: invalid value\",\n description,\n \"* except Exception as e:\",\n \"> * raise RuntimeError('runtime problem')\" + exc_handling_code,\n \"E *RuntimeError: runtime problem\",\n ]\n )"},{"col":4,"comment":"null","endLoc":700,"header":"def test_attrs_with_attribute_comparison_off(self)","id":6999,"name":"test_attrs_with_attribute_comparison_off","nodeType":"Function","startLoc":686,"text":"def test_attrs_with_attribute_comparison_off(self):\n @attr.s\n class SimpleDataObject(object):\n field_a = attr.ib()\n field_b = attr.ib(cmp=False)\n\n left = SimpleDataObject(1, \"b\")\n right = SimpleDataObject(1, \"b\")\n\n lines = callequal(left, right, verbose=2)\n assert lines[1].startswith(\"Matching attributes:\")\n assert \"Omitting\" not in lines[1]\n assert lines[2] == \"['field_a']\"\n for line in lines[2:]:\n assert \"field_b\" not in line"},{"col":0,"comment":"null","endLoc":418,"header":"def _notin_text(term, text, verbose=0)","id":7000,"name":"_notin_text","nodeType":"Function","startLoc":402,"text":"def _notin_text(term, text, verbose=0):\n index = text.find(term)\n head = text[:index]\n tail = text[index + len(term) :]\n correct_text = head + tail\n diff = _diff_text(correct_text, text, verbose)\n newdiff = [u\"%s is contained here:\" % saferepr(term, maxsize=42)]\n for line in diff:\n if line.startswith(u\"Skipping\"):\n continue\n if line.startswith(u\"- \"):\n continue\n if line.startswith(u\"+ \"):\n newdiff.append(u\" \" + line[2:])\n else:\n newdiff.append(line)\n return newdiff"},{"col":4,"comment":"null","endLoc":717,"header":"def test_comparing_two_different_attrs_classes(self)","id":7001,"name":"test_comparing_two_different_attrs_classes","nodeType":"Function","startLoc":702,"text":"def test_comparing_two_different_attrs_classes(self):\n @attr.s\n class SimpleDataObjectOne(object):\n field_a = attr.ib()\n field_b = attr.ib()\n\n @attr.s\n class SimpleDataObjectTwo(object):\n field_a = attr.ib()\n field_b = attr.ib()\n\n left = SimpleDataObjectOne(1, \"b\")\n right = SimpleDataObjectTwo(1, \"c\")\n\n lines = callequal(left, right)\n assert lines is None"},{"col":4,"comment":"null","endLoc":1366,"header":"@pytest.mark.skipif(\"sys.version_info[0] < 3\")\n def test_exc_chain_repr_cycle(self, importasmod)","id":7002,"name":"test_exc_chain_repr_cycle","nodeType":"Function","startLoc":1324,"text":"@pytest.mark.skipif(\"sys.version_info[0] < 3\")\n def test_exc_chain_repr_cycle(self, importasmod):\n mod = importasmod(\n \"\"\"\n class Err(Exception):\n pass\n def fail():\n return 0 / 0\n def reraise():\n try:\n fail()\n except ZeroDivisionError as e:\n raise Err() from e\n def unreraise():\n try:\n reraise()\n except Err as e:\n raise e.__cause__\n \"\"\"\n )\n excinfo = pytest.raises(ZeroDivisionError, mod.unreraise)\n r = excinfo.getrepr(style=\"short\")\n tw = TWMock()\n r.toterminal(tw)\n out = \"\\n\".join(line for line in tw.lines if isinstance(line, str))\n expected_out = textwrap.dedent(\n \"\"\"\\\n :13: in unreraise\n reraise()\n :10: in reraise\n raise Err() from e\n E test_exc_chain_repr_cycle0.mod.Err\n\n During handling of the above exception, another exception occurred:\n :15: in unreraise\n raise e.__cause__\n :8: in reraise\n fail()\n :5: in fail\n return 0 / 0\n E ZeroDivisionError: division by zero\"\"\"\n )\n assert out == expected_out"},{"className":"TestFormatExplanation","col":0,"comment":"null","endLoc":804,"id":7003,"nodeType":"Class","startLoc":720,"text":"class TestFormatExplanation(object):\n def test_special_chars_full(self, testdir):\n # Issue 453, for the bug this would raise IndexError\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert '\\\\n}' == ''\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines([\"*AssertionError*\"])\n\n def test_fmt_simple(self):\n expl = \"assert foo\"\n assert util.format_explanation(expl) == \"assert foo\"\n\n def test_fmt_where(self):\n expl = \"\\n\".join([\"assert 1\", \"{1 = foo\", \"} == 2\"])\n res = \"\\n\".join([\"assert 1 == 2\", \" + where 1 = foo\"])\n assert util.format_explanation(expl) == res\n\n def test_fmt_and(self):\n expl = \"\\n\".join([\"assert 1\", \"{1 = foo\", \"} == 2\", \"{2 = bar\", \"}\"])\n res = \"\\n\".join([\"assert 1 == 2\", \" + where 1 = foo\", \" + and 2 = bar\"])\n assert util.format_explanation(expl) == res\n\n def test_fmt_where_nested(self):\n expl = \"\\n\".join([\"assert 1\", \"{1 = foo\", \"{foo = bar\", \"}\", \"} == 2\"])\n res = \"\\n\".join([\"assert 1 == 2\", \" + where 1 = foo\", \" + where foo = bar\"])\n assert util.format_explanation(expl) == res\n\n def test_fmt_newline(self):\n expl = \"\\n\".join(['assert \"foo\" == \"bar\"', \"~- foo\", \"~+ bar\"])\n res = \"\\n\".join(['assert \"foo\" == \"bar\"', \" - foo\", \" + bar\"])\n assert util.format_explanation(expl) == res\n\n def test_fmt_newline_escaped(self):\n expl = \"\\n\".join([\"assert foo == bar\", \"baz\"])\n res = \"assert foo == bar\\\\nbaz\"\n assert util.format_explanation(expl) == res\n\n def test_fmt_newline_before_where(self):\n expl = \"\\n\".join(\n [\n \"the assertion message here\",\n \">assert 1\",\n \"{1 = foo\",\n \"} == 2\",\n \"{2 = bar\",\n \"}\",\n ]\n )\n res = \"\\n\".join(\n [\n \"the assertion message here\",\n \"assert 1 == 2\",\n \" + where 1 = foo\",\n \" + and 2 = bar\",\n ]\n )\n assert util.format_explanation(expl) == res\n\n def test_fmt_multi_newline_before_where(self):\n expl = \"\\n\".join(\n [\n \"the assertion\",\n \"~message here\",\n \">assert 1\",\n \"{1 = foo\",\n \"} == 2\",\n \"{2 = bar\",\n \"}\",\n ]\n )\n res = \"\\n\".join(\n [\n \"the assertion\",\n \" message here\",\n \"assert 1 == 2\",\n \" + where 1 = foo\",\n \" + and 2 = bar\",\n ]\n )\n assert util.format_explanation(expl) == res"},{"col":4,"comment":"null","endLoc":731,"header":"def test_special_chars_full(self, testdir)","id":7004,"name":"test_special_chars_full","nodeType":"Function","startLoc":721,"text":"def test_special_chars_full(self, testdir):\n # Issue 453, for the bug this would raise IndexError\n testdir.makepyfile(\n \"\"\"\n def test_foo():\n assert '\\\\n}' == ''\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines([\"*AssertionError*\"])"},{"col":4,"comment":"null","endLoc":735,"header":"def test_fmt_simple(self)","id":7005,"name":"test_fmt_simple","nodeType":"Function","startLoc":733,"text":"def test_fmt_simple(self):\n expl = \"assert foo\"\n assert util.format_explanation(expl) == \"assert foo\""},{"col":4,"comment":"null","endLoc":740,"header":"def test_fmt_where(self)","id":7006,"name":"test_fmt_where","nodeType":"Function","startLoc":737,"text":"def test_fmt_where(self):\n expl = \"\\n\".join([\"assert 1\", \"{1 = foo\", \"} == 2\"])\n res = \"\\n\".join([\"assert 1 == 2\", \" + where 1 = foo\"])\n assert util.format_explanation(expl) == res"},{"col":4,"comment":"null","endLoc":745,"header":"def test_fmt_and(self)","id":7007,"name":"test_fmt_and","nodeType":"Function","startLoc":742,"text":"def test_fmt_and(self):\n expl = \"\\n\".join([\"assert 1\", \"{1 = foo\", \"} == 2\", \"{2 = bar\", \"}\"])\n res = \"\\n\".join([\"assert 1 == 2\", \" + where 1 = foo\", \" + and 2 = bar\"])\n assert util.format_explanation(expl) == res"},{"col":4,"comment":"null","endLoc":750,"header":"def test_fmt_where_nested(self)","id":7008,"name":"test_fmt_where_nested","nodeType":"Function","startLoc":747,"text":"def test_fmt_where_nested(self):\n expl = \"\\n\".join([\"assert 1\", \"{1 = foo\", \"{foo = bar\", \"}\", \"} == 2\"])\n res = \"\\n\".join([\"assert 1 == 2\", \" + where 1 = foo\", \" + where foo = bar\"])\n assert util.format_explanation(expl) == res"},{"col":4,"comment":"null","endLoc":755,"header":"def test_fmt_newline(self)","id":7009,"name":"test_fmt_newline","nodeType":"Function","startLoc":752,"text":"def test_fmt_newline(self):\n expl = \"\\n\".join(['assert \"foo\" == \"bar\"', \"~- foo\", \"~+ bar\"])\n res = \"\\n\".join(['assert \"foo\" == \"bar\"', \" - foo\", \" + bar\"])\n assert util.format_explanation(expl) == res"},{"col":4,"comment":"null","endLoc":760,"header":"def test_fmt_newline_escaped(self)","id":7010,"name":"test_fmt_newline_escaped","nodeType":"Function","startLoc":757,"text":"def test_fmt_newline_escaped(self):\n expl = \"\\n\".join([\"assert foo == bar\", \"baz\"])\n res = \"assert foo == bar\\\\nbaz\"\n assert util.format_explanation(expl) == res"},{"col":4,"comment":"null","endLoc":781,"header":"def test_fmt_newline_before_where(self)","id":7011,"name":"test_fmt_newline_before_where","nodeType":"Function","startLoc":762,"text":"def test_fmt_newline_before_where(self):\n expl = \"\\n\".join(\n [\n \"the assertion message here\",\n \">assert 1\",\n \"{1 = foo\",\n \"} == 2\",\n \"{2 = bar\",\n \"}\",\n ]\n )\n res = \"\\n\".join(\n [\n \"the assertion message here\",\n \"assert 1 == 2\",\n \" + where 1 = foo\",\n \" + and 2 = bar\",\n ]\n )\n assert util.format_explanation(expl) == res"},{"col":4,"comment":"null","endLoc":804,"header":"def test_fmt_multi_newline_before_where(self)","id":7012,"name":"test_fmt_multi_newline_before_where","nodeType":"Function","startLoc":783,"text":"def test_fmt_multi_newline_before_where(self):\n expl = \"\\n\".join(\n [\n \"the assertion\",\n \"~message here\",\n \">assert 1\",\n \"{1 = foo\",\n \"} == 2\",\n \"{2 = bar\",\n \"}\",\n ]\n )\n res = \"\\n\".join(\n [\n \"the assertion\",\n \" message here\",\n \"assert 1 == 2\",\n \" + where 1 = foo\",\n \" + and 2 = bar\",\n ]\n )\n assert util.format_explanation(expl) == res"},{"col":0,"comment":"null","endLoc":39,"header":"@pytest.fixture\ndef limited_recursion_depth()","id":7013,"name":"limited_recursion_depth","nodeType":"Function","startLoc":34,"text":"@pytest.fixture\ndef limited_recursion_depth():\n before = sys.getrecursionlimit()\n sys.setrecursionlimit(150)\n yield\n sys.setrecursionlimit(before)"},{"className":"TestTruncateExplanation","col":0,"comment":" Confirm assertion output is truncated as expected ","endLoc":910,"id":7015,"nodeType":"Class","startLoc":807,"text":"class TestTruncateExplanation(object):\n\n \"\"\" Confirm assertion output is truncated as expected \"\"\"\n\n # The number of lines in the truncation explanation message. Used\n # to calculate that results have the expected length.\n LINES_IN_TRUNCATION_MSG = 2\n\n def test_doesnt_truncate_when_input_is_empty_list(self):\n expl = []\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)\n assert result == expl\n\n def test_doesnt_truncate_at_when_input_is_5_lines_and_LT_max_chars(self):\n expl = [\"a\" * 100 for x in range(5)]\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)\n assert result == expl\n\n def test_truncates_at_8_lines_when_given_list_of_empty_strings(self):\n expl = [\"\" for x in range(50)]\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)\n assert result != expl\n assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG\n assert \"Full output truncated\" in result[-1]\n assert \"43 lines hidden\" in result[-1]\n last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]\n assert last_line_before_trunc_msg.endswith(\"...\")\n\n def test_truncates_at_8_lines_when_first_8_lines_are_LT_max_chars(self):\n expl = [\"a\" for x in range(100)]\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)\n assert result != expl\n assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG\n assert \"Full output truncated\" in result[-1]\n assert \"93 lines hidden\" in result[-1]\n last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]\n assert last_line_before_trunc_msg.endswith(\"...\")\n\n def test_truncates_at_8_lines_when_first_8_lines_are_EQ_max_chars(self):\n expl = [\"a\" * 80 for x in range(16)]\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)\n assert result != expl\n assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG\n assert \"Full output truncated\" in result[-1]\n assert \"9 lines hidden\" in result[-1]\n last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]\n assert last_line_before_trunc_msg.endswith(\"...\")\n\n def test_truncates_at_4_lines_when_first_4_lines_are_GT_max_chars(self):\n expl = [\"a\" * 250 for x in range(10)]\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=999)\n assert result != expl\n assert len(result) == 4 + self.LINES_IN_TRUNCATION_MSG\n assert \"Full output truncated\" in result[-1]\n assert \"7 lines hidden\" in result[-1]\n last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]\n assert last_line_before_trunc_msg.endswith(\"...\")\n\n def test_truncates_at_1_line_when_first_line_is_GT_max_chars(self):\n expl = [\"a\" * 250 for x in range(1000)]\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)\n assert result != expl\n assert len(result) == 1 + self.LINES_IN_TRUNCATION_MSG\n assert \"Full output truncated\" in result[-1]\n assert \"1000 lines hidden\" in result[-1]\n last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]\n assert last_line_before_trunc_msg.endswith(\"...\")\n\n def test_full_output_truncated(self, monkeypatch, testdir):\n \"\"\" Test against full runpytest() output. \"\"\"\n\n line_count = 7\n line_len = 100\n expected_truncated_lines = 2\n testdir.makepyfile(\n r\"\"\"\n def test_many_lines():\n a = list([str(i)[0] * %d for i in range(%d)])\n b = a[::2]\n a = '\\n'.join(map(str, a))\n b = '\\n'.join(map(str, b))\n assert a == b\n \"\"\"\n % (line_len, line_count)\n )\n monkeypatch.delenv(\"CI\", raising=False)\n\n result = testdir.runpytest()\n # without -vv, truncate the message showing a few diff lines only\n result.stdout.fnmatch_lines(\n [\n \"*- 1*\",\n \"*- 3*\",\n \"*- 5*\",\n \"*truncated (%d lines hidden)*use*-vv*\" % expected_truncated_lines,\n ]\n )\n\n result = testdir.runpytest(\"-vv\")\n result.stdout.fnmatch_lines([\"* 6*\"])\n\n monkeypatch.setenv(\"CI\", \"1\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 6*\"])"},{"col":4,"comment":"null","endLoc":818,"header":"def test_doesnt_truncate_when_input_is_empty_list(self)","id":7016,"name":"test_doesnt_truncate_when_input_is_empty_list","nodeType":"Function","startLoc":815,"text":"def test_doesnt_truncate_when_input_is_empty_list(self):\n expl = []\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)\n assert result == expl"},{"col":0,"comment":"null","endLoc":74,"header":"def test_excinfo_simple()","id":7018,"name":"test_excinfo_simple","nodeType":"Function","startLoc":69,"text":"def test_excinfo_simple():\n try:\n raise ValueError\n except ValueError:\n info = _pytest._code.ExceptionInfo.from_current()\n assert info.type == ValueError"},{"col":4,"comment":"null","endLoc":823,"header":"def test_doesnt_truncate_at_when_input_is_5_lines_and_LT_max_chars(self)","id":7019,"name":"test_doesnt_truncate_at_when_input_is_5_lines_and_LT_max_chars","nodeType":"Function","startLoc":820,"text":"def test_doesnt_truncate_at_when_input_is_5_lines_and_LT_max_chars(self):\n expl = [\"a\" * 100 for x in range(5)]\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)\n assert result == expl"},{"col":0,"comment":"null","endLoc":98,"header":"def test_excinfo_getstatement()","id":7020,"name":"test_excinfo_getstatement","nodeType":"Function","startLoc":77,"text":"def test_excinfo_getstatement():\n def g():\n raise ValueError\n\n def f():\n g()\n\n try:\n f()\n except ValueError:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n linenumbers = [\n _pytest._code.getrawcode(f).co_firstlineno - 1 + 4,\n _pytest._code.getrawcode(f).co_firstlineno - 1 + 1,\n _pytest._code.getrawcode(g).co_firstlineno - 1 + 1,\n ]\n values = list(excinfo.traceback)\n foundlinenumbers = [x.lineno for x in values]\n assert foundlinenumbers == linenumbers\n # for x in info:\n # print \"%s:%d %s\" %(x.path.relto(root), x.lineno, x.statement)\n # xxx"},{"col":4,"comment":"null","endLoc":1166,"header":"def _dump_lines(self, lines, fp)","id":7022,"name":"_dump_lines","nodeType":"Function","startLoc":1161,"text":"def _dump_lines(self, lines, fp):\n try:\n for line in lines:\n print(line, file=fp)\n except UnicodeEncodeError:\n print(\"couldn't print to %s because of encoding\" % (fp,))"},{"col":4,"comment":"Return the collection node for name from the module collection.\n\n This will search a module collection node for a collection node\n matching the given name.\n\n :param modcol: a module collection node; see :py:meth:`getmodulecol`\n\n :param name: the name of the node to return\n\n ","endLoc":1030,"header":"def collect_by_name(self, modcol, name)","id":7024,"name":"collect_by_name","nodeType":"Function","startLoc":1015,"text":"def collect_by_name(self, modcol, name):\n \"\"\"Return the collection node for name from the module collection.\n\n This will search a module collection node for a collection node\n matching the given name.\n\n :param modcol: a module collection node; see :py:meth:`getmodulecol`\n\n :param name: the name of the node to return\n\n \"\"\"\n if modcol not in self._mod_collections:\n self._mod_collections[modcol] = list(modcol.collect())\n for colitem in self._mod_collections[modcol]:\n if colitem.name == name:\n return colitem"},{"col":4,"comment":"null","endLoc":833,"header":"def test_truncates_at_8_lines_when_given_list_of_empty_strings(self)","id":7025,"name":"test_truncates_at_8_lines_when_given_list_of_empty_strings","nodeType":"Function","startLoc":825,"text":"def test_truncates_at_8_lines_when_given_list_of_empty_strings(self):\n expl = [\"\" for x in range(50)]\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)\n assert result != expl\n assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG\n assert \"Full output truncated\" in result[-1]\n assert \"43 lines hidden\" in result[-1]\n last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]\n assert last_line_before_trunc_msg.endswith(\"...\")"},{"col":4,"comment":"Run a python script using sys.executable as interpreter.\n\n Returns a :py:class:`RunResult`.\n\n ","endLoc":1177,"header":"def runpython(self, script)","id":7026,"name":"runpython","nodeType":"Function","startLoc":1171,"text":"def runpython(self, script):\n \"\"\"Run a python script using sys.executable as interpreter.\n\n Returns a :py:class:`RunResult`.\n\n \"\"\"\n return self.run(sys.executable, script)"},{"col":4,"comment":"Run python -c \"command\", return a :py:class:`RunResult`.","endLoc":1181,"header":"def runpython_c(self, command)","id":7027,"name":"runpython_c","nodeType":"Function","startLoc":1179,"text":"def runpython_c(self, command):\n \"\"\"Run python -c \"command\", return a :py:class:`RunResult`.\"\"\"\n return self.run(sys.executable, \"-c\", command)"},{"col":4,"comment":"Run pytest using pexpect.\n\n This makes sure to use the right pytest and sets up the temporary\n directory locations.\n\n The pexpect child is returned.\n\n ","endLoc":1224,"header":"def spawn_pytest(self, string, expect_timeout=10.0)","id":7028,"name":"spawn_pytest","nodeType":"Function","startLoc":1212,"text":"def spawn_pytest(self, string, expect_timeout=10.0):\n \"\"\"Run pytest using pexpect.\n\n This makes sure to use the right pytest and sets up the temporary\n directory locations.\n\n The pexpect child is returned.\n\n \"\"\"\n basetemp = self.tmpdir.mkdir(\"temp-pexpect\")\n invoke = \" \".join(map(str, self._getpytestargs()))\n cmd = \"%s --basetemp=%s %s\" % (invoke, basetemp, string)\n return self.spawn(cmd, expect_timeout=expect_timeout)"},{"col":0,"comment":"null","endLoc":342,"header":"def test_excinfo_exconly()","id":7029,"name":"test_excinfo_exconly","nodeType":"Function","startLoc":335,"text":"def test_excinfo_exconly():\n excinfo = pytest.raises(ValueError, h)\n assert excinfo.exconly().startswith(\"ValueError\")\n with pytest.raises(ValueError) as excinfo:\n raise ValueError(\"hello\\nworld\")\n msg = excinfo.exconly(tryshort=True)\n assert msg.startswith(\"ValueError\")\n assert msg.endswith(\"world\")"},{"col":4,"comment":"null","endLoc":843,"header":"def test_truncates_at_8_lines_when_first_8_lines_are_LT_max_chars(self)","id":7030,"name":"test_truncates_at_8_lines_when_first_8_lines_are_LT_max_chars","nodeType":"Function","startLoc":835,"text":"def test_truncates_at_8_lines_when_first_8_lines_are_LT_max_chars(self):\n expl = [\"a\" for x in range(100)]\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)\n assert result != expl\n assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG\n assert \"Full output truncated\" in result[-1]\n assert \"93 lines hidden\" in result[-1]\n last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]\n assert last_line_before_trunc_msg.endswith(\"...\")"},{"col":0,"comment":"null","endLoc":348,"header":"def test_excinfo_repr()","id":7031,"name":"test_excinfo_repr","nodeType":"Function","startLoc":345,"text":"def test_excinfo_repr():\n excinfo = pytest.raises(ValueError, h)\n s = repr(excinfo)\n assert s == \"\""},{"col":0,"comment":"null","endLoc":356,"header":"def test_excinfo_str()","id":7032,"name":"test_excinfo_str","nodeType":"Function","startLoc":351,"text":"def test_excinfo_str():\n excinfo = pytest.raises(ValueError, h)\n s = str(excinfo)\n assert s.startswith(__file__[:-9]) # pyc file and $py.class\n assert s.endswith(\"ValueError\")\n assert len(s.split(\":\")) >= 3 # on windows it's 4"},{"col":4,"comment":"null","endLoc":853,"header":"def test_truncates_at_8_lines_when_first_8_lines_are_EQ_max_chars(self)","id":7033,"name":"test_truncates_at_8_lines_when_first_8_lines_are_EQ_max_chars","nodeType":"Function","startLoc":845,"text":"def test_truncates_at_8_lines_when_first_8_lines_are_EQ_max_chars(self):\n expl = [\"a\" * 80 for x in range(16)]\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)\n assert result != expl\n assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG\n assert \"Full output truncated\" in result[-1]\n assert \"9 lines hidden\" in result[-1]\n last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]\n assert last_line_before_trunc_msg.endswith(\"...\")"},{"attributeType":"str","col":0,"comment":"null","endLoc":26,"id":7034,"name":"README_CONTENT","nodeType":"Attribute","startLoc":26,"text":"README_CONTENT"},{"attributeType":"bytes","col":0,"comment":"null","endLoc":37,"id":7035,"name":"CACHEDIR_TAG_CONTENT","nodeType":"Attribute","startLoc":37,"text":"CACHEDIR_TAG_CONTENT"},{"col":0,"comment":"","endLoc":7,"header":"cacheprovider.py#","id":7036,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"\nmerged implementation of the cache provider\n\nthe name cache was not chosen to ensure pluggy automatically\nignores the external pytest-cache\n\"\"\"\n\nREADME_CONTENT = u\"\"\"\\\n# pytest cache directory #\n\nThis directory contains data from the pytest's cache plugin,\nwhich provides the `--lf` and `--ff` options, as well as the `cache` fixture.\n\n**Do not** commit this to version control.\n\nSee [the docs](https://docs.pytest.org/en/latest/cache.html) for more information.\n\"\"\"\n\nCACHEDIR_TAG_CONTENT = b\"\"\"\\\nSignature: 8a477f597d28d172789f06886806bc55\n# This file is a cache directory tag created by pytest.\n# For information about cache directory tags, see:\n#\thttp://www.bford.info/cachedir/spec.html\n\"\"\""},{"col":4,"comment":"null","endLoc":863,"header":"def test_truncates_at_4_lines_when_first_4_lines_are_GT_max_chars(self)","id":7037,"name":"test_truncates_at_4_lines_when_first_4_lines_are_GT_max_chars","nodeType":"Function","startLoc":855,"text":"def test_truncates_at_4_lines_when_first_4_lines_are_GT_max_chars(self):\n expl = [\"a\" * 250 for x in range(10)]\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=999)\n assert result != expl\n assert len(result) == 4 + self.LINES_IN_TRUNCATION_MSG\n assert \"Full output truncated\" in result[-1]\n assert \"7 lines hidden\" in result[-1]\n last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]\n assert last_line_before_trunc_msg.endswith(\"...\")"},{"attributeType":"None","col":0,"comment":"null","endLoc":20,"id":7038,"name":"_reprcompare","nodeType":"Attribute","startLoc":20,"text":"_reprcompare"},{"attributeType":"null","col":4,"comment":"null","endLoc":102,"id":7039,"name":"basestring","nodeType":"Attribute","startLoc":102,"text":"basestring"},{"col":0,"comment":"","endLoc":2,"header":"util.py#","id":7040,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"Utilities for assertion debugging\"\"\"\n\n_reprcompare = None\n\ntry:\n basestring = basestring\nexcept NameError:\n basestring = str"},{"col":0,"comment":"null","endLoc":362,"header":"def test_excinfo_for_later()","id":7041,"name":"test_excinfo_for_later","nodeType":"Function","startLoc":359,"text":"def test_excinfo_for_later():\n e = ExceptionInfo.for_later()\n assert \"for raises\" in repr(e)\n assert \"for raises\" in str(e)"},{"col":4,"comment":"null","endLoc":873,"header":"def test_truncates_at_1_line_when_first_line_is_GT_max_chars(self)","id":7042,"name":"test_truncates_at_1_line_when_first_line_is_GT_max_chars","nodeType":"Function","startLoc":865,"text":"def test_truncates_at_1_line_when_first_line_is_GT_max_chars(self):\n expl = [\"a\" * 250 for x in range(1000)]\n result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)\n assert result != expl\n assert len(result) == 1 + self.LINES_IN_TRUNCATION_MSG\n assert \"Full output truncated\" in result[-1]\n assert \"1000 lines hidden\" in result[-1]\n last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]\n assert last_line_before_trunc_msg.endswith(\"...\")"},{"col":0,"comment":"null","endLoc":367,"header":"def test_excinfo_errisinstance()","id":7043,"name":"test_excinfo_errisinstance","nodeType":"Function","startLoc":365,"text":"def test_excinfo_errisinstance():\n excinfo = pytest.raises(ValueError, h)\n assert excinfo.errisinstance(ValueError)"},{"col":0,"comment":"null","endLoc":376,"header":"def test_excinfo_no_sourcecode()","id":7044,"name":"test_excinfo_no_sourcecode","nodeType":"Function","startLoc":370,"text":"def test_excinfo_no_sourcecode():\n try:\n exec(\"raise ValueError()\")\n except ValueError:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n s = str(excinfo.traceback[-1])\n assert s == \" File '':1 in \\n ???\\n\""},{"col":4,"comment":" Test against full runpytest() output. ","endLoc":910,"header":"def test_full_output_truncated(self, monkeypatch, testdir)","id":7045,"name":"test_full_output_truncated","nodeType":"Function","startLoc":875,"text":"def test_full_output_truncated(self, monkeypatch, testdir):\n \"\"\" Test against full runpytest() output. \"\"\"\n\n line_count = 7\n line_len = 100\n expected_truncated_lines = 2\n testdir.makepyfile(\n r\"\"\"\n def test_many_lines():\n a = list([str(i)[0] * %d for i in range(%d)])\n b = a[::2]\n a = '\\n'.join(map(str, a))\n b = '\\n'.join(map(str, b))\n assert a == b\n \"\"\"\n % (line_len, line_count)\n )\n monkeypatch.delenv(\"CI\", raising=False)\n\n result = testdir.runpytest()\n # without -vv, truncate the message showing a few diff lines only\n result.stdout.fnmatch_lines(\n [\n \"*- 1*\",\n \"*- 3*\",\n \"*- 5*\",\n \"*truncated (%d lines hidden)*use*-vv*\" % expected_truncated_lines,\n ]\n )\n\n result = testdir.runpytest(\"-vv\")\n result.stdout.fnmatch_lines([\"* 6*\"])\n\n monkeypatch.setenv(\"CI\", \"1\")\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 6*\"])"},{"attributeType":"int","col":4,"comment":"null","endLoc":813,"id":7046,"name":"LINES_IN_TRUNCATION_MSG","nodeType":"Attribute","startLoc":813,"text":"LINES_IN_TRUNCATION_MSG"},{"col":0,"comment":"null","endLoc":392,"header":"def test_excinfo_no_python_sourcecode(tmpdir)","id":7047,"name":"test_excinfo_no_python_sourcecode","nodeType":"Function","startLoc":379,"text":"def test_excinfo_no_python_sourcecode(tmpdir):\n # XXX: simplified locally testable version\n tmpdir.join(\"test.txt\").write(\"{{ h()}}:\")\n\n jinja2 = pytest.importorskip(\"jinja2\")\n loader = jinja2.FileSystemLoader(str(tmpdir))\n env = jinja2.Environment(loader=loader)\n template = env.get_template(\"test.txt\")\n excinfo = pytest.raises(ValueError, template.render, h=h)\n for item in excinfo.traceback:\n print(item) # XXX: for some reason jinja.Template.render is printed in full\n item.source # shouldnt fail\n if item.path.basename == \"test.txt\":\n assert str(item.source) == \"{{ h()}}:\""},{"col":0,"comment":"null","endLoc":928,"header":"def test_python25_compile_issue257(testdir)","id":7048,"name":"test_python25_compile_issue257","nodeType":"Function","startLoc":913,"text":"def test_python25_compile_issue257(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_rewritten():\n assert 1 == 2\n # some comment\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret == 1\n result.stdout.fnmatch_lines(\n \"\"\"\n *E*assert 1 == 2*\n *1 failed*\n \"\"\"\n )"},{"col":0,"comment":"null","endLoc":938,"header":"def test_rewritten(testdir)","id":7049,"name":"test_rewritten","nodeType":"Function","startLoc":931,"text":"def test_rewritten(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_rewritten():\n assert \"@py_builtins\" in globals()\n \"\"\"\n )\n assert testdir.runpytest().ret == 0"},{"col":0,"comment":"null","endLoc":944,"header":"def test_reprcompare_notin()","id":7050,"name":"test_reprcompare_notin","nodeType":"Function","startLoc":941,"text":"def test_reprcompare_notin():\n config = mock_config()\n detail = plugin.pytest_assertrepr_compare(config, \"not in\", \"foo\", \"aaafoobbb\")[1:]\n assert detail == [\"'foo' is contained here:\", \" aaafoobbb\", \"? +++\"]"},{"col":0,"comment":"null","endLoc":956,"header":"def test_reprcompare_whitespaces()","id":7051,"name":"test_reprcompare_whitespaces","nodeType":"Function","startLoc":947,"text":"def test_reprcompare_whitespaces():\n config = mock_config()\n detail = plugin.pytest_assertrepr_compare(config, \"==\", \"\\r\\n\", \"\\n\")\n assert detail == [\n r\"'\\r\\n' == '\\n'\",\n r\"Strings contain only whitespace, escaping them using repr()\",\n r\"- '\\r\\n'\",\n r\"? --\",\n r\"+ '\\n'\",\n ]"},{"col":0,"comment":"null","endLoc":972,"header":"def test_pytest_assertrepr_compare_integration(testdir)","id":7052,"name":"test_pytest_assertrepr_compare_integration","nodeType":"Function","startLoc":959,"text":"def test_pytest_assertrepr_compare_integration(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n x = set(range(100))\n y = x.copy()\n y.remove(50)\n assert x == y\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"*def test_hello():*\", \"*assert x == y*\", \"*E*Extra items*left*\", \"*E*50*\"]\n )"},{"col":0,"comment":"null","endLoc":994,"header":"def test_sequence_comparison_uses_repr(testdir)","id":7053,"name":"test_sequence_comparison_uses_repr","nodeType":"Function","startLoc":975,"text":"def test_sequence_comparison_uses_repr(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n x = set(\"hello x\")\n y = set(\"hello y\")\n assert x == y\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*def test_hello():*\",\n \"*assert x == y*\",\n \"*E*Extra items*left*\",\n \"*E*'x'*\",\n \"*E*Extra items*right*\",\n \"*E*'y'*\",\n ]\n )"},{"col":0,"comment":"null","endLoc":1019,"header":"def test_assertrepr_loaded_per_dir(testdir)","id":7054,"name":"test_assertrepr_loaded_per_dir","nodeType":"Function","startLoc":997,"text":"def test_assertrepr_loaded_per_dir(testdir):\n testdir.makepyfile(test_base=[\"def test_base(): assert 1 == 2\"])\n a = testdir.mkdir(\"a\")\n a_test = a.join(\"test_a.py\")\n a_test.write(\"def test_a(): assert 1 == 2\")\n a_conftest = a.join(\"conftest.py\")\n a_conftest.write('def pytest_assertrepr_compare(): return [\"summary a\"]')\n b = testdir.mkdir(\"b\")\n b_test = b.join(\"test_b.py\")\n b_test.write(\"def test_b(): assert 1 == 2\")\n b_conftest = b.join(\"conftest.py\")\n b_conftest.write('def pytest_assertrepr_compare(): return [\"summary b\"]')\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\n \"*def test_base():*\",\n \"*E*assert 1 == 2*\",\n \"*def test_a():*\",\n \"*E*assert summary a*\",\n \"*def test_b():*\",\n \"*E*assert summary b*\",\n ]\n )"},{"col":0,"comment":"null","endLoc":1033,"header":"def test_assertion_options(testdir)","id":7055,"name":"test_assertion_options","nodeType":"Function","startLoc":1022,"text":"def test_assertion_options(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n x = 3\n assert x == 4\n \"\"\"\n )\n result = testdir.runpytest()\n assert \"3 == 4\" in result.stdout.str()\n result = testdir.runpytest_subprocess(\"--assert=plain\")\n assert \"3 == 4\" not in result.stdout.str()"},{"col":0,"comment":"null","endLoc":1045,"header":"def test_triple_quoted_string_issue113(testdir)","id":7056,"name":"test_triple_quoted_string_issue113","nodeType":"Function","startLoc":1036,"text":"def test_triple_quoted_string_issue113(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n assert \"\" == '''\n '''\"\"\"\n )\n result = testdir.runpytest(\"--fulltrace\")\n result.stdout.fnmatch_lines([\"*1 failed*\"])\n assert \"SyntaxError\" not in result.stdout.str()"},{"col":0,"comment":"null","endLoc":1100,"header":"def test_traceback_failure(testdir)","id":7057,"name":"test_traceback_failure","nodeType":"Function","startLoc":1048,"text":"def test_traceback_failure(testdir):\n p1 = testdir.makepyfile(\n \"\"\"\n def g():\n return 2\n def f(x):\n assert x == g()\n def test_onefails():\n f(3)\n \"\"\"\n )\n result = testdir.runpytest(p1, \"--tb=long\")\n result.stdout.fnmatch_lines(\n [\n \"*test_traceback_failure.py F*\",\n \"====* FAILURES *====\",\n \"____*____\",\n \"\",\n \" def test_onefails():\",\n \"> f(3)\",\n \"\",\n \"*test_*.py:6: \",\n \"_ _ _ *\",\n # \"\",\n \" def f(x):\",\n \"> assert x == g()\",\n \"E assert 3 == 2\",\n \"E + where 2 = g()\",\n \"\",\n \"*test_traceback_failure.py:4: AssertionError\",\n ]\n )\n\n result = testdir.runpytest(p1) # \"auto\"\n result.stdout.fnmatch_lines(\n [\n \"*test_traceback_failure.py F*\",\n \"====* FAILURES *====\",\n \"____*____\",\n \"\",\n \" def test_onefails():\",\n \"> f(3)\",\n \"\",\n \"*test_*.py:6: \",\n \"\",\n \" def f(x):\",\n \"> assert x == g()\",\n \"E assert 3 == 2\",\n \"E + where 2 = g()\",\n \"\",\n \"*test_traceback_failure.py:4: AssertionError\",\n ]\n )"},{"col":0,"comment":"null","endLoc":404,"header":"def test_entrysource_Queue_example()","id":7058,"name":"test_entrysource_Queue_example","nodeType":"Function","startLoc":395,"text":"def test_entrysource_Queue_example():\n try:\n queue.Queue().get(timeout=0.001)\n except queue.Empty:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n entry = excinfo.traceback[-1]\n source = entry.getsource()\n assert source is not None\n s = str(source).strip()\n assert s.startswith(\"def get\")"},{"col":0,"comment":"\n Handle chain exceptions in tasks submitted by the multiprocess module (#1984).\n ","endLoc":1137,"header":"@pytest.mark.skipif(\n sys.version_info[:2] <= (3, 3),\n reason=\"Python 3.4+ shows chained exceptions on multiprocess\",\n)\ndef test_exception_handling_no_traceback(testdir)","id":7059,"name":"test_exception_handling_no_traceback","nodeType":"Function","startLoc":1103,"text":"@pytest.mark.skipif(\n sys.version_info[:2] <= (3, 3),\n reason=\"Python 3.4+ shows chained exceptions on multiprocess\",\n)\ndef test_exception_handling_no_traceback(testdir):\n \"\"\"\n Handle chain exceptions in tasks submitted by the multiprocess module (#1984).\n \"\"\"\n p1 = testdir.makepyfile(\n \"\"\"\n from multiprocessing import Pool\n\n def process_task(n):\n assert n == 10\n\n def multitask_job():\n tasks = [1]\n with Pool(processes=1) as pool:\n pool.map(process_task, tasks)\n\n def test_multitask_job():\n multitask_job()\n \"\"\"\n )\n result = testdir.runpytest(p1, \"--tb=long\")\n result.stdout.fnmatch_lines(\n [\n \"====* FAILURES *====\",\n \"*multiprocessing.pool.RemoteTraceback:*\",\n \"Traceback (most recent call last):\",\n \"*assert n == 10\",\n \"The above exception was the direct cause of the following exception:\",\n \"> * multitask_job()\",\n ]\n )"},{"col":0,"comment":"null","endLoc":1148,"header":"@pytest.mark.skipif(\n \"'__pypy__' in sys.builtin_module_names or sys.platform.startswith('java')\"\n)\ndef test_warn_missing(testdir)","id":7060,"name":"test_warn_missing","nodeType":"Function","startLoc":1140,"text":"@pytest.mark.skipif(\n \"'__pypy__' in sys.builtin_module_names or sys.platform.startswith('java')\"\n)\ndef test_warn_missing(testdir):\n testdir.makepyfile(\"\")\n result = testdir.run(sys.executable, \"-OO\", \"-m\", \"pytest\", \"-h\")\n result.stderr.fnmatch_lines([\"*WARNING*assert statements are not executed*\"])\n result = testdir.run(sys.executable, \"-OO\", \"-m\", \"pytest\")\n result.stderr.fnmatch_lines([\"*WARNING*assert statements are not executed*\"])"},{"col":0,"comment":"null","endLoc":1169,"header":"def test_recursion_source_decode(testdir)","id":7061,"name":"test_recursion_source_decode","nodeType":"Function","startLoc":1151,"text":"def test_recursion_source_decode(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_something():\n pass\n \"\"\"\n )\n testdir.makeini(\n \"\"\"\n [pytest]\n python_files = *.py\n \"\"\"\n )\n result = testdir.runpytest(\"--collect-only\")\n result.stdout.fnmatch_lines(\n \"\"\"\n \n \"\"\"\n )"},{"col":0,"comment":"null","endLoc":1187,"header":"def test_AssertionError_message(testdir)","id":7062,"name":"test_AssertionError_message","nodeType":"Function","startLoc":1172,"text":"def test_AssertionError_message(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_hello():\n x,y = 1,2\n assert 0, (x,y)\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n \"\"\"\n *def test_hello*\n *assert 0, (x,y)*\n *AssertionError: (1, 2)*\n \"\"\"\n )"},{"col":0,"comment":"null","endLoc":1226,"header":"@pytest.mark.skipif(PY3, reason=\"This bug does not exist on PY3\")\ndef test_set_with_unsortable_elements()","id":7063,"name":"test_set_with_unsortable_elements","nodeType":"Function","startLoc":1190,"text":"@pytest.mark.skipif(PY3, reason=\"This bug does not exist on PY3\")\ndef test_set_with_unsortable_elements():\n # issue #718\n class UnsortableKey(object):\n def __init__(self, name):\n self.name = name\n\n def __lt__(self, other):\n raise RuntimeError()\n\n def __repr__(self):\n return \"repr({})\".format(self.name)\n\n def __eq__(self, other):\n return self.name == other.name\n\n def __hash__(self):\n return hash(self.name)\n\n left_set = {UnsortableKey(str(i)) for i in range(1, 3)}\n right_set = {UnsortableKey(str(i)) for i in range(2, 4)}\n expl = callequal(left_set, right_set, verbose=True)\n # skip first line because it contains the \"construction\" of the set, which does not have a guaranteed order\n expl = expl[1:]\n dedent = textwrap.dedent(\n \"\"\"\n Extra items in the left set:\n repr(1)\n Extra items in the right set:\n repr(3)\n Full diff (fallback to calling repr on each item):\n - repr(1)\n repr(2)\n + repr(3)\n \"\"\"\n ).strip()\n assert \"\\n\".join(expl) == dedent"},{"col":4,"comment":"null","endLoc":1031,"header":"def visit_Attribute(self, attr)","id":7065,"name":"visit_Attribute","nodeType":"Function","startLoc":1023,"text":"def visit_Attribute(self, attr):\n if not isinstance(attr.ctx, ast.Load):\n return self.generic_visit(attr)\n value, value_expl = self.visit(attr.value)\n res = self.assign(ast.Attribute(value, attr.attr, ast.Load()))\n res_expl = self.explanation_param(self.display(res))\n pat = \"%s\\n{%s = %s.%s\\n}\"\n expl = pat % (res_expl, res_expl, value_expl, attr.attr)\n return res, expl"},{"col":4,"comment":"null","endLoc":1069,"header":"def visit_Compare(self, comp)","id":7068,"name":"visit_Compare","nodeType":"Function","startLoc":1033,"text":"def visit_Compare(self, comp):\n self.push_format_context()\n left_res, left_expl = self.visit(comp.left)\n if isinstance(comp.left, (ast.Compare, ast.BoolOp)):\n left_expl = \"({})\".format(left_expl)\n res_variables = [self.variable() for i in range(len(comp.ops))]\n load_names = [ast.Name(v, ast.Load()) for v in res_variables]\n store_names = [ast.Name(v, ast.Store()) for v in res_variables]\n it = zip(range(len(comp.ops)), comp.ops, comp.comparators)\n expls = []\n syms = []\n results = [left_res]\n for i, op, next_operand in it:\n next_res, next_expl = self.visit(next_operand)\n if isinstance(next_operand, (ast.Compare, ast.BoolOp)):\n next_expl = \"({})\".format(next_expl)\n results.append(next_res)\n sym = binop_map[op.__class__]\n syms.append(ast.Str(sym))\n expl = \"%s %s %s\" % (left_expl, sym, next_expl)\n expls.append(ast.Str(expl))\n res_expr = ast.Compare(left_res, [op], [next_res])\n self.statements.append(ast.Assign([store_names[i]], res_expr))\n left_res, left_expl = next_res, next_expl\n # Use pytest.assertion.util._reprcompare if that's available.\n expl_call = self.helper(\n \"_call_reprcompare\",\n ast.Tuple(syms, ast.Load()),\n ast.Tuple(load_names, ast.Load()),\n ast.Tuple(expls, ast.Load()),\n ast.Tuple(results, ast.Load()),\n )\n if len(comp.ops) > 1:\n res = ast.BoolOp(ast.And(), load_names)\n else:\n res = load_names[0]\n return res, self.explanation_param(self.pop_format_context(expl_call))"},{"col":0,"comment":"null","endLoc":416,"header":"def test_codepath_Queue_example()","id":7069,"name":"test_codepath_Queue_example","nodeType":"Function","startLoc":407,"text":"def test_codepath_Queue_example():\n try:\n queue.Queue().get(timeout=0.001)\n except queue.Empty:\n excinfo = _pytest._code.ExceptionInfo.from_current()\n entry = excinfo.traceback[-1]\n path = entry.path\n assert isinstance(path, py.path.local)\n assert path.basename.lower() == \"queue.py\"\n assert path.check()"},{"col":0,"comment":"null","endLoc":422,"header":"def test_match_succeeds()","id":7070,"name":"test_match_succeeds","nodeType":"Function","startLoc":419,"text":"def test_match_succeeds():\n with pytest.raises(ZeroDivisionError) as excinfo:\n 0 // 0\n excinfo.match(r\".*zero.*\")"},{"col":0,"comment":"null","endLoc":437,"header":"def test_match_raises_error(testdir)","id":7071,"name":"test_match_raises_error","nodeType":"Function","startLoc":425,"text":"def test_match_raises_error(testdir):\n testdir.makepyfile(\n \"\"\"\n import pytest\n def test_division_zero():\n with pytest.raises(ZeroDivisionError) as excinfo:\n 0 / 0\n excinfo.match(r'[123]+')\n \"\"\"\n )\n result = testdir.runpytest()\n assert result.ret != 0\n result.stdout.fnmatch_lines([\"*AssertionError*Pattern*[123]*not found*\"])"},{"col":0,"comment":"null","endLoc":1381,"header":"@pytest.mark.parametrize(\"style\", [\"short\", \"long\"])\n@pytest.mark.parametrize(\"encoding\", [None, \"utf8\", \"utf16\"])\ndef test_repr_traceback_with_unicode(style, encoding)","id":7072,"name":"test_repr_traceback_with_unicode","nodeType":"Function","startLoc":1369,"text":"@pytest.mark.parametrize(\"style\", [\"short\", \"long\"])\n@pytest.mark.parametrize(\"encoding\", [None, \"utf8\", \"utf16\"])\ndef test_repr_traceback_with_unicode(style, encoding):\n msg = u\"☹\"\n if encoding is not None:\n msg = msg.encode(encoding)\n try:\n raise RuntimeError(msg)\n except RuntimeError:\n e_info = ExceptionInfo.from_current()\n formatter = FormattedExcinfo(style=style)\n repr_traceback = formatter.repr_traceback(e_info)\n assert repr_traceback is not None"},{"col":0,"comment":"null","endLoc":1245,"header":"def test_diff_newline_at_end(monkeypatch, testdir)","id":7073,"name":"test_diff_newline_at_end","nodeType":"Function","startLoc":1229,"text":"def test_diff_newline_at_end(monkeypatch, testdir):\n testdir.makepyfile(\n r\"\"\"\n def test_diff():\n assert 'asdf' == 'asdf\\n'\n \"\"\"\n )\n\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n r\"\"\"\n *assert 'asdf' == 'asdf\\n'\n * - asdf\n * + asdf\n * ? +\n \"\"\"\n )"},{"col":0,"comment":"null","endLoc":1268,"header":"@pytest.mark.filterwarnings(\"default\")\ndef test_assert_tuple_warning(testdir)","id":7074,"name":"test_assert_tuple_warning","nodeType":"Function","startLoc":1248,"text":"@pytest.mark.filterwarnings(\"default\")\ndef test_assert_tuple_warning(testdir):\n msg = \"assertion is always true\"\n testdir.makepyfile(\n \"\"\"\n def test_tuple():\n assert(False, 'you shall not pass')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*test_assert_tuple_warning.py:2:*{}*\".format(msg)])\n\n # tuples with size != 2 should not trigger the warning\n testdir.makepyfile(\n \"\"\"\n def test_tuple():\n assert ()\n \"\"\"\n )\n result = testdir.runpytest()\n assert msg not in result.stdout.str()"},{"col":0,"comment":"null","endLoc":1281,"header":"def test_assert_indirect_tuple_no_warning(testdir)","id":7075,"name":"test_assert_indirect_tuple_no_warning","nodeType":"Function","startLoc":1271,"text":"def test_assert_indirect_tuple_no_warning(testdir):\n testdir.makepyfile(\n \"\"\"\n def test_tuple():\n tpl = ('foo', 'bar')\n assert tpl\n \"\"\"\n )\n result = testdir.runpytest(\"-rw\")\n output = \"\\n\".join(result.stdout.lines)\n assert \"WR1\" not in output"},{"col":0,"comment":"null","endLoc":1293,"header":"def test_assert_with_unicode(monkeypatch, testdir)","id":7076,"name":"test_assert_with_unicode","nodeType":"Function","startLoc":1284,"text":"def test_assert_with_unicode(monkeypatch, testdir):\n testdir.makepyfile(\n u\"\"\"\n # -*- coding: utf-8 -*-\n def test_unicode():\n assert u'유니코드' == u'Unicode'\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*AssertionError*\"])"},{"col":0,"comment":"null","endLoc":1306,"header":"def test_raise_unprintable_assertion_error(testdir)","id":7077,"name":"test_raise_unprintable_assertion_error","nodeType":"Function","startLoc":1296,"text":"def test_raise_unprintable_assertion_error(testdir):\n testdir.makepyfile(\n r\"\"\"\n def test_raise_assertion_error():\n raise AssertionError('\\xff')\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [r\"> raise AssertionError('\\xff')\", \"E AssertionError: *\"]\n )"},{"col":4,"comment":"Run a command using pexpect.\n\n The pexpect child is returned.\n\n ","endLoc":1246,"header":"def spawn(self, cmd, expect_timeout=10.0)","id":7078,"name":"spawn","nodeType":"Function","startLoc":1226,"text":"def spawn(self, cmd, expect_timeout=10.0):\n \"\"\"Run a command using pexpect.\n\n The pexpect child is returned.\n\n \"\"\"\n pexpect = pytest.importorskip(\"pexpect\", \"3.0\")\n if hasattr(sys, \"pypy_version_info\") and \"64\" in platform.machine():\n pytest.skip(\"pypy-64 bit not supported\")\n if sys.platform.startswith(\"freebsd\"):\n pytest.xfail(\"pexpect does not work reliably on freebsd\")\n logfile = self.tmpdir.join(\"spawn.out\").open(\"wb\")\n\n # Do not load user config.\n env = os.environ.copy()\n env.update(self._env_run_update)\n\n child = pexpect.spawn(cmd, logfile=logfile, env=env)\n self.request.addfinalizer(logfile.close)\n child.timeout = expect_timeout\n return child"},{"col":0,"comment":"null","endLoc":1322,"header":"def test_raise_assertion_error_raisin_repr(testdir)","id":7080,"name":"test_raise_assertion_error_raisin_repr","nodeType":"Function","startLoc":1309,"text":"def test_raise_assertion_error_raisin_repr(testdir):\n testdir.makepyfile(\n u\"\"\"\n class RaisingRepr(object):\n def __repr__(self):\n raise Exception()\n def test_raising_repr():\n raise AssertionError(RaisingRepr())\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines(\n [\"E AssertionError: \"]\n )"},{"col":0,"comment":"null","endLoc":1339,"header":"def test_issue_1944(testdir)","id":7081,"name":"test_issue_1944","nodeType":"Function","startLoc":1325,"text":"def test_issue_1944(testdir):\n testdir.makepyfile(\n \"\"\"\n def f():\n return\n\n assert f() == 10\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"*1 error*\"])\n assert (\n \"AttributeError: 'Module' object has no attribute '_obj'\"\n not in result.stdout.str()\n )"},{"attributeType":"object","col":4,"comment":"null","endLoc":481,"id":7082,"name":"CLOSE_STDIN","nodeType":"Attribute","startLoc":481,"text":"CLOSE_STDIN"},{"attributeType":"Session","col":4,"comment":"null","endLoc":691,"id":7083,"name":"Session","nodeType":"Attribute","startLoc":691,"text":"Session"},{"col":0,"comment":"null","endLoc":1349,"header":"def test_exit_from_assertrepr_compare(monkeypatch)","id":7084,"name":"test_exit_from_assertrepr_compare","nodeType":"Function","startLoc":1342,"text":"def test_exit_from_assertrepr_compare(monkeypatch):\n def raise_exit(obj):\n outcomes.exit(\"Quitting debugger\")\n\n monkeypatch.setattr(util, \"istext\", raise_exit)\n\n with pytest.raises(outcomes.Exit, match=\"Quitting debugger\"):\n callequal(1, 1)"},{"attributeType":"null","col":8,"comment":"null","endLoc":490,"id":7085,"name":"tmpdir","nodeType":"Attribute","startLoc":490,"text":"self.tmpdir"},{"attributeType":"null","col":8,"comment":"null","endLoc":491,"id":7086,"name":"test_tmproot","nodeType":"Attribute","startLoc":491,"text":"self.test_tmproot"},{"attributeType":"SysModulesSnapshot","col":8,"comment":"null","endLoc":495,"id":7087,"name":"_sys_modules_snapshot","nodeType":"Attribute","startLoc":495,"text":"self._sys_modules_snapshot"},{"attributeType":"MonkeyPatch","col":13,"comment":"null","endLoc":504,"id":7088,"name":"monkeypatch","nodeType":"Attribute","startLoc":504,"text":"self.monkeypatch"},{"attributeType":"{function}","col":8,"comment":"null","endLoc":487,"id":7089,"name":"request","nodeType":"Attribute","startLoc":487,"text":"self.request"},{"attributeType":"CwdSnapshot","col":8,"comment":"null","endLoc":493,"id":7090,"name":"_cwd_snapshot","nodeType":"Attribute","startLoc":493,"text":"self._cwd_snapshot"},{"attributeType":"list","col":8,"comment":"null","endLoc":492,"id":7091,"name":"plugins","nodeType":"Attribute","startLoc":492,"text":"self.plugins"},{"attributeType":"SysPathsSnapshot","col":8,"comment":"null","endLoc":494,"id":7092,"name":"_sys_path_snapshot","nodeType":"Attribute","startLoc":494,"text":"self._sys_path_snapshot"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":513,"id":7093,"name":"_env_run_update","nodeType":"Attribute","startLoc":513,"text":"self._env_run_update"},{"attributeType":"WeakKeyDictionary","col":8,"comment":"null","endLoc":488,"id":7094,"name":"_mod_collections","nodeType":"Attribute","startLoc":488,"text":"self._mod_collections"},{"attributeType":"null","col":28,"comment":"null","endLoc":12,"id":7095,"name":"plugin","nodeType":"Attribute","startLoc":12,"text":"plugin"},{"attributeType":"bool","col":0,"comment":"null","endLoc":18,"id":7096,"name":"PY3","nodeType":"Attribute","startLoc":18,"text":"PY3"},{"attributeType":"function","col":12,"comment":"null","endLoc":502,"id":7097,"name":"_runpytest_method","nodeType":"Attribute","startLoc":502,"text":"self._runpytest_method"},{"attributeType":"null","col":8,"comment":"null","endLoc":1012,"id":7098,"name":"config","nodeType":"Attribute","startLoc":1012,"text":"self.config"},{"col":0,"comment":"","endLoc":2,"header":"test_assertion.py#","id":7099,"name":"","nodeType":"Function","startLoc":2,"text":"PY3 = sys.version_info >= (3, 0)"},{"className":"LineComp","col":0,"comment":"null","endLoc":1271,"id":7100,"nodeType":"Class","startLoc":1256,"text":"class LineComp(object):\n def __init__(self):\n self.stringio = py.io.TextIO()\n\n def assert_contains_lines(self, lines2):\n \"\"\"Assert that lines2 are contained (linearly) in lines1.\n\n Return a list of extralines found.\n\n \"\"\"\n __tracebackhide__ = True\n val = self.stringio.getvalue()\n self.stringio.truncate(0)\n self.stringio.seek(0)\n lines1 = val.split(\"\\n\")\n return LineMatcher(lines1).fnmatch_lines(lines2)"},{"col":4,"comment":"null","endLoc":1258,"header":"def __init__(self)","id":7101,"name":"__init__","nodeType":"Function","startLoc":1257,"text":"def __init__(self):\n self.stringio = py.io.TextIO()"},{"col":4,"comment":"Assert that lines2 are contained (linearly) in lines1.\n\n Return a list of extralines found.\n\n ","endLoc":1271,"header":"def assert_contains_lines(self, lines2)","id":7102,"name":"assert_contains_lines","nodeType":"Function","startLoc":1260,"text":"def assert_contains_lines(self, lines2):\n \"\"\"Assert that lines2 are contained (linearly) in lines1.\n\n Return a list of extralines found.\n\n \"\"\"\n __tracebackhide__ = True\n val = self.stringio.getvalue()\n self.stringio.truncate(0)\n self.stringio.seek(0)\n lines1 = val.split(\"\\n\")\n return LineMatcher(lines1).fnmatch_lines(lines2)"},{"attributeType":"null","col":8,"comment":"null","endLoc":1258,"id":7103,"name":"stringio","nodeType":"Attribute","startLoc":1258,"text":"self.stringio"},{"col":0,"comment":"null","endLoc":63,"header":"def pytest_addoption(parser)","id":7104,"name":"pytest_addoption","nodeType":"Function","startLoc":41,"text":"def pytest_addoption(parser):\n parser.addoption(\n \"--lsof\",\n action=\"store_true\",\n dest=\"lsof\",\n default=False,\n help=\"run FD checks if lsof is available\",\n )\n\n parser.addoption(\n \"--runpytest\",\n default=\"inprocess\",\n dest=\"runpytest\",\n choices=(\"inprocess\", \"subprocess\"),\n help=(\n \"run pytest sub runs in tests using an 'inprocess' \"\n \"or 'subprocess' (python -m main) method\"\n ),\n )\n\n parser.addini(\n \"pytester_example_dir\", help=\"directory to take the pytester example files from\"\n )"},{"col":0,"comment":"null","endLoc":76,"header":"def pytest_configure(config)","id":7105,"name":"pytest_configure","nodeType":"Function","startLoc":66,"text":"def pytest_configure(config):\n if config.getvalue(\"lsof\"):\n checker = LsofFdLeakChecker()\n if checker.matching_platform():\n config.pluginmanager.register(checker)\n\n config.addinivalue_line(\n \"markers\",\n \"pytester_example_path(*path_segments): join the given path \"\n \"segments to `pytester_example_dir` for this test.\",\n )"},{"col":0,"comment":"Return a helper which offers a gethookrecorder(hook) method which\n returns a HookRecorder instance which helps to make assertions about called\n hooks.\n\n ","endLoc":166,"header":"@pytest.fixture\ndef _pytest(request)","id":7106,"name":"_pytest","nodeType":"Function","startLoc":159,"text":"@pytest.fixture\ndef _pytest(request):\n \"\"\"Return a helper which offers a gethookrecorder(hook) method which\n returns a HookRecorder instance which helps to make assertions about called\n hooks.\n\n \"\"\"\n return PytestArg(request)"},{"col":0,"comment":"null","endLoc":327,"header":"@pytest.fixture\ndef linecomp(request)","id":7107,"name":"linecomp","nodeType":"Function","startLoc":325,"text":"@pytest.fixture\ndef linecomp(request):\n return LineComp()"},{"col":0,"comment":"null","endLoc":332,"header":"@pytest.fixture(name=\"LineMatcher\")\ndef LineMatcher_fixture(request)","id":7108,"name":"LineMatcher_fixture","nodeType":"Function","startLoc":330,"text":"@pytest.fixture(name=\"LineMatcher\")\ndef LineMatcher_fixture(request):\n return LineMatcher"},{"col":0,"comment":"null","endLoc":337,"header":"@pytest.fixture\ndef testdir(request, tmpdir_factory)","id":7109,"name":"testdir","nodeType":"Function","startLoc":335,"text":"@pytest.fixture\ndef testdir(request, tmpdir_factory):\n return Testdir(request, tmpdir_factory)"},{"col":0,"comment":"null","endLoc":346,"header":"@pytest.fixture\ndef _sys_snapshot()","id":7110,"name":"_sys_snapshot","nodeType":"Function","startLoc":340,"text":"@pytest.fixture\ndef _sys_snapshot():\n snappaths = SysPathsSnapshot()\n snapmods = SysModulesSnapshot()\n yield\n snapmods.restore()\n snappaths.restore()"},{"col":0,"comment":"null","endLoc":355,"header":"@pytest.fixture\ndef _config_for_test()","id":7111,"name":"_config_for_test","nodeType":"Function","startLoc":349,"text":"@pytest.fixture\ndef _config_for_test():\n from _pytest.config import get_config\n\n config = get_config()\n yield config\n config._ensure_unconfigure() # cleanup, e.g. capman closing tmpfiles."},{"col":0,"comment":"null","endLoc":1253,"header":"def getdecoded(out)","id":7112,"name":"getdecoded","nodeType":"Function","startLoc":1249,"text":"def getdecoded(out):\n try:\n return out.decode(\"utf-8\")\n except UnicodeDecodeError:\n return \"INTERNAL not-utf8-decodeable, truncated string:\\n%s\" % (saferepr(out),)"},{"attributeType":"list","col":0,"comment":"null","endLoc":36,"id":7113,"name":"IGNORE_PAM","nodeType":"Attribute","startLoc":36,"text":"IGNORE_PAM"},{"attributeType":"Pattern","col":0,"comment":"null","endLoc":358,"id":7114,"name":"rex_outcome","nodeType":"Attribute","startLoc":358,"text":"rex_outcome"},{"col":0,"comment":"","endLoc":2,"header":"pytester.py#","id":7115,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"(disabled by default) support for testing pytest and pytest plugins.\"\"\"\n\nIGNORE_PAM = [ # filenames added when obtaining details about the current user\n u\"/var/lib/sss/mc/passwd\"\n]\n\nrex_outcome = re.compile(r\"(\\d+) ([\\w-]+)\")"},{"col":0,"comment":"null","endLoc":1395,"header":"def test_cwd_deleted(testdir)","id":7116,"name":"test_cwd_deleted","nodeType":"Function","startLoc":1384,"text":"def test_cwd_deleted(testdir):\n testdir.makepyfile(\n \"\"\"\n def test(tmpdir):\n tmpdir.chdir()\n tmpdir.remove()\n assert False\n \"\"\"\n )\n result = testdir.runpytest()\n result.stdout.fnmatch_lines([\"* 1 failed in *\"])\n assert \"INTERNALERROR\" not in result.stdout.str() + result.stderr.str()"},{"col":0,"comment":"\n Ensure we can properly detect a recursion error even\n if some locals raise error on comparison (#2459).\n ","endLoc":1430,"header":"@pytest.mark.usefixtures(\"limited_recursion_depth\")\ndef test_exception_repr_extraction_error_on_recursion()","id":7117,"name":"test_exception_repr_extraction_error_on_recursion","nodeType":"Function","startLoc":1398,"text":"@pytest.mark.usefixtures(\"limited_recursion_depth\")\ndef test_exception_repr_extraction_error_on_recursion():\n \"\"\"\n Ensure we can properly detect a recursion error even\n if some locals raise error on comparison (#2459).\n \"\"\"\n from _pytest.pytester import LineMatcher\n\n class numpy_like(object):\n def __eq__(self, other):\n if type(other) is numpy_like:\n raise ValueError(\n \"The truth value of an array \"\n \"with more than one element is ambiguous.\"\n )\n\n def a(x):\n return b(numpy_like())\n\n def b(x):\n return a(numpy_like())\n\n with pytest.raises(RuntimeError) as excinfo:\n a(numpy_like())\n\n matcher = LineMatcher(str(excinfo.getrepr()).splitlines())\n matcher.fnmatch_lines(\n [\n \"!!! Recursion error detected, but an error occurred locating the origin of recursion.\",\n \"*The following exception happened*\",\n \"*ValueError: The truth value of an array*\",\n ]\n )"},{"col":0,"comment":"\n Ensure that we don't break in case we can't find the recursion index\n during a recursion error (#2486).\n ","endLoc":1446,"header":"@pytest.mark.usefixtures(\"limited_recursion_depth\")\ndef test_no_recursion_index_on_recursion_error()","id":7120,"name":"test_no_recursion_index_on_recursion_error","nodeType":"Function","startLoc":1433,"text":"@pytest.mark.usefixtures(\"limited_recursion_depth\")\ndef test_no_recursion_index_on_recursion_error():\n \"\"\"\n Ensure that we don't break in case we can't find the recursion index\n during a recursion error (#2486).\n \"\"\"\n\n class RecursionDepthError(object):\n def __getattr__(self, attr):\n return getattr(self, \"_\" + attr)\n\n with pytest.raises(RuntimeError) as excinfo:\n RecursionDepthError().trigger\n assert \"maximum recursion\" in str(excinfo.getrepr())"},{"attributeType":"None","col":4,"comment":"null","endLoc":27,"id":7121,"name":"invalidate_import_caches","nodeType":"Attribute","startLoc":27,"text":"invalidate_import_caches"},{"attributeType":"null","col":0,"comment":"null","endLoc":29,"id":7122,"name":"failsonjython","nodeType":"Attribute","startLoc":29,"text":"failsonjython"},{"attributeType":"(int, ...)","col":0,"comment":"null","endLoc":31,"id":7123,"name":"pytest_version_info","nodeType":"Attribute","startLoc":31,"text":"pytest_version_info"},{"col":0,"comment":"","endLoc":2,"header":"test_excinfo.py#","id":7124,"name":"","nodeType":"Function","startLoc":2,"text":"try:\n import importlib\nexcept ImportError:\n invalidate_import_caches = None\nelse:\n invalidate_import_caches = getattr(importlib, \"invalidate_caches\", None)\n\nfailsonjython = pytest.mark.xfail(\"sys.platform.startswith('java')\")\n\npytest_version_info = tuple(map(int, pytest.__version__.split(\".\")[:3]))"},{"attributeType":"function","col":8,"comment":"null","endLoc":1019,"id":7126,"name":"visit_Call","nodeType":"Attribute","startLoc":1019,"text":"visit_Call"},{"attributeType":"list","col":8,"comment":"null","endLoc":825,"id":7127,"name":"on_failure","nodeType":"Attribute","startLoc":825,"text":"self.on_failure"},{"attributeType":"list","col":8,"comment":"null","endLoc":822,"id":7128,"name":"variables","nodeType":"Attribute","startLoc":822,"text":"self.variables"},{"attributeType":"list","col":8,"comment":"null","endLoc":824,"id":7129,"name":"stack","nodeType":"Attribute","startLoc":824,"text":"self.stack"},{"attributeType":"TypedDict","col":8,"comment":"null","endLoc":771,"id":7130,"name":"explanation_specifiers","nodeType":"Attribute","startLoc":771,"text":"self.explanation_specifiers"},{"attributeType":"count","col":8,"comment":"null","endLoc":823,"id":7131,"name":"variable_counter","nodeType":"Attribute","startLoc":823,"text":"self.variable_counter"},{"attributeType":"list","col":8,"comment":"null","endLoc":821,"id":7132,"name":"statements","nodeType":"Attribute","startLoc":821,"text":"self.statements"},{"attributeType":"null","col":8,"comment":"null","endLoc":648,"id":7133,"name":"config","nodeType":"Attribute","startLoc":648,"text":"self.config"},{"attributeType":"null","col":8,"comment":"null","endLoc":647,"id":7134,"name":"module_path","nodeType":"Attribute","startLoc":647,"text":"self.module_path"},{"col":0,"comment":"Get a safe repr of an object for assertion error messages.\n\n The assertion formatting (util.format_explanation()) requires\n newlines to be escaped since they are a special character for it.\n Normally assertion.util.format_explanation() does this but for a\n custom repr it is possible to contain one of the special escape\n sequences, especially '\n{' and '\n}' are likely to be present in\n JSON reprs.\n\n ","endLoc":475,"header":"def _saferepr(obj)","id":7135,"name":"_saferepr","nodeType":"Function","startLoc":456,"text":"def _saferepr(obj):\n \"\"\"Get a safe repr of an object for assertion error messages.\n\n The assertion formatting (util.format_explanation()) requires\n newlines to be escaped since they are a special character for it.\n Normally assertion.util.format_explanation() does this but for a\n custom repr it is possible to contain one of the special escape\n sequences, especially '\\n{' and '\\n}' are likely to be present in\n JSON reprs.\n\n \"\"\"\n r = saferepr(obj)\n # only occurs in python2.x, repr must return text in python3+\n if isinstance(r, bytes):\n # Represent unprintable bytes as `\\x##`\n r = u\"\".join(\n u\"\\\\x{:x}\".format(ord(c)) if c not in string.printable else c.decode()\n for c in r\n )\n return r.replace(u\"\\n\", u\"\\\\n\")"},{"col":0,"comment":"Format the custom assertion message given.\n\n For strings this simply replaces newlines with '\n~' so that\n util.format_explanation() will preserve them instead of escaping\n newlines. For other objects saferepr() is used first.\n\n ","endLoc":501,"header":"def _format_assertmsg(obj)","id":7136,"name":"_format_assertmsg","nodeType":"Function","startLoc":478,"text":"def _format_assertmsg(obj):\n \"\"\"Format the custom assertion message given.\n\n For strings this simply replaces newlines with '\\n~' so that\n util.format_explanation() will preserve them instead of escaping\n newlines. For other objects saferepr() is used first.\n\n \"\"\"\n # reprlib appears to have a bug which means that if a string\n # contains a newline it gets escaped, however if an object has a\n # .__repr__() which contains newlines it does not get escaped.\n # However in either case we want to preserve the newline.\n replaces = [(u\"\\n\", u\"\\n~\"), (u\"%\", u\"%%\")]\n if not isinstance(obj, six.string_types):\n obj = saferepr(obj)\n replaces.append((u\"\\\\n\", u\"\\n~\"))\n\n if isinstance(obj, bytes):\n replaces = [(r1.encode(), r2.encode()) for r1, r2 in replaces]\n\n for r1, r2 in replaces:\n obj = obj.replace(r1, r2)\n\n return obj"},{"col":0,"comment":"null","endLoc":511,"header":"def _should_repr_global_name(obj)","id":7138,"name":"_should_repr_global_name","nodeType":"Function","startLoc":504,"text":"def _should_repr_global_name(obj):\n if callable(obj):\n return False\n\n try:\n return not hasattr(obj, \"__name__\")\n except Exception:\n return True"},{"col":0,"comment":"null","endLoc":519,"header":"def _format_boolop(explanations, is_or)","id":7139,"name":"_format_boolop","nodeType":"Function","startLoc":514,"text":"def _format_boolop(explanations, is_or):\n explanation = \"(\" + (is_or and \" or \" or \" and \").join(explanations) + \")\"\n if isinstance(explanation, six.text_type):\n return explanation.replace(u\"%\", u\"%%\")\n else:\n return explanation.replace(b\"%\", b\"%%\")"},{"col":0,"comment":"null","endLoc":534,"header":"def _call_reprcompare(ops, results, expls, each_obj)","id":7140,"name":"_call_reprcompare","nodeType":"Function","startLoc":522,"text":"def _call_reprcompare(ops, results, expls, each_obj):\n for i, res, expl in zip(range(len(ops)), results, expls):\n try:\n done = not res\n except Exception:\n done = True\n if done:\n break\n if util._reprcompare is not None:\n custom = util._reprcompare(ops[i], each_obj[i], each_obj[i + 1])\n if custom is not None:\n return custom\n return expl"},{"attributeType":"str","col":8,"comment":"null","endLoc":37,"id":7141,"name":"impl","nodeType":"Attribute","startLoc":37,"text":"impl"},{"attributeType":"str","col":8,"comment":"null","endLoc":39,"id":7142,"name":"impl","nodeType":"Attribute","startLoc":39,"text":"impl"},{"attributeType":"str","col":8,"comment":"null","endLoc":41,"id":7143,"name":"impl","nodeType":"Attribute","startLoc":41,"text":"impl"},{"attributeType":"_version_info","col":4,"comment":"null","endLoc":42,"id":7144,"name":"ver","nodeType":"Attribute","startLoc":42,"text":"ver"},{"attributeType":"str","col":0,"comment":"null","endLoc":46,"id":7145,"name":"PYC_EXT","nodeType":"Attribute","startLoc":46,"text":"PYC_EXT"},{"attributeType":"str","col":0,"comment":"null","endLoc":47,"id":7146,"name":"PYC_TAIL","nodeType":"Attribute","startLoc":47,"text":"PYC_TAIL"},{"attributeType":"bool","col":0,"comment":"null","endLoc":49,"id":7147,"name":"ASCII_IS_DEFAULT_ENCODING","nodeType":"Attribute","startLoc":49,"text":"ASCII_IS_DEFAULT_ENCODING"},{"attributeType":"Call","col":4,"comment":"null","endLoc":52,"id":7148,"name":"ast_Call","nodeType":"Attribute","startLoc":52,"text":"ast_Call"},{"attributeType":"bytes","col":0,"comment":"null","endLoc":352,"id":7149,"name":"RN","nodeType":"Attribute","startLoc":352,"text":"RN"},{"attributeType":"bytes","col":0,"comment":"null","endLoc":353,"id":7150,"name":"N","nodeType":"Attribute","startLoc":353,"text":"N"},{"attributeType":"Pattern","col":0,"comment":"null","endLoc":355,"id":7151,"name":"cookie_re","nodeType":"Attribute","startLoc":355,"text":"cookie_re"},{"attributeType":"str","col":0,"comment":"null","endLoc":356,"id":7152,"name":"BOM_UTF8","nodeType":"Attribute","startLoc":356,"text":"BOM_UTF8"},{"attributeType":"dict","col":0,"comment":"null","endLoc":537,"id":7153,"name":"unary_map","nodeType":"Attribute","startLoc":537,"text":"unary_map"},{"attributeType":"dict","col":0,"comment":"null","endLoc":539,"id":7154,"name":"binop_map","nodeType":"Attribute","startLoc":539,"text":"binop_map"},{"attributeType":"NameConstant","col":4,"comment":"null","endLoc":571,"id":7155,"name":"_NameConstant","nodeType":"Attribute","startLoc":571,"text":"_NameConstant"},{"col":0,"comment":"","endLoc":2,"header":"rewrite.py#","id":7156,"name":"","nodeType":"Function","startLoc":2,"text":"\"\"\"Rewrite assertion AST to produce nice error messages\"\"\"\n\nif hasattr(imp, \"get_tag\"):\n PYTEST_TAG = imp.get_tag() + \"-PYTEST\"\nelse:\n if hasattr(sys, \"pypy_version_info\"):\n impl = \"pypy\"\n elif sys.platform == \"java\":\n impl = \"jython\"\n else:\n impl = \"cpython\"\n ver = sys.version_info\n PYTEST_TAG = \"%s-%s%s-PYTEST\" % (impl, ver[0], ver[1])\n del ver, impl\n\nPYC_EXT = \".py\" + (__debug__ and \"c\" or \"o\")\n\nPYC_TAIL = \".\" + PYTEST_TAG + PYC_EXT\n\nASCII_IS_DEFAULT_ENCODING = sys.version_info[0] < 3\n\nif sys.version_info >= (3, 5):\n ast_Call = ast.Call\nelse:\n\n def ast_Call(a, b, c):\n return ast.Call(a, b, c, None, None)\n\nRN = \"\\r\\n\".encode(\"utf-8\")\n\nN = \"\\n\".encode(\"utf-8\")\n\ncookie_re = re.compile(r\"^[ \\t\\f]*#.*coding[:=][ \\t]*[-\\w.]+\")\n\nBOM_UTF8 = \"\\xef\\xbb\\xbf\"\n\nunary_map = {ast.Not: \"not %s\", ast.Invert: \"~%s\", ast.USub: \"-%s\", ast.UAdd: \"+%s\"}\n\nbinop_map = {\n ast.BitOr: \"|\",\n ast.BitXor: \"^\",\n ast.BitAnd: \"&\",\n ast.LShift: \"<<\",\n ast.RShift: \">>\",\n ast.Add: \"+\",\n ast.Sub: \"-\",\n ast.Mult: \"*\",\n ast.Div: \"/\",\n ast.FloorDiv: \"//\",\n ast.Mod: \"%%\", # escaped for string formatting\n ast.Eq: \"==\",\n ast.NotEq: \"!=\",\n ast.Lt: \"<\",\n ast.LtE: \"<=\",\n ast.Gt: \">\",\n ast.GtE: \">=\",\n ast.Pow: \"**\",\n ast.Is: \"is\",\n ast.IsNot: \"is not\",\n ast.In: \"in\",\n ast.NotIn: \"not in\",\n}\n\ntry:\n binop_map[ast.MatMult] = \"@\"\nexcept AttributeError:\n pass\n\nif hasattr(ast, \"NameConstant\"):\n _NameConstant = ast.NameConstant\nelse:\n\n def _NameConstant(c):\n return ast.Name(str(c), ast.Load())"}]} \ No newline at end of file